CCCamera.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  1. /****************************************************************************
  2. Copyright (c) 2014-2016 Chukong Technologies Inc.
  3. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
  4. http://www.cocos2d-x.org
  5. Permission is hereby granted, free of charge, to any person obtaining a copy
  6. of this software and associated documentation files (the "Software"), to deal
  7. in the Software without restriction, including without limitation the rights
  8. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. copies of the Software, and to permit persons to whom the Software is
  10. furnished to do so, subject to the following conditions:
  11. The above copyright notice and this permission notice shall be included in
  12. all copies or substantial portions of the Software.
  13. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. THE SOFTWARE.
  20. Code based GamePlay3D's Camera: http://gameplay3d.org
  21. ****************************************************************************/
  22. #include "2d/CCCamera.h"
  23. #include "2d/CCCameraBackgroundBrush.h"
  24. #include "base/CCDirector.h"
  25. #include "platform/CCGLView.h"
  26. #include "2d/CCScene.h"
  27. #include "renderer/CCRenderer.h"
  28. #include "renderer/CCQuadCommand.h"
  29. #include "renderer/CCGLProgramCache.h"
  30. #include "renderer/ccGLStateCache.h"
  31. #include "renderer/CCFrameBuffer.h"
  32. #include "renderer/CCRenderState.h"
  33. NS_CC_BEGIN
  34. Camera* Camera::_visitingCamera = nullptr;
  35. experimental::Viewport Camera::_defaultViewport;
  36. // start static methods
  37. Camera* Camera::create()
  38. {
  39. Camera* camera = new (std::nothrow) Camera();
  40. camera->initDefault();
  41. camera->autorelease();
  42. camera->setDepth(0.f);
  43. return camera;
  44. }
  45. Camera* Camera::createPerspective(float fieldOfView, float aspectRatio, float nearPlane, float farPlane)
  46. {
  47. auto ret = new (std::nothrow) Camera();
  48. if (ret)
  49. {
  50. ret->initPerspective(fieldOfView, aspectRatio, nearPlane, farPlane);
  51. ret->autorelease();
  52. return ret;
  53. }
  54. CC_SAFE_DELETE(ret);
  55. return nullptr;
  56. }
  57. Camera* Camera::createOrthographic(float zoomX, float zoomY, float nearPlane, float farPlane)
  58. {
  59. auto ret = new (std::nothrow) Camera();
  60. if (ret)
  61. {
  62. ret->initOrthographic(zoomX, zoomY, nearPlane, farPlane);
  63. ret->autorelease();
  64. return ret;
  65. }
  66. CC_SAFE_DELETE(ret);
  67. return nullptr;
  68. }
  69. Camera* Camera::getDefaultCamera()
  70. {
  71. auto scene = Director::getInstance()->getRunningScene();
  72. if(scene)
  73. {
  74. return scene->getDefaultCamera();
  75. }
  76. return nullptr;
  77. }
  78. const experimental::Viewport& Camera::getDefaultViewport()
  79. {
  80. return _defaultViewport;
  81. }
  82. void Camera::setDefaultViewport(const experimental::Viewport& vp)
  83. {
  84. _defaultViewport = vp;
  85. }
  86. const Camera* Camera::getVisitingCamera()
  87. {
  88. return _visitingCamera;
  89. }
  90. // end static methods
  91. Camera::Camera()
  92. : _scene(nullptr)
  93. , _viewProjectionDirty(true)
  94. , _cameraFlag(1)
  95. , _frustumDirty(true)
  96. , _viewProjectionUpdated(false)
  97. , _depth(-1)
  98. , _fbo(nullptr)
  99. {
  100. _frustum.setClipZ(true);
  101. _clearBrush = CameraBackgroundBrush::createDepthBrush(1.f);
  102. _clearBrush->retain();
  103. }
  104. Camera::~Camera()
  105. {
  106. CC_SAFE_RELEASE_NULL(_fbo);
  107. CC_SAFE_RELEASE(_clearBrush);
  108. }
  109. const Mat4& Camera::getProjectionMatrix() const
  110. {
  111. return _projection;
  112. }
  113. const Mat4& Camera::getViewMatrix() const
  114. {
  115. Mat4 viewInv(getNodeToWorldTransform());
  116. static int count = sizeof(float) * 16;
  117. if (memcmp(viewInv.m, _viewInv.m, count) != 0)
  118. {
  119. _viewProjectionDirty = true;
  120. _frustumDirty = true;
  121. _viewInv = viewInv;
  122. _view = viewInv.getInversed();
  123. }
  124. return _view;
  125. }
  126. void Camera::lookAt(const Vec3& lookAtPos, const Vec3& up)
  127. {
  128. Vec3 upv = up;
  129. upv.normalize();
  130. Vec3 zaxis;
  131. Vec3::subtract(this->getPosition3D(), lookAtPos, &zaxis);
  132. zaxis.normalize();
  133. Vec3 xaxis;
  134. Vec3::cross(upv, zaxis, &xaxis);
  135. xaxis.normalize();
  136. Vec3 yaxis;
  137. Vec3::cross(zaxis, xaxis, &yaxis);
  138. yaxis.normalize();
  139. Mat4 rotation;
  140. rotation.m[0] = xaxis.x;
  141. rotation.m[1] = xaxis.y;
  142. rotation.m[2] = xaxis.z;
  143. rotation.m[3] = 0;
  144. rotation.m[4] = yaxis.x;
  145. rotation.m[5] = yaxis.y;
  146. rotation.m[6] = yaxis.z;
  147. rotation.m[7] = 0;
  148. rotation.m[8] = zaxis.x;
  149. rotation.m[9] = zaxis.y;
  150. rotation.m[10] = zaxis.z;
  151. rotation.m[11] = 0;
  152. Quaternion quaternion;
  153. Quaternion::createFromRotationMatrix(rotation,&quaternion);
  154. quaternion.normalize();
  155. setRotationQuat(quaternion);
  156. }
  157. const Mat4& Camera::getViewProjectionMatrix() const
  158. {
  159. getViewMatrix();
  160. if (_viewProjectionDirty)
  161. {
  162. _viewProjectionDirty = false;
  163. Mat4::multiply(_projection, _view, &_viewProjection);
  164. }
  165. return _viewProjection;
  166. }
  167. void Camera::setAdditionalProjection(const Mat4& mat)
  168. {
  169. _projection = mat * _projection;
  170. getViewProjectionMatrix();
  171. }
  172. bool Camera::initDefault()
  173. {
  174. auto size = Director::getInstance()->getWinSize();
  175. //create default camera
  176. auto projection = Director::getInstance()->getProjection();
  177. switch (projection)
  178. {
  179. case Director::Projection::_2D:
  180. {
  181. initOrthographic(size.width, size.height, -1024, 1024);
  182. setPosition3D(Vec3(0.0f, 0.0f, 0.0f));
  183. setRotation3D(Vec3(0.f, 0.f, 0.f));
  184. break;
  185. }
  186. case Director::Projection::_3D:
  187. {
  188. float zeye = Director::getInstance()->getZEye();
  189. initPerspective(60, (GLfloat)size.width / size.height, 10, zeye + size.height / 2.0f);
  190. Vec3 eye(size.width/2, size.height/2.0f, zeye), center(size.width/2, size.height/2, 0.0f), up(0.0f, 1.0f, 0.0f);
  191. setPosition3D(eye);
  192. lookAt(center, up);
  193. break;
  194. }
  195. default:
  196. CCLOG("unrecognized projection");
  197. break;
  198. }
  199. return true;
  200. }
  201. bool Camera::initPerspective(float fieldOfView, float aspectRatio, float nearPlane, float farPlane)
  202. {
  203. _fieldOfView = fieldOfView;
  204. _aspectRatio = aspectRatio;
  205. _nearPlane = nearPlane;
  206. _farPlane = farPlane;
  207. Mat4::createPerspective(_fieldOfView, _aspectRatio, _nearPlane, _farPlane, &_projection);
  208. _viewProjectionDirty = true;
  209. _frustumDirty = true;
  210. _type = Type::PERSPECTIVE;
  211. return true;
  212. }
  213. bool Camera::initOrthographic(float zoomX, float zoomY, float nearPlane, float farPlane)
  214. {
  215. _zoom[0] = zoomX;
  216. _zoom[1] = zoomY;
  217. _nearPlane = nearPlane;
  218. _farPlane = farPlane;
  219. Mat4::createOrthographicOffCenter(0, _zoom[0], 0, _zoom[1], _nearPlane, _farPlane, &_projection);
  220. _viewProjectionDirty = true;
  221. _frustumDirty = true;
  222. _type = Type::ORTHOGRAPHIC;
  223. return true;
  224. }
  225. Vec2 Camera::project(const Vec3& src) const
  226. {
  227. Vec2 screenPos;
  228. auto viewport = Director::getInstance()->getWinSize();
  229. Vec4 clipPos;
  230. getViewProjectionMatrix().transformVector(Vec4(src.x, src.y, src.z, 1.0f), &clipPos);
  231. CCASSERT(clipPos.w != 0.0f, "clipPos.w can't be 0.0f!");
  232. float ndcX = clipPos.x / clipPos.w;
  233. float ndcY = clipPos.y / clipPos.w;
  234. screenPos.x = (ndcX + 1.0f) * 0.5f * viewport.width;
  235. screenPos.y = (1.0f - (ndcY + 1.0f) * 0.5f) * viewport.height;
  236. return screenPos;
  237. }
  238. Vec2 Camera::projectGL(const Vec3& src) const
  239. {
  240. Vec2 screenPos;
  241. auto viewport = Director::getInstance()->getWinSize();
  242. Vec4 clipPos;
  243. getViewProjectionMatrix().transformVector(Vec4(src.x, src.y, src.z, 1.0f), &clipPos);
  244. CCASSERT(clipPos.w != 0.0f, "clipPos.w can't be 0.0f!");
  245. float ndcX = clipPos.x / clipPos.w;
  246. float ndcY = clipPos.y / clipPos.w;
  247. screenPos.x = (ndcX + 1.0f) * 0.5f * viewport.width;
  248. screenPos.y = (ndcY + 1.0f) * 0.5f * viewport.height;
  249. return screenPos;
  250. }
  251. Vec3 Camera::unproject(const Vec3& src) const
  252. {
  253. Vec3 dst;
  254. unproject(Director::getInstance()->getWinSize(), &src, &dst);
  255. return dst;
  256. }
  257. Vec3 Camera::unprojectGL(const Vec3& src) const
  258. {
  259. Vec3 dst;
  260. unprojectGL(Director::getInstance()->getWinSize(), &src, &dst);
  261. return dst;
  262. }
  263. void Camera::unproject(const Size& viewport, const Vec3* src, Vec3* dst) const
  264. {
  265. CCASSERT(src && dst, "vec3 can not be null");
  266. Vec4 screen(src->x / viewport.width, ((viewport.height - src->y)) / viewport.height, src->z, 1.0f);
  267. screen.x = screen.x * 2.0f - 1.0f;
  268. screen.y = screen.y * 2.0f - 1.0f;
  269. screen.z = screen.z * 2.0f - 1.0f;
  270. getViewProjectionMatrix().getInversed().transformVector(screen, &screen);
  271. if (screen.w != 0.0f)
  272. {
  273. screen.x /= screen.w;
  274. screen.y /= screen.w;
  275. screen.z /= screen.w;
  276. }
  277. dst->set(screen.x, screen.y, screen.z);
  278. }
  279. void Camera::unprojectGL(const Size& viewport, const Vec3* src, Vec3* dst) const
  280. {
  281. CCASSERT(src && dst, "vec3 can not be null");
  282. Vec4 screen(src->x / viewport.width, src->y / viewport.height, src->z, 1.0f);
  283. screen.x = screen.x * 2.0f - 1.0f;
  284. screen.y = screen.y * 2.0f - 1.0f;
  285. screen.z = screen.z * 2.0f - 1.0f;
  286. getViewProjectionMatrix().getInversed().transformVector(screen, &screen);
  287. if (screen.w != 0.0f)
  288. {
  289. screen.x /= screen.w;
  290. screen.y /= screen.w;
  291. screen.z /= screen.w;
  292. }
  293. dst->set(screen.x, screen.y, screen.z);
  294. }
  295. bool Camera::isVisibleInFrustum(const AABB* aabb) const
  296. {
  297. if (_frustumDirty)
  298. {
  299. _frustum.initFrustum(this);
  300. _frustumDirty = false;
  301. }
  302. return !_frustum.isOutOfFrustum(*aabb);
  303. }
  304. float Camera::getDepthInView(const Mat4& transform) const
  305. {
  306. Mat4 camWorldMat = getNodeToWorldTransform();
  307. const Mat4 &viewMat = camWorldMat.getInversed();
  308. float depth = -(viewMat.m[2] * transform.m[12] + viewMat.m[6] * transform.m[13] + viewMat.m[10] * transform.m[14] + viewMat.m[14]);
  309. return depth;
  310. }
  311. void Camera::setDepth(int8_t depth)
  312. {
  313. if (_depth != depth)
  314. {
  315. _depth = depth;
  316. if (_scene)
  317. {
  318. //notify scene that the camera order is dirty
  319. _scene->setCameraOrderDirty();
  320. }
  321. }
  322. }
  323. void Camera::onEnter()
  324. {
  325. if (_scene == nullptr)
  326. {
  327. auto scene = getScene();
  328. if (scene)
  329. {
  330. setScene(scene);
  331. }
  332. }
  333. Node::onEnter();
  334. }
  335. void Camera::onExit()
  336. {
  337. // remove this camera from scene
  338. setScene(nullptr);
  339. Node::onExit();
  340. }
  341. void Camera::setScene(Scene* scene)
  342. {
  343. if (_scene != scene)
  344. {
  345. //remove old scene
  346. if (_scene)
  347. {
  348. auto& cameras = _scene->_cameras;
  349. auto it = std::find(cameras.begin(), cameras.end(), this);
  350. if (it != cameras.end())
  351. cameras.erase(it);
  352. _scene = nullptr;
  353. }
  354. //set new scene
  355. if (scene)
  356. {
  357. _scene = scene;
  358. auto& cameras = _scene->_cameras;
  359. auto it = std::find(cameras.begin(), cameras.end(), this);
  360. if (it == cameras.end())
  361. {
  362. _scene->_cameras.push_back(this);
  363. //notify scene that the camera order is dirty
  364. _scene->setCameraOrderDirty();
  365. }
  366. }
  367. }
  368. }
  369. void Camera::clearBackground()
  370. {
  371. if (_clearBrush)
  372. {
  373. _clearBrush->drawBackground(this);
  374. }
  375. }
  376. void Camera::setFrameBufferObject(experimental::FrameBuffer *fbo)
  377. {
  378. CC_SAFE_RETAIN(fbo);
  379. CC_SAFE_RELEASE_NULL(_fbo);
  380. _fbo = fbo;
  381. if(_scene)
  382. {
  383. _scene->setCameraOrderDirty();
  384. }
  385. }
  386. void Camera::apply()
  387. {
  388. _viewProjectionUpdated = _transformUpdated;
  389. applyFrameBufferObject();
  390. applyViewport();
  391. }
  392. void Camera::applyFrameBufferObject()
  393. {
  394. if(nullptr == _fbo)
  395. {
  396. // inherit from context if it doesn't have a FBO
  397. // don't call apply the default one
  398. // experimental::FrameBuffer::applyDefaultFBO();
  399. }
  400. else
  401. {
  402. _fbo->applyFBO();
  403. }
  404. }
  405. void Camera::applyViewport()
  406. {
  407. glGetIntegerv(GL_VIEWPORT, _oldViewport);
  408. if(nullptr == _fbo)
  409. {
  410. glViewport(getDefaultViewport()._left, getDefaultViewport()._bottom, getDefaultViewport()._width, getDefaultViewport()._height);
  411. }
  412. else
  413. {
  414. glViewport(_viewport._left * _fbo->getWidth(), _viewport._bottom * _fbo->getHeight(),
  415. _viewport._width * _fbo->getWidth(), _viewport._height * _fbo->getHeight());
  416. }
  417. }
  418. void Camera::setViewport(const experimental::Viewport& vp)
  419. {
  420. _viewport = vp;
  421. }
  422. void Camera::restore()
  423. {
  424. restoreFrameBufferObject();
  425. restoreViewport();
  426. }
  427. void Camera::restoreFrameBufferObject()
  428. {
  429. if(nullptr == _fbo)
  430. {
  431. // it was inherited from context if it doesn't have a FBO
  432. // don't call restore the default one... just keep using the previous one
  433. // experimental::FrameBuffer::applyDefaultFBO();
  434. }
  435. else
  436. {
  437. _fbo->restoreFBO();
  438. }
  439. }
  440. void Camera::restoreViewport()
  441. {
  442. glViewport(_oldViewport[0], _oldViewport[1], _oldViewport[2], _oldViewport[3]);
  443. }
  444. int Camera::getRenderOrder() const
  445. {
  446. int result(0);
  447. if(_fbo)
  448. {
  449. result = _fbo->getFID()<<8;
  450. }
  451. else
  452. {
  453. result = 127 <<8;
  454. }
  455. result += _depth;
  456. return result;
  457. }
  458. void Camera::visit(Renderer* renderer, const Mat4 &parentTransform, uint32_t parentFlags)
  459. {
  460. _viewProjectionUpdated = _transformUpdated;
  461. return Node::visit(renderer, parentTransform, parentFlags);
  462. }
  463. void Camera::setBackgroundBrush(CameraBackgroundBrush* clearBrush)
  464. {
  465. CC_SAFE_RETAIN(clearBrush);
  466. CC_SAFE_RELEASE(_clearBrush);
  467. _clearBrush = clearBrush;
  468. }
  469. bool Camera::isBrushValid()
  470. {
  471. return _clearBrush != nullptr && _clearBrush->isValid();
  472. }
  473. NS_CC_END