summaryrefslogtreecommitdiff
path: root/retrace/glstate_images.cpp
blob: 13cddb176bf4f708648de7e9bcb2e9ac9b2e809d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
/**************************************************************************
 *
 * Copyright 2011-2014 Jose Fonseca
 * All Rights Reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 **************************************************************************/


#include <assert.h>
#include <string.h>

#include <algorithm>
#include <iostream>
#include <sstream>

#include "image.hpp"
#include "state_writer.hpp"
#include "glproc.hpp"
#include "glsize.hpp"
#include "glstate.hpp"
#include "glstate_internal.hpp"


#ifdef __linux__
#include <dlfcn.h>
#endif

#ifdef __APPLE__

#include <Carbon/Carbon.h>

#ifdef __cplusplus
extern "C" {
#endif

OSStatus CGSGetSurfaceBounds(CGSConnectionID, CGWindowID, CGSSurfaceID, CGRect *);

#ifdef __cplusplus
}
#endif

#endif /* __APPLE__ */


namespace glstate {


struct ImageDesc
{
    GLint width;
    GLint height;
    GLint depth;
    GLint samples;
    GLint internalFormat;

    inline
    ImageDesc() :
        width(0),
        height(0),
        depth(0),
        samples(0),
        internalFormat(GL_NONE)
    {}

    inline bool
    operator == (const ImageDesc &other) const {
        return width == other.width &&
               height == other.height &&
               depth == other.depth &&
               samples == other.samples &&
               internalFormat == other.internalFormat;
    }

    inline bool
    valid(void) const {
        return width > 0 && height > 0 && depth > 0;
    }
};


static GLenum
getTextureTarget(Context &context, GLuint texture);


/**
 * OpenGL ES does not support glGetTexLevelParameteriv, but it is possible to
 * probe whether a texture has a given size by crafting a dummy glTexSubImage()
 * call.
 */
static bool
probeTextureLevelSizeOES(GLenum target, GLint level, const GLint size[3],
                         GLenum internalFormat, GLenum type)
{
    flushErrors();

    GLint dummy = 0;

    switch (target) {
    case GL_TEXTURE_2D:
    case GL_TEXTURE_CUBE_MAP:
    case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
    case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
    case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
    case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
    case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
    case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
        glTexSubImage2D(target, level, size[0], size[1], 0, 0, internalFormat, type, &dummy);
        break;
    case GL_TEXTURE_3D_OES:
        glTexSubImage3DOES(target, level, size[0], size[1], size[2], 0, 0, 0, internalFormat, type, &dummy);
        break;
    default:
        assert(0);
        return false;
    }

    GLenum error = glGetError();

    if (0) {
        std::cerr << "(" << size[0] << ", " << size[1] << ", " << size[2] << ") = " << enumToString(error) << "\n";
    }

    if (error == GL_NO_ERROR) {
        return true;
    }

    flushErrors();

    return false;
}


static bool
probeTextureFormatOES(GLenum target, GLint level,
                      GLenum *internalFormat, GLenum *type)
{
    static const struct {
        GLenum internalFormat;
        GLenum type;
    } info[] = {
        /* internalFormat */        /* type */
        { GL_RGBA,                  GL_UNSIGNED_BYTE },
        { GL_DEPTH_STENCIL,         GL_FLOAT_32_UNSIGNED_INT_24_8_REV },
        { GL_DEPTH_STENCIL,         GL_UNSIGNED_INT_24_8 },
        { GL_DEPTH_COMPONENT,       GL_FLOAT },
        { GL_DEPTH_COMPONENT,       GL_UNSIGNED_SHORT },
        { GL_STENCIL_INDEX,         GL_UNSIGNED_BYTE },
        /* others? */
        { 0, 0 },
    };
    static const GLint size[3] = {1, 1, 1};

    for (int i = 0; info[i].internalFormat; i++) {
        if (probeTextureLevelSizeOES(target, level, size,
                                     info[i].internalFormat,
                                     info[i].type)) {
            *internalFormat = info[i].internalFormat;
            *type = info[i].type;
            return true;
        }
    }

    return false;
}


/**
 * Bisect the texture size along an axis.
 *
 * It is assumed that the texture exists.
 */
static GLint
bisectTextureLevelSizeOES(GLenum target, GLint level, GLint axis, GLint max,
                          GLenum internalFormat, GLenum type)
{
    GLint size[3] = {0, 0, 0};

    assert(axis < 3);
    assert(max >= 0);

    GLint min = 0;
    while (true) {
        GLint test = (min + max) / 2;
        if (test == min) {
            return min;
        }

        size[axis] = test;

        if (probeTextureLevelSizeOES(target, level, size, internalFormat, type)) {
            min = test;
        } else {
            max = test;
        }
    }
}


/**
 * Special path to obtain texture size on OpenGL ES, that does not rely on
 * glGetTexLevelParameteriv
 */
static bool
getActiveTextureLevelDescOES(Context &context, GLenum target, GLint level, ImageDesc &desc)
{
    if (target == GL_TEXTURE_1D) {
        // OpenGL ES does not support 1D textures
        return false;
    }
    GLenum internalFormat, type;

    if (!probeTextureFormatOES(target, level, &internalFormat, &type)) {
        return false;
    }

    desc.internalFormat = internalFormat;

    GLint maxSize = 0;
    switch (target) {
    case GL_TEXTURE_2D:
        glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maxSize);
        desc.width = bisectTextureLevelSizeOES(target, level, 0, maxSize, internalFormat, type);
        desc.height = bisectTextureLevelSizeOES(target, level, 1, maxSize, internalFormat, type);
        desc.depth = 1;
        break;
    case GL_TEXTURE_CUBE_MAP:
    case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
    case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
    case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
    case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
    case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
    case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
        glGetIntegerv(GL_MAX_CUBE_MAP_TEXTURE_SIZE, &maxSize);
        desc.width = bisectTextureLevelSizeOES(target, level, 0, maxSize, internalFormat, type);
        desc.height = desc.width;
        desc.depth = 1;
        break;
    case GL_TEXTURE_3D_OES:
        glGetIntegerv(GL_MAX_3D_TEXTURE_SIZE_OES, &maxSize);
        desc.width = bisectTextureLevelSizeOES(target, level, 0, maxSize, internalFormat, type);
        desc.width = bisectTextureLevelSizeOES(target, level, 1, maxSize, internalFormat, type);
        desc.depth = bisectTextureLevelSizeOES(target, level, 2, maxSize, internalFormat, type);
        break;
    default:
        return false;
    }

