From ca36e42922326a798c4fdd950b3630fe92522551 Mon Sep 17 00:00:00 2001 From: Dan Goodliffe Date: Tue, 1 Nov 2022 01:23:43 +0000 Subject: Somewhat dirty but functional helper to save a texture Useful for debugging and not much else. --- gfx/models/texture.cpp | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) (limited to 'gfx/models/texture.cpp') diff --git a/gfx/models/texture.cpp b/gfx/models/texture.cpp index ab04f4f..ff38d0f 100644 --- a/gfx/models/texture.cpp +++ b/gfx/models/texture.cpp @@ -2,7 +2,9 @@ #include "glArrays.h" #include #include +#include #include +#include #include #include @@ -36,3 +38,28 @@ Texture::bind(GLenum unit) const glActiveTexture(unit); glBindTexture(GL_TEXTURE_2D, m_texture); } + +void +Texture::save(const glTexture & texture, const glm::ivec2 & size, const char * path) +{ + GLint drawFboId = 0, readFboId = 0; + glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &drawFboId); + glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &readFboId); + std::vector buffer(static_cast(size.x * size.y * 3)); + { + glFrameBuffer tmp; + glBindFramebuffer(GL_FRAMEBUFFER, tmp); + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture, 0); + glReadPixels(0, 0, size.x, size.y, GL_BGR, GL_UNSIGNED_BYTE, buffer.data()); + } + { + auto out = open(path, O_WRONLY | O_CREAT, 0660); + short TGAhead[] = {0, 2, 0, 0, 0, 0, static_cast(size.x), static_cast(size.y), 24}; + std::ignore = write(out, &TGAhead, sizeof(TGAhead)); + std::ignore = write(out, buffer.data(), buffer.size()); + std::ignore = ftruncate(out, static_cast(buffer.size() + sizeof(TGAhead))); + close(out); + } + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, static_cast(drawFboId)); + glBindFramebuffer(GL_READ_FRAMEBUFFER, static_cast(readFboId)); +} -- cgit v1.2.3