This code works for OpenGL ES 1.1 as well! :)
authorSam Lantinga <slouken@libsdl.org>
Mon, 31 Oct 2011 03:06:32 -0400
changeset 6043 46d78e48ae8b
parent 6042 ff2ab1e8d516
child 6044 35448a5ea044
This code works for OpenGL ES 1.1 as well! :)
src/render/opengles/SDL_render_gles.c
--- a/src/render/opengles/SDL_render_gles.c	Mon Oct 31 02:55:21 2011 -0400
+++ b/src/render/opengles/SDL_render_gles.c	Mon Oct 31 03:06:32 2011 -0400
@@ -64,6 +64,8 @@
 static int GLES_RenderCopy(SDL_Renderer * renderer, SDL_Texture * texture,
                            const SDL_Rect * srcrect,
                            const SDL_Rect * dstrect);
+static int GLES_RenderReadPixels(SDL_Renderer * renderer, const SDL_Rect * rect,
+                    Uint32 pixel_format, void * pixels, int pitch);
 static void GLES_RenderPresent(SDL_Renderer * renderer);
 static void GLES_DestroyTexture(SDL_Renderer * renderer,
                                 SDL_Texture * texture);
@@ -216,6 +218,7 @@
     renderer->RenderDrawLines = GLES_RenderDrawLines;
     renderer->RenderFillRects = GLES_RenderFillRects;
     renderer->RenderCopy = GLES_RenderCopy;
+    renderer->RenderReadPixels = GLES_RenderReadPixels;
     renderer->RenderPresent = GLES_RenderPresent;
     renderer->DestroyTexture = GLES_DestroyTexture;
     renderer->DestroyRenderer = GLES_DestroyRenderer;
@@ -744,6 +747,57 @@
     return 0;
 }
 
+static int
+GLES_RenderReadPixels(SDL_Renderer * renderer, const SDL_Rect * rect,
+                    Uint32 pixel_format, void * pixels, int pitch)
+{
+    SDL_Window *window = renderer->window;
+    Uint32 temp_format = SDL_PIXELFORMAT_ABGR8888;
+    void *temp_pixels;
+    int temp_pitch;
+    Uint8 *src, *dst, *tmp;
+    int w, h, length, rows;
+    int status;
+
+    GLES_ActivateRenderer(renderer);
+
+    temp_pitch = rect->w * SDL_BYTESPERPIXEL(temp_format);
+    temp_pixels = SDL_malloc(rect->h * temp_pitch);
+    if (!temp_pixels) {
+        SDL_OutOfMemory();
+        return -1;
+    }
+
+    SDL_GetWindowSize(window, &w, &h);
+
+    glPixelStorei(GL_PACK_ALIGNMENT, 1);
+
+    glReadPixels(rect->x, (h-rect->y)-rect->h, rect->w, rect->h,
+                       GL_RGBA, GL_UNSIGNED_BYTE, temp_pixels);
+
+    /* Flip the rows to be top-down */
+    length = rect->w * SDL_BYTESPERPIXEL(temp_format);
+    src = (Uint8*)temp_pixels + (rect->h-1)*temp_pitch;
+    dst = (Uint8*)temp_pixels;
+    tmp = SDL_stack_alloc(Uint8, length);
+    rows = rect->h / 2;
+    while (rows--) {
+        SDL_memcpy(tmp, dst, length);
+        SDL_memcpy(dst, src, length);
+        SDL_memcpy(src, tmp, length);
+        dst += temp_pitch;
+        src -= temp_pitch;
+    }
+    SDL_stack_free(tmp);
+
+    status = SDL_ConvertPixels(rect->w, rect->h,
+                               temp_format, temp_pixels, temp_pitch,
+                               pixel_format, pixels, pitch);
+    SDL_free(temp_pixels);
+
+    return status;
+}
+
 static void
 GLES_RenderPresent(SDL_Renderer * renderer)
 {