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