summaryrefslogtreecommitdiff
path: root/src/VBox/HostServices/SharedOpenGL/crserverlib/server_misc.c
blob: e9385996e8065a90336930414dc1da846ba4b891 (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
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
/* Copyright (c) 2001, Stanford University
 * All rights reserved
 *
 * See the file LICENSE.txt for information on redistributing this software.
 */

#include "server_dispatch.h"
#include "server.h"
#include "cr_error.h"
#include "cr_mem.h"
#include "cr_string.h"
#include "cr_pixeldata.h"

void SERVER_DISPATCH_APIENTRY crServerDispatchSelectBuffer( GLsizei size, GLuint *buffer )
{
    (void) size;
    (void) buffer;
    crError( "Unsupported network glSelectBuffer call." );
}

void SERVER_DISPATCH_APIENTRY crServerDispatchGetChromiumParametervCR(GLenum target, GLuint index, GLenum type, GLsizei count, GLvoid *values)
{
    GLubyte local_storage[4096];
    GLint bytes = 0;

    switch (type) {
    case GL_BYTE:
    case GL_UNSIGNED_BYTE:
         bytes = count * sizeof(GLbyte);
         break;
    case GL_SHORT:
    case GL_UNSIGNED_SHORT:
         bytes = count * sizeof(GLshort);
         break;
    case GL_INT:
    case GL_UNSIGNED_INT:
         bytes = count * sizeof(GLint);
         break;
    case GL_FLOAT:
         bytes = count * sizeof(GLfloat);
         break;
    case GL_DOUBLE:
         bytes = count * sizeof(GLdouble);
         break;
    default:
         crError("Bad type in crServerDispatchGetChromiumParametervCR");
    }

    CRASSERT(bytes >= 0);
    CRASSERT(bytes < 4096);

    switch (target)
    {
        case GL_DBG_CHECK_BREAK_CR:
        {
            if (bytes > 0)
            {
                GLubyte *pbRc = local_storage;
                GLuint *puRc = (GLuint *)(bytes >=4 ? local_storage : NULL);
                int rc;
                memset(local_storage, 0, bytes);
                if (cr_server.RcToGuestOnce)
                {
                    rc = cr_server.RcToGuestOnce;
                    cr_server.RcToGuestOnce = 0;
                }
                else
                {
                    rc = cr_server.RcToGuest;
                }
                if (puRc)
                    *puRc = rc;
                else
                    *pbRc = !!rc;
            }
            else
            {
                crWarning("zero bytes for GL_DBG_CHECK_BREAK_CR");
            }
            break;
        }
        default:
            cr_server.head_spu->dispatch_table.GetChromiumParametervCR( target, index, type, count, local_storage );
            break;
    }

    crServerReturnValue( local_storage, bytes );
}

void SERVER_DISPATCH_APIENTRY crServerDispatchChromiumParametervCR(GLenum target, GLenum type, GLsizei count, const GLvoid *values)
{
    CRMuralInfo *mural = cr_server.curClient->currentMural;
    static int gather_connect_count = 0;

    switch (target) {
    case GL_SET_MAX_VIEWPORT_CR:
        {
            GLint *maxDims = (GLint *)values;
            cr_server.limits.maxViewportDims[0] = maxDims[0];
            cr_server.limits.maxViewportDims[1] = maxDims[1];
        }
        break;

    case GL_TILE_INFO_CR:
        /* message from tilesort SPU to set new tile bounds */
        {
            GLint numTiles, muralWidth, muralHeight, server, tiles;
            GLint *tileBounds;
            CRASSERT(count >= 4);
            CRASSERT((count - 4) % 4 == 0); /* must be multiple of four */
            CRASSERT(type == GL_INT);
            numTiles = (count - 4) / 4;
            tileBounds = (GLint *) values;
            server = tileBounds[0];
            muralWidth = tileBounds[1];
            muralHeight = tileBounds[2];
            tiles = tileBounds[3];
            CRASSERT(tiles == numTiles);
            tileBounds += 4; /* skip over header values */
            /*crServerNewMuralTiling(mural, muralWidth, muralHeight, numTiles, tileBounds);
            mural->viewportValidated = GL_FALSE;*/
        }
        break;

    case GL_GATHER_DRAWPIXELS_CR:
        if (cr_server.only_swap_once && cr_server.curClient != cr_server.clients[0])
            break;
        cr_server.head_spu->dispatch_table.ChromiumParametervCR( target, type, count, values );
        break;

    case GL_GATHER_CONNECT_CR:
        /*
         * We want the last connect to go through,
         * otherwise we might deadlock in CheckWindowSize()
         * in the readback spu
         */
        gather_connect_count++;
        if (cr_server.only_swap_once && (gather_connect_count != cr_server.numClients))
        {
            break;
        }
        cr_server.head_spu->dispatch_table.ChromiumParametervCR( target, type, count, values );
        gather_connect_count = 0;
        break;

    case GL_SERVER_VIEW_MATRIX_CR:
        /* Set this server's view matrix which will get premultiplied onto the
         * modelview matrix.  For non-planar tilesort and stereo.
         */
        CRASSERT(count == 18);
        CRASSERT(type == GL_FLOAT);
        /* values[0] is the server index. Ignored here but used in tilesort SPU */
        /* values[1] is the left/right eye index (0 or 1) */
        {
            const GLfloat *v = (const GLfloat *) values;
            const int eye = v[1] == 0.0 ? 0 : 1;
            crMatrixInitFromFloats(&cr_server.viewMatrix[eye], v + 2);

            crDebug("Got GL_SERVER_VIEW_MATRIX_CR:\n"
                            "  %f %f %f %f\n"
                            "  %f %f %f %f\n"
                            "  %f %f %f %f\n"
                            "  %f %f %f %f",
                            cr_server.viewMatrix[eye].m00,
                            cr_server.viewMatrix[eye].m10,
                            cr_server.viewMatrix[eye].m20,
                            cr_server.viewMatrix[eye].m30,
                            cr_server.viewMatrix[eye].m01,
                            cr_server.viewMatrix[eye].m11,
                            cr_server.viewMatrix[eye].m21,
                            cr_server.viewMatrix[eye].m31,
                            cr_server.viewMatrix[eye].m02,
                            cr_server.viewMatrix[eye].m12,
                            cr_server.viewMatrix[eye].m22,
                            cr_server.viewMatrix[eye].m32,
                            cr_server.viewMatrix[eye].m03,
                            cr_server.viewMatrix[eye].m13,
                            cr_server.viewMatrix[eye].m23,
                            cr_server.viewMatrix[eye].m33);
        }
        cr_server.viewOverride = GL_TRUE;
        break;

    case GL_SERVER_PROJECTION_MATRIX_CR:
        /* Set this server's projection matrix which will get replace the user's
         * projection matrix.  For non-planar tilesort and stereo.
         */
        CRASSERT(count == 18);
        CRASSERT(type == GL_FLOAT);
        /* values[0] is the server index. Ignored here but used in tilesort SPU */
        /* values[1] is the left/right eye index (0 or 1) */
        {
            const GLfloat *v = (const GLfloat *) values;
            const int eye = v[1] == 0.0 ? 0 : 1;
            crMatrixInitFromFloats(&cr_server.projectionMatrix[eye], v + 2);

            crDebug("Got GL_SERVER_PROJECTION_MATRIX_CR:\n"
                            "  %f %f %f %f\n"
                            "  %f %f %f %f\n"
                            "  %f %f %f %f\n"
                            "  %f %f %f %f",
                            cr_server.projectionMatrix[eye].m00,
                            cr_server.projectionMatrix[eye].m10,
                            cr_server.projectionMatrix[eye].m20,
                            cr_server.projectionMatrix[eye].m30,
                            cr_server.projectionMatrix[eye].m01,
                            cr_server.projectionMatrix[eye].m11,
                            cr_server.projectionMatrix[eye].m21,
                            cr_server.projectionMatrix[eye].m31,
                            cr_server.projectionMatrix[eye].m02,
                            cr_server.projectionMatrix[eye].m12,
                            cr_server.projectionMatrix[eye].m22,
                            cr_server.projectionMatrix[eye].m32,
                            cr_server.projectionMatrix[eye].m03,
                            cr_server.projectionMatrix[eye].m13,
                            cr_server.projectionMatrix[eye].m23,
                            cr_server.projectionMatrix[eye].m33);

            if (cr_server.projectionMatrix[eye].m33 == 0.0f) {
                float x = cr_server.projectionMatrix[eye].m00;
                float y = cr_server.projectionMatrix[eye].m11;
                float a = cr_server.projectionMatrix[eye].m20;
                float b = cr_server.projectionMatrix[eye].m21;
                float c = cr_server.projectionMatrix[eye].m22;
                float d = cr_server.projectionMatrix[eye].m32;
                float znear = -d / (1.0f - c);
                float zfar = (c - 1.0f) * znear / (c + 1.0f);
                float left = znear * (a - 1.0f) / x;
                float right = 2.0f * znear / x + left;
                float bottom = znear * (b - 1.0f) / y;
              float top = 2.0f * znear / y + bottom;
              crDebug("Frustum: left, right, bottom, top, near, far: %f, %f, %f, %f, %f, %f", left, right, bottom, top, znear, zfar);
            }
            else {
                /* Todo: Add debug output for orthographic projection*/
            }

        }
        cr_server.projectionOverride = GL_TRUE;
        break;

    case GL_HH_SET_TMPCTX_MAKE_CURRENT:
        /*we should not receive it from the guest! */
        break;

    default:
        /* Pass the parameter info to the head SPU */
        cr_server.head_spu->dispatch_table.ChromiumParametervCR( target, type, count, values );
        break;
    }
}


void SERVER_DISPATCH_APIENTRY crServerDispatchChromiumParameteriCR(GLenum target, GLint value)
{
  switch (target) {
    case GL_SHARE_CONTEXT_RESOURCES_CR:
        crStateShareContext(value);
        break;
    case GL_RCUSAGE_TEXTURE_SET_CR:
        crStateSetTextureUsed(value, GL_TRUE);
        break;
    case GL_RCUSAGE_TEXTURE_CLEAR_CR:
        crStateSetTextureUsed(value, GL_FALSE);
        break;
    case GL_SHARED_DISPLAY_LISTS_CR:
        cr_server.sharedDisplayLists = value;
        break;
    case GL_SHARED_TEXTURE_OBJECTS_CR:
        cr_server.sharedTextureObjects = value;
        break;
    case GL_SHARED_PROGRAMS_CR:
        cr_server.sharedPrograms = value;
        break;
    case GL_SERVER_CURRENT_EYE_CR:
        cr_server.currentEye = value ? 1 : 0;
        break;
    case GL_HOST_WND_CREATED_HIDDEN_CR:
        cr_server.bWindowsInitiallyHidden = value ? 1 : 0;
        break;
    case GL_HH_SET_DEFAULT_SHARED_CTX:
        crWarning("Recieved GL_HH_SET_DEFAULT_SHARED_CTX from guest, ignoring");
        break;
    default:
        /* Pass the parameter info to the head SPU */
        cr_server.head_spu->dispatch_table.ChromiumParameteriCR( target, value );
    }
}


void SERVER_DISPATCH_APIENTRY crServerDispatchChromiumParameterfCR(GLenum target, GLfloat value)
{
  switch (target) {
    case GL_SHARED_DISPLAY_LISTS_CR:
        cr_server.sharedDisplayLists = (int) value;
        break;
    case GL_SHARED_TEXTURE_OBJECTS_CR:
        cr_server.sharedTextureObjects = (int) value;
        break;
    case GL_SHARED_PROGRAMS_CR:
        cr_server.sharedPrograms = (int) value;
        break;
    default:
        /* Pass the parameter info to the head SPU */
        cr_server.head_spu->dispatch_table.ChromiumParameterfCR( target, value );
    }
}

GLint crServerGenerateID(GLint *pCounter)
{
    return (*pCounter)++;
}

/*#define CR_DUMP_BLITS*/

#ifdef CR_DUMP_BLITS
static int blitnum=0;
static int copynum=0;
#endif

# ifdef DEBUG_misha
//# define CR_CHECK_BLITS
#  include <iprt/assert.h>
#  undef CRASSERT /* iprt assert's int3 are inlined that is why are more convenient to use since they can be easily disabled individually */
#  define CRASSERT Assert
# endif


void SERVER_DISPATCH_APIENTRY
crServerDispatchCopyTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height)
{
    /*@todo pbo/fbo disabled for now as it's slower, check on other gpus*/
    static int siHavePBO = 0;
    static int siHaveFBO = 0;

    if ((target!=GL_TEXTURE_2D) || (height>=0))
    {
        cr_server.head_spu->dispatch_table.CopyTexSubImage2D(target, level, xoffset, yoffset, x, y, width, height);

#ifdef CR_DUMP_BLITS
        {
            SPUDispatchTable *gl = &cr_server.head_spu->dispatch_table;
            void *img;
            GLint w, h;
            char fname[200];

            copynum++;

            gl->GetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &w);
            gl->GetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT, &h);

            img = crAlloc(w*h*4);
            CRASSERT(img);

            gl->GetTexImage(GL_TEXTURE_2D, 0, GL_BGRA, GL_UNSIGNED_BYTE, img);
            sprintf(fname, "copy_blit%i_copy_%i.tga", blitnum, copynum);
            crDumpNamedTGA(fname, w, h, img);
            crFree(img);
        }
