slutpet/img.c
2025-05-26 13:08:18 +10:00

80 lines
1.5 KiB
C

#define STB_IMAGE_IMPLEMENTATION
#include <SDL3/SDL.h>
#include "stb_image.h"
#include "dat.h"
#include "fns.h"
void
free_image(Image *i)
{
if (i) {
if (i->tex) {
babble("free img %s texture...", i->name);
SDL_DestroyTexture(i->tex);
}
if (i->data) {
babble("free img %s data...", i->name);
SDL_free(i->data);
}
if (i->name) {
babble("free img %s name...", i->name);
SDL_free(i->name);
}
babble("free aforementioned img...");
SDL_free(i);
}
}
Image *
load_image(SDL_Renderer *ren, char *path)
{
Image *i;
SDL_Surface *sur;
babble("create image %s...", path);
babble("alloc image...", path);
i = SDL_calloc(1, sizeof(Image));
if (!i) {
shit("mem alloc fail: %s", SDL_GetError());
return NULL;
}
babble("alloc image name...", path);
i->name = SDL_strdup(path);
if (!i->name) {
shit("strdup fail: %s", SDL_GetError());
free_image(i);
return NULL;
}
i->data = stbi_load(path, &i->w, &i->h,
&i->bpp, 4);
if (!i->data) {
shit("mem alloc fail: %s", SDL_GetError());
free_image(i);
return NULL;
}
sur = SDL_CreateSurfaceFrom(i->w, i->h,
SDL_PIXELFORMAT_RGBA32, i->data,
i->w * 4);
if (!sur) {
shit("surface creation fail: %s", SDL_GetError());
free_image(i);
return NULL;
}
i->tex = SDL_CreateTextureFromSurface(ren, sur);
if (!i->tex) {
shit("surface creation fail: %s", SDL_GetError());
SDL_DestroySurface(sur);
free_image(i);
return NULL;
}
SDL_DestroySurface(sur);
babble("image %s created", path);
return i;
}