SpriteBatch.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  1. /**
  2. * Copyright (c) 2006-2020 LOVE Development Team
  3. *
  4. * This software is provided 'as-is', without any express or implied
  5. * warranty. In no event will the authors be held liable for any damages
  6. * arising from the use of this software.
  7. *
  8. * Permission is granted to anyone to use this software for any purpose,
  9. * including commercial applications, and to alter it and redistribute it
  10. * freely, subject to the following restrictions:
  11. *
  12. * 1. The origin of this software must not be misrepresented; you must not
  13. * claim that you wrote the original software. If you use this software
  14. * in a product, an acknowledgment in the product documentation would be
  15. * appreciated but is not required.
  16. * 2. Altered source versions must be plainly marked as such, and must not be
  17. * misrepresented as being the original software.
  18. * 3. This notice may not be removed or altered from any source distribution.
  19. **/
  20. #include "common/config.h"
  21. #include "SpriteBatch.h"
  22. // LOVE
  23. #include "Texture.h"
  24. #include "Quad.h"
  25. #include "Graphics.h"
  26. #include "Buffer.h"
  27. // C++
  28. #include <algorithm>
  29. // C
  30. #include <stddef.h>
  31. namespace love
  32. {
  33. namespace graphics
  34. {
  35. love::Type SpriteBatch::type("SpriteBatch", &Drawable::type);
  36. SpriteBatch::SpriteBatch(Graphics *gfx, Texture *texture, int size, BufferUsage usage)
  37. : texture(texture)
  38. , size(size)
  39. , next(0)
  40. , color(255, 255, 255, 255)
  41. , colorf(1.0f, 1.0f, 1.0f, 1.0f)
  42. , array_buf(nullptr)
  43. , range_start(-1)
  44. , range_count(-1)
  45. {
  46. if (size <= 0)
  47. throw love::Exception("Invalid SpriteBatch size.");
  48. if (texture == nullptr)
  49. throw love::Exception("A texture must be used when creating a SpriteBatch.");
  50. if (texture->getTextureType() == TEXTURE_2D_ARRAY)
  51. vertex_format = CommonFormat::XYf_STPf_RGBAub;
  52. else
  53. vertex_format = CommonFormat::XYf_STf_RGBAub;
  54. vertex_stride = getFormatStride(vertex_format);
  55. size_t vertex_size = vertex_stride * 4 * size;
  56. Buffer::Settings settings(Buffer::TYPEFLAG_VERTEX, Buffer::MAP_EXPLICIT_RANGE_MODIFY, usage);
  57. auto decl = Buffer::getCommonFormatDeclaration(vertex_format);
  58. array_buf = gfx->newBuffer(settings, decl, nullptr, vertex_size, 0);
  59. }
  60. SpriteBatch::~SpriteBatch()
  61. {
  62. delete array_buf;
  63. }
  64. int SpriteBatch::add(const Matrix4 &m, int index /*= -1*/)
  65. {
  66. return add(texture->getQuad(), m, index);
  67. }
  68. int SpriteBatch::add(Quad *quad, const Matrix4 &m, int index /*= -1*/)
  69. {
  70. if (vertex_format == CommonFormat::XYf_STPf_RGBAub)
  71. return addLayer(quad->getLayer(), quad, m, index);
  72. if (index < -1 || index >= size)
  73. throw love::Exception("Invalid sprite index: %d", index + 1);
  74. if (index == -1 && next >= size)
  75. setBufferSize(size * 2);
  76. const Vector2 *quadpositions = quad->getVertexPositions();
  77. const Vector2 *quadtexcoords = quad->getVertexTexCoords();
  78. // Always keep the buffer mapped when adding data (it'll be unmapped on draw.)
  79. size_t offset = (index == -1 ? next : index) * vertex_stride * 4;
  80. auto verts = (XYf_STf_RGBAub *) ((uint8 *) array_buf->map() + offset);
  81. m.transformXY(verts, quadpositions, 4);
  82. for (int i = 0; i < 4; i++)
  83. {
  84. verts[i].s = quadtexcoords[i].x;
  85. verts[i].t = quadtexcoords[i].y;
  86. verts[i].color = color;
  87. }
  88. array_buf->setMappedRangeModified(offset, vertex_stride * 4);
  89. // Increment counter.
  90. if (index == -1)
  91. return next++;
  92. return index;
  93. }
  94. int SpriteBatch::addLayer(int layer, const Matrix4 &m, int index)
  95. {
  96. return addLayer(layer, texture->getQuad(), m, index);
  97. }
  98. int SpriteBatch::addLayer(int layer, Quad *quad, const Matrix4 &m, int index)
  99. {
  100. if (vertex_format != CommonFormat::XYf_STPf_RGBAub)
  101. throw love::Exception("addLayer can only be called on a SpriteBatch that uses an Array Texture!");
  102. if (index < -1 || index >= size)
  103. throw love::Exception("Invalid sprite index: %d", index + 1);
  104. if (layer < 0 || layer >= texture->getLayerCount())
  105. throw love::Exception("Invalid layer: %d (Texture has %d layers)", layer + 1, texture->getLayerCount());
  106. if (index == -1 && next >= size)
  107. setBufferSize(size * 2);
  108. const Vector2 *quadpositions = quad->getVertexPositions();
  109. const Vector2 *quadtexcoords = quad->getVertexTexCoords();
  110. // Always keep the buffer mapped when adding data (it'll be unmapped on draw.)
  111. size_t offset = (index == -1 ? next : index) * vertex_stride * 4;
  112. auto verts = (XYf_STPf_RGBAub *) ((uint8 *) array_buf->map() + offset);
  113. m.transformXY(verts, quadpositions, 4);
  114. for (int i = 0; i < 4; i++)
  115. {
  116. verts[i].s = quadtexcoords[i].x;
  117. verts[i].t = quadtexcoords[i].y;
  118. verts[i].p = (float) layer;
  119. verts[i].color = color;
  120. }
  121. array_buf->setMappedRangeModified(offset, vertex_stride * 4);
  122. // Increment counter.
  123. if (index == -1)
  124. return next++;
  125. return index;
  126. }
  127. void SpriteBatch::clear()
  128. {
  129. // Reset the position of the next index.
  130. next = 0;
  131. }
  132. void SpriteBatch::flush()
  133. {
  134. array_buf->unmap();
  135. }
  136. void SpriteBatch::setTexture(Texture *newtexture)
  137. {
  138. if (texture->getTextureType() != newtexture->getTextureType())
  139. throw love::Exception("Texture must have the same type as the SpriteBatch's previous texture.");
  140. texture.set(newtexture);
  141. }
  142. Texture *SpriteBatch::getTexture() const
  143. {
  144. return texture.get();
  145. }
  146. void SpriteBatch::setColor(const Colorf &c)
  147. {
  148. colorf.r = std::min(std::max(c.r, 0.0f), 1.0f);
  149. colorf.g = std::min(std::max(c.g, 0.0f), 1.0f);
  150. colorf.b = std::min(std::max(c.b, 0.0f), 1.0f);
  151. colorf.a = std::min(std::max(c.a, 0.0f), 1.0f);
  152. color = toColor32(colorf);
  153. }
  154. Colorf SpriteBatch::getColor() const
  155. {
  156. return colorf;
  157. }
  158. int SpriteBatch::getCount() const
  159. {
  160. return next;
  161. }
  162. void SpriteBatch::setBufferSize(int newsize)
  163. {
  164. if (newsize <= 0)
  165. throw love::Exception("Invalid SpriteBatch size.");
  166. if (newsize == size)
  167. return;
  168. size_t vertex_size = vertex_stride * 4 * newsize;
  169. love::graphics::Buffer *new_array_buf = nullptr;
  170. int new_next = std::min(next, newsize);
  171. try
  172. {
  173. auto gfx = Module::getInstance<graphics::Graphics>(Module::M_GRAPHICS);
  174. Buffer::Settings settings(array_buf->getTypeFlags(), array_buf->getMapFlags(), array_buf->getUsage());
  175. auto decl = Buffer::getCommonFormatDeclaration(vertex_format);
  176. new_array_buf = gfx->newBuffer(settings, decl, nullptr, vertex_size, 0);
  177. // Copy as much of the old data into the new GLBuffer as can fit.
  178. size_t copy_size = vertex_stride * 4 * new_next;
  179. array_buf->copyTo(0, copy_size, new_array_buf, 0);
  180. }
  181. catch (love::Exception &)
  182. {
  183. delete new_array_buf;
  184. throw;
  185. }
  186. // We don't need to unmap the old GLBuffer since we're deleting it.
  187. delete array_buf;
  188. array_buf = new_array_buf;
  189. size = newsize;
  190. next = new_next;
  191. }
  192. int SpriteBatch::getBufferSize() const
  193. {
  194. return size;
  195. }
  196. void SpriteBatch::attachAttribute(const std::string &name, Buffer *buffer)
  197. {
  198. if ((buffer->getTypeFlags() & Buffer::TYPEFLAG_VERTEX) == 0)
  199. throw love::Exception("GraphicsBuffer must be created with vertex buffer support to be used as a SpriteBatch vertex attribute.");
  200. AttachedAttribute oldattrib = {};
  201. AttachedAttribute newattrib = {};
  202. if (buffer->getArrayLength() < (size_t) next * 4)
  203. throw love::Exception("Buffer has too few vertices to be attached to this SpriteBatch (at least %d vertices are required)", next*4);
  204. auto it = attached_attributes.find(name);
  205. if (it != attached_attributes.end())
  206. oldattrib = it->second;
  207. newattrib.index = buffer->getDataMemberIndex(name);
  208. if (newattrib.index < 0)
  209. throw love::Exception("The specified Buffer does not have a vertex attribute named '%s'", name.c_str());
  210. newattrib.buffer = buffer;
  211. attached_attributes[name] = newattrib;
  212. }
  213. void SpriteBatch::setDrawRange(int start, int count)
  214. {
  215. if (start < 0 || count <= 0)
  216. throw love::Exception("Invalid draw range.");
  217. range_start = start;
  218. range_count = count;
  219. }
  220. void SpriteBatch::setDrawRange()
  221. {
  222. range_start = range_count = -1;
  223. }
  224. bool SpriteBatch::getDrawRange(int &start, int &count) const
  225. {
  226. if (range_start < 0 || range_count <= 0)
  227. return false;
  228. start = range_start;
  229. count = range_count;
  230. return true;
  231. }
  232. void SpriteBatch::draw(Graphics *gfx, const Matrix4 &m)
  233. {
  234. if (next == 0)
  235. return;
  236. gfx->flushBatchedDraws();
  237. if (texture.get())
  238. {
  239. if (Shader::isDefaultActive())
  240. {
  241. Shader::StandardShader defaultshader = Shader::STANDARD_DEFAULT;
  242. if (texture->getTextureType() == TEXTURE_2D_ARRAY)
  243. defaultshader = Shader::STANDARD_ARRAY;
  244. Shader::attachDefault(defaultshader);
  245. }
  246. if (Shader::current)
  247. Shader::current->checkMainTexture(texture);
  248. }
  249. // Make sure the buffer isn't mapped when we draw (sends data to GPU if needed.)
  250. array_buf->unmap();
  251. VertexAttributes attributes;
  252. BufferBindings buffers;
  253. {
  254. buffers.set(0, array_buf, 0);
  255. attributes.setCommonFormat(vertex_format, 0);
  256. }
  257. int activebuffers = 1;
  258. for (const auto &it : attached_attributes)
  259. {
  260. Buffer *buffer = it.second.buffer.get();
  261. // We have to do this check here as wll because setBufferSize can be
  262. // called after attachAttribute.
  263. if (buffer->getArrayLength() < (size_t) next * 4)
  264. throw love::Exception("Buffer with attribute '%s' attached to this SpriteBatch has too few vertices", it.first.c_str());
  265. int attributeindex = -1;
  266. // If the attribute is one of the LOVE-defined ones, use the constant
  267. // attribute index for it, otherwise query the index from the shader.
  268. BuiltinVertexAttribute builtinattrib;
  269. if (getConstant(it.first.c_str(), builtinattrib))
  270. attributeindex = (int) builtinattrib;
  271. else if (Shader::current)
  272. attributeindex = Shader::current->getVertexAttributeIndex(it.first);
  273. if (attributeindex >= 0)
  274. {
  275. // Make sure the buffer isn't mapped (sends data to GPU if needed.)
  276. buffer->unmap();
  277. const auto &member = buffer->getDataMember(it.second.index);
  278. uint16 offset = (uint16) buffer->getMemberOffset(it.second.index);
  279. uint16 stride = (uint16) buffer->getArrayStride();
  280. attributes.set(attributeindex, member.decl.format, offset, activebuffers);
  281. attributes.setBufferLayout(activebuffers, stride);
  282. // TODO: We should reuse buffer bindings with the same buffer+stride+step.
  283. buffers.set(activebuffers, buffer, 0);
  284. activebuffers++;
  285. }
  286. }
  287. Graphics::TempTransform transform(gfx, m);
  288. int start = std::min(std::max(0, range_start), next - 1);
  289. int count = next;
  290. if (range_count > 0)
  291. count = std::min(count, range_count);
  292. count = std::min(count, next - start);
  293. if (count > 0)
  294. gfx->drawQuads(start, count, attributes, buffers, texture);
  295. }
  296. } // graphics
  297. } // love