Scene.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678
  1. #include "Base.h"
  2. #include "AudioListener.h"
  3. #include "Scene.h"
  4. #include "SceneLoader.h"
  5. #include "MeshSkin.h"
  6. #include "Joint.h"
  7. #include "Terrain.h"
  8. #include "Bundle.h"
  9. namespace gameplay
  10. {
  11. // Global list of active scenes
  12. static std::vector<Scene*> __sceneList;
  13. static inline char lowercase(char c)
  14. {
  15. if (c >= 'A' && c <='Z')
  16. {
  17. c |= 0x20;
  18. }
  19. return c;
  20. }
  21. // Returns true if 'str' ends with 'suffix'; false otherwise.
  22. static bool endsWith(const char* str, const char* suffix, bool ignoreCase)
  23. {
  24. if (str == NULL || suffix == NULL)
  25. return false;
  26. size_t length = strlen(str);
  27. size_t suffixLength = strlen(suffix);
  28. if (suffixLength > length)
  29. {
  30. return false;
  31. }
  32. size_t offset = length - suffixLength;
  33. const char* p = str + offset;
  34. while (*p != '\0' && *suffix != '\0')
  35. {
  36. if (ignoreCase)
  37. {
  38. if (lowercase(*p) != lowercase(*suffix))
  39. {
  40. return false;
  41. }
  42. }
  43. else if (*p != *suffix)
  44. {
  45. return false;
  46. }
  47. ++p;
  48. ++suffix;
  49. }
  50. return true;
  51. }
  52. Scene::Scene(const char* id)
  53. : _id(id ? id : ""), _activeCamera(NULL), _firstNode(NULL), _lastNode(NULL), _nodeCount(0),
  54. _lightColor(1,1,1), _lightDirection(0,-1,0), _bindAudioListenerToCamera(true), _debugBatch(NULL)
  55. {
  56. __sceneList.push_back(this);
  57. }
  58. Scene::~Scene()
  59. {
  60. // Unbind our active camera from the audio listener
  61. if (_activeCamera)
  62. {
  63. AudioListener* audioListener = AudioListener::getInstance();
  64. if (audioListener && (audioListener->getCamera() == _activeCamera))
  65. {
  66. audioListener->setCamera(NULL);
  67. }
  68. SAFE_RELEASE(_activeCamera);
  69. }
  70. // Remove all nodes from the scene
  71. removeAllNodes();
  72. SAFE_DELETE(_debugBatch);
  73. // Remove the scene from global list
  74. std::vector<Scene*>::iterator itr = std::find(__sceneList.begin(), __sceneList.end(), this);
  75. if (itr != __sceneList.end())
  76. __sceneList.erase(itr);
  77. }
  78. Scene* Scene::create(const char* id)
  79. {
  80. return new Scene(id);
  81. }
  82. Scene* Scene::load(const char* filePath)
  83. {
  84. if (endsWith(filePath, ".gpb", true))
  85. {
  86. Scene* scene = NULL;
  87. Bundle* bundle = Bundle::create(filePath);
  88. if (bundle)
  89. {
  90. scene = bundle->loadScene();
  91. SAFE_RELEASE(bundle);
  92. }
  93. return scene;
  94. }
  95. return SceneLoader::load(filePath);
  96. }
  97. Scene* Scene::getScene(const char* id)
  98. {
  99. if (id == NULL)
  100. return __sceneList.size() ? __sceneList[0] : NULL;
  101. for (size_t i = 0, count = __sceneList.size(); i < count; ++i)
  102. {
  103. if (__sceneList[i]->_id == id)
  104. return __sceneList[i];
  105. }
  106. return NULL;
  107. }
  108. const char* Scene::getId() const
  109. {
  110. return _id.c_str();
  111. }
  112. void Scene::setId(const char* id)
  113. {
  114. _id = id ? id : "";
  115. }
  116. Node* Scene::findNode(const char* id, bool recursive, bool exactMatch) const
  117. {
  118. GP_ASSERT(id);
  119. // Search immediate children first.
  120. for (Node* child = getFirstNode(); child != NULL; child = child->getNextSibling())
  121. {
  122. // Does this child's ID match?
  123. if ((exactMatch && child->_id == id) || (!exactMatch && child->_id.find(id) == 0))
  124. {
  125. return child;
  126. }
  127. }
  128. // Recurse.
  129. if (recursive)
  130. {
  131. for (Node* child = getFirstNode(); child != NULL; child = child->getNextSibling())
  132. {
  133. Node* match = child->findNode(id, true, exactMatch);
  134. if (match)
  135. {
  136. return match;
  137. }
  138. }
  139. }
  140. return NULL;
  141. }
  142. unsigned int Scene::findNodes(const char* id, std::vector<Node*>& nodes, bool recursive, bool exactMatch) const
  143. {
  144. GP_ASSERT(id);
  145. unsigned int count = 0;
  146. // Search immediate children first.
  147. for (Node* child = getFirstNode(); child != NULL; child = child->getNextSibling())
  148. {
  149. // Does this child's ID match?
  150. if ((exactMatch && child->_id == id) || (!exactMatch && child->_id.find(id) == 0))
  151. {
  152. nodes.push_back(child);
  153. ++count;
  154. }
  155. }
  156. // Recurse.
  157. if (recursive)
  158. {
  159. for (Node* child = getFirstNode(); child != NULL; child = child->getNextSibling())
  160. {
  161. count += child->findNodes(id, nodes, true, exactMatch);
  162. }
  163. }
  164. return count;
  165. }
  166. void Scene::visitNode(Node* node, const char* visitMethod)
  167. {
  168. ScriptController* sc = Game::getInstance()->getScriptController();
  169. // Invoke the visit method for this node.
  170. if (!sc->executeFunction<bool>(visitMethod, "<Node>", node))
  171. return;
  172. // If this node has a model with a mesh skin, visit the joint hierarchy within it
  173. // since we don't add joint hierarcies directly to the scene. If joints are never
  174. // visited, it's possible that nodes embedded within the joint hierarchy that contain
  175. // models will never get visited (and therefore never get drawn).
  176. if (node->_model && node->_model->_skin && node->_model->_skin->_rootNode)
  177. {
  178. visitNode(node->_model->_skin->_rootNode, visitMethod);
  179. }
  180. // Recurse for all children.
  181. for (Node* child = node->getFirstChild(); child != NULL; child = child->getNextSibling())
  182. {
  183. visitNode(child, visitMethod);
  184. }
  185. }
  186. Node* Scene::addNode(const char* id)
  187. {
  188. Node* node = Node::create(id);
  189. GP_ASSERT(node);
  190. addNode(node);
  191. // Call release to decrement the ref count to 1 before returning.
  192. node->release();
  193. return node;
  194. }
  195. void Scene::addNode(Node* node)
  196. {
  197. GP_ASSERT(node);
  198. if (node->_scene == this)
  199. {
  200. // The node is already a member of this scene.
  201. return;
  202. }
  203. node->addRef();
  204. // If the node is part of another scene, remove it.
  205. if (node->_scene && node->_scene != this)
  206. {
  207. node->_scene->removeNode(node);
  208. }
  209. // If the node is part of another node hierarchy, remove it.
  210. if (node->getParent())
  211. {
  212. node->getParent()->removeChild(node);
  213. }
  214. // Link the new node into our list.
  215. if (_lastNode)
  216. {
  217. _lastNode->_nextSibling = node;
  218. node->_prevSibling = _lastNode;
  219. _lastNode = node;
  220. }
  221. else
  222. {
  223. _firstNode = _lastNode = node;
  224. }
  225. node->_scene = this;
  226. ++_nodeCount;
  227. // If we don't have an active camera set, then check for one and set it.
  228. if (_activeCamera == NULL)
  229. {
  230. Camera* camera = node->getCamera();
  231. if (camera)
  232. {
  233. setActiveCamera(camera);
  234. }
  235. }
  236. }
  237. void Scene::removeNode(Node* node)
  238. {
  239. GP_ASSERT(node);
  240. if (node->_scene != this)
  241. return;
  242. if (node == _firstNode)
  243. {
  244. _firstNode = node->_nextSibling;
  245. }
  246. if (node == _lastNode)
  247. {
  248. _lastNode = node->_prevSibling;
  249. }
  250. node->remove();
  251. node->_scene = NULL;
  252. SAFE_RELEASE(node);
  253. --_nodeCount;
  254. }
  255. void Scene::removeAllNodes()
  256. {
  257. while (_lastNode)
  258. {
  259. removeNode(_lastNode);
  260. }
  261. }
  262. unsigned int Scene::getNodeCount() const
  263. {
  264. return _nodeCount;
  265. }
  266. Node* Scene::getFirstNode() const
  267. {
  268. return _firstNode;
  269. }
  270. Camera* Scene::getActiveCamera() const
  271. {
  272. return _activeCamera;
  273. }
  274. void Scene::setActiveCamera(Camera* camera)
  275. {
  276. // Make sure we don't release the camera if the same camera is set twice.
  277. if (_activeCamera != camera)
  278. {
  279. AudioListener* audioListener = AudioListener::getInstance();
  280. if (_activeCamera)
  281. {
  282. // Unbind the active camera from the audio listener
  283. if (audioListener && (audioListener->getCamera() == _activeCamera))
  284. {
  285. audioListener->setCamera(NULL);
  286. }
  287. SAFE_RELEASE(_activeCamera);
  288. }
  289. _activeCamera = camera;
  290. if (_activeCamera)
  291. {
  292. _activeCamera->addRef();
  293. if (audioListener && _bindAudioListenerToCamera)
  294. {
  295. audioListener->setCamera(_activeCamera);
  296. }
  297. }
  298. }
  299. }
  300. void Scene::bindAudioListenerToCamera(bool bind)
  301. {
  302. if (_bindAudioListenerToCamera != bind)
  303. {
  304. _bindAudioListenerToCamera = bind;
  305. if (AudioListener::getInstance())
  306. {
  307. AudioListener::getInstance()->setCamera(bind ? _activeCamera : NULL);
  308. }
  309. }
  310. }
  311. const Vector3& Scene::getAmbientColor() const
  312. {
  313. return _ambientColor;
  314. }
  315. void Scene::setAmbientColor(float red, float green, float blue)
  316. {
  317. _ambientColor.set(red, green, blue);
  318. }
  319. const Vector3& Scene::getLightColor() const
  320. {
  321. return _lightColor;
  322. }
  323. void Scene::setLightColor(float red, float green, float blue)
  324. {
  325. _lightColor.set(red, green, blue);
  326. }
  327. const Vector3& Scene::getLightDirection() const
  328. {
  329. return _lightDirection;
  330. }
  331. void Scene::setLightDirection(const Vector3& direction)
  332. {
  333. _lightDirection = direction;
  334. }
  335. static Material* createDebugMaterial()
  336. {
  337. // Vertex shader for drawing colored lines.
  338. const char* vs_str =
  339. {
  340. "uniform mat4 u_viewProjectionMatrix;\n"
  341. "attribute vec4 a_position;\n"
  342. "attribute vec4 a_color;\n"
  343. "varying vec4 v_color;\n"
  344. "void main(void) {\n"
  345. " v_color = a_color;\n"
  346. " gl_Position = u_viewProjectionMatrix * a_position;\n"
  347. "}"
  348. };
  349. // Fragment shader for drawing colored lines.
  350. const char* fs_str =
  351. {
  352. #ifdef OPENGL_ES
  353. "precision highp float;\n"
  354. #endif
  355. "varying vec4 v_color;\n"
  356. "void main(void) {\n"
  357. " gl_FragColor = v_color;\n"
  358. "}"
  359. };
  360. Effect* effect = Effect::createFromSource(vs_str, fs_str);
  361. Material* material = Material::create(effect);
  362. GP_ASSERT(material && material->getStateBlock());
  363. material->getStateBlock()->setDepthTest(true);
  364. SAFE_RELEASE(effect);
  365. return material;
  366. }
  367. /**
  368. * DebugVertex structure.
  369. * @script{ignore}
  370. */
  371. struct DebugVertex
  372. {
  373. /**
  374. * The x coordinate of the vertex.
  375. */
  376. float x;
  377. /**
  378. * The y coordinate of the vertex.
  379. */
  380. float y;
  381. /**
  382. * The z coordinate of the vertex.
  383. */
  384. float z;
  385. /**
  386. * The red color component of the vertex.
  387. */
  388. float r;
  389. /**
  390. * The green color component of the vertex.
  391. */
  392. float g;
  393. /**
  394. * The blue color component of the vertex.
  395. */
  396. float b;
  397. /**
  398. * The alpha component of the vertex.
  399. */
  400. float a;
  401. };
  402. static void drawDebugLine(MeshBatch* batch, const Vector3& point1, const Vector3& point2, const Vector3& color)
  403. {
  404. GP_ASSERT(batch);
  405. static DebugVertex verts[2];
  406. verts[0].x = point1.x;
  407. verts[0].y = point1.y;
  408. verts[0].z = point1.z;
  409. verts[0].r = color.x;
  410. verts[0].g = color.y;
  411. verts[0].b = color.z;
  412. verts[0].a = 1.0f;
  413. verts[1].x = point2.x;
  414. verts[1].y = point2.y;
  415. verts[1].z = point2.z;
  416. verts[1].r = color.x;
  417. verts[1].g = color.y;
  418. verts[1].b = color.z;
  419. verts[1].a = 1.0f;
  420. batch->add(verts, 2);
  421. }
  422. #define DEBUG_BOX_COLOR Vector3(0, 1, 0)
  423. #define DEBUG_SPHERE_COLOR Vector3(0, 1, 0)
  424. static void drawDebugBox(MeshBatch* batch, const BoundingBox& box, const Matrix& matrix)
  425. {
  426. if (box.isEmpty())
  427. return;
  428. // Transform box into world space (since we only store local boxes on mesh)
  429. BoundingBox worldSpaceBox(box);
  430. worldSpaceBox.transform(matrix);
  431. // Get box corners
  432. static Vector3 corners[8];
  433. worldSpaceBox.getCorners(corners);
  434. // Draw box lines
  435. drawDebugLine(batch, corners[0], corners[1], DEBUG_BOX_COLOR);
  436. drawDebugLine(batch, corners[1], corners[2], DEBUG_BOX_COLOR);
  437. drawDebugLine(batch, corners[2], corners[3], DEBUG_BOX_COLOR);
  438. drawDebugLine(batch, corners[3], corners[0], DEBUG_BOX_COLOR);
  439. drawDebugLine(batch, corners[4], corners[5], DEBUG_BOX_COLOR);
  440. drawDebugLine(batch, corners[5], corners[6], DEBUG_BOX_COLOR);
  441. drawDebugLine(batch, corners[6], corners[7], DEBUG_BOX_COLOR);
  442. drawDebugLine(batch, corners[7], corners[4], DEBUG_BOX_COLOR);
  443. drawDebugLine(batch, corners[0], corners[7], DEBUG_BOX_COLOR);
  444. drawDebugLine(batch, corners[1], corners[6], DEBUG_BOX_COLOR);
  445. drawDebugLine(batch, corners[2], corners[5], DEBUG_BOX_COLOR);
  446. drawDebugLine(batch, corners[3], corners[4], DEBUG_BOX_COLOR);
  447. }
  448. static void drawDebugSphere(MeshBatch* batch, const BoundingSphere& sphere)
  449. {
  450. if (sphere.isEmpty())
  451. return;
  452. // Draw three rings for the sphere (one for the x, y and z axes)
  453. Vector3 pos1, pos2;
  454. float step = MATH_PI * 0.2f;
  455. float max = MATH_PIX2 + step;
  456. // X ring
  457. for (float r = 0.0f; r < max; r += step)
  458. {
  459. pos2.x = sphere.center.x;
  460. pos2.y = sphere.center.y + std::cos(r) * sphere.radius;
  461. pos2.z = sphere.center.z + std::sin(r) * sphere.radius;
  462. if (r > 0)
  463. drawDebugLine(batch, pos1, pos2, DEBUG_SPHERE_COLOR);
  464. pos1 = pos2;
  465. }
  466. // Y ring
  467. for (float r = 0.0f; r < max; r += step)
  468. {
  469. pos2.x = sphere.center.x + std::cos(r) * sphere.radius;
  470. pos2.y = sphere.center.y;
  471. pos2.z = sphere.center.z + std::sin(r) * sphere.radius;
  472. if (r > 0)
  473. drawDebugLine(batch, pos1, pos2, DEBUG_SPHERE_COLOR);
  474. pos1 = pos2;
  475. }
  476. // Z ring
  477. for (float r = 0.0f; r < max; r += step)
  478. {
  479. pos2.x = sphere.center.x + std::cos(r) * sphere.radius;
  480. pos2.y = sphere.center.y + std::sin(r) * sphere.radius;
  481. pos2.z = sphere.center.z;
  482. if (r > 0)
  483. drawDebugLine(batch, pos1, pos2, DEBUG_SPHERE_COLOR);
  484. pos1 = pos2;
  485. }
  486. }
  487. static void drawDebugNode(Scene* scene, MeshBatch* batch, Node* node, unsigned int debugFlags)
  488. {
  489. GP_ASSERT(node);
  490. // If the node isn't visible, don't draw its bounds
  491. Camera* camera = scene->getActiveCamera();
  492. if (camera)
  493. {
  494. const BoundingSphere& sphere = node->getBoundingSphere();
  495. if (!sphere.isEmpty() && !camera->getFrustum().intersects(sphere))
  496. return;
  497. }
  498. if (debugFlags & Scene::DEBUG_BOXES)
  499. {
  500. if (node->getModel())
  501. {
  502. Model* model = node->getModel();
  503. GP_ASSERT(model->getMesh());
  504. MeshSkin* skin = model->getSkin();
  505. if (skin && skin->getRootJoint() && skin->getRootJoint()->getParent())
  506. {
  507. // For skinned meshes that have a parent node to the skin's root joint,
  508. // we need to transform the bounding volume by that parent node's transform
  509. // as well to get the full skinned bounding volume.
  510. drawDebugBox(batch, model->getMesh()->getBoundingBox(), node->getWorldMatrix() * skin->getRootJoint()->getParent()->getWorldMatrix());
  511. }
  512. else
  513. {
  514. drawDebugBox(batch, model->getMesh()->getBoundingBox(), node->getWorldMatrix());
  515. }
  516. }
  517. if (node->getTerrain())
  518. {
  519. drawDebugBox(batch, node->getTerrain()->getBoundingBox(), node->getWorldMatrix());
  520. }
  521. }
  522. if (debugFlags & Scene::DEBUG_SPHERES)
  523. {
  524. drawDebugSphere(batch, node->getBoundingSphere());
  525. }
  526. for (Node* child = node->getFirstChild(); child != NULL; child = child->getNextSibling())
  527. {
  528. drawDebugNode(scene, batch, child, debugFlags);
  529. }
  530. }
  531. void Scene::drawDebug(unsigned int debugFlags)
  532. {
  533. if (_debugBatch == NULL)
  534. {
  535. Material* material = createDebugMaterial();
  536. VertexFormat::Element elements[] =
  537. {
  538. VertexFormat::Element(VertexFormat::POSITION, 3),
  539. VertexFormat::Element(VertexFormat::COLOR, 4)
  540. };
  541. _debugBatch = MeshBatch::create(VertexFormat(elements, 2), Mesh::LINES, material, false);
  542. SAFE_RELEASE(material);
  543. }
  544. _debugBatch->start();
  545. for (Node* node = _firstNode; node != NULL; node = node->_nextSibling)
  546. {
  547. drawDebugNode(this, _debugBatch, node, debugFlags);
  548. }
  549. _debugBatch->finish();
  550. if (_activeCamera)
  551. {
  552. GP_ASSERT(_debugBatch->getMaterial());
  553. GP_ASSERT(_debugBatch->getMaterial()->getParameter("u_viewProjectionMatrix"));
  554. _debugBatch->getMaterial()->getParameter("u_viewProjectionMatrix")->setValue(_activeCamera->getViewProjectionMatrix());
  555. }
  556. _debugBatch->draw();
  557. }
  558. }