#endif
    }
    else /* negative height, means we have to Yinvert the source pixels while copying */
    {
        SPUDispatchTable *gl = &cr_server.head_spu->dispatch_table;

        if (siHavePBO<0)
        {
            const char *ext = (const char*)gl->GetString(GL_EXTENSIONS);
            siHavePBO = crStrstr(ext, "GL_ARB_pixel_buffer_object") ? 1:0;
        }

        if (siHaveFBO<0)
        {
            const char *ext = (const char*)gl->GetString(GL_EXTENSIONS);
            siHaveFBO = crStrstr(ext, "GL_EXT_framebuffer_object") ? 1:0;
        }

        if (siHavePBO==0 && siHaveFBO==0)
        {
#if 1
            GLint dRow, sRow;
            for (dRow=yoffset, sRow=y-height-1; dRow<yoffset-height; dRow++, sRow--)
            {
                gl->CopyTexSubImage2D(target, level, xoffset, dRow, x, sRow, width, 1);
            }
#else
            {
                GLint w, h, i;
                char *img1, *img2, *sPtr, *dPtr;
                CRContext *ctx = crStateGetCurrent();

                w = ctx->texture.unit[ctx->texture.curTextureUnit].currentTexture2D->level[0][level].width;
                h = ctx->texture.unit[ctx->texture.curTextureUnit].currentTexture2D->level[0][level].height;

                img1 = crAlloc(4*w*h);
                img2 = crAlloc(4*width*(-height));
                CRASSERT(img1 && img2);

                gl->CopyTexSubImage2D(target, level, xoffset, yoffset, x, y, width, -height);
                gl->GetTexImage(target, level, GL_RGBA, GL_UNSIGNED_BYTE, img1);

                sPtr=img1+4*xoffset+4*w*yoffset;
                dPtr=img2+4*width*(-height-1);

                for (i=0; i<-height; ++i)
                {
                    crMemcpy(dPtr, sPtr, 4*width);
                    sPtr += 4*w;
                    dPtr -= 4*width;
                }

                gl->TexSubImage2D(target, level, xoffset, yoffset, width, -height, GL_RGBA, GL_UNSIGNED_BYTE, img2);

                crFree(img1);
                crFree(img2);
            }
#endif
        }
        else if (siHaveFBO==1) /*@todo more states to set and restore here*/
        {
            GLuint tID, fboID;
            GLenum status;
            CRContext *ctx = crStateGetCurrent();

            gl->GenTextures(1, &tID);
            gl->BindTexture(target, tID);
            gl->CopyTexImage2D(target, level, GL_RGBA, x, y, width, -height, 0);
            gl->GenFramebuffersEXT(1, &fboID);
            gl->BindFramebufferEXT(GL_FRAMEBUFFER_EXT, fboID);
            gl->FramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, target,
                                        ctx->texture.unit[ctx->texture.curTextureUnit].currentTexture2D->hwid, level);
            status = gl->CheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
            if (status != GL_FRAMEBUFFER_COMPLETE_EXT)
            {
                crWarning("Framebuffer status 0x%x", status);
            }

            gl->Enable(target);
            gl->PushAttrib(GL_VIEWPORT_BIT);
            gl->Viewport(xoffset, yoffset, width, -height);
            gl->MatrixMode(GL_PROJECTION);
            gl->PushMatrix();
            gl->LoadIdentity();
            gl->MatrixMode(GL_MODELVIEW);
	        gl->PushMatrix();
            gl->LoadIdentity();

            gl->Disable(GL_DEPTH_TEST);
            gl->Disable(GL_CULL_FACE);
            gl->Disable(GL_STENCIL_TEST);
            gl->Disable(GL_SCISSOR_TEST);

            gl->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
            gl->TexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
            gl->TexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
            gl->TexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
            gl->TexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);

            gl->Begin(GL_QUADS);
                gl->TexCoord2f(0.0f, 1.0f);
                gl->Vertex2f(-1.0, -1.0);

                gl->TexCoord2f(0.0f, 0.0f);
                gl->Vertex2f(-1.0f, 1.0f);

                gl->TexCoord2f(1.0f, 0.0f);
                gl->Vertex2f(1.0f, 1.0f);

                gl->TexCoord2f(1.0f, 1.0f);
                gl->Vertex2f(1.0f, -1.0f);
            gl->End();

            gl->PopMatrix();
            gl->MatrixMode(GL_PROJECTION);
            gl->PopMatrix();
            gl->PopAttrib();

            gl->FramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, target, 0, level);
            gl->BindFramebufferEXT(GL_FRAMEBUFFER_EXT, ctx->framebufferobject.drawFB ? ctx->framebufferobject.drawFB->hwid:0);
            gl->BindTexture(target, ctx->texture.unit[ctx->texture.curTextureUnit].currentTexture2D->hwid);
            gl->DeleteFramebuffersEXT(1, &fboID);
            gl->DeleteTextures(1, &tID);

#if 0
            {
                GLint dRow, sRow, w, h;
                void *img1, *img2;

                w = ctx->texture.unit[ctx->texture.curTextureUnit].currentTexture2D->level[0][level].width;
                h = ctx->texture.unit[ctx->texture.curTextureUnit].currentTexture2D->level[0][level].height;

                img1 = crAlloc(4*w*h);
                img2 = crAlloc(4*w*h);
                CRASSERT(img1 && img2);

                gl->GetTexImage(target, level, GL_BGRA, GL_UNSIGNED_BYTE, img1);


                for (dRow=yoffset, sRow=y-height-1; dRow<yoffset-height; dRow++, sRow--)
                {
                    gl->CopyTexSubImage2D(target, level, xoffset, dRow, x, sRow, width, 1);
                }

                gl->GetTexImage(target, level, GL_BGRA, GL_UNSIGNED_BYTE, img2);

                if (crMemcmp(img1, img2, 4*w*h))
                {
                    crDebug("MISMATCH! (%x, %i, ->%i,%i  <-%i, %i  [%ix%i])", target, level, xoffset, yoffset, x, y, width, height);
                    crDumpTGA(w, h, img1);
                    crDumpTGA(w, h, img2);
                    DebugBreak();
                }
                crFree(img1);
                crFree(img2);
            }
#endif
        }
        else
        {
            GLuint pboId, dRow, sRow;
            CRContext *ctx = crStateGetCurrent();

            gl->GenBuffersARB(1, &pboId);
            gl->BindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, pboId);
            gl->BufferDataARB(GL_PIXEL_PACK_BUFFER_ARB, -width*height*4, 0, GL_STATIC_COPY_ARB);

