BsSceneObject.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  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)
  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), mIsCachedLocalTfrmUpToDate(false),
  15. mCachedWorldTfrm(Matrix4::IDENTITY), mIsCachedWorldTfrmUpToDate(false), mIsCoreDirtyFlags(0xFFFFFFFF)
  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();
  25. }
  26. }
  27. HSceneObject SceneObject::create(const String& name)
  28. {
  29. HSceneObject newObject = createInternal(name);
  30. gSceneManager().registerNewSO(newObject);
  31. return newObject;
  32. }
  33. HSceneObject SceneObject::createInternal(const String& name)
  34. {
  35. std::shared_ptr<SceneObject> sceneObjectPtr = std::shared_ptr<SceneObject>(new (bs_alloc<SceneObject, PoolAlloc>()) SceneObject(name),
  36. &bs_delete<PoolAlloc, SceneObject>, StdAlloc<PoolAlloc>());
  37. HSceneObject sceneObject = GameObjectManager::instance().registerObject(sceneObjectPtr);
  38. sceneObject->mThisHandle = sceneObject;
  39. return sceneObject;
  40. }
  41. void SceneObject::destroy()
  42. {
  43. // Parent is our owner, so when his reference to us is removed, delete might be called.
  44. // So make sure this is the last thing we do.
  45. if(mParent != nullptr)
  46. {
  47. if(!mParent.isDestroyed())
  48. mParent->removeChild(mThisHandle);
  49. }
  50. destroyInternal();
  51. }
  52. void SceneObject::destroyInternal()
  53. {
  54. for(auto iter = mChildren.begin(); iter != mChildren.end(); ++iter)
  55. (*iter)->destroyInternal();
  56. mChildren.clear();
  57. for(auto iter = mComponents.begin(); iter != mComponents.end(); ++iter)
  58. {
  59. gSceneManager().notifyComponentRemoved((*iter));
  60. GameObjectManager::instance().unregisterObject(*iter);
  61. (*iter).destroy();
  62. }
  63. mComponents.clear();
  64. GameObjectManager::instance().unregisterObject(mThisHandle);
  65. mThisHandle.destroy();
  66. }
  67. /************************************************************************/
  68. /* Transform */
  69. /************************************************************************/
  70. void SceneObject::setPosition(const Vector3& position)
  71. {
  72. mPosition = position;
  73. markTfrmDirty();
  74. }
  75. void SceneObject::setRotation(const Quaternion& rotation)
  76. {
  77. mRotation = rotation;
  78. markTfrmDirty();
  79. }
  80. void SceneObject::setScale(const Vector3& scale)
  81. {
  82. mScale = scale;
  83. markTfrmDirty();
  84. }
  85. const Vector3& SceneObject::getWorldPosition() const
  86. {
  87. if(!mIsCachedWorldTfrmUpToDate)
  88. updateWorldTfrm();
  89. return mWorldPosition;
  90. }
  91. const Quaternion& SceneObject::getWorldRotation() const
  92. {
  93. if(!mIsCachedWorldTfrmUpToDate)
  94. updateWorldTfrm();
  95. return mWorldRotation;
  96. }
  97. const Vector3& SceneObject::getWorldScale() const
  98. {
  99. if(!mIsCachedWorldTfrmUpToDate)
  100. updateWorldTfrm();
  101. return mWorldScale;
  102. }
  103. void SceneObject::lookAt(const Vector3& location, const Vector3& up)
  104. {
  105. Vector3 forward = location - mPosition;
  106. forward.normalize();
  107. setForward(forward);
  108. Quaternion upRot = Quaternion::getRotationFromTo(getUp(), up);
  109. setRotation(getRotation() * upRot);
  110. }
  111. const Matrix4& SceneObject::getWorldTfrm() const
  112. {
  113. if(!mIsCachedWorldTfrmUpToDate)
  114. updateWorldTfrm();
  115. return mCachedWorldTfrm;
  116. }
  117. const Matrix4& SceneObject::getLocalTfrm() const
  118. {
  119. if(!mIsCachedLocalTfrmUpToDate)
  120. updateLocalTfrm();
  121. return mCachedLocalTfrm;
  122. }
  123. void SceneObject::move(const Vector3& vec)
  124. {
  125. setPosition(mPosition + vec);
  126. }
  127. void SceneObject::moveRelative(const Vector3& vec)
  128. {
  129. // Transform the axes of the relative vector by camera's local axes
  130. Vector3 trans = mRotation.rotate(vec);
  131. setPosition(mPosition + trans);
  132. }
  133. void SceneObject::rotate(const Vector3& axis, const Radian& angle)
  134. {
  135. Quaternion q;
  136. q.fromAxisAngle(axis, angle);
  137. rotate(q);
  138. }
  139. void SceneObject::rotate(const Quaternion& q)
  140. {
  141. // Note the order of the mult, i.e. q comes after
  142. // Normalize the quat to avoid cumulative problems with precision
  143. Quaternion qnorm = q;
  144. qnorm.normalize();
  145. setRotation(qnorm * mRotation);
  146. }
  147. void SceneObject::roll(const Radian& angle)
  148. {
  149. // Rotate around local Z axis
  150. Vector3 zAxis = mRotation.rotate(Vector3::UNIT_Z);
  151. rotate(zAxis, angle);
  152. }
  153. void SceneObject::yaw(const Radian& angle)
  154. {
  155. Vector3 yAxis = mRotation.rotate(Vector3::UNIT_Y);
  156. rotate(yAxis, angle);
  157. }
  158. void SceneObject::pitch(const Radian& angle)
  159. {
  160. // Rotate around local X axis
  161. Vector3 xAxis = mRotation.rotate(Vector3::UNIT_X);
  162. rotate(xAxis, angle);
  163. }
  164. void SceneObject::setForward(const Vector3& forwardDir)
  165. {
  166. if (forwardDir == Vector3::ZERO)
  167. return;
  168. Vector3 nrmForwardDir = Vector3::normalize(forwardDir);
  169. Vector3 currentForwardDir = getForward();
  170. const Quaternion& currentRotation = getWorldRotation();
  171. Quaternion targetRotation;
  172. if ((nrmForwardDir+currentForwardDir).squaredLength() < 0.00005f)
  173. {
  174. // Oops, a 180 degree turn (infinite possible rotation axes)
  175. // Default to yaw i.e. use current UP
  176. targetRotation = Quaternion(-currentRotation.y, -currentRotation.z, currentRotation.w, currentRotation.x);
  177. }
  178. else
  179. {
  180. // Derive shortest arc to new direction
  181. Quaternion rotQuat = Quaternion::getRotationFromTo(currentForwardDir, nrmForwardDir);
  182. targetRotation = rotQuat * currentRotation;
  183. }
  184. setRotation(targetRotation);
  185. }
  186. void SceneObject::updateTransformsIfDirty()
  187. {
  188. if (!mIsCachedLocalTfrmUpToDate)
  189. updateLocalTfrm();
  190. if (!mIsCachedWorldTfrmUpToDate)
  191. updateWorldTfrm();
  192. }
  193. void SceneObject::markTfrmDirty() const
  194. {
  195. mIsCachedLocalTfrmUpToDate = false;
  196. mIsCachedWorldTfrmUpToDate = false;
  197. mIsCoreDirtyFlags = 0xFFFFFFFF;
  198. for(auto iter = mChildren.begin(); iter != mChildren.end(); ++iter)
  199. {
  200. (*iter)->markTfrmDirty();
  201. }
  202. }
  203. void SceneObject::updateWorldTfrm() const
  204. {
  205. if(mParent != nullptr)
  206. {
  207. mCachedWorldTfrm = getLocalTfrm() * mParent->getWorldTfrm();
  208. // Update orientation
  209. const Quaternion& parentOrientation = mParent->getWorldRotation();
  210. mWorldRotation = parentOrientation * mRotation;
  211. // Update scale
  212. const Vector3& parentScale = mParent->getWorldScale();
  213. // Scale own position by parent scale, NB just combine
  214. // as equivalent axes, no shearing
  215. mWorldScale = parentScale * mScale;
  216. // Change position vector based on parent's orientation & scale
  217. mWorldPosition = parentOrientation.rotate(parentScale * mPosition);
  218. // Add altered position vector to parents
  219. mWorldPosition += mParent->getWorldPosition();
  220. }
  221. else
  222. {
  223. mCachedWorldTfrm = getLocalTfrm();
  224. mWorldRotation = mRotation;
  225. mWorldPosition = mPosition;
  226. mWorldScale = mScale;
  227. }
  228. mIsCachedWorldTfrmUpToDate = true;
  229. }
  230. void SceneObject::updateLocalTfrm() const
  231. {
  232. mCachedLocalTfrm.setTRS(mPosition, mRotation, mScale);
  233. mIsCachedLocalTfrmUpToDate = true;
  234. }
  235. /************************************************************************/
  236. /* Hierarchy */
  237. /************************************************************************/
  238. void SceneObject::setParent(const HSceneObject& parent)
  239. {
  240. if(parent.isDestroyed())
  241. {
  242. BS_EXCEPT(InternalErrorException,
  243. "Trying to assign a SceneObject parent that is destroyed.");
  244. }
  245. if(mParent == nullptr || mParent != parent)
  246. {
  247. if(mParent != nullptr)
  248. mParent->removeChild(mThisHandle);
  249. if(parent != nullptr)
  250. parent->addChild(mThisHandle);
  251. mParent = parent;
  252. markTfrmDirty();
  253. }
  254. }
  255. HSceneObject SceneObject::getChild(UINT32 idx) const
  256. {
  257. if(idx < 0 || idx >= mChildren.size())
  258. {
  259. BS_EXCEPT(InternalErrorException, "Child index out of range.");
  260. }
  261. return mChildren[idx];
  262. }
  263. int SceneObject::indexOfChild(const HSceneObject& child) const
  264. {
  265. for(int i = 0; i < (int)mChildren.size(); i++)
  266. {
  267. if(mChildren[i] == child)
  268. return i;
  269. }
  270. return -1;
  271. }
  272. void SceneObject::addChild(const HSceneObject& object)
  273. {
  274. mChildren.push_back(object);
  275. }
  276. void SceneObject::removeChild(const HSceneObject& object)
  277. {
  278. auto result = find(mChildren.begin(), mChildren.end(), object);
  279. if(result != mChildren.end())
  280. mChildren.erase(result);
  281. else
  282. {
  283. BS_EXCEPT(InternalErrorException,
  284. "Trying to remove a child but it's not a child of the transform.");
  285. }
  286. }
  287. HSceneObject SceneObject::clone()
  288. {
  289. UINT32 bufferSize = 0;
  290. MemorySerializer serializer;
  291. UINT8* buffer = serializer.encode(this, bufferSize, &bs_alloc);
  292. GameObjectManager::instance().startDeserialization();
  293. std::shared_ptr<SceneObject> cloneObj = std::static_pointer_cast<SceneObject>(serializer.decode(buffer, bufferSize));
  294. bs_free(buffer);
  295. GameObjectManager::instance().endDeserialization();
  296. return cloneObj->mThisHandle;
  297. }
  298. HComponent SceneObject::getComponent(UINT32 typeId) const
  299. {
  300. for(auto iter = mComponents.begin(); iter != mComponents.end(); ++iter)
  301. {
  302. if((*iter)->getRTTI()->getRTTIId() == typeId)
  303. return *iter;
  304. }
  305. return HComponent();
  306. }
  307. void SceneObject::destroyComponent(const HComponent& component)
  308. {
  309. if(component == nullptr)
  310. {
  311. LOGDBG("Trying to remove a null component");
  312. return;
  313. }
  314. auto iter = std::find(mComponents.begin(), mComponents.end(), component);
  315. if(iter != mComponents.end())
  316. {
  317. gSceneManager().notifyComponentRemoved((*iter));
  318. GameObjectManager::instance().unregisterObject(component);
  319. (*iter)->onDestroyed();
  320. (*iter).destroy();
  321. mComponents.erase(iter);
  322. }
  323. else
  324. LOGDBG("Trying to remove a component that doesn't exist on this SceneObject.");
  325. }
  326. void SceneObject::destroyComponent(Component* component)
  327. {
  328. auto iterFind = std::find_if(mComponents.begin(), mComponents.end(),
  329. [component](const HComponent& x)
  330. {
  331. if(x.isDestroyed())
  332. return false;
  333. return x._getHandleData()->mPtr->object.get() == component; }
  334. );
  335. if(iterFind != mComponents.end())
  336. {
  337. destroyComponent(*iterFind);
  338. }
  339. }
  340. void SceneObject::addComponentInternal(const std::shared_ptr<Component> component)
  341. {
  342. GameObjectHandle<Component> newComponent = GameObjectHandle<Component>(component);
  343. newComponent->mParent = mThisHandle;
  344. mComponents.push_back(newComponent);
  345. gSceneManager().notifyComponentAdded(newComponent);
  346. }
  347. RTTITypeBase* SceneObject::getRTTIStatic()
  348. {
  349. return SceneObjectRTTI::instance();
  350. }
  351. RTTITypeBase* SceneObject::getRTTI() const
  352. {
  353. return SceneObject::getRTTIStatic();
  354. }
  355. }