Scene.h 16 KB

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