    if (0) {
        std::cerr
            << enumToString(target) << " "
            << level << " "
            << desc.width << "x" << desc.height << "x" << desc.depth
            << "\n";
    }

    return desc.valid();
}


static inline bool
getActiveTextureLevelDesc(Context &context, GLenum target, GLint level, ImageDesc &desc)
{
    assert(target != GL_TEXTURE_CUBE_MAP);

    if (context.ES) {
        return getActiveTextureLevelDescOES(context, target, level, desc);
    }

    if (target == GL_TEXTURE_BUFFER) {
        assert(level == 0);

        GLint buffer = 0;
        glGetIntegerv(GL_TEXTURE_BUFFER_DATA_STORE_BINDING, &buffer);
        if (!buffer) {
            return false;
        }

        // This is the general binding point, not the texture's
        GLint active_buffer = 0;
        glGetIntegerv(GL_TEXTURE_BUFFER, &active_buffer);
        glBindBuffer(GL_TEXTURE_BUFFER, buffer);

        GLint buffer_size = 0;
        glGetBufferParameteriv(GL_TEXTURE_BUFFER, GL_BUFFER_SIZE, &buffer_size);
        
        glBindBuffer(GL_TEXTURE_BUFFER, active_buffer);

        glGetIntegerv(GL_TEXTURE_BUFFER_FORMAT_ARB, &desc.internalFormat);

        const InternalFormatDesc &formatDesc = getInternalFormatDesc(desc.internalFormat);
        if (formatDesc.type == GL_NONE) {
            std::cerr << "error: unexpected GL_TEXTURE_BUFFER internal format "
                      << enumToString(desc.internalFormat)
                      << " (https://github.com/apitrace/apitrace/issues/426)\n";
            return false;
        }

        unsigned bits_per_pixel = _gl_format_size(formatDesc.format, formatDesc.type);

        desc.width = buffer_size * 8 / bits_per_pixel;
        desc.height = 1;
        desc.depth = 1;

        return desc.valid();
    }

    glGetTexLevelParameteriv(target, level, GL_TEXTURE_INTERNAL_FORMAT, &desc.internalFormat);

    desc.width = 0;
    glGetTexLevelParameteriv(target, level, GL_TEXTURE_WIDTH, &desc.width);

    if (target == GL_TEXTURE_BUFFER ||
        target == GL_TEXTURE_1D) {
        desc.height = 1;
        desc.depth = 1;
    } else {
        desc.height = 0;
        glGetTexLevelParameteriv(target, level, GL_TEXTURE_HEIGHT, &desc.height);
        if (target != GL_TEXTURE_3D &&
            target != GL_TEXTURE_2D_ARRAY &&
            target != GL_TEXTURE_2D_MULTISAMPLE_ARRAY &&
            target != GL_TEXTURE_CUBE_MAP_ARRAY) {
            desc.depth = 1;
        } else {
            desc.depth = 0;
            glGetTexLevelParameteriv(target, level, GL_TEXTURE_DEPTH, &desc.depth);
        }
    }

    glGetTexLevelParameteriv(target, level, GL_TEXTURE_SAMPLES, &desc.samples);

    return desc.valid();
}


const GLenum
textureTargets[] = {
    GL_TEXTURE_2D,
    GL_TEXTURE_1D,
    GL_TEXTURE_RECTANGLE,
    GL_TEXTURE_CUBE_MAP,
    GL_TEXTURE_3D,
    GL_TEXTURE_2D_MULTISAMPLE,
    GL_TEXTURE_2D_ARRAY,
    GL_TEXTURE_2D_MULTISAMPLE_ARRAY,
    GL_TEXTURE_1D_ARRAY,
    GL_TEXTURE_CUBE_MAP_ARRAY,
    GL_TEXTURE_BUFFER,
};

const unsigned
numTextureTargets = ARRAYSIZE(textureTargets);


GLenum
getTextureBinding(GLenum target)
{
    switch (target) {
    case GL_TEXTURE_1D:
        return GL_TEXTURE_BINDING_1D;
    case GL_TEXTURE_1D_ARRAY:
        return GL_TEXTURE_BINDING_1D_ARRAY;
    case GL_TEXTURE_2D:
        return GL_TEXTURE_BINDING_2D;
    case GL_TEXTURE_2D_ARRAY:
        return GL_TEXTURE_BINDING_2D_ARRAY;
    case GL_TEXTURE_2D_MULTISAMPLE:
        return GL_TEXTURE_BINDING_2D_MULTISAMPLE;
    case GL_TEXTURE_2D_MULTISAMPLE_ARRAY:
        return GL_TEXTURE_BINDING_2D_MULTISAMPLE_ARRAY;
    case GL_TEXTURE_RECTANGLE:
        return GL_TEXTURE_BINDING_RECTANGLE;
    case GL_TEXTURE_CUBE_MAP:
    case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
    case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
    case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
    case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
    case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
    case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
        return GL_TEXTURE_BINDING_CUBE_MAP;
    case GL_TEXTURE_CUBE_MAP_ARRAY:
        return GL_TEXTURE_BINDING_CUBE_MAP_ARRAY;
    case GL_TEXTURE_3D:
        return GL_TEXTURE_BINDING_3D;
    case GL_TEXTURE_BUFFER:
        return GL_TEXTURE_BINDING_BUFFER;
    default:
        assert(false);
        return GL_NONE;
    }
}


/**
 * OpenGL ES does not support glGetTexImage. Obtain the pixels by attaching the
 * texture to a framebuffer.
 */
