Kumo

A hand-rolled game engine.

git clone https://git.sentomk.me/Kumo.git

frame_buffer.cpp (2360B) · raw


      1 #include "render/frame_buffer.h"
      2 
      3 #include <cstdio>
      4 
      5 namespace kumo {
      6 
      7 uint64_t hash_pixels(const FrameBuffer& framebuffer) {
      8   uint64_t hash = 0xcbf29ce484222325ull;  // FNV-1a offset basis
      9 
     10   // Feeds the four bytes of a value, least significant first, whatever the
     11   // byte order of this machine is.
     12   auto mix = [&hash](uint32_t value) {
     13     for (int shift = 0; shift < 32; shift += 8) {
     14       hash ^= (value >> shift) & 0xFF;
     15       hash *= 0x100000001b3ull;  // FNV-1a prime; unsigned, so wraps defined
     16     }
     17   };
     18 
     19   mix(static_cast<uint32_t>(framebuffer.width));
     20   mix(static_cast<uint32_t>(framebuffer.height));
     21   for (Color pixel : framebuffer.pixels) mix(pixel);
     22   return hash;
     23 }
     24 
     25 bool write_tga(const FrameBuffer& framebuffer, const char* path) {
     26   const int width = framebuffer.width;
     27   const int height = framebuffer.height;
     28   if (width < 1 || height < 1 || width > 65535 || height > 65535) return false;
     29 
     30   std::FILE* file = std::fopen(path, "wb");
     31   if (file == nullptr) return false;
     32 
     33   // The 18 byte header; every field not set below stays zero.
     34   uint8_t header[18] = {};
     35   header[2] = 2;  // image type: uncompressed true color
     36   header[12] = static_cast<uint8_t>(width & 0xFF);  // width, little endian
     37   header[13] = static_cast<uint8_t>(width >> 8);
     38   header[14] = static_cast<uint8_t>(height & 0xFF);  // height, little endian
     39   header[15] = static_cast<uint8_t>(height >> 8);
     40   header[16] = 32;    // bits per pixel
     41   header[17] = 0x28;  // 8 alpha bits, and the first row is the top one
     42   bool ok = std::fwrite(header, 1, sizeof(header), file) == sizeof(header);
     43 
     44   // Bytes are written as blue, green, red, alpha, which is what the format
     45   // wants, one by one so the file does not depend on this machine's byte order.
     46   std::vector<uint8_t> bytes;
     47   bytes.reserve(framebuffer.pixels.size() * 4);
     48   for (Color pixel : framebuffer.pixels) {
     49     bytes.push_back(static_cast<uint8_t>(pixel & 0xFF));
     50     bytes.push_back(static_cast<uint8_t>((pixel >> 8) & 0xFF));
     51     bytes.push_back(static_cast<uint8_t>((pixel >> 16) & 0xFF));
     52     bytes.push_back(static_cast<uint8_t>((pixel >> 24) & 0xFF));
     53   }
     54   ok = ok && std::fwrite(bytes.data(), 1, bytes.size(), file) == bytes.size();
     55 
     56   // Close in every case, and count a failed close (a failed flush) as an error.
     57   ok = (std::fclose(file) == 0) && ok;
     58   return ok;
     59 }
     60 
     61 }  // namespace kumo