]> git.localhorst.tv Git - blobs.git/blob - src/graphics/buffer.hpp
eating and drinking
[blobs.git] / src / graphics / buffer.hpp
1 #ifndef BLOBS_GRAPHICS_BUFFER_HPP_
2 #define BLOBS_GRAPHICS_BUFFER_HPP_
3
4 #include "../app/error.hpp"
5
6 #include <algorithm>
7 #include <GL/glew.h>
8
9
10 namespace blobs {
11 namespace graphics {
12
13 template<class T>
14 class MappedBuffer {
15
16 public:
17         MappedBuffer(GLenum target, GLenum access)
18         : buf(reinterpret_cast<T *>(glMapBuffer(target, access)))
19         , target(target) {
20                 if (!buf) {
21                         throw app::GLError("failed to map buffer");
22                 }
23         }
24         MappedBuffer()
25         : buf(nullptr)
26         , target(0) {
27         }
28         ~MappedBuffer() noexcept {
29                 if (buf) {
30                         glUnmapBuffer(target);
31                 }
32         }
33
34         MappedBuffer(MappedBuffer<T> &&other) noexcept
35         : buf(other.buf)
36         , target(other.target) {
37                 other.buf = nullptr;
38         }
39         MappedBuffer<T> &operator =(MappedBuffer<T> &&other) noexcept {
40                 std::swap(buf, other.buf);
41                 std::swap(target, other.target);
42         }
43
44         MappedBuffer(const MappedBuffer<T> &) = delete;
45         MappedBuffer<T> &operator =(const MappedBuffer<T> &) = delete;
46
47         explicit operator bool() const noexcept { return buf; }
48
49 public:
50         T &operator [](std::size_t i) noexcept { return buf[i]; }
51         const T &operator [](std::size_t i) const noexcept { return buf[i]; }
52
53 private:
54         T *buf;
55         GLenum target;
56
57 };
58
59 }
60 }
61
62 #endif