static inline void
getTexImageOES(GLenum target, GLint level, GLenum format, GLenum type,
               ImageDesc &desc, GLubyte *pixels)
{
    memset(pixels, 0x80, desc.height * desc.width * 4);

    GLenum texture_binding = getTextureBinding(target);
    if (texture_binding == GL_NONE) {
        return;
    }

    GLint texture = 0;
    glGetIntegerv(texture_binding, &texture);
    if (!texture) {
        return;
    }

    GLint prev_fbo = 0;
    GLuint fbo = 0;
    glGetIntegerv(GL_FRAMEBUFFER_BINDING, &prev_fbo);
    glGenFramebuffers(1, &fbo);
    glBindFramebuffer(GL_FRAMEBUFFER, fbo);

    GLenum status;

    switch (target) {
    case GL_TEXTURE_2D:
    case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
    case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
    case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
    case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
    case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
    case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture, level);
        status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
        if (status != GL_FRAMEBUFFER_COMPLETE) {
            std::cerr << __FUNCTION__ << ": " << enumToString(status) << "\n";
        }
        glReadPixels(0, 0, desc.width, desc.height, format, type, pixels);
        break;
    case GL_TEXTURE_3D_OES:
        for (int i = 0; i < desc.depth; i++) {
            glFramebufferTexture3D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_3D, texture, level, i);
            glReadPixels(0, 0, desc.width, desc.height, format, type, pixels + 4 * i * desc.width * desc.height);
        }
        break;
    }

    glBindFramebuffer(GL_FRAMEBUFFER, prev_fbo);

    glDeleteFramebuffers(1, &fbo);
}


static inline void
dumpActiveTextureLevel(StateWriter &writer, Context &context,
                       GLenum target, GLint level,
                       const std::string & label,
                       const char *userLabel)
{
    ImageDesc desc;
    if (!getActiveTextureLevelDesc(context, target, level, desc)) {
        return;
    }

    const InternalFormatDesc &formatDesc = getInternalFormatDesc(desc.internalFormat);

    GLenum format;
    GLenum type;
    const PixelFormat *pixelFormat = nullptr;

    if (target == GL_TEXTURE_BUFFER) {
        pixelFormat = getPixelFormat(desc.internalFormat);
        if (!pixelFormat) {
            std::cerr << "warning: unsupported texture buffer internal format " << formatToString(desc.internalFormat) << "\n";
            return;
        }
        format = GL_RGBA;
        type = GL_FLOAT;
    } else {
        chooseReadBackFormat(formatDesc, format, type);
    }

    writer.beginMember(label);

    if (context.ES && format == GL_DEPTH_COMPONENT) {
        format = GL_RED;
    }

    GLuint channels;
    image::ChannelType channelType;
    getImageFormat(format, type, channels, channelType);

    if (0) {
        std::cerr << enumToString(desc.internalFormat) << " "
                  << enumToString(format) << " "
                  << enumToString(type) << "\n";
    }

    image::Image *image = new image::Image(desc.width, desc.height*desc.depth, channels, true, channelType);

    PixelPackState pps(context);

    if (target == GL_TEXTURE_BUFFER) {
        assert(desc.height == 1);
        assert(desc.depth == 1);
        assert(pixelFormat);
        assert(format == GL_RGBA);
        assert(type == GL_FLOAT);
        assert(image->bytesPerPixel == sizeof(float[4]));

        GLint buffer = 0;
        glGetIntegerv(GL_TEXTURE_BUFFER_DATA_STORE_BINDING, &buffer);
        assert(buffer);

        BufferMapping bm;

        const GLvoid *map = bm.map(GL_TEXTURE_BUFFER, buffer);
        if (map) {
            pixelFormat->unpackSpan(static_cast<const uint8_t *>(map),
                                    reinterpret_cast<float *>(image->pixels), image->width);
        }
    } else {
        if (context.ES) {
            getTexImageOES(target, level, format, type, desc, image->pixels);
        } else {
            glGetTexImage(target, level, format, type, image->pixels);
        }
    }

    if (userLabel) {
        image->label = userLabel;
    }

    StateWriter::ImageDesc imageDesc;
    imageDesc.depth = desc.depth;
    imageDesc.format = formatToString(desc.internalFormat);
    writer.writeImage(image, imageDesc);

    delete image;

    writer.endMember(); // label
}


static inline void
dumpActiveTexture(StateWriter &writer, Context &context, GLenum target, GLuint texture)
{
    char *object_label = getObjectLabel(context, GL_TEXTURE, texture);

    GLint active_texture = GL_TEXTURE0;
    glGetIntegerv(GL_ACTIVE_TEXTURE, &active_texture);
    assert(active_texture >= GL_TEXTURE0);

    GLenum start_subtarget;
    GLenum stop_subtarget;
    if (target == GL_TEXTURE_CUBE_MAP) {
        start_subtarget = GL_TEXTURE_CUBE_MAP_POSITIVE_X;
        stop_subtarget = start_subtarget + 6;
    } else {
        start_subtarget = target;
        stop_subtarget = start_subtarget + 1;
    }

    GLboolean allowMipmaps = target != GL_TEXTURE_RECTANGLE &&
                             target != GL_TEXTURE_BUFFER;

    GLint level = 0;
    do {
        ImageDesc desc;

        for (GLenum subtarget = start_subtarget; subtarget < stop_subtarget; ++subtarget) {
            std::stringstream label;
            label << "GL_TEXTURE" << (active_texture - GL_TEXTURE0) << ", "
                  << enumToString(subtarget);
            if (allowMipmaps) {
                label << ", level = " << level;
            }

            if (!getActiveTextureLevelDesc(context, subtarget, level, desc)) {
                goto finished;
            }
            dumpActiveTextureLevel(writer, context, subtarget, level, label.str(), object_label);
        }

        if (!allowMipmaps) {
            // no mipmaps
            break;
        }

        ++level;
    } while(true);

finished:
    free(object_label);
}

