#include #include "png.h" #define STBI_ONLY_PNG #define STBI_MAX_DIMENSIONS 205 #define STBI_NO_FAILURE_STRINGS #define STBI_NO_LINEAR #define STBI_NO_STDIO #define STBI_NO_THREAD_LOCALS #define STBI_MALLOC(sz) SDL_malloc(sz) #define STBI_REALLOC(p, sz) SDL_realloc(p, sz) #define STBI_FREE(p) SDL_free(p) #define STB_IMAGE_IMPLEMENTATION #if defined(__GNUC__) || defined(__clang__) static int stbi__addints_valid(int, int) __attribute__((unused)); static int stbi__mul2shorts_valid(int, int) __attribute__((unused)); #endif #include union pw_png_pixel *pw_png_load(uint8_t const *data, size_t sz, int w, int h) { int x, y, n; int ok = stbi_info_from_memory(data, sz, &x, &y, &n); if (!ok || x != w || y != h) { SDL_SetError("unexpected PNG dimensions"); return NULL; } stbi_uc *image = stbi_load_from_memory(data, sz, &x, &y, &n, 4); if (!image) { SDL_SetError("malformed PNG"); return NULL; } // The desired channels are set to 4, making the STB image library ensure // that the resulting image has exactly 4 8-bit colour channels per pixel; // allowing us to treat the image as x-by-y 32-bit pixels. Furthermore, // the `image` is the result of an `SDL_malloc` which is guaranteed to // alias to any type (as is guaranteed by `malloc`), meaning we do not // violate any strict-aliasing rules. return (union pw_png_pixel *)image; }