]> git.cworth.org Git - apitrace/blob - glstate.cpp
Enable framebuffer dump during replay for EGL.
[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 #include <map>
32 #include <sstream>
33
34 #include "image.hpp"
35 #include "json.hpp"
36 #include "glproc.hpp"
37 #include "glsize.hpp"
38 #include "glstate.hpp"
39
40
41 #ifdef __APPLE__
42
43 #include <Carbon/Carbon.h>
44
45 #ifdef __cplusplus
46 extern "C" {
47 #endif
48
49 OSStatus CGSGetSurfaceBounds(CGSConnectionID, CGWindowID, CGSSurfaceID, CGRect *);
50
51 #ifdef __cplusplus
52 }
53 #endif
54
55 #endif /* __APPLE__ */
56
57
58 namespace glstate {
59
60
61 static inline void
62 resetPixelPackState(void) {
63     glPushClientAttrib(GL_CLIENT_PIXEL_STORE_BIT);
64     glPixelStorei(GL_PACK_SWAP_BYTES, GL_FALSE);
65     glPixelStorei(GL_PACK_LSB_FIRST, GL_FALSE);
66     glPixelStorei(GL_PACK_ROW_LENGTH, 0);
67     glPixelStorei(GL_PACK_IMAGE_HEIGHT, 0);
68     glPixelStorei(GL_PACK_SKIP_ROWS, 0);
69     glPixelStorei(GL_PACK_SKIP_PIXELS, 0);
70     glPixelStorei(GL_PACK_SKIP_IMAGES, 0);
71     glPixelStorei(GL_PACK_ALIGNMENT, 1);
72     glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
73 }
74
75
76 static inline void
77 restorePixelPackState(void) {
78     glPopClientAttrib();
79 }
80
81
82 // Mapping from shader type to shader source, used to accumulated the sources
83 // of different shaders with same type.
84 typedef std::map<std::string, std::string> ShaderMap;
85
86
87 static void
88 getShaderSource(ShaderMap &shaderMap, GLuint shader)
89 {
90     if (!shader) {
91         return;
92     }
93
94     GLint shader_type = 0;
95     glGetShaderiv(shader, GL_SHADER_TYPE, &shader_type);
96     if (!shader_type) {
97         return;
98     }
99
100     GLint source_length = 0;
101     glGetShaderiv(shader, GL_SHADER_SOURCE_LENGTH, &source_length);
102     if (!source_length) {
103         return;
104     }
105
106     GLchar *source = new GLchar[source_length];
107     GLsizei length = 0;
108     source[0] = 0;
109     glGetShaderSource(shader, source_length, &length, source);
110
111     shaderMap[enumToString(shader_type)] += source;
112
113     delete [] source;
114 }
115
116
117 static void
118 getShaderObjSource(ShaderMap &shaderMap, GLhandleARB shaderObj)
119 {
120     if (!shaderObj) {
121         return;
122     }
123
124     GLint object_type = 0;
125     glGetObjectParameterivARB(shaderObj, GL_OBJECT_TYPE_ARB, &object_type);
126     if (object_type != GL_SHADER_OBJECT_ARB) {
127         return;
128     }
129
130     GLint shader_type = 0;
131     glGetObjectParameterivARB(shaderObj, GL_OBJECT_SUBTYPE_ARB, &shader_type);
132     if (!shader_type) {
133         return;
134     }
135
136     GLint source_length = 0;
137     glGetObjectParameterivARB(shaderObj, GL_OBJECT_SHADER_SOURCE_LENGTH_ARB, &source_length);
138     if (!source_length) {
139         return;
140     }
141
142     GLcharARB *source = new GLcharARB[source_length];
143     GLsizei length = 0;
144     source[0] = 0;
145     glGetShaderSource(shaderObj, source_length, &length, source);
146
147     shaderMap[enumToString(shader_type)] += source;
148
149     delete [] source;
150 }
151
152
153 static inline void
154 dumpProgram(JSONWriter &json, GLint program)
155 {
156     GLint attached_shaders = 0;
157     glGetProgramiv(program, GL_ATTACHED_SHADERS, &attached_shaders);
158     if (!attached_shaders) {
159         return;
160     }
161
162     ShaderMap shaderMap;
163
164     GLuint *shaders = new GLuint[attached_shaders];
165     GLsizei count = 0;
166     glGetAttachedShaders(program, attached_shaders, &count, shaders);
167     std::sort(shaders, shaders + count);
168     for (GLsizei i = 0; i < count; ++ i) {
169        getShaderSource(shaderMap, shaders[i]);
170     }
171     delete [] shaders;
172
173     for (ShaderMap::const_iterator it = shaderMap.begin(); it != shaderMap.end(); ++it) {
174         json.beginMember(it->first);
175         json.writeString(it->second);
176         json.endMember();
177     }
178 }
179
180
181 static inline void
182 dumpProgramObj(JSONWriter &json, GLhandleARB programObj)
183 {
184     GLint attached_shaders = 0;
185     glGetObjectParameterivARB(programObj, GL_OBJECT_ATTACHED_OBJECTS_ARB, &attached_shaders);
186     if (!attached_shaders) {
187         return;
188     }
189
190     ShaderMap shaderMap;
191
192     GLhandleARB *shaderObjs = new GLhandleARB[attached_shaders];
193     GLsizei count = 0;
194     glGetAttachedObjectsARB(programObj, attached_shaders, &count, shaderObjs);
195     std::sort(shaderObjs, shaderObjs + count);
196     for (GLsizei i = 0; i < count; ++ i) {
197        getShaderObjSource(shaderMap, shaderObjs[i]);
198     }
199     delete [] shaderObjs;
200
201     for (ShaderMap::const_iterator it = shaderMap.begin(); it != shaderMap.end(); ++it) {
202         json.beginMember(it->first);
203         json.writeString(it->second);
204         json.endMember();
205     }
206 }
207
208 /*
209  * When fetching the uniform name of an array we usually get name[0]
210  * so we need to cut the trailing "[0]" in order to properly construct
211  * array names later. Otherwise we endup with stuff like
212  * uniformArray[0][0],
213  * uniformArray[0][1],
214  * instead of
215  * uniformArray[0],
216  * uniformArray[1].
217  */
218 static std::string
219 resolveUniformName(const GLchar *name,  GLint size)
220 {
221     std::string qualifiedName(name);
222     if (size > 1) {
223         std::string::size_type nameLength = qualifiedName.length();
224         static const char * const arrayStart = "[0]";
225         static const int arrayStartLen = 3;
226         if (qualifiedName.rfind(arrayStart) == (nameLength - arrayStartLen)) {
227             qualifiedName = qualifiedName.substr(0, nameLength - 3);
228         }
229     }
230     return qualifiedName;
231 }
232
233 static void
234 dumpUniform(JSONWriter &json, GLint program, GLint size, GLenum type, const GLchar *name) {
235     GLenum elemType;
236     GLint numElems;
237     __gl_uniform_size(type, elemType, numElems);
238     if (elemType == GL_NONE) {
239         return;
240     }
241
242     GLfloat fvalues[4*4];
243     GLdouble dvalues[4*4];
244     GLint ivalues[4*4];
245     GLuint uivalues[4*4];
246
247     GLint i, j;
248
249     std::string qualifiedName = resolveUniformName(name, size);
250
251     for (i = 0; i < size; ++i) {
252         std::stringstream ss;
253         ss << qualifiedName;
254
255         if (size > 1) {
256             ss << '[' << i << ']';
257         }
258
259         std::string elemName = ss.str();
260
261         json.beginMember(elemName);
262
263         GLint location = glGetUniformLocation(program, elemName.c_str());
264
265         if (numElems > 1) {
266             json.beginArray();
267         }
268
269         switch (elemType) {
270         case GL_FLOAT:
271             glGetUniformfv(program, location, fvalues);
272             for (j = 0; j < numElems; ++j) {
273                 json.writeNumber(fvalues[j]);
274             }
275             break;
276         case GL_DOUBLE:
277             glGetUniformdv(program, location, dvalues);
278             for (j = 0; j < numElems; ++j) {
279                 json.writeNumber(dvalues[j]);
280             }
281             break;
282         case GL_INT:
283             glGetUniformiv(program, location, ivalues);
284             for (j = 0; j < numElems; ++j) {
285                 json.writeNumber(ivalues[j]);
286             }
287             break;
288         case GL_UNSIGNED_INT:
289             glGetUniformuiv(program, location, uivalues);
290             for (j = 0; j < numElems; ++j) {
291                 json.writeNumber(uivalues[j]);
292             }
293             break;
294         case GL_BOOL:
295             glGetUniformiv(program, location, ivalues);
296             for (j = 0; j < numElems; ++j) {
297                 json.writeBool(ivalues[j]);
298             }
299             break;
300         default:
301             assert(0);
302             break;
303         }
304
305         if (numElems > 1) {
306             json.endArray();
307         }
308
309         json.endMember();
310     }
311 }
312
313
314 static void
315 dumpUniformARB(JSONWriter &json, GLhandleARB programObj, GLint size, GLenum type, const GLchar *name) {
316
317     GLenum elemType;
318     GLint numElems;
319     __gl_uniform_size(type, elemType, numElems);
320     if (elemType == GL_NONE) {
321         return;
322     }
323
324     GLfloat fvalues[4*4];
325     GLint ivalues[4*4];
326
327     GLint i, j;
328
329     std::string qualifiedName = resolveUniformName(name, size);
330
331     for (i = 0; i < size; ++i) {
332         std::stringstream ss;
333         ss << qualifiedName;
334
335         if (size > 1) {
336             ss << '[' << i << ']';
337         }
338
339         std::string elemName = ss.str();
340
341         json.beginMember(elemName);
342
343         GLint location = glGetUniformLocationARB(programObj, elemName.c_str());
344
345         if (numElems > 1) {
346             json.beginArray();
347         }
348
349         switch (elemType) {
350         case GL_DOUBLE:
351             // glGetUniformdvARB does not exists
352         case GL_FLOAT:
353             glGetUniformfvARB(programObj, location, fvalues);
354             for (j = 0; j < numElems; ++j) {
355                 json.writeNumber(fvalues[j]);
356             }
357             break;
358         case GL_UNSIGNED_INT:
359             // glGetUniformuivARB does not exists
360         case GL_INT:
361             glGetUniformivARB(programObj, location, ivalues);
362             for (j = 0; j < numElems; ++j) {
363                 json.writeNumber(ivalues[j]);
364             }
365             break;
366         case GL_BOOL:
367             glGetUniformivARB(programObj, location, ivalues);
368             for (j = 0; j < numElems; ++j) {
369                 json.writeBool(ivalues[j]);
370             }
371             break;
372         default:
373             assert(0);
374             break;
375         }
376
377         if (numElems > 1) {
378             json.endArray();
379         }
380
381         json.endMember();
382     }
383 }
384
385
386 static inline void
387 dumpProgramUniforms(JSONWriter &json, GLint program)
388 {
389     GLint active_uniforms = 0;
390     glGetProgramiv(program, GL_ACTIVE_UNIFORMS, &active_uniforms);
391     if (!active_uniforms) {
392         return;
393     }
394
395     GLint active_uniform_max_length = 0;
396     glGetProgramiv(program, GL_ACTIVE_UNIFORM_MAX_LENGTH, &active_uniform_max_length);
397     GLchar *name = new GLchar[active_uniform_max_length];
398     if (!name) {
399         return;
400     }
401
402     for (GLint index = 0; index < active_uniforms; ++index) {
403         GLsizei length = 0;
404         GLint size = 0;
405         GLenum type = GL_NONE;
406         glGetActiveUniform(program, index, active_uniform_max_length, &length, &size, &type, name);
407
408         dumpUniform(json, program, size, type, name);
409     }
410
411     delete [] name;
412 }
413
414
415 static inline void
416 dumpProgramObjUniforms(JSONWriter &json, GLhandleARB programObj)
417 {
418     GLint active_uniforms = 0;
419     glGetObjectParameterivARB(programObj, GL_OBJECT_ACTIVE_UNIFORMS_ARB, &active_uniforms);
420     if (!active_uniforms) {
421         return;
422     }
423
424     GLint active_uniform_max_length = 0;
425     glGetObjectParameterivARB(programObj, GL_OBJECT_ACTIVE_UNIFORM_MAX_LENGTH_ARB, &active_uniform_max_length);
426     GLchar *name = new GLchar[active_uniform_max_length];
427     if (!name) {
428         return;
429     }
430
431     for (GLint index = 0; index < active_uniforms; ++index) {
432         GLsizei length = 0;
433         GLint size = 0;
434         GLenum type = GL_NONE;
435         glGetActiveUniformARB(programObj, index, active_uniform_max_length, &length, &size, &type, name);
436
437         dumpUniformARB(json, programObj, size, type, name);
438     }
439
440     delete [] name;
441 }
442
443
444 static inline void
445 dumpArbProgram(JSONWriter &json, GLenum target)
446 {
447     if (!glIsEnabled(target)) {
448         return;
449     }
450
451     GLint program_length = 0;
452     glGetProgramivARB(target, GL_PROGRAM_LENGTH_ARB, &program_length);
453     if (!program_length) {
454         return;
455     }
456
457     GLchar *source = new GLchar[program_length + 1];
458     source[0] = 0;
459     glGetProgramStringARB(target, GL_PROGRAM_STRING_ARB, source);
460     source[program_length] = 0;
461
462     json.beginMember(enumToString(target));
463     json.writeString(source);
464     json.endMember();
465
466     delete [] source;
467 }
468
469
470 static inline void
471 dumpArbProgramUniforms(JSONWriter &json, GLenum target, const char *prefix)
472 {
473     if (!glIsEnabled(target)) {
474         return;
475     }
476
477     GLint program_parameters = 0;
478     glGetProgramivARB(target, GL_PROGRAM_PARAMETERS_ARB, &program_parameters);
479     if (!program_parameters) {
480         return;
481     }
482
483     GLint max_program_local_parameters = 0;
484     glGetProgramivARB(target, GL_MAX_PROGRAM_LOCAL_PARAMETERS_ARB, &max_program_local_parameters);
485     for (GLint index = 0; index < max_program_local_parameters; ++index) {
486         GLdouble params[4] = {0, 0, 0, 0};
487         glGetProgramLocalParameterdvARB(target, index, params);
488
489         if (!params[0] && !params[1] && !params[2] && !params[3]) {
490             continue;
491         }
492
493         char name[256];
494         snprintf(name, sizeof name, "%sprogram.local[%i]", prefix, index);
495
496         json.beginMember(name);
497         json.beginArray();
498         json.writeNumber(params[0]);
499         json.writeNumber(params[1]);
500         json.writeNumber(params[2]);
501         json.writeNumber(params[3]);
502         json.endArray();
503         json.endMember();
504     }
505
506     GLint max_program_env_parameters = 0;
507     glGetProgramivARB(target, GL_MAX_PROGRAM_ENV_PARAMETERS_ARB, &max_program_env_parameters);
508     for (GLint index = 0; index < max_program_env_parameters; ++index) {
509         GLdouble params[4] = {0, 0, 0, 0};
510         glGetProgramEnvParameterdvARB(target, index, params);
511
512         if (!params[0] && !params[1] && !params[2] && !params[3]) {
513             continue;
514         }
515
516         char name[256];
517         snprintf(name, sizeof name, "%sprogram.env[%i]", prefix, index);
518
519         json.beginMember(name);
520         json.beginArray();
521         json.writeNumber(params[0]);
522         json.writeNumber(params[1]);
523         json.writeNumber(params[2]);
524         json.writeNumber(params[3]);
525         json.endArray();
526         json.endMember();
527     }
528 }
529
530
531 static inline void
532 dumpShadersUniforms(JSONWriter &json)
533 {
534     GLint program = 0;
535     glGetIntegerv(GL_CURRENT_PROGRAM, &program);
536
537     GLhandleARB programObj = glGetHandleARB(GL_PROGRAM_OBJECT_ARB);
538
539     json.beginMember("shaders");
540     json.beginObject();
541     if (program) {
542         dumpProgram(json, program);
543     } else if (programObj) {
544         dumpProgramObj(json, programObj);
545     } else {
546         dumpArbProgram(json, GL_FRAGMENT_PROGRAM_ARB);
547         dumpArbProgram(json, GL_VERTEX_PROGRAM_ARB);
548     }
549     json.endObject();
550     json.endMember(); // shaders
551
552     json.beginMember("uniforms");
553     json.beginObject();
554     if (program) {
555         dumpProgramUniforms(json, program);
556     } else if (programObj) {
557         dumpProgramObjUniforms(json, programObj);
558     } else {
559         dumpArbProgramUniforms(json, GL_FRAGMENT_PROGRAM_ARB, "fp.");
560         dumpArbProgramUniforms(json, GL_VERTEX_PROGRAM_ARB, "vp.");
561     }
562     json.endObject();
563     json.endMember(); // uniforms
564 }
565
566
567 static inline void
568 dumpTextureImage(JSONWriter &json, GLenum target, GLint level)
569 {
570     GLint width, height = 1, depth = 1;
571     GLint format;
572
573     glGetTexLevelParameteriv(target, level, GL_TEXTURE_INTERNAL_FORMAT, &format);
574
575     width = 0;
576     glGetTexLevelParameteriv(target, level, GL_TEXTURE_WIDTH, &width);
577
578     if (target != GL_TEXTURE_1D) {
579         height = 0;
580         glGetTexLevelParameteriv(target, level, GL_TEXTURE_HEIGHT, &height);
581         if (target == GL_TEXTURE_3D) {
582             depth = 0;
583             glGetTexLevelParameteriv(target, level, GL_TEXTURE_DEPTH, &depth);
584         }
585     }
586
587     if (width <= 0 || height <= 0 || depth <= 0) {
588         return;
589     } else {
590         char label[512];
591
592         GLint active_texture = GL_TEXTURE0;
593         glGetIntegerv(GL_ACTIVE_TEXTURE, &active_texture);
594         snprintf(label, sizeof label, "%s, %s, level = %d",
595                  enumToString(active_texture), enumToString(target), level);
596
597         json.beginMember(label);
598
599         json.beginObject();
600
601         // Tell the GUI this is no ordinary object, but an image
602         json.writeStringMember("__class__", "image");
603
604         json.writeNumberMember("__width__", width);
605         json.writeNumberMember("__height__", height);
606         json.writeNumberMember("__depth__", depth);
607
608         json.writeStringMember("__format__", enumToString(format));
609
610         // Hardcoded for now, but we could chose types more adequate to the
611         // texture internal format
612         json.writeStringMember("__type__", "uint8");
613         json.writeBoolMember("__normalized__", true);
614         json.writeNumberMember("__channels__", 4);
615
616         GLubyte *pixels = new GLubyte[depth*width*height*4];
617
618         resetPixelPackState();
619
620         glGetTexImage(target, level, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
621
622         restorePixelPackState();
623
624         json.beginMember("__data__");
625         char *pngBuffer;
626         int pngBufferSize;
627         image::writePixelsToBuffer(pixels, width, height, 4, true, &pngBuffer, &pngBufferSize);
628         json.writeBase64(pngBuffer, pngBufferSize);
629         free(pngBuffer);
630         json.endMember(); // __data__
631
632         delete [] pixels;
633         json.endObject();
634     }
635 }
636
637
638 static inline void
639 dumpTexture(JSONWriter &json, GLenum target, GLenum binding)
640 {
641     GLint texture_binding = 0;
642     glGetIntegerv(binding, &texture_binding);
643     if (!glIsEnabled(target) && !texture_binding) {
644         return;
645     }
646
647     GLint level = 0;
648     do {
649         GLint width = 0, height = 0;
650         glGetTexLevelParameteriv(target, level, GL_TEXTURE_WIDTH, &width);
651         glGetTexLevelParameteriv(target, level, GL_TEXTURE_HEIGHT, &height);
652         if (!width || !height) {
653             break;
654         }
655
656         if (target == GL_TEXTURE_CUBE_MAP) {
657             for (int face = 0; face < 6; ++face) {
658                 dumpTextureImage(json, GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, level);
659             }
660         } else {
661             dumpTextureImage(json, target, level);
662         }
663
664         ++level;
665     } while(true);
666 }
667
668
669 static inline void
670 dumpTextures(JSONWriter &json)
671 {
672     json.beginMember("textures");
673     json.beginObject();
674     GLint active_texture = GL_TEXTURE0;
675     glGetIntegerv(GL_ACTIVE_TEXTURE, &active_texture);
676     GLint max_texture_coords = 0;
677     glGetIntegerv(GL_MAX_TEXTURE_COORDS, &max_texture_coords);
678     GLint max_combined_texture_image_units = 0;
679     glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &max_combined_texture_image_units);
680     GLint max_units = std::max(max_combined_texture_image_units, max_texture_coords);
681     for (GLint unit = 0; unit < max_units; ++unit) {
682         GLenum texture = GL_TEXTURE0 + unit;
683         glActiveTexture(texture);
684         dumpTexture(json, GL_TEXTURE_1D, GL_TEXTURE_BINDING_1D);
685         dumpTexture(json, GL_TEXTURE_2D, GL_TEXTURE_BINDING_2D);
686         dumpTexture(json, GL_TEXTURE_3D, GL_TEXTURE_BINDING_3D);
687         dumpTexture(json, GL_TEXTURE_RECTANGLE, GL_TEXTURE_BINDING_RECTANGLE);
688         dumpTexture(json, GL_TEXTURE_CUBE_MAP, GL_TEXTURE_BINDING_CUBE_MAP);
689     }
690     glActiveTexture(active_texture);
691     json.endObject();
692     json.endMember(); // textures
693 }
694
695
696 static bool
697 getDrawableBounds(GLint *width, GLint *height) {
698 #if defined(TRACE_EGL)
699
700     EGLContext currentContext = eglGetCurrentContext();
701     if (currentContext == EGL_NO_CONTEXT) {
702         return false;
703     }
704
705     EGLSurface currentSurface = eglGetCurrentSurface(EGL_DRAW);
706     if (currentSurface == EGL_NO_SURFACE) {
707         return false;
708     }
709
710     EGLDisplay currentDisplay = eglGetCurrentDisplay();
711     if (currentDisplay == EGL_NO_DISPLAY) {
712         return false;
713     }
714
715     if (!eglQuerySurface(currentDisplay, currentSurface, EGL_WIDTH, width) ||
716         !eglQuerySurface(currentDisplay, currentSurface, EGL_HEIGHT, height)) {
717         return false;
718     }
719
720     return true;
721
722 #elif defined(_WIN32)
723
724     HDC hDC = wglGetCurrentDC();
725     if (!hDC) {
726         return false;
727     }
728
729     HWND hWnd = WindowFromDC(hDC);
730     RECT rect;
731
732     if (!GetClientRect(hWnd, &rect)) {
733        return false;
734     }
735
736     *width  = rect.right  - rect.left;
737     *height = rect.bottom - rect.top;
738
739 #elif defined(__APPLE__)
740
741     CGLContextObj ctx = CGLGetCurrentContext();
742     if (ctx == NULL) {
743         return false;
744     }
745
746     CGSConnectionID cid;
747     CGSWindowID wid;
748     CGSSurfaceID sid;
749
750     if (CGLGetSurface(ctx, &cid, &wid, &sid) != kCGLNoError) {
751         return false;
752     }
753
754     CGRect rect;
755
756     if (CGSGetSurfaceBounds(cid, wid, sid, &rect) != 0) {
757         return false;
758     }
759
760     *width = rect.size.width;
761     *height = rect.size.height;
762     return true;
763
764 #elif defined(HAVE_X11)
765
766     Display *display;
767     Drawable drawable;
768     Window root;
769     int x, y;
770     unsigned int w, h, bw, depth;
771
772     display = glXGetCurrentDisplay();
773     if (!display) {
774         return false;
775     }
776
777     drawable = glXGetCurrentDrawable();
778     if (drawable == None) {
779         return false;
780     }
781
782     if (!XGetGeometry(display, drawable, &root, &x, &y, &w, &h, &bw, &depth)) {
783         return false;
784     }
785
786     *width = w;
787     *height = h;
788     return true;
789
790 #else
791
792     return false;
793
794 #endif
795 }
796
797
798 static const GLenum texture_bindings[][2] = {
799     {GL_TEXTURE_1D, GL_TEXTURE_BINDING_1D},
800     {GL_TEXTURE_2D, GL_TEXTURE_BINDING_2D},
801     {GL_TEXTURE_3D, GL_TEXTURE_BINDING_3D},
802     {GL_TEXTURE_RECTANGLE, GL_TEXTURE_BINDING_RECTANGLE},
803     {GL_TEXTURE_CUBE_MAP, GL_TEXTURE_BINDING_CUBE_MAP}
804 };
805
806
807 static bool
808 bindTexture(GLint texture, GLenum &target, GLint &bound_texture)
809 {
810
811     for (unsigned i = 0; i < sizeof(texture_bindings)/sizeof(texture_bindings[0]); ++i) {
812         target  = texture_bindings[i][0];
813
814         GLenum binding = texture_bindings[i][1];
815
816         while (glGetError() != GL_NO_ERROR)
817             ;
818
819         glGetIntegerv(binding, &bound_texture);
820         glBindTexture(target, texture);
821
822         if (glGetError() == GL_NO_ERROR) {
823             return true;
824         }
825
826         glBindTexture(target, bound_texture);
827     }
828
829     target = GL_NONE;
830
831     return false;
832 }
833
834
835 static bool
836 getTextureLevelSize(GLint texture, GLint level, GLint *width, GLint *height)
837 {
838     *width = 0;
839     *height = 0;
840
841     GLenum target;
842     GLint bound_texture = 0;
843     if (!bindTexture(texture, target, bound_texture)) {
844         return false;
845     }
846
847     glGetTexLevelParameteriv(target, level, GL_TEXTURE_WIDTH, width);
848     glGetTexLevelParameteriv(target, level, GL_TEXTURE_HEIGHT, height);
849
850     glBindTexture(target, bound_texture);
851
852     return *width > 0 && *height > 0;
853 }
854
855
856 static GLenum
857 getTextureLevelFormat(GLint texture, GLint level)
858 {
859     GLenum target;
860     GLint bound_texture = 0;
861     if (!bindTexture(texture, target, bound_texture)) {
862         return GL_NONE;
863     }
864
865     GLint format = GL_NONE;
866     glGetTexLevelParameteriv(target, level, GL_TEXTURE_INTERNAL_FORMAT, &format);
867
868     glBindTexture(target, bound_texture);
869
870     return format;
871 }
872
873
874
875 static bool
876 getRenderbufferSize(GLint renderbuffer, GLint *width, GLint *height)
877 {
878     GLint bound_renderbuffer = 0;
879     glGetIntegerv(GL_RENDERBUFFER_BINDING, &bound_renderbuffer);
880     glBindRenderbuffer(GL_RENDERBUFFER, renderbuffer);
881
882     *width = 0;
883     *height = 0;
884     glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, width);
885     glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, height);
886
887     glBindRenderbuffer(GL_RENDERBUFFER, bound_renderbuffer);
888     
889     return *width > 0 && *height > 0;
890 }
891
892
893 static GLenum
894 getRenderbufferFormat(GLint renderbuffer)
895 {
896     GLint bound_renderbuffer = 0;
897     glGetIntegerv(GL_RENDERBUFFER_BINDING, &bound_renderbuffer);
898     glBindRenderbuffer(GL_RENDERBUFFER, renderbuffer);
899
900     GLint format = GL_NONE;
901     glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_INTERNAL_FORMAT, &format);
902
903     glBindRenderbuffer(GL_RENDERBUFFER, bound_renderbuffer);
904     
905     return format;
906 }
907
908
909 static bool
910 getFramebufferAttachmentSize(GLenum target, GLenum attachment, GLint *width, GLint *height)
911 {
912     GLint object_type = GL_NONE;
913     glGetFramebufferAttachmentParameteriv(target, attachment,
914                                           GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE,
915                                           &object_type);
916     if (object_type == GL_NONE) {
917         return false;
918     }
919
920     GLint object_name = 0;
921     glGetFramebufferAttachmentParameteriv(target, attachment,
922                                           GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME,
923                                           &object_name);
924     if (object_name == 0) {
925         return false;
926     }
927
928     if (object_type == GL_RENDERBUFFER) {
929         return getRenderbufferSize(object_name, width, height);
930     } else if (object_type == GL_TEXTURE) {
931         GLint texture_level = 0;
932         glGetFramebufferAttachmentParameteriv(target, attachment,
933                                               GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL,
934                                               &texture_level);
935         return getTextureLevelSize(object_name, texture_level, width, height);
936     } else {
937         std::cerr << "warning: unexpected GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE = " << object_type << "\n";
938         return false;
939     }
940 }
941
942
943
944 static GLint
945 getFramebufferAttachmentFormat(GLenum target, GLenum attachment)
946 {
947     GLint object_type = GL_NONE;
948     glGetFramebufferAttachmentParameteriv(target, attachment,
949                                           GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE,
950                                           &object_type);
951     if (object_type == GL_NONE) {
952         return GL_NONE;
953     }
954
955     GLint object_name = 0;
956     glGetFramebufferAttachmentParameteriv(target, attachment,
957                                           GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME,
958                                           &object_name);
959     if (object_name == 0) {
960         return GL_NONE;
961     }
962
963     if (object_type == GL_RENDERBUFFER) {
964         return getRenderbufferFormat(object_name);
965     } else if (object_type == GL_TEXTURE) {
966         GLint texture_level = 0;
967         glGetFramebufferAttachmentParameteriv(target, attachment,
968                                               GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL,
969                                               &texture_level);
970         return getTextureLevelFormat(object_name, texture_level);
971     } else {
972         std::cerr << "warning: unexpected GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE = " << object_type << "\n";
973         return GL_NONE;
974     }
975 }
976
977
978
979 image::Image *
980 getDrawBufferImage() {
981     GLenum format = GL_RGB;
982     GLint channels = __gl_format_channels(format);
983     if (channels > 4) {
984         return NULL;
985     }
986
987     GLint draw_framebuffer = 0;
988     glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &draw_framebuffer);
989
990     GLint draw_buffer = GL_NONE;
991     GLint width, height;
992     if (draw_framebuffer) {
993         glGetIntegerv(GL_DRAW_BUFFER0, &draw_buffer);
994         if (draw_buffer == GL_NONE) {
995             return NULL;
996         }
997
998         if (!getFramebufferAttachmentSize(GL_DRAW_FRAMEBUFFER, draw_buffer, &width, &height)) {
999             return NULL;
1000         }
1001     } else {
1002         glGetIntegerv(GL_DRAW_BUFFER, &draw_buffer);
1003         if (draw_buffer == GL_NONE) {
1004             return NULL;
1005         }
1006
1007         if (!getDrawableBounds(&width, &height)) {
1008             return NULL;
1009         }
1010     }
1011
1012     image::Image *image = new image::Image(width, height, channels, true);
1013     if (!image) {
1014         return NULL;
1015     }
1016
1017     while (glGetError() != GL_NO_ERROR) {}
1018
1019     GLint read_framebuffer = 0;
1020     glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &read_framebuffer);
1021     glBindFramebuffer(GL_READ_FRAMEBUFFER, draw_framebuffer);
1022
1023     GLint read_buffer = 0;
1024     glGetIntegerv(GL_READ_BUFFER, &read_buffer);
1025     glReadBuffer(draw_buffer);
1026
1027     // TODO: reset imaging state too
1028     resetPixelPackState();
1029
1030     glReadPixels(0, 0, width, height, format, GL_UNSIGNED_BYTE, image->pixels);
1031
1032     restorePixelPackState();
1033     glReadBuffer(read_buffer);
1034     glBindFramebuffer(GL_READ_FRAMEBUFFER, read_framebuffer);
1035
1036     GLenum error = glGetError();
1037     if (error != GL_NO_ERROR) {
1038         do {
1039             std::cerr << "warning: " << enumToString(error) << " while getting snapshot\n";
1040             error = glGetError();
1041         } while(error != GL_NO_ERROR);
1042         delete image;
1043         return NULL;
1044     }
1045      
1046     return image;
1047 }
1048
1049
1050 /**
1051  * Dump the image of the currently bound read buffer.
1052  */
1053 static inline void
1054 dumpReadBufferImage(JSONWriter &json, GLint width, GLint height, GLenum format,
1055                     GLint internalFormat = GL_NONE)
1056 {
1057     GLint channels = __gl_format_channels(format);
1058
1059     json.beginObject();
1060
1061     // Tell the GUI this is no ordinary object, but an image
1062     json.writeStringMember("__class__", "image");
1063
1064     json.writeNumberMember("__width__", width);
1065     json.writeNumberMember("__height__", height);
1066     json.writeNumberMember("__depth__", 1);
1067
1068     json.writeStringMember("__format__", enumToString(internalFormat));
1069
1070     // Hardcoded for now, but we could chose types more adequate to the
1071     // texture internal format
1072     json.writeStringMember("__type__", "uint8");
1073     json.writeBoolMember("__normalized__", true);
1074     json.writeNumberMember("__channels__", channels);
1075
1076     GLubyte *pixels = new GLubyte[width*height*channels];
1077
1078     // TODO: reset imaging state too
1079     resetPixelPackState();
1080
1081     glReadPixels(0, 0, width, height, format, GL_UNSIGNED_BYTE, pixels);
1082
1083     restorePixelPackState();
1084
1085     json.beginMember("__data__");
1086     char *pngBuffer;
1087     int pngBufferSize;
1088     image::writePixelsToBuffer(pixels, width, height, channels, true, &pngBuffer, &pngBufferSize);
1089     //std::cerr <<" Before = "<<(width * height * channels * sizeof *pixels)
1090     //          <<", after = "<<pngBufferSize << ", ratio = " << double(width * height * channels * sizeof *pixels)/pngBufferSize;
1091     json.writeBase64(pngBuffer, pngBufferSize);
1092     free(pngBuffer);
1093     json.endMember(); // __data__
1094
1095     delete [] pixels;
1096     json.endObject();
1097 }
1098
1099
1100 static inline GLuint
1101 downsampledFramebuffer(GLuint oldFbo, GLint drawbuffer,
1102                        GLint colorRb, GLint depthRb, GLint stencilRb,
1103                        GLuint *rbs, GLint *numRbs)
1104 {
1105     GLuint fbo;
1106     GLint format;
1107     GLint w, h;
1108
1109     *numRbs = 0;
1110
1111     glGenFramebuffers(1, &fbo);
1112     glBindFramebuffer(GL_FRAMEBUFFER, fbo);
1113
1114     glBindRenderbuffer(GL_RENDERBUFFER, colorRb);
1115     glGetRenderbufferParameteriv(GL_RENDERBUFFER,
1116                                  GL_RENDERBUFFER_WIDTH, &w);
1117     glGetRenderbufferParameteriv(GL_RENDERBUFFER,
1118                                  GL_RENDERBUFFER_HEIGHT, &h);
1119     glGetRenderbufferParameteriv(GL_RENDERBUFFER,
1120                                  GL_RENDERBUFFER_INTERNAL_FORMAT, &format);
1121
1122     glGenRenderbuffers(1, &rbs[*numRbs]);
1123     glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]);
1124     glRenderbufferStorage(GL_RENDERBUFFER, format, w, h);
1125     glFramebufferRenderbuffer(GL_FRAMEBUFFER, drawbuffer,
1126                               GL_RENDERBUFFER, rbs[*numRbs]);
1127
1128     glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo);
1129     glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
1130     glDrawBuffer(drawbuffer);
1131     glReadBuffer(drawbuffer);
1132     glBlitFramebuffer(0, 0, w, h, 0, 0, w, h,
1133                       GL_COLOR_BUFFER_BIT, GL_NEAREST);
1134     glBindFramebuffer(GL_FRAMEBUFFER, fbo);
1135     ++*numRbs;
1136
1137     if (stencilRb == depthRb && stencilRb) {
1138         //combined depth and stencil buffer
1139         glBindRenderbuffer(GL_RENDERBUFFER, depthRb);
1140         glGetRenderbufferParameteriv(GL_RENDERBUFFER,
1141                                      GL_RENDERBUFFER_WIDTH, &w);
1142         glGetRenderbufferParameteriv(GL_RENDERBUFFER,
1143                                      GL_RENDERBUFFER_HEIGHT, &h);
1144         glGetRenderbufferParameteriv(GL_RENDERBUFFER,
1145                                      GL_RENDERBUFFER_INTERNAL_FORMAT, &format);
1146
1147         glGenRenderbuffers(1, &rbs[*numRbs]);
1148         glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]);
1149         glRenderbufferStorage(GL_RENDERBUFFER, format, w, h);
1150         glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT,
1151                                   GL_RENDERBUFFER, rbs[*numRbs]);
1152         glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo);
1153         glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
1154         glBlitFramebuffer(0, 0, w, h, 0, 0, w, h,
1155                           GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT, GL_NEAREST);
1156         glBindFramebuffer(GL_FRAMEBUFFER, fbo);
1157         ++*numRbs;
1158     } else {
1159         if (depthRb) {
1160             glBindRenderbuffer(GL_RENDERBUFFER, depthRb);
1161             glGetRenderbufferParameteriv(GL_RENDERBUFFER,
1162                                          GL_RENDERBUFFER_WIDTH, &w);
1163             glGetRenderbufferParameteriv(GL_RENDERBUFFER,
1164                                          GL_RENDERBUFFER_HEIGHT, &h);
1165             glGetRenderbufferParameteriv(GL_RENDERBUFFER,
1166                                          GL_RENDERBUFFER_INTERNAL_FORMAT, &format);
1167
1168             glGenRenderbuffers(1, &rbs[*numRbs]);
1169             glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]);
1170             glRenderbufferStorage(GL_RENDERBUFFER, format, w, h);
1171             glFramebufferRenderbuffer(GL_FRAMEBUFFER,
1172                                       GL_DEPTH_ATTACHMENT,
1173                                       GL_RENDERBUFFER, rbs[*numRbs]);
1174             glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo);
1175             glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
1176             glDrawBuffer(GL_DEPTH_ATTACHMENT);
1177             glReadBuffer(GL_DEPTH_ATTACHMENT);
1178             glBlitFramebuffer(0, 0, w, h, 0, 0, w, h,
1179                               GL_DEPTH_BUFFER_BIT, GL_NEAREST);
1180             ++*numRbs;
1181         }
1182         if (stencilRb) {
1183             glBindRenderbuffer(GL_RENDERBUFFER, stencilRb);
1184             glGetRenderbufferParameteriv(GL_RENDERBUFFER,
1185                                          GL_RENDERBUFFER_WIDTH, &w);
1186             glGetRenderbufferParameteriv(GL_RENDERBUFFER,
1187                                          GL_RENDERBUFFER_HEIGHT, &h);
1188             glGetRenderbufferParameteriv(GL_RENDERBUFFER,
1189                                      GL_RENDERBUFFER_INTERNAL_FORMAT, &format);
1190
1191             glGenRenderbuffers(1, &rbs[*numRbs]);
1192             glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]);
1193             glRenderbufferStorage(GL_RENDERBUFFER, format, w, h);
1194             glFramebufferRenderbuffer(GL_FRAMEBUFFER,
1195                                       GL_STENCIL_ATTACHMENT,
1196                                       GL_RENDERBUFFER, rbs[*numRbs]);
1197             glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo);
1198             glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
1199             glDrawBuffer(GL_STENCIL_ATTACHMENT);
1200             glReadBuffer(GL_STENCIL_ATTACHMENT);
1201             glBlitFramebuffer(0, 0, w, h, 0, 0, w, h,
1202                               GL_STENCIL_BUFFER_BIT, GL_NEAREST);
1203             ++*numRbs;
1204         }
1205     }
1206
1207     return fbo;
1208 }
1209
1210
1211 /**
1212  * Dump images of current draw drawable/window.
1213  */
1214 static void
1215 dumpDrawableImages(JSONWriter &json)
1216 {
1217     GLint width, height;
1218
1219     if (!getDrawableBounds(&width, &height)) {
1220         return;
1221     }
1222
1223     GLint draw_buffer = GL_NONE;
1224     glGetIntegerv(GL_DRAW_BUFFER, &draw_buffer);
1225     glReadBuffer(draw_buffer);
1226
1227     if (draw_buffer != GL_NONE) {
1228         GLint read_buffer = GL_NONE;
1229         glGetIntegerv(GL_READ_BUFFER, &read_buffer);
1230
1231         GLint alpha_bits = 0;
1232 #if 0
1233         // XXX: Ignore alpha until we are able to match the traced visual
1234         glGetIntegerv(GL_ALPHA_BITS, &alpha_bits);
1235 #endif
1236         GLenum format = alpha_bits ? GL_RGBA : GL_RGB;
1237         json.beginMember(enumToString(draw_buffer));
1238         dumpReadBufferImage(json, width, height, format);
1239         json.endMember();
1240
1241         glReadBuffer(read_buffer);
1242     }
1243
1244     GLint depth_bits = 0;
1245     glGetIntegerv(GL_DEPTH_BITS, &depth_bits);
1246     if (depth_bits) {
1247         json.beginMember("GL_DEPTH_COMPONENT");
1248         dumpReadBufferImage(json, width, height, GL_DEPTH_COMPONENT);
1249         json.endMember();
1250     }
1251
1252     GLint stencil_bits = 0;
1253     glGetIntegerv(GL_STENCIL_BITS, &stencil_bits);
1254     if (stencil_bits) {
1255         json.beginMember("GL_STENCIL_INDEX");
1256         dumpReadBufferImage(json, width, height, GL_STENCIL_INDEX);
1257         json.endMember();
1258     }
1259 }
1260
1261
1262 /**
1263  * Dump the specified framebuffer attachment.
1264  *
1265  * In the case of a color attachment, it assumes it is already bound for read.
1266  */
1267 static void
1268 dumpFramebufferAttachment(JSONWriter &json, GLenum target, GLenum attachment, GLenum format)
1269 {
1270     GLint width = 0, height = 0;
1271     if (!getFramebufferAttachmentSize(target, attachment, &width, &height)) {
1272         return;
1273     }
1274
1275     GLint internalFormat = getFramebufferAttachmentFormat(target, attachment);
1276
1277     json.beginMember(enumToString(attachment));
1278     dumpReadBufferImage(json, width, height, format, internalFormat);
1279     json.endMember();
1280 }
1281
1282
1283 static void
1284 dumpFramebufferAttachments(JSONWriter &json, GLenum target)
1285 {
1286     GLint read_framebuffer = 0;
1287     glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &read_framebuffer);
1288
1289     GLint read_buffer = GL_NONE;
1290     glGetIntegerv(GL_READ_BUFFER, &read_buffer);
1291
1292     GLint max_draw_buffers = 1;
1293     glGetIntegerv(GL_MAX_DRAW_BUFFERS, &max_draw_buffers);
1294     GLint max_color_attachments = 0;
1295     glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS, &max_color_attachments);
1296
1297     for (GLint i = 0; i < max_draw_buffers; ++i) {
1298         GLint draw_buffer = GL_NONE;
1299         glGetIntegerv(GL_DRAW_BUFFER0 + i, &draw_buffer);
1300         if (draw_buffer != GL_NONE) {
1301             glReadBuffer(draw_buffer);
1302             GLint attachment;
1303             if (draw_buffer >= GL_COLOR_ATTACHMENT0 && draw_buffer < GL_COLOR_ATTACHMENT0 + max_color_attachments) {
1304                 attachment = draw_buffer;
1305             } else {
1306                 std::cerr << "warning: unexpected GL_DRAW_BUFFER" << i << " = " << draw_buffer << "\n";
1307                 attachment = GL_COLOR_ATTACHMENT0;
1308             }
1309             GLint alpha_size = 0;
1310             glGetFramebufferAttachmentParameteriv(target, attachment,
1311                                                   GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE,
1312                                                   &alpha_size);
1313             GLenum format = alpha_size ? GL_RGBA : GL_RGB;
1314             dumpFramebufferAttachment(json, target, attachment, format);
1315         }
1316     }
1317
1318     glReadBuffer(read_buffer);
1319
1320     dumpFramebufferAttachment(json, target, GL_DEPTH_ATTACHMENT, GL_DEPTH_COMPONENT);
1321     dumpFramebufferAttachment(json, target, GL_STENCIL_ATTACHMENT, GL_STENCIL_INDEX);
1322
1323     glBindFramebuffer(GL_READ_FRAMEBUFFER, read_framebuffer);
1324 }
1325
1326
1327 static void
1328 dumpFramebuffer(JSONWriter &json)
1329 {
1330     json.beginMember("framebuffer");
1331     json.beginObject();
1332
1333     GLint boundDrawFbo = 0, boundReadFbo = 0;
1334     glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &boundDrawFbo);
1335     glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &boundReadFbo);
1336     if (!boundDrawFbo) {
1337         dumpDrawableImages(json);
1338     } else {
1339         GLint colorRb = 0, stencilRb = 0, depthRb = 0;
1340         GLint draw_buffer0 = GL_NONE;
1341         glGetIntegerv(GL_DRAW_BUFFER0, &draw_buffer0);
1342         bool multisample = false;
1343
1344         GLint boundRb = 0;
1345         glGetIntegerv(GL_RENDERBUFFER_BINDING, &boundRb);
1346
1347         GLint object_type;
1348         glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, draw_buffer0, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, &object_type);
1349         if (object_type == GL_RENDERBUFFER) {
1350             glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, draw_buffer0, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, &colorRb);
1351             glBindRenderbuffer(GL_RENDERBUFFER, colorRb);
1352             GLint samples = 0;
1353             glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_SAMPLES, &samples);
1354             if (samples) {
1355                 multisample = true;
1356             }
1357         }
1358
1359         glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, &object_type);
1360         if (object_type == GL_RENDERBUFFER) {
1361             glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, &depthRb);
1362             glBindRenderbuffer(GL_RENDERBUFFER, depthRb);
1363             GLint samples = 0;
1364             glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_SAMPLES, &samples);
1365             if (samples) {
1366                 multisample = true;
1367             }
1368         }
1369
1370         glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, &object_type);
1371         if (object_type == GL_RENDERBUFFER) {
1372             glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, &stencilRb);
1373             glBindRenderbuffer(GL_RENDERBUFFER, stencilRb);
1374             GLint samples = 0;
1375             glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_SAMPLES, &samples);
1376             if (samples) {
1377                 multisample = true;
1378             }
1379         }
1380
1381         glBindRenderbuffer(GL_RENDERBUFFER, boundRb);
1382
1383         GLuint rbs[3];
1384         GLint numRbs = 0;
1385         GLuint fboCopy = 0;
1386
1387         if (multisample) {
1388             // glReadPixels doesnt support multisampled buffers so we need
1389             // to blit the fbo to a temporary one
1390             fboCopy = downsampledFramebuffer(boundDrawFbo, draw_buffer0,
1391                                              colorRb, depthRb, stencilRb,
1392                                              rbs, &numRbs);
1393         }
1394
1395         dumpFramebufferAttachments(json, GL_DRAW_FRAMEBUFFER);
1396
1397         if (multisample) {
1398             glBindRenderbuffer(GL_RENDERBUFFER_BINDING, boundRb);
1399             glDeleteRenderbuffers(numRbs, rbs);
1400             glDeleteFramebuffers(1, &fboCopy);
1401         }
1402
1403         glBindFramebuffer(GL_READ_FRAMEBUFFER, boundReadFbo);
1404         glBindFramebuffer(GL_DRAW_FRAMEBUFFER, boundDrawFbo);
1405     }
1406
1407     json.endObject();
1408     json.endMember(); // framebuffer
1409 }
1410
1411
1412 static const GLenum bindings[] = {
1413     GL_DRAW_BUFFER,
1414     GL_READ_BUFFER,
1415     GL_PIXEL_PACK_BUFFER_BINDING,
1416     GL_PIXEL_UNPACK_BUFFER_BINDING,
1417     GL_TEXTURE_BINDING_1D,
1418     GL_TEXTURE_BINDING_2D,
1419     GL_TEXTURE_BINDING_3D,
1420     GL_TEXTURE_BINDING_RECTANGLE,
1421     GL_TEXTURE_BINDING_CUBE_MAP,
1422     GL_DRAW_FRAMEBUFFER_BINDING,
1423     GL_READ_FRAMEBUFFER_BINDING,
1424     GL_RENDERBUFFER_BINDING,
1425     GL_DRAW_BUFFER0,
1426     GL_DRAW_BUFFER1,
1427     GL_DRAW_BUFFER2,
1428     GL_DRAW_BUFFER3,
1429     GL_DRAW_BUFFER4,
1430     GL_DRAW_BUFFER5,
1431     GL_DRAW_BUFFER6,
1432     GL_DRAW_BUFFER7,
1433 };
1434
1435
1436 #define NUM_BINDINGS sizeof(bindings)/sizeof(bindings[0])
1437
1438
1439 void dumpCurrentContext(std::ostream &os)
1440 {
1441     JSONWriter json(os);
1442
1443 #ifndef NDEBUG
1444     GLint old_bindings[NUM_BINDINGS];
1445     for (unsigned i = 0; i < NUM_BINDINGS; ++i) {
1446         old_bindings[i] = 0;
1447         glGetIntegerv(bindings[i], &old_bindings[i]);
1448     }
1449 #endif
1450
1451     dumpParameters(json);
1452     dumpShadersUniforms(json);
1453     dumpTextures(json);
1454     dumpFramebuffer(json);
1455
1456 #ifndef NDEBUG
1457     for (unsigned i = 0; i < NUM_BINDINGS; ++i) {
1458         GLint new_binding = 0;
1459         glGetIntegerv(bindings[i], &new_binding);
1460         if (new_binding != old_bindings[i]) {
1461             std::cerr << "warning: " << enumToString(bindings[i]) << " was clobbered\n";
1462         }
1463     }
1464 #endif
1465
1466 }
1467
1468
1469 } /* namespace glstate */