static void
dumpTextureImages(StateWriter &writer, Context &context)
{
    if (!context.ARB_shader_image_load_store) {
        return;
    }

    GLint maxImageUnits = 0;
    glGetIntegerv(GL_MAX_IMAGE_UNITS, &maxImageUnits);
    glMemoryBarrier(GL_TEXTURE_UPDATE_BARRIER_BIT);

    for (GLint imageUnit = 0; imageUnit < maxImageUnits; ++imageUnit) {
        GLint texture = 0;
        glGetIntegeri_v(GL_IMAGE_BINDING_NAME, imageUnit, &texture);
        if (texture) {
            GLint level = 0;
            glGetIntegeri_v(GL_IMAGE_BINDING_LEVEL, imageUnit, &level);
            GLint isLayered = 0;
            glGetIntegeri_v(GL_IMAGE_BINDING_LAYERED, imageUnit, &isLayered);
            GLint layer = 0;
            glGetIntegeri_v(GL_IMAGE_BINDING_LAYER, imageUnit, &layer);
            std::stringstream label;
            label << "Image Unit " << imageUnit;
            if (level) {
                label << ", level = " << level;
            }
            if (isLayered) {
                label << ", layer = " << layer;
            }
            GLenum target = getTextureTarget(context, texture);
            GLint previousTexture = 0;
            glGetIntegerv(getTextureBinding(target), &previousTexture);

            glBindTexture(target, texture);
            char *object_label = getObjectLabel(context, GL_TEXTURE, texture);
            dumpActiveTextureLevel(writer, context, target, level, label.str(),
                                   object_label);
            free(object_label);
            glBindTexture(target, previousTexture);
        }
    }
}


void
dumpTextures(StateWriter &writer, Context &context)
{
    writer.beginMember("textures");
    writer.beginObject();

    GLint max_texture_coords = 0;
    if (!context.core) {
        glGetIntegerv(GL_MAX_TEXTURE_COORDS, &max_texture_coords);
    }

    GLint max_combined_texture_image_units = 0;
    glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &max_combined_texture_image_units);

    /*
     * At least the Android software GL implementation doesn't return the
     * proper value for this, but rather returns 0. The GL(ES) specification
     * mandates a minimum value of 2, so use this as a fall-back value.
     */
    max_combined_texture_image_units = std::max(max_combined_texture_image_units, 2);

    GLint max_units = std::max(max_combined_texture_image_units, max_texture_coords);

    GLint active_texture = GL_TEXTURE0;
    glGetIntegerv(GL_ACTIVE_TEXTURE, &active_texture);

    for (GLint unit = 0; unit < max_units; ++unit) {
        GLenum texture = GL_TEXTURE0 + unit;
        glActiveTexture(texture);

        for (auto target : textureTargets) {

            // Whether this fixed-function stage is enabled
            GLboolean enabled = GL_FALSE;
            if (unit < max_texture_coords &&
                (target == GL_TEXTURE_1D ||
                 target == GL_TEXTURE_2D ||
                 target == GL_TEXTURE_3D ||
                 target == GL_TEXTURE_CUBE_MAP ||
                 target == GL_TEXTURE_RECTANGLE)) {
                glGetBooleanv(target, &enabled);
            }

            // Whether a texture object is bound
            GLint texture = 0;
            if (unit < max_combined_texture_image_units) {
                GLenum binding = getTextureBinding(target);
                glGetIntegerv(binding, &texture);
            }

            if (enabled || texture) {
                dumpActiveTexture(writer, context, target, texture);
            }
        }
    }

    glActiveTexture(active_texture);

    dumpTextureImages(writer, context);

    writer.endObject();
    writer.endMember(); // textures
}


bool
getDrawableBounds(GLint *width, GLint *height) {
#if defined(__linux__)
    if (_getPublicProcAddress("eglGetCurrentContext")) {
        EGLContext currentContext = eglGetCurrentContext();
        if (currentContext != EGL_NO_CONTEXT) {
            EGLSurface currentSurface = eglGetCurrentSurface(EGL_DRAW);
            if (currentSurface == EGL_NO_SURFACE) {
                return false;
            }

            EGLDisplay currentDisplay = eglGetCurrentDisplay();
            if (currentDisplay == EGL_NO_DISPLAY) {
                return false;
            }

            if (!eglQuerySurface(currentDisplay, currentSurface, EGL_WIDTH, width) ||
                !eglQuerySurface(currentDisplay, currentSurface, EGL_HEIGHT, height)) {
                return false;
            }

            return true;
        }
    }
#endif

#if defined(_WIN32)

    HDC hDC = wglGetCurrentDC();
    if (!hDC) {
        return false;
    }

    HWND hWnd = WindowFromDC(hDC);
    RECT rect;

    if (!GetClientRect(hWnd, &rect)) {
       return false;
    }

    *width  = rect.right  - rect.left;
    *height = rect.bottom - rect.top;
    return true;

#elif defined(__APPLE__)

    CGLContextObj ctx = CGLGetCurrentContext();
    if (ctx == NULL) {
        return false;
    }

    CGSConnectionID cid;
    CGSWindowID wid;
    CGSSurfaceID sid;

    if (CGLGetSurface(ctx, &cid, &wid, &sid) != kCGLNoError) {
        return false;
    }

    CGRect rect;

    if (CGSGetSurfaceBounds(cid, wid, sid, &rect) != 0) {
        return false;
    }

    *width = rect.size.width;
    *height = rect.size.height;
    return true;

#elif defined(HAVE_X11)

    Display *display;
    GLXDrawable drawable;

    display = glXGetCurrentDisplay();
    if (!display) {
        return false;
    }

    drawable = glXGetCurrentDrawable();
    if (drawable == None) {
        return false;
    }

    // XGetGeometry will fail for PBuffers, whereas glXQueryDrawable should not.
    unsigned int w = 0;
    unsigned int h = 0;
    glXQueryDrawable(display, drawable, GLX_WIDTH, &w);
    glXQueryDrawable(display, drawable, GLX_HEIGHT, &h);

    *width = w;
    *height = h;
    return true;

#else

    return false;

#endif
}


