BsSceneObject.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #include "Scene/BsSceneObject.h"
  4. #include "Scene/BsComponent.h"
  5. #include "Scene/BsSceneManager.h"
  6. #include "Error/BsException.h"
  7. #include "Debug/BsDebug.h"
  8. #include "RTTI/BsSceneObjectRTTI.h"
  9. #include "Serialization/BsMemorySerializer.h"
  10. #include "Scene/BsGameObjectManager.h"
  11. #include "Scene/BsPrefabUtility.h"
  12. #include "Math/BsMatrix3.h"
  13. #include "BsCoreApplication.h"
  14. namespace bs
  15. {
  16. SceneObject::SceneObject(const String& name, UINT32 flags)
  17. : GameObject(), mPrefabHash(0), mFlags(flags), mPosition(Vector3::ZERO), mRotation(Quaternion::IDENTITY)
  18. , mScale(Vector3::ONE), mWorldPosition(Vector3::ZERO), mWorldRotation(Quaternion::IDENTITY)
  19. , mWorldScale(Vector3::ONE), mCachedLocalTfrm(Matrix4::IDENTITY), mCachedWorldTfrm(Matrix4::IDENTITY)
  20. , mDirtyFlags(0xFFFFFFFF), mDirtyHash(0), mActiveSelf(true), mActiveHierarchy(true)
  21. , mMobility(ObjectMobility::Movable)
  22. {
  23. setName(name);
  24. }
  25. SceneObject::~SceneObject()
  26. {
  27. if(!mThisHandle.isDestroyed())
  28. {
  29. LOGWRN("Object is being deleted without being destroyed first? " + mName);
  30. destroyInternal(mThisHandle, true);
  31. }
  32. }
  33. HSceneObject SceneObject::create(const String& name, UINT32 flags)
  34. {
  35. HSceneObject newObject = createInternal(name, flags);
  36. if (newObject->isInstantiated())
  37. gSceneManager().registerNewSO(newObject);
  38. return newObject;
  39. }
  40. HSceneObject SceneObject::createInternal(const String& name, UINT32 flags)
  41. {
  42. SPtr<SceneObject> sceneObjectPtr = SPtr<SceneObject>(new (bs_alloc<SceneObject>()) SceneObject(name, flags),
  43. &bs_delete<SceneObject>, StdAlloc<SceneObject>());
  44. HSceneObject sceneObject = GameObjectManager::instance().registerObject(sceneObjectPtr);
  45. sceneObject->mThisHandle = sceneObject;
  46. return sceneObject;
  47. }
  48. HSceneObject SceneObject::createInternal(const SPtr<SceneObject>& soPtr, UINT64 originalId)
  49. {
  50. HSceneObject sceneObject = GameObjectManager::instance().registerObject(soPtr, originalId);
  51. sceneObject->mThisHandle = sceneObject;
  52. return sceneObject;
  53. }
  54. void SceneObject::destroy(bool immediate)
  55. {
  56. // Parent is our owner, so when his reference to us is removed, delete might be called.
  57. // So make sure this is the last thing we do.
  58. if(mParent != nullptr)
  59. {
  60. if(!mParent.isDestroyed())
  61. mParent->removeChild(mThisHandle);
  62. mParent = nullptr;
  63. }
  64. destroyInternal(mThisHandle, immediate);
  65. }
  66. void SceneObject::destroyInternal(GameObjectHandleBase& handle, bool immediate)
  67. {
  68. if (immediate)
  69. {
  70. for (auto iter = mChildren.begin(); iter != mChildren.end(); ++iter)
  71. (*iter)->destroyInternal(*iter, true);
  72. mChildren.clear();
  73. // It's important to remove the elements from the array as soon as they're destroyed, as OnDestroy callbacks
  74. // for components might query the SO's components, and we want to only return live ones
  75. while (!mComponents.empty())
  76. {
  77. HComponent component = mComponents.back();
  78. component->_setIsDestroyed();
  79. if (isInstantiated())
  80. gSceneManager()._notifyComponentDestroyed(component);
  81. component->destroyInternal(component, true);
  82. mComponents.erase(mComponents.end() - 1);
  83. }
  84. GameObjectManager::instance().unregisterObject(handle);
  85. }
  86. else
  87. GameObjectManager::instance().queueForDestroy(handle);
  88. }
  89. void SceneObject::_setInstanceData(GameObjectInstanceDataPtr& other)
  90. {
  91. GameObject::_setInstanceData(other);
  92. // Instance data changed, so make sure to refresh the handles to reflect that
  93. SPtr<SceneObject> thisPtr = mThisHandle.getInternalPtr();
  94. mThisHandle._setHandleData(thisPtr);
  95. }
  96. String SceneObject::getPrefabLink(bool onlyDirect) const
  97. {
  98. const SceneObject* curObj = this;
  99. while (curObj != nullptr)
  100. {
  101. if (!curObj->mPrefabLinkUUID.empty())
  102. return curObj->mPrefabLinkUUID;
  103. if (curObj->mParent != nullptr && !onlyDirect)
  104. curObj = curObj->mParent.get();
  105. else
  106. curObj = nullptr;
  107. }
  108. return "";
  109. }
  110. HSceneObject SceneObject::getPrefabParent() const
  111. {
  112. HSceneObject curObj = mThisHandle;
  113. while (curObj != nullptr)
  114. {
  115. if (!curObj->mPrefabLinkUUID.empty())
  116. return curObj;
  117. if (curObj->mParent != nullptr)
  118. curObj = curObj->mParent;
  119. else
  120. curObj = nullptr;
  121. }
  122. return curObj;
  123. }
  124. void SceneObject::breakPrefabLink()
  125. {
  126. SceneObject* rootObj = this;
  127. while (rootObj != nullptr)
  128. {
  129. if (!rootObj->mPrefabLinkUUID.empty())
  130. break;
  131. if (rootObj->mParent != nullptr)
  132. rootObj = rootObj->mParent.get();
  133. else
  134. rootObj = nullptr;
  135. }
  136. if (rootObj != nullptr)
  137. {
  138. rootObj->mPrefabLinkUUID = "";
  139. rootObj->mPrefabDiff = nullptr;
  140. PrefabUtility::clearPrefabIds(rootObj->getHandle(), true, false);
  141. }
  142. }
  143. bool SceneObject::hasFlag(UINT32 flag) const
  144. {
  145. return (mFlags & flag) != 0;
  146. }
  147. void SceneObject::_setFlags(UINT32 flags)
  148. {
  149. mFlags |= flags;
  150. for (auto& child : mChildren)
  151. child->_setFlags(flags);
  152. }
  153. void SceneObject::_unsetFlags(UINT32 flags)
  154. {
  155. mFlags &= ~flags;
  156. for (auto& child : mChildren)
  157. child->_unsetFlags(flags);
  158. }
  159. void SceneObject::_instantiate(bool prefabOnly)
  160. {
  161. std::function<void(SceneObject*)> instantiateRecursive = [&](SceneObject* obj)
  162. {
  163. obj->mFlags &= ~SOF_DontInstantiate;
  164. if (obj->mParent == nullptr)
  165. gSceneManager().registerNewSO(obj->mThisHandle);
  166. for (auto& component : obj->mComponents)
  167. component->_instantiate();
  168. for (auto& child : obj->mChildren)
  169. {
  170. if(!prefabOnly || child->mPrefabLinkUUID.empty())
  171. instantiateRecursive(child.get());
  172. }
  173. };
  174. std::function<void(SceneObject*)> triggerEventsRecursive = [&](SceneObject* obj)
  175. {
  176. for (auto& component : obj->mComponents)
  177. gSceneManager()._notifyComponentCreated(component, obj->getActive());
  178. for (auto& child : obj->mChildren)
  179. {
  180. if (!prefabOnly || child->mPrefabLinkUUID.empty())
  181. triggerEventsRecursive(child.get());
  182. }
  183. };
  184. instantiateRecursive(this);
  185. triggerEventsRecursive(this);
  186. }
  187. /************************************************************************/
  188. /* Transform */
  189. /************************************************************************/
  190. void SceneObject::setPosition(const Vector3& position)
  191. {
  192. if (mMobility == ObjectMobility::Movable)
  193. {
  194. mPosition = position;
  195. notifyTransformChanged(TCF_Transform);
  196. }
  197. }
  198. void SceneObject::setRotation(const Quaternion& rotation)
  199. {
  200. if (mMobility == ObjectMobility::Movable)
  201. {
  202. mRotation = rotation;
  203. notifyTransformChanged(TCF_Transform);
  204. }
  205. }
  206. void SceneObject::setScale(const Vector3& scale)
  207. {
  208. if (mMobility == ObjectMobility::Movable)
  209. {
  210. mScale = scale;
  211. notifyTransformChanged(TCF_Transform);
  212. }
  213. }
  214. void SceneObject::setWorldPosition(const Vector3& position)
  215. {
  216. if(mMobility != ObjectMobility::Movable)
  217. return;
  218. if (mParent != nullptr)
  219. {
  220. Vector3 invScale = mParent->getWorldScale();
  221. if (invScale.x != 0) invScale.x = 1.0f / invScale.x;
  222. if (invScale.y != 0) invScale.y = 1.0f / invScale.y;
  223. if (invScale.z != 0) invScale.z = 1.0f / invScale.z;
  224. Quaternion invRotation = mParent->getWorldRotation().inverse();
  225. mPosition = invRotation.rotate(position - mParent->getWorldPosition()) * invScale;
  226. }
  227. else
  228. mPosition = position;
  229. notifyTransformChanged(TCF_Transform);
  230. }
  231. void SceneObject::setWorldRotation(const Quaternion& rotation)
  232. {
  233. if (mMobility != ObjectMobility::Movable)
  234. return;
  235. if (mParent != nullptr)
  236. {
  237. Quaternion invRotation = mParent->getWorldRotation().inverse();
  238. mRotation = invRotation * rotation;
  239. }
  240. else
  241. mRotation = rotation;
  242. notifyTransformChanged(TCF_Transform);
  243. }
  244. void SceneObject::setWorldScale(const Vector3& scale)
  245. {
  246. if (mMobility != ObjectMobility::Movable)
  247. return;
  248. if (mParent != nullptr)
  249. {
  250. Matrix3 rotScale;
  251. mParent->getWorldTfrm().extract3x3Matrix(rotScale);
  252. rotScale.inverse();
  253. Matrix3 scaleMat = Matrix3(Quaternion::IDENTITY, scale);
  254. scaleMat = rotScale * scaleMat;
  255. Quaternion rotation;
  256. Vector3 localScale;
  257. scaleMat.decomposition(rotation, localScale);
  258. mScale = localScale;
  259. }
  260. else
  261. mScale = scale;
  262. notifyTransformChanged(TCF_Transform);
  263. }
  264. const Vector3& SceneObject::getWorldPosition() const
  265. {
  266. if (!isCachedWorldTfrmUpToDate())
  267. updateWorldTfrm();
  268. return mWorldPosition;
  269. }
  270. const Quaternion& SceneObject::getWorldRotation() const
  271. {
  272. if (!isCachedWorldTfrmUpToDate())
  273. updateWorldTfrm();
  274. return mWorldRotation;
  275. }
  276. const Vector3& SceneObject::getWorldScale() const
  277. {
  278. if (!isCachedWorldTfrmUpToDate())
  279. updateWorldTfrm();
  280. return mWorldScale;
  281. }
  282. void SceneObject::lookAt(const Vector3& location, const Vector3& up)
  283. {
  284. Vector3 forward = location - getWorldPosition();
  285. Quaternion rotation = getWorldRotation();
  286. rotation.lookRotation(forward, up);
  287. setWorldRotation(rotation);
  288. }
  289. const Matrix4& SceneObject::getWorldTfrm() const
  290. {
  291. if (!isCachedWorldTfrmUpToDate())
  292. updateWorldTfrm();
  293. return mCachedWorldTfrm;
  294. }
  295. Matrix4 SceneObject::getInvWorldTfrm() const
  296. {
  297. if (!isCachedWorldTfrmUpToDate())
  298. updateWorldTfrm();
  299. Matrix4 worldToLocal = Matrix4::inverseTRS(mWorldPosition, mWorldRotation, mWorldScale);
  300. return worldToLocal;
  301. }
  302. const Matrix4& SceneObject::getLocalTfrm() const
  303. {
  304. if (!isCachedLocalTfrmUpToDate())
  305. updateLocalTfrm();
  306. return mCachedLocalTfrm;
  307. }
  308. void SceneObject::move(const Vector3& vec)
  309. {
  310. setPosition(mPosition + vec);
  311. }
  312. void SceneObject::moveRelative(const Vector3& vec)
  313. {
  314. // Transform the axes of the relative vector by camera's local axes
  315. Vector3 trans = mRotation.rotate(vec);
  316. setPosition(mPosition + trans);
  317. }
  318. void SceneObject::rotate(const Vector3& axis, const Radian& angle)
  319. {
  320. Quaternion q;
  321. q.fromAxisAngle(axis, angle);
  322. rotate(q);
  323. }
  324. void SceneObject::rotate(const Quaternion& q)
  325. {
  326. // Note the order of the mult, i.e. q comes after
  327. // Normalize the quat to avoid cumulative problems with precision
  328. Quaternion qnorm = q;
  329. qnorm.normalize();
  330. setRotation(qnorm * mRotation);
  331. }
  332. void SceneObject::roll(const Radian& angle)
  333. {
  334. // Rotate around local Z axis
  335. Vector3 zAxis = mRotation.rotate(Vector3::UNIT_Z);
  336. rotate(zAxis, angle);
  337. }
  338. void SceneObject::yaw(const Radian& angle)
  339. {
  340. Vector3 yAxis = mRotation.rotate(Vector3::UNIT_Y);
  341. rotate(yAxis, angle);
  342. }
  343. void SceneObject::pitch(const Radian& angle)
  344. {
  345. // Rotate around local X axis
  346. Vector3 xAxis = mRotation.rotate(Vector3::UNIT_X);
  347. rotate(xAxis, angle);
  348. }
  349. void SceneObject::setForward(const Vector3& forwardDir)
  350. {
  351. Quaternion currentRotation = getWorldRotation();
  352. currentRotation.lookRotation(forwardDir);
  353. setWorldRotation(currentRotation);
  354. }
  355. void SceneObject::updateTransformsIfDirty()
  356. {
  357. if (!isCachedLocalTfrmUpToDate())
  358. updateLocalTfrm();
  359. if (!isCachedWorldTfrmUpToDate())
  360. updateWorldTfrm();
  361. }
  362. void SceneObject::notifyTransformChanged(TransformChangedFlags flags) const
  363. {
  364. // If object is immovable, don't send transform changed events nor mark the transform dirty
  365. TransformChangedFlags componentFlags = flags;
  366. if (mMobility != ObjectMobility::Movable)
  367. componentFlags = (TransformChangedFlags)(componentFlags & ~TCF_Transform);
  368. else
  369. {
  370. mDirtyFlags |= DirtyFlags::LocalTfrmDirty | DirtyFlags::WorldTfrmDirty;
  371. mDirtyHash++;
  372. }
  373. // Only send component flags if we haven't removed them all
  374. if (componentFlags != 0)
  375. {
  376. for (auto& entry : mComponents)
  377. {
  378. if (entry->supportsNotify(flags))
  379. {
  380. bool alwaysRun = entry->hasFlag(ComponentFlag::AlwaysRun);
  381. if (alwaysRun || gSceneManager().isRunning())
  382. entry->onTransformChanged(componentFlags);
  383. }
  384. }
  385. }
  386. // Mobility flag is only relevant for this scene object
  387. flags = (TransformChangedFlags)(flags & ~TCF_Mobility);
  388. if (flags != 0)
  389. {
  390. for (auto& entry : mChildren)
  391. entry->notifyTransformChanged(flags);
  392. }
  393. }
  394. void SceneObject::updateWorldTfrm() const
  395. {
  396. // Don't allow movement from parent when not movable
  397. if (mParent != nullptr && mMobility == ObjectMobility::Movable)
  398. {
  399. // Update orientation
  400. const Quaternion& parentOrientation = mParent->getWorldRotation();
  401. mWorldRotation = parentOrientation * mRotation;
  402. // Update scale
  403. const Vector3& parentScale = mParent->getWorldScale();
  404. // Scale own position by parent scale, just combine
  405. // as equivalent axes, no shearing
  406. mWorldScale = parentScale * mScale;
  407. // Change position vector based on parent's orientation & scale
  408. mWorldPosition = parentOrientation.rotate(parentScale * mPosition);
  409. // Add altered position vector to parents
  410. mWorldPosition += mParent->getWorldPosition();
  411. mCachedWorldTfrm.setTRS(mWorldPosition, mWorldRotation, mWorldScale);
  412. }
  413. else
  414. {
  415. mWorldRotation = mRotation;
  416. mWorldPosition = mPosition;
  417. mWorldScale = mScale;
  418. mCachedWorldTfrm = getLocalTfrm();
  419. }
  420. mDirtyFlags &= ~DirtyFlags::WorldTfrmDirty;
  421. }
  422. void SceneObject::updateLocalTfrm() const
  423. {
  424. mCachedLocalTfrm.setTRS(mPosition, mRotation, mScale);
  425. mDirtyFlags &= ~DirtyFlags::LocalTfrmDirty;
  426. }
  427. /************************************************************************/
  428. /* Hierarchy */
  429. /************************************************************************/
  430. void SceneObject::setParent(const HSceneObject& parent, bool keepWorldTransform)
  431. {
  432. if (parent.isDestroyed())
  433. return;
  434. #if BS_EDITOR_BUILD
  435. String originalPrefab = getPrefabLink();
  436. #endif
  437. _setParent(parent, keepWorldTransform);
  438. #if BS_EDITOR_BUILD
  439. if (gCoreApplication().isEditor())
  440. {
  441. String newPrefab = getPrefabLink();
  442. if (originalPrefab != newPrefab)
  443. PrefabUtility::clearPrefabIds(mThisHandle);
  444. }
  445. #endif
  446. }
  447. void SceneObject::_setParent(const HSceneObject& parent, bool keepWorldTransform)
  448. {
  449. if (mThisHandle == parent)
  450. return;
  451. if (mParent == nullptr || mParent != parent)
  452. {
  453. Vector3 worldPos;
  454. Quaternion worldRot;
  455. Vector3 worldScale;
  456. if (keepWorldTransform)
  457. {
  458. // Make sure the object keeps its world coordinates
  459. worldPos = getWorldPosition();
  460. worldRot = getWorldRotation();
  461. worldScale = getWorldScale();
  462. }
  463. if (mParent != nullptr)
  464. mParent->removeChild(mThisHandle);
  465. if (parent != nullptr)
  466. parent->addChild(mThisHandle);
  467. mParent = parent;
  468. if (keepWorldTransform)
  469. {
  470. setWorldPosition(worldPos);
  471. setWorldRotation(worldRot);
  472. setWorldScale(worldScale);
  473. }
  474. notifyTransformChanged((TransformChangedFlags)(TCF_Parent | TCF_Transform));
  475. }
  476. }
  477. HSceneObject SceneObject::getChild(UINT32 idx) const
  478. {
  479. if(idx >= mChildren.size())
  480. {
  481. BS_EXCEPT(InternalErrorException, "Child index out of range.");
  482. }
  483. return mChildren[idx];
  484. }
  485. int SceneObject::indexOfChild(const HSceneObject& child) const
  486. {
  487. for(int i = 0; i < (int)mChildren.size(); i++)
  488. {
  489. if(mChildren[i] == child)
  490. return i;
  491. }
  492. return -1;
  493. }
  494. void SceneObject::addChild(const HSceneObject& object)
  495. {
  496. mChildren.push_back(object);
  497. object->_setFlags(mFlags);
  498. }
  499. void SceneObject::removeChild(const HSceneObject& object)
  500. {
  501. auto result = find(mChildren.begin(), mChildren.end(), object);
  502. if(result != mChildren.end())
  503. mChildren.erase(result);
  504. else
  505. {
  506. BS_EXCEPT(InternalErrorException,
  507. "Trying to remove a child but it's not a child of the transform.");
  508. }
  509. }
  510. HSceneObject SceneObject::findPath(const String& path) const
  511. {
  512. if (path.empty())
  513. return HSceneObject();
  514. String trimmedPath = path;
  515. StringUtil::trim(trimmedPath, "/");
  516. Vector<String> entries = StringUtil::split(trimmedPath, "/");
  517. // Find scene object referenced by the path
  518. HSceneObject so = getHandle();
  519. UINT32 pathIdx = 0;
  520. for (; pathIdx < (UINT32)entries.size(); pathIdx++)
  521. {
  522. String entry = entries[pathIdx];
  523. if (entry.empty())
  524. continue;
  525. // This character signifies not-a-scene-object. This is allowed to support
  526. // paths used by the scripting system (which can point to properties of
  527. // components on scene objects).
  528. if (entry[0] != '!')
  529. break;
  530. String childName = entry.substr(1, entry.size() - 1);
  531. so = so->findChild(childName);
  532. if (so == nullptr)
  533. break;
  534. }
  535. return so;
  536. }
  537. HSceneObject SceneObject::findChild(const String& name, bool recursive)
  538. {
  539. for (auto& child : mChildren)
  540. {
  541. if (child->getName() == name)
  542. return child;
  543. }
  544. if (recursive)
  545. {
  546. for (auto& child : mChildren)
  547. {
  548. HSceneObject foundObject = child->findChild(name, true);
  549. if (foundObject != nullptr)
  550. return foundObject;
  551. }
  552. }
  553. return HSceneObject();
  554. }
  555. Vector<HSceneObject> SceneObject::findChildren(const String& name, bool recursive)
  556. {
  557. std::function<void(const HSceneObject&, Vector<HSceneObject>&)> findChildrenInternal =
  558. [&](const HSceneObject& so, Vector<HSceneObject>& output)
  559. {
  560. for (auto& child : so->mChildren)
  561. {
  562. if (child->getName() == name)
  563. output.push_back(child);
  564. }
  565. if (recursive)
  566. {
  567. for (auto& child : so->mChildren)
  568. findChildrenInternal(child, output);
  569. }
  570. };
  571. Vector<HSceneObject> output;
  572. findChildrenInternal(mThisHandle, output);
  573. return output;
  574. }
  575. void SceneObject::setActive(bool active)
  576. {
  577. mActiveSelf = active;
  578. setActiveHierarchy(active);
  579. }
  580. void SceneObject::setActiveHierarchy(bool active, bool triggerEvents)
  581. {
  582. bool activeHierarchy = active && mActiveSelf;
  583. if (mActiveHierarchy != activeHierarchy)
  584. {
  585. mActiveHierarchy = activeHierarchy;
  586. if (triggerEvents)
  587. {
  588. if (activeHierarchy)
  589. {
  590. for (auto& component : mComponents)
  591. gSceneManager()._notifyComponentActivated(component, triggerEvents);
  592. }
  593. else
  594. {
  595. for (auto& component : mComponents)
  596. gSceneManager()._notifyComponentDeactivated(component, triggerEvents);
  597. }
  598. }
  599. }
  600. for (auto child : mChildren)
  601. {
  602. child->setActiveHierarchy(mActiveHierarchy, triggerEvents);
  603. }
  604. }
  605. bool SceneObject::getActive(bool self)
  606. {
  607. if (self)
  608. return mActiveSelf;
  609. else
  610. return mActiveHierarchy;
  611. }
  612. void SceneObject::setMobility(ObjectMobility mobility)
  613. {
  614. if(mMobility != mobility)
  615. {
  616. mMobility = mobility;
  617. // If mobility changed to movable, update both the mobility flag and transform, otherwise just mobility
  618. if (mMobility == ObjectMobility::Movable)
  619. notifyTransformChanged((TransformChangedFlags)(TCF_Transform | TCF_Mobility));
  620. else
  621. notifyTransformChanged(TCF_Mobility);
  622. }
  623. }
  624. HSceneObject SceneObject::clone(bool instantiate)
  625. {
  626. bool isInstantiated = !hasFlag(SOF_DontInstantiate);
  627. if (!instantiate)
  628. _setFlags(SOF_DontInstantiate);
  629. else
  630. _unsetFlags(SOF_DontInstantiate);
  631. UINT32 bufferSize = 0;
  632. MemorySerializer serializer;
  633. UINT8* buffer = serializer.encode(this, bufferSize, (void*(*)(UINT32))&bs_alloc);
  634. GameObjectManager::instance().setDeserializationMode(GODM_UseNewIds | GODM_RestoreExternal);
  635. SPtr<SceneObject> cloneObj = std::static_pointer_cast<SceneObject>(serializer.decode(buffer, bufferSize));
  636. bs_free(buffer);
  637. if(isInstantiated)
  638. _unsetFlags(SOF_DontInstantiate);
  639. else
  640. _setFlags(SOF_DontInstantiate);
  641. return cloneObj->mThisHandle;
  642. }
  643. HComponent SceneObject::getComponent(RTTITypeBase* type) const
  644. {
  645. for(auto& entry : mComponents)
  646. {
  647. if(entry->getRTTI()->isDerivedFrom(type))
  648. return entry;
  649. }
  650. return HComponent();
  651. }
  652. void SceneObject::destroyComponent(const HComponent component, bool immediate)
  653. {
  654. if(component == nullptr)
  655. {
  656. LOGDBG("Trying to remove a null component");
  657. return;
  658. }
  659. auto iter = std::find(mComponents.begin(), mComponents.end(), component);
  660. if(iter != mComponents.end())
  661. {
  662. (*iter)->_setIsDestroyed();
  663. if (isInstantiated())
  664. gSceneManager()._notifyComponentDestroyed(*iter);
  665. (*iter)->destroyInternal(*iter, immediate);
  666. mComponents.erase(iter);
  667. }
  668. else
  669. LOGDBG("Trying to remove a component that doesn't exist on this SceneObject.");
  670. }
  671. void SceneObject::destroyComponent(Component* component, bool immediate)
  672. {
  673. auto iterFind = std::find_if(mComponents.begin(), mComponents.end(),
  674. [component](const HComponent& x)
  675. {
  676. if(x.isDestroyed())
  677. return false;
  678. return x._getHandleData()->mPtr->object.get() == component; }
  679. );
  680. if(iterFind != mComponents.end())
  681. {
  682. destroyComponent(*iterFind, immediate);
  683. }
  684. }
  685. HComponent SceneObject::addComponent(UINT32 typeId)
  686. {
  687. SPtr<IReflectable> newObj = rtti_create(typeId);
  688. if(!rtti_is_subclass<Component>(newObj.get()))
  689. {
  690. LOGERR("Specified type is not a valid Component.");
  691. return HComponent();
  692. }
  693. SPtr<Component> componentPtr = std::static_pointer_cast<Component>(newObj);
  694. HComponent newComponent = GameObjectManager::instance().registerObject(componentPtr);
  695. newComponent->mParent = mThisHandle;
  696. addAndInitializeComponent(newComponent);
  697. return newComponent;
  698. }
  699. void SceneObject::addComponentInternal(const SPtr<Component> component)
  700. {
  701. GameObjectHandle<Component> newComponent = GameObjectManager::instance().getObject(component->getInstanceId());
  702. newComponent->mParent = mThisHandle;
  703. newComponent->mThisHandle = newComponent;
  704. mComponents.push_back(newComponent);
  705. }
  706. void SceneObject::addAndInitializeComponent(const HComponent& component)
  707. {
  708. component->mThisHandle = component;
  709. mComponents.push_back(component);
  710. if (isInstantiated())
  711. {
  712. component->_instantiate();
  713. gSceneManager()._notifyComponentCreated(component, getActive());
  714. }
  715. }
  716. void SceneObject::addAndInitializeComponent(const SPtr<Component> component)
  717. {
  718. GameObjectHandle<Component> newComponent = GameObjectManager::instance().getObject(component->getInstanceId());
  719. newComponent->mParent = mThisHandle;
  720. addAndInitializeComponent(newComponent);
  721. }
  722. RTTITypeBase* SceneObject::getRTTIStatic()
  723. {
  724. return SceneObjectRTTI::instance();
  725. }
  726. RTTITypeBase* SceneObject::getRTTI() const
  727. {
  728. return SceneObject::getRTTIStatic();
  729. }
  730. }