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