persistent_buffer_example.cpp 2.2 KB

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