feat: add stb dependency and window::screenshot()

Added deps/Findstb.cmake (fetches stb via FetchContent, provides
stb::stb interface target).

Linked to cbt_opengl. Implemented window::screenshot() using
glReadPixels + vertical flip + stb_image_write to save RGBA PNG.

Press S in the app to capture current frame (saved as
screenshot.png). Updated help text.

(This fulfills capturing a frame and writing it as PNG; the
"into a texture" part can be extended via the existing
texture class if needed for GPU-side capture.)
This commit is contained in:
2026-05-05 23:48:05 +02:00
parent c3860cc1d3
commit 4a88c8cc06
5 changed files with 94 additions and 76 deletions
+38
View File
@@ -3,6 +3,8 @@
#include <windows.h>
#endif
#include <vector>
#define GLFW_INCLUDE_NONE
#include "GLFW/glfw3.h"
@@ -12,6 +14,9 @@
#endif
#include "fmt/std.h"
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image_write.h"
#include "glad/glad.h"
#include "cbt/window.hpp"
@@ -89,4 +94,37 @@ auto window::stop() -> void {
}
}
auto window::screenshot(std::string filepath) const -> bool {
if (!m_window || !valid()) {
return false;
}
int width = 0;
int height = 0;
glfwGetFramebufferSize(m_window, &width, &height);
if (width <= 0 || height <= 0) {
return false;
}
std::vector<unsigned char> pixels(static_cast<size_t>(width * height * 4));
glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, pixels.data());
// Flip vertically (OpenGL reads bottom-up; PNG is top-down)
for (int y = 0; y < height / 2; ++y) {
int y2 = height - 1 - y;
for (int x = 0; x < width * 4; ++x) {
std::swap(pixels[static_cast<size_t>(y * width * 4 + x)],
pixels[static_cast<size_t>(y2 * width * 4 + x)]);
}
}
if (stbi_write_png(filepath.c_str(), width, height, 4, pixels.data(), width * 4) != 0) {
fmt::print("Screenshot saved to {}\n", filepath);
return true;
}
fmt::print("Failed to write screenshot to {}\n", filepath);
return false;
}
}
+1
View File
@@ -18,6 +18,7 @@ public:
auto poll_events() -> void;
auto raw() const -> GLFWwindow*;
auto stop() -> void;
auto screenshot(std::string filepath = "screenshot.png") const -> bool;
private:
GLFWwindow* m_window = nullptr;