static GLenum
getTextureTarget(Context &context, GLuint texture)
{
    if (!glIsTexture(texture)) {
        return GL_NONE;
    }

    /*
     * GL_ARB_direct_state_access's glGetTextureParameteriv(GL_TEXTURE_TARGET)
     * would be perfect, except the fact it's not supported for
     * TEXTURE_BUFFERS...
     */

    GLint result = GL_NONE;

    flushErrors();

    // Temporarily disable debug messages
    GLDEBUGPROC prevDebugCallbackFunction = 0;
    void *prevDebugCallbackUserParam = 0;
    if (context.KHR_debug) {
        glGetPointerv(GL_DEBUG_CALLBACK_FUNCTION, (GLvoid **) &prevDebugCallbackFunction);
        glGetPointerv(GL_DEBUG_CALLBACK_USER_PARAM, &prevDebugCallbackUserParam);
        glDebugMessageCallback(NULL, NULL);
    }

    for (auto target : textureTargets) {
        GLenum binding = getTextureBinding(target);

        GLint bound_texture = 0;
        glGetIntegerv(binding, &bound_texture);
        glBindTexture(target, texture);

        bool succeeded = glGetError() == GL_NO_ERROR;

        glBindTexture(target, bound_texture);

        if (succeeded) {
            result = target;
            break;
        }

        flushErrors();
    }

    if (context.KHR_debug) {
        glDebugMessageCallback(prevDebugCallbackFunction, prevDebugCallbackUserParam);
    }

    return result;
}


static bool
getBoundRenderbufferDesc(Context &context, ImageDesc &desc)
{
    glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &desc.width);
    glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &desc.height);
    desc.depth = 1;
    
    glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_SAMPLES, &desc.samples);

    glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_INTERNAL_FORMAT, &desc.internalFormat);
    
    return desc.valid();
}


static bool
getRenderbufferDesc(Context &context, GLint renderbuffer, ImageDesc &desc)
{
    GLint bound_renderbuffer = 0;
    glGetIntegerv(GL_RENDERBUFFER_BINDING, &bound_renderbuffer);
    glBindRenderbuffer(GL_RENDERBUFFER, renderbuffer);

    getBoundRenderbufferDesc(context, desc);

    glBindRenderbuffer(GL_RENDERBUFFER, bound_renderbuffer);
    
    return desc.valid();
}


static bool
getFramebufferAttachmentDesc(Context &context, GLenum target, GLenum attachment, ImageDesc &desc)
{
    GLint object_type = GL_NONE;
    glGetFramebufferAttachmentParameteriv(target, attachment,
                                          GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE,
                                          &object_type);
    if (object_type == GL_NONE) {
        return false;
    }

    GLint object_name = 0;
    glGetFramebufferAttachmentParameteriv(target, attachment,
                                          GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME,
                                          &object_name);
    if (object_name == 0) {
        return false;
    }

    if (object_type == GL_RENDERBUFFER) {
        return getRenderbufferDesc(context, object_name, desc);
    } else if (object_type == GL_TEXTURE) {
        GLint texture_face = 0;
        glGetFramebufferAttachmentParameteriv(target, attachment,
                                              GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE,
                                              &texture_face);

        GLint texture_level = 0;
        glGetFramebufferAttachmentParameteriv(target, attachment,
                                              GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL,
                                              &texture_level);

        GLint bound_texture = 0;
        if (texture_face != 0) {
            glGetIntegerv(GL_TEXTURE_BINDING_CUBE_MAP, &bound_texture);
            glBindTexture(GL_TEXTURE_CUBE_MAP, object_name);
            getActiveTextureLevelDesc(context, texture_face, texture_level, desc);
            glBindTexture(GL_TEXTURE_CUBE_MAP, bound_texture);
        } else {
            GLenum texture_target = getTextureTarget(context, object_name);
            GLenum texture_binding = getTextureBinding(texture_target);
            glGetIntegerv(texture_binding, &bound_texture);
            glBindTexture(texture_target, object_name);
            getActiveTextureLevelDesc(context, texture_target, texture_level, desc);
            glBindTexture(texture_target, bound_texture);
        }

        return desc.valid();
    } else {
        std::cerr << "warning: unexpected GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE = " << enumToString(object_type) << "\n";
        return false;
    }
}



image::Image *
getDrawBufferImage()
{
    Context context;

    GLenum framebuffer_binding;
    GLenum framebuffer_target;
    if (context.read_framebuffer_object) {
        framebuffer_binding = GL_DRAW_FRAMEBUFFER_BINDING;
        framebuffer_target = GL_DRAW_FRAMEBUFFER;
    } else {
        framebuffer_binding = GL_FRAMEBUFFER_BINDING;
        framebuffer_target = GL_FRAMEBUFFER;
    }
    GLint draw_framebuffer = 0;
    if (context.framebuffer_object) {
        glGetIntegerv(framebuffer_binding, &draw_framebuffer);
    }

    GLint draw_buffer = GL_NONE;
    ImageDesc desc;
    if (draw_framebuffer) {
        if (context.ARB_draw_buffers) {
            glGetIntegerv(GL_DRAW_BUFFER0, &draw_buffer);
            if (draw_buffer == GL_NONE) {
                return NULL;
            }
        } else {
            // GL_COLOR_ATTACHMENT0 is implied
            draw_buffer = GL_COLOR_ATTACHMENT0;
        }

        if (!getFramebufferAttachmentDesc(context, framebuffer_target, draw_buffer, desc)) {
            return NULL;
        }
    } else {
        if (context.ES) {
            // XXX: Draw buffer is always FRONT for single buffer context, BACK
            // for double buffered contexts. There is no way to know which (as
            // GL_DOUBLEBUFFER state is also unavailable), so always assume
            // double-buffering.
            draw_buffer = GL_BACK;
        } else {
            glGetIntegerv(GL_DRAW_BUFFER, &draw_buffer);
            if (draw_buffer == GL_NONE) {
                return NULL;
            }
        }

        if (!getDrawableBounds(&desc.width, &desc.height)) {
            return NULL;
        }

        desc.depth = 1;
    }

    GLenum format = GL_RGB;
    GLenum type = GL_UNSIGNED_BYTE;
    if (context.ES) {
        format = GL_RGBA;
    }

    GLint channels = _gl_format_channels(format);
    if (channels > 4) {
        return NULL;
    }

    image::ChannelType channelType = image::TYPE_UNORM8;

    if (format == GL_DEPTH_COMPONENT) {
        type = GL_FLOAT;
        channels = 1;
        channelType = image::TYPE_FLOAT;
    }

    image::Image *image = new image::Image(desc.width, desc.height, channels, true, channelType);
    if (!image) {
        return NULL;
    }

    flushErrors();

    GLint read_framebuffer = 0;
    GLint read_buffer = GL_NONE;
    if (context.read_framebuffer_object) {
        glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &read_framebuffer);
        glBindFramebuffer(GL_READ_FRAMEBUFFER, draw_framebuffer);
    }

    if (context.read_buffer) {
        glGetIntegerv(GL_READ_BUFFER, &read_buffer);
        glReadBuffer(draw_buffer);
    }

    {
        // TODO: reset imaging state too
        PixelPackState pps(context);
        glReadPixels(0, 0, desc.width, desc.height, format, type, image->pixels);
    }


    if (context.read_buffer) {
        glReadBuffer(read_buffer);
    }
    if (context.read_framebuffer_object) {
        glBindFramebuffer(GL_READ_FRAMEBUFFER, read_framebuffer);
    }

    GLenum error = glGetError();
    if (error != GL_NO_ERROR) {
        do {
            std::cerr << "warning: " << enumToString(error) << " while getting snapshot\n";
            error = glGetError();
        } while(error != GL_NO_ERROR);
        delete image;
        return NULL;
    }
     
    return image;
}


