summaryrefslogtreecommitdiff
path: root/include/llmr/geometry/buffer.hpp
blob: 1177bb196eb417ab80f29795fb9ea69a681d09e2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#ifndef LLMR_GEOMETRY_BUFFER
#define LLMR_GEOMETRY_BUFFER

#include <cstdlib>
#include <cassert>
#include <llmr/platform/gl.hpp>

namespace llmr {

template <
    size_t itemSize,
    int bufferType = GL_ARRAY_BUFFER,
    size_t defaultLength = 8192
>
class Buffer {
public:
    ~Buffer() {
        if (array) {
            free(array);
            array = nullptr;
        }
        if (buffer != 0) {
            glDeleteBuffers(1, &buffer);
            buffer = 0;
        }
    }

    // Returns the number of elements in this buffer. This is not the number of
    // bytes, but rather the number of coordinates with associated information.
    inline size_t index() const {
        return pos / itemSize;
    }

    // Transfers this buffer to the GPU and binds the buffer to the GL context.
    void bind() {
        if (buffer == 0) {
            glGenBuffers(1, &buffer);
            glBindBuffer(bufferType, buffer);
            glBufferData(bufferType, pos, array, GL_STATIC_DRAW);
            free(array);
            array = nullptr;
        } else {
            glBindBuffer(bufferType, buffer);
        }
    }

protected:
    // increase the buffer size by at least /required/ bytes.
    void *addElement() {
        assert("Buffer is already bound to GPU" && buffer == 0);
        if (length < pos + itemSize) {
            while (length < pos + itemSize) length += defaultLength;
            array = realloc(array, length);
            assert("Buffer reallocation failed" && array != nullptr);
        }
        pos += itemSize;
        return static_cast<char *>(array) + (pos - itemSize);
    }

private:
    // CPU buffer
    void *array = nullptr;

    // Byte position where we are writing.
    size_t pos = 0;

    // Number of bytes that are valid in this buffer.
    size_t length = 0;

    // GL buffer ID
    uint32_t buffer = 0;
};

}

#endif