#if 1
            gl->ReadPixels(x, y, width, -height, GL_RGBA, GL_UNSIGNED_BYTE, 0);
            gl->BindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, ctx->bufferobject.packBuffer->hwid);

            gl->BindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, pboId);
            for (dRow=yoffset, sRow=-height-1; dRow<yoffset-height; dRow++, sRow--)
            {
                gl->TexSubImage2D(target, level, xoffset, dRow, width, 1, GL_RGBA, GL_UNSIGNED_BYTE, (void*)((uintptr_t)sRow*width*4));
            }
#else /*few times slower again*/
            for (dRow=0, sRow=y-height-1; dRow<-height; dRow++, sRow--)
            {
                gl->ReadPixels(x, sRow, width, 1, GL_RGBA, GL_UNSIGNED_BYTE, (void*)((uintptr_t)dRow*width*4));
            }
            gl->BindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, ctx->bufferobject.packBuffer->hwid);

            gl->BindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, pboId);
            gl->TexSubImage2D(target, level, xoffset, yoffset, width, -height, GL_RGBA, GL_UNSIGNED_BYTE, 0);
#endif

            gl->BindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, ctx->bufferobject.unpackBuffer->hwid);
            gl->DeleteBuffersARB(1, &pboId);
        }
    }
}

#ifdef CR_CHECK_BLITS
void crDbgFree(void *pvData)
{
    crFree(pvData);
}

void crDbgGetTexImage2D(GLint texTarget, GLint texName, GLvoid **ppvImage, GLint *pw, GLint *ph)
{
    SPUDispatchTable *gl = &cr_server.head_spu->dispatch_table;
    GLint ppb, pub, dstw, dsth, otex;
    GLint pa, pr, psp, psr, ua, ur, usp, usr;
    GLvoid *pvImage;
    GLint rfb, dfb, rb, db;

    gl->GetIntegerv(GL_READ_FRAMEBUFFER_BINDING_EXT, &rfb);
    gl->GetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING_EXT, &dfb);
    gl->GetIntegerv(GL_READ_BUFFER, &rb);
    gl->GetIntegerv(GL_DRAW_BUFFER, &db);

    gl->BindFramebufferEXT(GL_READ_FRAMEBUFFER_BINDING_EXT, 0);
    gl->BindFramebufferEXT(GL_DRAW_FRAMEBUFFER_BINDING_EXT, 0);
    gl->ReadBuffer(GL_BACK);
    gl->DrawBuffer(GL_BACK);

    gl->GetIntegerv(GL_PIXEL_PACK_BUFFER_BINDING, &ppb);
    gl->GetIntegerv(GL_PIXEL_UNPACK_BUFFER_BINDING, &pub);
    gl->GetIntegerv(GL_TEXTURE_BINDING_2D, &otex);

    gl->GetIntegerv(GL_PACK_ROW_LENGTH, &pr);
    gl->GetIntegerv(GL_PACK_ALIGNMENT, &pa);
    gl->GetIntegerv(GL_PACK_SKIP_PIXELS, &psp);
    gl->GetIntegerv(GL_PACK_SKIP_ROWS, &psr);

    gl->GetIntegerv(GL_UNPACK_ROW_LENGTH, &ur);
    gl->GetIntegerv(GL_UNPACK_ALIGNMENT, &ua);
    gl->GetIntegerv(GL_UNPACK_SKIP_PIXELS, &usp);
    gl->GetIntegerv(GL_UNPACK_SKIP_ROWS, &usr);

    gl->BindTexture(texTarget, texName);
    gl->GetTexLevelParameteriv(texTarget, 0, GL_TEXTURE_WIDTH, &dstw);
    gl->GetTexLevelParameteriv(texTarget, 0, GL_TEXTURE_HEIGHT, &dsth);

    gl->PixelStorei(GL_PACK_ROW_LENGTH, 0);
    gl->PixelStorei(GL_PACK_ALIGNMENT, 1);
    gl->PixelStorei(GL_PACK_SKIP_PIXELS, 0);
    gl->PixelStorei(GL_PACK_SKIP_ROWS, 0);

    gl->PixelStorei(GL_UNPACK_ROW_LENGTH, 0);
    gl->PixelStorei(GL_UNPACK_ALIGNMENT, 1);
    gl->PixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
    gl->PixelStorei(GL_UNPACK_SKIP_ROWS, 0);

    gl->BindBufferARB(GL_PIXEL_PACK_BUFFER, 0);
    gl->BindBufferARB(GL_PIXEL_UNPACK_BUFFER, 0);

    pvImage = crAlloc(4*dstw*dsth);
    gl->GetTexImage(texTarget, 0, GL_BGRA, GL_UNSIGNED_BYTE, pvImage);

    gl->BindTexture(texTarget, otex);

    gl->PixelStorei(GL_PACK_ROW_LENGTH, pr);
    gl->PixelStorei(GL_PACK_ALIGNMENT, pa);
    gl->PixelStorei(GL_PACK_SKIP_PIXELS, psp);
    gl->PixelStorei(GL_PACK_SKIP_ROWS, psr);

    gl->PixelStorei(GL_UNPACK_ROW_LENGTH, ur);
    gl->PixelStorei(GL_UNPACK_ALIGNMENT, ua);
    gl->PixelStorei(GL_UNPACK_SKIP_PIXELS, usp);
    gl->PixelStorei(GL_UNPACK_SKIP_ROWS, usr);

    gl->BindBufferARB(GL_PIXEL_PACK_BUFFER, ppb);
    gl->BindBufferARB(GL_PIXEL_UNPACK_BUFFER, pub);

    gl->BindFramebufferEXT(GL_READ_FRAMEBUFFER_BINDING_EXT, rfb);
    gl->BindFramebufferEXT(GL_DRAW_FRAMEBUFFER_BINDING_EXT, dfb);
    gl->ReadBuffer(rb);
    gl->DrawBuffer(db);

    *ppvImage = pvImage;
    *pw = dstw;
    *ph = dsth;
}

DECLEXPORT(void) crDbgPrint(const char *format, ... )
{
    va_list args;
    static char txt[8092];

    va_start( args, format );
    vsprintf( txt, format, args );

    OutputDebugString(txt);
}

void crDbgDumpImage2D(const char* pszDesc, const void *pvData, uint32_t width, uint32_t height, uint32_t bpp, uint32_t pitch)
{
    crDbgPrint("<?dml?><exec cmd=\"!vbvdbg.ms 0x%p 0n%d 0n%d 0n%d 0n%d\">%s</exec>, ( !vbvdbg.ms 0x%p 0n%d 0n%d 0n%d 0n%d )\n",
            pvData, width, height, bpp, pitch,
            pszDesc,
            pvData, width, height, bpp, pitch);
}

void crDbgDumpTexImage2D(const char* pszDesc, GLint texTarget, GLint texName, GLboolean fBreak)
{
    GLvoid *pvImage;
    GLint w, h;
    crDbgGetTexImage2D(texTarget, texName, &pvImage, &w, &h);
    crDbgPrint("%s target(%d), name(%d), width(%d), height(%d)", pszDesc, texTarget, texName, w, h);
    crDbgDumpImage2D("texture data", pvImage, w, h, 32, (32 * w)/8);
    if (fBreak)
    {
        CRASSERT(0);
    }
    crDbgFree(pvImage);
}
#endif

PCR_BLITTER crServerVBoxBlitterGet()
{
    if (!CrBltIsInitialized(&cr_server.Blitter))
    {
        CR_BLITTER_CONTEXT Ctx;
        int rc;
        CRASSERT(cr_server.MainContextInfo.SpuContext);
        Ctx.Base.id = cr_server.MainContextInfo.SpuContext;
        Ctx.Base.visualBits = cr_server.MainContextInfo.CreateInfo.realVisualBits;
        rc = CrBltInit(&cr_server.Blitter, &Ctx, true, true, NULL, &cr_server.TmpCtxDispatch);
        if (RT_SUCCESS(rc))
        {
            CRASSERT(CrBltIsInitialized(&cr_server.Blitter));
        }
        else
        {
            crWarning("CrBltInit failed, rc %d", rc);
            CRASSERT(!CrBltIsInitialized(&cr_server.Blitter));
            return NULL;
        }
    }

    if (!CrBltMuralGetCurrentInfo(&cr_server.Blitter)->Base.id)
    {
        CRMuralInfo *dummy = crServerGetDummyMural(cr_server.MainContextInfo.CreateInfo.realVisualBits);
        CR_BLITTER_WINDOW DummyInfo;
        CRASSERT(dummy);
        crServerVBoxBlitterWinInit(&DummyInfo, dummy);
        CrBltMuralSetCurrentInfo(&cr_server.Blitter, &DummyInfo);
    }

    return &cr_server.Blitter;
}

PCR_BLITTER crServerVBoxBlitterGetInitialized()
{
    if (CrBltIsInitialized(&cr_server.Blitter))
        return &cr_server.Blitter;
    return NULL;
}


