Kumo
A hand-rolled game engine.
git clone https://git.sentomk.me/Kumo.git
frame_buffer.h (2398B) · raw
1 /// @file render/frame_buffer.h 2 /// @brief The pixel buffer the software renderer draws into, and what can be 3 /// done with one: hash it, save it as an image. 4 #pragma once 5 6 #include <vector> 7 8 #include "core/types.h" 9 10 namespace kumo { 11 12 /// @brief A color packed as 0xAARRGGBB. 13 using Color = uint32_t; 14 15 /// @brief Packs 8-bit channels into a Color. 16 constexpr Color make_color(uint8_t r, uint8_t g, uint8_t b, uint8_t a = 255) { 17 return (static_cast<Color>(a) << 24) | (static_cast<Color>(r) << 16) | 18 (static_cast<Color>(g) << 8) | (static_cast<Color>(b)); 19 } 20 21 /// @brief A grid of pixels stored row by row, top row first. 22 struct FrameBuffer { 23 int width; 24 int height; 25 std::vector<Color> pixels; ///< width * height colors; (0, 0) is top left. 26 27 /// @brief Creates a buffer with every pixel set to @p fill. 28 FrameBuffer(int width, int height, Color fill = 0) 29 : width(width), 30 height(height), 31 pixels(static_cast<size_t>(width) * static_cast<size_t>(height), fill) { 32 } 33 34 /// @brief Tells whether (x, y) lies inside the buffer. 35 bool contains(int x, int y) const { 36 return x >= 0 && y >= 0 && x < width && y < height; 37 } 38 39 /// @brief The pixel at (x, y), which must be inside the buffer. 40 Color& at(int x, int y) { 41 return pixels[static_cast<size_t>(y) * static_cast<size_t>(width) + 42 static_cast<size_t>(x)]; 43 } 44 45 /// @copydoc at(int, int) 46 Color at(int x, int y) const { 47 return pixels[static_cast<size_t>(y) * static_cast<size_t>(width) + 48 static_cast<size_t>(x)]; 49 } 50 }; 51 52 /// @brief Hashes the size and the pixels of a buffer with 64-bit FNV-1a. 53 /// 54 /// The bytes are fed to the hash in a fixed order, not the order they have in 55 /// memory, so the result is the same on every platform. Two renders are 56 /// identical if and only if (in practice) their hashes are equal. 57 /// 58 /// @param framebuffer The buffer to hash. 59 /// @return The hash. 60 uint64_t hash_pixels(const FrameBuffer& framebuffer); 61 62 /// @brief Saves a buffer as an uncompressed 32-bit TGA image. 63 /// 64 /// TGA is chosen because it is a few lines to write and macOS Preview opens 65 /// it directly. 66 /// 67 /// @param framebuffer The buffer to save; both sides must be 1 to 65535. 68 /// @param path File to create or overwrite. 69 /// @return `true` on success. 70 bool write_tga(const FrameBuffer& framebuffer, const char* path); 71 72 } // namespace kumo
