bad-apple/encoder/main.cpp
2023-12-23 12:39:40 +07:00

111 lines
2.9 KiB
C++

#include <cstdio>
#include <iostream>
#include <filesystem>
#include <fstream>
#include <string>
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#include "fastlz.h"
unsigned short RGB15(int r, int g, int b) {
unsigned short rgb15 =
((r >> 3) << 10) | // 5 bits for red
((g >> 3) << 5) | // 5 bits for green
(b >> 3); // 5 bits for blue
// Set the alpha bit to 1
rgb15 |= 1 << 15;
return rgb15;
}
int main()
{
std::string path_out = "../assets/out/";
std::string path_palette = "../assets/palette.png";
std::string path_resource = "../resource";
std::string path_test = "../assets/out/out_3667.bmp";
int frame_total = -1;
// Find total frame
for (const auto& entry : std::filesystem::directory_iterator(path_out)) {
if (entry.is_regular_file()) {
std::string fileName = entry.path().filename().string();
if (fileName.substr(0, 4) == "out_" && fileName.substr(fileName.size() - 4) == ".bmp") {
int number = std::stoi(fileName.substr(4, fileName.size() - 8));
if (number > frame_total) {
frame_total = number;
}
}
}
}
// Generate palette
uint16_t palette[256];
int palette_w = -1;
int palette_h = -1;
int palette_n = -1;
unsigned char *palette_data = stbi_load(path_palette.c_str(), &palette_w, &palette_h, &palette_n, 3);
for (int i=0; i<256; i++)
{
int index = i*3;
unsigned char r = palette_data[index];
unsigned char g = palette_data[index + 1];
unsigned char b = palette_data[index + 2];
palette[i] = RGB15(r, g, b);
// printf("%i> %i,%i,%i (%i)\n", i, r, g, b, palette[i]);
}
std::ofstream out;
out.open(path_resource + "/palette.bin", std::ios::binary);
out.write(reinterpret_cast<const char*>(palette), sizeof(palette));
out.close();
uint8_t test[256*192];
uint8_t test_compress[(256*192)*2];
uint32_t test_compress_len = 0;
int test_w = -1;
int test_h = -1;
int test_n = -1;
unsigned char *test_data = stbi_load(path_test.c_str(), &test_w, &test_h, &test_n, 3);
for (int i=0; i<256*192; i++)
{
int index = i*3;
unsigned char r = test_data[index];
unsigned char g = test_data[index + 1];
unsigned char b = test_data[index + 2];
uint16_t current_pal = RGB15(r, g, b);
int current_index = -1;
for (int i2=0; i2<256; i2++)
{
if (palette[i2] == current_pal) {
current_index = i2;
break;
}
}
if (current_index == -1) printf("%i> %i\n", i, current_index);
else test[i] = current_index;
}
test_compress_len = fastlz_compress_level(1, test, 256*192, test_compress);
printf("len: %i\n", test_compress_len);
out.open(path_resource + "/image.bin", std::ios::binary);
out.write(reinterpret_cast<const char*>(&test_compress_len), sizeof(test_compress_len));
out.write(reinterpret_cast<const char*>(test_compress), test_compress_len);
out.close();
// Print
printf("Total Frame: %i\n", frame_total);
}