int crServerVBoxBlitterTexInit(CRContext *ctx, CRMuralInfo *mural, PVBOXVR_TEXTURE pTex, GLboolean fDraw)
{
    CRTextureObj *tobj;
    CRFramebufferObjectState *pBuf = &ctx->framebufferobject;
    GLenum enmBuf;
    CRFBOAttachmentPoint *pAp;
    GLuint idx;
    CRTextureLevel *tl;
    CRFramebufferObject *pFBO = fDraw ? pBuf->drawFB : pBuf->readFB;

    if (!pFBO)
    {
        GLuint hwid;

        if (!mural->fRedirected)
            return VERR_NOT_IMPLEMENTED;

        enmBuf = fDraw ? ctx->buffer.drawBuffer : ctx->buffer.readBuffer;
        switch (enmBuf)
        {
            case GL_BACK:
            case GL_BACK_RIGHT:
            case GL_BACK_LEFT:
                hwid = mural->aidColorTexs[CR_SERVER_FBO_BB_IDX(mural)];
                break;
            case GL_FRONT:
            case GL_FRONT_RIGHT:
            case GL_FRONT_LEFT:
                hwid = mural->aidColorTexs[CR_SERVER_FBO_FB_IDX(mural)];
                break;
            default:
                crWarning("unsupported enum buf");
                return VERR_NOT_IMPLEMENTED;
                break;
        }

        if (!hwid)
        {
            crWarning("offscreen render tex hwid is null");
            return VERR_INVALID_STATE;
        }

        pTex->width = mural->width;
        pTex->height = mural->height;
        pTex->target = GL_TEXTURE_2D;
        pTex->hwid = hwid;
        return VINF_SUCCESS;
    }

    enmBuf = fDraw ? pFBO->drawbuffer[0] : pFBO->readbuffer;
    idx = enmBuf - GL_COLOR_ATTACHMENT0_EXT;
    if (idx >= CR_MAX_COLOR_ATTACHMENTS)
    {
        crWarning("idx is invalid %d, using 0", idx);
    }

    pAp = &pFBO->color[idx];

    if (!pAp->name)
    {
        crWarning("no collor draw attachment");
        return VERR_INVALID_STATE;
    }

    if (pAp->level)
    {
        crWarning("non-zero level not implemented");
        return VERR_NOT_IMPLEMENTED;
    }

    tobj = (CRTextureObj*)crHashtableSearch(ctx->shared->textureTable, pAp->name);
    if (!tobj)
    {
        crWarning("no texture object found for name %d", pAp->name);
        return VERR_INVALID_STATE;
    }

    if (tobj->target != GL_TEXTURE_2D && tobj->target != GL_TEXTURE_RECTANGLE_NV)
    {
        crWarning("non-texture[rect|2d] not implemented");
        return VERR_NOT_IMPLEMENTED;
    }

    CRASSERT(tobj->hwid);

    tl = tobj->level[0];
    pTex->width = tl->width;
    pTex->height = tl->height;
    pTex->target = tobj->target;
    pTex->hwid = tobj->hwid;

    return VINF_SUCCESS;
}

int crServerVBoxBlitterBlitCurrentCtx(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1,
        GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1,
        GLbitfield mask, GLenum filter)
{
    PCR_BLITTER pBlitter;
    CR_BLITTER_CONTEXT Ctx;
    CRMuralInfo *mural;
    CRContext *ctx = crStateGetCurrent();
    PVBOXVR_TEXTURE pDrawTex, pReadTex;
    VBOXVR_TEXTURE DrawTex, ReadTex;
    int rc;
    GLuint idDrawFBO, idReadFBO;
    CR_BLITTER_WINDOW BltInfo;

    if (mask != GL_COLOR_BUFFER_BIT)
    {
        crWarning("not supported blit mask %d", mask);
        return VERR_NOT_IMPLEMENTED;
    }

    if (!cr_server.curClient)
    {
        crWarning("no current client");
        return VERR_INVALID_STATE;
    }
    mural = cr_server.curClient->currentMural;
    if (!mural)
    {
        crWarning("no current mural");
        return VERR_INVALID_STATE;
    }

    rc = crServerVBoxBlitterTexInit(ctx, mural, &DrawTex, GL_TRUE);
    if (RT_SUCCESS(rc))
    {
        pDrawTex = &DrawTex;
    }
    else
    {
        crWarning("crServerVBoxBlitterTexInit failed for draw");
        return rc;
    }

    rc = crServerVBoxBlitterTexInit(ctx, mural, &ReadTex, GL_FALSE);
    if (RT_SUCCESS(rc))
    {
        pReadTex = &ReadTex;
    }
    else
    {
//        crWarning("crServerVBoxBlitterTexInit failed for read");
        return rc;
    }

    pBlitter = crServerVBoxBlitterGet();
    if (!pBlitter)
    {
        crWarning("crServerVBoxBlitterGet failed");
        return VERR_GENERAL_FAILURE;
    }

    crServerVBoxBlitterWinInit(&BltInfo, mural);

    crServerVBoxBlitterCtxInit(&Ctx, cr_server.curClient->currentCtxInfo);

    CrBltMuralSetCurrentInfo(pBlitter, &BltInfo);

    idDrawFBO = CR_SERVER_FBO_FOR_IDX(mural, mural->iCurDrawBuffer);
    idReadFBO = CR_SERVER_FBO_FOR_IDX(mural, mural->iCurReadBuffer);

    crStateSwitchPrepare(NULL, ctx, idDrawFBO, idReadFBO);

    rc = CrBltEnter(pBlitter);
    if (RT_SUCCESS(rc))
    {
        RTRECT ReadRect, DrawRect;
        ReadRect.xLeft = srcX0;
        ReadRect.yTop = srcY0;
        ReadRect.xRight = srcX1;
        ReadRect.yBottom = srcY1;
        DrawRect.xLeft = dstX0;
        DrawRect.yTop = dstY0;
        DrawRect.xRight = dstX1;
        DrawRect.yBottom = dstY1;
        CrBltBlitTexTex(pBlitter, pReadTex, &ReadRect, pDrawTex, &DrawRect, 1, CRBLT_FLAGS_FROM_FILTER(filter));
        CrBltLeave(pBlitter);
    }
    else
    {
        crWarning("CrBltEnter failed rc %d", rc);
    }

    crStateSwitchPostprocess(ctx, NULL, idDrawFBO, idReadFBO);

    return rc;
}

void SERVER_DISPATCH_APIENTRY
crServerDispatchBlitFramebufferEXT(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1,
                                   GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1,
                                   GLbitfield mask, GLenum filter)
{
    CRContext *ctx = crStateGetCurrent();
    bool fTryBlitter = false;
#ifdef CR_CHECK_BLITS
//    {
        SPUDispatchTable *gl = &cr_server.head_spu->dispatch_table;
        GLint rfb=0, dfb=0, dtex=0, dlev=-1, rtex=0, rlev=-1, rb=0, db=0, ppb=0, pub=0, vp[4], otex, dstw, dsth;
        GLint sdtex=0, srtex=0;
        GLenum dStatus, rStatus;

        CRTextureObj *tobj = 0;
        CRTextureLevel *tl = 0;
        GLint id, tuId, pbufId, pbufIdHw, ubufId, ubufIdHw, width, height, depth;

        crDebug("===StateTracker===");
        crDebug("Current TU: %i", ctx->texture.curTextureUnit);

        tobj = ctx->texture.unit[ctx->texture.curTextureUnit].currentTexture2D;
        CRASSERT(tobj);
        tl = &tobj->level[0][0];
        crDebug("Texture %i(hw %i), w=%i, h=%i", tobj->id, tobj->hwid, tl->width, tl->height, tl->depth);

        if (crStateIsBufferBound(GL_PIXEL_PACK_BUFFER_ARB))
        {
            pbufId = ctx->bufferobject.packBuffer->hwid;
        }
        else
        {
            pbufId = 0;
        }
        crDebug("Pack BufferId %i", pbufId);

        if (crStateIsBufferBound(GL_PIXEL_UNPACK_BUFFER_ARB))
        {
            ubufId = ctx->bufferobject.unpackBuffer->hwid;
        }
        else
        {
            ubufId = 0;
        }
        crDebug("Unpack BufferId %i", ubufId);

        crDebug("===GPU===");
        cr_server.head_spu->dispatch_table.GetIntegerv(GL_ACTIVE_TEXTURE, &tuId);
        crDebug("Current TU: %i", tuId - GL_TEXTURE0_ARB);
        CRASSERT(tuId - GL_TEXTURE0_ARB == ctx->texture.curTextureUnit);

        cr_server.head_spu->dispatch_table.GetIntegerv(GL_TEXTURE_BINDING_2D, &id);
        cr_server.head_spu->dispatch_table.GetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &width);
        cr_server.head_spu->dispatch_table.GetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT, &height);
        cr_server.head_spu->dispatch_table.GetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_DEPTH, &depth);
        crDebug("Texture: %i, w=%i, h=%i, d=%i", id, width, height, depth);
        CRASSERT(id == tobj->hwid);
        CRASSERT(width == tl->width);
        CRASSERT(height == tl->height);
        CRASSERT(depth == tl->depth);

        cr_server.head_spu->dispatch_table.GetIntegerv(GL_PIXEL_PACK_BUFFER_BINDING, &pbufIdHw);
        crDebug("Hw Pack BufferId %i", pbufIdHw);
        CRASSERT(pbufIdHw == pbufId);

        cr_server.head_spu->dispatch_table.GetIntegerv(GL_PIXEL_UNPACK_BUFFER_BINDING, &ubufIdHw);
        crDebug("Hw Unpack BufferId %i", ubufIdHw);
        CRASSERT(ubufIdHw == ubufId);

        gl->GetIntegerv(GL_READ_FRAMEBUFFER_BINDING_EXT, &rfb);
        gl->GetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING_EXT, &dfb);
        gl->GetIntegerv(GL_READ_BUFFER, &rb);
        gl->GetIntegerv(GL_DRAW_BUFFER, &db);

        gl->GetIntegerv(GL_PIXEL_PACK_BUFFER_BINDING, &ppb);
        gl->GetIntegerv(GL_PIXEL_UNPACK_BUFFER_BINDING, &pub);

        gl->GetIntegerv(GL_VIEWPORT, &vp[0]);

        gl->GetIntegerv(GL_TEXTURE_BINDING_2D, &otex);

        gl->GetFramebufferAttachmentParameterivEXT(GL_DRAW_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME_EXT, &dtex);
        gl->GetFramebufferAttachmentParameterivEXT(GL_DRAW_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL_EXT, &dlev);
        dStatus = gl->CheckFramebufferStatusEXT(GL_DRAW_FRAMEBUFFER_EXT);

        gl->GetFramebufferAttachmentParameterivEXT(GL_READ_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME_EXT, &rtex);
        gl->GetFramebufferAttachmentParameterivEXT(GL_READ_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL_EXT, &rlev);
        rStatus = gl->CheckFramebufferStatusEXT(GL_READ_FRAMEBUFFER_EXT);

        if (dtex)
        {
            CRASSERT(!dlev);
        }

        if (rtex)
        {
            CRASSERT(!rlev);
        }

        if (ctx->framebufferobject.drawFB)
        {
            CRASSERT(dfb);
            CRASSERT(ctx->framebufferobject.drawFB->hwid == dfb);
            CRASSERT(ctx->framebufferobject.drawFB->drawbuffer[0] == db);

            CRASSERT(dStatus==GL_FRAMEBUFFER_COMPLETE_EXT);
            CRASSERT(db==GL_COLOR_ATTACHMENT0_EXT);

            CRASSERT(ctx->framebufferobject.drawFB->color[0].type == GL_TEXTURE);
            CRASSERT(ctx->framebufferobject.drawFB->color[0].level == 0);
            sdtex = ctx->framebufferobject.drawFB->color[0].name;
            sdtex = crStateGetTextureHWID(sdtex);

            CRASSERT(sdtex);
        }
        else
        {
            CRASSERT(!dfb);
        }

        if (ctx->framebufferobject.readFB)
        {
            CRASSERT(rfb);
            CRASSERT(ctx->framebufferobject.readFB->hwid == rfb);

            CRASSERT(rStatus==GL_FRAMEBUFFER_COMPLETE_EXT);

            CRASSERT(ctx->framebufferobject.readFB->color[0].type == GL_TEXTURE);
            CRASSERT(ctx->framebufferobject.readFB->color[0].level == 0);
            srtex = ctx->framebufferobject.readFB->color[0].name;
            srtex = crStateGetTextureHWID(srtex);

            CRASSERT(srtex);
        }
        else
        {
            CRASSERT(!rfb);
        }

        CRASSERT(sdtex == dtex);
        CRASSERT(srtex == rtex);

