BsSceneObject.cpp 16 KB

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