Scene.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. //
  2. // Copyright (c) 2008-2014 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 "HashSet.h"
  24. #include "Mutex.h"
  25. #include "Node.h"
  26. #include "SceneResolver.h"
  27. #include "XMLElement.h"
  28. namespace Urho3D
  29. {
  30. class File;
  31. class PackageFile;
  32. static const unsigned FIRST_REPLICATED_ID = 0x1;
  33. static const unsigned LAST_REPLICATED_ID = 0xffffff;
  34. static const unsigned FIRST_LOCAL_ID = 0x01000000;
  35. static const unsigned LAST_LOCAL_ID = 0xffffffff;
  36. /// Asynchronous loading progress of a scene.
  37. struct AsyncProgress
  38. {
  39. /// File for binary mode.
  40. SharedPtr<File> file_;
  41. /// XML file for XML mode.
  42. SharedPtr<XMLFile> xmlFile_;
  43. /// Current XML element for XML mode.
  44. XMLElement xmlElement_;
  45. /// Loaded root-level nodes.
  46. unsigned loadedNodes_;
  47. /// Total root-level nodes.
  48. unsigned totalNodes_;
  49. };
  50. /// Root scene node, represents the whole scene.
  51. class URHO3D_API Scene : public Node
  52. {
  53. OBJECT(Scene);
  54. using Node::GetComponent;
  55. using Node::SaveXML;
  56. public:
  57. /// Construct.
  58. Scene(Context* context);
  59. /// Destruct.
  60. virtual ~Scene();
  61. /// Register object factory. Node must be registered first.
  62. static void RegisterObject(Context* context);
  63. /// Load from binary data. Removes all existing child nodes and components first. Return true if successful.
  64. virtual bool Load(Deserializer& source, bool setInstanceDefault = false);
  65. /// Save to binary data. Return true if successful.
  66. virtual bool Save(Serializer& dest) const;
  67. /// Load from XML data. Removes all existing child nodes and components first. Return true if successful.
  68. virtual bool LoadXML(const XMLElement& source, bool setInstanceDefault = false);
  69. /// Add a replication state that is tracking this scene.
  70. virtual void AddReplicationState(NodeReplicationState* state);
  71. /// Load from an XML file. Return true if successful.
  72. bool LoadXML(Deserializer& source);
  73. /// Save to an XML file. Return true if successful.
  74. bool SaveXML(Serializer& dest) const;
  75. /// Load from a binary file asynchronously. Return true if started successfully.
  76. bool LoadAsync(File* file);
  77. /// Load from an XML file asynchronously. Return true if started successfully.
  78. bool LoadAsyncXML(File* file);
  79. /// Stop asynchronous loading.
  80. void StopAsyncLoading();
  81. /// Instantiate scene content from binary data. Return root node if successful.
  82. Node* Instantiate(Deserializer& source, const Vector3& position, const Quaternion& rotation, CreateMode mode = REPLICATED);
  83. /// Instantiate scene content from XML data. Return root node if successful.
  84. Node* InstantiateXML(const XMLElement& source, const Vector3& position, const Quaternion& rotation, CreateMode mode = REPLICATED);
  85. /// Instantiate scene content from XML data. Return root node if successful.
  86. Node* InstantiateXML(Deserializer& source, const Vector3& position, const Quaternion& rotation, CreateMode mode = REPLICATED);
  87. /// Clear scene completely of either replicated, local or all nodes and components.
  88. void Clear(bool clearReplicated = true, bool clearLocal = true);
  89. /// Enable or disable scene update.
  90. void SetUpdateEnabled(bool enable);
  91. /// Set update time scale. 1.0 = real time (default.)
  92. void SetTimeScale(float scale);
  93. /// Set elapsed time in seconds. This can be used to prevent inaccuracy in the timer if the scene runs for a long time.
  94. void SetElapsedTime(float time);
  95. /// Set network client motion smoothing constant.
  96. void SetSmoothingConstant(float constant);
  97. /// Set network client motion smoothing snap threshold.
  98. void SetSnapThreshold(float threshold);
  99. /// Add a required package file for networking. To be called on the server.
  100. void AddRequiredPackageFile(PackageFile* package);
  101. /// Clear required package files.
  102. void ClearRequiredPackageFiles();
  103. /// Register a node user variable hash reverse mapping (for editing.)
  104. void RegisterVar(const String& name);
  105. /// Unregister a node user variable hash reverse mapping.
  106. void UnregisterVar(const String& name);
  107. /// Clear all registered node user variable hash reverse mappings.
  108. void UnregisterAllVars();
  109. /// Return node from the whole scene by ID, or null if not found.
  110. Node* GetNode(unsigned id) const;
  111. /// Return component from the whole scene by ID, or null if not found.
  112. Component* GetComponent(unsigned id) const;
  113. /// Return whether updates are enabled.
  114. bool IsUpdateEnabled() const { return updateEnabled_; }
  115. /// Return whether an asynchronous loading operation is in progress.
  116. bool IsAsyncLoading() const { return asyncLoading_; }
  117. /// Return asynchronous loading progress between 0.0 and 1.0, or 1.0 if not in progress.
  118. float GetAsyncProgress() const;
  119. /// Return source file name.
  120. const String& GetFileName() const { return fileName_; }
  121. /// Return source file checksum.
  122. unsigned GetChecksum() const { return checksum_; }
  123. /// Return update time scale.
  124. float GetTimeScale() const { return timeScale_; }
  125. /// Return elapsed time in seconds.
  126. float GetElapsedTime() const { return elapsedTime_; }
  127. /// Return motion smoothing constant.
  128. float GetSmoothingConstant() const { return smoothingConstant_; }
  129. /// Return motion smoothing snap threshold.
  130. float GetSnapThreshold() const { return snapThreshold_; }
  131. /// Return required package files.
  132. const Vector<SharedPtr<PackageFile> >& GetRequiredPackageFiles() const { return requiredPackageFiles_; }
  133. /// Return a node user variable name, or empty if not registered.
  134. const String& GetVarName(ShortStringHash hash) const;
  135. /// Update scene. Called by HandleUpdate.
  136. void Update(float timeStep);
  137. /// Begin a threaded update. During threaded update components can choose to delay dirty processing.
  138. void BeginThreadedUpdate();
  139. /// End a threaded update. Notify components that marked themselves for delayed dirty processing.
  140. void EndThreadedUpdate();
  141. /// Add a component to the delayed dirty notify queue. Is thread-safe.
  142. void DelayedMarkedDirty(Component* component);
  143. /// Return threaded update flag.
  144. bool IsThreadedUpdate() const { return threadedUpdate_; }
  145. /// Get free node ID, either non-local or local.
  146. unsigned GetFreeNodeID(CreateMode mode);
  147. /// Get free component ID, either non-local or local.
  148. unsigned GetFreeComponentID(CreateMode mode);
  149. /// Node added. Assign scene pointer and add to ID map.
  150. void NodeAdded(Node* node);
  151. /// Node removed. Remove from ID map.
  152. void NodeRemoved(Node* node);
  153. /// Component added. Add to ID map.
  154. void ComponentAdded(Component* component);
  155. /// Component removed. Remove from ID map.
  156. void ComponentRemoved(Component* component);
  157. /// Set node user variable reverse mappings.
  158. void SetVarNamesAttr(String value);
  159. /// Return node user variable reverse mappings.
  160. String GetVarNamesAttr() const;
  161. /// Prepare network update by comparing attributes and marking replication states dirty as necessary.
  162. void PrepareNetworkUpdate();
  163. /// Clean up all references to a network connection that is about to be removed.
  164. void CleanupConnection(Connection* connection);
  165. /// Mark a node for attribute check on the next network update.
  166. void MarkNetworkUpdate(Node* node);
  167. /// Mark a comoponent for attribute check on the next network update.
  168. void MarkNetworkUpdate(Component* component);
  169. /// Mark a node dirty in scene replication states. The node does not need to have own replication state yet.
  170. void MarkReplicationDirty(Node* node);
  171. private:
  172. /// Handle the logic update event to update the scene, if active.
  173. void HandleUpdate(StringHash eventType, VariantMap& eventData);
  174. /// Update asynchronous loading.
  175. void UpdateAsyncLoading();
  176. /// Finish asynchronous loading.
  177. void FinishAsyncLoading();
  178. /// Finish loading. Sets the scene filename and checksum.
  179. void FinishLoading(Deserializer* source);
  180. /// Finish saving. Sets the scene filename and checksum.
  181. void FinishSaving(Serializer* dest) const;
  182. /// Replicated scene nodes by ID.
  183. HashMap<unsigned, Node*> replicatedNodes_;
  184. /// Local scene nodes by ID.
  185. HashMap<unsigned, Node*> localNodes_;
  186. /// Replicated components by ID.
  187. HashMap<unsigned, Component*> replicatedComponents_;
  188. /// Local components by ID.
  189. HashMap<unsigned, Component*> localComponents_;
  190. /// Asynchronous loading progress.
  191. AsyncProgress asyncProgress_;
  192. /// Node and component ID resolver for asynchronous loading.
  193. SceneResolver resolver_;
  194. /// Source file name.
  195. mutable String fileName_;
  196. /// Required package files for networking.
  197. Vector<SharedPtr<PackageFile> > requiredPackageFiles_;
  198. /// Registered node user variable reverse mappings.
  199. HashMap<ShortStringHash, String> varNames_;
  200. /// Nodes to check for attribute changes on the next network update.
  201. HashSet<unsigned> networkUpdateNodes_;
  202. /// Components to check for attribute changes on the next network update.
  203. HashSet<unsigned> networkUpdateComponents_;
  204. /// Delayed dirty notification queue for components.
  205. PODVector<Component*> delayedDirtyComponents_;
  206. /// Mutex for the delayed dirty notification queue.
  207. Mutex sceneMutex_;
  208. /// Preallocated event data map for smoothing update events.
  209. VariantMap smoothingData_;
  210. /// Next free non-local node ID.
  211. unsigned replicatedNodeID_;
  212. /// Next free non-local component ID.
  213. unsigned replicatedComponentID_;
  214. /// Next free local node ID.
  215. unsigned localNodeID_;
  216. /// Next free local component ID.
  217. unsigned localComponentID_;
  218. /// Scene source file checksum.
  219. mutable unsigned checksum_;
  220. /// Scene update time scale.
  221. float timeScale_;
  222. /// Elapsed time accumulator.
  223. float elapsedTime_;
  224. /// Motion smoothing constant.
  225. float smoothingConstant_;
  226. /// Motion smoothing snap threshold.
  227. float snapThreshold_;
  228. /// Update enabled flag.
  229. bool updateEnabled_;
  230. /// Asynchronous loading flag.
  231. bool asyncLoading_;
  232. /// Threaded update flag.
  233. bool threadedUpdate_;
  234. };
  235. /// Register Scene library objects.
  236. void URHO3D_API RegisterSceneLibrary(Context* context);
  237. }