BsSceneObject.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  1. #pragma once
  2. #include "BsCorePrerequisites.h"
  3. #include "BsMatrix4.h"
  4. #include "BsVector3.h"
  5. #include "BsQuaternion.h"
  6. #include "BsRTTIType.h"
  7. #include "BsCoreSceneManager.h"
  8. #include "BsGameObjectManager.h"
  9. #include "BsGameObject.h"
  10. #include "BsComponent.h"
  11. namespace BansheeEngine
  12. {
  13. /**
  14. * @brief Possible modifiers that can be applied to a SceneObject
  15. */
  16. enum SceneObjectFlags
  17. {
  18. SOF_DontInstantiate = 0x01, /**< Object wont be in the main scene and its components won't receive updates. */
  19. SOF_DontSave = 0x02 /**< Object will be skipped when saving the scene hierarchy or a prefab. */
  20. };
  21. /**
  22. * @brief SceneObject represents an object in the scene graph. It has a world position,
  23. * place in the hierarchy and optionally a number of attached components.
  24. */
  25. class BS_CORE_EXPORT SceneObject : public GameObject
  26. {
  27. /**
  28. * @brief Flags that signify which part of the SceneObject needs updating.
  29. */
  30. enum DirtyFlags
  31. {
  32. LocalTfrmDirty = 0x01,
  33. WorldTfrmDirty = 0x02
  34. };
  35. friend class CoreSceneManager;
  36. friend class Prefab;
  37. friend class PrefabDiff;
  38. public:
  39. ~SceneObject();
  40. /**
  41. * @brief Creates a new SceneObject with the specified name. Object will be placed in the top
  42. * of the scene hierarchy.
  43. */
  44. static HSceneObject create(const String& name, UINT32 flags = 0);
  45. /**
  46. * @brief Destroys this object and any of its held components.
  47. *
  48. * @param [in] immediate If true, the object will be deallocated and become unusable
  49. * right away. Otherwise the deallocation will be delayed to the end of
  50. * frame (preferred method).
  51. */
  52. void destroy(bool immediate = false);
  53. /**
  54. * @copydoc GameObject::_setInstanceData
  55. */
  56. void _setInstanceData(GameObjectInstanceDataPtr& other);
  57. /**
  58. * @brief Returns a handle to this object.
  59. */
  60. HSceneObject getHandle() const { return mThisHandle; }
  61. /**
  62. * @brief Returns the prefab this object is linked to, if any.
  63. *
  64. * @note Requires a search of all parents potentially.
  65. */
  66. HPrefab getPrefabLink() const;
  67. /**
  68. * @brief Checks if the scene object has a specific bit flag set.
  69. */
  70. bool hasFlag(UINT32 flag) const;
  71. private:
  72. SceneObject(const String& name, UINT32 flags);
  73. /**
  74. * @brief Creates a new SceneObject instance, registers it with the game object manager,
  75. * creates and returns a handle to the new object.
  76. *
  77. * @note When creating objects with DontInstantiate flag it is the callers responsibility
  78. * to manually destroy the object, otherwise it will leak.
  79. */
  80. static HSceneObject createInternal(const String& name, UINT32 flags = 0);
  81. /**
  82. * @brief Destroys this object and any of its held components.
  83. *
  84. * @param [in] immediate If true, the object will be deallocated and become unusable
  85. * right away. Otherwise the deallocation will be delayed to the end of
  86. * frame (preferred method).
  87. *
  88. * @note Unlike "destroy", does not remove the object from its parent.
  89. */
  90. void destroyInternal(bool immediate = false);
  91. /**
  92. * @brief Recursively enables the provided set of flags on
  93. * this object and all children.
  94. */
  95. void setFlags(UINT32 flags);
  96. /**
  97. * @brief Recursively disables the provided set of flags on
  98. * this object and all children.
  99. */
  100. void unsetFlags(UINT32 flags);
  101. /**
  102. * @brief Checks is the scene object instantiated and visible in the scene.
  103. */
  104. bool isInstantiated() const { return (mFlags & SOF_DontInstantiate) == 0; }
  105. /**
  106. * @brief Register the scene object with the scene and activate all of its components.
  107. */
  108. void instantiate();
  109. private:
  110. HSceneObject mThisHandle;
  111. HPrefab mPrefabLink;
  112. UINT32 mFlags;
  113. /************************************************************************/
  114. /* Transform */
  115. /************************************************************************/
  116. public:
  117. /**
  118. * @brief Sets the local position of the object.
  119. */
  120. void setPosition(const Vector3& position);
  121. /**
  122. * @brief Gets the local position of the object.
  123. */
  124. const Vector3& getPosition() const { return mPosition; }
  125. /**
  126. * @brief Sets the world position of the object.
  127. */
  128. void setWorldPosition(const Vector3& position);
  129. /**
  130. * @brief Gets the world position of the object.
  131. *
  132. * @note Performance warning: This might involve updating the transforms if the transform is dirty.
  133. */
  134. const Vector3& getWorldPosition() const;
  135. /**
  136. * @brief Sets the local rotation of the object.
  137. */
  138. void setRotation(const Quaternion& rotation);
  139. /**
  140. * @brief Gets the local rotation of the object.
  141. */
  142. const Quaternion& getRotation() const { return mRotation; }
  143. /**
  144. * @brief Sets the world rotation of the object.
  145. */
  146. void setWorldRotation(const Quaternion& rotation);
  147. /**
  148. * @brief Gets world rotation of the object.
  149. *
  150. * @note Performance warning: This might involve updating the transforms if the transform is dirty.
  151. */
  152. const Quaternion& getWorldRotation() const;
  153. /**
  154. * @brief Sets the local scale of the object.
  155. */
  156. void setScale(const Vector3& scale);
  157. /**
  158. * @brief Gets the local scale of the object.
  159. */
  160. const Vector3& getScale() const { return mScale; }
  161. /**
  162. * @brief Sets the world scale of the object.
  163. *
  164. * @note This will not work properly if this object or any of its parents
  165. * have non-affine transform matrices.
  166. */
  167. void setWorldScale(const Vector3& scale);
  168. /**
  169. * @brief Gets world scale of the object.
  170. *
  171. * @note Performance warning: This might involve updating the transforms if the transform is dirty.
  172. */
  173. const Vector3& getWorldScale() const;
  174. /**
  175. * @brief Orients the object so it is looking at the provided "location" (local space)
  176. * where "up" is used for determining the location of the objects Y axis.
  177. *
  178. */
  179. void lookAt(const Vector3& location, const Vector3& up = Vector3::UNIT_Y);
  180. /**
  181. * @brief Gets the objects world transform matrix.
  182. *
  183. * @note Performance warning: This might involve updating the transforms if the transform is dirty.
  184. */
  185. const Matrix4& getWorldTfrm() const;
  186. /**
  187. * @brief Gets the objects local transform matrix.
  188. */
  189. const Matrix4& getLocalTfrm() const;
  190. /**
  191. * @brief Moves the object's position by the vector offset provided along world axes.
  192. */
  193. void move(const Vector3& vec);
  194. /**
  195. * @brief Moves the object's position by the vector offset provided along it's own axes (relative to orientation).
  196. */
  197. void moveRelative(const Vector3& vec);
  198. /**
  199. * @brief Gets the Z (forward) axis of the object, in world space.
  200. *
  201. * @return Forward axis of the object.
  202. */
  203. Vector3 getForward() const { return getWorldRotation().rotate(-Vector3::UNIT_Z); }
  204. /**
  205. * @brief Gets the Y (up) axis of the object, in world space.
  206. *
  207. * @return Up axis of the object.
  208. */
  209. Vector3 getUp() const { return getWorldRotation().rotate(Vector3::UNIT_Y); }
  210. /**
  211. * @brief Gets the X (right) axis of the object, in world space.
  212. *
  213. * @return Right axis of the object.
  214. */
  215. Vector3 getRight() const { return getWorldRotation().rotate(Vector3::UNIT_X); }
  216. /**
  217. * @brief Rotates the game object so it's forward axis faces the provided
  218. * direction.
  219. *
  220. * @note Local forward axis is considered to be negative Z.
  221. *
  222. * @param forwardDir The forward direction to face, in world space.
  223. */
  224. void setForward(const Vector3& forwardDir);
  225. /**
  226. * @brief Rotate the object around an arbitrary axis.
  227. */
  228. void rotate(const Vector3& axis, const Radian& angle);
  229. /**
  230. * @brief Rotate the object around an arbitrary axis using a Quaternion.
  231. */
  232. void rotate(const Quaternion& q);
  233. /**
  234. * @brief Rotates around local Z axis.
  235. *
  236. * @param angle Angle to rotate by.
  237. */
  238. void roll(const Radian& angle);
  239. /**
  240. * @brief Rotates around Y axis.
  241. *
  242. * @param angle Angle to rotate by.
  243. */
  244. void yaw(const Radian& angle);
  245. /**
  246. * @brief Rotates around X axis
  247. *
  248. * @param angle Angle to rotate by.
  249. */
  250. void pitch(const Radian& angle);
  251. /**
  252. * @brief Forces any dirty transform matrices on this object to be updated.
  253. *
  254. * @note Normally this is done internally when retrieving a transform, but sometimes
  255. * it is useful to update transforms manually.
  256. */
  257. void updateTransformsIfDirty();
  258. /**
  259. * @brief Returns a hash value that changes whenever a scene objects
  260. * transform gets updated. It allows you to detect changes with
  261. * the local or world transforms without directly comparing their
  262. * values with some older state.
  263. */
  264. UINT32 getTransformHash() const { return mDirtyHash; }
  265. private:
  266. Vector3 mPosition;
  267. Quaternion mRotation;
  268. Vector3 mScale;
  269. mutable Vector3 mWorldPosition;
  270. mutable Quaternion mWorldRotation;
  271. mutable Vector3 mWorldScale;
  272. mutable Matrix4 mCachedLocalTfrm;
  273. mutable Matrix4 mCachedWorldTfrm;
  274. mutable UINT32 mDirtyFlags;
  275. mutable UINT32 mDirtyHash;
  276. /**
  277. * @brief Marks the transform as dirty so that we know to update
  278. * it when the transform is requested.
  279. */
  280. void markTfrmDirty() const;
  281. /**
  282. * @brief Updates the local transform. Normally just reconstructs the
  283. * transform matrix from the position/rotation/scale.
  284. */
  285. void updateLocalTfrm() const;
  286. /**
  287. * @brief Updates the world transform. Reconstructs the local transform
  288. * matrix and multiplies it with any parent transforms.
  289. *
  290. * @note If parent transforms are dirty they will be updated.
  291. */
  292. void updateWorldTfrm() const;
  293. /**
  294. * @brief Checks if cached local transform needs updating.
  295. */
  296. bool isCachedLocalTfrmUpToDate() const { return (mDirtyFlags & DirtyFlags::LocalTfrmDirty) == 0; }
  297. /**
  298. * @brief Checks if cached world transform needs updating.
  299. */
  300. bool isCachedWorldTfrmUpToDate() const { return (mDirtyFlags & DirtyFlags::WorldTfrmDirty) == 0; }
  301. /************************************************************************/
  302. /* Hierarchy */
  303. /************************************************************************/
  304. public:
  305. /**
  306. * @brief Changes the parent of this object. Also removes the object from the current parent,
  307. * and assigns it to the new parent.
  308. *
  309. * @param [in] parent New parent.
  310. */
  311. void setParent(const HSceneObject& parent);
  312. /**
  313. * @brief Gets the parent of this object.
  314. *
  315. * @return Parent object, or nullptr if this SceneObject is at root level.
  316. */
  317. HSceneObject getParent() const { return mParent; }
  318. /**
  319. * @brief Gets a child of this item.
  320. *
  321. * @param idx The zero based index of the child.
  322. *
  323. * @return SceneObject of the child.
  324. */
  325. HSceneObject getChild(UINT32 idx) const;
  326. /**
  327. * @brief Find the index of the specified child. Don't persist this value as
  328. * it may change whenever you add/remove children.
  329. *
  330. * @param child The child to look for.
  331. *
  332. * @return The zero-based index of the found child, or -1 if no match was found.
  333. */
  334. int indexOfChild(const HSceneObject& child) const;
  335. /**
  336. * @brief Gets the number of all child GameObjects.
  337. */
  338. UINT32 getNumChildren() const { return (UINT32)mChildren.size(); }
  339. /**
  340. * @brief Enables or disables this object. Disabled objects also implicitly disable
  341. * all their child objects. No components on the disabled object are updated.
  342. */
  343. void setActive(bool active);
  344. /**
  345. * @brief Returns whether or not an object is active.
  346. *
  347. * @param self If true, the method will only check if this particular object was activated
  348. * or deactivated directly via setActive. If false we we also check if any of
  349. * the objects parents are inactive.
  350. */
  351. bool getActive(bool self = false);
  352. /**
  353. * @brief Makes a deep copy of this object.
  354. */
  355. HSceneObject clone();
  356. private:
  357. HSceneObject mParent;
  358. Vector<HSceneObject> mChildren;
  359. bool mActiveSelf;
  360. bool mActiveHierarchy;
  361. /**
  362. * @brief Adds a child to the child array. This method doesn't check for null or duplicate values.
  363. *
  364. * @param [in] object New child.
  365. */
  366. void addChild(const HSceneObject& object);
  367. /**
  368. * @brief Removes the child from the object.
  369. *
  370. * @param [in] object Child to remove.
  371. *
  372. * @throws INTERNAL_ERROR If the provided child isn't a child of the current object.
  373. */
  374. void removeChild(const HSceneObject& object);
  375. /**
  376. * @brief Changes the object active in hierarchy state.
  377. */
  378. void setActiveHierarchy(bool active);
  379. /************************************************************************/
  380. /* Component */
  381. /************************************************************************/
  382. public:
  383. /**
  384. * @brief Constructs a new component of the specified type and adds it to
  385. * the internal component list.
  386. */
  387. template<class T, class... Args>
  388. GameObjectHandle<T> addComponent(Args &&... args)
  389. {
  390. static_assert((std::is_base_of<BansheeEngine::Component, T>::value),
  391. "Specified type is not a valid Component.");
  392. std::shared_ptr<T> gameObject(new (bs_alloc<T, PoolAlloc>()) T(mThisHandle,
  393. std::forward<Args>(args)...),
  394. &bs_delete<PoolAlloc, T>, StdAlloc<T, PoolAlloc>());
  395. GameObjectHandle<T> newComponent =
  396. GameObjectHandle<T>(GameObjectManager::instance().registerObject(gameObject));
  397. mComponents.push_back(newComponent);
  398. if (isInstantiated())
  399. newComponent->onInitialized();
  400. return newComponent;
  401. }
  402. /**
  403. * @brief Searches for a component with the specific type and returns the first one
  404. * it finds.
  405. *
  406. * @note Don't call this too often as it is relatively slow. It is more efficient
  407. * to call it once and store the result for further use.
  408. *
  409. * @tparam typename T Type of the component.
  410. *
  411. * @return Component if found, nullptr otherwise.
  412. */
  413. template <typename T>
  414. GameObjectHandle<T> getComponent()
  415. {
  416. static_assert((std::is_base_of<BansheeEngine::Component, T>::value),
  417. "Specified type is not a valid Component.");
  418. return static_object_cast<T>(getComponent(T::getRTTIStatic()->getRTTIId()));
  419. }
  420. /**
  421. * @brief Checks if the current object contains the specified component
  422. *
  423. * @note Don't call this too often as it is relatively slow.
  424. *
  425. * @tparam typename T Type of the component.
  426. *
  427. * @return True if component exists on the object.
  428. */
  429. template <typename T>
  430. bool hasComponent()
  431. {
  432. static_assert((std::is_base_of<BansheeEngine::Component, T>::value),
  433. "Specified type is not a valid Component.");
  434. for (auto iter = mComponents.begin(); iter != mComponents.end(); ++iter)
  435. {
  436. if ((*iter)->getRTTI()->getRTTIId() == T::getRTTIStatic()->getRTTIId())
  437. return true;
  438. }
  439. return false;
  440. }
  441. /**
  442. * @brief Searches for a component with the specified type id and returns the first one it
  443. * finds.
  444. *
  445. * @note Don't call this too often as it is relatively slow. It is more efficient to
  446. * call it once and store the result for further use.
  447. *
  448. * @param typeId Identifier for the type.
  449. *
  450. * @return Component if found, nullptr otherwise.
  451. */
  452. HComponent getComponent(UINT32 typeId) const;
  453. /**
  454. * @brief Removes the component from this object, and deallocates it.
  455. *
  456. * @param [in] component The component to destroy.
  457. * @param [in] immediate If true, the component will be deallocated and become unusable
  458. * right away. Otherwise the deallocation will be delayed to the end of
  459. * frame (preferred method).
  460. */
  461. void destroyComponent(const HComponent& component, bool immediate = false);
  462. /**
  463. * @brief Removes the component from this object, and deallocates it.
  464. *
  465. * @param [in] component The component to destroy.
  466. * @param [in] immediate If true, the component will be deallocated and become unusable
  467. * right away. Otherwise the deallocation will be delayed to the end of
  468. * frame (preferred method).
  469. */
  470. void destroyComponent(Component* component, bool immediate = false);
  471. /**
  472. * @brief Returns all components on this object.
  473. */
  474. const Vector<HComponent>& getComponents() const { return mComponents; }
  475. private:
  476. /**
  477. * @brief Creates an empty component with the default constructor.
  478. */
  479. template <typename T>
  480. static std::shared_ptr<T> createEmptyComponent()
  481. {
  482. static_assert((std::is_base_of<BansheeEngine::Component, T>::value), "Specified type is not a valid Component.");
  483. std::shared_ptr<T> gameObject(new (bs_alloc<T, PoolAlloc>()) T(), &bs_delete<PoolAlloc, T>, StdAlloc<T, PoolAlloc>());
  484. GameObjectHandle<T>(GameObjectManager::instance().registerObject(gameObject));
  485. return gameObject;
  486. }
  487. /**
  488. * @brief Adds the component to the internal component array.
  489. */
  490. void addComponentInternal(const std::shared_ptr<Component> component);
  491. Vector<HComponent> mComponents;
  492. /************************************************************************/
  493. /* RTTI */
  494. /************************************************************************/
  495. public:
  496. friend class GameObjectRTTI;
  497. friend class SceneObjectRTTI;
  498. static RTTITypeBase* getRTTIStatic();
  499. virtual RTTITypeBase* getRTTI() const;
  500. };
  501. }