//        crDbgDumpTexImage2D("==> src tex:", GL_TEXTURE_2D, rtex, true);
//        crDbgDumpTexImage2D("==> dst tex:", GL_TEXTURE_2D, dtex, true);

//    }
#endif
#ifdef CR_DUMP_BLITS
    SPUDispatchTable *gl = &cr_server.head_spu->dispatch_table;
    GLint rfb=0, dfb=0, dtex=0, dlev=-1, rb=0, db=0, ppb=0, pub=0, vp[4], otex, dstw, dsth;
    GLenum status;
    char fname[200];
    void *img;

    blitnum++;

    crDebug("[%i]BlitFramebufferEXT(%i, %i, %i, %i, %i, %i, %i, %i, %x, %x)", blitnum, srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter);
    crDebug("%i, %i <-> %i, %i", srcX1-srcX0, srcY1-srcY0, dstX1-dstX0, dstY1-dstY0);

    gl->GetIntegerv(GL_READ_FRAMEBUFFER_BINDING_EXT, &rfb);
    gl->GetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING_EXT, &dfb);
    gl->GetIntegerv(GL_READ_BUFFER, &rb);
    gl->GetIntegerv(GL_DRAW_BUFFER, &db);

    gl->GetIntegerv(GL_PIXEL_PACK_BUFFER_BINDING, &ppb);
    gl->GetIntegerv(GL_PIXEL_UNPACK_BUFFER_BINDING, &pub);

    gl->GetIntegerv(GL_VIEWPORT, &vp[0]);

    gl->GetIntegerv(GL_TEXTURE_BINDING_2D, &otex);

    CRASSERT(!rfb && dfb);
    gl->GetFramebufferAttachmentParameterivEXT(GL_DRAW_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME_EXT, &dtex);
    gl->GetFramebufferAttachmentParameterivEXT(GL_DRAW_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL_EXT, &dlev);
    status = gl->CheckFramebufferStatusEXT(GL_DRAW_FRAMEBUFFER_EXT);

    CRASSERT(status==GL_FRAMEBUFFER_COMPLETE_EXT
             && db==GL_COLOR_ATTACHMENT0_EXT
             && (rb==GL_FRONT || rb==GL_BACK)
             && !rfb && dfb && dtex && !dlev
             && !ppb && !pub);

    crDebug("Src[rb 0x%x, fbo %i] Dst[db 0x%x, fbo %i(0x%x), tex %i.%i]", rb, rfb, db, dfb, status, dtex, dlev);
    crDebug("Viewport [%i, %i, %i, %i]", vp[0], vp[1], vp[2], vp[3]);

    gl->PixelStorei(GL_PACK_ROW_LENGTH, 0);
    gl->PixelStorei(GL_PACK_ALIGNMENT, 1);
    gl->PixelStorei(GL_PACK_SKIP_PIXELS, 0);
    gl->PixelStorei(GL_PACK_SKIP_ROWS, 0);

    gl->PixelStorei(GL_UNPACK_ROW_LENGTH, 0);
    gl->PixelStorei(GL_UNPACK_ALIGNMENT, 1);
    gl->PixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
    gl->PixelStorei(GL_UNPACK_SKIP_ROWS, 0);

    gl->BindTexture(GL_TEXTURE_2D, dtex);
    gl->GetTexLevelParameteriv(GL_TEXTURE_2D, dlev, GL_TEXTURE_WIDTH, &dstw);
    gl->GetTexLevelParameteriv(GL_TEXTURE_2D, dlev, GL_TEXTURE_HEIGHT, &dsth);
    gl->BindTexture(GL_TEXTURE_2D, otex);
    crDebug("Dst is %i, %i", dstw, dsth);

    CRASSERT(vp[2]>=dstw && vp[3]>=dsth);
    img = crAlloc(vp[2]*vp[3]*4);
    CRASSERT(img);

    gl->ReadPixels(0, 0, vp[2], vp[3], GL_BGRA, GL_UNSIGNED_BYTE, img);
    sprintf(fname, "blit%iA_src.tga", blitnum);
    crDumpNamedTGA(fname, vp[2], vp[3], img);

    gl->BindTexture(GL_TEXTURE_2D, dtex);
    gl->GetTexImage(GL_TEXTURE_2D, dlev, GL_BGRA, GL_UNSIGNED_BYTE, img);
    sprintf(fname, "blit%iB_dst.tga", blitnum);
    crDumpNamedTGA(fname, dstw, dsth, img);
    gl->BindTexture(GL_TEXTURE_2D, otex);
#endif

    if (srcY0 > srcY1)
    {
        /* work around Intel driver bug on Linux host  */
        if (1 || dstY0 > dstY1)
        {
            /* use srcY1 < srcY2 && dstY1 < dstY2 whenever possible to avoid GPU driver bugs */
            int32_t tmp = srcY0;
            srcY0 = srcY1;
            srcY1 = tmp;
            tmp = dstY0;
            dstY0 = dstY1;
            dstY1 = tmp;
        }
    }

    if (srcX0 > srcX1)
    {
        if (dstX0 > dstX1)
        {
            /* use srcX1 < srcX2 && dstX1 < dstX2 whenever possible to avoid GPU driver bugs */
            int32_t tmp = srcX0;
            srcX0 = srcX1;
            srcX1 = tmp;
            tmp = dstX0;
            dstX0 = dstX1;
            dstX1 = tmp;
        }
    }

    if (cr_server.fBlitterMode)
    {
        fTryBlitter = true;
    }

    if (fTryBlitter)
    {
        int rc = crServerVBoxBlitterBlitCurrentCtx(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter);
        if (RT_SUCCESS(rc))
            goto my_exit;
    }

    if (ctx->viewport.scissorTest)
        cr_server.head_spu->dispatch_table.Disable(GL_SCISSOR_TEST);

    cr_server.head_spu->dispatch_table.BlitFramebufferEXT(srcX0, srcY0, srcX1, srcY1,
                                                          dstX0, dstY0, dstX1, dstY1,
                                                          mask, filter);

    if (ctx->viewport.scissorTest)
        cr_server.head_spu->dispatch_table.Enable(GL_SCISSOR_TEST);


my_exit:

//#ifdef CR_CHECK_BLITS
//    crDbgDumpTexImage2D("<== src tex:", GL_TEXTURE_2D, rtex, true);
//    crDbgDumpTexImage2D("<== dst tex:", GL_TEXTURE_2D, dtex, true);
//#endif
#ifdef CR_DUMP_BLITS
    gl->BindTexture(GL_TEXTURE_2D, dtex);
    gl->GetTexImage(GL_TEXTURE_2D, dlev, GL_BGRA, GL_UNSIGNED_BYTE, img);
    sprintf(fname, "blit%iC_res.tga", blitnum);
    crDumpNamedTGA(fname, dstw, dsth, img);
    gl->BindTexture(GL_TEXTURE_2D, otex);
    crFree(img);
#endif
    return;
}

