persistent_buffer_example.cpp 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #include "persistent_buffer.h"
  2. PersistentRingBuffer<CylinderInstanceGpu> m_cylinderPersistentBuffer;
  3. void Backend::initializeCylinderPipeline() {
  4. const std::size_t initialCapacity = 10000;
  5. if (m_cylinderPersistentBuffer.initialize(initialCapacity, 3)) {
  6. } else {
  7. qWarning()
  8. << "Failed to init persistent buffer, falling back to old method";
  9. }
  10. }
  11. void Backend::beginFrame() {
  12. if (m_cylinderPersistentBuffer.isValid()) {
  13. m_cylinderPersistentBuffer.beginFrame();
  14. }
  15. }
  16. void Backend::uploadCylinderInstances(std::size_t count) {
  17. if (count == 0)
  18. return;
  19. if (m_cylinderPersistentBuffer.isValid()) {
  20. if (count > m_cylinderPersistentBuffer.capacity()) {
  21. qWarning() << "Too many cylinders:" << count
  22. << "max:" << m_cylinderPersistentBuffer.capacity();
  23. count = m_cylinderPersistentBuffer.capacity();
  24. }
  25. m_cylinderPersistentBuffer.write(m_cylinderScratch.data(), count);
  26. glBindBuffer(GL_ARRAY_BUFFER, m_cylinderPersistentBuffer.buffer());
  27. return;
  28. }
  29. if (!m_cylinderInstanceBuffer)
  30. return;
  31. glBindBuffer(GL_ARRAY_BUFFER, m_cylinderInstanceBuffer);
  32. if (count > m_cylinderInstanceCapacity) {
  33. m_cylinderInstanceCapacity = std::max<std::size_t>(
  34. count,
  35. m_cylinderInstanceCapacity ? m_cylinderInstanceCapacity * 2 : count);
  36. glBufferData(GL_ARRAY_BUFFER,
  37. m_cylinderInstanceCapacity * sizeof(CylinderInstanceGpu),
  38. nullptr, GL_DYNAMIC_DRAW);
  39. m_cylinderScratch.reserve(m_cylinderInstanceCapacity);
  40. }
  41. glBufferSubData(GL_ARRAY_BUFFER, 0, count * sizeof(CylinderInstanceGpu),
  42. m_cylinderScratch.data());
  43. glBindBuffer(GL_ARRAY_BUFFER, 0);
  44. }
  45. void Backend::drawCylinders(std::size_t count) {
  46. if (!m_cylinderVao || m_cylinderIndexCount == 0 || count == 0)
  47. return;
  48. initializeOpenGLFunctions();
  49. glBindVertexArray(m_cylinderVao);
  50. glDrawElementsInstanced(GL_TRIANGLES, m_cylinderIndexCount, GL_UNSIGNED_INT,
  51. nullptr, static_cast<GLsizei>(count));
  52. glBindVertexArray(0);
  53. }
  54. void Backend::shutdownCylinderPipeline() {
  55. m_cylinderPersistentBuffer.destroy();
  56. }