BsSceneObject.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742
  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)
  383. {
  384. if (parent.isDestroyed())
  385. return;
  386. #if BS_EDITOR_BUILD
  387. String originalPrefab = getPrefabLink();
  388. #endif
  389. _setParent(parent);
  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)
  397. {
  398. if (mThisHandle == parent)
  399. return;
  400. if (mParent == nullptr || mParent != parent)
  401. {
  402. // Make sure the object keeps its world coordinates
  403. Vector3 worldPos = getWorldPosition();
  404. Quaternion worldRot = getWorldRotation();
  405. Vector3 worldScale = getWorldScale();
  406. if (mParent != nullptr)
  407. mParent->removeChild(mThisHandle);
  408. if (parent != nullptr)
  409. parent->addChild(mThisHandle);
  410. mParent = parent;
  411. setWorldPosition(worldPos);
  412. setWorldRotation(worldRot);
  413. setWorldScale(worldScale);
  414. markTfrmDirty();
  415. }
  416. }
  417. HSceneObject SceneObject::getChild(UINT32 idx) const
  418. {
  419. if(idx < 0 || idx >= mChildren.size())
  420. {
  421. BS_EXCEPT(InternalErrorException, "Child index out of range.");
  422. }
  423. return mChildren[idx];
  424. }
  425. int SceneObject::indexOfChild(const HSceneObject& child) const
  426. {
  427. for(int i = 0; i < (int)mChildren.size(); i++)
  428. {
  429. if(mChildren[i] == child)
  430. return i;
  431. }
  432. return -1;
  433. }
  434. void SceneObject::addChild(const HSceneObject& object)
  435. {
  436. mChildren.push_back(object);
  437. object->setFlags(mFlags);
  438. }
  439. void SceneObject::removeChild(const HSceneObject& object)
  440. {
  441. auto result = find(mChildren.begin(), mChildren.end(), object);
  442. if(result != mChildren.end())
  443. mChildren.erase(result);
  444. else
  445. {
  446. BS_EXCEPT(InternalErrorException,
  447. "Trying to remove a child but it's not a child of the transform.");
  448. }
  449. }
  450. HSceneObject SceneObject::findChild(const String& name, bool recursive)
  451. {
  452. for (auto& child : mChildren)
  453. {
  454. if (child->getName() == name)
  455. return child;
  456. }
  457. if (recursive)
  458. {
  459. for (auto& child : mChildren)
  460. {
  461. HSceneObject foundObject = child->findChild(name, true);
  462. if (foundObject != nullptr)
  463. return foundObject;
  464. }
  465. }
  466. return HSceneObject();
  467. }
  468. Vector<HSceneObject> SceneObject::findChildren(const String& name, bool recursive)
  469. {
  470. std::function<void(const HSceneObject&, Vector<HSceneObject>&)> findChildrenInternal =
  471. [&](const HSceneObject& so, Vector<HSceneObject>& output)
  472. {
  473. for (auto& child : so->mChildren)
  474. {
  475. if (child->getName() == name)
  476. output.push_back(child);
  477. }
  478. if (recursive)
  479. {
  480. for (auto& child : so->mChildren)
  481. findChildrenInternal(child, output);
  482. }
  483. };
  484. Vector<HSceneObject> output;
  485. findChildrenInternal(mThisHandle, output);
  486. return output;
  487. }
  488. void SceneObject::setActive(bool active)
  489. {
  490. mActiveSelf = active;
  491. setActiveHierarchy(active);
  492. }
  493. void SceneObject::setActiveHierarchy(bool active)
  494. {
  495. bool activeHierarchy = active && mActiveSelf;
  496. if (mActiveHierarchy != activeHierarchy)
  497. {
  498. mActiveHierarchy = activeHierarchy;
  499. if (activeHierarchy)
  500. {
  501. for (auto& component : mComponents)
  502. component->onEnabled();
  503. }
  504. else
  505. {
  506. for (auto& component : mComponents)
  507. component->onDisabled();
  508. }
  509. }
  510. for (auto child : mChildren)
  511. {
  512. child->setActiveHierarchy(mActiveHierarchy);
  513. }
  514. }
  515. bool SceneObject::getActive(bool self)
  516. {
  517. if (self)
  518. return mActiveSelf;
  519. else
  520. return mActiveHierarchy;
  521. }
  522. HSceneObject SceneObject::clone()
  523. {
  524. UINT32 bufferSize = 0;
  525. MemorySerializer serializer;
  526. UINT8* buffer = serializer.encode(this, bufferSize, (void*(*)(UINT32))&bs_alloc);
  527. GameObjectManager::instance().setDeserializationMode(GODM_UseNewIds | GODM_RestoreExternal);
  528. std::shared_ptr<SceneObject> cloneObj = std::static_pointer_cast<SceneObject>(serializer.decode(buffer, bufferSize));
  529. bs_free(buffer);
  530. return cloneObj->mThisHandle;
  531. }
  532. HComponent SceneObject::getComponent(UINT32 typeId) const
  533. {
  534. for(auto iter = mComponents.begin(); iter != mComponents.end(); ++iter)
  535. {
  536. if((*iter)->getRTTI()->getRTTIId() == typeId)
  537. return *iter;
  538. }
  539. return HComponent();
  540. }
  541. void SceneObject::destroyComponent(const HComponent component, bool immediate)
  542. {
  543. if(component == nullptr)
  544. {
  545. LOGDBG("Trying to remove a null component");
  546. return;
  547. }
  548. auto iter = std::find(mComponents.begin(), mComponents.end(), component);
  549. if(iter != mComponents.end())
  550. {
  551. (*iter)->_setIsDestroyed();
  552. if (isInstantiated())
  553. {
  554. if (getActive())
  555. component->onDisabled();
  556. (*iter)->onDestroyed();
  557. }
  558. (*iter)->destroyInternal(*iter, immediate);
  559. mComponents.erase(iter);
  560. }
  561. else
  562. LOGDBG("Trying to remove a component that doesn't exist on this SceneObject.");
  563. }
  564. void SceneObject::destroyComponent(Component* component, bool immediate)
  565. {
  566. auto iterFind = std::find_if(mComponents.begin(), mComponents.end(),
  567. [component](const HComponent& x)
  568. {
  569. if(x.isDestroyed())
  570. return false;
  571. return x._getHandleData()->mPtr->object.get() == component; }
  572. );
  573. if(iterFind != mComponents.end())
  574. {
  575. destroyComponent(*iterFind, immediate);
  576. }
  577. }
  578. void SceneObject::addComponentInternal(const std::shared_ptr<Component> component)
  579. {
  580. GameObjectHandle<Component> newComponent = GameObjectManager::instance().getObject(component->getInstanceId());
  581. newComponent->mParent = mThisHandle;
  582. mComponents.push_back(newComponent);
  583. }
  584. RTTITypeBase* SceneObject::getRTTIStatic()
  585. {
  586. return SceneObjectRTTI::instance();
  587. }
  588. RTTITypeBase* SceneObject::getRTTI() const
  589. {
  590. return SceneObject::getRTTIStatic();
  591. }
  592. }