bngviewer.c 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. #include <assert.h>
  2. #include <SDL.h>
  3. #include "bng.h"
  4. void* read_whole_file(const char *filename)
  5. {
  6. FILE *f = fopen(filename, "rb");
  7. fseek(f, 0, SEEK_END);
  8. long size = ftell(f);
  9. fseek(f, 0, SEEK_SET);
  10. void *data = malloc(size);
  11. size_t read_size = fread(data, 1, size, f);
  12. return data;
  13. }
  14. uint32_t *bng_load(const char *filepath, uint32_t *width, uint32_t *height)
  15. {
  16. struct Bng *compressed_bng = read_whole_file(filepath);
  17. uint32_t *pixels = malloc(compressed_bng->width * compressed_bng->height * sizeof(uint32_t));
  18. decompress_pixels(compressed_bng->pairs, compressed_bng->pairs_count, pixels);
  19. for (size_t i = 0; i < compressed_bng->width * compressed_bng->height; ++i) {
  20. pixels[i] = convert_pixel(pixels[i], compressed_bng->pixel_format, RGBA);
  21. }
  22. *width = compressed_bng->width;
  23. *height = compressed_bng->height;
  24. return pixels;
  25. }
  26. int main(int argc, char *argv[])
  27. {
  28. if (argc < 2) {
  29. fprintf(stderr, "./bngviewer <input.bng>");
  30. exit(1);
  31. }
  32. const char *input_filepath = argv[1];
  33. SDL_Init(SDL_INIT_VIDEO);
  34. SDL_Window *window =
  35. SDL_CreateWindow(
  36. "BNG Viewer",
  37. 0, 0, 800, 600,
  38. SDL_WINDOW_RESIZABLE);
  39. SDL_Renderer *renderer =
  40. SDL_CreateRenderer(
  41. window, -1,
  42. SDL_RENDERER_PRESENTVSYNC | SDL_RENDERER_ACCELERATED);
  43. uint32_t width, height;
  44. uint32_t *pixels = bng_load(input_filepath, &width, &height);
  45. SDL_Surface* image_surface =
  46. SDL_CreateRGBSurfaceFrom(pixels,
  47. width,
  48. height,
  49. 32,
  50. width * 4,
  51. 0x000000FF,
  52. 0x0000FF00,
  53. 0x00FF0000,
  54. 0xFF000000);
  55. SDL_Texture *texture = SDL_CreateTextureFromSurface(renderer, image_surface);
  56. int quit = 0;
  57. while (!quit) {
  58. SDL_Event event;
  59. while (SDL_PollEvent(&event)) {
  60. switch (event.type) {
  61. case SDL_QUIT: {
  62. quit = 1;
  63. } break;
  64. }
  65. }
  66. SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0);
  67. SDL_RenderClear(renderer);
  68. SDL_Rect rect = {0, 0, width, height};
  69. SDL_RenderCopy(renderer, texture, &rect, &rect);
  70. SDL_RenderPresent(renderer);
  71. }
  72. SDL_Quit();
  73. return 0;
  74. }