#include #include "scale.h" static bool is_safei(int i) { return i >= -PW_MAX_SAFE_INT && i <= PW_MAX_SAFE_INT; } static bool is_safef(float f) { return f >= -PW_MAX_SAFE_INT && f <= PW_MAX_SAFE_INT && (int32_t)f != 0; } static SDL_ScaleMode scale_pixel_perfect(float twf, float thf, int rw, int rh, SDL_FRect *target) { int32_t tw = (int32_t)twf; int32_t th = (int32_t)thf; int32_t scale = SDL_min(rw / tw, rh / th); int32_t w = scale * tw; int32_t h = scale * th; int32_t x = (rw - w) / 2; int32_t y = (rh - h) / 2; target->w = (float)w; target->h = (float)h; target->x = (float)x; target->y = (float)y; return SDL_SCALEMODE_NEAREST; } static SDL_ScaleMode scale_fill(float twf, float thf, int rw, int rh, SDL_FRect *target) { float rwf = (float)rw; float rhf = (float)rh; float scale = SDL_min(rwf / twf, rhf / thf); float w = scale * twf; float h = scale * thf; float x = (rw - w) / 2.; float y = (rh - h) / 2.; target->w = w; target->h = h; target->x = x; target->y = y; #if SDL_VERSION_ATLEAST(3, 4, 0) return SDL_SCALEMODE_PIXELART; #else return SDL_SCALEMODE_NEAREST; #endif } static SDL_ScaleMode scale_stretch(float twf, float thf, int rw, int rh, SDL_FRect *target) { (void)twf; (void)thf; target->w = rw; target->h = rh; target->x = 0.; target->y = 0.; #if SDL_VERSION_ATLEAST(3, 4, 0) return SDL_SCALEMODE_PIXELART; #else return SDL_SCALEMODE_NEAREST; #endif } bool pw_scale(enum pw_scale_mode mode, SDL_Texture *texture, SDL_FRect *target) { SDL_ScaleMode (*scalefn)(float, float, int, int, SDL_FRect *); switch (mode) { case PW_SCALE_MODE_PIXEL_PERFECT: scalefn = scale_pixel_perfect; break; case PW_SCALE_MODE_FILL: scalefn = scale_fill; break; case PW_SCALE_MODE_STRETCH: scalefn = scale_stretch; break; default: SDL_InvalidParamError("mode"); return false; } if (!texture) { SDL_InvalidParamError("texture"); return false; } if (!target) { SDL_InvalidParamError("target"); return false; } float twf, thf; if (!SDL_GetTextureSize(texture, &twf, &thf)) { return false; } SDL_Renderer *renderer = SDL_GetRendererFromTexture(texture); if (!renderer) { return false; } int rw, rh; if (!SDL_GetRenderOutputSize(renderer, &rw, &rh)) { return false; } if (!is_safef(twf) || !is_safef(thf) || !is_safei(rw) || !is_safei(rh)) { return SDL_SetError("unreasonable texture or render sizes"); } SDL_FRect t; SDL_ScaleMode m = scalefn(twf, thf, rw, rh, &t); if (!SDL_SetTextureScaleMode(texture, m)) { return false; } SDL_memcpy(target, &t, sizeof(*target)); return true; }