]> git.cworth.org Git - apitrace/blob - glstate_images.cpp
More code simplification.
[apitrace] / 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 __APPLE__
41
42 #include <Carbon/Carbon.h>
43
44 #ifdef __cplusplus
45 extern "C" {
46 #endif
47
48 OSStatus CGSGetSurfaceBounds(CGSConnectionID, CGWindowID, CGSSurfaceID, CGRect *);
49
50 #ifdef __cplusplus
51 }
52 #endif
53
54 #endif /* __APPLE__ */
55
56
57 /* Change thi to one to force interpreting depth buffers as RGBA, which enables
58  * visualizing full dynamic range, until we can transmit HDR images to the GUI */
59 #define DEPTH_AS_RGBA 0
60
61
62 namespace glstate {
63
64
65 struct ImageDesc
66 {
67     GLint width;
68     GLint height;
69     GLint depth;
70     GLint internalFormat;
71
72     inline
73     ImageDesc() :
74         width(0),
75         height(0),
76         depth(0),
77         internalFormat(GL_NONE)
78     {}
79
80     inline bool
81     valid(void) const {
82         return width > 0 && height > 0 && depth > 0;
83     }
84 };
85
86
87 static inline bool
88 getActiveTextureLevelDesc(Context &context, GLenum target, GLint level, ImageDesc &desc)
89 {
90     if (context.ES) {
91         // XXX: OpenGL ES does not support glGetTexLevelParameteriv
92         return false;
93     }
94
95     glGetTexLevelParameteriv(target, level, GL_TEXTURE_INTERNAL_FORMAT, &desc.internalFormat);
96
97     desc.width = 0;
98     glGetTexLevelParameteriv(target, level, GL_TEXTURE_WIDTH, &desc.width);
99
100     if (target == GL_TEXTURE_1D) {
101         desc.height = 1;
102         desc.depth = 1;
103     } else {
104         desc.height = 0;
105         glGetTexLevelParameteriv(target, level, GL_TEXTURE_HEIGHT, &desc.height);
106         if (target != GL_TEXTURE_3D) {
107             desc.depth = 1;
108         } else {
109             desc.depth = 0;
110             glGetTexLevelParameteriv(target, level, GL_TEXTURE_DEPTH, &desc.depth);
111         }
112     }
113
114     return desc.valid();
115 }
116
117
118 static inline void
119 dumpActiveTextureLevel(JSONWriter &json, Context &context, GLenum target, GLint level)
120 {
121     ImageDesc desc;
122     if (!getActiveTextureLevelDesc(context, target, level, desc)) {
123         return;
124     }
125
126     char label[512];
127
128     GLint active_texture = GL_TEXTURE0;
129     glGetIntegerv(GL_ACTIVE_TEXTURE, &active_texture);
130     snprintf(label, sizeof label, "%s, %s, level = %d",
131              enumToString(active_texture), enumToString(target), level);
132
133     json.beginMember(label);
134
135     json.beginObject();
136
137     // Tell the GUI this is no ordinary object, but an image
138     json.writeStringMember("__class__", "image");
139
140     json.writeNumberMember("__width__", desc.width);
141     json.writeNumberMember("__height__", desc.height);
142     json.writeNumberMember("__depth__", desc.depth);
143
144     json.writeStringMember("__format__", enumToString(desc.internalFormat));
145
146     // Hardcoded for now, but we could chose types more adequate to the
147     // texture internal format
148     json.writeStringMember("__type__", "uint8");
149     json.writeBoolMember("__normalized__", true);
150     json.writeNumberMember("__channels__", 4);
151
152     GLubyte *pixels = new GLubyte[desc.depth*desc.width*desc.height*4];
153
154     context.resetPixelPackState();
155
156     glGetTexImage(target, level, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
157
158     context.restorePixelPackState();
159
160     json.beginMember("__data__");
161     char *pngBuffer;
162     int pngBufferSize;
163     image::writePixelsToBuffer(pixels, desc.width, desc.height, 4, true, &pngBuffer, &pngBufferSize);
164     json.writeBase64(pngBuffer, pngBufferSize);
165     free(pngBuffer);
166     json.endMember(); // __data__
167
168     delete [] pixels;
169     json.endObject();
170 }
171
172
173 static inline void
174 dumpTexture(JSONWriter &json, Context &context, GLenum target, GLenum binding)
175 {
176     GLint texture_binding = 0;
177     glGetIntegerv(binding, &texture_binding);
178     if (!glIsEnabled(target) && !texture_binding) {
179         return;
180     }
181
182     GLint level = 0;
183     do {
184         ImageDesc desc;
185         if (!getActiveTextureLevelDesc(context, target, level, desc)) {
186             break;
187         }
188
189         if (target == GL_TEXTURE_CUBE_MAP) {
190             for (int face = 0; face < 6; ++face) {
191                 dumpActiveTextureLevel(json, context, GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, level);
192             }
193         } else {
194             dumpActiveTextureLevel(json, context, target, level);
195         }
196
197         ++level;
198     } while(true);
199 }
200
201
202 void
203 dumpTextures(JSONWriter &json, Context &context)
204 {
205     json.beginMember("textures");
206     json.beginObject();
207     GLint active_texture = GL_TEXTURE0;
208     glGetIntegerv(GL_ACTIVE_TEXTURE, &active_texture);
209     GLint max_texture_coords = 0;
210     glGetIntegerv(GL_MAX_TEXTURE_COORDS, &max_texture_coords);
211     GLint max_combined_texture_image_units = 0;
212     glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &max_combined_texture_image_units);
213     GLint max_units = std::max(max_combined_texture_image_units, max_texture_coords);
214     for (GLint unit = 0; unit < max_units; ++unit) {
215         GLenum texture = GL_TEXTURE0 + unit;
216         glActiveTexture(texture);
217         dumpTexture(json, context, GL_TEXTURE_1D, GL_TEXTURE_BINDING_1D);
218         dumpTexture(json, context, GL_TEXTURE_2D, GL_TEXTURE_BINDING_2D);
219         dumpTexture(json, context, GL_TEXTURE_3D, GL_TEXTURE_BINDING_3D);
220         dumpTexture(json, context, GL_TEXTURE_RECTANGLE, GL_TEXTURE_BINDING_RECTANGLE);
221         dumpTexture(json, context, GL_TEXTURE_CUBE_MAP, GL_TEXTURE_BINDING_CUBE_MAP);
222     }
223     glActiveTexture(active_texture);
224     json.endObject();
225     json.endMember(); // textures
226 }
227
228
229 static bool
230 getDrawableBounds(GLint *width, GLint *height) {
231 #if defined(TRACE_EGL)
232
233     EGLContext currentContext = eglGetCurrentContext();
234     if (currentContext == EGL_NO_CONTEXT) {
235         return false;
236     }
237
238     EGLSurface currentSurface = eglGetCurrentSurface(EGL_DRAW);
239     if (currentSurface == EGL_NO_SURFACE) {
240         return false;
241     }
242
243     EGLDisplay currentDisplay = eglGetCurrentDisplay();
244     if (currentDisplay == EGL_NO_DISPLAY) {
245         return false;
246     }
247
248     if (!eglQuerySurface(currentDisplay, currentSurface, EGL_WIDTH, width) ||
249         !eglQuerySurface(currentDisplay, currentSurface, EGL_HEIGHT, height)) {
250         return false;
251     }
252
253     return true;
254
255 #elif defined(_WIN32)
256
257     HDC hDC = wglGetCurrentDC();
258     if (!hDC) {
259         return false;
260     }
261
262     HWND hWnd = WindowFromDC(hDC);
263     RECT rect;
264
265     if (!GetClientRect(hWnd, &rect)) {
266        return false;
267     }
268
269     *width  = rect.right  - rect.left;
270     *height = rect.bottom - rect.top;
271     return true;
272
273 #elif defined(__APPLE__)
274
275     CGLContextObj ctx = CGLGetCurrentContext();
276     if (ctx == NULL) {
277         return false;
278     }
279
280     CGSConnectionID cid;
281     CGSWindowID wid;
282     CGSSurfaceID sid;
283
284     if (CGLGetSurface(ctx, &cid, &wid, &sid) != kCGLNoError) {
285         return false;
286     }
287
288     CGRect rect;
289
290     if (CGSGetSurfaceBounds(cid, wid, sid, &rect) != 0) {
291         return false;
292     }
293
294     *width = rect.size.width;
295     *height = rect.size.height;
296     return true;
297
298 #elif defined(HAVE_X11)
299
300     Display *display;
301     Drawable drawable;
302     Window root;
303     int x, y;
304     unsigned int w, h, bw, depth;
305
306     display = glXGetCurrentDisplay();
307     if (!display) {
308         return false;
309     }
310
311     drawable = glXGetCurrentDrawable();
312     if (drawable == None) {
313         return false;
314     }
315
316     if (!XGetGeometry(display, drawable, &root, &x, &y, &w, &h, &bw, &depth)) {
317         return false;
318     }
319
320     *width = w;
321     *height = h;
322     return true;
323
324 #else
325
326     return false;
327
328 #endif
329 }
330
331
332 static const GLenum texture_bindings[][2] = {
333     {GL_TEXTURE_1D, GL_TEXTURE_BINDING_1D},
334     {GL_TEXTURE_2D, GL_TEXTURE_BINDING_2D},
335     {GL_TEXTURE_3D, GL_TEXTURE_BINDING_3D},
336     {GL_TEXTURE_RECTANGLE, GL_TEXTURE_BINDING_RECTANGLE},
337     {GL_TEXTURE_CUBE_MAP, GL_TEXTURE_BINDING_CUBE_MAP}
338 };
339
340
341 static bool
342 bindTexture(GLint texture, GLenum &target, GLint &bound_texture)
343 {
344
345     for (unsigned i = 0; i < sizeof(texture_bindings)/sizeof(texture_bindings[0]); ++i) {
346         target  = texture_bindings[i][0];
347
348         GLenum binding = texture_bindings[i][1];
349
350         while (glGetError() != GL_NO_ERROR)
351             ;
352
353         glGetIntegerv(binding, &bound_texture);
354         glBindTexture(target, texture);
355
356         if (glGetError() == GL_NO_ERROR) {
357             return true;
358         }
359
360         glBindTexture(target, bound_texture);
361     }
362
363     target = GL_NONE;
364
365     return false;
366 }
367
368
369 static bool
370 getTextureLevelDesc(Context &context, GLint texture, GLint level, ImageDesc &desc)
371 {
372     GLenum target;
373     GLint bound_texture = 0;
374     if (!bindTexture(texture, target, bound_texture)) {
375         return false;
376     }
377
378     getActiveTextureLevelDesc(context, target, level, desc);
379
380     glBindTexture(target, bound_texture);
381
382     return desc.valid();
383 }
384
385
386 static bool
387 getBoundRenderbufferDesc(Context &context, ImageDesc &desc)
388 {
389     glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &desc.width);
390     glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &desc.height);
391     desc.depth = 1;
392     
393     glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_INTERNAL_FORMAT, &desc.internalFormat);
394     
395     return desc.valid();
396 }
397
398
399 static bool
400 getRenderbufferDesc(Context &context, GLint renderbuffer, ImageDesc &desc)
401 {
402     GLint bound_renderbuffer = 0;
403     glGetIntegerv(GL_RENDERBUFFER_BINDING, &bound_renderbuffer);
404     glBindRenderbuffer(GL_RENDERBUFFER, renderbuffer);
405
406     getBoundRenderbufferDesc(context, desc);
407
408     glBindRenderbuffer(GL_RENDERBUFFER, bound_renderbuffer);
409     
410     return desc.valid();
411 }
412
413
414 static bool
415 getFramebufferAttachmentDesc(Context &context, GLenum target, GLenum attachment, ImageDesc &desc)
416 {
417     GLint object_type = GL_NONE;
418     glGetFramebufferAttachmentParameteriv(target, attachment,
419                                           GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE,
420                                           &object_type);
421     if (object_type == GL_NONE) {
422         return false;
423     }
424
425     GLint object_name = 0;
426     glGetFramebufferAttachmentParameteriv(target, attachment,
427                                           GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME,
428                                           &object_name);
429     if (object_name == 0) {
430         return false;
431     }
432
433     if (object_type == GL_RENDERBUFFER) {
434         return getRenderbufferDesc(context, object_name, desc);
435     } else if (object_type == GL_TEXTURE) {
436         GLint texture_level = 0;
437         glGetFramebufferAttachmentParameteriv(target, attachment,
438                                               GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL,
439                                               &texture_level);
440         return getTextureLevelDesc(context, object_name, texture_level, desc);
441     } else {
442         std::cerr << "warning: unexpected GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE = " << object_type << "\n";
443         return false;
444     }
445 }
446
447
448
449 image::Image *
450 getDrawBufferImage() {
451     GLenum format = GL_RGB;
452     GLint channels = __gl_format_channels(format);
453     if (channels > 4) {
454         return NULL;
455     }
456
457     Context context;
458
459     GLenum framebuffer_binding;
460     GLenum framebuffer_target;
461     if (context.ES) {
462         framebuffer_binding = GL_FRAMEBUFFER_BINDING;
463         framebuffer_target = GL_FRAMEBUFFER;
464     } else {
465         framebuffer_binding = GL_DRAW_FRAMEBUFFER_BINDING;
466         framebuffer_target = GL_DRAW_FRAMEBUFFER;
467     }
468
469     GLint draw_framebuffer = 0;
470     glGetIntegerv(framebuffer_binding, &draw_framebuffer);
471
472     GLint draw_buffer = GL_NONE;
473     ImageDesc desc;
474     if (draw_framebuffer) {
475         if (context.ARB_draw_buffers) {
476             glGetIntegerv(GL_DRAW_BUFFER0, &draw_buffer);
477             if (draw_buffer == GL_NONE) {
478                 return NULL;
479             }
480         }
481
482         if (!getFramebufferAttachmentDesc(context, framebuffer_target, draw_buffer, desc)) {
483             return NULL;
484         }
485     } else {
486         if (!context.ES) {
487             glGetIntegerv(GL_DRAW_BUFFER, &draw_buffer);
488             if (draw_buffer == GL_NONE) {
489                 return NULL;
490             }
491         }
492
493         if (!getDrawableBounds(&desc.width, &desc.height)) {
494             return NULL;
495         }
496
497         desc.depth = 1;
498     }
499
500     GLenum type = GL_UNSIGNED_BYTE;
501
502 #if DEPTH_AS_RGBA
503     if (format == GL_DEPTH_COMPONENT) {
504         type = GL_UNSIGNED_INT;
505         channels = 4;
506     }
507 #endif
508
509     image::Image *image = new image::Image(desc.width, desc.height, channels, true);
510     if (!image) {
511         return NULL;
512     }
513
514     while (glGetError() != GL_NO_ERROR) {}
515
516     GLint read_framebuffer = 0;
517     GLint read_buffer = GL_NONE;
518     if (!context.ES) {
519         glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &read_framebuffer);
520         glBindFramebuffer(GL_READ_FRAMEBUFFER, draw_framebuffer);
521
522         glGetIntegerv(GL_READ_BUFFER, &read_buffer);
523         glReadBuffer(draw_buffer);
524     }
525
526     // TODO: reset imaging state too
527     context.resetPixelPackState();
528
529     glReadPixels(0, 0, desc.width, desc.height, format, type, image->pixels);
530
531     context.restorePixelPackState();
532
533     if (!context.ES) {
534         glReadBuffer(read_buffer);
535         glBindFramebuffer(GL_READ_FRAMEBUFFER, read_framebuffer);
536     }
537
538     GLenum error = glGetError();
539     if (error != GL_NO_ERROR) {
540         do {
541             std::cerr << "warning: " << enumToString(error) << " while getting snapshot\n";
542             error = glGetError();
543         } while(error != GL_NO_ERROR);
544         delete image;
545         return NULL;
546     }
547      
548     return image;
549 }
550
551
552 /**
553  * Dump the image of the currently bound read buffer.
554  */
555 static inline void
556 dumpReadBufferImage(JSONWriter &json, GLint width, GLint height, GLenum format,
557                     GLint internalFormat = GL_NONE)
558 {
559     GLint channels = __gl_format_channels(format);
560
561     Context context;
562
563     json.beginObject();
564
565     // Tell the GUI this is no ordinary object, but an image
566     json.writeStringMember("__class__", "image");
567
568     json.writeNumberMember("__width__", width);
569     json.writeNumberMember("__height__", height);
570     json.writeNumberMember("__depth__", 1);
571
572     json.writeStringMember("__format__", enumToString(internalFormat));
573
574     // Hardcoded for now, but we could chose types more adequate to the
575     // texture internal format
576     json.writeStringMember("__type__", "uint8");
577     json.writeBoolMember("__normalized__", true);
578     json.writeNumberMember("__channels__", channels);
579
580     GLenum type = GL_UNSIGNED_BYTE;
581
582 #if DEPTH_AS_RGBA
583     if (format == GL_DEPTH_COMPONENT) {
584         type = GL_UNSIGNED_INT;
585         channels = 4;
586     }
587 #endif
588
589     GLubyte *pixels = new GLubyte[width*height*channels];
590
591     // TODO: reset imaging state too
592     context.resetPixelPackState();
593
594     glReadPixels(0, 0, width, height, format, type, pixels);
595
596     context.restorePixelPackState();
597
598     json.beginMember("__data__");
599     char *pngBuffer;
600     int pngBufferSize;
601     image::writePixelsToBuffer(pixels, width, height, channels, true, &pngBuffer, &pngBufferSize);
602     //std::cerr <<" Before = "<<(width * height * channels * sizeof *pixels)
603     //          <<", after = "<<pngBufferSize << ", ratio = " << double(width * height * channels * sizeof *pixels)/pngBufferSize;
604     json.writeBase64(pngBuffer, pngBufferSize);
605     free(pngBuffer);
606     json.endMember(); // __data__
607
608     delete [] pixels;
609     json.endObject();
610 }
611
612
613 static inline GLuint
614 downsampledFramebuffer(Context &context,
615                        GLuint oldFbo, GLint drawbuffer,
616                        GLint colorRb, GLint depthRb, GLint stencilRb,
617                        GLuint *rbs, GLint *numRbs)
618 {
619     GLuint fbo;
620
621
622     *numRbs = 0;
623
624     glGenFramebuffers(1, &fbo);
625     glBindFramebuffer(GL_FRAMEBUFFER, fbo);
626
627     {
628         // color buffer
629         ImageDesc desc;
630         glBindRenderbuffer(GL_RENDERBUFFER, colorRb);
631         getBoundRenderbufferDesc(context, desc);
632
633         glGenRenderbuffers(1, &rbs[*numRbs]);
634         glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]);
635         glRenderbufferStorage(GL_RENDERBUFFER, desc.internalFormat, desc.width, desc.height);
636         glFramebufferRenderbuffer(GL_FRAMEBUFFER, drawbuffer,
637                                   GL_RENDERBUFFER, rbs[*numRbs]);
638
639         glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo);
640         glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
641         glDrawBuffer(drawbuffer);
642         glReadBuffer(drawbuffer);
643         glBlitFramebuffer(0, 0, desc.width, desc.height, 0, 0, desc.width, desc.height,
644                           GL_COLOR_BUFFER_BIT, GL_NEAREST);
645         glBindFramebuffer(GL_FRAMEBUFFER, fbo);
646         ++*numRbs;
647     }
648
649     if (stencilRb == depthRb && stencilRb) {
650         //combined depth and stencil buffer
651         ImageDesc desc;
652         glBindRenderbuffer(GL_RENDERBUFFER, depthRb);
653         getBoundRenderbufferDesc(context, desc);
654
655         glGenRenderbuffers(1, &rbs[*numRbs]);
656         glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]);
657         glRenderbufferStorage(GL_RENDERBUFFER, desc.internalFormat, desc.width, desc.height);
658         glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT,
659                                   GL_RENDERBUFFER, rbs[*numRbs]);
660         glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo);
661         glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
662         glBlitFramebuffer(0, 0, desc.width, desc.height, 0, 0, desc.width, desc.height,
663                           GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT, GL_NEAREST);
664         glBindFramebuffer(GL_FRAMEBUFFER, fbo);
665         ++*numRbs;
666     } else {
667         if (depthRb) {
668             ImageDesc desc;
669             glBindRenderbuffer(GL_RENDERBUFFER, depthRb);
670             getBoundRenderbufferDesc(context, desc);
671
672             glGenRenderbuffers(1, &rbs[*numRbs]);
673             glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]);
674             glRenderbufferStorage(GL_RENDERBUFFER, desc.internalFormat, desc.width, desc.height);
675             glFramebufferRenderbuffer(GL_FRAMEBUFFER,
676                                       GL_DEPTH_ATTACHMENT,
677                                       GL_RENDERBUFFER, rbs[*numRbs]);
678             glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo);
679             glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
680             glDrawBuffer(GL_DEPTH_ATTACHMENT);
681             glReadBuffer(GL_DEPTH_ATTACHMENT);
682             glBlitFramebuffer(0, 0, desc.width, desc.height, 0, 0, desc.width, desc.height,
683                               GL_DEPTH_BUFFER_BIT, GL_NEAREST);
684             ++*numRbs;
685         }
686         if (stencilRb) {
687             ImageDesc desc;
688             glBindRenderbuffer(GL_RENDERBUFFER, stencilRb);
689             getBoundRenderbufferDesc(context, desc);
690
691             glGenRenderbuffers(1, &rbs[*numRbs]);
692             glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]);
693             glRenderbufferStorage(GL_RENDERBUFFER, desc.internalFormat, desc.width, desc.height);
694             glFramebufferRenderbuffer(GL_FRAMEBUFFER,
695                                       GL_STENCIL_ATTACHMENT,
696                                       GL_RENDERBUFFER, rbs[*numRbs]);
697             glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo);
698             glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
699             glDrawBuffer(GL_STENCIL_ATTACHMENT);
700             glReadBuffer(GL_STENCIL_ATTACHMENT);
701             glBlitFramebuffer(0, 0, desc.width, desc.height, 0, 0, desc.width, desc.height,
702                               GL_STENCIL_BUFFER_BIT, GL_NEAREST);
703             ++*numRbs;
704         }
705     }
706
707     return fbo;
708 }
709
710
711 /**
712  * Dump images of current draw drawable/window.
713  */
714 static void
715 dumpDrawableImages(JSONWriter &json, Context &context)
716 {
717     GLint width, height;
718
719     if (!getDrawableBounds(&width, &height)) {
720         return;
721     }
722
723     GLint draw_buffer = GL_NONE;
724     if (context.ES) {
725         draw_buffer = GL_BACK;
726     } else {
727         glGetIntegerv(GL_DRAW_BUFFER, &draw_buffer);
728         glReadBuffer(draw_buffer);
729     }
730
731     if (draw_buffer != GL_NONE) {
732         GLint read_buffer = GL_NONE;
733         if (!context.ES) {
734             glGetIntegerv(GL_READ_BUFFER, &read_buffer);
735         }
736
737         GLint alpha_bits = 0;
738 #if 0
739         // XXX: Ignore alpha until we are able to match the traced visual
740         glGetIntegerv(GL_ALPHA_BITS, &alpha_bits);
741 #endif
742         GLenum format = alpha_bits ? GL_RGBA : GL_RGB;
743         json.beginMember(enumToString(draw_buffer));
744         dumpReadBufferImage(json, width, height, format);
745         json.endMember();
746
747         if (!context.ES) {
748             glReadBuffer(read_buffer);
749         }
750     }
751
752     if (!context.ES) {
753         GLint depth_bits = 0;
754         glGetIntegerv(GL_DEPTH_BITS, &depth_bits);
755         if (depth_bits) {
756             json.beginMember("GL_DEPTH_COMPONENT");
757             dumpReadBufferImage(json, width, height, GL_DEPTH_COMPONENT);
758             json.endMember();
759         }
760
761         GLint stencil_bits = 0;
762         glGetIntegerv(GL_STENCIL_BITS, &stencil_bits);
763         if (stencil_bits) {
764             json.beginMember("GL_STENCIL_INDEX");
765             dumpReadBufferImage(json, width, height, GL_STENCIL_INDEX);
766             json.endMember();
767         }
768     }
769 }
770
771
772 /**
773  * Dump the specified framebuffer attachment.
774  *
775  * In the case of a color attachment, it assumes it is already bound for read.
776  */
777 static void
778 dumpFramebufferAttachment(JSONWriter &json, Context &context, GLenum target, GLenum attachment, GLenum format)
779 {
780     ImageDesc desc;
781     if (!getFramebufferAttachmentDesc(context, target, attachment, desc)) {
782         return;
783     }
784
785     json.beginMember(enumToString(attachment));
786     dumpReadBufferImage(json, desc.width, desc.height, format, desc.internalFormat);
787     json.endMember();
788 }
789
790
791 static void
792 dumpFramebufferAttachments(JSONWriter &json, Context &context, GLenum target)
793 {
794     GLint read_framebuffer = 0;
795     glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &read_framebuffer);
796
797     GLint read_buffer = GL_NONE;
798     glGetIntegerv(GL_READ_BUFFER, &read_buffer);
799
800     GLint max_draw_buffers = 1;
801     glGetIntegerv(GL_MAX_DRAW_BUFFERS, &max_draw_buffers);
802     GLint max_color_attachments = 0;
803     glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS, &max_color_attachments);
804
805     for (GLint i = 0; i < max_draw_buffers; ++i) {
806         GLint draw_buffer = GL_NONE;
807         glGetIntegerv(GL_DRAW_BUFFER0 + i, &draw_buffer);
808         if (draw_buffer != GL_NONE) {
809             glReadBuffer(draw_buffer);
810             GLint attachment;
811             if (draw_buffer >= GL_COLOR_ATTACHMENT0 && draw_buffer < GL_COLOR_ATTACHMENT0 + max_color_attachments) {
812                 attachment = draw_buffer;
813             } else {
814                 std::cerr << "warning: unexpected GL_DRAW_BUFFER" << i << " = " << draw_buffer << "\n";
815                 attachment = GL_COLOR_ATTACHMENT0;
816             }
817             GLint alpha_size = 0;
818             glGetFramebufferAttachmentParameteriv(target, attachment,
819                                                   GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE,
820                                                   &alpha_size);
821             GLenum format = alpha_size ? GL_RGBA : GL_RGB;
822             dumpFramebufferAttachment(json, context, target, attachment, format);
823         }
824     }
825
826     glReadBuffer(read_buffer);
827
828     if (!context.ES) {
829         dumpFramebufferAttachment(json, context, target, GL_DEPTH_ATTACHMENT, GL_DEPTH_COMPONENT);
830         dumpFramebufferAttachment(json, context, target, GL_STENCIL_ATTACHMENT, GL_STENCIL_INDEX);
831     }
832
833     glBindFramebuffer(GL_READ_FRAMEBUFFER, read_framebuffer);
834 }
835
836
837 void
838 dumpFramebuffer(JSONWriter &json, Context &context)
839 {
840     json.beginMember("framebuffer");
841     json.beginObject();
842
843     GLint boundDrawFbo = 0, boundReadFbo = 0;
844     glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &boundDrawFbo);
845     glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &boundReadFbo);
846     if (!boundDrawFbo) {
847         dumpDrawableImages(json, context);
848     } else if (context.ES) {
849         dumpFramebufferAttachments(json, context, GL_FRAMEBUFFER);
850     } else {
851         GLint colorRb = 0, stencilRb = 0, depthRb = 0;
852         GLint draw_buffer0 = GL_NONE;
853         glGetIntegerv(GL_DRAW_BUFFER0, &draw_buffer0);
854         bool multisample = false;
855
856         GLint boundRb = 0;
857         glGetIntegerv(GL_RENDERBUFFER_BINDING, &boundRb);
858
859         GLint object_type;
860         glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, draw_buffer0, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, &object_type);
861         if (object_type == GL_RENDERBUFFER) {
862             glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, draw_buffer0, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, &colorRb);
863             glBindRenderbuffer(GL_RENDERBUFFER, colorRb);
864             GLint samples = 0;
865             glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_SAMPLES, &samples);
866             if (samples) {
867                 multisample = true;
868             }
869         }
870
871         glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, &object_type);
872         if (object_type == GL_RENDERBUFFER) {
873             glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, &depthRb);
874             glBindRenderbuffer(GL_RENDERBUFFER, depthRb);
875             GLint samples = 0;
876             glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_SAMPLES, &samples);
877             if (samples) {
878                 multisample = true;
879             }
880         }
881
882         glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, &object_type);
883         if (object_type == GL_RENDERBUFFER) {
884             glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, &stencilRb);
885             glBindRenderbuffer(GL_RENDERBUFFER, stencilRb);
886             GLint samples = 0;
887             glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_SAMPLES, &samples);
888             if (samples) {
889                 multisample = true;
890             }
891         }
892
893         glBindRenderbuffer(GL_RENDERBUFFER, boundRb);
894
895         GLuint rbs[3];
896         GLint numRbs = 0;
897         GLuint fboCopy = 0;
898
899         if (multisample) {
900             // glReadPixels doesnt support multisampled buffers so we need
901             // to blit the fbo to a temporary one
902             fboCopy = downsampledFramebuffer(context,
903                                              boundDrawFbo, draw_buffer0,
904                                              colorRb, depthRb, stencilRb,
905                                              rbs, &numRbs);
906         }
907
908         dumpFramebufferAttachments(json, context, GL_DRAW_FRAMEBUFFER);
909
910         if (multisample) {
911             glBindRenderbuffer(GL_RENDERBUFFER_BINDING, boundRb);
912             glDeleteRenderbuffers(numRbs, rbs);
913             glDeleteFramebuffers(1, &fboCopy);
914         }
915
916         glBindFramebuffer(GL_READ_FRAMEBUFFER, boundReadFbo);
917         glBindFramebuffer(GL_DRAW_FRAMEBUFFER, boundDrawFbo);
918     }
919
920     json.endObject();
921     json.endMember(); // framebuffer
922 }
923
924
925 } /* namespace glstate */