BsSceneObject.cpp 15 KB

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