void SERVER_DISPATCH_APIENTRY crServerDispatchDrawBuffer( GLenum mode )
{
    crStateDrawBuffer( mode );

    if (!crStateGetCurrent()->framebufferobject.drawFB)
    {
        if (mode == GL_FRONT || mode == GL_FRONT_LEFT || mode == GL_FRONT_RIGHT)
            cr_server.curClient->currentMural->bFbDraw = GL_TRUE;

        if (crServerIsRedirectedToFBO()
                && cr_server.curClient->currentMural->aidFBOs[0])
        {
            CRMuralInfo *mural = cr_server.curClient->currentMural;
            GLint iBufferNeeded = -1;
            switch (mode)
            {
                case GL_BACK:
                case GL_BACK_LEFT:
                case GL_BACK_RIGHT:
                    mode = GL_COLOR_ATTACHMENT0;
                    iBufferNeeded = CR_SERVER_FBO_BB_IDX(mural);
                    break;
                case GL_FRONT:
                case GL_FRONT_LEFT:
                case GL_FRONT_RIGHT:
                    mode = GL_COLOR_ATTACHMENT0;
                    iBufferNeeded = CR_SERVER_FBO_FB_IDX(mural);
                    break;
                case GL_NONE:
                    crDebug("DrawBuffer: GL_NONE");
                    break;
                case GL_AUX0:
                    crDebug("DrawBuffer: GL_AUX0");
                    break;
                case GL_AUX1:
                    crDebug("DrawBuffer: GL_AUX1");
                    break;
                case GL_AUX2:
                    crDebug("DrawBuffer: GL_AUX2");
                    break;
                case GL_AUX3:
                    crDebug("DrawBuffer: GL_AUX3");
                    break;
                case GL_LEFT:
                    crWarning("DrawBuffer: GL_LEFT not supported properly");
                    mode = GL_COLOR_ATTACHMENT0;
                    iBufferNeeded = CR_SERVER_FBO_BB_IDX(mural);
                    break;
                case GL_RIGHT:
                    crWarning("DrawBuffer: GL_RIGHT not supported properly");
                    mode = GL_COLOR_ATTACHMENT0;
                    iBufferNeeded = CR_SERVER_FBO_BB_IDX(mural);
                    break;
                case GL_FRONT_AND_BACK:
                    crWarning("DrawBuffer: GL_FRONT_AND_BACK not supported properly");
                    mode = GL_COLOR_ATTACHMENT0;
                    iBufferNeeded = CR_SERVER_FBO_BB_IDX(mural);
                    break;
                default:
                    crWarning("DrawBuffer: unexpected mode! 0x%x", mode);
                    iBufferNeeded = mural->iCurDrawBuffer;
                    break;
            }

            if (iBufferNeeded != mural->iCurDrawBuffer)
            {
                mural->iCurDrawBuffer = iBufferNeeded;
                cr_server.head_spu->dispatch_table.BindFramebufferEXT(GL_DRAW_FRAMEBUFFER, CR_SERVER_FBO_FOR_IDX(mural, iBufferNeeded));
            }
        }
    }

    cr_server.head_spu->dispatch_table.DrawBuffer( mode );
}

void SERVER_DISPATCH_APIENTRY crServerDispatchReadBuffer( GLenum mode )
{
    crStateReadBuffer( mode );

    if (crServerIsRedirectedToFBO()
            && cr_server.curClient->currentMural->aidFBOs[0]
            && !crStateGetCurrent()->framebufferobject.readFB)
    {
        CRMuralInfo *mural = cr_server.curClient->currentMural;
        GLint iBufferNeeded = -1;
        switch (mode)
        {
            case GL_BACK:
            case GL_BACK_LEFT:
            case GL_BACK_RIGHT:
                mode = GL_COLOR_ATTACHMENT0;
                iBufferNeeded = CR_SERVER_FBO_BB_IDX(mural);
                break;
            case GL_FRONT:
            case GL_FRONT_LEFT:
            case GL_FRONT_RIGHT:
                mode = GL_COLOR_ATTACHMENT0;
                iBufferNeeded = CR_SERVER_FBO_FB_IDX(mural);
                break;
            case GL_NONE:
                crDebug("ReadBuffer: GL_NONE");
                break;
            case GL_AUX0:
                crDebug("ReadBuffer: GL_AUX0");
                break;
            case GL_AUX1:
                crDebug("ReadBuffer: GL_AUX1");
                break;
            case GL_AUX2:
                crDebug("ReadBuffer: GL_AUX2");
                break;
            case GL_AUX3:
                crDebug("ReadBuffer: GL_AUX3");
                break;
            case GL_LEFT:
                crWarning("ReadBuffer: GL_LEFT not supported properly");
                mode = GL_COLOR_ATTACHMENT0;
                iBufferNeeded = CR_SERVER_FBO_BB_IDX(mural);
                break;
            case GL_RIGHT:
                crWarning("ReadBuffer: GL_RIGHT not supported properly");
                mode = GL_COLOR_ATTACHMENT0;
                iBufferNeeded = CR_SERVER_FBO_BB_IDX(mural);
                break;
            case GL_FRONT_AND_BACK:
                crWarning("ReadBuffer: GL_FRONT_AND_BACK not supported properly");
                mode = GL_COLOR_ATTACHMENT0;
                iBufferNeeded = CR_SERVER_FBO_BB_IDX(mural);
                break;
            default:
                crWarning("ReadBuffer: unexpected mode! 0x%x", mode);
                iBufferNeeded = mural->iCurDrawBuffer;
                break;
        }

        Assert(CR_SERVER_FBO_FOR_IDX(mural, mural->iCurReadBuffer));
        if (iBufferNeeded != mural->iCurReadBuffer)
        {
            mural->iCurReadBuffer = iBufferNeeded;
            cr_server.head_spu->dispatch_table.BindFramebufferEXT(GL_READ_FRAMEBUFFER, CR_SERVER_FBO_FOR_IDX(mural, iBufferNeeded));
        }
    }
    cr_server.head_spu->dispatch_table.ReadBuffer( mode );
}

GLenum SERVER_DISPATCH_APIENTRY crServerDispatchGetError( void )
{
    GLenum retval, err;
    CRContext *ctx = crStateGetCurrent();
    retval = ctx->error;

    err = cr_server.head_spu->dispatch_table.GetError();
    if (retval == GL_NO_ERROR)
        retval = err;
    else
        ctx->error = GL_NO_ERROR;

    /* our impl has a single error flag, so we just loop here to reset all error flags to no_error */
    while (err != GL_NO_ERROR)
        err = cr_server.head_spu->dispatch_table.GetError();

    crServerReturnValue( &retval, sizeof(retval) );
    return retval; /* WILL PROBABLY BE IGNORED */
}

void SERVER_DISPATCH_APIENTRY
crServerMakeTmpCtxCurrent( GLint window, GLint nativeWindow, GLint context )
{
    CRContext *pCtx = crStateGetCurrent();
    CRContext *pCurCtx = NULL;
    GLuint idDrawFBO = 0, idReadFBO = 0;
    int fDoPrePostProcess = 0;

    if (pCtx)
    {
        CRMuralInfo *pCurrentMural = cr_server.currentMural;

        pCurCtx = cr_server.currentCtxInfo ? cr_server.currentCtxInfo->pContext : cr_server.MainContextInfo.pContext;
        Assert(pCurCtx == pCtx);

        if (!context)
        {
            if (pCurrentMural)
            {
                Assert(cr_server.currentCtxInfo);
                context = cr_server.currentCtxInfo->SpuContext > 0 ? cr_server.currentCtxInfo->SpuContext : cr_server.MainContextInfo.SpuContext;
                window = pCurrentMural->spuWindow;
            }
            else
            {
                CRMuralInfo * pDummy;
                Assert(!cr_server.currentCtxInfo);
                pDummy = crServerGetDummyMural(cr_server.MainContextInfo.CreateInfo.realVisualBits);
                context = cr_server.MainContextInfo.SpuContext;
                window = pDummy->spuWindow;
            }


            fDoPrePostProcess = -1;
        }
        else
        {
            fDoPrePostProcess = 1;
        }

        if (pCurrentMural)
        {
            idDrawFBO = CR_SERVER_FBO_FOR_IDX(pCurrentMural, pCurrentMural->iCurDrawBuffer);
            idReadFBO = CR_SERVER_FBO_FOR_IDX(pCurrentMural, pCurrentMural->iCurReadBuffer);
        }
        else
        {
            idDrawFBO = 0;
            idReadFBO = 0;
        }
    }
    else
    {
        /* this is a GUI thread, so no need to do anything here */
    }

    if (fDoPrePostProcess > 0)
        crStateSwitchPrepare(NULL, pCurCtx, idDrawFBO, idReadFBO);

    cr_server.head_spu->dispatch_table.MakeCurrent( window, nativeWindow, context);

    if (fDoPrePostProcess < 0)
        crStateSwitchPostprocess(pCurCtx, NULL, idDrawFBO, idReadFBO);
}

void crServerInitTmpCtxDispatch()
{
    MakeCurrentFunc_t pfnMakeCurrent;

    crSPUInitDispatchTable(&cr_server.TmpCtxDispatch);
    crSPUCopyDispatchTable(&cr_server.TmpCtxDispatch, &cr_server.head_spu->dispatch_table);
    cr_server.TmpCtxDispatch.MakeCurrent = crServerMakeTmpCtxCurrent;

    pfnMakeCurrent = crServerMakeTmpCtxCurrent;
    cr_server.head_spu->dispatch_table.ChromiumParametervCR(GL_HH_SET_TMPCTX_MAKE_CURRENT, GL_BYTE, sizeof (void*), &pfnMakeCurrent);

}

/* dump stuff */
#ifdef VBOX_WITH_CRSERVER_DUMPER

/* first four bits are buffer dump config
 * second four bits are texture dump config
 * config flags:
 * 1 - blit on enter
 * 2 - blit on exit
 *
 *
 * Example:
 *
 * 0x03 - dump buffer on enter and exit
 * 0x22 - dump texture and buffer on exit */

int64_t g_CrDbgDumpPid = 0;
unsigned long g_CrDbgDumpEnabled = 0;
unsigned long g_CrDbgDumpDraw = 0
#if 0
        | CR_SERVER_DUMP_F_COMPILE_SHADER
        | CR_SERVER_DUMP_F_LINK_PROGRAM
#endif
        ;
#if 0
        | CR_SERVER_DUMP_F_DRAW_BUFF_ENTER
        | CR_SERVER_DUMP_F_DRAW_BUFF_LEAVE
        | CR_SERVER_DUMP_F_DRAW_PROGRAM_UNIFORMS_ENTER
        | CR_SERVER_DUMP_F_DRAW_PROGRAM_ATTRIBS_ENTER
        | CR_SERVER_DUMP_F_DRAW_TEX_ENTER
        | CR_SERVER_DUMP_F_DRAW_PROGRAM_ENTER
        | CR_SERVER_DUMP_F_DRAW_STATE_ENTER
        | CR_SERVER_DUMP_F_SWAPBUFFERS_ENTER
        | CR_SERVER_DUMP_F_DRAWEL
        | CR_SERVER_DUMP_F_SHADER_SOURCE
        ;
