-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathframe_buffer.cpp
More file actions
87 lines (70 loc) · 2.5 KB
/
frame_buffer.cpp
File metadata and controls
87 lines (70 loc) · 2.5 KB
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
77
78
79
80
81
82
83
84
85
86
87
#include "frame_buffer.hpp"
#include <limits>
#include <array>
FrameBuffer::FrameBuffer() : _fbo{0}, _textureId{0}, _depthStencilId{0}, _width{0}, _height{0} {}
void FrameBuffer::CreateBuffer(float width, float height)
{
_width = width;
_height = height;
if (_fbo)
DeleteBuffer();
glGenFramebuffers(1, &_fbo);
glBindFramebuffer(GL_FRAMEBUFFER, _fbo);
glGenTextures(1, &_textureId);
glBindTexture(GL_TEXTURE_2D, _textureId);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, nullptr);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, _textureId, 0);
glGenTextures(1, &_depthStencilId);
glBindTexture(GL_TEXTURE_2D, _depthStencilId);
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH24_STENCIL8, width, height, 0, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8, nullptr);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D, _depthStencilId, 0);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glBindTexture(GL_TEXTURE_2D, 0);
glBindRenderbuffer(GL_RENDERBUFFER, 0);
Unbind();
}
FrameBuffer::~FrameBuffer()
{
DeleteBuffer();
}
void FrameBuffer::DeleteBuffer()
{
if (!_fbo)
return;
glDeleteFramebuffers(1, &_fbo);
glDeleteTextures(1, &_textureId);
glDeleteTextures(1, &_depthStencilId);
}
void FrameBuffer::Bind()
{
glBindFramebuffer(GL_FRAMEBUFFER, _fbo);
glViewport(0, 0, _width, _height);
}
void FrameBuffer::Unbind()
{
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
GLuint FrameBuffer::GetTextureId()
{
return _textureId;
}
glm::vec3 FrameBuffer::EncodeId(int id)
{
return glm::vec3(
static_cast<float>((id & 0x000000FF) >> 0) / 255.0f,
static_cast<float>((id & 0x0000FF00) >> 8) / 255.0f,
static_cast<float>((id & 0x00FF0000) >> 16) / 255.0f);
}
int FrameBuffer::DecodePixel(float x, float y)
{
std::array<unsigned char, 4> byte;
glReadPixels(x, y, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, byte.data());
auto id = byte[0] + byte[1] * 256 + byte[2] * 256 * 256;
return id != 0x00ffffff ? id : -1;
}