]> git.cworth.org Git - apitrace/blob - retrace/glstate_images.cpp
glstate: Cleanup the read buffer selection code slightly.
[apitrace] / retrace / glstate_images.cpp
1 /**************************************************************************
2  *
3  * Copyright 2011 Jose Fonseca
4  * All Rights Reserved.
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to deal
8  * in the Software without restriction, including without limitation the rights
9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10  * copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22  * THE SOFTWARE.
23  *
24  **************************************************************************/
25
26
27 #include <assert.h>
28 #include <string.h>
29
30 #include <algorithm>
31 #include <iostream>
32
33 #include "image.hpp"
34 #include "json.hpp"
35 #include "glproc.hpp"
36 #include "glsize.hpp"
37 #include "glstate.hpp"
38 #include "glstate_internal.hpp"
39
40
41 #ifdef __linux__
42 #include <dlfcn.h>
43 #endif
44
45 #ifdef __APPLE__
46
47 #include <Carbon/Carbon.h>
48
49 #ifdef __cplusplus
50 extern "C" {
51 #endif
52
53 OSStatus CGSGetSurfaceBounds(CGSConnectionID, CGWindowID, CGSSurfaceID, CGRect *);
54
55 #ifdef __cplusplus
56 }
57 #endif
58
59 #endif /* __APPLE__ */
60
61
62 /* Change thi to one to force interpreting depth buffers as RGBA, which enables
63  * visualizing full dynamic range, until we can transmit HDR images to the GUI */
64 #define DEPTH_AS_RGBA 0
65
66
67 namespace glstate {
68
69
70 struct ImageDesc
71 {
72     GLint width;
73     GLint height;
74     GLint depth;
75     GLint internalFormat;
76
77     inline
78     ImageDesc() :
79         width(0),
80         height(0),
81         depth(0),
82         internalFormat(GL_NONE)
83     {}
84
85     inline bool
86     valid(void) const {
87         return width > 0 && height > 0 && depth > 0;
88     }
89 };
90
91
92 /**
93  * Sames as enumToString, but with special provision to handle formatsLUMINANCE_ALPHA.
94  *
95  * OpenGL 2.1 specification states that "internalFormat may (for backwards
96  * compatibility with the 1.0 version of the GL) also take on the integer
97  * values 1, 2, 3, and 4, which are equivalent to symbolic constants LUMINANCE,
98  * LUMINANCE ALPHA, RGB, and RGBA respectively". 
99  */
100 const char *
101 formatToString(GLenum internalFormat) {
102     switch (internalFormat) {
103     case 1:
104         return "GL_LUMINANCE";
105     case 2:
106         return "GL_LUMINANCE_ALPHA";
107     case 3:
108         return "GL_RGB";
109     case 4:
110         return "GL_RGBA";
111     default:
112         return enumToString(internalFormat);
113     }
114 }
115
116
117 /**
118  * OpenGL ES does not support glGetTexLevelParameteriv, but it is possible to
119  * probe whether a texture has a given size by crafting a dummy glTexSubImage()
120  * call.
121  */
122 static bool
123 probeTextureLevelSizeOES(GLenum target, GLint level, const GLint size[3]) {
124     while (glGetError() != GL_NO_ERROR)
125         ;
126
127     GLenum internalFormat = GL_RGBA;
128     GLenum type = GL_UNSIGNED_BYTE;
129     GLint dummy = 0;
130
131     switch (target) {
132     case GL_TEXTURE_2D:
133     case GL_TEXTURE_CUBE_MAP:
134     case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
135     case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
136     case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
137     case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
138     case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
139     case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
140         glTexSubImage2D(target, level, size[0], size[1], 0, 0, internalFormat, type, &dummy);
141         break;
142     case GL_TEXTURE_3D_OES:
143         glTexSubImage3DOES(target, level, size[0], size[1], size[2], 0, 0, 0, internalFormat, type, &dummy);
144     default:
145         assert(0);
146         return false;
147     }
148
149     GLenum error = glGetError();
150
151     if (0) {
152         std::cerr << "(" << size[0] << ", " << size[1] << ", " << size[2] << ") = " << enumToString(error) << "\n";
153     }
154
155     if (error == GL_NO_ERROR) {
156         return true;
157     }
158
159     while (glGetError() != GL_NO_ERROR)
160         ;
161
162     return false;
163 }
164
165
166 /**
167  * Bisect the texture size along an axis.
168  *
169  * It is assumed that the texture exists.
170  */
171 static GLint
172 bisectTextureLevelSizeOES(GLenum target, GLint level, GLint axis, GLint max) {
173     GLint size[3] = {0, 0, 0};
174
175     assert(axis < 3);
176     assert(max >= 0);
177
178     GLint min = 0;
179     while (true) {
180         GLint test = (min + max) / 2;
181         if (test == min) {
182             return min;
183         }
184
185         size[axis] = test;
186
187         if (probeTextureLevelSizeOES(target, level, size)) {
188             min = test;
189         } else {
190             max = test;
191         }
192     }
193 }
194
195
196 /**
197  * Special path to obtain texture size on OpenGL ES, that does not rely on
198  * glGetTexLevelParameteriv
199  */
200 static bool
201 getActiveTextureLevelDescOES(Context &context, GLenum target, GLint level, ImageDesc &desc)
202 {
203     if (target == GL_TEXTURE_1D) {
204         // OpenGL ES does not support 1D textures
205         return false;
206     }
207
208     const GLint size[3] = {1, 1, 1}; 
209     if (!probeTextureLevelSizeOES(target, level, size)) {
210         return false;
211     }
212
213     // XXX: mere guess
214     desc.internalFormat = GL_RGBA;
215
216     GLint maxSize = 0;
217     switch (target) {
218     case GL_TEXTURE_2D:
219         glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maxSize);
220         desc.width = bisectTextureLevelSizeOES(target, level, 0, maxSize);
221         desc.height = bisectTextureLevelSizeOES(target, level, 1, maxSize);
222         desc.depth = 1;
223         break;
224     case GL_TEXTURE_CUBE_MAP:
225     case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
226     case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
227     case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
228     case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
229     case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
230     case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
231         glGetIntegerv(GL_MAX_CUBE_MAP_TEXTURE_SIZE, &maxSize);
232         desc.width = bisectTextureLevelSizeOES(target, level, 0, maxSize);
233         desc.height = desc.width;
234         desc.depth = 1;
235         break;
236     case GL_TEXTURE_3D_OES:
237         glGetIntegerv(GL_MAX_3D_TEXTURE_SIZE_OES, &maxSize);
238         desc.width = bisectTextureLevelSizeOES(target, level, 0, maxSize);
239         desc.width = bisectTextureLevelSizeOES(target, level, 1, maxSize);
240         desc.depth = bisectTextureLevelSizeOES(target, level, 2, maxSize);
241         break;
242     default:
243         return false;
244     }
245
246     if (0) {
247         std::cerr
248             << enumToString(target) << " "
249             << level << " "
250             << desc.width << "x" << desc.height << "x" << desc.depth
251             << "\n";
252     }
253
254     return desc.valid();
255 }
256
257
258 static inline bool
259 getActiveTextureLevelDesc(Context &context, GLenum target, GLint level, ImageDesc &desc)
260 {
261     assert(target != GL_TEXTURE_CUBE_MAP);
262
263     if (context.ES) {
264         return getActiveTextureLevelDescOES(context, target, level, desc);
265     }
266
267     glGetTexLevelParameteriv(target, level, GL_TEXTURE_INTERNAL_FORMAT, &desc.internalFormat);
268
269     desc.width = 0;
270     glGetTexLevelParameteriv(target, level, GL_TEXTURE_WIDTH, &desc.width);
271
272     if (target == GL_TEXTURE_1D) {
273         desc.height = 1;
274         desc.depth = 1;
275     } else {
276         desc.height = 0;
277         glGetTexLevelParameteriv(target, level, GL_TEXTURE_HEIGHT, &desc.height);
278         if (target != GL_TEXTURE_3D) {
279             desc.depth = 1;
280         } else {
281             desc.depth = 0;
282             glGetTexLevelParameteriv(target, level, GL_TEXTURE_DEPTH, &desc.depth);
283         }
284     }
285
286     return desc.valid();
287 }
288
289
290 /**
291  * OpenGL ES does not support glGetTexImage. Obtain the pixels by attaching the
292  * texture to a framebuffer.
293  */
294 static inline void
295 getTexImageOES(GLenum target, GLint level, ImageDesc &desc, GLubyte *pixels)
296 {
297     memset(pixels, 0x80, desc.height * desc.width * 4);
298
299     GLenum texture_binding = GL_NONE;
300     switch (target) {
301     case GL_TEXTURE_2D:
302         texture_binding = GL_TEXTURE_BINDING_2D;
303         break;
304     case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
305     case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
306     case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
307     case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
308     case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
309     case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
310         texture_binding = GL_TEXTURE_BINDING_CUBE_MAP;
311         break;
312     case GL_TEXTURE_3D_OES:
313         texture_binding = GL_TEXTURE_BINDING_3D_OES;
314     default:
315         return;
316     }
317
318     GLint texture = 0;
319     glGetIntegerv(texture_binding, &texture);
320     if (!texture) {
321         return;
322     }
323
324     GLint prev_fbo = 0;
325     GLuint fbo = 0;
326     glGetIntegerv(GL_FRAMEBUFFER_BINDING, &prev_fbo);
327     glGenFramebuffers(1, &fbo);
328     glBindFramebuffer(GL_FRAMEBUFFER, fbo);
329
330     GLenum status;
331
332     switch (target) {
333     case GL_TEXTURE_2D:
334     case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
335     case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
336     case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
337     case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
338     case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
339     case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
340         glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture, level);
341         status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
342         if (status != GL_FRAMEBUFFER_COMPLETE) {
343             std::cerr << __FUNCTION__ << ": " << enumToString(status) << "\n";
344         }
345         glReadPixels(0, 0, desc.width, desc.height, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
346         break;
347     case GL_TEXTURE_3D_OES:
348         for (int i = 0; i < desc.depth; i++) {
349             glFramebufferTexture3D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_3D, texture, level, i);
350             glReadPixels(0, 0, desc.width, desc.height, GL_RGBA, GL_UNSIGNED_BYTE, pixels + 4 * i * desc.width * desc.height);
351         }
352         break;
353     }
354
355     glBindFramebuffer(GL_FRAMEBUFFER, prev_fbo);
356
357     glDeleteFramebuffers(1, &fbo);
358 }
359
360
361 static inline GLboolean
362 isDepthFormat(GLenum internalFormat)
363 {
364    switch (internalFormat) {
365    case GL_DEPTH_COMPONENT:
366    case GL_DEPTH_COMPONENT16:
367    case GL_DEPTH_COMPONENT24:
368    case GL_DEPTH_COMPONENT32:
369    case GL_DEPTH_COMPONENT32F:
370    case GL_DEPTH_COMPONENT32F_NV:
371    case GL_DEPTH_STENCIL:
372    case GL_DEPTH24_STENCIL8:
373    case GL_DEPTH32F_STENCIL8:
374    case GL_DEPTH32F_STENCIL8_NV:
375       return GL_TRUE;
376    }
377    return GL_FALSE;
378 }
379
380
381 static inline void
382 dumpActiveTextureLevel(JSONWriter &json, Context &context, GLenum target, GLint level)
383 {
384     ImageDesc desc;
385     if (!getActiveTextureLevelDesc(context, target, level, desc)) {
386         return;
387     }
388
389     char label[512];
390     GLint active_texture = GL_TEXTURE0;
391     glGetIntegerv(GL_ACTIVE_TEXTURE, &active_texture);
392     snprintf(label, sizeof label, "%s, %s, level = %d",
393              enumToString(active_texture), enumToString(target), level);
394
395     json.beginMember(label);
396
397     GLuint channels;
398     GLenum format;
399     if (!context.ES && isDepthFormat(desc.internalFormat)) {
400        format = GL_DEPTH_COMPONENT;
401        channels = 1;
402     } else {
403        format = GL_RGBA;
404        channels = 4;
405     }
406
407     image::Image *image = new image::Image(desc.width, desc.height*desc.depth, channels, true);
408
409     context.resetPixelPackState();
410
411     if (context.ES) {
412         getTexImageOES(target, level, desc, image->pixels);
413     } else {
414         glGetTexImage(target, level, format, GL_UNSIGNED_BYTE, image->pixels);
415     }
416
417     context.restorePixelPackState();
418
419     json.writeImage(image, formatToString(desc.internalFormat), desc.depth);
420
421     delete image;
422
423     json.endMember(); // label
424 }
425
426
427 static inline void
428 dumpTexture(JSONWriter &json, Context &context, GLenum target, GLenum binding)
429 {
430     GLint texture_binding = 0;
431     glGetIntegerv(binding, &texture_binding);
432     if (!glIsEnabled(target) && !texture_binding) {
433         return;
434     }
435
436     GLint level = 0;
437     do {
438         ImageDesc desc;
439
440         if (target == GL_TEXTURE_CUBE_MAP) {
441             for (int face = 0; face < 6; ++face) {
442                 if (!getActiveTextureLevelDesc(context, GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, level, desc)) {
443                     return;
444                 }
445                 dumpActiveTextureLevel(json, context, GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, level);
446             }
447         } else {
448             if (!getActiveTextureLevelDesc(context, target, level, desc)) {
449                 return;
450             }
451             dumpActiveTextureLevel(json, context, target, level);
452         }
453
454         ++level;
455     } while(true);
456 }
457
458
459 void
460 dumpTextures(JSONWriter &json, Context &context)
461 {
462     json.beginMember("textures");
463     json.beginObject();
464     GLint active_texture = GL_TEXTURE0;
465     glGetIntegerv(GL_ACTIVE_TEXTURE, &active_texture);
466
467     GLint max_texture_coords = 0;
468     glGetIntegerv(GL_MAX_TEXTURE_COORDS, &max_texture_coords);
469     GLint max_combined_texture_image_units = 0;
470     glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &max_combined_texture_image_units);
471     GLint max_units = std::max(max_combined_texture_image_units, max_texture_coords);
472
473     /*
474      * At least the Android software GL implementation doesn't return the
475      * proper value for this, but rather returns 0. The GL(ES) specification
476      * mandates a minimum value of 2, so use this as a fall-back value.
477      */
478     max_units = std::max(max_units, 2);
479
480     for (GLint unit = 0; unit < max_units; ++unit) {
481         GLenum texture = GL_TEXTURE0 + unit;
482         glActiveTexture(texture);
483         dumpTexture(json, context, GL_TEXTURE_1D, GL_TEXTURE_BINDING_1D);
484         dumpTexture(json, context, GL_TEXTURE_2D, GL_TEXTURE_BINDING_2D);
485         dumpTexture(json, context, GL_TEXTURE_3D, GL_TEXTURE_BINDING_3D);
486         dumpTexture(json, context, GL_TEXTURE_RECTANGLE, GL_TEXTURE_BINDING_RECTANGLE);
487         dumpTexture(json, context, GL_TEXTURE_CUBE_MAP, GL_TEXTURE_BINDING_CUBE_MAP);
488     }
489     glActiveTexture(active_texture);
490     json.endObject();
491     json.endMember(); // textures
492 }
493
494
495 static bool
496 getDrawableBounds(GLint *width, GLint *height) {
497 #if defined(__linux__)
498     if (dlsym(RTLD_DEFAULT, "eglGetCurrentContext")) {
499         EGLContext currentContext = eglGetCurrentContext();
500         if (currentContext == EGL_NO_CONTEXT) {
501             return false;
502         }
503
504         EGLSurface currentSurface = eglGetCurrentSurface(EGL_DRAW);
505         if (currentSurface == EGL_NO_SURFACE) {
506             return false;
507         }
508
509         EGLDisplay currentDisplay = eglGetCurrentDisplay();
510         if (currentDisplay == EGL_NO_DISPLAY) {
511             return false;
512         }
513
514         if (!eglQuerySurface(currentDisplay, currentSurface, EGL_WIDTH, width) ||
515             !eglQuerySurface(currentDisplay, currentSurface, EGL_HEIGHT, height)) {
516             return false;
517         }
518
519         return true;
520     }
521 #endif
522
523 #if defined(_WIN32)
524
525     HDC hDC = wglGetCurrentDC();
526     if (!hDC) {
527         return false;
528     }
529
530     HWND hWnd = WindowFromDC(hDC);
531     RECT rect;
532
533     if (!GetClientRect(hWnd, &rect)) {
534        return false;
535     }
536
537     *width  = rect.right  - rect.left;
538     *height = rect.bottom - rect.top;
539     return true;
540
541 #elif defined(__APPLE__)
542
543     CGLContextObj ctx = CGLGetCurrentContext();
544     if (ctx == NULL) {
545         return false;
546     }
547
548     CGSConnectionID cid;
549     CGSWindowID wid;
550     CGSSurfaceID sid;
551
552     if (CGLGetSurface(ctx, &cid, &wid, &sid) != kCGLNoError) {
553         return false;
554     }
555
556     CGRect rect;
557
558     if (CGSGetSurfaceBounds(cid, wid, sid, &rect) != 0) {
559         return false;
560     }
561
562     *width = rect.size.width;
563     *height = rect.size.height;
564     return true;
565
566 #elif defined(HAVE_X11)
567
568     Display *display;
569     Drawable drawable;
570     Window root;
571     int x, y;
572     unsigned int w, h, bw, depth;
573
574     display = glXGetCurrentDisplay();
575     if (!display) {
576         return false;
577     }
578
579     drawable = glXGetCurrentDrawable();
580     if (drawable == None) {
581         return false;
582     }
583
584     if (!XGetGeometry(display, drawable, &root, &x, &y, &w, &h, &bw, &depth)) {
585         return false;
586     }
587
588     *width = w;
589     *height = h;
590     return true;
591
592 #else
593
594     return false;
595
596 #endif
597 }
598
599
600 static const GLenum texture_bindings[][2] = {
601     {GL_TEXTURE_1D, GL_TEXTURE_BINDING_1D},
602     {GL_TEXTURE_2D, GL_TEXTURE_BINDING_2D},
603     {GL_TEXTURE_3D, GL_TEXTURE_BINDING_3D},
604     {GL_TEXTURE_RECTANGLE, GL_TEXTURE_BINDING_RECTANGLE},
605     {GL_TEXTURE_CUBE_MAP, GL_TEXTURE_BINDING_CUBE_MAP}
606 };
607
608
609 static bool
610 bindTexture(GLint texture, GLenum &target, GLint &bound_texture)
611 {
612
613     for (unsigned i = 0; i < sizeof(texture_bindings)/sizeof(texture_bindings[0]); ++i) {
614         target  = texture_bindings[i][0];
615
616         GLenum binding = texture_bindings[i][1];
617
618         while (glGetError() != GL_NO_ERROR)
619             ;
620
621         glGetIntegerv(binding, &bound_texture);
622         glBindTexture(target, texture);
623
624         if (glGetError() == GL_NO_ERROR) {
625             return true;
626         }
627
628         glBindTexture(target, bound_texture);
629     }
630
631     target = GL_NONE;
632
633     return false;
634 }
635
636
637 static bool
638 getTextureLevelDesc(Context &context, GLint texture, GLint level, ImageDesc &desc)
639 {
640     GLenum target;
641     GLint bound_texture = 0;
642     if (!bindTexture(texture, target, bound_texture)) {
643         return false;
644     }
645
646     getActiveTextureLevelDesc(context, target, level, desc);
647
648     glBindTexture(target, bound_texture);
649
650     return desc.valid();
651 }
652
653
654 static bool
655 getBoundRenderbufferDesc(Context &context, ImageDesc &desc)
656 {
657     glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &desc.width);
658     glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &desc.height);
659     desc.depth = 1;
660     
661     glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_INTERNAL_FORMAT, &desc.internalFormat);
662     
663     return desc.valid();
664 }
665
666
667 static bool
668 getRenderbufferDesc(Context &context, GLint renderbuffer, ImageDesc &desc)
669 {
670     GLint bound_renderbuffer = 0;
671     glGetIntegerv(GL_RENDERBUFFER_BINDING, &bound_renderbuffer);
672     glBindRenderbuffer(GL_RENDERBUFFER, renderbuffer);
673
674     getBoundRenderbufferDesc(context, desc);
675
676     glBindRenderbuffer(GL_RENDERBUFFER, bound_renderbuffer);
677     
678     return desc.valid();
679 }
680
681
682 static bool
683 getFramebufferAttachmentDesc(Context &context, GLenum target, GLenum attachment, ImageDesc &desc)
684 {
685     GLint object_type = GL_NONE;
686     glGetFramebufferAttachmentParameteriv(target, attachment,
687                                           GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE,
688                                           &object_type);
689     if (object_type == GL_NONE) {
690         return false;
691     }
692
693     GLint object_name = 0;
694     glGetFramebufferAttachmentParameteriv(target, attachment,
695                                           GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME,
696                                           &object_name);
697     if (object_name == 0) {
698         return false;
699     }
700
701     if (object_type == GL_RENDERBUFFER) {
702         return getRenderbufferDesc(context, object_name, desc);
703     } else if (object_type == GL_TEXTURE) {
704         GLint texture_level = 0;
705         glGetFramebufferAttachmentParameteriv(target, attachment,
706                                               GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL,
707                                               &texture_level);
708         return getTextureLevelDesc(context, object_name, texture_level, desc);
709     } else {
710         std::cerr << "warning: unexpected GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE = " << object_type << "\n";
711         return false;
712     }
713 }
714
715
716
717 image::Image *
718 getDrawBufferImage() {
719     GLenum format = GL_RGB;
720     GLint channels = _gl_format_channels(format);
721     if (channels > 4) {
722         return NULL;
723     }
724
725     Context context;
726
727     GLenum framebuffer_binding;
728     GLenum framebuffer_target;
729     if (context.ES) {
730         framebuffer_binding = GL_FRAMEBUFFER_BINDING;
731         framebuffer_target = GL_FRAMEBUFFER;
732     } else {
733         framebuffer_binding = GL_DRAW_FRAMEBUFFER_BINDING;
734         framebuffer_target = GL_DRAW_FRAMEBUFFER;
735     }
736
737     GLint draw_framebuffer = 0;
738     glGetIntegerv(framebuffer_binding, &draw_framebuffer);
739
740     GLint draw_buffer = GL_NONE;
741     ImageDesc desc;
742     if (draw_framebuffer) {
743         if (context.ARB_draw_buffers) {
744             glGetIntegerv(GL_DRAW_BUFFER0, &draw_buffer);
745             if (draw_buffer == GL_NONE) {
746                 return NULL;
747             }
748         } else {
749             // GL_COLOR_ATTACHMENT0 is implied
750             draw_buffer = GL_COLOR_ATTACHMENT0;
751         }
752
753         if (!getFramebufferAttachmentDesc(context, framebuffer_target, draw_buffer, desc)) {
754             return NULL;
755         }
756     } else {
757         if (context.ES) {
758             // XXX: Draw buffer is always FRONT for single buffer context, BACK
759             // for double buffered contexts. There is no way to know which (as
760             // GL_DOUBLEBUFFER state is also unavailable), so always assume
761             // double-buffering.
762             draw_buffer = GL_BACK;
763         } else {
764             glGetIntegerv(GL_DRAW_BUFFER, &draw_buffer);
765             if (draw_buffer == GL_NONE) {
766                 return NULL;
767             }
768         }
769
770         if (!getDrawableBounds(&desc.width, &desc.height)) {
771             return NULL;
772         }
773
774         desc.depth = 1;
775     }
776
777     GLenum type = GL_UNSIGNED_BYTE;
778
779 #if DEPTH_AS_RGBA
780     if (format == GL_DEPTH_COMPONENT) {
781         type = GL_UNSIGNED_INT;
782         channels = 4;
783     }
784 #endif
785
786     image::Image *image = new image::Image(desc.width, desc.height, channels, true);
787     if (!image) {
788         return NULL;
789     }
790
791     while (glGetError() != GL_NO_ERROR) {}
792
793     GLint read_framebuffer = 0;
794     GLint read_buffer = GL_NONE;
795     if (!context.ES) {
796         glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &read_framebuffer);
797         glBindFramebuffer(GL_READ_FRAMEBUFFER, draw_framebuffer);
798
799         glGetIntegerv(GL_READ_BUFFER, &read_buffer);
800         glReadBuffer(draw_buffer);
801     }
802
803     // TODO: reset imaging state too
804     context.resetPixelPackState();
805
806     glReadPixels(0, 0, desc.width, desc.height, format, type, image->pixels);
807
808     context.restorePixelPackState();
809
810     if (!context.ES) {
811         glReadBuffer(read_buffer);
812         glBindFramebuffer(GL_READ_FRAMEBUFFER, read_framebuffer);
813     }
814
815     GLenum error = glGetError();
816     if (error != GL_NO_ERROR) {
817         do {
818             std::cerr << "warning: " << enumToString(error) << " while getting snapshot\n";
819             error = glGetError();
820         } while(error != GL_NO_ERROR);
821         delete image;
822         return NULL;
823     }
824      
825     return image;
826 }
827
828
829 /**
830  * Dump the image of the currently bound read buffer.
831  */
832 static inline void
833 dumpReadBufferImage(JSONWriter &json, GLint width, GLint height, GLenum format,
834                     GLint internalFormat = GL_NONE)
835 {
836     GLint channels = _gl_format_channels(format);
837
838     if (internalFormat == GL_NONE) {
839         internalFormat = format;
840     }
841
842     Context context;
843
844     GLenum type = GL_UNSIGNED_BYTE;
845
846 #if DEPTH_AS_RGBA
847     if (format == GL_DEPTH_COMPONENT) {
848         type = GL_UNSIGNED_INT;
849         channels = 4;
850     }
851 #endif
852
853     image::Image *image = new image::Image(width, height, channels, true);
854
855     // TODO: reset imaging state too
856     context.resetPixelPackState();
857
858     glReadPixels(0, 0, width, height, format, type, image->pixels);
859
860     context.restorePixelPackState();
861
862     json.writeImage(image, formatToString(internalFormat));
863
864     delete image;
865 }
866
867
868 static inline GLuint
869 downsampledFramebuffer(Context &context,
870                        GLuint oldFbo, GLint drawbuffer,
871                        GLint colorRb, GLint depthRb, GLint stencilRb,
872                        GLuint *rbs, GLint *numRbs)
873 {
874     GLuint fbo;
875
876
877     *numRbs = 0;
878
879     glGenFramebuffers(1, &fbo);
880     glBindFramebuffer(GL_FRAMEBUFFER, fbo);
881
882     {
883         // color buffer
884         ImageDesc desc;
885         glBindRenderbuffer(GL_RENDERBUFFER, colorRb);
886         getBoundRenderbufferDesc(context, desc);
887
888         glGenRenderbuffers(1, &rbs[*numRbs]);
889         glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]);
890         glRenderbufferStorage(GL_RENDERBUFFER, desc.internalFormat, desc.width, desc.height);
891         glFramebufferRenderbuffer(GL_FRAMEBUFFER, drawbuffer,
892                                   GL_RENDERBUFFER, rbs[*numRbs]);
893
894         glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo);
895         glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
896         glDrawBuffer(drawbuffer);
897         glReadBuffer(drawbuffer);
898         glBlitFramebuffer(0, 0, desc.width, desc.height, 0, 0, desc.width, desc.height,
899                           GL_COLOR_BUFFER_BIT, GL_NEAREST);
900         glBindFramebuffer(GL_FRAMEBUFFER, fbo);
901         ++*numRbs;
902     }
903
904     if (stencilRb == depthRb && stencilRb) {
905         //combined depth and stencil buffer
906         ImageDesc desc;
907         glBindRenderbuffer(GL_RENDERBUFFER, depthRb);
908         getBoundRenderbufferDesc(context, desc);
909
910         glGenRenderbuffers(1, &rbs[*numRbs]);
911         glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]);
912         glRenderbufferStorage(GL_RENDERBUFFER, desc.internalFormat, desc.width, desc.height);
913         glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT,
914                                   GL_RENDERBUFFER, rbs[*numRbs]);
915         glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo);
916         glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
917         glBlitFramebuffer(0, 0, desc.width, desc.height, 0, 0, desc.width, desc.height,
918                           GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT, GL_NEAREST);
919         glBindFramebuffer(GL_FRAMEBUFFER, fbo);
920         ++*numRbs;
921     } else {
922         if (depthRb) {
923             ImageDesc desc;
924             glBindRenderbuffer(GL_RENDERBUFFER, depthRb);
925             getBoundRenderbufferDesc(context, desc);
926
927             glGenRenderbuffers(1, &rbs[*numRbs]);
928             glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]);
929             glRenderbufferStorage(GL_RENDERBUFFER, desc.internalFormat, desc.width, desc.height);
930             glFramebufferRenderbuffer(GL_FRAMEBUFFER,
931                                       GL_DEPTH_ATTACHMENT,
932                                       GL_RENDERBUFFER, rbs[*numRbs]);
933             glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo);
934             glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
935             glDrawBuffer(GL_DEPTH_ATTACHMENT);
936             glReadBuffer(GL_DEPTH_ATTACHMENT);
937             glBlitFramebuffer(0, 0, desc.width, desc.height, 0, 0, desc.width, desc.height,
938                               GL_DEPTH_BUFFER_BIT, GL_NEAREST);
939             ++*numRbs;
940         }
941         if (stencilRb) {
942             ImageDesc desc;
943             glBindRenderbuffer(GL_RENDERBUFFER, stencilRb);
944             getBoundRenderbufferDesc(context, desc);
945
946             glGenRenderbuffers(1, &rbs[*numRbs]);
947             glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]);
948             glRenderbufferStorage(GL_RENDERBUFFER, desc.internalFormat, desc.width, desc.height);
949             glFramebufferRenderbuffer(GL_FRAMEBUFFER,
950                                       GL_STENCIL_ATTACHMENT,
951                                       GL_RENDERBUFFER, rbs[*numRbs]);
952             glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo);
953             glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
954             glDrawBuffer(GL_STENCIL_ATTACHMENT);
955             glReadBuffer(GL_STENCIL_ATTACHMENT);
956             glBlitFramebuffer(0, 0, desc.width, desc.height, 0, 0, desc.width, desc.height,
957                               GL_STENCIL_BUFFER_BIT, GL_NEAREST);
958             ++*numRbs;
959         }
960     }
961
962     return fbo;
963 }
964
965
966 /**
967  * Dump images of current draw drawable/window.
968  */
969 static void
970 dumpDrawableImages(JSONWriter &json, Context &context)
971 {
972     GLint width, height;
973
974     if (!getDrawableBounds(&width, &height)) {
975         return;
976     }
977
978     GLint draw_buffer = GL_NONE;
979     if (context.ES) {
980         // XXX: Draw buffer is always FRONT for single buffer context, BACK for
981         // double buffered contexts. There is no way to know which (as
982         // GL_DOUBLEBUFFER state is also unavailable), so always assume
983         // double-buffering.
984         draw_buffer = GL_BACK;
985     } else {
986         glGetIntegerv(GL_DRAW_BUFFER, &draw_buffer);
987     }
988
989     if (draw_buffer != GL_NONE) {
990         // Read from current draw buffer
991         GLint read_buffer = GL_NONE;
992         if (!context.ES) {
993             glGetIntegerv(GL_READ_BUFFER, &read_buffer);
994             glReadBuffer(draw_buffer);
995         }
996
997         GLint alpha_bits = 0;
998 #if 0
999         // XXX: Ignore alpha until we are able to match the traced visual
1000         glGetIntegerv(GL_ALPHA_BITS, &alpha_bits);
1001 #endif
1002         GLenum format = alpha_bits ? GL_RGBA : GL_RGB;
1003         json.beginMember(enumToString(draw_buffer));
1004         dumpReadBufferImage(json, width, height, format);
1005         json.endMember();
1006
1007         // Restore original read buffer
1008         if (!context.ES) {
1009             glReadBuffer(read_buffer);
1010         }
1011     }
1012
1013     if (!context.ES) {
1014         GLint depth_bits = 0;
1015         glGetIntegerv(GL_DEPTH_BITS, &depth_bits);
1016         if (depth_bits) {
1017             json.beginMember("GL_DEPTH_COMPONENT");
1018             dumpReadBufferImage(json, width, height, GL_DEPTH_COMPONENT);
1019             json.endMember();
1020         }
1021
1022         GLint stencil_bits = 0;
1023         glGetIntegerv(GL_STENCIL_BITS, &stencil_bits);
1024         if (stencil_bits) {
1025             json.beginMember("GL_STENCIL_INDEX");
1026             dumpReadBufferImage(json, width, height, GL_STENCIL_INDEX);
1027             json.endMember();
1028         }
1029     }
1030 }
1031
1032
1033 /**
1034  * Dump the specified framebuffer attachment.
1035  *
1036  * In the case of a color attachment, it assumes it is already bound for read.
1037  */
1038 static void
1039 dumpFramebufferAttachment(JSONWriter &json, Context &context, GLenum target, GLenum attachment, GLenum format)
1040 {
1041     ImageDesc desc;
1042     if (!getFramebufferAttachmentDesc(context, target, attachment, desc)) {
1043         return;
1044     }
1045
1046     json.beginMember(enumToString(attachment));
1047     dumpReadBufferImage(json, desc.width, desc.height, format, desc.internalFormat);
1048     json.endMember();
1049 }
1050
1051
1052 static void
1053 dumpFramebufferAttachments(JSONWriter &json, Context &context, GLenum target)
1054 {
1055     GLint read_framebuffer = 0;
1056     glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &read_framebuffer);
1057
1058     GLint read_buffer = GL_NONE;
1059     glGetIntegerv(GL_READ_BUFFER, &read_buffer);
1060
1061     GLint max_draw_buffers = 1;
1062     glGetIntegerv(GL_MAX_DRAW_BUFFERS, &max_draw_buffers);
1063     GLint max_color_attachments = 0;
1064     glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS, &max_color_attachments);
1065
1066     for (GLint i = 0; i < max_draw_buffers; ++i) {
1067         GLint draw_buffer = GL_NONE;
1068         glGetIntegerv(GL_DRAW_BUFFER0 + i, &draw_buffer);
1069         if (draw_buffer != GL_NONE) {
1070             glReadBuffer(draw_buffer);
1071             GLint attachment;
1072             if (draw_buffer >= GL_COLOR_ATTACHMENT0 && draw_buffer < GL_COLOR_ATTACHMENT0 + max_color_attachments) {
1073                 attachment = draw_buffer;
1074             } else {
1075                 std::cerr << "warning: unexpected GL_DRAW_BUFFER" << i << " = " << draw_buffer << "\n";
1076                 attachment = GL_COLOR_ATTACHMENT0;
1077             }
1078             GLint alpha_size = 0;
1079             glGetFramebufferAttachmentParameteriv(target, attachment,
1080                                                   GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE,
1081                                                   &alpha_size);
1082             GLenum format = alpha_size ? GL_RGBA : GL_RGB;
1083             dumpFramebufferAttachment(json, context, target, attachment, format);
1084         }
1085     }
1086
1087     glReadBuffer(read_buffer);
1088
1089     if (!context.ES) {
1090         dumpFramebufferAttachment(json, context, target, GL_DEPTH_ATTACHMENT, GL_DEPTH_COMPONENT);
1091         dumpFramebufferAttachment(json, context, target, GL_STENCIL_ATTACHMENT, GL_STENCIL_INDEX);
1092     }
1093
1094     glBindFramebuffer(GL_READ_FRAMEBUFFER, read_framebuffer);
1095 }
1096
1097
1098 void
1099 dumpFramebuffer(JSONWriter &json, Context &context)
1100 {
1101     json.beginMember("framebuffer");
1102     json.beginObject();
1103
1104     GLint boundDrawFbo = 0, boundReadFbo = 0;
1105     glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &boundDrawFbo);
1106     glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &boundReadFbo);
1107     if (!boundDrawFbo) {
1108         dumpDrawableImages(json, context);
1109     } else if (context.ES) {
1110         dumpFramebufferAttachments(json, context, GL_FRAMEBUFFER);
1111     } else {
1112         GLint colorRb = 0, stencilRb = 0, depthRb = 0;
1113         GLint draw_buffer0 = GL_NONE;
1114         glGetIntegerv(GL_DRAW_BUFFER0, &draw_buffer0);
1115         bool multisample = false;
1116
1117         GLint boundRb = 0;
1118         glGetIntegerv(GL_RENDERBUFFER_BINDING, &boundRb);
1119
1120         GLint object_type;
1121         glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, draw_buffer0, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, &object_type);
1122         if (object_type == GL_RENDERBUFFER) {
1123             glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, draw_buffer0, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, &colorRb);
1124             glBindRenderbuffer(GL_RENDERBUFFER, colorRb);
1125             GLint samples = 0;
1126             glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_SAMPLES, &samples);
1127             if (samples) {
1128                 multisample = true;
1129             }
1130         }
1131
1132         glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, &object_type);
1133         if (object_type == GL_RENDERBUFFER) {
1134             glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, &depthRb);
1135             glBindRenderbuffer(GL_RENDERBUFFER, depthRb);
1136             GLint samples = 0;
1137             glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_SAMPLES, &samples);
1138             if (samples) {
1139                 multisample = true;
1140             }
1141         }
1142
1143         glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, &object_type);
1144         if (object_type == GL_RENDERBUFFER) {
1145             glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, &stencilRb);
1146             glBindRenderbuffer(GL_RENDERBUFFER, stencilRb);
1147             GLint samples = 0;
1148             glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_SAMPLES, &samples);
1149             if (samples) {
1150                 multisample = true;
1151             }
1152         }
1153
1154         glBindRenderbuffer(GL_RENDERBUFFER, boundRb);
1155
1156         GLuint rbs[3];
1157         GLint numRbs = 0;
1158         GLuint fboCopy = 0;
1159
1160         if (multisample) {
1161             // glReadPixels doesnt support multisampled buffers so we need
1162             // to blit the fbo to a temporary one
1163             fboCopy = downsampledFramebuffer(context,
1164                                              boundDrawFbo, draw_buffer0,
1165                                              colorRb, depthRb, stencilRb,
1166                                              rbs, &numRbs);
1167         }
1168
1169         dumpFramebufferAttachments(json, context, GL_DRAW_FRAMEBUFFER);
1170
1171         if (multisample) {
1172             glBindRenderbuffer(GL_RENDERBUFFER_BINDING, boundRb);
1173             glDeleteRenderbuffers(numRbs, rbs);
1174             glDeleteFramebuffers(1, &fboCopy);
1175         }
1176
1177         glBindFramebuffer(GL_READ_FRAMEBUFFER, boundReadFbo);
1178         glBindFramebuffer(GL_DRAW_FRAMEBUFFER, boundDrawFbo);
1179     }
1180
1181     json.endObject();
1182     json.endMember(); // framebuffer
1183 }
1184
1185
1186 } /* namespace glstate */