/**
 * Dump the image of the currently bound read buffer.
 */
static inline void
dumpReadBufferImage(StateWriter &writer,
                    Context & context,
                    const char *label,
                    const char *userLabel,
                    GLint width, GLint height,
                    GLenum format, GLenum type,
                    GLenum internalFormat = GL_NONE)
{
    if (internalFormat == GL_NONE) {
        internalFormat = format;
    }

    if (context.ES) {
        switch (format) {
        case GL_DEPTH_COMPONENT:
        case GL_DEPTH_STENCIL:
            if (!context.NV_read_depth_stencil) {
                return;
            }
            /* FIXME: NV_read_depth_stencil states that type must match the
             * internal format, whereas we always request GL_FLOAT, as that's
             * what we want.  To fix this we should probe the adequate type
             * here, and then manually convert the pixels to float after
             * glReadPixels */
            break;
        case GL_STENCIL_INDEX:
            if (!context.NV_read_depth_stencil) {
                return;
            }
            type = GL_UNSIGNED_BYTE;
            break;
        default:
            // Color formats -- GLES glReadPixels only supports the following combinations:
            // - GL_RGBA and GL_UNSIGNED_BYTE
            // - values of IMPLEMENTATION_COLOR_READ_FORMAT and IMPLEMENTATION_COLOR_READ_TYPE
            format = GL_RGBA;
            type = GL_UNSIGNED_BYTE;
            break;
        }
    }

    GLuint channels;
    image::ChannelType channelType;
    getImageFormat(format, type, channels, channelType);

    if (0) {
        std::cerr << enumToString(internalFormat) << " "
                  << enumToString(format) << " "
                  << enumToString(type) << "\n";
    }

    image::Image *image = new image::Image(width, height, channels, true, channelType);

    flushErrors();

    {
        // TODO: reset imaging state too
        PixelPackState pps(context);

        glReadPixels(0, 0, width, height, format, type, image->pixels);
    }

    GLenum error = glGetError();
    if (error != GL_NO_ERROR) {
        do {
            std::cerr << "warning: " << enumToString(error) << " while reading framebuffer\n";
            error = glGetError();
        } while(error != GL_NO_ERROR);
    } else {
        if (userLabel) {
            image->label = userLabel;
        }

        StateWriter::ImageDesc imageDesc;
        imageDesc.format = formatToString(internalFormat);
        writer.beginMember(label);
        writer.writeImage(image, imageDesc);
        writer.endMember();
    }

    delete image;
}


static inline GLuint
downsampledFramebuffer(Context &context,
                       GLuint oldFbo, GLint drawbuffer,
                       const ImageDesc &colorDesc,
                       const ImageDesc &depthDesc,
                       const ImageDesc &stencilDesc,
                       GLuint *rbs, GLint *numRbs)
{
    GLuint fbo;

    *numRbs = 0;

    glGenFramebuffers(1, &fbo);
    glBindFramebuffer(GL_FRAMEBUFFER, fbo);

    GLboolean scissor_test = glIsEnabled(GL_SCISSOR_TEST);
    if (scissor_test) {
        glDisable(GL_SCISSOR_TEST);
    }

    {
        // color buffer
        glGenRenderbuffers(1, &rbs[*numRbs]);
        glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]);
        glRenderbufferStorage(GL_RENDERBUFFER, colorDesc.internalFormat, colorDesc.width, colorDesc.height);
        glFramebufferRenderbuffer(GL_FRAMEBUFFER, drawbuffer,
                                  GL_RENDERBUFFER, rbs[*numRbs]);

        glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo);
        glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
        glDrawBuffer(drawbuffer);
        glReadBuffer(drawbuffer);
        glBlitFramebuffer(0, 0, colorDesc.width, colorDesc.height, 0, 0, colorDesc.width, colorDesc.height,
                          GL_COLOR_BUFFER_BIT, GL_NEAREST);
        glBindFramebuffer(GL_FRAMEBUFFER, fbo);
        ++*numRbs;
    }

    if (stencilDesc == depthDesc &&
        depthDesc.valid()) {
        //combined depth and stencil buffer
        glGenRenderbuffers(1, &rbs[*numRbs]);
        glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]);
        glRenderbufferStorage(GL_RENDERBUFFER, depthDesc.internalFormat, depthDesc.width, depthDesc.height);
        glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT,
                                  GL_RENDERBUFFER, rbs[*numRbs]);
        glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo);
        glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
        glDrawBuffer(drawbuffer);
        glReadBuffer(drawbuffer);
        glBlitFramebuffer(0, 0, depthDesc.width, depthDesc.height, 0, 0, depthDesc.width, depthDesc.height,
                          GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT, GL_NEAREST);
        glBindFramebuffer(GL_FRAMEBUFFER, fbo);
        ++*numRbs;
    } else {
        if (depthDesc.valid()) {
            glGenRenderbuffers(1, &rbs[*numRbs]);
            glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]);
            glRenderbufferStorage(GL_RENDERBUFFER, depthDesc.internalFormat, depthDesc.width, depthDesc.height);
            glFramebufferRenderbuffer(GL_FRAMEBUFFER,
                                      GL_DEPTH_ATTACHMENT,
                                      GL_RENDERBUFFER, rbs[*numRbs]);
            glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo);
            glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
            glDrawBuffer(drawbuffer);
            glReadBuffer(drawbuffer);
            glBlitFramebuffer(0, 0, depthDesc.width, depthDesc.height, 0, 0, depthDesc.width, depthDesc.height,
                              GL_DEPTH_BUFFER_BIT, GL_NEAREST);
            glBindFramebuffer(GL_FRAMEBUFFER, fbo);
            ++*numRbs;
        }
        if (stencilDesc.valid()) {
            glGenRenderbuffers(1, &rbs[*numRbs]);
            glBindRenderbuffer(GL_RENDERBUFFER, rbs[*numRbs]);
            glRenderbufferStorage(GL_RENDERBUFFER, stencilDesc.internalFormat, stencilDesc.width, stencilDesc.height);
            glFramebufferRenderbuffer(GL_FRAMEBUFFER,
                                      GL_STENCIL_ATTACHMENT,
                                      GL_RENDERBUFFER, rbs[*numRbs]);
            glBindFramebuffer(GL_READ_FRAMEBUFFER, oldFbo);
            glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
            glDrawBuffer(drawbuffer);
            glReadBuffer(drawbuffer);
            glBlitFramebuffer(0, 0, stencilDesc.width, stencilDesc.height, 0, 0, stencilDesc.width, stencilDesc.height,
                              GL_STENCIL_BUFFER_BIT, GL_NEAREST);
            glBindFramebuffer(GL_FRAMEBUFFER, fbo);
            ++*numRbs;
        }
    }

    if (scissor_test) {
        glEnable(GL_SCISSOR_TEST);
    }

    return fbo;
}


