BsSceneObject.cpp 17 KB

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