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