#endif
unsigned long g_CrDbgDumpDrawFramesSettings = CR_SERVER_DUMP_F_DRAW_BUFF_ENTER
        | CR_SERVER_DUMP_F_DRAW_BUFF_LEAVE
        | CR_SERVER_DUMP_F_DRAW_TEX_ENTER
        | CR_SERVER_DUMP_F_DRAW_PROGRAM_ENTER
        | CR_SERVER_DUMP_F_COMPILE_SHADER
        | CR_SERVER_DUMP_F_LINK_PROGRAM
        | CR_SERVER_DUMP_F_SWAPBUFFERS_ENTER;
unsigned long g_CrDbgDumpDrawFramesAppliedSettings = 0;
unsigned long g_CrDbgDumpDrawFramesSavedInitSettings = 0;
unsigned long g_CrDbgDumpDrawFramesCount = 0;

uint32_t g_CrDbgDumpDrawCount = 0;
uint32_t g_CrDbgDumpDumpOnCount = 10;
uint32_t g_CrDbgDumpDumpOnCountEnabled = 0;
uint32_t g_CrDbgDumpDumpOnCountPerform = 0;
uint32_t g_CrDbgDumpDrawFlags = CR_SERVER_DUMP_F_COMPILE_SHADER
        | CR_SERVER_DUMP_F_SHADER_SOURCE
        | CR_SERVER_DUMP_F_COMPILE_SHADER
        | CR_SERVER_DUMP_F_LINK_PROGRAM
        | CR_SERVER_DUMP_F_DRAW_BUFF_ENTER
        | CR_SERVER_DUMP_F_DRAW_BUFF_LEAVE
        | CR_SERVER_DUMP_F_DRAW_TEX_ENTER
        | CR_SERVER_DUMP_F_DRAW_PROGRAM_UNIFORMS_ENTER
        | CR_SERVER_DUMP_F_DRAW_PROGRAM_ATTRIBS_ENTER
        | CR_SERVER_DUMP_F_DRAW_PROGRAM_ENTER
        | CR_SERVER_DUMP_F_DRAW_STATE_ENTER
        | CR_SERVER_DUMP_F_SWAPBUFFERS_ENTER
        | CR_SERVER_DUMP_F_DRAWEL
        | CR_SERVER_DUMP_F_TEXPRESENT;

void crServerDumpCheckTerm()
{
    if (!CrBltIsInitialized(&cr_server.RecorderBlitter))
        return;

    CrBltTerm(&cr_server.RecorderBlitter);
}

int crServerDumpCheckInit()
{
    int rc;
    CR_BLITTER_WINDOW BltWin;
    CR_BLITTER_CONTEXT BltCtx;
    CRMuralInfo *pBlitterMural;

    if (!CrBltIsInitialized(&cr_server.RecorderBlitter))
    {
        pBlitterMural = crServerGetDummyMural(cr_server.MainContextInfo.CreateInfo.realVisualBits);
        if (!pBlitterMural)
        {
            crWarning("crServerGetDummyMural failed");
            return VERR_GENERAL_FAILURE;
        }

        crServerVBoxBlitterWinInit(&BltWin, pBlitterMural);
        crServerVBoxBlitterCtxInit(&BltCtx, &cr_server.MainContextInfo);

        rc = CrBltInit(&cr_server.RecorderBlitter, &BltCtx, true, true, NULL, &cr_server.TmpCtxDispatch);
        if (!RT_SUCCESS(rc))
        {
            crWarning("CrBltInit failed rc %d", rc);
            return rc;
        }

        rc = CrBltMuralSetCurrentInfo(&cr_server.RecorderBlitter, &BltWin);
        if (!RT_SUCCESS(rc))
        {
            crWarning("CrBltMuralSetCurrentInfo failed rc %d", rc);
            return rc;
        }
    }

#if 0
    crDmpDbgPrintInit(&cr_server.DbgPrintDumper);
    cr_server.pDumper = &cr_server.DbgPrintDumper.Base;
#else
    if (!crDmpHtmlIsInited(&cr_server.HtmlDumper))
    {
        static int cCounter = 0;
//    crDmpHtmlInit(&cr_server.HtmlDumper, "S:\\projects\\virtualbox\\3d\\dumps\\1", "index.html");
        crDmpHtmlInitF(&cr_server.HtmlDumper, "/Users/oracle-mac/vbox/dump/1", "index%d.html", cCounter);
        cr_server.pDumper = &cr_server.HtmlDumper.Base;
        ++cCounter;
    }
#endif

    crRecInit(&cr_server.Recorder, &cr_server.RecorderBlitter, &cr_server.TmpCtxDispatch, cr_server.pDumper);
    return VINF_SUCCESS;
}

void crServerDumpShader(GLint id)
{
    CRContext *ctx = crStateGetCurrent();
    crRecDumpShader(&cr_server.Recorder, ctx, id, 0);
}

void crServerDumpProgram(GLint id)
{
    CRContext *ctx = crStateGetCurrent();
    crRecDumpProgram(&cr_server.Recorder, ctx, id, 0);
}

void crServerDumpCurrentProgram()
{
    CRContext *ctx = crStateGetCurrent();
    crRecDumpCurrentProgram(&cr_server.Recorder, ctx);
}

void crServerDumpRecompileDumpCurrentProgram()
{
    crDmpStrF(cr_server.Recorder.pDumper, "==Dump(1)==");
    crServerRecompileCurrentProgram();
    crServerDumpCurrentProgramUniforms();
    crServerDumpCurrentProgramAttribs();
    crDmpStrF(cr_server.Recorder.pDumper, "Done Dump(1)");
    crServerRecompileCurrentProgram();
    crDmpStrF(cr_server.Recorder.pDumper, "Dump(2)");
    crServerRecompileCurrentProgram();
    crServerDumpCurrentProgramUniforms();
    crServerDumpCurrentProgramAttribs();
    crDmpStrF(cr_server.Recorder.pDumper, "Done Dump(2)");
}

void crServerRecompileCurrentProgram()
{
    CRContext *ctx = crStateGetCurrent();
    crRecRecompileCurrentProgram(&cr_server.Recorder, ctx);
}

void crServerDumpCurrentProgramUniforms()
{
    CRContext *ctx = crStateGetCurrent();
    crDmpStrF(cr_server.Recorder.pDumper, "==Uniforms==");
    crRecDumpCurrentProgramUniforms(&cr_server.Recorder, ctx);
    crDmpStrF(cr_server.Recorder.pDumper, "==Done Uniforms==");
}

void crServerDumpCurrentProgramAttribs()
{
    CRContext *ctx = crStateGetCurrent();
    crDmpStrF(cr_server.Recorder.pDumper, "==Attribs==");
    crRecDumpCurrentProgramAttribs(&cr_server.Recorder, ctx);
    crDmpStrF(cr_server.Recorder.pDumper, "==Done Attribs==");
}

void crServerDumpState()
{
    CRContext *ctx = crStateGetCurrent();
    crRecDumpGlGetState(&cr_server.Recorder, ctx);
    crRecDumpGlEnableState(&cr_server.Recorder, ctx);
}

void crServerDumpDrawel(const char*pszFormat, ...)
{
    CRContext *ctx = crStateGetCurrent();
    va_list pArgList;
    va_start(pArgList, pszFormat);
    crRecDumpVertAttrV(&cr_server.Recorder, ctx, pszFormat, pArgList);
    va_end(pArgList);
}

void crServerDumpDrawelv(GLuint idx, const char*pszElFormat, uint32_t cbEl, const void *pvVal, uint32_t cVal)
{
    CRContext *ctx = crStateGetCurrent();
    crRecDumpVertAttrv(&cr_server.Recorder, ctx, idx, pszElFormat, cbEl, pvVal, cVal);
}

void crServerDumpBuffer(int idx)
{
    CRContextInfo *pCtxInfo = cr_server.currentCtxInfo;
    CR_BLITTER_WINDOW BltWin;
    CR_BLITTER_CONTEXT BltCtx;
    CRContext *ctx = crStateGetCurrent();
    GLint idFBO;
    GLint idTex;
    VBOXVR_TEXTURE RedirTex;
    int rc = crServerDumpCheckInit();
    idx = idx >= 0 ? idx : crServerMuralFBOIdxFromBufferName(cr_server.currentMural, pCtxInfo->pContext->buffer.drawBuffer);
    if (!RT_SUCCESS(rc))
    {
        crWarning("crServerDumpCheckInit failed, rc %d", rc);
        return;
    }

    if (idx < 0)
    {
        crWarning("neg idx, unsupported");
        return;
    }

    idFBO = CR_SERVER_FBO_FOR_IDX(cr_server.currentMural, idx);
    idTex = CR_SERVER_FBO_TEX_FOR_IDX(cr_server.currentMural, idx);

    crServerVBoxBlitterWinInit(&BltWin, cr_server.currentMural);
    crServerVBoxBlitterCtxInit(&BltCtx, pCtxInfo);

    RedirTex.width = cr_server.currentMural->fboWidth;
    RedirTex.height = cr_server.currentMural->fboHeight;
    RedirTex.target = GL_TEXTURE_2D;
    RedirTex.hwid = idTex;

    crRecDumpBuffer(&cr_server.Recorder, ctx, &BltCtx, &BltWin, idFBO, idTex ? &RedirTex : NULL);
}

void crServerDumpTexture(const VBOXVR_TEXTURE *pTex)
{
    CRContextInfo *pCtxInfo = cr_server.currentCtxInfo;
    CR_BLITTER_WINDOW BltWin;
    CR_BLITTER_CONTEXT BltCtx;
    CRContext *ctx = crStateGetCurrent();
    int rc = crServerDumpCheckInit();
    if (!RT_SUCCESS(rc))
    {
        crWarning("crServerDumpCheckInit failed, rc %d", rc);
        return;
    }

    crServerVBoxBlitterWinInit(&BltWin, cr_server.currentMural);
    crServerVBoxBlitterCtxInit(&BltCtx, pCtxInfo);

    crRecDumpTextureF(&cr_server.Recorder, pTex, &BltCtx, &BltWin, "Tex (%d x %d), hwid (%d) target %#x", pTex->width, pTex->height, pTex->hwid, pTex->target);
}

