]> git.cworth.org Git - apitrace/blob - retrace/glstate_images.cpp
glstate: Fix typo in glBindRenderbuffer argument.
[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 static GLenum
291 getTextureBinding(GLenum target)
292 {
293     switch (target) {
294     case GL_TEXTURE_1D:
295         return GL_TEXTURE_BINDING_1D;
296     case GL_TEXTURE_1D_ARRAY:
297         return GL_TEXTURE_BINDING_1D_ARRAY;
298     case GL_TEXTURE_2D:
299         return GL_TEXTURE_BINDING_2D;
300     case GL_TEXTURE_2D_MULTISAMPLE:
301         return GL_TEXTURE_BINDING_2D_MULTISAMPLE;
302     case GL_TEXTURE_2D_ARRAY:
303         return GL_TEXTURE_BINDING_2D_ARRAY;
304     case GL_TEXTURE_RECTANGLE:
305         return GL_TEXTURE_BINDING_RECTANGLE;
306     case GL_TEXTURE_CUBE_MAP:
307     case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
308     case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
309     case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
310     case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
311     case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
312     case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
313         return GL_TEXTURE_BINDING_CUBE_MAP;
314     case GL_TEXTURE_CUBE_MAP_ARRAY:
315         return GL_TEXTURE_BINDING_CUBE_MAP_ARRAY;
316     case GL_TEXTURE_3D:
317         return GL_TEXTURE_BINDING_3D;
318     default:
319         assert(false);
320         return GL_NONE;
321     }
322 }
323
324
325 /**
326  * OpenGL ES does not support glGetTexImage. Obtain the pixels by attaching the
327  * texture to a framebuffer.
328  */
329 static inline void
330 getTexImageOES(GLenum target, GLint level, ImageDesc &desc, GLubyte *pixels)
331 {
332     memset(pixels, 0x80, desc.height * desc.width * 4);
333
334     GLenum texture_binding = getTextureBinding(target);
335     if (texture_binding == GL_NONE) {
336         return;
337     }
338
339     GLint texture = 0;
340     glGetIntegerv(texture_binding, &texture);
341     if (!texture) {
342         return;
343     }
344
345     GLint prev_fbo = 0;
346     GLuint fbo = 0;
347     glGetIntegerv(GL_FRAMEBUFFER_BINDING, &prev_fbo);
348     glGenFramebuffers(1, &fbo);
349     glBindFramebuffer(GL_FRAMEBUFFER, fbo);
350
351     GLenum status;
352
353     switch (target) {
354     case GL_TEXTURE_2D:
355     case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
356     case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
357     case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
358     case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
359     case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
360     case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
361         glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture, level);
362         status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
363         if (status != GL_FRAMEBUFFER_COMPLETE) {
364             std::cerr << __FUNCTION__ << ": " << enumToString(status) << "\n";
365         }
366         glReadPixels(0, 0, desc.width, desc.height, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
367         break;
368     case GL_TEXTURE_3D_OES:
369         for (int i = 0; i < desc.depth; i++) {
370             glFramebufferTexture3D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_3D, texture, level, i);
371             glReadPixels(0, 0, desc.width, desc.height, GL_RGBA, GL_UNSIGNED_BYTE, pixels + 4 * i * desc.width * desc.height);
372         }
373         break;
374     }
375
376     glBindFramebuffer(GL_FRAMEBUFFER, prev_fbo);
377
378     glDeleteFramebuffers(1, &fbo);
379 }
380
381
382 static inline GLboolean
383 isDepthFormat(GLenum internalFormat)
384 {
385    switch (internalFormat) {
386    case GL_DEPTH_COMPONENT:
387    case GL_DEPTH_COMPONENT16:
388    case GL_DEPTH_COMPONENT24:
389    case GL_DEPTH_COMPONENT32:
390    case GL_DEPTH_COMPONENT32F:
391    case GL_DEPTH_COMPONENT32F_NV:
392    case GL_DEPTH_STENCIL:
393    case GL_DEPTH24_STENCIL8:
394    case GL_DEPTH32F_STENCIL8:
395    case GL_DEPTH32F_STENCIL8_NV:
396       return GL_TRUE;
397    }
398    return GL_FALSE;
399 }
400
401
402 static inline void
403 dumpActiveTextureLevel(JSONWriter &json, Context &context, GLenum target, GLint level)
404 {
405     ImageDesc desc;
406     if (!getActiveTextureLevelDesc(context, target, level, desc)) {
407         return;
408     }
409
410     char label[512];
411     GLint active_texture = GL_TEXTURE0;
412     glGetIntegerv(GL_ACTIVE_TEXTURE, &active_texture);
413     snprintf(label, sizeof label, "%s, %s, level = %d",
414              enumToString(active_texture), enumToString(target), level);
415
416     json.beginMember(label);
417
418     GLuint channels;
419     GLenum format;
420     if (!context.ES && isDepthFormat(desc.internalFormat)) {
421        format = GL_DEPTH_COMPONENT;
422        channels = 1;
423     } else {
424        format = GL_RGBA;
425        channels = 4;
426     }
427
428     image::Image *image = new image::Image(desc.width, desc.height*desc.depth, channels, true);
429
430     context.resetPixelPackState();
431
432     if (context.ES) {
433         getTexImageOES(target, level, desc, image->pixels);
434     } else {
435         glGetTexImage(target, level, format, GL_UNSIGNED_BYTE, image->pixels);
436     }
437
438     context.restorePixelPackState();
439
440     json.writeImage(image, formatToString(desc.internalFormat), desc.depth);
441
442     delete image;
443
444     json.endMember(); // label
445 }
446
447
448 static inline void
449 dumpTexture(JSONWriter &json, Context &context, GLenum target, GLenum binding)
450 {
451     GLint texture_binding = 0;
452     glGetIntegerv(binding, &texture_binding);
453     if (!glIsEnabled(target) && !texture_binding) {
454         return;
455     }
456
457     GLint level = 0;
458     do {
459         ImageDesc desc;
460
461         if (target == GL_TEXTURE_CUBE_MAP) {
462             for (int face = 0; face < 6; ++face) {
463                 if (!getActiveTextureLevelDesc(context, GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, level, desc)) {
464                     return;
465                 }
466                 dumpActiveTextureLevel(json, context, GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, level);
467             }
468         } else {
469             if (!getActiveTextureLevelDesc(context, target, level, desc)) {
470                 return;
471             }
472             dumpActiveTextureLevel(json, context, target, level);
473         }
474
475         ++level;
476     } while(true);
477 }
478
479
480 void
481 dumpTextures(JSONWriter &json, Context &context)
482 {
483     json.beginMember("textures");
484     json.beginObject();
485     GLint active_texture = GL_TEXTURE0;
486     glGetIntegerv(GL_ACTIVE_TEXTURE, &active_texture);
487
488     GLint max_texture_coords = 0;
489     glGetIntegerv(GL_MAX_TEXTURE_COORDS, &max_texture_coords);
490     GLint max_combined_texture_image_units = 0;
491     glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &max_combined_texture_image_units);
492     GLint max_units = std::max(max_combined_texture_image_units, max_texture_coords);
493
494     /*
495      * At least the Android software GL implementation doesn't return the
496      * proper value for this, but rather returns 0. The GL(ES) specification
497      * mandates a minimum value of 2, so use this as a fall-back value.
498      */
499     max_units = std::max(max_units, 2);
500
501     for (GLint unit = 0; unit < max_units; ++unit) {
502         GLenum texture = GL_TEXTURE0 + unit;
503         glActiveTexture(texture);
504         dumpTexture(json, context, GL_TEXTURE_1D, GL_TEXTURE_BINDING_1D);
505         dumpTexture(json, context, GL_TEXTURE_2D, GL_TEXTURE_BINDING_2D);
506         dumpTexture(json, context, GL_TEXTURE_3D, GL_TEXTURE_BINDING_3D);
507         dumpTexture(json, context, GL_TEXTURE_RECTANGLE, GL_TEXTURE_BINDING_RECTANGLE);
508         dumpTexture(json, context, GL_TEXTURE_CUBE_MAP, GL_TEXTURE_BINDING_CUBE_MAP);
509     }
510     glActiveTexture(active_texture);
511     json.endObject();
512     json.endMember(); // textures
513 }
514
515
516 static bool
517 getDrawableBounds(GLint *width, GLint *height) {
518 #if defined(__linux__)
519     if (dlsym(RTLD_DEFAULT, "eglGetCurrentContext")) {
520         EGLContext currentContext = eglGetCurrentContext();
521         if (currentContext != EGL_NO_CONTEXT) {
522             EGLSurface currentSurface = eglGetCurrentSurface(EGL_DRAW);
523             if (currentSurface == EGL_NO_SURFACE) {
524                 return false;
525             }
526
527             EGLDisplay currentDisplay = eglGetCurrentDisplay();
528             if (currentDisplay == EGL_NO_DISPLAY) {
529                 return false;
530             }
531
532             if (!eglQuerySurface(currentDisplay, currentSurface, EGL_WIDTH, width) ||
533                 !eglQuerySurface(currentDisplay, currentSurface, EGL_HEIGHT, height)) {
534                 return false;
535             }
536
537             return true;
538         }
539     }
540 #endif
541
542 #if defined(_WIN32)
543
544     HDC hDC = wglGetCurrentDC();
545     if (!hDC) {
546         return false;
547     }
548
549     HWND hWnd = WindowFromDC(hDC);
550     RECT rect;
551
552     if (!GetClientRect(hWnd, &rect)) {
553        return false;
554     }
555
556     *width  = rect.right  - rect.left;
557     *height = rect.bottom - rect.top;
558     return true;
559
560 #elif defined(__APPLE__)
561
562     CGLContextObj ctx = CGLGetCurrentContext();
563     if (ctx == NULL) {
564         return false;
565     }
566
567     CGSConnectionID cid;
568     CGSWindowID wid;
569     CGSSurfaceID sid;
570
571     if (CGLGetSurface(ctx, &cid, &wid, &sid) != kCGLNoError) {
572         return false;
573     }
574
575     CGRect rect;
576
577     if (CGSGetSurfaceBounds(cid, wid, sid, &rect) != 0) {
578         return false;
579     }
580
581     *width = rect.size.width;
582     *height = rect.size.height;
583     return true;
584
585 #elif defined(HAVE_X11)
586
587     Display *display;
588     Drawable drawable;
589     Window root;
590     int x, y;
591     unsigned int w, h, bw, depth;
592
593     display = glXGetCurrentDisplay();
594     if (!display) {
595         return false;
596     }
597
598     drawable = glXGetCurrentDrawable();
599     if (drawable == None) {
600         return false;
601     }
602
603     if (!XGetGeometry(display, drawable, &root, &x, &y, &w, &h, &bw, &depth)) {
604         return false;
605     }
606
607     *width = w;
608     *height = h;
609     return true;
610
611 #else
612
613     return false;
614
615 #endif
616 }
617
618
619 struct TextureTargetBinding
620 {
621     GLenum target;
622     GLenum binding;
623 };
624
625
626 static const GLenum
627 textureTargets[] = {
628     GL_TEXTURE_1D,
629     GL_TEXTURE_2D,
630     GL_TEXTURE_RECTANGLE,
631     GL_TEXTURE_CUBE_MAP,
632     GL_TEXTURE_3D,
633     GL_TEXTURE_2D_MULTISAMPLE,
634     GL_TEXTURE_1D_ARRAY,
635     GL_TEXTURE_2D_ARRAY,
636     GL_TEXTURE_CUBE_MAP_ARRAY,
637 };
638
639
640 static GLenum
641 getTextureTarget(GLint texture)
642 {
643     if (!glIsTexture(texture)) {
644         return GL_NONE;
645     }
646
647     for (unsigned i = 0; i < sizeof(textureTargets)/sizeof(textureTargets[0]); ++i) {
648         GLenum target = textureTargets[i];
649         GLenum binding = getTextureBinding(target);
650
651         while (glGetError() != GL_NO_ERROR)
652             ;
653
654         GLint bound_texture = 0;
655         glGetIntegerv(binding, &bound_texture);
656         glBindTexture(target, texture);
657
658         bool succeeded = glGetError() == GL_NO_ERROR;
659
660         glBindTexture(target, bound_texture);
661
662         if (succeeded) {
663             return target;
664         }
665     }
666
667     return GL_NONE;
668 }
669
670
671 static bool
672 getBoundRenderbufferDesc(Context &context, ImageDesc &desc)
673 {
674     glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &desc.width);
675     glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &desc.height);
676     desc.depth = 1;
677     
678     glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_INTERNAL_FORMAT, &desc.internalFormat);
679     
680     return desc.valid();
681 }
682
683
684 static bool
685 getRenderbufferDesc(Context &context, GLint renderbuffer, ImageDesc &desc)
686 {
687     GLint bound_renderbuffer = 0;
688     glGetIntegerv(GL_RENDERBUFFER_BINDING, &bound_renderbuffer);
689     glBindRenderbuffer(GL_RENDERBUFFER, renderbuffer);
690
691     getBoundRenderbufferDesc(context, desc);
692
693     glBindRenderbuffer(GL_RENDERBUFFER, bound_renderbuffer);
694     
695     return desc.valid();
696 }
697
698
699 static bool
700 getFramebufferAttachmentDesc(Context &context, GLenum target, GLenum attachment, ImageDesc &desc)
701 {
702     GLint object_type = GL_NONE;
703     glGetFramebufferAttachmentParameteriv(target, attachment,
704                                           GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE,
705                                           &object_type);
706     if (object_type == GL_NONE) {
707         return false;
708     }
709
710     GLint object_name = 0;
711     glGetFramebufferAttachmentParameteriv(target, attachment,
712                                           GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME,
713                                           &object_name);
714     if (object_name == 0) {
715         return false;
716     }
717
718     if (object_type == GL_RENDERBUFFER) {
719         return getRenderbufferDesc(context, object_name, desc);
720     } else if (object_type == GL_TEXTURE) {
721         GLint texture_face = 0;
722         glGetFramebufferAttachmentParameteriv(target, attachment,
723                                               GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE,
724                                               &texture_face);
725
726         GLint texture_level = 0;
727         glGetFramebufferAttachmentParameteriv(target, attachment,
728                                               GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL,
729                                               &texture_level);
730
731         GLint bound_texture = 0;
732         if (texture_face != 0) {
733             glGetIntegerv(GL_TEXTURE_BINDING_CUBE_MAP, &bound_texture);
734             glBindTexture(GL_TEXTURE_CUBE_MAP, object_name);
735             getActiveTextureLevelDesc(context, texture_face, texture_level, desc);
736             glBindTexture(GL_TEXTURE_CUBE_MAP, bound_texture);
737         } else {
738             GLenum texture_target = getTextureTarget(object_name);
739             GLenum texture_binding = getTextureBinding(texture_target);
740             glGetIntegerv(texture_binding, &bound_texture);
741             glBindTexture(texture_target, object_name);
742             getActiveTextureLevelDesc(context, texture_target, texture_level, desc);
743             glBindTexture(texture_target, bound_texture);
744         }
745
746         return desc.valid();
747     } else {
748         std::cerr << "warning: unexpected GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE = " << object_type << "\n";
749         return false;
750     }
751 }
752
753
754
755 image::Image *
756 getDrawBufferImage() {
757     GLenum format = GL_RGB;
758     GLint channels = _gl_format_channels(format);
759     if (channels > 4) {
760         return NULL;
761     }
762
763     Context context;
764
765     GLenum framebuffer_binding;
766     GLenum framebuffer_target;
767     if (context.ES) {
768         framebuffer_binding = GL_FRAMEBUFFER_BINDING;
769         framebuffer_target = GL_FRAMEBUFFER;
770     } else {
771         framebuffer_binding = GL_DRAW_FRAMEBUFFER_BINDING;
772         framebuffer_target = GL_DRAW_FRAMEBUFFER;
773     }
774
775     GLint draw_framebuffer = 0;
776     glGetIntegerv(framebuffer_binding, &draw_framebuffer);
777
778     GLint draw_buffer = GL_NONE;
779     ImageDesc desc;
780     if (draw_framebuffer) {
781         if (context.ARB_draw_buffers) {
782             glGetIntegerv(GL_DRAW_BUFFER0, &draw_buffer);
783             if (draw_buffer == GL_NONE) {
784                 return NULL;
785             }
786         } else {
787             // GL_COLOR_ATTACHMENT0 is implied
788             draw_buffer = GL_COLOR_ATTACHMENT0;
789         }
790
791         if (!getFramebufferAttachmentDesc(context, framebuffer_target, draw_buffer, desc)) {
792             return NULL;
793         }
794     } else {
795         if (context.ES) {
796             // XXX: Draw buffer is always FRONT for single buffer context, BACK
797             // for double buffered contexts. There is no way to know which (as
798             // GL_DOUBLEBUFFER state is also unavailable), so always assume
799             // double-buffering.
800             draw_buffer = GL_BACK;
801         } else {
802             glGetIntegerv(GL_DRAW_BUFFER, &draw_buffer);
803             if (draw_buffer == GL_NONE) {
804                 return NULL;
805             }
806         }
807
808         if (!getDrawableBounds(&desc.width, &desc.height)) {
809             return NULL;
810         }
811
812         desc.depth = 1;
813     }
814
815     GLenum type = GL_UNSIGNED_BYTE;
816
817 #if DEPTH_AS_RGBA
818     if (format == GL_DEPTH_COMPONENT) {
819         type = GL_UNSIGNED_INT;
820         channels = 4;
821     }
822 #endif
823
824     image::Image *image = new image::Image(desc.width, desc.height, channels, true);
825     if (!image) {
826         return NULL;
827     }
828
829     while (glGetError() != GL_NO_ERROR) {}
830
831     GLint read_framebuffer = 0;
832     GLint read_buffer = GL_NONE;
833     if (!context.ES) {
834         glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &read_framebuffer);
835         glBindFramebuffer(GL_READ_FRAMEBUFFER, draw_framebuffer);
836
837         glGetIntegerv(GL_READ_BUFFER, &read_buffer);
838         glReadBuffer(draw_buffer);
839     }
840
841     // TODO: reset imaging state too
842     context.resetPixelPackState();
843
844     glReadPixels(0, 0, desc.width, desc.height, format, type, image->pixels);
845
846     context.restorePixelPackState();
847
848     if (!context.ES) {
849         glReadBuffer(read_buffer);
850         glBindFramebuffer(GL_READ_FRAMEBUFFER, read_framebuffer);
851     }
852
853     GLenum error = glGetError();
854     if (error != GL_NO_ERROR) {
855         do {
856             std::cerr << "warning: " << enumToString(error) << " while getting snapshot\n";
857             error = glGetError();
858         } while(error != GL_NO_ERROR);
859         delete image;
860         return NULL;
861     }
862      
863     return image;
864 }
865
866
867 /**
868  * Dump the image of the currently bound read buffer.
869  */
870 static inline void
871 dumpReadBufferImage(JSONWriter &json, GLint width, GLint height, GLenum format,
872                     GLint internalFormat = GL_NONE)
873 {
874     GLint channels = _gl_format_channels(format);
875
876     if (internalFormat == GL_NONE) {
877         internalFormat = format;
878     }
879
880     Context context;
881
882     GLenum type = GL_UNSIGNED_BYTE;
883
884 #if DEPTH_AS_RGBA
885     if (format == GL_DEPTH_COMPONENT) {
886         type = GL_UNSIGNED_INT;
887         channels = 4;
888     }
889 #endif
890
891     image::Image *image = new image::Image(width, height, channels, true);
892
893     while (glGetError() != GL_NO_ERROR) {}
894
895     // TODO: reset imaging state too
896     context.resetPixelPackState();
897
898     glReadPixels(0, 0, width, height, format, type, image->pixels);
899
900     context.restorePixelPackState();
901
902     GLenum error = glGetError();
903     if (error != GL_NO_ERROR) {
904         do {
905             std::cerr << "warning: " << enumToString(error) << " while reading framebuffer\n";
906             error = glGetError();
907         } while(error != GL_NO_ERROR);
908         json.writeNull();
909     } else {
910         json.writeImage(image, formatToString(internalFormat));
911     }
912
913     delete image;
914 }
915
916
917 static inline GLuint
918 downsampledFramebuffer(Context &context,
919                        GLuint oldFbo, GLint drawbuffer,
920                        GLint colorRb, GLint depthRb, GLint stencilRb,
921                        GLuint *rbs, GLint *numRbs)
922 {
923     GLuint fbo;
924
925
926     *numRbs = 0;
927
928     glGenFramebuffers(1, &fbo);
929     glBindFramebuffer(GL_FRAMEBUFFER, fbo);
930
931     {
932         // color buffer
933         ImageDesc desc;
934         glBindRenderbuffer(GL_RENDERBUFFER, colorRb);
935         getBoundRenderbufferDesc(context, desc);
936
937         glGenRenderbuffers(1, &rbs[*numRbs]);
938         glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]);
939         glRenderbufferStorage(GL_RENDERBUFFER, desc.internalFormat, desc.width, desc.height);
940         glFramebufferRenderbuffer(GL_FRAMEBUFFER, drawbuffer,
941                                   GL_RENDERBUFFER, rbs[*numRbs]);
942
943         glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo);
944         glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
945         glDrawBuffer(drawbuffer);
946         glReadBuffer(drawbuffer);
947         glBlitFramebuffer(0, 0, desc.width, desc.height, 0, 0, desc.width, desc.height,
948                           GL_COLOR_BUFFER_BIT, GL_NEAREST);
949         glBindFramebuffer(GL_FRAMEBUFFER, fbo);
950         ++*numRbs;
951     }
952
953     if (stencilRb == depthRb && stencilRb) {
954         //combined depth and stencil buffer
955         ImageDesc desc;
956         glBindRenderbuffer(GL_RENDERBUFFER, depthRb);
957         getBoundRenderbufferDesc(context, desc);
958
959         glGenRenderbuffers(1, &rbs[*numRbs]);
960         glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]);
961         glRenderbufferStorage(GL_RENDERBUFFER, desc.internalFormat, desc.width, desc.height);
962         glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT,
963                                   GL_RENDERBUFFER, rbs[*numRbs]);
964         glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo);
965         glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
966         glBlitFramebuffer(0, 0, desc.width, desc.height, 0, 0, desc.width, desc.height,
967                           GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT, GL_NEAREST);
968         glBindFramebuffer(GL_FRAMEBUFFER, fbo);
969         ++*numRbs;
970     } else {
971         if (depthRb) {
972             ImageDesc desc;
973             glBindRenderbuffer(GL_RENDERBUFFER, depthRb);
974             getBoundRenderbufferDesc(context, desc);
975
976             glGenRenderbuffers(1, &rbs[*numRbs]);
977             glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]);
978             glRenderbufferStorage(GL_RENDERBUFFER, desc.internalFormat, desc.width, desc.height);
979             glFramebufferRenderbuffer(GL_FRAMEBUFFER,
980                                       GL_DEPTH_ATTACHMENT,
981                                       GL_RENDERBUFFER, rbs[*numRbs]);
982             glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo);
983             glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
984             glDrawBuffer(GL_DEPTH_ATTACHMENT);
985             glReadBuffer(GL_DEPTH_ATTACHMENT);
986             glBlitFramebuffer(0, 0, desc.width, desc.height, 0, 0, desc.width, desc.height,
987                               GL_DEPTH_BUFFER_BIT, GL_NEAREST);
988             ++*numRbs;
989         }
990         if (stencilRb) {
991             ImageDesc desc;
992             glBindRenderbuffer(GL_RENDERBUFFER, stencilRb);
993             getBoundRenderbufferDesc(context, desc);
994
995             glGenRenderbuffers(1, &rbs[*numRbs]);
996             glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]);
997             glRenderbufferStorage(GL_RENDERBUFFER, desc.internalFormat, desc.width, desc.height);
998             glFramebufferRenderbuffer(GL_FRAMEBUFFER,
999                                       GL_STENCIL_ATTACHMENT,
1000                                       GL_RENDERBUFFER, rbs[*numRbs]);
1001             glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo);
1002             glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
1003             glDrawBuffer(GL_STENCIL_ATTACHMENT);
1004             glReadBuffer(GL_STENCIL_ATTACHMENT);
1005             glBlitFramebuffer(0, 0, desc.width, desc.height, 0, 0, desc.width, desc.height,
1006                               GL_STENCIL_BUFFER_BIT, GL_NEAREST);
1007             ++*numRbs;
1008         }
1009     }
1010
1011     return fbo;
1012 }
1013
1014
1015 /**
1016  * Dump images of current draw drawable/window.
1017  */
1018 static void
1019 dumpDrawableImages(JSONWriter &json, Context &context)
1020 {
1021     GLint width, height;
1022
1023     if (!getDrawableBounds(&width, &height)) {
1024         return;
1025     }
1026
1027     GLint draw_buffer = GL_NONE;
1028     if (context.ES) {
1029         // XXX: Draw buffer is always FRONT for single buffer context, BACK for
1030         // double buffered contexts. There is no way to know which (as
1031         // GL_DOUBLEBUFFER state is also unavailable), so always assume
1032         // double-buffering.
1033         draw_buffer = GL_BACK;
1034     } else {
1035         glGetIntegerv(GL_DRAW_BUFFER, &draw_buffer);
1036     }
1037
1038     if (draw_buffer != GL_NONE) {
1039         // Read from current draw buffer
1040         GLint read_buffer = GL_NONE;
1041         if (!context.ES) {
1042             glGetIntegerv(GL_READ_BUFFER, &read_buffer);
1043             glReadBuffer(draw_buffer);
1044         }
1045
1046         GLint alpha_bits = 0;
1047 #if 0
1048         // XXX: Ignore alpha until we are able to match the traced visual
1049         glGetIntegerv(GL_ALPHA_BITS, &alpha_bits);
1050 #endif
1051         GLenum format = alpha_bits ? GL_RGBA : GL_RGB;
1052         json.beginMember(enumToString(draw_buffer));
1053         dumpReadBufferImage(json, width, height, format);
1054         json.endMember();
1055
1056         // Restore original read buffer
1057         if (!context.ES) {
1058             glReadBuffer(read_buffer);
1059         }
1060     }
1061
1062     if (!context.ES) {
1063         GLint depth_bits = 0;
1064         glGetIntegerv(GL_DEPTH_BITS, &depth_bits);
1065         if (depth_bits) {
1066             json.beginMember("GL_DEPTH_COMPONENT");
1067             dumpReadBufferImage(json, width, height, GL_DEPTH_COMPONENT);
1068             json.endMember();
1069         }
1070
1071         GLint stencil_bits = 0;
1072         glGetIntegerv(GL_STENCIL_BITS, &stencil_bits);
1073         if (stencil_bits) {
1074             json.beginMember("GL_STENCIL_INDEX");
1075             dumpReadBufferImage(json, width, height, GL_STENCIL_INDEX);
1076             json.endMember();
1077         }
1078     }
1079 }
1080
1081
1082 /**
1083  * Dump the specified framebuffer attachment.
1084  *
1085  * In the case of a color attachment, it assumes it is already bound for read.
1086  */
1087 static void
1088 dumpFramebufferAttachment(JSONWriter &json, Context &context, GLenum target, GLenum attachment, GLenum format)
1089 {
1090     ImageDesc desc;
1091     if (!getFramebufferAttachmentDesc(context, target, attachment, desc)) {
1092         return;
1093     }
1094
1095     json.beginMember(enumToString(attachment));
1096     dumpReadBufferImage(json, desc.width, desc.height, format, desc.internalFormat);
1097     json.endMember();
1098 }
1099
1100
1101 static void
1102 dumpFramebufferAttachments(JSONWriter &json, Context &context, GLenum target)
1103 {
1104     GLint read_framebuffer = 0;
1105     glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &read_framebuffer);
1106
1107     GLint read_buffer = GL_NONE;
1108     glGetIntegerv(GL_READ_BUFFER, &read_buffer);
1109
1110     GLint max_draw_buffers = 1;
1111     glGetIntegerv(GL_MAX_DRAW_BUFFERS, &max_draw_buffers);
1112     GLint max_color_attachments = 0;
1113     glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS, &max_color_attachments);
1114
1115     for (GLint i = 0; i < max_draw_buffers; ++i) {
1116         GLint draw_buffer = GL_NONE;
1117         glGetIntegerv(GL_DRAW_BUFFER0 + i, &draw_buffer);
1118         if (draw_buffer != GL_NONE) {
1119             glReadBuffer(draw_buffer);
1120             GLint attachment;
1121             if (draw_buffer >= GL_COLOR_ATTACHMENT0 && draw_buffer < GL_COLOR_ATTACHMENT0 + max_color_attachments) {
1122                 attachment = draw_buffer;
1123             } else {
1124                 std::cerr << "warning: unexpected GL_DRAW_BUFFER" << i << " = " << draw_buffer << "\n";
1125                 attachment = GL_COLOR_ATTACHMENT0;
1126             }
1127             GLint alpha_size = 0;
1128             glGetFramebufferAttachmentParameteriv(target, attachment,
1129                                                   GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE,
1130                                                   &alpha_size);
1131             GLenum format = alpha_size ? GL_RGBA : GL_RGB;
1132             dumpFramebufferAttachment(json, context, target, attachment, format);
1133         }
1134     }
1135
1136     glReadBuffer(read_buffer);
1137
1138     if (!context.ES) {
1139         dumpFramebufferAttachment(json, context, target, GL_DEPTH_ATTACHMENT, GL_DEPTH_COMPONENT);
1140         dumpFramebufferAttachment(json, context, target, GL_STENCIL_ATTACHMENT, GL_STENCIL_INDEX);
1141     }
1142
1143     glBindFramebuffer(GL_READ_FRAMEBUFFER, read_framebuffer);
1144 }
1145
1146
1147 void
1148 dumpFramebuffer(JSONWriter &json, Context &context)
1149 {
1150     json.beginMember("framebuffer");
1151     json.beginObject();
1152
1153     GLint boundDrawFbo = 0, boundReadFbo = 0;
1154     glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &boundDrawFbo);
1155     glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &boundReadFbo);
1156     if (!boundDrawFbo) {
1157         dumpDrawableImages(json, context);
1158     } else if (context.ES) {
1159         dumpFramebufferAttachments(json, context, GL_FRAMEBUFFER);
1160     } else {
1161         GLint colorRb = 0, stencilRb = 0, depthRb = 0;
1162         GLint draw_buffer0 = GL_NONE;
1163         glGetIntegerv(GL_DRAW_BUFFER0, &draw_buffer0);
1164         bool multisample = false;
1165
1166         GLint boundRb = 0;
1167         glGetIntegerv(GL_RENDERBUFFER_BINDING, &boundRb);
1168
1169         GLint object_type;
1170         glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, draw_buffer0, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, &object_type);
1171         if (object_type == GL_RENDERBUFFER) {
1172             glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, draw_buffer0, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, &colorRb);
1173             glBindRenderbuffer(GL_RENDERBUFFER, colorRb);
1174             GLint samples = 0;
1175             glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_SAMPLES, &samples);
1176             if (samples) {
1177                 multisample = true;
1178             }
1179         }
1180
1181         glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, &object_type);
1182         if (object_type == GL_RENDERBUFFER) {
1183             glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, &depthRb);
1184             glBindRenderbuffer(GL_RENDERBUFFER, depthRb);
1185             GLint samples = 0;
1186             glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_SAMPLES, &samples);
1187             if (samples) {
1188                 multisample = true;
1189             }
1190         }
1191
1192         glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, &object_type);
1193         if (object_type == GL_RENDERBUFFER) {
1194             glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, &stencilRb);
1195             glBindRenderbuffer(GL_RENDERBUFFER, stencilRb);
1196             GLint samples = 0;
1197             glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_SAMPLES, &samples);
1198             if (samples) {
1199                 multisample = true;
1200             }
1201         }
1202
1203         glBindRenderbuffer(GL_RENDERBUFFER, boundRb);
1204
1205         GLuint rbs[3];
1206         GLint numRbs = 0;
1207         GLuint fboCopy = 0;
1208
1209         if (multisample) {
1210             // glReadPixels doesnt support multisampled buffers so we need
1211             // to blit the fbo to a temporary one
1212             fboCopy = downsampledFramebuffer(context,
1213                                              boundDrawFbo, draw_buffer0,
1214                                              colorRb, depthRb, stencilRb,
1215                                              rbs, &numRbs);
1216         }
1217
1218         dumpFramebufferAttachments(json, context, GL_DRAW_FRAMEBUFFER);
1219
1220         if (multisample) {
1221             glBindRenderbuffer(GL_RENDERBUFFER, boundRb);
1222             glDeleteRenderbuffers(numRbs, rbs);
1223             glDeleteFramebuffers(1, &fboCopy);
1224         }
1225
1226         glBindFramebuffer(GL_READ_FRAMEBUFFER, boundReadFbo);
1227         glBindFramebuffer(GL_DRAW_FRAMEBUFFER, boundDrawFbo);
1228     }
1229
1230     json.endObject();
1231     json.endMember(); // framebuffer
1232 }
1233
1234
1235 } /* namespace glstate */