BsSceneObject.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #include "BsSceneObject.h"
  4. #include "BsComponent.h"
  5. #include "BsCoreSceneManager.h"
  6. #include "BsException.h"
  7. #include "BsDebug.h"
  8. #include "BsSceneObjectRTTI.h"
  9. #include "BsMemorySerializer.h"
  10. #include "BsGameObjectManager.h"
  11. #include "BsPrefabUtility.h"
  12. #include "BsMatrix3.h"
  13. #include "BsCoreApplication.h"
  14. namespace BansheeEngine
  15. {
  16. SceneObject::SceneObject(const String& name, UINT32 flags)
  17. :GameObject(), mPosition(Vector3::ZERO), mRotation(Quaternion::IDENTITY), mScale(Vector3::ONE),
  18. mWorldPosition(Vector3::ZERO), mWorldRotation(Quaternion::IDENTITY), mWorldScale(Vector3::ONE),
  19. mCachedLocalTfrm(Matrix4::IDENTITY), mDirtyFlags(0xFFFFFFFF), mCachedWorldTfrm(Matrix4::IDENTITY),
  20. mActiveSelf(true), mActiveHierarchy(true), mDirtyHash(0), mFlags(flags), mPrefabHash(0)
  21. {
  22. setName(name);
  23. }
  24. SceneObject::~SceneObject()
  25. {
  26. if(!mThisHandle.isDestroyed())
  27. {
  28. LOGWRN("Object is being deleted without being destroyed first?");
  29. destroyInternal(mThisHandle, true);
  30. }
  31. }
  32. HSceneObject SceneObject::create(const String& name, UINT32 flags)
  33. {
  34. HSceneObject newObject = createInternal(name, flags);
  35. if (newObject->isInstantiated())
  36. gCoreSceneManager().registerNewSO(newObject);
  37. return newObject;
  38. }
  39. HSceneObject SceneObject::createInternal(const String& name, UINT32 flags)
  40. {
  41. SPtr<SceneObject> sceneObjectPtr = SPtr<SceneObject>(new (bs_alloc<SceneObject>()) SceneObject(name, flags),
  42. &bs_delete<SceneObject>, StdAlloc<SceneObject>());
  43. HSceneObject sceneObject = GameObjectManager::instance().registerObject(sceneObjectPtr);
  44. sceneObject->mThisHandle = sceneObject;
  45. return sceneObject;
  46. }
  47. HSceneObject SceneObject::createInternal(const SPtr<SceneObject>& soPtr, UINT64 originalId)
  48. {
  49. HSceneObject sceneObject = GameObjectManager::instance().registerObject(soPtr, originalId);
  50. sceneObject->mThisHandle = sceneObject;
  51. return sceneObject;
  52. }
  53. void SceneObject::destroy(bool immediate)
  54. {
  55. // Parent is our owner, so when his reference to us is removed, delete might be called.
  56. // So make sure this is the last thing we do.
  57. if(mParent != nullptr)
  58. {
  59. if(!mParent.isDestroyed())
  60. mParent->removeChild(mThisHandle);
  61. mParent = nullptr;
  62. }
  63. destroyInternal(mThisHandle, immediate);
  64. }
  65. void SceneObject::destroyInternal(GameObjectHandleBase& handle, bool immediate)
  66. {
  67. if (immediate)
  68. {
  69. for (auto iter = mChildren.begin(); iter != mChildren.end(); ++iter)
  70. (*iter)->destroyInternal(*iter, true);
  71. mChildren.clear();
  72. for (auto iter = mComponents.begin(); iter != mComponents.end(); ++iter)
  73. {
  74. HComponent component = *iter;
  75. component->_setIsDestroyed();
  76. if (isInstantiated())
  77. {
  78. if (getActive())
  79. component->onDisabled();
  80. component->onDestroyed();
  81. }
  82. component->destroyInternal(*iter, true);
  83. }
  84. mComponents.clear();
  85. GameObjectManager::instance().unregisterObject(handle);
  86. }
  87. else
  88. GameObjectManager::instance().queueForDestroy(handle);
  89. }
  90. void SceneObject::_setInstanceData(GameObjectInstanceDataPtr& other)
  91. {
  92. GameObject::_setInstanceData(other);
  93. // Instance data changed, so make sure to refresh the handles to reflect that
  94. mThisHandle._setHandleData(mThisHandle.getInternalPtr());
  95. }
  96. String SceneObject::getPrefabLink() const
  97. {
  98. const SceneObject* curObj = this;
  99. while (curObj != nullptr)
  100. {
  101. if (!curObj->mPrefabLinkUUID.empty())
  102. return curObj->mPrefabLinkUUID;
  103. if (curObj->mParent != nullptr)
  104. curObj = curObj->mParent.get();
  105. else
  106. curObj = nullptr;
  107. }
  108. return "";
  109. }
  110. HSceneObject SceneObject::getPrefabParent() const
  111. {
  112. HSceneObject curObj = mThisHandle;
  113. while (curObj != nullptr)
  114. {
  115. if (!curObj->mPrefabLinkUUID.empty())
  116. return curObj;
  117. if (curObj->mParent != nullptr)
  118. curObj = curObj->mParent;
  119. else
  120. curObj = nullptr;
  121. }
  122. return curObj;
  123. }
  124. void SceneObject::breakPrefabLink()
  125. {
  126. SceneObject* rootObj = this;
  127. while (rootObj != nullptr)
  128. {
  129. if (!rootObj->mPrefabLinkUUID.empty())
  130. break;
  131. if (rootObj->mParent != nullptr)
  132. rootObj = rootObj->mParent.get();
  133. else
  134. rootObj = nullptr;
  135. }
  136. if (rootObj != nullptr)
  137. {
  138. rootObj->mPrefabLinkUUID = "";
  139. rootObj->mPrefabDiff = nullptr;
  140. PrefabUtility::clearPrefabIds(rootObj->getHandle());
  141. }
  142. }
  143. bool SceneObject::hasFlag(UINT32 flag) const
  144. {
  145. return (mFlags & flag) != 0;
  146. }
  147. void SceneObject::setFlags(UINT32 flags)
  148. {
  149. mFlags |= flags;
  150. for (auto& child : mChildren)
  151. child->setFlags(flags);
  152. }
  153. void SceneObject::unsetFlags(UINT32 flags)
  154. {
  155. mFlags &= ~flags;
  156. for (auto& child : mChildren)
  157. child->unsetFlags(flags);
  158. }
  159. void SceneObject::_instantiate()
  160. {
  161. std::function<void(SceneObject*)> instantiateRecursive = [&](SceneObject* obj)
  162. {
  163. obj->mFlags &= ~SOF_DontInstantiate;
  164. if (obj->mParent == nullptr)
  165. gCoreSceneManager().registerNewSO(obj->mThisHandle);
  166. for (auto& component : obj->mComponents)
  167. component->instantiate();
  168. for (auto& child : obj->mChildren)
  169. instantiateRecursive(child.get());
  170. };
  171. std::function<void(SceneObject*)> triggerEventsRecursive = [&](SceneObject* obj)
  172. {
  173. for (auto& component : obj->mComponents)
  174. {
  175. component->onInitialized();
  176. if (obj->getActive())
  177. component->onEnabled();
  178. }
  179. for (auto& child : obj->mChildren)
  180. triggerEventsRecursive(child.get());
  181. };
  182. instantiateRecursive(this);
  183. triggerEventsRecursive(this);
  184. }
  185. /************************************************************************/
  186. /* Transform */
  187. /************************************************************************/
  188. void SceneObject::setPosition(const Vector3& position)
  189. {
  190. mPosition = position;
  191. notifyTransformChanged(TCF_Transform);
  192. }
  193. void SceneObject::setRotation(const Quaternion& rotation)
  194. {
  195. mRotation = rotation;
  196. notifyTransformChanged(TCF_Transform);
  197. }
  198. void SceneObject::setScale(const Vector3& scale)
  199. {
  200. mScale = scale;
  201. notifyTransformChanged(TCF_Transform);
  202. }
  203. void SceneObject::setWorldPosition(const Vector3& position)
  204. {
  205. if (mParent != nullptr)
  206. {
  207. Vector3 invScale = mParent->getWorldScale();
  208. if (invScale.x != 0) invScale.x = 1.0f / invScale.x;
  209. if (invScale.y != 0) invScale.y = 1.0f / invScale.y;
  210. if (invScale.z != 0) invScale.z = 1.0f / invScale.z;
  211. Quaternion invRotation = mParent->getWorldRotation().inverse();
  212. mPosition = invRotation.rotate(position - mParent->getWorldPosition()) * invScale;
  213. }
  214. else
  215. mPosition = position;
  216. notifyTransformChanged(TCF_Transform);
  217. }
  218. void SceneObject::setWorldRotation(const Quaternion& rotation)
  219. {
  220. if (mParent != nullptr)
  221. {
  222. Quaternion invRotation = mParent->getWorldRotation().inverse();
  223. mRotation = invRotation * rotation;
  224. }
  225. else
  226. mRotation = rotation;
  227. notifyTransformChanged(TCF_Transform);
  228. }
  229. void SceneObject::setWorldScale(const Vector3& scale)
  230. {
  231. if (mParent != nullptr)
  232. {
  233. Matrix3 rotScale;
  234. mParent->getWorldTfrm().extract3x3Matrix(rotScale);
  235. rotScale.inverse();
  236. Matrix3 scaleMat = Matrix3(Quaternion::IDENTITY, scale);
  237. scaleMat = rotScale * scaleMat;
  238. Quaternion rotation;
  239. Vector3 localScale;
  240. scaleMat.decomposition(rotation, localScale);
  241. mScale = localScale;
  242. }
  243. else
  244. mScale = scale;
  245. notifyTransformChanged(TCF_Transform);
  246. }
  247. const Vector3& SceneObject::getWorldPosition() const
  248. {
  249. if (!isCachedWorldTfrmUpToDate())
  250. updateWorldTfrm();
  251. return mWorldPosition;
  252. }
  253. const Quaternion& SceneObject::getWorldRotation() const
  254. {
  255. if (!isCachedWorldTfrmUpToDate())
  256. updateWorldTfrm();
  257. return mWorldRotation;
  258. }
  259. const Vector3& SceneObject::getWorldScale() const
  260. {
  261. if (!isCachedWorldTfrmUpToDate())
  262. updateWorldTfrm();
  263. return mWorldScale;
  264. }
  265. void SceneObject::lookAt(const Vector3& location, const Vector3& up)
  266. {
  267. Vector3 forward = location - getWorldPosition();
  268. Quaternion rotation = getWorldRotation();
  269. rotation.lookRotation(forward, up);
  270. setWorldRotation(rotation);
  271. }
  272. const Matrix4& SceneObject::getWorldTfrm() const
  273. {
  274. if (!isCachedWorldTfrmUpToDate())
  275. updateWorldTfrm();
  276. return mCachedWorldTfrm;
  277. }
  278. const Matrix4& SceneObject::getLocalTfrm() const
  279. {
  280. if (!isCachedLocalTfrmUpToDate())
  281. updateLocalTfrm();
  282. return mCachedLocalTfrm;
  283. }
  284. void SceneObject::move(const Vector3& vec)
  285. {
  286. setPosition(mPosition + vec);
  287. }
  288. void SceneObject::moveRelative(const Vector3& vec)
  289. {
  290. // Transform the axes of the relative vector by camera's local axes
  291. Vector3 trans = mRotation.rotate(vec);
  292. setPosition(mPosition + trans);
  293. }
  294. void SceneObject::rotate(const Vector3& axis, const Radian& angle)
  295. {
  296. Quaternion q;
  297. q.fromAxisAngle(axis, angle);
  298. rotate(q);
  299. }
  300. void SceneObject::rotate(const Quaternion& q)
  301. {
  302. // Note the order of the mult, i.e. q comes after
  303. // Normalize the quat to avoid cumulative problems with precision
  304. Quaternion qnorm = q;
  305. qnorm.normalize();
  306. setRotation(qnorm * mRotation);
  307. }
  308. void SceneObject::roll(const Radian& angle)
  309. {
  310. // Rotate around local Z axis
  311. Vector3 zAxis = mRotation.rotate(Vector3::UNIT_Z);
  312. rotate(zAxis, angle);
  313. }
  314. void SceneObject::yaw(const Radian& angle)
  315. {
  316. Vector3 yAxis = mRotation.rotate(Vector3::UNIT_Y);
  317. rotate(yAxis, angle);
  318. }
  319. void SceneObject::pitch(const Radian& angle)
  320. {
  321. // Rotate around local X axis
  322. Vector3 xAxis = mRotation.rotate(Vector3::UNIT_X);
  323. rotate(xAxis, angle);
  324. }
  325. void SceneObject::setForward(const Vector3& forwardDir)
  326. {
  327. Quaternion currentRotation = getWorldRotation();
  328. currentRotation.lookRotation(forwardDir);
  329. setWorldRotation(currentRotation);
  330. }
  331. void SceneObject::updateTransformsIfDirty()
  332. {
  333. if (!isCachedLocalTfrmUpToDate())
  334. updateLocalTfrm();
  335. if (!isCachedWorldTfrmUpToDate())
  336. updateWorldTfrm();
  337. }
  338. void SceneObject::notifyTransformChanged(TransformChangedFlags flags) const
  339. {
  340. mDirtyFlags |= DirtyFlags::LocalTfrmDirty | DirtyFlags::WorldTfrmDirty;
  341. mDirtyHash++;
  342. for(auto& entry : mComponents)
  343. {
  344. if (entry->supportsNotify(flags))
  345. entry->onTransformChanged(flags);
  346. }
  347. for (auto& entry : mChildren)
  348. entry->notifyTransformChanged(flags);
  349. }
  350. void SceneObject::updateWorldTfrm() const
  351. {
  352. if(mParent != nullptr)
  353. {
  354. // Update orientation
  355. const Quaternion& parentOrientation = mParent->getWorldRotation();
  356. mWorldRotation = parentOrientation * mRotation;
  357. // Update scale
  358. const Vector3& parentScale = mParent->getWorldScale();
  359. // Scale own position by parent scale, just combine
  360. // as equivalent axes, no shearing
  361. mWorldScale = parentScale * mScale;
  362. // Change position vector based on parent's orientation & scale
  363. mWorldPosition = parentOrientation.rotate(parentScale * mPosition);
  364. // Add altered position vector to parents
  365. mWorldPosition += mParent->getWorldPosition();
  366. mCachedWorldTfrm.setTRS(mWorldPosition, mWorldRotation, mWorldScale);
  367. }
  368. else
  369. {
  370. mWorldRotation = mRotation;
  371. mWorldPosition = mPosition;
  372. mWorldScale = mScale;
  373. mCachedWorldTfrm = getLocalTfrm();
  374. }
  375. mDirtyFlags &= ~DirtyFlags::WorldTfrmDirty;
  376. }
  377. void SceneObject::updateLocalTfrm() const
  378. {
  379. mCachedLocalTfrm.setTRS(mPosition, mRotation, mScale);
  380. mDirtyFlags &= ~DirtyFlags::LocalTfrmDirty;
  381. }
  382. /************************************************************************/
  383. /* Hierarchy */
  384. /************************************************************************/
  385. void SceneObject::setParent(const HSceneObject& parent, bool keepWorldTransform)
  386. {
  387. if (parent.isDestroyed())
  388. return;
  389. #if BS_EDITOR_BUILD
  390. String originalPrefab = getPrefabLink();
  391. #endif
  392. _setParent(parent, keepWorldTransform);
  393. #if BS_EDITOR_BUILD
  394. if (gCoreApplication().isEditor())
  395. {
  396. String newPrefab = getPrefabLink();
  397. if (originalPrefab != newPrefab)
  398. PrefabUtility::clearPrefabIds(mThisHandle);
  399. }
  400. #endif
  401. }
  402. void SceneObject::_setParent(const HSceneObject& parent, bool keepWorldTransform)
  403. {
  404. if (mThisHandle == parent)
  405. return;
  406. if (mParent == nullptr || mParent != parent)
  407. {
  408. Vector3 worldPos;
  409. Quaternion worldRot;
  410. Vector3 worldScale;
  411. if (keepWorldTransform)
  412. {
  413. // Make sure the object keeps its world coordinates
  414. worldPos = getWorldPosition();
  415. worldRot = getWorldRotation();
  416. worldScale = getWorldScale();
  417. }
  418. if (mParent != nullptr)
  419. mParent->removeChild(mThisHandle);
  420. if (parent != nullptr)
  421. parent->addChild(mThisHandle);
  422. mParent = parent;
  423. if (keepWorldTransform)
  424. {
  425. setWorldPosition(worldPos);
  426. setWorldRotation(worldRot);
  427. setWorldScale(worldScale);
  428. }
  429. notifyTransformChanged((TransformChangedFlags)(TCF_Parent | TCF_Transform));
  430. }
  431. }
  432. HSceneObject SceneObject::getChild(UINT32 idx) const
  433. {
  434. if(idx < 0 || idx >= mChildren.size())
  435. {
  436. BS_EXCEPT(InternalErrorException, "Child index out of range.");
  437. }
  438. return mChildren[idx];
  439. }
  440. int SceneObject::indexOfChild(const HSceneObject& child) const
  441. {
  442. for(int i = 0; i < (int)mChildren.size(); i++)
  443. {
  444. if(mChildren[i] == child)
  445. return i;
  446. }
  447. return -1;
  448. }
  449. void SceneObject::addChild(const HSceneObject& object)
  450. {
  451. mChildren.push_back(object);
  452. object->setFlags(mFlags);
  453. }
  454. void SceneObject::removeChild(const HSceneObject& object)
  455. {
  456. auto result = find(mChildren.begin(), mChildren.end(), object);
  457. if(result != mChildren.end())
  458. mChildren.erase(result);
  459. else
  460. {
  461. BS_EXCEPT(InternalErrorException,
  462. "Trying to remove a child but it's not a child of the transform.");
  463. }
  464. }
  465. HSceneObject SceneObject::findChild(const String& name, bool recursive)
  466. {
  467. for (auto& child : mChildren)
  468. {
  469. if (child->getName() == name)
  470. return child;
  471. }
  472. if (recursive)
  473. {
  474. for (auto& child : mChildren)
  475. {
  476. HSceneObject foundObject = child->findChild(name, true);
  477. if (foundObject != nullptr)
  478. return foundObject;
  479. }
  480. }
  481. return HSceneObject();
  482. }
  483. Vector<HSceneObject> SceneObject::findChildren(const String& name, bool recursive)
  484. {
  485. std::function<void(const HSceneObject&, Vector<HSceneObject>&)> findChildrenInternal =
  486. [&](const HSceneObject& so, Vector<HSceneObject>& output)
  487. {
  488. for (auto& child : so->mChildren)
  489. {
  490. if (child->getName() == name)
  491. output.push_back(child);
  492. }
  493. if (recursive)
  494. {
  495. for (auto& child : so->mChildren)
  496. findChildrenInternal(child, output);
  497. }
  498. };
  499. Vector<HSceneObject> output;
  500. findChildrenInternal(mThisHandle, output);
  501. return output;
  502. }
  503. void SceneObject::setActive(bool active)
  504. {
  505. mActiveSelf = active;
  506. setActiveHierarchy(active);
  507. }
  508. void SceneObject::setActiveHierarchy(bool active)
  509. {
  510. bool activeHierarchy = active && mActiveSelf;
  511. if (mActiveHierarchy != activeHierarchy)
  512. {
  513. mActiveHierarchy = activeHierarchy;
  514. if (activeHierarchy)
  515. {
  516. for (auto& component : mComponents)
  517. component->onEnabled();
  518. }
  519. else
  520. {
  521. for (auto& component : mComponents)
  522. component->onDisabled();
  523. }
  524. }
  525. for (auto child : mChildren)
  526. {
  527. child->setActiveHierarchy(mActiveHierarchy);
  528. }
  529. }
  530. bool SceneObject::getActive(bool self)
  531. {
  532. if (self)
  533. return mActiveSelf;
  534. else
  535. return mActiveHierarchy;
  536. }
  537. HSceneObject SceneObject::clone(bool instantiate)
  538. {
  539. if (!instantiate)
  540. setFlags(SOF_DontInstantiate);
  541. UINT32 bufferSize = 0;
  542. MemorySerializer serializer;
  543. UINT8* buffer = serializer.encode(this, bufferSize, (void*(*)(UINT32))&bs_alloc);
  544. GameObjectManager::instance().setDeserializationMode(GODM_UseNewIds | GODM_RestoreExternal);
  545. std::shared_ptr<SceneObject> cloneObj = std::static_pointer_cast<SceneObject>(serializer.decode(buffer, bufferSize));
  546. bs_free(buffer);
  547. if (!instantiate)
  548. unsetFlags(SOF_DontInstantiate);
  549. return cloneObj->mThisHandle;
  550. }
  551. HComponent SceneObject::getComponent(UINT32 typeId) const
  552. {
  553. for(auto iter = mComponents.begin(); iter != mComponents.end(); ++iter)
  554. {
  555. if((*iter)->getRTTI()->getRTTIId() == typeId)
  556. return *iter;
  557. }
  558. return HComponent();
  559. }
  560. void SceneObject::destroyComponent(const HComponent component, bool immediate)
  561. {
  562. if(component == nullptr)
  563. {
  564. LOGDBG("Trying to remove a null component");
  565. return;
  566. }
  567. auto iter = std::find(mComponents.begin(), mComponents.end(), component);
  568. if(iter != mComponents.end())
  569. {
  570. (*iter)->_setIsDestroyed();
  571. if (isInstantiated())
  572. {
  573. if (getActive())
  574. component->onDisabled();
  575. (*iter)->onDestroyed();
  576. }
  577. (*iter)->destroyInternal(*iter, immediate);
  578. mComponents.erase(iter);
  579. }
  580. else
  581. LOGDBG("Trying to remove a component that doesn't exist on this SceneObject.");
  582. }
  583. void SceneObject::destroyComponent(Component* component, bool immediate)
  584. {
  585. auto iterFind = std::find_if(mComponents.begin(), mComponents.end(),
  586. [component](const HComponent& x)
  587. {
  588. if(x.isDestroyed())
  589. return false;
  590. return x._getHandleData()->mPtr->object.get() == component; }
  591. );
  592. if(iterFind != mComponents.end())
  593. {
  594. destroyComponent(*iterFind, immediate);
  595. }
  596. }
  597. void SceneObject::addComponentInternal(const std::shared_ptr<Component> component)
  598. {
  599. GameObjectHandle<Component> newComponent = GameObjectManager::instance().getObject(component->getInstanceId());
  600. newComponent->mParent = mThisHandle;
  601. mComponents.push_back(newComponent);
  602. }
  603. RTTITypeBase* SceneObject::getRTTIStatic()
  604. {
  605. return SceneObjectRTTI::instance();
  606. }
  607. RTTITypeBase* SceneObject::getRTTI() const
  608. {
  609. return SceneObject::getRTTIStatic();
  610. }
  611. }