SpriteBatch.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. #include "Base.h"
  2. #include "SpriteBatch.h"
  3. #include "Game.h"
  4. // Default size of a newly created sprite batch
  5. #define SPRITE_BATCH_DEFAULT_SIZE 128
  6. // Factor to grow a sprite batch by when its size is exceeded
  7. #define SPRITE_BATCH_GROW_FACTOR 2.0f
  8. // Macro for adding a sprite to the batch
  9. #define ADD_SPRITE_VERTEX(vtx, vx, vy, vz, vu, vv, vr, vg, vb, va) \
  10. vtx.x = vx; vtx.y = vy; vtx.z = vz; \
  11. vtx.u = vu; vtx.v = vv; \
  12. vtx.r = vr; vtx.g = vg; vtx.b = vb; vtx.a = va
  13. // Default sprite vertex shader
  14. #define SPRITE_VSH \
  15. "uniform mat4 u_projectionMatrix;\n" \
  16. "attribute vec3 a_position;\n" \
  17. "attribute vec2 a_texCoord;\n" \
  18. "attribute vec4 a_color;\n" \
  19. "varying vec2 v_texCoord;\n" \
  20. "varying vec4 v_color;\n" \
  21. "void main()\n" \
  22. "{\n" \
  23. "gl_Position = u_projectionMatrix * vec4(a_position, 1);\n" \
  24. "v_texCoord = a_texCoord;\n" \
  25. "v_color = a_color;\n" \
  26. "}\n"
  27. // Default sprite fragment shader
  28. #define SPRITE_FSH \
  29. "#ifdef OPENGL_ES\n" \
  30. "precision highp float;\n" \
  31. "#endif\n" \
  32. "varying vec2 v_texCoord;\n" \
  33. "varying vec4 v_color;\n" \
  34. "uniform sampler2D u_texture;\n" \
  35. "void main()\n" \
  36. "{\n" \
  37. "gl_FragColor = v_color * texture2D(u_texture, v_texCoord);\n" \
  38. "}\n"
  39. namespace gameplay
  40. {
  41. /**
  42. * Sprite vertex structure used for batching.
  43. */
  44. struct SpriteVertex
  45. {
  46. /**
  47. * The x coordinate of the vertex.
  48. */
  49. float x;
  50. /**
  51. * The y coordinate of the vertex.
  52. */
  53. float y;
  54. /**
  55. * The z coordinate of the vertex.
  56. */
  57. float z;
  58. /**
  59. * The u component of the (u, v) texture coordinates for the vertex.
  60. */
  61. float u;
  62. /**
  63. * The v component of the (u, v) texture coordinates for the vertex.
  64. */
  65. float v;
  66. /**
  67. * The red color component of the vertex.
  68. */
  69. float r;
  70. /**
  71. * The green color component of the vertex.
  72. */
  73. float g;
  74. /**
  75. * The blue color component of the vertex.
  76. */
  77. float b;
  78. /**
  79. * The alpha component of the vertex.
  80. */
  81. float a;
  82. };
  83. // Shared sprite effects
  84. static Effect* __spriteEffect = NULL;
  85. SpriteBatch::SpriteBatch()
  86. : _batch(NULL), _textureWidthRatio(0.0f), _textureHeightRatio(0.0f)
  87. {
  88. }
  89. SpriteBatch::SpriteBatch(const SpriteBatch& copy)
  90. {
  91. // hiddden
  92. }
  93. SpriteBatch::~SpriteBatch()
  94. {
  95. SAFE_DELETE(_batch);
  96. if (!_customEffect)
  97. {
  98. if (__spriteEffect->getRefCount() == 1)
  99. {
  100. __spriteEffect->release();
  101. __spriteEffect = NULL;
  102. }
  103. else
  104. __spriteEffect->release();
  105. }
  106. }
  107. SpriteBatch* SpriteBatch::create(const char* texturePath, Effect* effect, unsigned int initialCapacity)
  108. {
  109. Texture* texture = Texture::create(texturePath);
  110. SpriteBatch* batch = SpriteBatch::create(texture);
  111. SAFE_RELEASE(texture);
  112. return batch;
  113. }
  114. SpriteBatch* SpriteBatch::create(Texture* texture, Effect* effect, unsigned int initialCapacity)
  115. {
  116. assert(texture != NULL);
  117. bool customEffect = (effect != NULL);
  118. if (!customEffect)
  119. {
  120. // Create our static sprite effect.
  121. if (__spriteEffect == NULL)
  122. {
  123. __spriteEffect = Effect::createFromSource(SPRITE_VSH, SPRITE_FSH);
  124. if (__spriteEffect == NULL)
  125. {
  126. LOG_ERROR("Unable to load sprite effect.");
  127. return NULL;
  128. }
  129. effect = __spriteEffect;
  130. }
  131. else
  132. {
  133. effect = __spriteEffect;
  134. __spriteEffect->addRef();
  135. }
  136. }
  137. // Search for the first sampler uniform in the effect.
  138. Uniform* samplerUniform = NULL;
  139. for (unsigned int i = 0, count = effect->getUniformCount(); i < count; ++i)
  140. {
  141. Uniform* uniform = effect->getUniform(i);
  142. if (uniform && uniform->getType() == GL_SAMPLER_2D)
  143. {
  144. samplerUniform = uniform;
  145. break;
  146. }
  147. }
  148. if (!samplerUniform)
  149. {
  150. LOG_ERROR("No uniform of type GL_SAMPLER_2D found in sprite effect.");
  151. SAFE_RELEASE(effect);
  152. return NULL;
  153. }
  154. // Wrap the effect in a material
  155. Material* material = Material::create(effect); // +ref effect
  156. // Set initial material state
  157. material->getStateBlock()->setBlend(true);
  158. material->getStateBlock()->setBlendSrc(RenderState::BLEND_SRC_ALPHA);
  159. material->getStateBlock()->setBlendDst(RenderState::BLEND_ONE_MINUS_SRC_ALPHA);
  160. // Bind the texture to the material as a sampler
  161. Texture::Sampler* sampler = Texture::Sampler::create(texture); // +ref texture
  162. material->getParameter(samplerUniform->getName())->setValue(sampler);
  163. SAFE_RELEASE(sampler);
  164. // Define the vertex format for the batch
  165. VertexFormat::Element vertexElements[] =
  166. {
  167. VertexFormat::Element(VertexFormat::POSITION, 3),
  168. VertexFormat::Element(VertexFormat::TEXCOORD0, 2),
  169. VertexFormat::Element(VertexFormat::COLOR, 4)
  170. };
  171. VertexFormat vertexFormat(vertexElements, 3);
  172. // Create the mesh batch
  173. MeshBatch* meshBatch = MeshBatch::create(vertexFormat, Mesh::TRIANGLE_STRIP, material, true, initialCapacity > 0 ? initialCapacity : SPRITE_BATCH_DEFAULT_SIZE);
  174. material->release(); // don't call SAFE_RELEASE since material is used below
  175. // Create the batch
  176. SpriteBatch* batch = new SpriteBatch();
  177. batch->_customEffect = customEffect;
  178. batch->_batch = meshBatch;
  179. batch->_textureWidthRatio = 1.0f / (float)texture->getWidth();
  180. batch->_textureHeightRatio = 1.0f / (float)texture->getHeight();
  181. // Bind an ortho projection to the material by default (user can override with setProjectionMatrix)
  182. material->getParameter("u_projectionMatrix")->bindValue(batch, &SpriteBatch::getOrthoMatrix);
  183. return batch;
  184. }
  185. void SpriteBatch::begin()
  186. {
  187. _batch->begin();
  188. }
  189. void SpriteBatch::draw(const Rectangle& dst, const Rectangle& src, const Vector4& color)
  190. {
  191. // Calculate uvs.
  192. float u1 = _textureWidthRatio * src.x;
  193. float v1 = 1.0f - _textureHeightRatio * src.y;
  194. float u2 = u1 + _textureWidthRatio * src.width;
  195. float v2 = v1 - _textureHeightRatio * src.height;
  196. draw(dst.x, dst.y, dst.width, dst.height, u1, v1, u2, v2, color);
  197. }
  198. void SpriteBatch::draw(const Vector3& dst, const Rectangle& src, const Vector2& scale, const Vector4& color)
  199. {
  200. // Calculate uvs.
  201. float u1 = _textureWidthRatio * src.x;
  202. float v1 = 1.0f - _textureHeightRatio * src.y;
  203. float u2 = u1 + _textureWidthRatio * src.width;
  204. float v2 = v1 - _textureHeightRatio * src.height;
  205. draw(dst.x, dst.y, dst.z, scale.x, scale.y, u2, v2, u1, v1, color);
  206. }
  207. void SpriteBatch::draw(const Vector3& dst, const Rectangle& src, const Vector2& scale, const Vector4& color,
  208. const Vector2& rotationPoint, float rotationAngle)
  209. {
  210. // Calculate uvs.
  211. float u1 = _textureWidthRatio * src.x;
  212. float v1 = 1.0f - _textureHeightRatio * src.y;
  213. float u2 = u1 + _textureWidthRatio * src.width;
  214. float v2 = v1 - _textureHeightRatio * src.height;
  215. draw(dst, scale.x, scale.y, u1, v1, u2, v2, color, rotationPoint, rotationAngle);
  216. }
  217. void SpriteBatch::draw(const Vector3& dst, float width, float height, float u1, float v1, float u2, float v2, const Vector4& color,
  218. const Vector2& rotationPoint, float rotationAngle, bool positionIsCenter)
  219. {
  220. float x = dst.x;
  221. float y = dst.y;
  222. // Treat the given position as the center if the user specified it as such.
  223. if (positionIsCenter)
  224. {
  225. x -= 0.5f * width;
  226. y -= 0.5f * height;
  227. }
  228. // Expand the destination position by scale into 4 points.
  229. float x2 = x + width;
  230. float y2 = y + height;
  231. Vector2 upLeft(x, y);
  232. Vector2 upRight(x2, y);
  233. Vector2 downLeft(x, y2);
  234. Vector2 downRight(x2, y2);
  235. // Rotate points around rotationAxis by rotationAngle.
  236. Vector2 pivotPoint(rotationPoint);
  237. pivotPoint.x *= width;
  238. pivotPoint.y *= height;
  239. pivotPoint.x += x;
  240. pivotPoint.y += y;
  241. upLeft.rotate(pivotPoint, rotationAngle);
  242. upRight.rotate(pivotPoint, rotationAngle);
  243. downLeft.rotate(pivotPoint, rotationAngle);
  244. downRight.rotate(pivotPoint, rotationAngle);
  245. // Write sprite vertex data.
  246. static SpriteVertex v[4];
  247. ADD_SPRITE_VERTEX(v[0], upLeft.x, upLeft.y, dst.z, u1, v1, color.x, color.y, color.z, color.w);
  248. ADD_SPRITE_VERTEX(v[1], upRight.x, upRight.y, dst.z, u1, v2, color.x, color.y, color.z, color.w);
  249. ADD_SPRITE_VERTEX(v[2], downLeft.x, downLeft.y, dst.z, u2, v1, color.x, color.y, color.z, color.w);
  250. ADD_SPRITE_VERTEX(v[3], downRight.x, downRight.y, dst.z, u2, v2, color.x, color.y, color.z, color.w);
  251. static unsigned short indices[4] = { 0, 1, 2, 3 };
  252. _batch->add(v, 4, indices, 4);
  253. }
  254. void SpriteBatch::draw(const Vector3& position, const Vector3& right, const Vector3& forward, float width, float height,
  255. float u1, float v1, float u2, float v2, const Vector4& color, const Vector2& rotationPoint, float rotationAngle)
  256. {
  257. // Calculate the vertex positions.
  258. Vector3 p[4];
  259. p[0] = position - 0.5f * width * right - 0.5f * height * forward;
  260. p[1] = position + 0.5f * width * right - 0.5f * height * forward;
  261. p[2] = p[0] + height * forward;
  262. p[3] = p[1] + height * forward;
  263. // Calculate the rotation point.
  264. Vector3 rp = p[0] + (rotationPoint.x * width * right) + (rotationPoint.y * height * forward);
  265. // Rotate all points the specified amount about the given point (about the up vector).
  266. Vector3 u;
  267. Vector3::cross(right, forward, &u);
  268. Matrix rotation;
  269. Matrix::createRotation(u, rotationAngle, &rotation);
  270. p[0] = (rotation * (p[0] - rp)) + rp;
  271. p[1] = (rotation * (p[1] - rp)) + rp;
  272. p[2] = (rotation * (p[2] - rp)) + rp;
  273. p[3] = (rotation * (p[3] - rp)) + rp;
  274. // Add the sprite vertex data to the batch.
  275. static SpriteVertex v[4];
  276. ADD_SPRITE_VERTEX(v[0], p[0].x, p[0].y, p[0].z, u1, v1, color.x, color.y, color.z, color.w);
  277. ADD_SPRITE_VERTEX(v[1], p[1].x, p[1].y, p[1].z, u2, v1, color.x, color.y, color.z, color.w);
  278. ADD_SPRITE_VERTEX(v[2], p[2].x, p[2].y, p[2].z, u1, v2, color.x, color.y, color.z, color.w);
  279. ADD_SPRITE_VERTEX(v[3], p[3].x, p[3].y, p[3].z, u2, v2, color.x, color.y, color.z, color.w);
  280. static const unsigned short indices[4] = { 0, 1, 2, 3 };
  281. _batch->add(v, 4, const_cast<unsigned short*>(indices), 4);
  282. }
  283. void SpriteBatch::draw(float x, float y, float width, float height, float u1, float v1, float u2, float v2, const Vector4& color)
  284. {
  285. draw(x, y, 0, width, height, u1, v1, u2, v2, color);
  286. }
  287. void SpriteBatch::draw(float x, float y, float width, float height, float u1, float v1, float u2, float v2, const Vector4& color, const Rectangle& clip)
  288. {
  289. // Need to clip the rectangle given by { x, y, width, height } into clip by potentially:
  290. // - Moving x to the right.
  291. // - Moving y down.
  292. // - Moving width to the left.
  293. // - Moving height up.
  294. // - A combination of the above.
  295. // - Not drawing at all.
  296. //
  297. // We need to scale the uvs accordingly as we do this.
  298. // First check to see if we need to draw at all.
  299. if (x + width < clip.x || x > clip.x + clip.width ||
  300. y + height < clip.y || y > clip.y + clip.height)
  301. {
  302. return;
  303. }
  304. const float uvWidth = u2 - u1;
  305. const float uvHeight = v2 - v1;
  306. // Moving x to the right.
  307. if (x < clip.x)
  308. {
  309. const float percent = (clip.x - x) / width;
  310. x = clip.x;
  311. u1 += uvWidth * percent;
  312. }
  313. // Moving y down.
  314. if (y < clip.y)
  315. {
  316. const float percent = (clip.y - y) / height;
  317. y = clip.y;
  318. v1 += uvHeight * percent;
  319. }
  320. // Moving width to the left.
  321. const float clipX2 = clip.x + clip.width;
  322. float x2 = x + width;
  323. if (x2 > clipX2)
  324. {
  325. const float percent = (x2 - clipX2) / width;
  326. width = clipX2 - x;
  327. u2 -= uvWidth * percent;
  328. }
  329. // Moving height up.
  330. const float clipY2 = clip.y + clip.height;
  331. float y2 = y + height;
  332. if (y2 > clipY2)
  333. {
  334. const float percent = (y2 - clipY2) / height;
  335. height = clipY2 - y;
  336. v2 -= uvHeight * percent;
  337. }
  338. // Now we can perform a normal draw call.
  339. draw(x, y, 0, width, height, u1, v1, u2, v2, color);
  340. }
  341. void SpriteBatch::draw(float x, float y, float z, float width, float height, float u1, float v1, float u2, float v2, const Vector4& color, bool positionIsCenter)
  342. {
  343. // Treat the given position as the center if the user specified it as such.
  344. if (positionIsCenter)
  345. {
  346. x -= 0.5f * width;
  347. y -= 0.5f * height;
  348. }
  349. // Write sprite vertex data.
  350. const float x2 = x + width;
  351. const float y2 = y + height;
  352. static SpriteVertex v[4];
  353. ADD_SPRITE_VERTEX(v[0], x, y, z, u1, v1, color.x, color.y, color.z, color.w);
  354. ADD_SPRITE_VERTEX(v[1], x, y2, z, u1, v2, color.x, color.y, color.z, color.w);
  355. ADD_SPRITE_VERTEX(v[2], x2, y, z, u2, v1, color.x, color.y, color.z, color.w);
  356. ADD_SPRITE_VERTEX(v[3], x2, y2, z, u2, v2, color.x, color.y, color.z, color.w);
  357. static unsigned short indices[4] = { 0, 1, 2, 3 };
  358. _batch->add(v, 4, indices, 4);
  359. }
  360. void SpriteBatch::end()
  361. {
  362. // Finish and draw the batch
  363. _batch->end();
  364. _batch->draw();
  365. }
  366. RenderState::StateBlock* SpriteBatch::getStateBlock() const
  367. {
  368. return _batch->getMaterial()->getStateBlock();
  369. }
  370. Material* SpriteBatch::getMaterial()
  371. {
  372. return _batch->getMaterial();
  373. }
  374. void SpriteBatch::setProjectionMatrix(const Matrix& matrix)
  375. {
  376. // Bind the specified matrix to a parameter named 'u_projectionMatrix' (assumed to exist).
  377. _batch->getMaterial()->getParameter("u_projectionMatrix")->setValue(matrix);
  378. }
  379. const Matrix& SpriteBatch::getOrthoMatrix() const
  380. {
  381. // Update matrix with ortho projection and return it.
  382. Game* game = Game::getInstance();
  383. Matrix::createOrthographicOffCenter(0, game->getWidth(), game->getHeight(), 0, 0, 1, &_projectionMatrix);
  384. return _projectionMatrix;
  385. }
  386. }