BsSceneObject.cpp 15 KB

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