BsSceneObject.cpp 15 KB

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