VertexBuffer.cpp 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. /**
  2. * Copyright (c) 2006-2013 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 "VertexBuffer.h"
  21. #include "common/Exception.h"
  22. #include "common/config.h"
  23. #include <cstdlib>
  24. #include <cstring>
  25. #include <algorithm>
  26. #include <limits>
  27. // Conflicts with std::numeric_limits<GLushort>::max() (Windows).
  28. #ifdef max
  29. # undef max
  30. #endif
  31. namespace love
  32. {
  33. namespace graphics
  34. {
  35. namespace opengl
  36. {
  37. // VertexBuffer
  38. VertexBuffer *VertexBuffer::Create(size_t size, GLenum target, GLenum usage, MemoryBacking backing)
  39. {
  40. try
  41. {
  42. // Try to create a VBO.
  43. return new VBO(size, target, usage, backing);
  44. }
  45. catch(const love::Exception &)
  46. {
  47. // VBO not supported ... create regular array.
  48. return new VertexArray(size, target, usage, backing);
  49. }
  50. }
  51. VertexBuffer::VertexBuffer(size_t size, GLenum target, GLenum usage, MemoryBacking backing)
  52. : is_bound(false)
  53. , is_mapped(false)
  54. , size(size)
  55. , target(target)
  56. , usage(usage)
  57. , backing(backing)
  58. {
  59. }
  60. VertexBuffer::~VertexBuffer()
  61. {
  62. }
  63. // VertexArray
  64. VertexArray::VertexArray(size_t size, GLenum target, GLenum usage, MemoryBacking backing)
  65. : VertexBuffer(size, target, usage, backing)
  66. , buf(new char[size])
  67. {
  68. }
  69. VertexArray::~VertexArray()
  70. {
  71. delete [] buf;
  72. }
  73. void *VertexArray::map()
  74. {
  75. is_mapped = true;
  76. return buf;
  77. }
  78. void VertexArray::unmap()
  79. {
  80. is_mapped = false;
  81. }
  82. void VertexArray::bind()
  83. {
  84. is_bound = true;
  85. }
  86. void VertexArray::unbind()
  87. {
  88. is_bound = false;
  89. }
  90. void VertexArray::fill(size_t offset, size_t size, const void *data)
  91. {
  92. memcpy(buf + offset, data, size);
  93. }
  94. const void *VertexArray::getPointer(size_t offset) const
  95. {
  96. return buf + offset;
  97. }
  98. // VBO
  99. VBO::VBO(size_t size, GLenum target, GLenum usage, MemoryBacking backing)
  100. : VertexBuffer(size, target, usage, backing)
  101. , vbo(0)
  102. , memory_map(0)
  103. , is_dirty(true)
  104. {
  105. if (!(GLEE_ARB_vertex_buffer_object || GLEE_VERSION_1_5))
  106. throw love::Exception("Not supported");
  107. if (getMemoryBacking() == BACKING_FULL)
  108. memory_map = malloc(getSize());
  109. bool ok = load(false);
  110. if (!ok)
  111. {
  112. free(memory_map);
  113. throw love::Exception("Could not load VBO.");
  114. }
  115. }
  116. VBO::~VBO()
  117. {
  118. if (vbo != 0)
  119. unload(false);
  120. if (memory_map)
  121. free(memory_map);
  122. }
  123. void *VBO::map()
  124. {
  125. if (is_mapped)
  126. return memory_map;
  127. if (!memory_map)
  128. {
  129. memory_map = malloc(getSize());
  130. if (!memory_map)
  131. throw love::Exception("Out of memory (oh the humanity!)");
  132. }
  133. if (is_dirty)
  134. {
  135. glGetBufferSubDataARB(getTarget(), 0, getSize(), memory_map);
  136. is_dirty = false;
  137. }
  138. is_mapped = true;
  139. return memory_map;
  140. }
  141. void VBO::unmap()
  142. {
  143. if (!is_mapped)
  144. return;
  145. // VBO::bind is a no-op when the VBO is mapped, so we have to make sure it's
  146. // bound here.
  147. if (!is_bound)
  148. {
  149. glBindBufferARB(getTarget(), vbo);
  150. is_bound = true;
  151. }
  152. // "orphan" current buffer to avoid implicit synchronisation on the GPU:
  153. // http://www.seas.upenn.edu/~pcozzi/OpenGLInsights/OpenGLInsights-AsynchronousBufferTransfers.pdf
  154. glBufferDataARB(getTarget(), getSize(), NULL, getUsage());
  155. glBufferDataARB(getTarget(), getSize(), memory_map, getUsage());
  156. is_mapped = false;
  157. }
  158. void VBO::bind()
  159. {
  160. if (!is_mapped)
  161. {
  162. glBindBufferARB(getTarget(), vbo);
  163. is_bound = true;
  164. }
  165. }
  166. void VBO::unbind()
  167. {
  168. if (is_bound)
  169. glBindBufferARB(getTarget(), 0);
  170. is_bound = false;
  171. }
  172. void VBO::fill(size_t offset, size_t size, const void *data)
  173. {
  174. if (is_mapped || getMemoryBacking() == BACKING_FULL)
  175. memcpy(static_cast<char *>(memory_map) + offset, data, size);
  176. if (!is_mapped)
  177. {
  178. // Not all systems have access to some faster paths...
  179. if (GLEE_APPLE_flush_buffer_range)
  180. {
  181. void *mapdata = glMapBufferARB(getTarget(), GL_WRITE_ONLY);
  182. if (mapdata)
  183. {
  184. // We specified in VBO::load that we'll do manual flushing.
  185. // Now we tell the driver it only needs to deal with the data
  186. // we changed.
  187. memcpy(static_cast<char *>(mapdata) + offset, data, size);
  188. glFlushMappedBufferRangeAPPLE(getTarget(), offset, size);
  189. }
  190. glUnmapBufferARB(getTarget());
  191. }
  192. else
  193. {
  194. // Fall back to a possibly slower SubData (more chance of syncing.)
  195. glBufferSubDataARB(getTarget(), offset, size, data);
  196. }
  197. if (getMemoryBacking() != BACKING_FULL)
  198. is_dirty = true;
  199. }
  200. }
  201. const void *VBO::getPointer(size_t offset) const
  202. {
  203. return BUFFER_OFFSET(offset);
  204. }
  205. bool VBO::loadVolatile()
  206. {
  207. return load(true);
  208. }
  209. void VBO::unloadVolatile()
  210. {
  211. unload(true);
  212. }
  213. bool VBO::load(bool restore)
  214. {
  215. glGenBuffersARB(1, &vbo);
  216. VertexBuffer::Bind bind(*this);
  217. // Copy the old buffer only if 'restore' was requested.
  218. const GLvoid *src = restore ? memory_map : 0;
  219. while (GL_NO_ERROR != glGetError())
  220. /* clear error messages */;
  221. // We don't want to flush the entire buffer when we just modify a small
  222. // portion of it (VBO::fill without VBO::map), so we'll handle the flushing
  223. // ourselves when we can.
  224. if (GLEE_APPLE_flush_buffer_range)
  225. glBufferParameteriAPPLE(getTarget(), GL_BUFFER_FLUSHING_UNMAP_APPLE, GL_FALSE);
  226. // Note that if 'src' is '0', no data will be copied.
  227. glBufferDataARB(getTarget(), getSize(), src, getUsage());
  228. GLenum err = glGetError();
  229. return (GL_NO_ERROR == err);
  230. }
  231. void VBO::unload(bool save)
  232. {
  233. // Save data before unloading, if we need to.
  234. if (save && getMemoryBacking() == BACKING_PARTIAL)
  235. {
  236. VertexBuffer::Bind bind(*this);
  237. bool mapped = is_mapped;
  238. map(); // saves buffer content to memory_map.
  239. is_mapped = mapped;
  240. }
  241. glDeleteBuffersARB(1, &vbo);
  242. vbo = 0;
  243. }
  244. // VertexIndex
  245. size_t VertexIndex::maxSize = 0;
  246. size_t VertexIndex::elementSize = 0;
  247. std::list<size_t> VertexIndex::sizeRefs;
  248. VertexBuffer *VertexIndex::element_array = NULL;
  249. VertexIndex::VertexIndex(size_t size)
  250. : size(size)
  251. {
  252. // The upper limit is the maximum of GLuint divided by six (the number
  253. // of indices per size) and divided by the size of GLuint. This guarantees
  254. // no overflows when calculating the array size in bytes.
  255. // Memory issues will be handled by other exceptions.
  256. if (size == 0 || size > ((GLuint) -1) / 6 / sizeof(GLuint))
  257. throw love::Exception("Invalid size.");
  258. addSize(size);
  259. }
  260. VertexIndex::~VertexIndex()
  261. {
  262. removeSize(size);
  263. }
  264. size_t VertexIndex::getSize() const
  265. {
  266. return size;
  267. }
  268. size_t VertexIndex::getIndexCount(size_t elements) const
  269. {
  270. return elements * 6;
  271. }
  272. GLenum VertexIndex::getType(size_t s) const
  273. {
  274. // Calculates if unsigned short is big enough to hold all the vertex indices.
  275. static const GLenum type_table[] = {GL_UNSIGNED_SHORT, GL_UNSIGNED_INT};
  276. return type_table[s * 4 > std::numeric_limits<GLushort>::max()];
  277. // if buffer-size > max(GLushort) then GL_UNSIGNED_INT else GL_UNSIGNED_SHORT
  278. }
  279. size_t VertexIndex::getElementSize()
  280. {
  281. return elementSize;
  282. }
  283. VertexBuffer *VertexIndex::getVertexBuffer() const
  284. {
  285. return element_array;
  286. }
  287. const void *VertexIndex::getPointer(size_t offset) const
  288. {
  289. return element_array->getPointer(offset);
  290. }
  291. void VertexIndex::addSize(size_t newSize)
  292. {
  293. if (newSize <= maxSize)
  294. {
  295. // Current size is bigger. Append the size to list and sort.
  296. sizeRefs.push_back(newSize);
  297. sizeRefs.sort();
  298. return;
  299. }
  300. // Try to resize before adding it to the list because resize may throw.
  301. resize(newSize);
  302. sizeRefs.push_back(newSize);
  303. }
  304. void VertexIndex::removeSize(size_t oldSize)
  305. {
  306. // TODO: For debugging purposes, this should check if the size was actually found.
  307. sizeRefs.erase(std::find(sizeRefs.begin(), sizeRefs.end(), oldSize));
  308. if (sizeRefs.size() == 0)
  309. {
  310. resize(0);
  311. return;
  312. }
  313. if (oldSize == maxSize)
  314. {
  315. // Shrink if there's a smaller size.
  316. size_t newSize = sizeRefs.back();
  317. if (newSize < maxSize)
  318. resize(newSize);
  319. }
  320. }
  321. void VertexIndex::resize(size_t size)
  322. {
  323. if (size == 0)
  324. {
  325. delete element_array;
  326. element_array = NULL;
  327. maxSize = 0;
  328. return;
  329. }
  330. VertexBuffer *new_element_array;
  331. // Depending on the size, a switch to int and more memory is needed.
  332. GLenum target_type = getType(size);
  333. size_t elem_size = (target_type == GL_UNSIGNED_SHORT) ? sizeof(GLushort) : sizeof(GLuint);
  334. size_t array_size = elem_size * 6 * size;
  335. // Create may throw out-of-memory exceptions.
  336. // VertexIndex will propagate the exception and keep the old VertexBuffer.
  337. try
  338. {
  339. new_element_array = VertexBuffer::Create(array_size, GL_ELEMENT_ARRAY_BUFFER, GL_STATIC_DRAW);
  340. }
  341. catch (std::bad_alloc &)
  342. {
  343. throw love::Exception("Out of memory.");
  344. }
  345. // Allocation of the new VertexBuffer succeeded.
  346. // The old VertexBuffer can now be deleted.
  347. delete element_array;
  348. element_array = new_element_array;
  349. maxSize = size;
  350. elementSize = elem_size;
  351. switch (target_type)
  352. {
  353. case GL_UNSIGNED_SHORT:
  354. fill<GLushort>();
  355. break;
  356. case GL_UNSIGNED_INT:
  357. fill<GLuint>();
  358. break;
  359. }
  360. }
  361. template <typename T>
  362. void VertexIndex::fill()
  363. {
  364. VertexBuffer::Bind bind(*element_array);
  365. VertexBuffer::Mapper mapper(*element_array);
  366. T *indices = (T *) mapper.get();
  367. for (size_t i = 0; i < maxSize; ++i)
  368. {
  369. indices[i*6+0] = i * 4 + 0;
  370. indices[i*6+1] = i * 4 + 1;
  371. indices[i*6+2] = i * 4 + 2;
  372. indices[i*6+3] = i * 4 + 0;
  373. indices[i*6+4] = i * 4 + 2;
  374. indices[i*6+5] = i * 4 + 3;
  375. }
  376. }
  377. } // opengl
  378. } // graphics
  379. } // love