SpriteBatch.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. /**
  2. * Copyright (c) 2006-2024 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, BufferDataUsage 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. , attributesID()
  43. , array_buf(nullptr)
  44. , vertex_data(nullptr)
  45. , modified_sprites()
  46. , range_start(-1)
  47. , range_count(-1)
  48. {
  49. if (size <= 0)
  50. throw love::Exception("Invalid SpriteBatch size.");
  51. if (texture == nullptr)
  52. throw love::Exception("A texture must be used when creating a SpriteBatch.");
  53. if (texture->getTextureType() == TEXTURE_2D_ARRAY)
  54. vertex_format = CommonFormat::XYf_STPf_RGBAub;
  55. else
  56. vertex_format = CommonFormat::XYf_STf_RGBAub;
  57. vertex_stride = getFormatStride(vertex_format);
  58. size_t vertex_size = vertex_stride * 4 * size;
  59. vertex_data = (uint8 *) malloc(vertex_size);
  60. if (vertex_data == nullptr)
  61. throw love::Exception("Out of memory.");
  62. memset(vertex_data, 0, vertex_size);
  63. Buffer::Settings settings(BUFFERUSAGEFLAG_VERTEX, usage);
  64. auto decl = Buffer::getCommonFormatDeclaration(vertex_format);
  65. array_buf.set(gfx->newBuffer(settings, decl, nullptr, vertex_size, 0), Acquire::NORETAIN);
  66. }
  67. SpriteBatch::~SpriteBatch()
  68. {
  69. free(vertex_data);
  70. }
  71. int SpriteBatch::add(const Matrix4 &m, int index /*= -1*/)
  72. {
  73. return add(texture->getQuad(), m, index);
  74. }
  75. int SpriteBatch::add(Quad *quad, const Matrix4 &m, int index /*= -1*/)
  76. {
  77. if (vertex_format == CommonFormat::XYf_STPf_RGBAub)
  78. return addLayer(quad->getLayer(), quad, m, index);
  79. if (index < -1 || index >= size)
  80. throw love::Exception("Invalid sprite index: %d", index + 1);
  81. if (index == -1 && next >= size)
  82. setBufferSize(size * 2);
  83. const Vector2 *quadpositions = quad->getVertexPositions();
  84. const Vector2 *quadtexcoords = quad->getVertexTexCoords();
  85. int spriteindex = (index == -1 ? next : index);
  86. size_t offset = spriteindex * vertex_stride * 4;
  87. auto verts = (XYf_STf_RGBAub *) (vertex_data + offset);
  88. m.transformXY(verts, quadpositions, 4);
  89. for (int i = 0; i < 4; i++)
  90. {
  91. verts[i].s = quadtexcoords[i].x;
  92. verts[i].t = quadtexcoords[i].y;
  93. verts[i].color = color;
  94. }
  95. modified_sprites.encapsulate(spriteindex);
  96. // Increment counter.
  97. if (index == -1)
  98. return next++;
  99. return index;
  100. }
  101. int SpriteBatch::addLayer(int layer, const Matrix4 &m, int index)
  102. {
  103. return addLayer(layer, texture->getQuad(), m, index);
  104. }
  105. int SpriteBatch::addLayer(int layer, Quad *quad, const Matrix4 &m, int index)
  106. {
  107. if (vertex_format != CommonFormat::XYf_STPf_RGBAub)
  108. throw love::Exception("addLayer can only be called on a SpriteBatch that uses an Array Texture.");
  109. if (index < -1 || index >= size)
  110. throw love::Exception("Invalid sprite index: %d", index + 1);
  111. if (layer < 0 || layer >= texture->getLayerCount())
  112. throw love::Exception("Invalid layer: %d (Texture has %d layers)", layer + 1, texture->getLayerCount());
  113. if (index == -1 && next >= size)
  114. setBufferSize(size * 2);
  115. const Vector2 *quadpositions = quad->getVertexPositions();
  116. const Vector2 *quadtexcoords = quad->getVertexTexCoords();
  117. int spriteindex = (index == -1 ? next : index);
  118. size_t offset = spriteindex * vertex_stride * 4;
  119. auto verts = (XYf_STPf_RGBAub *) (vertex_data + offset);
  120. m.transformXY(verts, quadpositions, 4);
  121. for (int i = 0; i < 4; i++)
  122. {
  123. verts[i].s = quadtexcoords[i].x;
  124. verts[i].t = quadtexcoords[i].y;
  125. verts[i].p = (float) layer;
  126. verts[i].color = color;
  127. }
  128. modified_sprites.encapsulate(spriteindex);
  129. // Increment counter.
  130. if (index == -1)
  131. return next++;
  132. return index;
  133. }
  134. void SpriteBatch::clear()
  135. {
  136. // Reset the position of the next index.
  137. next = 0;
  138. }
  139. void SpriteBatch::flush()
  140. {
  141. if (modified_sprites.isValid())
  142. {
  143. size_t offset = modified_sprites.getOffset() * vertex_stride * 4;
  144. size_t size = modified_sprites.getSize() * vertex_stride * 4;
  145. if (array_buf->getDataUsage() == BUFFERDATAUSAGE_STREAM)
  146. array_buf->fill(0, array_buf->getSize(), vertex_data);
  147. else
  148. array_buf->fill(offset, size, vertex_data + offset);
  149. modified_sprites.invalidate();
  150. }
  151. }
  152. void SpriteBatch::setTexture(Texture *newtexture)
  153. {
  154. if (texture->getTextureType() != newtexture->getTextureType())
  155. throw love::Exception("Texture must have the same type as the SpriteBatch's previous texture.");
  156. texture.set(newtexture);
  157. }
  158. Texture *SpriteBatch::getTexture() const
  159. {
  160. return texture.get();
  161. }
  162. void SpriteBatch::setColor(const Colorf &c)
  163. {
  164. colorf.r = std::min(std::max(c.r, 0.0f), 1.0f);
  165. colorf.g = std::min(std::max(c.g, 0.0f), 1.0f);
  166. colorf.b = std::min(std::max(c.b, 0.0f), 1.0f);
  167. colorf.a = std::min(std::max(c.a, 0.0f), 1.0f);
  168. color = toColor32(colorf);
  169. }
  170. Colorf SpriteBatch::getColor() const
  171. {
  172. return colorf;
  173. }
  174. int SpriteBatch::getCount() const
  175. {
  176. return next;
  177. }
  178. void SpriteBatch::setBufferSize(int newsize)
  179. {
  180. if (newsize <= 0)
  181. throw love::Exception("Invalid SpriteBatch size.");
  182. if (newsize == size)
  183. return;
  184. size_t vertex_size = vertex_stride * 4 * newsize;
  185. int new_next = std::min(next, newsize);
  186. void *new_vertex_data = realloc(vertex_data, vertex_size);
  187. if (new_vertex_data == nullptr)
  188. throw love::Exception("Out of memory.");
  189. auto gfx = Module::getInstance<graphics::Graphics>(Module::M_GRAPHICS);
  190. Buffer::Settings settings(array_buf->getUsageFlags(), array_buf->getDataUsage());
  191. auto decl = Buffer::getCommonFormatDeclaration(vertex_format);
  192. array_buf.set(gfx->newBuffer(settings, decl, nullptr, vertex_size, 0), Acquire::NORETAIN);
  193. array_buf->fill(0, vertex_stride * 4 * new_next, new_vertex_data);
  194. vertex_data = (uint8 *) new_vertex_data;
  195. size = newsize;
  196. next = new_next;
  197. }
  198. int SpriteBatch::getBufferSize() const
  199. {
  200. return size;
  201. }
  202. void SpriteBatch::attachAttribute(const std::string &name, Buffer *buffer, Mesh *mesh)
  203. {
  204. if ((buffer->getUsageFlags() & BUFFERUSAGEFLAG_VERTEX) == 0)
  205. throw love::Exception("GraphicsBuffer must be created with vertex buffer support to be used as a SpriteBatch vertex attribute.");
  206. AttachedAttribute oldattrib = {};
  207. AttachedAttribute newattrib = {};
  208. if (buffer->getArrayLength() < (size_t) next * 4)
  209. throw love::Exception("Buffer has too few vertices to be attached to this SpriteBatch (at least %d vertices are required)", next*4);
  210. auto it = attached_attributes.find(name);
  211. if (it != attached_attributes.end())
  212. oldattrib = it->second;
  213. newattrib.index = buffer->getDataMemberIndex(name);
  214. if (newattrib.index < 0)
  215. throw love::Exception("The specified Buffer does not have a vertex attribute named '%s'", name.c_str());
  216. newattrib.buffer = buffer;
  217. newattrib.mesh = mesh;
  218. newattrib.bindingIndex = buffer->getDataMember(newattrib.index).decl.bindingLocation;
  219. BuiltinVertexAttribute builtinattrib;
  220. if (newattrib.bindingIndex < 0 && getConstant(name.c_str(), builtinattrib))
  221. newattrib.bindingIndex = (int)builtinattrib;
  222. attached_attributes[name] = newattrib;
  223. // Invalidate attributes ID.
  224. attributesID = VertexAttributesID();
  225. }
  226. void SpriteBatch::setDrawRange(int start, int count)
  227. {
  228. if (start < 0 || count <= 0)
  229. throw love::Exception("Invalid draw range.");
  230. range_start = start;
  231. range_count = count;
  232. }
  233. void SpriteBatch::setDrawRange()
  234. {
  235. range_start = range_count = -1;
  236. }
  237. bool SpriteBatch::getDrawRange(int &start, int &count) const
  238. {
  239. if (range_start < 0 || range_count <= 0)
  240. return false;
  241. start = range_start;
  242. count = range_count;
  243. return true;
  244. }
  245. void SpriteBatch::draw(Graphics *gfx, const Matrix4 &m)
  246. {
  247. if (next == 0)
  248. return;
  249. gfx->flushBatchedDraws();
  250. if (texture.get())
  251. {
  252. if (Shader::isDefaultActive())
  253. {
  254. Shader::StandardShader defaultshader = Shader::STANDARD_DEFAULT;
  255. if (texture->getTextureType() == TEXTURE_2D_ARRAY)
  256. defaultshader = Shader::STANDARD_ARRAY;
  257. Shader::attachDefault(defaultshader);
  258. }
  259. }
  260. if (Shader::current)
  261. Shader::current->validateDrawState(PRIMITIVE_TRIANGLES, texture);
  262. flush(); // Upload any modified sprite data to the GPU.
  263. bool attributesIDneedsupdate = !attributesID.isValid();
  264. VertexAttributes attributes;
  265. BufferBindings buffers;
  266. {
  267. buffers.set(0, array_buf, 0);
  268. attributes.setCommonFormat(vertex_format, 0);
  269. }
  270. int activebuffers = 1;
  271. for (const auto &it : attached_attributes)
  272. {
  273. Buffer *buffer = it.second.buffer.get();
  274. // We have to do this check here as wll because setBufferSize can be
  275. // called after attachAttribute.
  276. if (buffer->getArrayLength() < (size_t) next * 4)
  277. throw love::Exception("Buffer with attribute '%s' attached to this SpriteBatch has too few vertices", it.first.c_str());
  278. int bindingindex = it.second.bindingIndex;
  279. // If the attribute is one of the LOVE-defined ones, use the constant
  280. // attribute index for it, otherwise query the index from the shader.
  281. if (bindingindex < 0 && Shader::current)
  282. {
  283. bindingindex = Shader::current->getVertexAttributeIndex(it.first);
  284. attributesIDneedsupdate = true;
  285. }
  286. if (bindingindex >= 0)
  287. {
  288. if (it.second.mesh.get())
  289. it.second.mesh->flush();
  290. const auto &member = buffer->getDataMember(it.second.index);
  291. uint16 offset = (uint16) buffer->getMemberOffset(it.second.index);
  292. uint16 stride = (uint16) buffer->getArrayStride();
  293. attributes.set(bindingindex, member.decl.format, offset, activebuffers);
  294. attributes.setBufferLayout(activebuffers, stride);
  295. // TODO: We should reuse buffer bindings with the same buffer+stride+step.
  296. buffers.set(activebuffers, buffer, 0);
  297. activebuffers++;
  298. }
  299. }
  300. if (attributesIDneedsupdate)
  301. attributesID = gfx->registerVertexAttributes(attributes);
  302. Graphics::TempTransform transform(gfx, m);
  303. int start = std::min(std::max(0, range_start), next - 1);
  304. int count = next;
  305. if (range_count > 0)
  306. count = std::min(count, range_count);
  307. count = std::min(count, next - start);
  308. if (count > 0)
  309. {
  310. Texture *tex = gfx->getTextureOrDefaultForActiveShader(texture);
  311. gfx->drawQuads(start, count, attributesID, buffers, tex);
  312. }
  313. }
  314. } // graphics
  315. } // love