CCMesh.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706
  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. ****************************************************************************/
  21. #include "3d/CCMesh.h"
  22. #include "3d/CCMeshSkin.h"
  23. #include "3d/CCSkeleton3D.h"
  24. #include "3d/CCMeshVertexIndexData.h"
  25. #include "2d/CCLight.h"
  26. #include "2d/CCScene.h"
  27. #include "base/CCEventDispatcher.h"
  28. #include "base/CCDirector.h"
  29. #include "base/CCConfiguration.h"
  30. #include "renderer/CCTextureCache.h"
  31. #include "renderer/CCGLProgramState.h"
  32. #include "renderer/CCMaterial.h"
  33. #include "renderer/CCTechnique.h"
  34. #include "renderer/CCPass.h"
  35. #include "renderer/CCRenderer.h"
  36. #include "renderer/CCVertexAttribBinding.h"
  37. #include "math/Mat4.h"
  38. using namespace std;
  39. NS_CC_BEGIN
  40. // Helpers
  41. //sampler uniform names, only diffuse and normal texture are supported for now
  42. std::string s_uniformSamplerName[] =
  43. {
  44. "",//NTextureData::Usage::Unknown,
  45. "",//NTextureData::Usage::None
  46. "",//NTextureData::Usage::Diffuse
  47. "",//NTextureData::Usage::Emissive
  48. "",//NTextureData::Usage::Ambient
  49. "",//NTextureData::Usage::Specular
  50. "",//NTextureData::Usage::Shininess
  51. "u_normalTex",//NTextureData::Usage::Normal
  52. "",//NTextureData::Usage::Bump
  53. "",//NTextureData::Usage::Transparency
  54. "",//NTextureData::Usage::Reflection
  55. };
  56. static const char *s_dirLightUniformColorName = "u_DirLightSourceColor";
  57. static const char *s_dirLightUniformDirName = "u_DirLightSourceDirection";
  58. static const char *s_pointLightUniformColorName = "u_PointLightSourceColor";
  59. static const char *s_pointLightUniformPositionName = "u_PointLightSourcePosition";
  60. static const char *s_pointLightUniformRangeInverseName = "u_PointLightSourceRangeInverse";
  61. static const char *s_spotLightUniformColorName = "u_SpotLightSourceColor";
  62. static const char *s_spotLightUniformPositionName = "u_SpotLightSourcePosition";
  63. static const char *s_spotLightUniformDirName = "u_SpotLightSourceDirection";
  64. static const char *s_spotLightUniformInnerAngleCosName = "u_SpotLightSourceInnerAngleCos";
  65. static const char *s_spotLightUniformOuterAngleCosName = "u_SpotLightSourceOuterAngleCos";
  66. static const char *s_spotLightUniformRangeInverseName = "u_SpotLightSourceRangeInverse";
  67. static const char *s_ambientLightUniformColorName = "u_AmbientLightSourceColor";
  68. // helpers
  69. void Mesh::resetLightUniformValues()
  70. {
  71. const auto& conf = Configuration::getInstance();
  72. int maxDirLight = conf->getMaxSupportDirLightInShader();
  73. int maxPointLight = conf->getMaxSupportPointLightInShader();
  74. int maxSpotLight = conf->getMaxSupportSpotLightInShader();
  75. _dirLightUniformColorValues.assign(maxDirLight, Vec3::ZERO);
  76. _dirLightUniformDirValues.assign(maxDirLight, Vec3::ZERO);
  77. _pointLightUniformColorValues.assign(maxPointLight, Vec3::ZERO);
  78. _pointLightUniformPositionValues.assign(maxPointLight, Vec3::ZERO);
  79. _pointLightUniformRangeInverseValues.assign(maxPointLight, 0.0f);
  80. _spotLightUniformColorValues.assign(maxSpotLight, Vec3::ZERO);
  81. _spotLightUniformPositionValues.assign(maxSpotLight, Vec3::ZERO);
  82. _spotLightUniformDirValues.assign(maxSpotLight, Vec3::ZERO);
  83. _spotLightUniformInnerAngleCosValues.assign(maxSpotLight, 1.0f);
  84. _spotLightUniformOuterAngleCosValues.assign(maxSpotLight, 0.0f);
  85. _spotLightUniformRangeInverseValues.assign(maxSpotLight, 0.0f);
  86. }
  87. //Generate a dummy texture when the texture file is missing
  88. static Texture2D * getDummyTexture()
  89. {
  90. auto texture = Director::getInstance()->getTextureCache()->getTextureForKey("/dummyTexture");
  91. if(!texture)
  92. {
  93. #ifdef NDEBUG
  94. unsigned char data[] ={0,0,0,0};//1*1 transparent picture
  95. #else
  96. unsigned char data[] ={255,0,0,255};//1*1 red picture
  97. #endif
  98. Image * image =new (std::nothrow) Image();
  99. image->initWithRawData(data,sizeof(data),1,1,sizeof(unsigned char));
  100. texture=Director::getInstance()->getTextureCache()->addImage(image,"/dummyTexture");
  101. image->release();
  102. }
  103. return texture;
  104. }
  105. Mesh::Mesh()
  106. : _skin(nullptr)
  107. , _visible(true)
  108. , _isTransparent(false)
  109. , _force2DQueue(false)
  110. , _meshIndexData(nullptr)
  111. , _glProgramState(nullptr)
  112. , _blend(BlendFunc::ALPHA_NON_PREMULTIPLIED)
  113. , _blendDirty(true)
  114. , _material(nullptr)
  115. , _texFile("")
  116. {
  117. }
  118. Mesh::~Mesh()
  119. {
  120. for (auto &tex : _textures){
  121. CC_SAFE_RELEASE(tex.second);
  122. }
  123. CC_SAFE_RELEASE(_skin);
  124. CC_SAFE_RELEASE(_meshIndexData);
  125. CC_SAFE_RELEASE(_material);
  126. CC_SAFE_RELEASE(_glProgramState);
  127. }
  128. GLuint Mesh::getVertexBuffer() const
  129. {
  130. return _meshIndexData->getVertexBuffer()->getVBO();
  131. }
  132. bool Mesh::hasVertexAttrib(int attrib) const
  133. {
  134. return _meshIndexData->getMeshVertexData()->hasVertexAttrib(attrib);
  135. }
  136. ssize_t Mesh::getMeshVertexAttribCount() const
  137. {
  138. return _meshIndexData->getMeshVertexData()->getMeshVertexAttribCount();
  139. }
  140. const MeshVertexAttrib& Mesh::getMeshVertexAttribute(int idx)
  141. {
  142. return _meshIndexData->getMeshVertexData()->getMeshVertexAttrib(idx);
  143. }
  144. int Mesh::getVertexSizeInBytes() const
  145. {
  146. return _meshIndexData->getVertexBuffer()->getSizePerVertex();
  147. }
  148. Mesh* Mesh::create(const std::vector<float>& positions, const std::vector<float>& normals, const std::vector<float>& texs, const IndexArray& indices)
  149. {
  150. int perVertexSizeInFloat = 0;
  151. std::vector<float> vertices;
  152. std::vector<MeshVertexAttrib> attribs;
  153. MeshVertexAttrib att;
  154. att.size = 3;
  155. att.type = GL_FLOAT;
  156. att.attribSizeBytes = att.size * sizeof(float);
  157. if (positions.size())
  158. {
  159. perVertexSizeInFloat += 3;
  160. att.vertexAttrib = GLProgram::VERTEX_ATTRIB_POSITION;
  161. attribs.push_back(att);
  162. }
  163. if (normals.size())
  164. {
  165. perVertexSizeInFloat += 3;
  166. att.vertexAttrib = GLProgram::VERTEX_ATTRIB_NORMAL;
  167. attribs.push_back(att);
  168. }
  169. if (texs.size())
  170. {
  171. perVertexSizeInFloat += 2;
  172. att.vertexAttrib = GLProgram::VERTEX_ATTRIB_TEX_COORD;
  173. att.size = 2;
  174. att.attribSizeBytes = att.size * sizeof(float);
  175. attribs.push_back(att);
  176. }
  177. bool hasNormal = (normals.size() != 0);
  178. bool hasTexCoord = (texs.size() != 0);
  179. //position, normal, texCoordinate into _vertexs
  180. size_t vertexNum = positions.size() / 3;
  181. for(size_t i = 0; i < vertexNum; i++)
  182. {
  183. vertices.push_back(positions[i * 3]);
  184. vertices.push_back(positions[i * 3 + 1]);
  185. vertices.push_back(positions[i * 3 + 2]);
  186. if (hasNormal)
  187. {
  188. vertices.push_back(normals[i * 3]);
  189. vertices.push_back(normals[i * 3 + 1]);
  190. vertices.push_back(normals[i * 3 + 2]);
  191. }
  192. if (hasTexCoord)
  193. {
  194. vertices.push_back(texs[i * 2]);
  195. vertices.push_back(texs[i * 2 + 1]);
  196. }
  197. }
  198. return create(vertices, perVertexSizeInFloat, indices, attribs);
  199. }
  200. Mesh* Mesh::create(const std::vector<float>& vertices, int /*perVertexSizeInFloat*/, const IndexArray& indices, const std::vector<MeshVertexAttrib>& attribs)
  201. {
  202. MeshData meshdata;
  203. meshdata.attribs = attribs;
  204. meshdata.vertex = vertices;
  205. meshdata.subMeshIndices.push_back(indices);
  206. meshdata.subMeshIds.push_back("");
  207. auto meshvertexdata = MeshVertexData::create(meshdata);
  208. auto indexData = meshvertexdata->getMeshIndexDataByIndex(0);
  209. return create("", indexData);
  210. }
  211. Mesh* Mesh::create(const std::string& name, MeshIndexData* indexData, MeshSkin* skin)
  212. {
  213. auto state = new (std::nothrow) Mesh();
  214. state->autorelease();
  215. state->bindMeshCommand();
  216. state->_name = name;
  217. state->setMeshIndexData(indexData);
  218. state->setSkin(skin);
  219. return state;
  220. }
  221. void Mesh::setVisible(bool visible)
  222. {
  223. if (_visible != visible)
  224. {
  225. _visible = visible;
  226. if (_visibleChanged)
  227. _visibleChanged();
  228. }
  229. }
  230. bool Mesh::isVisible() const
  231. {
  232. return _visible;
  233. }
  234. void Mesh::setTexture(const std::string& texPath)
  235. {
  236. _texFile = texPath;
  237. auto tex = Director::getInstance()->getTextureCache()->addImage(texPath);
  238. setTexture(tex, NTextureData::Usage::Diffuse);
  239. }
  240. void Mesh::setTexture(Texture2D* tex)
  241. {
  242. setTexture(tex, NTextureData::Usage::Diffuse);
  243. }
  244. void Mesh::setTexture(Texture2D* tex, NTextureData::Usage usage, bool cacheFileName)
  245. {
  246. // Texture must be saved for future use
  247. // it doesn't matter if the material is already set or not
  248. // This functionality is added for compatibility issues
  249. if (tex == nullptr)
  250. tex = getDummyTexture();
  251. CC_SAFE_RETAIN(tex);
  252. CC_SAFE_RELEASE(_textures[usage]);
  253. _textures[usage] = tex;
  254. if (usage == NTextureData::Usage::Diffuse){
  255. if (_material) {
  256. auto technique = _material->_currentTechnique;
  257. for(auto& pass: technique->_passes)
  258. {
  259. // FIXME: Ideally it should use glProgramState->setUniformTexture()
  260. // and set CC_Texture0 that way. But trying to it, will trigger
  261. // another bug
  262. pass->setTexture(tex);
  263. }
  264. }
  265. bindMeshCommand();
  266. if (cacheFileName)
  267. _texFile = tex->getPath();
  268. }
  269. else if (usage == NTextureData::Usage::Normal) // currently only diffuse and normal are supported
  270. {
  271. if (_material){
  272. auto technique = _material->_currentTechnique;
  273. for(auto& pass: technique->_passes)
  274. {
  275. pass->getGLProgramState()->setUniformTexture(s_uniformSamplerName[(int)usage], tex);
  276. }
  277. }
  278. }
  279. }
  280. void Mesh::setTexture(const std::string& texPath, NTextureData::Usage usage)
  281. {
  282. auto tex = Director::getInstance()->getTextureCache()->addImage(texPath);
  283. setTexture(tex, usage);
  284. }
  285. Texture2D* Mesh::getTexture() const
  286. {
  287. return _textures.at(NTextureData::Usage::Diffuse);
  288. }
  289. Texture2D* Mesh::getTexture(NTextureData::Usage usage)
  290. {
  291. return _textures[usage];
  292. }
  293. void Mesh::setMaterial(Material* material)
  294. {
  295. if (_material != material) {
  296. CC_SAFE_RELEASE(_material);
  297. _material = material;
  298. CC_SAFE_RETAIN(_material);
  299. }
  300. if (_material)
  301. {
  302. for (auto technique: _material->getTechniques())
  303. {
  304. for (auto pass: technique->getPasses())
  305. {
  306. auto vertexAttribBinding = VertexAttribBinding::create(_meshIndexData, pass->getGLProgramState());
  307. pass->setVertexAttribBinding(vertexAttribBinding);
  308. }
  309. }
  310. }
  311. // Was the texture set before the GLProgramState ? Set it
  312. for(auto& tex : _textures)
  313. setTexture(tex.second, tex.first);
  314. if (_blendDirty)
  315. setBlendFunc(_blend);
  316. bindMeshCommand();
  317. }
  318. Material* Mesh::getMaterial() const
  319. {
  320. return _material;
  321. }
  322. void Mesh::draw(Renderer* renderer, float globalZOrder, const Mat4& transform, uint32_t flags, unsigned int lightMask, const Vec4& color, bool forceDepthWrite)
  323. {
  324. if (! isVisible())
  325. return;
  326. bool isTransparent = (_isTransparent || color.w < 1.f);
  327. float globalZ = isTransparent ? 0 : globalZOrder;
  328. if (isTransparent)
  329. flags |= Node::FLAGS_RENDER_AS_3D;
  330. _meshCommand.init(globalZ,
  331. _material,
  332. getVertexBuffer(),
  333. getIndexBuffer(),
  334. getPrimitiveType(),
  335. getIndexFormat(),
  336. getIndexCount(),
  337. transform,
  338. flags);
  339. if (isTransparent && !forceDepthWrite)
  340. _material->getStateBlock()->setDepthWrite(false);
  341. else
  342. _material->getStateBlock()->setDepthWrite(true);
  343. _meshCommand.setSkipBatching(isTransparent);
  344. _meshCommand.setTransparent(isTransparent);
  345. _meshCommand.set3D(!_force2DQueue);
  346. _material->getStateBlock()->setBlend(_force2DQueue || isTransparent);
  347. // set default uniforms for Mesh
  348. // 'u_color' and others
  349. const auto scene = Director::getInstance()->getRunningScene();
  350. auto technique = _material->_currentTechnique;
  351. for(const auto pass : technique->_passes)
  352. {
  353. auto programState = pass->getGLProgramState();
  354. programState->setUniformVec4("u_color", color);
  355. if (_skin)
  356. programState->setUniformVec4v("u_matrixPalette", (GLsizei)_skin->getMatrixPaletteSize(), _skin->getMatrixPalette());
  357. if (scene && scene->getLights().size() > 0)
  358. setLightUniforms(pass, scene, color, lightMask);
  359. }
  360. renderer->addCommand(&_meshCommand);
  361. }
  362. void Mesh::setSkin(MeshSkin* skin)
  363. {
  364. if (_skin != skin)
  365. {
  366. CC_SAFE_RETAIN(skin);
  367. CC_SAFE_RELEASE(_skin);
  368. _skin = skin;
  369. calculateAABB();
  370. }
  371. }
  372. void Mesh::setMeshIndexData(MeshIndexData* subMesh)
  373. {
  374. if (_meshIndexData != subMesh)
  375. {
  376. CC_SAFE_RETAIN(subMesh);
  377. CC_SAFE_RELEASE(_meshIndexData);
  378. _meshIndexData = subMesh;
  379. calculateAABB();
  380. bindMeshCommand();
  381. }
  382. }
  383. void Mesh::setGLProgramState(GLProgramState* glProgramState)
  384. {
  385. // XXX create dummy texture
  386. auto material = Material::createWithGLStateProgram(glProgramState);
  387. if (_material)
  388. material->setStateBlock(_material->getStateBlock());
  389. setMaterial(material);
  390. }
  391. GLProgramState* Mesh::getGLProgramState() const
  392. {
  393. return _material ?
  394. _material->_currentTechnique->_passes.at(0)->getGLProgramState()
  395. : nullptr;
  396. }
  397. void Mesh::calculateAABB()
  398. {
  399. if (_meshIndexData)
  400. {
  401. _aabb = _meshIndexData->getAABB();
  402. if (_skin)
  403. {
  404. //get skin root
  405. Bone3D* root = nullptr;
  406. Mat4 invBindPose;
  407. if (_skin->_skinBones.size())
  408. {
  409. root = _skin->_skinBones.at(0);
  410. while (root) {
  411. auto parent = root->getParentBone();
  412. bool parentInSkinBone = false;
  413. for (const auto& bone : _skin->_skinBones) {
  414. if (bone == parent)
  415. {
  416. parentInSkinBone = true;
  417. break;
  418. }
  419. }
  420. if (!parentInSkinBone)
  421. break;
  422. root = parent;
  423. }
  424. }
  425. if (root)
  426. {
  427. _aabb.transform(root->getWorldMat() * _skin->getInvBindPose(root));
  428. }
  429. }
  430. }
  431. }
  432. void Mesh::bindMeshCommand()
  433. {
  434. if (_material && _meshIndexData)
  435. {
  436. auto pass = _material->_currentTechnique->_passes.at(0);
  437. auto glprogramstate = pass->getGLProgramState();
  438. auto texture = pass->getTexture();
  439. auto textureid = texture ? texture->getName() : 0;
  440. // XXX
  441. // auto blend = pass->getStateBlock()->getBlendFunc();
  442. auto blend = BlendFunc::ALPHA_PREMULTIPLIED;
  443. _meshCommand.genMaterialID(textureid, glprogramstate, _meshIndexData->getVertexBuffer()->getVBO(), _meshIndexData->getIndexBuffer()->getVBO(), blend);
  444. _material->getStateBlock()->setCullFace(true);
  445. _material->getStateBlock()->setDepthTest(true);
  446. }
  447. }
  448. void Mesh::setLightUniforms(Pass* pass, Scene* scene, const Vec4& color, unsigned int lightmask)
  449. {
  450. CCASSERT(pass, "Invalid Pass");
  451. CCASSERT(scene, "Invalid scene");
  452. const auto& conf = Configuration::getInstance();
  453. int maxDirLight = conf->getMaxSupportDirLightInShader();
  454. int maxPointLight = conf->getMaxSupportPointLightInShader();
  455. int maxSpotLight = conf->getMaxSupportSpotLightInShader();
  456. auto &lights = scene->getLights();
  457. auto glProgramState = pass->getGLProgramState();
  458. auto attributes = pass->getVertexAttributeBinding()->getVertexAttribsFlags();
  459. if (attributes & (1 << GLProgram::VERTEX_ATTRIB_NORMAL))
  460. {
  461. resetLightUniformValues();
  462. GLint enabledDirLightNum = 0;
  463. GLint enabledPointLightNum = 0;
  464. GLint enabledSpotLightNum = 0;
  465. Vec3 ambientColor;
  466. for (const auto& light : lights)
  467. {
  468. bool useLight = light->isEnabled() && ((unsigned int)light->getLightFlag() & lightmask);
  469. if (useLight)
  470. {
  471. float intensity = light->getIntensity();
  472. switch (light->getLightType())
  473. {
  474. case LightType::DIRECTIONAL:
  475. {
  476. if(enabledDirLightNum < maxDirLight)
  477. {
  478. auto dirLight = static_cast<DirectionLight *>(light);
  479. Vec3 dir = dirLight->getDirectionInWorld();
  480. dir.normalize();
  481. const Color3B &col = dirLight->getDisplayedColor();
  482. _dirLightUniformColorValues[enabledDirLightNum].set(col.r / 255.0f * intensity, col.g / 255.0f * intensity, col.b / 255.0f * intensity);
  483. _dirLightUniformDirValues[enabledDirLightNum] = dir;
  484. ++enabledDirLightNum;
  485. }
  486. }
  487. break;
  488. case LightType::POINT:
  489. {
  490. if(enabledPointLightNum < maxPointLight)
  491. {
  492. auto pointLight = static_cast<PointLight *>(light);
  493. Mat4 mat= pointLight->getNodeToWorldTransform();
  494. const Color3B &col = pointLight->getDisplayedColor();
  495. _pointLightUniformColorValues[enabledPointLightNum].set(col.r / 255.0f * intensity, col.g / 255.0f * intensity, col.b / 255.0f * intensity);
  496. _pointLightUniformPositionValues[enabledPointLightNum].set(mat.m[12], mat.m[13], mat.m[14]);
  497. _pointLightUniformRangeInverseValues[enabledPointLightNum] = 1.0f / pointLight->getRange();
  498. ++enabledPointLightNum;
  499. }
  500. }
  501. break;
  502. case LightType::SPOT:
  503. {
  504. if(enabledSpotLightNum < maxSpotLight)
  505. {
  506. auto spotLight = static_cast<SpotLight *>(light);
  507. Vec3 dir = spotLight->getDirectionInWorld();
  508. dir.normalize();
  509. Mat4 mat= light->getNodeToWorldTransform();
  510. const Color3B &col = spotLight->getDisplayedColor();
  511. _spotLightUniformColorValues[enabledSpotLightNum].set(col.r / 255.0f * intensity, col.g / 255.0f * intensity, col.b / 255.0f * intensity);
  512. _spotLightUniformPositionValues[enabledSpotLightNum].set(mat.m[12], mat.m[13], mat.m[14]);
  513. _spotLightUniformDirValues[enabledSpotLightNum] = dir;
  514. _spotLightUniformInnerAngleCosValues[enabledSpotLightNum] = spotLight->getCosInnerAngle();
  515. _spotLightUniformOuterAngleCosValues[enabledSpotLightNum] = spotLight->getCosOuterAngle();
  516. _spotLightUniformRangeInverseValues[enabledSpotLightNum] = 1.0f / spotLight->getRange();
  517. ++enabledSpotLightNum;
  518. }
  519. }
  520. break;
  521. case LightType::AMBIENT:
  522. {
  523. auto ambLight = static_cast<AmbientLight *>(light);
  524. const Color3B &col = ambLight->getDisplayedColor();
  525. ambientColor.add(col.r / 255.0f * intensity, col.g / 255.0f * intensity, col.b / 255.0f * intensity);
  526. }
  527. break;
  528. default:
  529. break;
  530. }
  531. }
  532. }
  533. if (0 < maxDirLight)
  534. {
  535. glProgramState->setUniformVec3v(s_dirLightUniformColorName, _dirLightUniformColorValues.size(), &_dirLightUniformColorValues[0]);
  536. glProgramState->setUniformVec3v(s_dirLightUniformDirName, _dirLightUniformDirValues.size(), &_dirLightUniformDirValues[0]);
  537. }
  538. if (0 < maxPointLight)
  539. {
  540. glProgramState->setUniformVec3v(s_pointLightUniformColorName, _pointLightUniformColorValues.size(), &_pointLightUniformColorValues[0]);
  541. glProgramState->setUniformVec3v(s_pointLightUniformPositionName, _pointLightUniformPositionValues.size(), &_pointLightUniformPositionValues[0]);
  542. glProgramState->setUniformFloatv(s_pointLightUniformRangeInverseName, _pointLightUniformRangeInverseValues.size(), &_pointLightUniformRangeInverseValues[0]);
  543. }
  544. if (0 < maxSpotLight)
  545. {
  546. glProgramState->setUniformVec3v(s_spotLightUniformColorName, _spotLightUniformColorValues.size(), &_spotLightUniformColorValues[0]);
  547. glProgramState->setUniformVec3v(s_spotLightUniformPositionName, _spotLightUniformPositionValues.size(), &_spotLightUniformPositionValues[0]);
  548. glProgramState->setUniformVec3v(s_spotLightUniformDirName, _spotLightUniformDirValues.size(), &_spotLightUniformDirValues[0]);
  549. glProgramState->setUniformFloatv(s_spotLightUniformInnerAngleCosName, _spotLightUniformInnerAngleCosValues.size(), &_spotLightUniformInnerAngleCosValues[0]);
  550. glProgramState->setUniformFloatv(s_spotLightUniformOuterAngleCosName, _spotLightUniformOuterAngleCosValues.size(), &_spotLightUniformOuterAngleCosValues[0]);
  551. glProgramState->setUniformFloatv(s_spotLightUniformRangeInverseName, _spotLightUniformRangeInverseValues.size(), &_spotLightUniformRangeInverseValues[0]);
  552. }
  553. glProgramState->setUniformVec3(s_ambientLightUniformColorName, Vec3(ambientColor.x, ambientColor.y, ambientColor.z));
  554. }
  555. else // normal does not exist
  556. {
  557. Vec3 ambient(0.0f, 0.0f, 0.0f);
  558. bool hasAmbient = false;
  559. for (const auto& light : lights)
  560. {
  561. if (light->getLightType() == LightType::AMBIENT)
  562. {
  563. bool useLight = light->isEnabled() && ((unsigned int)light->getLightFlag() & lightmask);
  564. if (useLight)
  565. {
  566. hasAmbient = true;
  567. const Color3B &col = light->getDisplayedColor();
  568. ambient.x += col.r * light->getIntensity();
  569. ambient.y += col.g * light->getIntensity();
  570. ambient.z += col.b * light->getIntensity();
  571. }
  572. }
  573. }
  574. if (hasAmbient)
  575. {
  576. ambient.x /= 255.f; ambient.y /= 255.f; ambient.z /= 255.f;
  577. //override the uniform value of u_color using the calculated color
  578. glProgramState->setUniformVec4("u_color", Vec4(color.x * ambient.x, color.y * ambient.y, color.z * ambient.z, color.w));
  579. }
  580. }
  581. }
  582. void Mesh::setBlendFunc(const BlendFunc &blendFunc)
  583. {
  584. // Blend must be saved for future use
  585. // it doesn't matter if the material is already set or not
  586. // This functionality is added for compatibility issues
  587. if(_blend != blendFunc)
  588. {
  589. _blendDirty = true;
  590. _blend = blendFunc;
  591. }
  592. if (_material) {
  593. _material->getStateBlock()->setBlendFunc(blendFunc);
  594. bindMeshCommand();
  595. }
  596. }
  597. const BlendFunc& Mesh::getBlendFunc() const
  598. {
  599. // return _material->_currentTechnique->_passes.at(0)->getBlendFunc();
  600. return _blend;
  601. }
  602. GLenum Mesh::getPrimitiveType() const
  603. {
  604. return _meshIndexData->getPrimitiveType();
  605. }
  606. ssize_t Mesh::getIndexCount() const
  607. {
  608. return _meshIndexData->getIndexBuffer()->getIndexNumber();
  609. }
  610. GLenum Mesh::getIndexFormat() const
  611. {
  612. return GL_UNSIGNED_SHORT;
  613. }
  614. GLuint Mesh::getIndexBuffer() const
  615. {
  616. return _meshIndexData->getIndexBuffer()->getVBO();
  617. }
  618. NS_CC_END