SpriteBatch.cpp 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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. array_buf = gfx->newBuffer(vertex_size, nullptr, BUFFERFLAG_VERTEX, usage, Buffer::MAP_EXPLICIT_RANGE_MODIFY);
  57. }
  58. SpriteBatch::~SpriteBatch()
  59. {
  60. delete array_buf;
  61. }
  62. int SpriteBatch::add(const Matrix4 &m, int index /*= -1*/)
  63. {
  64. return add(texture->getQuad(), m, index);
  65. }
  66. int SpriteBatch::add(Quad *quad, const Matrix4 &m, int index /*= -1*/)
  67. {
  68. if (vertex_format == CommonFormat::XYf_STPf_RGBAub)
  69. return addLayer(quad->getLayer(), quad, m, index);
  70. if (index < -1 || index >= size)
  71. throw love::Exception("Invalid sprite index: %d", index + 1);
  72. if (index == -1 && next >= size)
  73. setBufferSize(size * 2);
  74. const Vector2 *quadpositions = quad->getVertexPositions();
  75. const Vector2 *quadtexcoords = quad->getVertexTexCoords();
  76. // Always keep the buffer mapped when adding data (it'll be unmapped on draw.)
  77. size_t offset = (index == -1 ? next : index) * vertex_stride * 4;
  78. auto verts = (XYf_STf_RGBAub *) ((uint8 *) array_buf->map() + offset);
  79. m.transformXY(verts, quadpositions, 4);
  80. for (int i = 0; i < 4; i++)
  81. {
  82. verts[i].s = quadtexcoords[i].x;
  83. verts[i].t = quadtexcoords[i].y;
  84. verts[i].color = color;
  85. }
  86. array_buf->setMappedRangeModified(offset, vertex_stride * 4);
  87. // Increment counter.
  88. if (index == -1)
  89. return next++;
  90. return index;
  91. }
  92. int SpriteBatch::addLayer(int layer, const Matrix4 &m, int index)
  93. {
  94. return addLayer(layer, texture->getQuad(), m, index);
  95. }
  96. int SpriteBatch::addLayer(int layer, Quad *quad, const Matrix4 &m, int index)
  97. {
  98. if (vertex_format != CommonFormat::XYf_STPf_RGBAub)
  99. throw love::Exception("addLayer can only be called on a SpriteBatch that uses an Array Texture!");
  100. if (index < -1 || index >= size)
  101. throw love::Exception("Invalid sprite index: %d", index + 1);
  102. if (layer < 0 || layer >= texture->getLayerCount())
  103. throw love::Exception("Invalid layer: %d (Texture has %d layers)", layer + 1, texture->getLayerCount());
  104. if (index == -1 && next >= size)
  105. setBufferSize(size * 2);
  106. const Vector2 *quadpositions = quad->getVertexPositions();
  107. const Vector2 *quadtexcoords = quad->getVertexTexCoords();
  108. // Always keep the buffer mapped when adding data (it'll be unmapped on draw.)
  109. size_t offset = (index == -1 ? next : index) * vertex_stride * 4;
  110. auto verts = (XYf_STPf_RGBAub *) ((uint8 *) array_buf->map() + offset);
  111. m.transformXY(verts, quadpositions, 4);
  112. for (int i = 0; i < 4; i++)
  113. {
  114. verts[i].s = quadtexcoords[i].x;
  115. verts[i].t = quadtexcoords[i].y;
  116. verts[i].p = (float) layer;
  117. verts[i].color = color;
  118. }
  119. array_buf->setMappedRangeModified(offset, vertex_stride * 4);
  120. // Increment counter.
  121. if (index == -1)
  122. return next++;
  123. return index;
  124. }
  125. void SpriteBatch::clear()
  126. {
  127. // Reset the position of the next index.
  128. next = 0;
  129. }
  130. void SpriteBatch::flush()
  131. {
  132. array_buf->unmap();
  133. }
  134. void SpriteBatch::setTexture(Texture *newtexture)
  135. {
  136. if (texture->getTextureType() != newtexture->getTextureType())
  137. throw love::Exception("Texture must have the same texture type as the SpriteBatch's previous texture.");
  138. texture.set(newtexture);
  139. }
  140. Texture *SpriteBatch::getTexture() const
  141. {
  142. return texture.get();
  143. }
  144. void SpriteBatch::setColor(const Colorf &c)
  145. {
  146. colorf.r = std::min(std::max(c.r, 0.0f), 1.0f);
  147. colorf.g = std::min(std::max(c.g, 0.0f), 1.0f);
  148. colorf.b = std::min(std::max(c.b, 0.0f), 1.0f);
  149. colorf.a = std::min(std::max(c.a, 0.0f), 1.0f);
  150. color = toColor32(colorf);
  151. }
  152. Colorf SpriteBatch::getColor() const
  153. {
  154. return colorf;
  155. }
  156. int SpriteBatch::getCount() const
  157. {
  158. return next;
  159. }
  160. void SpriteBatch::setBufferSize(int newsize)
  161. {
  162. if (newsize <= 0)
  163. throw love::Exception("Invalid SpriteBatch size.");
  164. if (newsize == size)
  165. return;
  166. size_t vertex_size = vertex_stride * 4 * newsize;
  167. love::graphics::Buffer *new_array_buf = nullptr;
  168. int new_next = std::min(next, newsize);
  169. try
  170. {
  171. auto gfx = Module::getInstance<graphics::Graphics>(Module::M_GRAPHICS);
  172. new_array_buf = gfx->newBuffer(vertex_size, nullptr, array_buf->getTypeFlags(), array_buf->getUsage(), array_buf->getMapFlags());
  173. // Copy as much of the old data into the new GLBuffer as can fit.
  174. size_t copy_size = vertex_stride * 4 * new_next;
  175. array_buf->copyTo(0, copy_size, new_array_buf, 0);
  176. }
  177. catch (love::Exception &)
  178. {
  179. delete new_array_buf;
  180. throw;
  181. }
  182. // We don't need to unmap the old GLBuffer since we're deleting it.
  183. delete array_buf;
  184. array_buf = new_array_buf;
  185. size = newsize;
  186. next = new_next;
  187. }
  188. int SpriteBatch::getBufferSize() const
  189. {
  190. return size;
  191. }
  192. void SpriteBatch::attachAttribute(const std::string &name, Buffer *buffer)
  193. {
  194. if ((buffer->getTypeFlags() & BUFFER_VERTEX) == 0)
  195. throw love::Exception("GraphicsBuffer must be created with vertex buffer support to be used as a SpriteBatch vertex attribute.");
  196. AttachedAttribute oldattrib = {};
  197. AttachedAttribute newattrib = {};
  198. if (buffer->getArrayLength() < (size_t) next * 4)
  199. throw love::Exception("Buffer has too few vertices to be attached to this SpriteBatch (at least %d vertices are required)", next*4);
  200. auto it = attached_attributes.find(name);
  201. if (it != attached_attributes.end())
  202. oldattrib = it->second;
  203. newattrib.index = buffer->getDataMemberIndex(name);
  204. if (newattrib.index < 0)
  205. throw love::Exception("The specified Buffer does not have a vertex attribute named '%s'", name.c_str());
  206. newattrib.buffer = buffer;
  207. attached_attributes[name] = newattrib;
  208. }
  209. void SpriteBatch::setDrawRange(int start, int count)
  210. {
  211. if (start < 0 || count <= 0)
  212. throw love::Exception("Invalid draw range.");
  213. range_start = start;
  214. range_count = count;
  215. }
  216. void SpriteBatch::setDrawRange()
  217. {
  218. range_start = range_count = -1;
  219. }
  220. bool SpriteBatch::getDrawRange(int &start, int &count) const
  221. {
  222. if (range_start < 0 || range_count <= 0)
  223. return false;
  224. start = range_start;
  225. count = range_count;
  226. return true;
  227. }
  228. void SpriteBatch::draw(Graphics *gfx, const Matrix4 &m)
  229. {
  230. if (next == 0)
  231. return;
  232. gfx->flushStreamDraws();
  233. if (texture.get())
  234. {
  235. if (Shader::isDefaultActive())
  236. {
  237. Shader::StandardShader defaultshader = Shader::STANDARD_DEFAULT;
  238. if (texture->getTextureType() == TEXTURE_2D_ARRAY)
  239. defaultshader = Shader::STANDARD_ARRAY;
  240. Shader::attachDefault(defaultshader);
  241. }
  242. if (Shader::current)
  243. Shader::current->checkMainTexture(texture);
  244. }
  245. // Make sure the buffer isn't mapped when we draw (sends data to GPU if needed.)
  246. array_buf->unmap();
  247. VertexAttributes attributes;
  248. BufferBindings buffers;
  249. {
  250. buffers.set(0, array_buf, 0);
  251. attributes.setCommonFormat(vertex_format, 0);
  252. }
  253. int activebuffers = 1;
  254. for (const auto &it : attached_attributes)
  255. {
  256. Buffer *buffer = it.second.buffer.get();
  257. // We have to do this check here as wll because setBufferSize can be
  258. // called after attachAttribute.
  259. if (buffer->getArrayLength() < (size_t) next * 4)
  260. throw love::Exception("Buffer with attribute '%s' attached to this SpriteBatch has too few vertices", it.first.c_str());
  261. int attributeindex = -1;
  262. // If the attribute is one of the LOVE-defined ones, use the constant
  263. // attribute index for it, otherwise query the index from the shader.
  264. BuiltinVertexAttribute builtinattrib;
  265. if (getConstant(it.first.c_str(), builtinattrib))
  266. attributeindex = (int) builtinattrib;
  267. else if (Shader::current)
  268. attributeindex = Shader::current->getVertexAttributeIndex(it.first);
  269. if (attributeindex >= 0)
  270. {
  271. // Make sure the buffer isn't mapped (sends data to GPU if needed.)
  272. buffer->unmap();
  273. const auto &member = buffer->getDataMember(it.second.index);
  274. uint16 offset = (uint16) buffer->getMemberOffset(it.second.index);
  275. uint16 stride = (uint16) buffer->getArrayStride();
  276. attributes.set(attributeindex, member.format, offset, activebuffers);
  277. attributes.setBufferLayout(activebuffers, stride);
  278. // TODO: We should reuse buffer bindings with the same buffer+stride+step.
  279. buffers.set(activebuffers, buffer, 0);
  280. activebuffers++;
  281. }
  282. }
  283. Graphics::TempTransform transform(gfx, m);
  284. int start = std::min(std::max(0, range_start), next - 1);
  285. int count = next;
  286. if (range_count > 0)
  287. count = std::min(count, range_count);
  288. count = std::min(count, next - start);
  289. if (count > 0)
  290. gfx->drawQuads(start, count, attributes, buffers, texture);
  291. }
  292. } // graphics
  293. } // love