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