From 5f6c8dd8e627c15d1b5889cb062abda2ace96495 Mon Sep 17 00:00:00 2001 From: veclavtalica Date: Mon, 13 Jan 2025 17:35:50 +0300 Subject: [PATCH] missing texture when loading fails --- src/twn_textures.c | 42 ++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 40 insertions(+), 2 deletions(-) diff --git a/src/twn_textures.c b/src/twn_textures.c index c64527a..4b618dd 100644 --- a/src/twn_textures.c +++ b/src/twn_textures.c @@ -40,6 +40,43 @@ static int load_eof_callback(void *user) { return context->position == context->size; } + +static uint8_t *missing_texture_data; + +static SDL_Surface *gen_missing_texture_surface(void) { + Uint32 rmask, gmask, bmask, amask; + + #if SDL_BYTEORDER == SDL_BIG_ENDIAN + rmask = 0xff000000; + gmask = 0x00ff0000; + bmask = 0x0000ff00; + #else + rmask = 0x000000ff; + gmask = 0x0000ff00; + bmask = 0x00ff0000; + #endif + + if (!missing_texture_data) { + missing_texture_data = SDL_malloc(64 * 64 * 3); + for (int y = 0; y < 64; ++y) + for (int x = 0; x < 64; ++x) { + /* diagonal stripes, chosen so that asked pixel uvs are corresponding to final output */ + missing_texture_data[(y * 64 + x) * 3 + 0] = (x / 2 + y / 2) % 2 == 0 ? 175 : 0; + missing_texture_data[(y * 64 + x) * 3 + 1] = (x / 2 + y / 2) % 2 == 0 ? 0 : 0; + missing_texture_data[(y * 64 + x) * 3 + 2] = (x / 2 + y / 2) % 2 == 0 ? 175 : 0; + } + } + + /* same data is reused after being allocated/generated once */ + SDL_Surface* surface = SDL_CreateRGBSurfaceFrom(missing_texture_data, 64, 64, + 3 * 8, + 64 * 3, + rmask, gmask, bmask, 0); + + return surface; +} + + SDL_Surface *textures_load_surface(const char *path) { SDL_RWops *handle = PHYSFSRWOPS_openRead(path); if (handle == NULL) @@ -93,8 +130,9 @@ ERR_CANNOT_CREATE_SURFACE: ERR_CANNOT_READ_IMAGE: ERR_CANNOT_OPEN_FILE: - CRY(path, "Failed to load image. Aborting..."); - die_abruptly(); + /* something didn't worked out, use a stub texture */ + log_warn("Cannot open image: %s, using a stub", path); + return gen_missing_texture_surface(); }