void crServerDumpTextures()
{
    CRContextInfo *pCtxInfo = cr_server.currentCtxInfo;
    CR_BLITTER_WINDOW BltWin;
    CR_BLITTER_CONTEXT BltCtx;
    CRContext *ctx = crStateGetCurrent();
    int rc = crServerDumpCheckInit();
    if (!RT_SUCCESS(rc))
    {
        crWarning("crServerDumpCheckInit failed, rc %d", rc);
        return;
    }

    crServerVBoxBlitterWinInit(&BltWin, cr_server.currentMural);
    crServerVBoxBlitterCtxInit(&BltCtx, pCtxInfo);

    crRecDumpTextures(&cr_server.Recorder, ctx, &BltCtx, &BltWin);
}

void crServerDumpFilterOpLeave(unsigned long event, CR_DUMPER *pDumper)
{
    if (CR_SERVER_DUMP_F_DRAW_LEAVE_ALL & event)
    {
        g_CrDbgDumpDumpOnCountPerform = 0;
    }
}

bool crServerDumpFilterOpEnter(unsigned long event, CR_DUMPER *pDumper)
{
    if ((CR_SERVER_DUMP_F_SWAPBUFFERS_ENTER & event)
            || (CR_SERVER_DUMP_F_TEXPRESENT & event))
    {
        if (g_CrDbgDumpDumpOnCountEnabled == 1)
            g_CrDbgDumpDumpOnCountEnabled = 2;
        else if (g_CrDbgDumpDumpOnCountEnabled)
        {
            g_CrDbgDumpDumpOnCountEnabled = 0;
            if (cr_server.pDumper == &cr_server.HtmlDumper.Base)
            {
                crDmpHtmlTerm(&cr_server.HtmlDumper);
                cr_server.pDumper = NULL;
            }
        }

        g_CrDbgDumpDrawCount = 0;
    }
    else if (CR_SERVER_DUMP_F_DRAW_ENTER_ALL & event)
    {
        if (g_CrDbgDumpDumpOnCountEnabled == 2)
        {
            if (g_CrDbgDumpDumpOnCount == g_CrDbgDumpDrawCount)
            {
                g_CrDbgDumpDumpOnCountPerform = 1;
            }
            ++g_CrDbgDumpDrawCount;
        }
    }
    if (g_CrDbgDumpDumpOnCountPerform)
    {
        if (g_CrDbgDumpDrawFlags & event)
            return true;
    }
    return CR_SERVER_DUMP_DEFAULT_FILTER_OP(event);
}

bool crServerDumpFilterDmp(unsigned long event, CR_DUMPER *pDumper)
{
    if (g_CrDbgDumpDumpOnCountPerform)
    {
        if (g_CrDbgDumpDrawFlags & event)
            return true;
    }
    return CR_SERVER_DUMP_DEFAULT_FILTER_DMP(event);
}

void crServerDumpFramesCheck()
{
    if (!g_CrDbgDumpDrawFramesCount)
        return;

    if (!g_CrDbgDumpDrawFramesAppliedSettings)
    {
        if (!g_CrDbgDumpDrawFramesSettings)
        {
            crWarning("g_CrDbgDumpDrawFramesSettings is NULL, bump will not be started");
            g_CrDbgDumpDrawFramesCount = 0;
            return;
        }

        g_CrDbgDumpDrawFramesSavedInitSettings = g_CrDbgDumpDraw;
        g_CrDbgDumpDrawFramesAppliedSettings = g_CrDbgDumpDrawFramesSettings;
        g_CrDbgDumpDraw = g_CrDbgDumpDrawFramesSettings;
        crDmpStrF(cr_server.Recorder.pDumper, "***Starting draw dump for %d frames, settings(0x%x)", g_CrDbgDumpDrawFramesCount, g_CrDbgDumpDraw);
        return;
    }

    --g_CrDbgDumpDrawFramesCount;

    if (!g_CrDbgDumpDrawFramesCount)
    {
        crDmpStrF(cr_server.Recorder.pDumper, "***Stop draw dump");
        g_CrDbgDumpDraw = g_CrDbgDumpDrawFramesSavedInitSettings;
        g_CrDbgDumpDrawFramesAppliedSettings = 0;
    }
}
#endif

GLvoid crServerSpriteCoordReplEnable(GLboolean fEnable)
{
    CRContext *g = crStateGetCurrent();
    CRTextureState *t = &(g->texture);
    GLuint curTextureUnit = t->curTextureUnit;
    GLuint curTextureUnitRestore = curTextureUnit;
    GLuint i;

    for (i = 0; i < g->limits.maxTextureUnits; ++i)
    {
        if (g->point.coordReplacement[i])
        {
            if (i != curTextureUnit)
            {
                curTextureUnit = i;
                cr_server.head_spu->dispatch_table.ActiveTextureARB( i + GL_TEXTURE0_ARB );
            }

            cr_server.head_spu->dispatch_table.TexEnvi(GL_POINT_SPRITE, GL_COORD_REPLACE, (GLint)fEnable);
        }
    }

    if (curTextureUnit != curTextureUnitRestore)
    {
        cr_server.head_spu->dispatch_table.ActiveTextureARB( curTextureUnitRestore + GL_TEXTURE0_ARB );
    }
}

GLvoid SERVER_DISPATCH_APIENTRY crServerDispatchDrawArrays(GLenum mode, GLint first, GLsizei count)
{
#ifdef DEBUG
    GLenum status = cr_server.head_spu->dispatch_table.CheckFramebufferStatusEXT(GL_DRAW_FRAMEBUFFER_EXT);
    Assert(GL_FRAMEBUFFER_COMPLETE == status);
#endif
    if (mode == GL_POINTS)
        crServerSpriteCoordReplEnable(GL_TRUE);
    CR_SERVER_DUMP_DRAW_ENTER();
    CR_GLERR_CHECK(cr_server.head_spu->dispatch_table.DrawArrays(mode, first, count););
    CR_SERVER_DUMP_DRAW_LEAVE();
    if (mode == GL_POINTS)
        crServerSpriteCoordReplEnable(GL_FALSE);
}

GLvoid SERVER_DISPATCH_APIENTRY crServerDispatchDrawElements(GLenum mode,  GLsizei count,  GLenum type,  const GLvoid * indices)
{
#ifdef DEBUG
    GLenum status = cr_server.head_spu->dispatch_table.CheckFramebufferStatusEXT(GL_DRAW_FRAMEBUFFER_EXT);
    Assert(GL_FRAMEBUFFER_COMPLETE == status);
#endif
    if (mode == GL_POINTS)
        crServerSpriteCoordReplEnable(GL_TRUE);
    CR_SERVER_DUMP_DRAW_ENTER();
    CR_GLERR_CHECK(cr_server.head_spu->dispatch_table.DrawElements(mode, count, type, indices););
    CR_SERVER_DUMP_DRAW_LEAVE();
    if (mode == GL_POINTS)
        crServerSpriteCoordReplEnable(GL_FALSE);
}

void SERVER_DISPATCH_APIENTRY crServerDispatchEnd( void )
{
    CRContext *g = crStateGetCurrent();
    GLenum mode = g->current.mode;

    crStateEnd();
    cr_server.head_spu->dispatch_table.End();

    CR_SERVER_DUMP_DRAW_LEAVE();

    if (mode == GL_POINTS)
        crServerSpriteCoordReplEnable(GL_FALSE);
}

void SERVER_DISPATCH_APIENTRY crServerDispatchBegin(GLenum mode)
{
#ifdef DEBUG
    CRContext *ctx = crStateGetCurrent();
    SPUDispatchTable *gl = &cr_server.head_spu->dispatch_table;

    if (ctx->program.vpProgramBinding)
    {
        AssertRelease(ctx->program.currentVertexProgram);

        if (ctx->program.currentVertexProgram->isARBprogram)
        {
            GLint pid=-1;
            gl->GetProgramivARB(GL_VERTEX_PROGRAM_ARB, GL_PROGRAM_BINDING_ARB, &pid);

            if (pid != ctx->program.currentVertexProgram->id)
            {
                crWarning("pid(%d) != ctx->program.currentVertexProgram->id(%d)", pid, ctx->program.currentVertexProgram->id);
            }
            AssertRelease(pid == ctx->program.currentVertexProgram->id);
        }
        else
        {
            GLint pid=-1;

            gl->GetIntegerv(GL_VERTEX_PROGRAM_BINDING_NV, &pid);
            if (pid != ctx->program.currentVertexProgram->id)
            {
                crWarning("pid(%d) != ctx->program.currentVertexProgram->id(%d)", pid, ctx->program.currentVertexProgram->id);
            }
            AssertRelease(pid == ctx->program.currentVertexProgram->id);
        }
    }
    else if (ctx->glsl.activeProgram)
    {
        GLint pid=-1;

        gl->GetIntegerv(GL_CURRENT_PROGRAM, &pid);
        crDebug("pid %i, state: id %i, hwid %i", pid, ctx->glsl.activeProgram->id, ctx->glsl.activeProgram->hwid);
        if (pid != ctx->glsl.activeProgram->hwid)
        {
            crWarning("pid(%d) != ctx->glsl.activeProgram->hwid(%d)", pid, ctx->glsl.activeProgram->hwid);
        }
        AssertRelease(pid == ctx->glsl.activeProgram->hwid);
    }
#endif

    if (mode == GL_POINTS)
        crServerSpriteCoordReplEnable(GL_TRUE);

    CR_SERVER_DUMP_DRAW_ENTER();

    crStateBegin(mode);
    cr_server.head_spu->dispatch_table.Begin(mode);
}