From 78134dc88b0b39b0d051392fa937418bcd384404 Mon Sep 17 00:00:00 2001 From: Bertram Date: Thu, 17 Sep 2009 00:04:21 +0200 Subject: Optimized the Image::setAlpha() function for SDL. --- src/resources/image.cpp | 39 +++++++++++++++++++++++++-------------- 1 file changed, 25 insertions(+), 14 deletions(-) (limited to 'src/resources') diff --git a/src/resources/image.cpp b/src/resources/image.cpp index d2a1c82e..15ad3b54 100644 --- a/src/resources/image.cpp +++ b/src/resources/image.cpp @@ -229,20 +229,31 @@ void Image::setAlpha(float alpha) if (SDL_MUSTLOCK(mSDLSurface)) SDL_LockSurface(mSDLSurface); - for (int i = 0; i < mSDLSurface->w * mSDLSurface->h; ++i) - { - Uint8 r, g, b, a; - SDL_GetRGBA( - ((Uint32*) mSDLSurface->pixels)[i], - mSDLSurface->format, - &r, &g, &b, &a); - - a = (Uint8) (mAlphaChannel[i] * mAlpha); - - // Here is the pixel we want to set - ((Uint32 *)(mSDLSurface->pixels))[i] = - SDL_MapRGBA(mSDLSurface->format, r, g, b, a); - } + // Precompute as much as possible + int maxHeight = std::min((mBounds.y + mBounds.h), mSDLSurface->h); + int maxWidth = std::min((mBounds.x + mBounds.w), mSDLSurface->w); + int i = 0; + + for (int y = mBounds.y; y < maxHeight; y++) + for (int x = mBounds.x; x < maxWidth; x++) + { + i = y * mSDLSurface->w + x; + // Only change the pixel if it was visible at load time... + Uint8 sourceAlpha = mAlphaChannel[i]; + if (sourceAlpha > 0) + { + Uint8 r, g, b, a; + SDL_GetRGBA(((Uint32*) mSDLSurface->pixels)[i], + mSDLSurface->format, + &r, &g, &b, &a); + + a = (Uint8) (sourceAlpha * mAlpha); + + // Here is the pixel we want to set + ((Uint32 *)(mSDLSurface->pixels))[i] = + SDL_MapRGBA(mSDLSurface->format, r, g, b, a); + } + } if (SDL_MUSTLOCK(mSDLSurface)) SDL_UnlockSurface(mSDLSurface); -- cgit v1.2.3-60-g2f50