/**
 * Dump images of current draw drawable/window.
 */
static void
dumpDrawableImages(StateWriter &writer, Context &context)
{
    GLint width, height;

    if (!getDrawableBounds(&width, &height)) {
        return;
    }

    GLint draw_buffer = GL_NONE;
    if (context.ES) {
        // XXX: Draw buffer is always FRONT for single buffer context, BACK for
        // double buffered contexts. There is no way to know which (as
        // GL_DOUBLEBUFFER state is also unavailable), so always assume
        // double-buffering.
        draw_buffer = GL_BACK;
    } else {
        glGetIntegerv(GL_DRAW_BUFFER, &draw_buffer);
    }

    // Reset read framebuffer
    GLint read_framebuffer = 0;
    if (context.read_framebuffer_object) {
        glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &read_framebuffer);
        glBindFramebuffer(GL_READ_FRAMEBUFFER, 0);
    } else if (context.framebuffer_object) {
        glGetIntegerv(GL_FRAMEBUFFER_BINDING, &read_framebuffer);
        glBindFramebuffer(GL_FRAMEBUFFER, 0);
    }

    if (draw_buffer != GL_NONE) {
        // Read from current draw buffer
        GLint read_buffer = GL_NONE;
        if (context.read_buffer) {
            glGetIntegerv(GL_READ_BUFFER, &read_buffer);
            glReadBuffer(draw_buffer);
        }

        GLint alpha_bits = 0;
#if 0
        // XXX: Ignore alpha until we are able to match the traced visual
        glGetIntegerv(GL_ALPHA_BITS, &alpha_bits);
#endif
        GLenum format = alpha_bits ? GL_RGBA : GL_RGB;
        GLenum type = GL_UNSIGNED_BYTE;

        dumpReadBufferImage(writer, context, enumToString(draw_buffer), NULL, width, height, format, type);

        // Restore original read buffer
        if (context.read_buffer) {
            glReadBuffer(read_buffer);
        }
    }

    if (!context.ES || context.NV_read_depth_stencil) {
        GLint depth_bits = 0;
        if (context.core) {
            glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, GL_DEPTH, GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE, &depth_bits);
        } else {
            glGetIntegerv(GL_DEPTH_BITS, &depth_bits);
        }
        if (depth_bits) {
            dumpReadBufferImage(writer, context, "GL_DEPTH_COMPONENT", NULL, width, height, GL_DEPTH_COMPONENT, GL_FLOAT);
        }

        GLint stencil_bits = 0;
        if (context.core) {
            glGetFramebufferAttachmentParameteriv(GL_DRAW_FRAMEBUFFER, GL_STENCIL, GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE, &stencil_bits);
        } else {
            glGetIntegerv(GL_STENCIL_BITS, &stencil_bits);
        }
        if (stencil_bits) {
            assert(stencil_bits <= 8);
            dumpReadBufferImage(writer, context, "GL_STENCIL_INDEX", NULL, width, height, GL_STENCIL_INDEX, GL_UNSIGNED_BYTE);
        }
    }
    
    // Restore original read framebuffer
    if (context.read_framebuffer_object) {
        glBindFramebuffer(GL_READ_FRAMEBUFFER, read_framebuffer);
    } else if (context.framebuffer_object) {
        glBindFramebuffer(GL_FRAMEBUFFER, read_framebuffer);
    }
}


/**
 * Dump the specified framebuffer attachment.
 *
 * In the case of a color attachment, it assumes it is already bound for read.
 */
