BsSceneObject.cpp 17 KB

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