]> git.cworth.org Git - apitrace/blob - glstate.cpp
Return format info for both textures and framebuffers.
[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, %s, %d level",
595                  enumToString(active_texture), enumToString(target), enumToString(format), 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         // Hardcoded for now, but we could chose types more adequate to the
609         // texture internal format
610         json.writeStringMember("__type__", "uint8");
611         json.writeBoolMember("__normalized__", true);
612         json.writeNumberMember("__channels__", 4);
613
614         GLubyte *pixels = new GLubyte[depth*width*height*4];
615
616         resetPixelPackState();
617
618         glGetTexImage(target, level, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
619
620         restorePixelPackState();
621
622         json.beginMember("__data__");
623         char *pngBuffer;
624         int pngBufferSize;
625         image::writePixelsToBuffer(pixels, width, height, 4, true, &pngBuffer, &pngBufferSize);
626         json.writeBase64(pngBuffer, pngBufferSize);
627         free(pngBuffer);
628         json.endMember(); // __data__
629
630         delete [] pixels;
631         json.endObject();
632     }
633 }
634
635
636 static inline void
637 dumpTexture(JSONWriter &json, GLenum target, GLenum binding)
638 {
639     GLint texture_binding = 0;
640     glGetIntegerv(binding, &texture_binding);
641     if (!glIsEnabled(target) && !texture_binding) {
642         return;
643     }
644
645     GLint level = 0;
646     do {
647         GLint width = 0, height = 0;
648         glGetTexLevelParameteriv(target, level, GL_TEXTURE_WIDTH, &width);
649         glGetTexLevelParameteriv(target, level, GL_TEXTURE_HEIGHT, &height);
650         if (!width || !height) {
651             break;
652         }
653
654         if (target == GL_TEXTURE_CUBE_MAP) {
655             for (int face = 0; face < 6; ++face) {
656                 dumpTextureImage(json, GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, level);
657             }
658         } else {
659             dumpTextureImage(json, target, level);
660         }
661
662         ++level;
663     } while(true);
664 }
665
666
667 static inline void
668 dumpTextures(JSONWriter &json)
669 {
670     json.beginMember("textures");
671     json.beginObject();
672     GLint active_texture = GL_TEXTURE0;
673     glGetIntegerv(GL_ACTIVE_TEXTURE, &active_texture);
674     GLint max_texture_coords = 0;
675     glGetIntegerv(GL_MAX_TEXTURE_COORDS, &max_texture_coords);
676     GLint max_combined_texture_image_units = 0;
677     glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &max_combined_texture_image_units);
678     GLint max_units = std::max(max_combined_texture_image_units, max_texture_coords);
679     for (GLint unit = 0; unit < max_units; ++unit) {
680         GLenum texture = GL_TEXTURE0 + unit;
681         glActiveTexture(texture);
682         dumpTexture(json, GL_TEXTURE_1D, GL_TEXTURE_BINDING_1D);
683         dumpTexture(json, GL_TEXTURE_2D, GL_TEXTURE_BINDING_2D);
684         dumpTexture(json, GL_TEXTURE_3D, GL_TEXTURE_BINDING_3D);
685         dumpTexture(json, GL_TEXTURE_RECTANGLE, GL_TEXTURE_BINDING_RECTANGLE);
686         dumpTexture(json, GL_TEXTURE_CUBE_MAP, GL_TEXTURE_BINDING_CUBE_MAP);
687     }
688     glActiveTexture(active_texture);
689     json.endObject();
690     json.endMember(); // textures
691 }
692
693
694 static bool
695 getDrawableBounds(GLint *width, GLint *height) {
696 #if defined(_WIN32)
697
698     HDC hDC = wglGetCurrentDC();
699     if (!hDC) {
700         return false;
701     }
702
703     HWND hWnd = WindowFromDC(hDC);
704     RECT rect;
705
706     if (!GetClientRect(hWnd, &rect)) {
707        return false;
708     }
709
710     *width  = rect.right  - rect.left;
711     *height = rect.bottom - rect.top;
712
713 #elif defined(__APPLE__)
714
715     CGLContextObj ctx = CGLGetCurrentContext();
716     if (ctx == NULL) {
717         return false;
718     }
719
720     CGSConnectionID cid;
721     CGSWindowID wid;
722     CGSSurfaceID sid;
723
724     if (CGLGetSurface(ctx, &cid, &wid, &sid) != kCGLNoError) {
725         return false;
726     }
727
728     CGRect rect;
729
730     if (CGSGetSurfaceBounds(cid, wid, sid, &rect) != 0) {
731         return false;
732     }
733
734     *width = rect.size.width;
735     *height = rect.size.height;
736
737 #else
738
739     Display *display;
740     Drawable drawable;
741     Window root;
742     int x, y;
743     unsigned int w, h, bw, depth;
744
745     display = glXGetCurrentDisplay();
746     if (!display) {
747         return false;
748     }
749
750     drawable = glXGetCurrentDrawable();
751     if (drawable == None) {
752         return false;
753     }
754
755     if (!XGetGeometry(display, drawable, &root, &x, &y, &w, &h, &bw, &depth)) {
756         return false;
757     }
758
759     *width = w;
760     *height = h;
761
762 #endif
763
764     return true;
765 }
766
767
768 static const GLenum texture_bindings[][2] = {
769     {GL_TEXTURE_1D, GL_TEXTURE_BINDING_1D},
770     {GL_TEXTURE_2D, GL_TEXTURE_BINDING_2D},
771     {GL_TEXTURE_3D, GL_TEXTURE_BINDING_3D},
772     {GL_TEXTURE_RECTANGLE, GL_TEXTURE_BINDING_RECTANGLE},
773     {GL_TEXTURE_CUBE_MAP, GL_TEXTURE_BINDING_CUBE_MAP}
774 };
775
776
777 static bool
778 bindTexture(GLint texture, GLenum &target, GLint &bound_texture)
779 {
780
781     for (unsigned i = 0; i < sizeof(texture_bindings)/sizeof(texture_bindings[0]); ++i) {
782         target  = texture_bindings[i][0];
783
784         GLenum binding = texture_bindings[i][1];
785
786         while (glGetError() != GL_NO_ERROR)
787             ;
788
789         glGetIntegerv(binding, &bound_texture);
790         glBindTexture(target, texture);
791
792         if (glGetError() == GL_NO_ERROR) {
793             return true;
794         }
795
796         glBindTexture(target, bound_texture);
797     }
798
799     target = GL_NONE;
800
801     return false;
802 }
803
804
805 static bool
806 getTextureLevelSize(GLint texture, GLint level, GLint *width, GLint *height)
807 {
808     *width = 0;
809     *height = 0;
810
811     GLenum target;
812     GLint bound_texture = 0;
813     if (!bindTexture(texture, target, bound_texture)) {
814         return false;
815     }
816
817     glGetTexLevelParameteriv(target, level, GL_TEXTURE_WIDTH, width);
818     glGetTexLevelParameteriv(target, level, GL_TEXTURE_HEIGHT, height);
819
820     glBindTexture(target, bound_texture);
821
822     return *width > 0 && *height > 0;
823 }
824
825
826 static GLint
827 getTextureLevelFormat(GLint texture, GLint level)
828 {
829     GLenum target;
830     GLint bound_texture = 0;
831     if (!bindTexture(texture, target, bound_texture)) {
832         return GL_NONE;
833     }
834
835     GLint format = GL_NONE;
836     glGetTexLevelParameteriv(target, level, GL_TEXTURE_INTERNAL_FORMAT, &format);
837
838     glBindTexture(target, bound_texture);
839
840     return format;
841 }
842
843
844
845 static bool
846 getRenderbufferSize(GLint renderbuffer, GLint *width, GLint *height)
847 {
848     GLint bound_renderbuffer = 0;
849     glGetIntegerv(GL_RENDERBUFFER_BINDING, &bound_renderbuffer);
850     glBindRenderbuffer(GL_RENDERBUFFER, renderbuffer);
851
852     *width = 0;
853     *height = 0;
854     glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, width);
855     glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, height);
856
857     glBindRenderbuffer(GL_RENDERBUFFER, bound_renderbuffer);
858     
859     return *width > 0 && *height > 0;
860 }
861
862
863 static bool
864 getFramebufferAttachmentSize(GLenum target, GLenum attachment, GLint *width, GLint *height)
865 {
866     GLint object_type = GL_NONE;
867     glGetFramebufferAttachmentParameteriv(target, attachment,
868                                           GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE,
869                                           &object_type);
870     if (object_type == GL_NONE) {
871         return false;
872     }
873
874     GLint object_name = 0;
875     glGetFramebufferAttachmentParameteriv(target, attachment,
876                                           GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME,
877                                           &object_name);
878     if (object_name == 0) {
879         return false;
880     }
881
882     if (object_type == GL_RENDERBUFFER) {
883         return getRenderbufferSize(object_name, width, height);
884     } else if (object_type == GL_TEXTURE) {
885         GLint texture_level = 0;
886         glGetFramebufferAttachmentParameteriv(target, attachment,
887                                               GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL,
888                                               &texture_level);
889         return getTextureLevelSize(object_name, texture_level, width, height);
890     } else {
891         std::cerr << "warning: unexpected GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE = " << object_type << "\n";
892         return false;
893     }
894 }
895
896
897
898 static GLint
899 getFramebufferAttachmentFormat(GLenum target, GLenum attachment)
900 {
901     GLint object_type = GL_NONE;
902     glGetFramebufferAttachmentParameteriv(target, attachment,
903                                           GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE,
904                                           &object_type);
905     if (object_type == GL_NONE) {
906         return GL_NONE;
907     }
908
909     GLint object_name = 0;
910     glGetFramebufferAttachmentParameteriv(target, attachment,
911                                           GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME,
912                                           &object_name);
913     if (object_name == 0) {
914         return GL_NONE;
915     }
916
917     if (object_type == GL_RENDERBUFFER) {
918         GLint format = GL_NONE;
919         glGetRenderbufferParameteriv(object_name, GL_RENDERBUFFER_INTERNAL_FORMAT,
920                                      &format);
921         return format;
922     } else if (object_type == GL_TEXTURE) {
923         GLint texture_level = 0;
924         glGetFramebufferAttachmentParameteriv(target, attachment,
925                                               GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL,
926                                               &texture_level);
927
928         GLint format = getTextureLevelFormat(object_name, texture_level);
929         return format;
930     } else {
931         std::cerr << "warning: unexpected GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE = " << object_type << "\n";
932         return GL_NONE;
933     }
934 }
935
936
937
938 image::Image *
939 getDrawBufferImage(GLenum format) {
940     GLint channels = __gl_format_channels(format);
941     if (channels > 4) {
942         return NULL;
943     }
944
945     GLint draw_framebuffer = 0;
946     glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &draw_framebuffer);
947
948     GLint draw_buffer = GL_NONE;
949     GLint width, height;
950     if (draw_framebuffer) {
951         glGetIntegerv(GL_DRAW_BUFFER0, &draw_buffer);
952         if (draw_buffer == GL_NONE) {
953             return NULL;
954         }
955
956         if (!getFramebufferAttachmentSize(GL_DRAW_FRAMEBUFFER, draw_buffer, &width, &height)) {
957             return NULL;
958         }
959     } else {
960         glGetIntegerv(GL_DRAW_BUFFER, &draw_buffer);
961         if (draw_buffer == GL_NONE) {
962             return NULL;
963         }
964
965         if (!getDrawableBounds(&width, &height)) {
966             return NULL;
967         }
968     }
969
970     image::Image *image = new image::Image(width, height, channels, true);
971     if (!image) {
972         return NULL;
973     }
974
975     while (glGetError() != GL_NO_ERROR) {}
976
977     GLint read_framebuffer = 0;
978     glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &read_framebuffer);
979     glBindFramebuffer(GL_READ_FRAMEBUFFER, draw_framebuffer);
980
981     GLint read_buffer = 0;
982     glGetIntegerv(GL_READ_BUFFER, &read_buffer);
983     glReadBuffer(draw_buffer);
984
985     // TODO: reset imaging state too
986     resetPixelPackState();
987
988     glReadPixels(0, 0, width, height, format, GL_UNSIGNED_BYTE, image->pixels);
989
990     restorePixelPackState();
991     glReadBuffer(read_buffer);
992     glBindFramebuffer(GL_READ_FRAMEBUFFER, read_framebuffer);
993
994     GLenum error = glGetError();
995     if (error != GL_NO_ERROR) {
996         do {
997             std::cerr << "warning: " << enumToString(error) << " while getting snapshot\n";
998             error = glGetError();
999         } while(error != GL_NO_ERROR);
1000         delete image;
1001         return NULL;
1002     }
1003      
1004     return image;
1005 }
1006
1007
1008 /**
1009  * Dump the image of the currently bound read buffer.
1010  */
1011 static inline void
1012 dumpReadBufferImage(JSONWriter &json, GLint width, GLint height, GLenum format)
1013 {
1014     GLint channels = __gl_format_channels(format);
1015
1016     json.beginObject();
1017
1018     // Tell the GUI this is no ordinary object, but an image
1019     json.writeStringMember("__class__", "image");
1020
1021     json.writeNumberMember("__width__", width);
1022     json.writeNumberMember("__height__", height);
1023     json.writeNumberMember("__depth__", 1);
1024
1025     // Hardcoded for now, but we could chose types more adequate to the
1026     // texture internal format
1027     json.writeStringMember("__type__", "uint8");
1028     json.writeBoolMember("__normalized__", true);
1029     json.writeNumberMember("__channels__", channels);
1030
1031     GLubyte *pixels = new GLubyte[width*height*channels];
1032
1033     // TODO: reset imaging state too
1034     resetPixelPackState();
1035
1036     glReadPixels(0, 0, width, height, format, GL_UNSIGNED_BYTE, pixels);
1037
1038     restorePixelPackState();
1039
1040     json.beginMember("__data__");
1041     char *pngBuffer;
1042     int pngBufferSize;
1043     image::writePixelsToBuffer(pixels, width, height, channels, true, &pngBuffer, &pngBufferSize);
1044     //std::cerr <<" Before = "<<(width * height * channels * sizeof *pixels)
1045     //          <<", after = "<<pngBufferSize << ", ratio = " << double(width * height * channels * sizeof *pixels)/pngBufferSize;
1046     json.writeBase64(pngBuffer, pngBufferSize);
1047     free(pngBuffer);
1048     json.endMember(); // __data__
1049
1050     delete [] pixels;
1051     json.endObject();
1052 }
1053
1054
1055 static inline GLuint
1056 downsampledFramebuffer(GLuint oldFbo, GLint drawbuffer,
1057                        GLint colorRb, GLint depthRb, GLint stencilRb,
1058                        GLuint *rbs, GLint *numRbs)
1059 {
1060     GLuint fbo;
1061     GLint format;
1062     GLint w, h;
1063
1064     *numRbs = 0;
1065
1066     glGenFramebuffers(1, &fbo);
1067     glBindFramebuffer(GL_FRAMEBUFFER, fbo);
1068
1069     glBindRenderbuffer(GL_RENDERBUFFER, colorRb);
1070     glGetRenderbufferParameteriv(GL_RENDERBUFFER,
1071                                  GL_RENDERBUFFER_WIDTH, &w);
1072     glGetRenderbufferParameteriv(GL_RENDERBUFFER,
1073                                  GL_RENDERBUFFER_HEIGHT, &h);
1074     glGetRenderbufferParameteriv(GL_RENDERBUFFER,
1075                                  GL_RENDERBUFFER_INTERNAL_FORMAT, &format);
1076
1077     glGenRenderbuffers(1, &rbs[*numRbs]);
1078     glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]);
1079     glRenderbufferStorage(GL_RENDERBUFFER, format, w, h);
1080     glFramebufferRenderbuffer(GL_FRAMEBUFFER, drawbuffer,
1081                               GL_RENDERBUFFER, rbs[*numRbs]);
1082
1083     glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo);
1084     glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
1085     glDrawBuffer(drawbuffer);
1086     glReadBuffer(drawbuffer);
1087     glBlitFramebuffer(0, 0, w, h, 0, 0, w, h,
1088                       GL_COLOR_BUFFER_BIT, GL_NEAREST);
1089     glBindFramebuffer(GL_FRAMEBUFFER, fbo);
1090     ++*numRbs;
1091
1092     if (stencilRb == depthRb && stencilRb) {
1093         //combined depth and stencil buffer
1094         glBindRenderbuffer(GL_RENDERBUFFER, depthRb);
1095         glGetRenderbufferParameteriv(GL_RENDERBUFFER,
1096                                      GL_RENDERBUFFER_WIDTH, &w);
1097         glGetRenderbufferParameteriv(GL_RENDERBUFFER,
1098                                      GL_RENDERBUFFER_HEIGHT, &h);
1099         glGetRenderbufferParameteriv(GL_RENDERBUFFER,
1100                                      GL_RENDERBUFFER_INTERNAL_FORMAT, &format);
1101
1102         glGenRenderbuffers(1, &rbs[*numRbs]);
1103         glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]);
1104         glRenderbufferStorage(GL_RENDERBUFFER, format, w, h);
1105         glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT,
1106                                   GL_RENDERBUFFER, rbs[*numRbs]);
1107         glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo);
1108         glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
1109         glBlitFramebuffer(0, 0, w, h, 0, 0, w, h,
1110                           GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT, GL_NEAREST);
1111         glBindFramebuffer(GL_FRAMEBUFFER, fbo);
1112         ++*numRbs;
1113     } else {
1114         if (depthRb) {
1115             glBindRenderbuffer(GL_RENDERBUFFER, depthRb);
1116             glGetRenderbufferParameteriv(GL_RENDERBUFFER,
1117                                          GL_RENDERBUFFER_WIDTH, &w);
1118             glGetRenderbufferParameteriv(GL_RENDERBUFFER,
1119                                          GL_RENDERBUFFER_HEIGHT, &h);
1120             glGetRenderbufferParameteriv(GL_RENDERBUFFER,
1121                                          GL_RENDERBUFFER_INTERNAL_FORMAT, &format);
1122
1123             glGenRenderbuffers(1, &rbs[*numRbs]);
1124             glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]);
1125             glRenderbufferStorage(GL_RENDERBUFFER, format, w, h);
1126             glFramebufferRenderbuffer(GL_FRAMEBUFFER,
1127                                       GL_DEPTH_ATTACHMENT,
1128                                       GL_RENDERBUFFER, rbs[*numRbs]);
1129             glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo);
1130             glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
1131             glDrawBuffer(GL_DEPTH_ATTACHMENT);
1132             glReadBuffer(GL_DEPTH_ATTACHMENT);
1133             glBlitFramebuffer(0, 0, w, h, 0, 0, w, h,
1134                               GL_DEPTH_BUFFER_BIT, GL_NEAREST);
1135             ++*numRbs;
1136         }
1137         if (stencilRb) {
1138             glBindRenderbuffer(GL_RENDERBUFFER, stencilRb);
1139             glGetRenderbufferParameteriv(GL_RENDERBUFFER,
1140                                          GL_RENDERBUFFER_WIDTH, &w);
1141             glGetRenderbufferParameteriv(GL_RENDERBUFFER,
1142                                          GL_RENDERBUFFER_HEIGHT, &h);
1143             glGetRenderbufferParameteriv(GL_RENDERBUFFER,
1144                                      GL_RENDERBUFFER_INTERNAL_FORMAT, &format);
1145
1146             glGenRenderbuffers(1, &rbs[*numRbs]);
1147             glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]);
1148             glRenderbufferStorage(GL_RENDERBUFFER, format, w, h);
1149             glFramebufferRenderbuffer(GL_FRAMEBUFFER,
1150                                       GL_STENCIL_ATTACHMENT,
1151                                       GL_RENDERBUFFER, rbs[*numRbs]);
1152             glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo);
1153             glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
1154             glDrawBuffer(GL_STENCIL_ATTACHMENT);
1155             glReadBuffer(GL_STENCIL_ATTACHMENT);
1156             glBlitFramebuffer(0, 0, w, h, 0, 0, w, h,
1157                               GL_STENCIL_BUFFER_BIT, GL_NEAREST);
1158             ++*numRbs;
1159         }
1160     }
1161
1162     return fbo;
1163 }
1164
1165
1166 /**
1167  * Dump images of current draw drawable/window.
1168  */
1169 static void
1170 dumpDrawableImages(JSONWriter &json)
1171 {
1172     GLint width, height;
1173
1174     if (!getDrawableBounds(&width, &height)) {
1175         return;
1176     }
1177
1178     GLint draw_buffer = GL_NONE;
1179     glGetIntegerv(GL_DRAW_BUFFER, &draw_buffer);
1180     glReadBuffer(draw_buffer);
1181
1182     if (draw_buffer != GL_NONE) {
1183         GLint read_buffer = GL_NONE;
1184         glGetIntegerv(GL_READ_BUFFER, &read_buffer);
1185
1186         GLint alpha_bits = 0;
1187         glGetIntegerv(GL_ALPHA_BITS, &alpha_bits);
1188         GLenum format = alpha_bits ? GL_RGBA : GL_RGB;
1189         json.beginMember(enumToString(draw_buffer));
1190         dumpReadBufferImage(json, width, height, format);
1191         json.endMember();
1192
1193         glReadBuffer(read_buffer);
1194     }
1195
1196     GLint depth_bits = 0;
1197     glGetIntegerv(GL_DEPTH_BITS, &depth_bits);
1198     if (depth_bits) {
1199         json.beginMember("GL_DEPTH_COMPONENT");
1200         dumpReadBufferImage(json, width, height, GL_DEPTH_COMPONENT);
1201         json.endMember();
1202     }
1203
1204     GLint stencil_bits = 0;
1205     glGetIntegerv(GL_STENCIL_BITS, &stencil_bits);
1206     if (stencil_bits) {
1207         json.beginMember("GL_STENCIL_INDEX");
1208         dumpReadBufferImage(json, width, height, GL_STENCIL_INDEX);
1209         json.endMember();
1210     }
1211 }
1212 /**
1213  * Dump the specified framebuffer attachment.
1214  *
1215  * In the case of a color attachment, it assumes it is already bound for read.
1216  */
1217 static void
1218 dumpFramebufferAttachment(JSONWriter &json, GLenum target, GLenum attachment, GLenum format)
1219 {
1220     GLint width = 0, height = 0;
1221     if (!getFramebufferAttachmentSize(target, attachment, &width, &height)) {
1222         return;
1223     }
1224
1225     GLint internalFormat = getFramebufferAttachmentFormat(target, attachment);
1226     std::stringstream ss;
1227     ss << enumToString(attachment);
1228     if (internalFormat != GL_NONE) {
1229         ss << ", ";
1230         ss << enumToString(internalFormat);
1231     }
1232
1233     json.beginMember(ss.str());
1234     dumpReadBufferImage(json, width, height, format);
1235     json.endMember();
1236 }
1237
1238
1239 static void
1240 dumpFramebufferAttachments(JSONWriter &json, GLenum target)
1241 {
1242     GLint read_framebuffer = 0;
1243     glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &read_framebuffer);
1244
1245     GLint read_buffer = GL_NONE;
1246     glGetIntegerv(GL_READ_BUFFER, &read_buffer);
1247
1248     GLint max_draw_buffers = 1;
1249     glGetIntegerv(GL_MAX_DRAW_BUFFERS, &max_draw_buffers);
1250     GLint max_color_attachments = 0;
1251     glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS, &max_color_attachments);
1252
1253     for (GLint i = 0; i < max_draw_buffers; ++i) {
1254         GLint draw_buffer = GL_NONE;
1255         glGetIntegerv(GL_DRAW_BUFFER0 + i, &draw_buffer);
1256         if (draw_buffer != GL_NONE) {
1257             glReadBuffer(draw_buffer);
1258             GLint attachment;
1259             if (draw_buffer >= GL_COLOR_ATTACHMENT0 && draw_buffer < GL_COLOR_ATTACHMENT0 + max_color_attachments) {
1260                 attachment = draw_buffer;
1261             } else {
1262                 std::cerr << "warning: unexpected GL_DRAW_BUFFER" << i << " = " << draw_buffer << "\n";
1263                 attachment = GL_COLOR_ATTACHMENT0;
1264             }
1265             GLint alpha_size = 0;
1266             glGetFramebufferAttachmentParameteriv(target, attachment,
1267                                                   GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE,
1268                                                   &alpha_size);
1269             GLenum format = alpha_size ? GL_RGBA : GL_RGB;
1270             dumpFramebufferAttachment(json, target, attachment, format);
1271         }
1272     }
1273
1274     glReadBuffer(read_buffer);
1275
1276     dumpFramebufferAttachment(json, target, GL_DEPTH_ATTACHMENT, GL_DEPTH_COMPONENT);
1277     dumpFramebufferAttachment(json, target, GL_STENCIL_ATTACHMENT, GL_STENCIL_INDEX);
1278
1279     glBindFramebuffer(GL_READ_FRAMEBUFFER, read_framebuffer);
1280 }
1281
1282
1283 static void
1284 dumpFramebuffer(JSONWriter &json)
1285 {
1286     json.beginMember("framebuffer");
1287     json.beginObject();
1288
1289     GLint boundDrawFbo = 0, boundReadFbo = 0;
1290     glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &boundDrawFbo);
1291     glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &boundReadFbo);
1292     if (!boundDrawFbo) {
1293         dumpDrawableImages(json);
1294     } else {
1295         GLint colorRb = 0, stencilRb = 0, depthRb = 0;
1296         GLint draw_buffer0 = GL_NONE;
1297         glGetIntegerv(GL_DRAW_BUFFER0, &draw_buffer0);
1298         bool multisample = false;
1299
1300         GLint boundRb = 0;
1301         glGetIntegerv(GL_RENDERBUFFER_BINDING, &boundRb);
1302
1303         GLint object_type;
1304         glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, draw_buffer0, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, &object_type);
1305         if (object_type == GL_RENDERBUFFER) {
1306             glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, draw_buffer0, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, &colorRb);
1307             glBindRenderbuffer(GL_RENDERBUFFER, colorRb);
1308             GLint samples = 0;
1309             glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_SAMPLES, &samples);
1310             if (samples) {
1311                 multisample = true;
1312             }
1313         }
1314
1315         glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, &object_type);
1316         if (object_type == GL_RENDERBUFFER) {
1317             glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, &depthRb);
1318             glBindRenderbuffer(GL_RENDERBUFFER, depthRb);
1319             GLint samples = 0;
1320             glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_SAMPLES, &samples);
1321             if (samples) {
1322                 multisample = true;
1323             }
1324         }
1325
1326         glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, &object_type);
1327         if (object_type == GL_RENDERBUFFER) {
1328             glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, &stencilRb);
1329             glBindRenderbuffer(GL_RENDERBUFFER, stencilRb);
1330             GLint samples = 0;
1331             glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_SAMPLES, &samples);
1332             if (samples) {
1333                 multisample = true;
1334             }
1335         }
1336
1337         glBindRenderbuffer(GL_RENDERBUFFER, boundRb);
1338
1339         GLuint rbs[3];
1340         GLint numRbs = 0;
1341         GLuint fboCopy = 0;
1342
1343         if (multisample) {
1344             // glReadPixels doesnt support multisampled buffers so we need
1345             // to blit the fbo to a temporary one
1346             fboCopy = downsampledFramebuffer(boundDrawFbo, draw_buffer0,
1347                                              colorRb, depthRb, stencilRb,
1348                                              rbs, &numRbs);
1349         }
1350
1351         dumpFramebufferAttachments(json, GL_DRAW_FRAMEBUFFER);
1352
1353         if (multisample) {
1354             glBindRenderbuffer(GL_RENDERBUFFER_BINDING, boundRb);
1355             glDeleteRenderbuffers(numRbs, rbs);
1356             glDeleteFramebuffers(1, &fboCopy);
1357         }
1358
1359         glBindFramebuffer(GL_READ_FRAMEBUFFER, boundReadFbo);
1360         glBindFramebuffer(GL_DRAW_FRAMEBUFFER, boundDrawFbo);
1361     }
1362
1363     json.endObject();
1364     json.endMember(); // framebuffer
1365 }
1366
1367
1368 static const GLenum bindings[] = {
1369     GL_DRAW_BUFFER,
1370     GL_READ_BUFFER,
1371     GL_PIXEL_PACK_BUFFER_BINDING,
1372     GL_PIXEL_UNPACK_BUFFER_BINDING,
1373     GL_TEXTURE_BINDING_1D,
1374     GL_TEXTURE_BINDING_2D,
1375     GL_TEXTURE_BINDING_3D,
1376     GL_TEXTURE_BINDING_RECTANGLE,
1377     GL_TEXTURE_BINDING_CUBE_MAP,
1378     GL_DRAW_FRAMEBUFFER_BINDING,
1379     GL_READ_FRAMEBUFFER_BINDING,
1380     GL_RENDERBUFFER_BINDING,
1381     GL_DRAW_BUFFER0,
1382     GL_DRAW_BUFFER1,
1383     GL_DRAW_BUFFER2,
1384     GL_DRAW_BUFFER3,
1385     GL_DRAW_BUFFER4,
1386     GL_DRAW_BUFFER5,
1387     GL_DRAW_BUFFER6,
1388     GL_DRAW_BUFFER7,
1389 };
1390
1391
1392 #define NUM_BINDINGS sizeof(bindings)/sizeof(bindings[0])
1393
1394
1395 void dumpCurrentContext(std::ostream &os)
1396 {
1397     JSONWriter json(os);
1398
1399 #ifndef NDEBUG
1400     GLint old_bindings[NUM_BINDINGS];
1401     for (unsigned i = 0; i < NUM_BINDINGS; ++i) {
1402         old_bindings[i] = 0;
1403         glGetIntegerv(bindings[i], &old_bindings[i]);
1404     }
1405 #endif
1406
1407     dumpParameters(json);
1408     dumpShadersUniforms(json);
1409     dumpTextures(json);
1410     dumpFramebuffer(json);
1411
1412 #ifndef NDEBUG
1413     for (unsigned i = 0; i < NUM_BINDINGS; ++i) {
1414         GLint new_binding = 0;
1415         glGetIntegerv(bindings[i], &new_binding);
1416         if (new_binding != old_bindings[i]) {
1417             std::cerr << "warning: " << enumToString(bindings[i]) << " was clobbered\n";
1418         }
1419     }
1420 #endif
1421
1422 }
1423
1424
1425 } /* namespace glstate */