static void
dumpFramebufferAttachment(StateWriter &writer, Context &context, GLenum target, GLenum attachment)
{
    ImageDesc desc;
    if (!getFramebufferAttachmentDesc(context, target, attachment, desc)) {
        return;
    }

    assert(desc.samples == 0);

    GLenum format;
    GLenum type;
    switch (attachment) {
    case GL_DEPTH_ATTACHMENT:
        format = GL_DEPTH_COMPONENT;
        type = GL_FLOAT;
        break;
    case GL_STENCIL_ATTACHMENT:
        format = GL_STENCIL_INDEX;
        type = GL_UNSIGNED_BYTE;
        break;
    default:
        assert(desc.internalFormat != GL_NONE);
        const InternalFormatDesc &formatDesc = getInternalFormatDesc(desc.internalFormat);
        chooseReadBackFormat(formatDesc, format, type);
    }

    GLint object_type = GL_NONE;
    glGetFramebufferAttachmentParameteriv(target, attachment,
                                          GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE,
                                          &object_type);
    GLint object_name = 0;
    glGetFramebufferAttachmentParameteriv(target, attachment,
                                          GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME,
                                          &object_name);
    char *object_label = getObjectLabel(context, object_type, object_name);

    const char *label = enumToString(attachment);

    if (object_type == GL_TEXTURE) {
        GLint layered = GL_FALSE;
        glGetFramebufferAttachmentParameteriv(target, attachment,
                                              GL_FRAMEBUFFER_ATTACHMENT_LAYERED,
                                              &layered);
        if (layered &&
            isGeometryShaderBound(context)) {
            /*
             * Dump the whole texture array.
             *
             * Unfortunately we can't tell whether the bound GS writes or not gl_Layer.
             */

            GLint level = 0;
            glGetFramebufferAttachmentParameteriv(target, attachment,
                                                  GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL,
                                                  &level);

            GLenum texture_target = getTextureTarget(context, object_name);
            GLenum texture_binding = getTextureBinding(texture_target);

            GLint bound_texture = 0;
            glGetIntegerv(texture_binding, &bound_texture);
            glBindTexture(texture_target, object_name);

            dumpActiveTextureLevel(writer, context, texture_target, level, label, object_label);

            glBindTexture(texture_target, bound_texture);

            free(object_label);
            return;
        }
    }


    dumpReadBufferImage(writer, context,
                        label, object_label,
                        desc.width, desc.height,
                        format, type, desc.internalFormat);
    free(object_label);
}


static void
dumpFramebufferAttachments(StateWriter &writer, Context &context, GLenum target)
{
    GLenum status = glCheckFramebufferStatus(target);
    if (status != GL_FRAMEBUFFER_COMPLETE) {
        std::cerr
            << "warning: incomplete " << enumToString(target)
            << " (" << enumToString(status) << ")\n";
        return;
    }

    GLint read_framebuffer = 0;
    glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &read_framebuffer);

    GLint read_buffer = GL_NONE;
    glGetIntegerv(GL_READ_BUFFER, &read_buffer);

    GLint max_draw_buffers = 1;
    glGetIntegerv(GL_MAX_DRAW_BUFFERS, &max_draw_buffers);
    GLint max_color_attachments = 0;
    glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS, &max_color_attachments);

    for (GLint i = 0; i < max_draw_buffers; ++i) {
        GLint draw_buffer = GL_NONE;
        glGetIntegerv(GL_DRAW_BUFFER0 + i, &draw_buffer);
        if (draw_buffer != GL_NONE) {
            glReadBuffer(draw_buffer);
            GLint attachment;
            if (draw_buffer >= GL_COLOR_ATTACHMENT0 && draw_buffer < GL_COLOR_ATTACHMENT0 + max_color_attachments) {
                attachment = draw_buffer;
            } else {
                std::cerr << "warning: unexpected GL_DRAW_BUFFER" << i << " = " << draw_buffer << "\n";
                attachment = GL_COLOR_ATTACHMENT0;
            }
            dumpFramebufferAttachment(writer, context, target, attachment);
        }
    }

    glReadBuffer(read_buffer);

    if (!context.ES || context.NV_read_depth_stencil) {
        dumpFramebufferAttachment(writer, context, target, GL_DEPTH_ATTACHMENT);
        dumpFramebufferAttachment(writer, context, target, GL_STENCIL_ATTACHMENT);
    }

    glBindFramebuffer(GL_READ_FRAMEBUFFER, read_framebuffer);
}


void
dumpFramebuffer(StateWriter &writer, Context &context)
{
    writer.beginMember("framebuffer");
    writer.beginObject();

    GLint boundDrawFbo = 0, boundReadFbo = 0;
    glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &boundDrawFbo);
    glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &boundReadFbo);
    if (!boundDrawFbo) {
        dumpDrawableImages(writer, context);
    } else if (context.ES) {
        dumpFramebufferAttachments(writer, context, GL_FRAMEBUFFER);
    } else {
        GLint draw_buffer0 = GL_NONE;
        glGetIntegerv(GL_DRAW_BUFFER0, &draw_buffer0);
        bool multisample = false;

        GLint boundRb = 0;
        glGetIntegerv(GL_RENDERBUFFER_BINDING, &boundRb);

        ImageDesc colorDesc;
        if (getFramebufferAttachmentDesc(context, GL_DRAW_FRAMEBUFFER, draw_buffer0, colorDesc)) {
            if (colorDesc.samples) {
                multisample = true;
            }
        }

        ImageDesc depthDesc;
        if (getFramebufferAttachmentDesc(context, GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, depthDesc)) {
            if (depthDesc.samples) {
                multisample = true;
            }
        }

        ImageDesc stencilDesc;
        if (getFramebufferAttachmentDesc(context, GL_DRAW_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, stencilDesc)) {
            if (stencilDesc.samples) {
                multisample = true;
            }
        }

        GLuint rbs[3];
        GLint numRbs = 0;
        GLuint fboCopy = 0;

        if (multisample) {
            // glReadPixels doesnt support multisampled buffers so we need
            // to blit the fbo to a temporary one
            fboCopy = downsampledFramebuffer(context,
                                             boundDrawFbo, draw_buffer0,
                                             colorDesc, depthDesc, stencilDesc,
                                             rbs, &numRbs);
        } else {
            glBindFramebuffer(GL_READ_FRAMEBUFFER, boundDrawFbo);
        }

        dumpFramebufferAttachments(writer, context, GL_READ_FRAMEBUFFER);

        if (multisample) {
            glBindRenderbuffer(GL_RENDERBUFFER, boundRb);
            glDeleteRenderbuffers(numRbs, rbs);
            glDeleteFramebuffers(1, &fboCopy);
        }

        glBindFramebuffer(GL_READ_FRAMEBUFFER, boundReadFbo);
        glBindFramebuffer(GL_DRAW_FRAMEBUFFER, boundDrawFbo);
    }

    writer.endObject();
    writer.endMember(); // framebuffer
}


} /* namespace glstate */