Turn gfx::buffer to a templated gfx::basic_buffer to support different buffer types

This commit is contained in:
Nikita Lisitsa 2021-07-13 11:44:23 +03:00
parent 46d637328a
commit 96652584a9
2 changed files with 59 additions and 72 deletions

View file

@ -8,27 +8,67 @@
namespace psemek::gfx
{
struct buffer
template <GLenum Target>
struct basic_buffer
{
buffer();
buffer(buffer &&);
buffer & operator = (buffer &&);
~buffer();
static constexpr GLenum target = Target;
buffer(buffer const &) = delete;
buffer & operator = (buffer const &) = delete;
basic_buffer()
{
gl::GenBuffers(1, &id_);
}
static buffer null();
basic_buffer(basic_buffer && other)
: id_{other.id_}
{
other.id_ = 0;
}
basic_buffer & operator = (basic_buffer && other)
{
if (this == &other)
return *this;
reset();
id_ = std::move(other.id_);
other.id_ = 0;
return *this;
}
~basic_buffer()
{
reset();
}
basic_buffer(basic_buffer const &) = delete;
basic_buffer & operator = (basic_buffer const &) = delete;
static basic_buffer null()
{
return basic_buffer{nullptr};
}
GLuint id() const { return id_; }
explicit operator bool() const { return id() != 0; }
void bind() const;
void bind() const
{
gl::BindBuffer(Target, id_);
}
void reset();
void reset()
{
if (id_)
gl::DeleteBuffers(1, &id_);
id_ = 0;
}
void load(void const * data, std::size_t size, GLenum usage = gl::STREAM_DRAW);
void load(void const * data, std::size_t size, GLenum usage = gl::STREAM_DRAW)
{
bind();
gl::BufferData(Target, size, data, usage);
}
template <typename T>
void load(T const * data, std::size_t size, GLenum usage = gl::STREAM_DRAW)
@ -61,9 +101,9 @@ namespace psemek::gfx
return std::static_pointer_cast<T[]>(p);
bind();
std::shared_ptr<T[]> p(reinterpret_cast<T *>(gl::MapBuffer(gl::ARRAY_BUFFER, gl::WRITE_ONLY)), [this](T *){
std::shared_ptr<T[]> p(reinterpret_cast<T *>(gl::MapBuffer(Target, gl::WRITE_ONLY)), [this](T *){
bind();
gl::UnmapBuffer(gl::ARRAY_BUFFER);
gl::UnmapBuffer(Target);
});
mapped_ = p;
return p;
@ -73,7 +113,12 @@ namespace psemek::gfx
GLuint id_;
std::weak_ptr<void> mapped_;
explicit buffer(std::nullptr_t);
explicit basic_buffer(std::nullptr_t)
: id_{0}
{}
};
using buffer = basic_buffer<gl::ARRAY_BUFFER>;
using uniform_buffer = basic_buffer<gl::UNIFORM_BUFFER>;
}

View file

@ -1,58 +0,0 @@
#include <psemek/gfx/buffer.hpp>
namespace psemek::gfx
{
buffer::buffer()
{
gl::GenBuffers(1, &id_);
}
buffer::buffer(buffer && other)
: id_{other.id_}
{
other.id_ = 0;
}
buffer & buffer::operator = (buffer && other)
{
if (this == &other) return *this;
reset();
std::swap(id_, other.id_);
return *this;
}
buffer::~buffer()
{
reset();
}
buffer buffer::null()
{
return buffer(nullptr);
}
void buffer::bind() const
{
gl::BindBuffer(gl::ARRAY_BUFFER, id_);
}
void buffer::reset()
{
if (id_ != 0)
gl::DeleteBuffers(1, &id_);
id_ = 0;
}
void buffer::load(void const * data, std::size_t size, GLenum usage)
{
bind();
gl::BufferData(gl::ARRAY_BUFFER, size, data, usage);
}
buffer::buffer(std::nullptr_t)
: id_{0}
{}
}