Scene.h 13 KB

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