BsSceneObject.cpp 14 KB

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