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
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
/* DirectDraw Surface Implementation
 *
 * Copyright (c) 1997-2000 Marcus Meissner
 * Copyright (c) 1998-2000 Lionel Ulmer
 * Copyright (c) 2000-2001 TransGaming Technologies Inc.
 * Copyright (c) 2006 Stefan Dösinger
 * Copyright (c) 2011 Ričardas Barkauskas for CodeWeavers
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
 */

#include "config.h"
#include "wine/port.h"

#include "ddraw_private.h"

WINE_DEFAULT_DEBUG_CHANNEL(ddraw);

static struct ddraw_surface *unsafe_impl_from_IDirectDrawSurface2(IDirectDrawSurface2 *iface);
static struct ddraw_surface *unsafe_impl_from_IDirectDrawSurface3(IDirectDrawSurface3 *iface);

static inline struct ddraw_surface *impl_from_IDirectDrawGammaControl(IDirectDrawGammaControl *iface)
{
    return CONTAINING_RECORD(iface, struct ddraw_surface, IDirectDrawGammaControl_iface);
}

/* This is slow, of course. Also, in case of locks, we can't prevent other
 * applications from drawing to the screen while we've locked the frontbuffer.
 * We'd like to do this in wined3d instead, but for that to work wined3d needs
 * to support windowless rendering first. */
HRESULT ddraw_surface_update_frontbuffer(struct ddraw_surface *surface, const RECT *rect, BOOL read)
{
    struct ddraw *ddraw = surface->ddraw;
    HDC surface_dc, screen_dc;
    int x, y, w, h;
    HRESULT hr;
    BOOL ret;
    RECT r;

    if (!rect)
    {
        SetRect(&r, 0, 0, surface->surface_desc.dwWidth, surface->surface_desc.dwHeight);
        rect = &r;
    }

    x = rect->left;
    y = rect->top;
    w = rect->right - rect->left;
    h = rect->bottom - rect->top;

    if (w <= 0 || h <= 0)
        return DD_OK;

    if (ddraw->swapchain_window && !(ddraw->flags & DDRAW_GDI_FLIP))
    {
        /* Nothing to do, we control the frontbuffer, or at least the parts we
         * care about. */
        if (read)
            return DD_OK;

        return wined3d_texture_blt(ddraw->wined3d_frontbuffer, 0, rect,
                surface->wined3d_texture, surface->sub_resource_idx, rect, 0, NULL, WINED3D_TEXF_POINT);
    }

    if (FAILED(hr = wined3d_texture_get_dc(surface->wined3d_texture, surface->sub_resource_idx, &surface_dc)))
    {
        ERR("Failed to get surface DC, hr %#x.\n", hr);
        return hr;
    }
    if (surface->palette)
        wined3d_palette_apply_to_dc(surface->palette->wined3d_palette, surface_dc);

    if (!(screen_dc = GetDC(NULL)))
    {
        wined3d_texture_release_dc(surface->wined3d_texture, surface->sub_resource_idx, surface_dc);
        ERR("Failed to get screen DC.\n");
        return E_FAIL;
    }

    if (read)
        ret = BitBlt(surface_dc, x, y, w, h,
                screen_dc, x, y, SRCCOPY);
    else
        ret = BitBlt(screen_dc, x, y, w, h,
                surface_dc, x, y, SRCCOPY);

    ReleaseDC(NULL, screen_dc);
    wined3d_texture_release_dc(surface->wined3d_texture, surface->sub_resource_idx, surface_dc);

    if (!ret)
    {
        ERR("Failed to blit to/from screen.\n");
        return E_FAIL;
    }

    return DD_OK;
}

/*****************************************************************************
 * IUnknown parts follow
 *****************************************************************************/

/*****************************************************************************
 * IDirectDrawSurface7::QueryInterface
 *
 * A normal QueryInterface implementation. For QueryInterface rules
 * see ddraw.c, IDirectDraw7::QueryInterface. This method
 * can Query IDirectDrawSurface interfaces in all version, IDirect3DTexture
 * in all versions, the IDirectDrawGammaControl interface and it can
 * create an IDirect3DDevice. (Uses IDirect3D7::CreateDevice)
 *
 * Params:
 *  riid: The interface id queried for
 *  obj: Address to write the pointer to
 *
 * Returns:
 *  S_OK on success
 *  E_NOINTERFACE if the requested interface wasn't found
 *
 *****************************************************************************/
static HRESULT WINAPI ddraw_surface7_QueryInterface(IDirectDrawSurface7 *iface, REFIID riid, void **obj)
{
    struct ddraw_surface *This = impl_from_IDirectDrawSurface7(iface);

    TRACE("iface %p, riid %s, object %p.\n", iface, debugstr_guid(riid), obj);

    /* According to COM docs, if the QueryInterface fails, obj should be set to NULL */
    *obj = NULL;

    if(!riid)
        return DDERR_INVALIDPARAMS;

    if (IsEqualGUID(riid, &IID_IDirectDrawSurface7))
    {
        IDirectDrawSurface7_AddRef(iface);
        *obj = iface;
        TRACE("(%p) returning IDirectDrawSurface7 interface at %p\n", This, *obj);
        return S_OK;
    }

    if (IsEqualGUID(riid, &IID_IDirectDrawSurface4))
    {
        IDirectDrawSurface4_AddRef(&This->IDirectDrawSurface4_iface);
        *obj = &This->IDirectDrawSurface4_iface;
        TRACE("(%p) returning IDirectDrawSurface4 interface at %p\n", This, *obj);
        return S_OK;
    }

    if (IsEqualGUID(riid, &IID_IDirectDrawSurface3))
    {
        IDirectDrawSurface3_AddRef(&This->IDirectDrawSurface3_iface);
        *obj = &This->IDirectDrawSurface3_iface;
        TRACE("(%p) returning IDirectDrawSurface3 interface at %p\n", This, *obj);
        return S_OK;
    }

    if (IsEqualGUID(riid, &IID_IDirectDrawSurface2))
    {
        IDirectDrawSurface2_AddRef(&This->IDirectDrawSurface2_iface);
        *obj = &This->IDirectDrawSurface2_iface;
        TRACE("(%p) returning IDirectDrawSurface2 interface at %p\n", This, *obj);
        return S_OK;
    }

    if (IsEqualGUID(riid, &IID_IDirectDrawSurface)
            || IsEqualGUID(riid, &IID_IUnknown))
    {
        IDirectDrawSurface_AddRef(&This->IDirectDrawSurface_iface);
        *obj = &This->IDirectDrawSurface_iface;
        TRACE("(%p) returning IDirectDrawSurface interface at %p\n", This, *obj);
        return S_OK;
    }

    if (IsEqualGUID(riid, &IID_IDirectDrawGammaControl))
    {
        IDirectDrawGammaControl_AddRef(&This->IDirectDrawGammaControl_iface);
        *obj = &This->IDirectDrawGammaControl_iface;
        TRACE("(%p) returning IDirectDrawGammaControl interface at %p\n", This, *obj);
        return S_OK;
    }

    if (IsEqualGUID(riid, &IID_IDirectDrawColorControl))
    {
        WARN("Color control not implemented.\n");
        *obj = NULL;
        return E_NOINTERFACE;
    }

    if (This->version != 7)
    {
        if (IsEqualGUID(riid, &IID_D3DDEVICE_WineD3D)
                || IsEqualGUID(riid, &IID_IDirect3DHALDevice)
                || IsEqualGUID(riid, &IID_IDirect3DRGBDevice))
        {
            wined3d_mutex_lock();
            if (!This->device1)
            {
                HRESULT hr;

                if (FAILED(hr = d3d_device_create(This->ddraw, riid, This, (IUnknown *)&This->IDirectDrawSurface_iface,
                        1, &This->device1, (IUnknown *)&This->IDirectDrawSurface_iface)))
                {
                    This->device1 = NULL;
                    wined3d_mutex_unlock();
                    WARN("Failed to create device, hr %#x.\n", hr);
                    return hr;
                }
            }
            wined3d_mutex_unlock();

            IDirect3DDevice_AddRef(&This->device1->IDirect3DDevice_iface);
            *obj = &This->device1->IDirect3DDevice_iface;
            return S_OK;
        }

        if (IsEqualGUID(&IID_IDirect3DTexture2, riid))
        {
            IDirect3DTexture2_AddRef(&This->IDirect3DTexture2_iface);
            *obj = &This->IDirect3DTexture2_iface;
            return S_OK;
        }

        if (IsEqualGUID( &IID_IDirect3DTexture, riid ))
        {
            IDirect3DTexture2_AddRef(&This->IDirect3DTexture_iface);
            *obj = &This->IDirect3DTexture_iface;
            return S_OK;
        }
    }

    WARN("%s not implemented, returning E_NOINTERFACE.\n", debugstr_guid(riid));

    if (This->version != 7)
        return E_INVALIDARG;

    return E_NOINTERFACE;
}

static HRESULT WINAPI ddraw_surface4_QueryInterface(IDirectDrawSurface4 *iface, REFIID riid, void **object)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface4(iface);

    TRACE("iface %p, riid %s, object %p.\n", iface, debugstr_guid(riid), object);

    return ddraw_surface7_QueryInterface(&surface->IDirectDrawSurface7_iface, riid, object);
}

static HRESULT WINAPI ddraw_surface3_QueryInterface(IDirectDrawSurface3 *iface, REFIID riid, void **object)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface3(iface);

    TRACE("iface %p, riid %s, object %p.\n", iface, debugstr_guid(riid), object);

    return ddraw_surface7_QueryInterface(&surface->IDirectDrawSurface7_iface, riid, object);
}

static HRESULT WINAPI ddraw_surface2_QueryInterface(IDirectDrawSurface2 *iface, REFIID riid, void **object)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface2(iface);

    TRACE("iface %p, riid %s, object %p.\n", iface, debugstr_guid(riid), object);

    return ddraw_surface7_QueryInterface(&surface->IDirectDrawSurface7_iface, riid, object);
}

static HRESULT WINAPI ddraw_surface1_QueryInterface(IDirectDrawSurface *iface, REFIID riid, void **object)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface(iface);

    TRACE("iface %p, riid %s, object %p.\n", iface, debugstr_guid(riid), object);

    return ddraw_surface7_QueryInterface(&surface->IDirectDrawSurface7_iface, riid, object);
}

static HRESULT WINAPI ddraw_gamma_control_QueryInterface(IDirectDrawGammaControl *iface,
        REFIID riid, void **object)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawGammaControl(iface);

    TRACE("iface %p, riid %s, object %p.\n", iface, debugstr_guid(riid), object);

    return ddraw_surface7_QueryInterface(&surface->IDirectDrawSurface7_iface, riid, object);
}

static HRESULT WINAPI d3d_texture2_QueryInterface(IDirect3DTexture2 *iface, REFIID riid, void **object)
{
    struct ddraw_surface *surface = impl_from_IDirect3DTexture2(iface);

    TRACE("iface %p, riid %s, object %p.\n", iface, debugstr_guid(riid), object);

    return ddraw_surface7_QueryInterface(&surface->IDirectDrawSurface7_iface, riid, object);
}

static HRESULT WINAPI d3d_texture1_QueryInterface(IDirect3DTexture *iface, REFIID riid, void **object)
{
    struct ddraw_surface *surface = impl_from_IDirect3DTexture(iface);

    TRACE("iface %p, riid %s, object %p.\n", iface, debugstr_guid(riid), object);

    return ddraw_surface7_QueryInterface(&surface->IDirectDrawSurface7_iface, riid, object);
}

static void ddraw_surface_add_iface(struct ddraw_surface *surface)
{
    ULONG iface_count = InterlockedIncrement(&surface->iface_count);
    TRACE("%p increasing iface count to %u.\n", surface, iface_count);

    if (iface_count == 1)
    {
        if (surface->ifaceToRelease)
            IUnknown_AddRef(surface->ifaceToRelease);
        wined3d_mutex_lock();
        if (surface->wined3d_rtv)
            wined3d_rendertarget_view_incref(surface->wined3d_rtv);
        wined3d_texture_incref(surface->wined3d_texture);
        wined3d_mutex_unlock();
    }
}

/*****************************************************************************
 * IDirectDrawSurface7::AddRef
 *
 * A normal addref implementation
 *
 * Returns:
 *  The new refcount
 *
 *****************************************************************************/
static ULONG WINAPI ddraw_surface7_AddRef(IDirectDrawSurface7 *iface)
{
    struct ddraw_surface *This = impl_from_IDirectDrawSurface7(iface);
    ULONG refcount = InterlockedIncrement(&This->ref7);

    TRACE("iface %p increasing refcount to %u.\n", iface, refcount);

    if (refcount == 1)
    {
        ddraw_surface_add_iface(This);
    }

    return refcount;
}

static ULONG WINAPI ddraw_surface4_AddRef(IDirectDrawSurface4 *iface)
{
    struct ddraw_surface *This = impl_from_IDirectDrawSurface4(iface);
    ULONG refcount = InterlockedIncrement(&This->ref4);

    TRACE("iface %p increasing refcount to %u.\n", iface, refcount);

    if (refcount == 1)
    {
        ddraw_surface_add_iface(This);
    }

    return refcount;
}

static ULONG WINAPI ddraw_surface3_AddRef(IDirectDrawSurface3 *iface)
{
    struct ddraw_surface *This = impl_from_IDirectDrawSurface3(iface);
    ULONG refcount = InterlockedIncrement(&This->ref3);

    TRACE("iface %p increasing refcount to %u.\n", iface, refcount);

    if (refcount == 1)
    {
        ddraw_surface_add_iface(This);
    }

    return refcount;
}

static ULONG WINAPI ddraw_surface2_AddRef(IDirectDrawSurface2 *iface)
{
    struct ddraw_surface *This = impl_from_IDirectDrawSurface2(iface);
    ULONG refcount = InterlockedIncrement(&This->ref2);

    TRACE("iface %p increasing refcount to %u.\n", iface, refcount);

    if (refcount == 1)
    {
        ddraw_surface_add_iface(This);
    }

    return refcount;
}

static ULONG WINAPI ddraw_surface1_AddRef(IDirectDrawSurface *iface)
{
    struct ddraw_surface *This = impl_from_IDirectDrawSurface(iface);
    ULONG refcount = InterlockedIncrement(&This->ref1);

    TRACE("iface %p increasing refcount to %u.\n", iface, refcount);

    if (refcount == 1)
    {
        ddraw_surface_add_iface(This);
    }

    return refcount;
}

static ULONG WINAPI ddraw_gamma_control_AddRef(IDirectDrawGammaControl *iface)
{
    struct ddraw_surface *This = impl_from_IDirectDrawGammaControl(iface);
    ULONG refcount = InterlockedIncrement(&This->gamma_count);

    TRACE("iface %p increasing refcount to %u.\n", iface, refcount);

    if (refcount == 1)
    {
        ddraw_surface_add_iface(This);
    }

    return refcount;
}

static ULONG WINAPI d3d_texture2_AddRef(IDirect3DTexture2 *iface)
{
    struct ddraw_surface *surface = impl_from_IDirect3DTexture2(iface);

    TRACE("iface %p.\n", iface);

    return IUnknown_AddRef(surface->texture_outer);
}

static ULONG WINAPI d3d_texture1_AddRef(IDirect3DTexture *iface)
{
    struct ddraw_surface *surface = impl_from_IDirect3DTexture(iface);

    TRACE("iface %p.\n", iface);

    return IUnknown_AddRef(surface->texture_outer);
}

static HRESULT ddraw_surface_set_palette(struct ddraw_surface *surface, IDirectDrawPalette *palette)
{
    struct ddraw_palette *palette_impl = unsafe_impl_from_IDirectDrawPalette(palette);
    struct ddraw_palette *prev;

    TRACE("iface %p, palette %p.\n", surface, palette);

    if (palette_impl && palette_impl->flags & DDPCAPS_ALPHA
            && !(surface->surface_desc.ddsCaps.dwCaps & DDSCAPS_TEXTURE))
    {
        WARN("Alpha palette set on non-texture surface, returning DDERR_INVALIDSURFACETYPE.\n");
        return DDERR_INVALIDSURFACETYPE;
    }

    if (!format_is_paletteindexed(&surface->surface_desc.u4.ddpfPixelFormat))
        return DDERR_INVALIDPIXELFORMAT;

    wined3d_mutex_lock();

    prev = surface->palette;
    if (surface->surface_desc.ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE)
    {
        if (prev)
            prev->flags &= ~DDPCAPS_PRIMARYSURFACE;
        if (palette_impl)
            palette_impl->flags |= DDPCAPS_PRIMARYSURFACE;
        wined3d_swapchain_set_palette(surface->ddraw->wined3d_swapchain,
                palette_impl ? palette_impl->wined3d_palette : NULL);
        ddraw_surface_update_frontbuffer(surface, NULL, FALSE);
    }
    if (palette_impl)
        IDirectDrawPalette_AddRef(&palette_impl->IDirectDrawPalette_iface);
    if (prev)
        IDirectDrawPalette_Release(&prev->IDirectDrawPalette_iface);
    surface->palette = palette_impl;

    wined3d_mutex_unlock();

    return DD_OK;
}

static void ddraw_surface_cleanup(struct ddraw_surface *surface)
{
    struct ddraw_surface *surf;
    UINT i;

    TRACE("surface %p.\n", surface);

    /* The refcount test shows that the palette is detached when the surface
     * is destroyed. */
    ddraw_surface_set_palette(surface, NULL);

    /* Loop through all complex attached surfaces and destroy them.
     *
     * Yet again, only the root can have more than one complexly attached
     * surface, all the others have a total of one. */
    for (i = 0; i < MAX_COMPLEX_ATTACHED; ++i)
    {
        if (!surface->complex_array[i])
            break;

        surf = surface->complex_array[i];
        surface->complex_array[i] = NULL;
        if (!surf->is_complex_root)
            ddraw_surface_cleanup(surf);
    }

    if (surface->device1)
        IUnknown_Release(&surface->device1->IUnknown_inner);

    if (surface->iface_count > 1)
    {
        /* This can happen when a complex surface is destroyed, because the
         * 2nd surface was addref()ed when the app called
         * GetAttachedSurface(). */
        WARN("Destroying surface %p with refcounts 7: %u 4: %u 3: %u 2: %u 1: %u.\n",
                surface, surface->ref7, surface->ref4, surface->ref3, surface->ref2, surface->ref1);
    }

    if (surface->wined3d_rtv)
        wined3d_rendertarget_view_decref(surface->wined3d_rtv);
    wined3d_texture_decref(surface->wined3d_texture);
}

static ULONG ddraw_surface_release_iface(struct ddraw_surface *This)
{
    ULONG iface_count;

    /* Prevent the surface from being destroyed if it's still attached to
     * another surface. It will be destroyed when the root is destroyed. */
    if (This->iface_count == 1 && This->attached_iface)
        IUnknown_AddRef(This->attached_iface);
    iface_count = InterlockedDecrement(&This->iface_count);

    TRACE("%p decreasing iface count to %u.\n", This, iface_count);

    if (iface_count == 0)
    {
        struct ddraw_texture *texture = wined3d_texture_get_parent(This->wined3d_texture);
        struct wined3d_device *wined3d_device = texture->wined3d_device;
        IUnknown *release_iface = This->ifaceToRelease;

        /* Complex attached surfaces are destroyed implicitly when the root is released */
        wined3d_mutex_lock();
        if(!This->is_complex_root)
        {
            WARN("(%p) Attempt to destroy a surface that is not a complex root\n", This);
            wined3d_mutex_unlock();
            return iface_count;
        }
        ddraw_surface_cleanup(This);
        wined3d_mutex_unlock();

        if (release_iface)
            IUnknown_Release(release_iface);
        /* Release the device only after anything that may reference it (the
         * wined3d texture and rendertarget view in particular) is released. */
        wined3d_device_decref(wined3d_device);
    }

    return iface_count;
}

/*****************************************************************************
 * IDirectDrawSurface7::Release
 *
 * Reduces the surface's refcount by 1. If the refcount falls to 0, the
 * surface is destroyed.
 *
 * Destroying the surface is a bit tricky. For the connection between
 * WineD3DSurfaces and DirectDrawSurfaces see IDirectDraw7::CreateSurface
 * It has a nice graph explaining the connection.
 *
 * What happens here is basically this:
 * When a surface is destroyed, its WineD3DSurface is released,
 * and the refcount of the DirectDraw interface is reduced by 1. If it has
 * complex surfaces attached to it, then these surfaces are destroyed too,
 * regardless of their refcount. If any surface being destroyed has another
 * surface attached to it (with a "soft" attachment, not complex), then
 * this surface is detached with DeleteAttachedSurface.
 *
 * When the surface is a texture, the WineD3DTexture is released.
 * If the surface is the Direct3D render target, then the D3D
 * capabilities of the WineD3DDevice are uninitialized, which causes the
 * swapchain to be released.
 *
 * When a complex sublevel falls to ref zero, then this is ignored.
 *
 * Returns:
 *  The new refcount
 *
 *****************************************************************************/
static ULONG WINAPI ddraw_surface7_Release(IDirectDrawSurface7 *iface)
{
    struct ddraw_surface *This = impl_from_IDirectDrawSurface7(iface);
    ULONG refcount = InterlockedDecrement(&This->ref7);

    TRACE("iface %p decreasing refcount to %u.\n", iface, refcount);

    if (refcount == 0)
    {
        ddraw_surface_release_iface(This);
    }

    return refcount;
}

static ULONG WINAPI ddraw_surface4_Release(IDirectDrawSurface4 *iface)
{
    struct ddraw_surface *This = impl_from_IDirectDrawSurface4(iface);
    ULONG refcount = InterlockedDecrement(&This->ref4);

    TRACE("iface %p decreasing refcount to %u.\n", iface, refcount);

    if (refcount == 0)
    {
        ddraw_surface_release_iface(This);
    }

    return refcount;
}

static ULONG WINAPI ddraw_surface3_Release(IDirectDrawSurface3 *iface)
{
    struct ddraw_surface *This = impl_from_IDirectDrawSurface3(iface);
    ULONG refcount = InterlockedDecrement(&This->ref3);

    TRACE("iface %p decreasing refcount to %u.\n", iface, refcount);

    if (refcount == 0)
    {
        ddraw_surface_release_iface(This);
    }

    return refcount;
}

static ULONG WINAPI ddraw_surface2_Release(IDirectDrawSurface2 *iface)
{
    struct ddraw_surface *This = impl_from_IDirectDrawSurface2(iface);
    ULONG refcount = InterlockedDecrement(&This->ref2);

    TRACE("iface %p decreasing refcount to %u.\n", iface, refcount);

    if (refcount == 0)
    {
        ddraw_surface_release_iface(This);
    }

    return refcount;
}

static ULONG WINAPI ddraw_surface1_Release(IDirectDrawSurface *iface)
{
    struct ddraw_surface *This = impl_from_IDirectDrawSurface(iface);
    ULONG refcount = InterlockedDecrement(&This->ref1);

    TRACE("iface %p decreasing refcount to %u.\n", iface, refcount);

    if (refcount == 0)
    {
        ddraw_surface_release_iface(This);
    }

    return refcount;
}

static ULONG WINAPI ddraw_gamma_control_Release(IDirectDrawGammaControl *iface)
{
    struct ddraw_surface *This = impl_from_IDirectDrawGammaControl(iface);
    ULONG refcount = InterlockedDecrement(&This->gamma_count);

    TRACE("iface %p decreasing refcount to %u.\n", iface, refcount);

    if (refcount == 0)
    {
        ddraw_surface_release_iface(This);
    }

    return refcount;
}

static ULONG WINAPI d3d_texture2_Release(IDirect3DTexture2 *iface)
{
    struct ddraw_surface *surface = impl_from_IDirect3DTexture2(iface);

    TRACE("iface %p.\n", iface);

    return IUnknown_Release(surface->texture_outer);
}

static ULONG WINAPI d3d_texture1_Release(IDirect3DTexture *iface)
{
    struct ddraw_surface *surface = impl_from_IDirect3DTexture(iface);

    TRACE("iface %p.\n", iface);

    return IUnknown_Release(surface->texture_outer);
}

/*****************************************************************************
 * IDirectDrawSurface7::GetAttachedSurface
 *
 * Returns an attached surface with the requested caps. Surface attachment
 * and complex surfaces are not clearly described by the MSDN or sdk,
 * so this method is tricky and likely to contain problems.
 * This implementation searches the complex list first, then the
 * attachment chain.
 *
 * The chains are searched from This down to the last surface in the chain,
 * not from the first element in the chain. The first surface found is
 * returned. The MSDN says that this method fails if more than one surface
 * matches the caps, but it is not sure if that is right. The attachment
 * structure may not even allow two matching surfaces.
 *
 * The found surface is AddRef-ed before it is returned.
 *
 * Params:
 *  Caps: Pointer to a DDCAPS2 structure describing the caps asked for
 *  Surface: Address to store the found surface
 *
 * Returns:
 *  DD_OK on success
 *  DDERR_INVALIDPARAMS if Caps or Surface is NULL
 *  DDERR_NOTFOUND if no surface was found
 *
 *****************************************************************************/
static HRESULT WINAPI ddraw_surface7_GetAttachedSurface(IDirectDrawSurface7 *iface,
        DDSCAPS2 *Caps, IDirectDrawSurface7 **Surface)
{
    struct ddraw_surface *This = impl_from_IDirectDrawSurface7(iface);
    struct ddraw_surface *surf;
    DDSCAPS2 our_caps;
    int i;

    TRACE("iface %p, caps %p, attachment %p.\n", iface, Caps, Surface);

    wined3d_mutex_lock();

    if(This->version < 7)
    {
        /* Earlier dx apps put garbage into these members, clear them */
        our_caps.dwCaps = Caps->dwCaps;
        our_caps.dwCaps2 = 0;
        our_caps.dwCaps3 = 0;
        our_caps.u1.dwCaps4 = 0;
    }
    else
    {
        our_caps = *Caps;
    }

    TRACE("(%p): Looking for caps: %x,%x,%x,%x\n", This, our_caps.dwCaps, our_caps.dwCaps2, our_caps.dwCaps3, our_caps.u1.dwCaps4); /* FIXME: Better debugging */

    for(i = 0; i < MAX_COMPLEX_ATTACHED; i++)
    {
        surf = This->complex_array[i];
        if(!surf) break;

        TRACE("Surface: (%p) caps: %#x, %#x, %#x, %#x.\n", surf,
                surf->surface_desc.ddsCaps.dwCaps,
                surf->surface_desc.ddsCaps.dwCaps2,
                surf->surface_desc.ddsCaps.dwCaps3,
                surf->surface_desc.ddsCaps.u1.dwCaps4);

        if (((surf->surface_desc.ddsCaps.dwCaps & our_caps.dwCaps) == our_caps.dwCaps) &&
            ((surf->surface_desc.ddsCaps.dwCaps2 & our_caps.dwCaps2) == our_caps.dwCaps2)) {

            /* MSDN: "This method fails if more than one surface is attached
             * that matches the capabilities requested."
             *
             * Not sure how to test this.
             */

            TRACE("(%p): Returning surface %p\n", This, surf);
            *Surface = &surf->IDirectDrawSurface7_iface;
            ddraw_surface7_AddRef(*Surface);
            wined3d_mutex_unlock();

            return DD_OK;
        }
    }

    /* Next, look at the attachment chain */
    surf = This;

    while( (surf = surf->next_attached) )
    {
        TRACE("Surface: (%p) caps: %#x, %#x, %#x, %#x.\n", surf,
                surf->surface_desc.ddsCaps.dwCaps,
                surf->surface_desc.ddsCaps.dwCaps2,
                surf->surface_desc.ddsCaps.dwCaps3,
                surf->surface_desc.ddsCaps.u1.dwCaps4);

        if (((surf->surface_desc.ddsCaps.dwCaps & our_caps.dwCaps) == our_caps.dwCaps) &&
            ((surf->surface_desc.ddsCaps.dwCaps2 & our_caps.dwCaps2) == our_caps.dwCaps2)) {

            TRACE("(%p): Returning surface %p\n", This, surf);
            *Surface = &surf->IDirectDrawSurface7_iface;
            ddraw_surface7_AddRef(*Surface);
            wined3d_mutex_unlock();
            return DD_OK;
        }
    }

    TRACE("(%p) Didn't find a valid surface\n", This);

    wined3d_mutex_unlock();

    *Surface = NULL;
    return DDERR_NOTFOUND;
}

static HRESULT WINAPI ddraw_surface4_GetAttachedSurface(IDirectDrawSurface4 *iface,
        DDSCAPS2 *caps, IDirectDrawSurface4 **attachment)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface4(iface);
    struct ddraw_surface *attachment_impl;
    IDirectDrawSurface7 *attachment7;
    HRESULT hr;

    TRACE("iface %p, caps %p, attachment %p.\n", iface, caps, attachment);

    hr = ddraw_surface7_GetAttachedSurface(&surface->IDirectDrawSurface7_iface,
            caps, &attachment7);
    if (FAILED(hr))
    {
        *attachment = NULL;
        return hr;
    }
    attachment_impl = impl_from_IDirectDrawSurface7(attachment7);
    *attachment = &attachment_impl->IDirectDrawSurface4_iface;
    ddraw_surface4_AddRef(*attachment);
    ddraw_surface7_Release(attachment7);

    return hr;
}

static HRESULT WINAPI ddraw_surface3_GetAttachedSurface(IDirectDrawSurface3 *iface,
        DDSCAPS *caps, IDirectDrawSurface3 **attachment)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface3(iface);
    struct ddraw_surface *attachment_impl;
    IDirectDrawSurface7 *attachment7;
    DDSCAPS2 caps2;
    HRESULT hr;

    TRACE("iface %p, caps %p, attachment %p.\n", iface, caps, attachment);

    caps2.dwCaps  = caps->dwCaps;
    caps2.dwCaps2 = 0;
    caps2.dwCaps3 = 0;
    caps2.u1.dwCaps4 = 0;

    hr = ddraw_surface7_GetAttachedSurface(&surface->IDirectDrawSurface7_iface,
            &caps2, &attachment7);
    if (FAILED(hr))
    {
        *attachment = NULL;
        return hr;
    }
    attachment_impl = impl_from_IDirectDrawSurface7(attachment7);
    *attachment = &attachment_impl->IDirectDrawSurface3_iface;
    ddraw_surface3_AddRef(*attachment);
    ddraw_surface7_Release(attachment7);

    return hr;
}

static HRESULT WINAPI ddraw_surface2_GetAttachedSurface(IDirectDrawSurface2 *iface,
        DDSCAPS *caps, IDirectDrawSurface2 **attachment)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface2(iface);
    struct ddraw_surface *attachment_impl;
    IDirectDrawSurface7 *attachment7;
    DDSCAPS2 caps2;
    HRESULT hr;

    TRACE("iface %p, caps %p, attachment %p.\n", iface, caps, attachment);

    caps2.dwCaps  = caps->dwCaps;
    caps2.dwCaps2 = 0;
    caps2.dwCaps3 = 0;
    caps2.u1.dwCaps4 = 0;

    hr = ddraw_surface7_GetAttachedSurface(&surface->IDirectDrawSurface7_iface,
            &caps2, &attachment7);
    if (FAILED(hr))
    {
        *attachment = NULL;
        return hr;
    }
    attachment_impl = impl_from_IDirectDrawSurface7(attachment7);
    *attachment = &attachment_impl->IDirectDrawSurface2_iface;
    ddraw_surface2_AddRef(*attachment);
    ddraw_surface7_Release(attachment7);

    return hr;
}

static HRESULT WINAPI ddraw_surface1_GetAttachedSurface(IDirectDrawSurface *iface,
        DDSCAPS *caps, IDirectDrawSurface **attachment)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface(iface);
    struct ddraw_surface *attachment_impl;
    IDirectDrawSurface7 *attachment7;
    DDSCAPS2 caps2;
    HRESULT hr;

    TRACE("iface %p, caps %p, attachment %p.\n", iface, caps, attachment);

    caps2.dwCaps  = caps->dwCaps;
    caps2.dwCaps2 = 0;
    caps2.dwCaps3 = 0;
    caps2.u1.dwCaps4 = 0;

    hr = ddraw_surface7_GetAttachedSurface(&surface->IDirectDrawSurface7_iface,
            &caps2, &attachment7);
    if (FAILED(hr))
    {
        *attachment = NULL;
        return hr;
    }
    attachment_impl = impl_from_IDirectDrawSurface7(attachment7);
    *attachment = &attachment_impl->IDirectDrawSurface_iface;
    ddraw_surface1_AddRef(*attachment);
    ddraw_surface7_Release(attachment7);

    return hr;
}

/*****************************************************************************
 * IDirectDrawSurface7::Lock
 *
 * Locks the surface and returns a pointer to the surface's memory
 *
 * Params:
 *  Rect: Rectangle to lock. If NULL, the whole surface is locked
 *  DDSD: Pointer to a DDSURFACEDESC2 which shall receive the surface's desc.
 *  Flags: Locking flags, e.g Read only or write only
 *  h: An event handle that's not used and must be NULL
 *
 * Returns:
 *  DD_OK on success
 *  DDERR_INVALIDPARAMS if DDSD is NULL
 *
 *****************************************************************************/
static HRESULT surface_lock(struct ddraw_surface *surface,
        RECT *rect, DDSURFACEDESC2 *surface_desc, unsigned int surface_desc_size,
        DWORD flags, HANDLE h)
{
    struct wined3d_map_desc map_desc;
    struct wined3d_box box;
    HRESULT hr = DD_OK;

    TRACE("surface %p, rect %s, surface_desc %p, surface_desc_size %u, flags %#x, h %p.\n",
            surface, wine_dbgstr_rect(rect), surface_desc, surface_desc_size, flags, h);

    /* surface->surface_desc.dwWidth and dwHeight are changeable, thus lock */
    wined3d_mutex_lock();

    /* Should I check for the handle to be NULL?
     *
     * The DDLOCK flags and the D3DLOCK flags are equal
     * for the supported values. The others are ignored by WineD3D
     */

    /* Windows zeroes this if the rect is invalid */
    surface_desc->lpSurface = NULL;

    if (rect)
    {
        if ((rect->left < 0) || (rect->top < 0)
                || (rect->left > rect->right) || (rect->right > surface->surface_desc.dwWidth)
                || (rect->top > rect->bottom) || (rect->bottom > surface->surface_desc.dwHeight))
        {
            WARN("Trying to lock an invalid rectangle, returning DDERR_INVALIDPARAMS\n");
            wined3d_mutex_unlock();
            return DDERR_INVALIDPARAMS;
        }
        wined3d_box_set(&box, rect->left, rect->top, rect->right, rect->bottom, 0, 1);
    }

    if (surface->surface_desc.ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE)
        hr = ddraw_surface_update_frontbuffer(surface, rect, TRUE);
    if (SUCCEEDED(hr))
        hr = wined3d_resource_map(wined3d_texture_get_resource(surface->wined3d_texture),
                surface->sub_resource_idx, &map_desc, rect ? &box : NULL,
                wined3dmapflags_from_ddrawmapflags(flags));
    if (FAILED(hr))
    {
        wined3d_mutex_unlock();
        switch(hr)
        {
            /* D3D8 and D3D9 return the general D3DERR_INVALIDCALL error, but ddraw has a more
             * specific error. But since wined3d returns that error in this only occasion,
             * keep d3d8 and d3d9 free from the return value override. There are many different
             * places where d3d8/9 would have to catch the DDERR_SURFACEBUSY, it is much easier
             * to do it in one place in ddraw.
             */
            case WINED3DERR_INVALIDCALL:    return DDERR_SURFACEBUSY;
            default:                        return hr;
        }
    }

    if (surface->surface_desc.ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE)
    {
        if (flags & DDLOCK_READONLY)
            SetRectEmpty(&surface->ddraw->primary_lock);
        else if (rect)
            surface->ddraw->primary_lock = *rect;
        else
            SetRect(&surface->ddraw->primary_lock, 0, 0, surface->surface_desc.dwWidth, surface->surface_desc.dwHeight);
    }

    /* Windows does not set DDSD_LPSURFACE on locked surfaces. */
    DD_STRUCT_COPY_BYSIZE_(surface_desc, &surface->surface_desc, surface_desc_size, surface->surface_desc.dwSize);
    surface_desc->lpSurface = map_desc.data;

    TRACE("locked surface returning description :\n");
    if (TRACE_ON(ddraw))
        DDRAW_dump_surface_desc(surface_desc);

    wined3d_mutex_unlock();

    return DD_OK;
}

static BOOL surface_validate_lock_desc(struct ddraw_surface *surface,
        const DDSURFACEDESC *desc, unsigned int *size)
{
    if (!desc)
        return FALSE;

    if (desc->dwSize == sizeof(DDSURFACEDESC) || desc->dwSize == sizeof(DDSURFACEDESC2))
    {
        *size = desc->dwSize;
        return TRUE;
    }

    if (surface->version == 7
            && surface->surface_desc.ddsCaps.dwCaps & DDSCAPS_TEXTURE
            && !(surface->surface_desc.ddsCaps.dwCaps & DDSCAPS_VIDEOMEMORY))
    {
        if (desc->dwSize >= sizeof(DDSURFACEDESC2))
            *size = sizeof(DDSURFACEDESC2);
        else
            *size = sizeof(DDSURFACEDESC);
        return TRUE;
    }

    WARN("Invalid structure size %u.\n", desc->dwSize);
    return FALSE;
}

static HRESULT WINAPI ddraw_surface7_Lock(IDirectDrawSurface7 *iface,
        RECT *rect, DDSURFACEDESC2 *surface_desc, DWORD flags, HANDLE h)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface7(iface);
    unsigned int surface_desc_size;

    TRACE("iface %p, rect %s, surface_desc %p, flags %#x, h %p.\n",
            iface, wine_dbgstr_rect(rect), surface_desc, flags, h);

    if (!surface_validate_lock_desc(surface, (DDSURFACEDESC *)surface_desc, &surface_desc_size))
        return DDERR_INVALIDPARAMS;

    return surface_lock(surface, rect, surface_desc, surface_desc_size, flags, h);
}

static HRESULT WINAPI ddraw_surface4_Lock(IDirectDrawSurface4 *iface, RECT *rect,
        DDSURFACEDESC2 *surface_desc, DWORD flags, HANDLE h)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface4(iface);
    unsigned int surface_desc_size;

    TRACE("iface %p, rect %s, surface_desc %p, flags %#x, h %p.\n",
            iface, wine_dbgstr_rect(rect), surface_desc, flags, h);

    if (!surface_validate_lock_desc(surface, (DDSURFACEDESC *)surface_desc, &surface_desc_size))
        return DDERR_INVALIDPARAMS;

    return surface_lock(surface, rect, surface_desc, surface_desc_size, flags, h);
}

static HRESULT WINAPI ddraw_surface3_Lock(IDirectDrawSurface3 *iface, RECT *rect,
        DDSURFACEDESC *surface_desc, DWORD flags, HANDLE h)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface3(iface);
    unsigned int surface_desc_size;
    DDSURFACEDESC2 surface_desc2;
    HRESULT hr;

    TRACE("iface %p, rect %s, surface_desc %p, flags %#x, h %p.\n",
            iface, wine_dbgstr_rect(rect), surface_desc, flags, h);

    if (!surface_validate_lock_desc(surface, surface_desc, &surface_desc_size))
        return DDERR_INVALIDPARAMS;

    surface_desc2.dwSize = surface_desc->dwSize;
    surface_desc2.dwFlags = 0;
    hr = surface_lock(surface, rect, &surface_desc2, surface_desc_size, flags, h);
    DDSD2_to_DDSD(&surface_desc2, surface_desc);
    surface_desc->dwSize = surface_desc2.dwSize;
    return hr;
}

static HRESULT WINAPI ddraw_surface2_Lock(IDirectDrawSurface2 *iface, RECT *rect,
        DDSURFACEDESC *surface_desc, DWORD flags, HANDLE h)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface2(iface);
    unsigned int surface_desc_size;
    DDSURFACEDESC2 surface_desc2;
    HRESULT hr;

    TRACE("iface %p, rect %s, surface_desc %p, flags %#x, h %p.\n",
            iface, wine_dbgstr_rect(rect), surface_desc, flags, h);

    if (!surface_validate_lock_desc(surface, surface_desc, &surface_desc_size))
        return DDERR_INVALIDPARAMS;

    surface_desc2.dwSize = surface_desc->dwSize;
    surface_desc2.dwFlags = 0;
    hr = surface_lock(surface, rect, &surface_desc2, surface_desc_size, flags, h);
    DDSD2_to_DDSD(&surface_desc2, surface_desc);
    surface_desc->dwSize = surface_desc2.dwSize;
    return hr;
}

static HRESULT WINAPI ddraw_surface1_Lock(IDirectDrawSurface *iface, RECT *rect,
        DDSURFACEDESC *surface_desc, DWORD flags, HANDLE h)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface(iface);
    unsigned int surface_desc_size;
    DDSURFACEDESC2 surface_desc2;
    HRESULT hr;

    TRACE("iface %p, rect %s, surface_desc %p, flags %#x, h %p.\n",
            iface, wine_dbgstr_rect(rect), surface_desc, flags, h);

    if (!surface_validate_lock_desc(surface, surface_desc, &surface_desc_size))
        return DDERR_INVALIDPARAMS;

    surface_desc2.dwSize = surface_desc->dwSize;
    surface_desc2.dwFlags = 0;
    hr = surface_lock(surface, rect, &surface_desc2, surface_desc_size, flags, h);
    DDSD2_to_DDSD(&surface_desc2, surface_desc);
    surface_desc->dwSize = surface_desc2.dwSize;
    return hr;
}

/*****************************************************************************
 * IDirectDrawSurface7::Unlock
 *
 * Unlocks an locked surface
 *
 * Params:
 *  Rect: Not used by this implementation
 *
 * Returns:
 *  D3D_OK on success, error code otherwise.
 *
 *****************************************************************************/
static HRESULT WINAPI DECLSPEC_HOTPATCH ddraw_surface7_Unlock(IDirectDrawSurface7 *iface, RECT *pRect)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface7(iface);
    HRESULT hr;

    TRACE("iface %p, rect %s.\n", iface, wine_dbgstr_rect(pRect));

    wined3d_mutex_lock();
    hr = wined3d_resource_unmap(wined3d_texture_get_resource(surface->wined3d_texture), surface->sub_resource_idx);
    if (SUCCEEDED(hr) && surface->surface_desc.ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE)
        hr = ddraw_surface_update_frontbuffer(surface, &surface->ddraw->primary_lock, FALSE);
    wined3d_mutex_unlock();

    return hr;
}

static HRESULT WINAPI DECLSPEC_HOTPATCH ddraw_surface4_Unlock(IDirectDrawSurface4 *iface, RECT *pRect)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface4(iface);

    TRACE("iface %p, rect %p.\n", iface, pRect);

    return ddraw_surface7_Unlock(&surface->IDirectDrawSurface7_iface, pRect);
}

static HRESULT WINAPI DECLSPEC_HOTPATCH ddraw_surface3_Unlock(IDirectDrawSurface3 *iface, void *data)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface3(iface);

    TRACE("iface %p, data %p.\n", iface, data);

    /* data might not be the LPRECT of later versions, so drop it. */
    return ddraw_surface7_Unlock(&surface->IDirectDrawSurface7_iface, NULL);
}

static HRESULT WINAPI DECLSPEC_HOTPATCH ddraw_surface2_Unlock(IDirectDrawSurface2 *iface, void *data)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface2(iface);

    TRACE("iface %p, data %p.\n", iface, data);

    /* data might not be the LPRECT of later versions, so drop it. */
    return ddraw_surface7_Unlock(&surface->IDirectDrawSurface7_iface, NULL);
}

static HRESULT WINAPI DECLSPEC_HOTPATCH ddraw_surface1_Unlock(IDirectDrawSurface *iface, void *data)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface(iface);

    TRACE("iface %p, data %p.\n", iface, data);

    /* data might not be the LPRECT of later versions, so drop it. */
    return ddraw_surface7_Unlock(&surface->IDirectDrawSurface7_iface, NULL);
}

static HRESULT WINAPI DECLSPEC_HOTPATCH ddraw_surface7_Flip(IDirectDrawSurface7 *iface,
        IDirectDrawSurface7 *src, DWORD flags)
{
    struct ddraw_surface *dst_impl = impl_from_IDirectDrawSurface7(iface);
    struct ddraw_surface *src_impl = unsafe_impl_from_IDirectDrawSurface7(src);
    struct wined3d_rendertarget_view *tmp_rtv, *src_rtv, *rtv;
    struct ddraw_texture *ddraw_texture, *prev_ddraw_texture;
    DDSCAPS2 caps = {DDSCAPS_FLIP, 0, 0, {0}};
    struct wined3d_texture *texture;
    IDirectDrawSurface7 *current;
    HRESULT hr;

    TRACE("iface %p, src %p, flags %#x.\n", iface, src, flags);

    if (src == iface || !(dst_impl->surface_desc.ddsCaps.dwCaps & (DDSCAPS_FRONTBUFFER | DDSCAPS_OVERLAY)))
        return DDERR_NOTFLIPPABLE;

    if (IDirectDrawSurface7_IsLost(iface) == DDERR_SURFACELOST)
        return DDERR_SURFACELOST;

    wined3d_mutex_lock();

    if ((dst_impl->surface_desc.ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE)
            && !(dst_impl->ddraw->cooperative_level & DDSCL_EXCLUSIVE))
    {
        WARN("Not in exclusive mode.\n");
        wined3d_mutex_unlock();
        return DDERR_NOEXCLUSIVEMODE;
    }

    tmp_rtv = ddraw_surface_get_rendertarget_view(dst_impl);
    if (dst_impl->sub_resource_idx)
        ERR("Invalid sub-resource index %u on surface %p.\n", dst_impl->sub_resource_idx, dst_impl);
    texture = dst_impl->wined3d_texture;
    rtv = wined3d_device_get_rendertarget_view(dst_impl->ddraw->wined3d_device, 0);
    ddraw_texture = wined3d_texture_get_parent(dst_impl->wined3d_texture);

    if (src_impl)
    {
        for (current = iface; current != src;)
        {
            if (FAILED(hr = ddraw_surface7_GetAttachedSurface(current, &caps, &current)))
            {
                WARN("Surface %p is not on the same flip chain as surface %p.\n", src, iface);
                wined3d_mutex_unlock();
                return DDERR_NOTFLIPPABLE;
            }
            ddraw_surface7_Release(current);
            if (current == iface)
            {
                WARN("Surface %p is not on the same flip chain as surface %p.\n", src, iface);
                wined3d_mutex_unlock();
                return DDERR_NOTFLIPPABLE;
            }
        }

        src_rtv = ddraw_surface_get_rendertarget_view(src_impl);
        if (rtv == dst_impl->wined3d_rtv)
            wined3d_device_set_rendertarget_view(dst_impl->ddraw->wined3d_device, 0, src_rtv, FALSE);
        wined3d_rendertarget_view_set_parent(src_rtv, dst_impl);
        dst_impl->wined3d_rtv = src_rtv;
        wined3d_texture_set_sub_resource_parent(src_impl->wined3d_texture, 0, dst_impl);
        prev_ddraw_texture = wined3d_texture_get_parent(src_impl->wined3d_texture);
        wined3d_resource_set_parent(wined3d_texture_get_resource(src_impl->wined3d_texture), ddraw_texture);
        if (src_impl->sub_resource_idx)
            ERR("Invalid sub-resource index %u on surface %p.\n", src_impl->sub_resource_idx, src_impl);
        dst_impl->wined3d_texture = src_impl->wined3d_texture;
        ddraw_texture = prev_ddraw_texture;
    }
    else
    {
        for (current = iface;;)
        {
            if (FAILED(hr = ddraw_surface7_GetAttachedSurface(current, &caps, &current)))
            {
                ERR("Can't find a flip target\n");
                wined3d_mutex_unlock();
                return DDERR_NOTFLIPPABLE; /* Unchecked */
            }
            ddraw_surface7_Release(current);
            if (current == iface)
            {
                dst_impl = impl_from_IDirectDrawSurface7(iface);
                break;
            }

            src_impl = impl_from_IDirectDrawSurface7(current);
            src_rtv = ddraw_surface_get_rendertarget_view(src_impl);
            if (rtv == dst_impl->wined3d_rtv)
                wined3d_device_set_rendertarget_view(dst_impl->ddraw->wined3d_device, 0, src_rtv, FALSE);
            wined3d_rendertarget_view_set_parent(src_rtv, dst_impl);
            dst_impl->wined3d_rtv = src_rtv;
            wined3d_texture_set_sub_resource_parent(src_impl->wined3d_texture, 0, dst_impl);
            prev_ddraw_texture = wined3d_texture_get_parent(src_impl->wined3d_texture);
            wined3d_resource_set_parent(wined3d_texture_get_resource(src_impl->wined3d_texture), ddraw_texture);
            ddraw_texture = prev_ddraw_texture;
            if (src_impl->sub_resource_idx)
                ERR("Invalid sub-resource index %u on surface %p.\n", src_impl->sub_resource_idx, src_impl);
            dst_impl->wined3d_texture = src_impl->wined3d_texture;
            dst_impl = src_impl;
        }
    }

    /* We don't have to worry about potential texture bindings, since
     * flippable surfaces can never be textures. */
    if (rtv == src_impl->wined3d_rtv)
        wined3d_device_set_rendertarget_view(dst_impl->ddraw->wined3d_device, 0, tmp_rtv, FALSE);
    wined3d_rendertarget_view_set_parent(tmp_rtv, src_impl);
    src_impl->wined3d_rtv = tmp_rtv;
    wined3d_texture_set_sub_resource_parent(texture, 0, src_impl);
    wined3d_resource_set_parent(wined3d_texture_get_resource(texture), ddraw_texture);
    src_impl->wined3d_texture = texture;

    if (flags)
    {
        static UINT once;
        if (!once++)
            FIXME("Ignoring flags %#x.\n", flags);
        else
            WARN("Ignoring flags %#x.\n", flags);
    }

    if (dst_impl->surface_desc.ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE)
        hr = ddraw_surface_update_frontbuffer(dst_impl, NULL, FALSE);
    else
        hr = DD_OK;

    wined3d_mutex_unlock();

    return hr;
}

static HRESULT WINAPI DECLSPEC_HOTPATCH ddraw_surface4_Flip(IDirectDrawSurface4 *iface,
        IDirectDrawSurface4 *src, DWORD flags)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface4(iface);
    struct ddraw_surface *src_impl = unsafe_impl_from_IDirectDrawSurface4(src);

    TRACE("iface %p, src %p, flags %#x.\n", iface, src, flags);

    return ddraw_surface7_Flip(&surface->IDirectDrawSurface7_iface,
            src_impl ? &src_impl->IDirectDrawSurface7_iface : NULL, flags);
}

static HRESULT WINAPI DECLSPEC_HOTPATCH ddraw_surface3_Flip(IDirectDrawSurface3 *iface,
        IDirectDrawSurface3 *src, DWORD flags)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface3(iface);
    struct ddraw_surface *src_impl = unsafe_impl_from_IDirectDrawSurface3(src);

    TRACE("iface %p, src %p, flags %#x.\n", iface, src, flags);

    return ddraw_surface7_Flip(&surface->IDirectDrawSurface7_iface,
            src_impl ? &src_impl->IDirectDrawSurface7_iface : NULL, flags);
}

static HRESULT WINAPI DECLSPEC_HOTPATCH ddraw_surface2_Flip(IDirectDrawSurface2 *iface,
        IDirectDrawSurface2 *src, DWORD flags)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface2(iface);
    struct ddraw_surface *src_impl = unsafe_impl_from_IDirectDrawSurface2(src);

    TRACE("iface %p, src %p, flags %#x.\n", iface, src, flags);

    return ddraw_surface7_Flip(&surface->IDirectDrawSurface7_iface,
            src_impl ? &src_impl->IDirectDrawSurface7_iface : NULL, flags);
}

static HRESULT WINAPI DECLSPEC_HOTPATCH ddraw_surface1_Flip(IDirectDrawSurface *iface,
        IDirectDrawSurface *src, DWORD flags)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface(iface);
    struct ddraw_surface *src_impl = unsafe_impl_from_IDirectDrawSurface(src);

    TRACE("iface %p, src %p, flags %#x.\n", iface, src, flags);

    return ddraw_surface7_Flip(&surface->IDirectDrawSurface7_iface,
            src_impl ? &src_impl->IDirectDrawSurface7_iface : NULL, flags);
}

static HRESULT ddraw_surface_blt(struct ddraw_surface *dst_surface, const RECT *dst_rect,
        struct ddraw_surface *src_surface, const RECT *src_rect, DWORD flags, DWORD fill_colour,
        const struct wined3d_blt_fx *fx, enum wined3d_texture_filter_type filter)
{
    struct wined3d_device *wined3d_device = dst_surface->ddraw->wined3d_device;
    struct wined3d_color colour;
    DWORD wined3d_flags;

    if (flags & DDBLT_COLORFILL)
    {
        if (!wined3d_colour_from_ddraw_colour(&dst_surface->surface_desc.u4.ddpfPixelFormat,
                dst_surface->palette, fill_colour, &colour))
            return DDERR_INVALIDPARAMS;

        return wined3d_device_clear_rendertarget_view(wined3d_device,
                ddraw_surface_get_rendertarget_view(dst_surface),
                dst_rect, WINED3DCLEAR_TARGET, &colour, 0.0f, 0);
    }

    if (flags & DDBLT_DEPTHFILL)
    {
        if (!wined3d_colour_from_ddraw_colour(&dst_surface->surface_desc.u4.ddpfPixelFormat,
                dst_surface->palette, fill_colour, &colour))
            return DDERR_INVALIDPARAMS;

        return wined3d_device_clear_rendertarget_view(wined3d_device,
                ddraw_surface_get_rendertarget_view(dst_surface),
                dst_rect, WINED3DCLEAR_ZBUFFER, NULL, colour.r, 0);
    }

    wined3d_flags = flags & ~DDBLT_ASYNC;
    if (wined3d_flags & ~WINED3D_BLT_MASK)
    {
        FIXME("Unhandled flags %#x.\n", flags);
        return E_NOTIMPL;
    }

    if (!(flags & DDBLT_ASYNC))
        wined3d_flags |= WINED3D_BLT_SYNCHRONOUS;

    return wined3d_texture_blt(dst_surface->wined3d_texture, dst_surface->sub_resource_idx, dst_rect,
            src_surface->wined3d_texture, src_surface->sub_resource_idx, src_rect, wined3d_flags, fx, filter);<--- Null pointer dereference
}

static HRESULT ddraw_surface_blt_clipped(struct ddraw_surface *dst_surface, const RECT *dst_rect_in,
        struct ddraw_surface *src_surface, const RECT *src_rect_in, DWORD flags, DWORD fill_colour,
        const struct wined3d_blt_fx *fx, enum wined3d_texture_filter_type filter)
{
    RECT src_rect, dst_rect;
    float scale_x, scale_y;
    const RECT *clip_rect;
    UINT clip_list_size;
    RGNDATA *clip_list;
    HRESULT hr = DD_OK;
    UINT i;

    if (!dst_rect_in)
        SetRect(&dst_rect, 0, 0, dst_surface->surface_desc.dwWidth,
                dst_surface->surface_desc.dwHeight);
    else
        dst_rect = *dst_rect_in;

    if (IsRectEmpty(&dst_rect))
        return DDERR_INVALIDRECT;

    if (src_surface)
    {
        if (!src_rect_in)
            SetRect(&src_rect, 0, 0, src_surface->surface_desc.dwWidth,
                    src_surface->surface_desc.dwHeight);
        else
            src_rect = *src_rect_in;

        if (IsRectEmpty(&src_rect))
            return DDERR_INVALIDRECT;
    }
    else
    {
        SetRectEmpty(&src_rect);
    }

    if (!dst_surface->clipper)
    {
        if (src_surface && src_surface->surface_desc.ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE)
            hr = ddraw_surface_update_frontbuffer(src_surface, &src_rect, TRUE);
        if (SUCCEEDED(hr))
            hr = ddraw_surface_blt(dst_surface, &dst_rect, src_surface, &src_rect, flags, fill_colour, fx, filter);
        if (SUCCEEDED(hr) && (dst_surface->surface_desc.ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE))
            hr = ddraw_surface_update_frontbuffer(dst_surface, &dst_rect, FALSE);

        return hr;
    }

    scale_x = (float)(src_rect.right - src_rect.left) / (float)(dst_rect.right - dst_rect.left);
    scale_y = (float)(src_rect.bottom - src_rect.top) / (float)(dst_rect.bottom - dst_rect.top);

    if (FAILED(hr = IDirectDrawClipper_GetClipList(&dst_surface->clipper->IDirectDrawClipper_iface,
            &dst_rect, NULL, &clip_list_size)))
    {
        WARN("Failed to get clip list size, hr %#x.\n", hr);
        return hr;
    }

    if (!(clip_list = heap_alloc(clip_list_size)))
    {
        WARN("Failed to allocate clip list.\n");
        return E_OUTOFMEMORY;
    }

    if (FAILED(hr = IDirectDrawClipper_GetClipList(&dst_surface->clipper->IDirectDrawClipper_iface,
            &dst_rect, clip_list, &clip_list_size)))
    {
        WARN("Failed to get clip list, hr %#x.\n", hr);
        heap_free(clip_list);
        return hr;
    }

    clip_rect = (RECT *)clip_list->Buffer;
    for (i = 0; i < clip_list->rdh.nCount; ++i)
    {
        RECT src_rect_clipped = src_rect;

        if (src_surface)<--- Assuming that condition 'src_surface' is not redundant
        {
            src_rect_clipped.left += (LONG)((clip_rect[i].left - dst_rect.left) * scale_x);
            src_rect_clipped.top += (LONG)((clip_rect[i].top - dst_rect.top) * scale_y);
            src_rect_clipped.right -= (LONG)((dst_rect.right - clip_rect[i].right) * scale_x);
            src_rect_clipped.bottom -= (LONG)((dst_rect.bottom - clip_rect[i].bottom) * scale_y);

            if (src_surface->surface_desc.ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE)
            {
                if (FAILED(hr = ddraw_surface_update_frontbuffer(src_surface, &src_rect_clipped, TRUE)))
                    break;
            }
        }

        if (FAILED(hr = ddraw_surface_blt(dst_surface, &clip_rect[i],
                src_surface, &src_rect_clipped, flags, fill_colour, fx, filter)))<--- Calling function 'ddraw_surface_blt', 3rd argument 'src_surface' value is 0
            break;

        if (dst_surface->surface_desc.ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE)
        {
            if (FAILED(hr = ddraw_surface_update_frontbuffer(dst_surface, &clip_rect[i], FALSE)))
                break;
        }
    }

    heap_free(clip_list);
    return hr;
}

/*****************************************************************************
 * IDirectDrawSurface7::Blt
 *
 * Performs a blit on the surface
 *
 * Params:
 *  DestRect: Destination rectangle, can be NULL
 *  SrcSurface: Source surface, can be NULL
 *  SrcRect: Source rectangle, can be NULL
 *  Flags: Blt flags
 *  DDBltFx: Some extended blt parameters, connected to the flags
 *
 * Returns:
 *  D3D_OK on success, error code otherwise.
 *
 *****************************************************************************/
static HRESULT WINAPI DECLSPEC_HOTPATCH ddraw_surface7_Blt(IDirectDrawSurface7 *iface, RECT *dst_rect,
        IDirectDrawSurface7 *src_surface, RECT *src_rect, DWORD flags, DDBLTFX *fx)
{
    struct ddraw_surface *dst_impl = impl_from_IDirectDrawSurface7(iface);
    struct ddraw_surface *src_impl = unsafe_impl_from_IDirectDrawSurface7(src_surface);
    struct wined3d_blt_fx wined3d_fx;
    DWORD unsupported_flags;
    DWORD fill_colour = 0;
    HRESULT hr = DD_OK;
    DDBLTFX rop_fx;

    TRACE("iface %p, dst_rect %s, src_surface %p, src_rect %s, flags %#x, fx %p.\n",
            iface, wine_dbgstr_rect(dst_rect), src_surface, wine_dbgstr_rect(src_rect), flags, fx);

    unsupported_flags = DDBLT_ALPHADEST
            | DDBLT_ALPHADESTCONSTOVERRIDE
            | DDBLT_ALPHADESTNEG
            | DDBLT_ALPHADESTSURFACEOVERRIDE
            | DDBLT_ALPHAEDGEBLEND
            | DDBLT_ALPHASRC
            | DDBLT_ALPHASRCCONSTOVERRIDE
            | DDBLT_ALPHASRCNEG
            | DDBLT_ALPHASRCSURFACEOVERRIDE
            | DDBLT_ZBUFFER
            | DDBLT_ZBUFFERDESTCONSTOVERRIDE
            | DDBLT_ZBUFFERDESTOVERRIDE
            | DDBLT_ZBUFFERSRCCONSTOVERRIDE
            | DDBLT_ZBUFFERSRCOVERRIDE;
    if (flags & unsupported_flags)
    {
        WARN("Ignoring unsupported flags %#x.\n", flags & unsupported_flags);
        flags &= ~unsupported_flags;
    }

    if ((flags & DDBLT_KEYSRCOVERRIDE) && (!fx || flags & DDBLT_KEYSRC))
    {
        WARN("Invalid source color key parameters, returning DDERR_INVALIDPARAMS\n");
        return DDERR_INVALIDPARAMS;
    }

    if ((flags & DDBLT_KEYDESTOVERRIDE) && (!fx || flags & DDBLT_KEYDEST))
    {
        WARN("Invalid destination color key parameters, returning DDERR_INVALIDPARAMS\n");
        return DDERR_INVALIDPARAMS;
    }

    if (flags & DDBLT_DDROPS)
    {
        FIXME("DDBLT_DDROPS not implemented.\n");
        if (fx)
            FIXME("    rop %#x, pattern %p.\n", fx->dwDDROP, fx->u5.lpDDSPattern);
        return DDERR_NORASTEROPHW;
    }

    wined3d_mutex_lock();

    if (flags & (DDBLT_COLORFILL | DDBLT_DEPTHFILL))
    {
        if (flags & DDBLT_ROP)
        {
            wined3d_mutex_unlock();
            WARN("DDBLT_ROP used with DDBLT_COLORFILL or DDBLT_DEPTHFILL, returning DDERR_INVALIDPARAMS.\n");
            return DDERR_INVALIDPARAMS;
        }
        if (src_impl)
        {
            wined3d_mutex_unlock();
            WARN("Depth or colorfill is not compatible with source surfaces, returning DDERR_INVALIDPARAMS\n");
            return DDERR_INVALIDPARAMS;
        }
        if (!fx)
        {
            wined3d_mutex_unlock();
            WARN("Depth or colorfill used with NULL fx, returning DDERR_INVALIDPARAMS.\n");
            return DDERR_INVALIDPARAMS;
        }

        if ((flags & (DDBLT_COLORFILL | DDBLT_DEPTHFILL)) == (DDBLT_COLORFILL | DDBLT_DEPTHFILL))
            flags &= ~DDBLT_DEPTHFILL;

        if ((dst_impl->surface_desc.ddsCaps.dwCaps & DDSCAPS_ZBUFFER) && (flags & DDBLT_COLORFILL))
        {
            wined3d_mutex_unlock();
            WARN("DDBLT_COLORFILL used on a depth buffer, returning DDERR_INVALIDPARAMS.\n");
            return DDERR_INVALIDPARAMS;
        }
        if (!(dst_impl->surface_desc.ddsCaps.dwCaps & DDSCAPS_ZBUFFER) && (flags & DDBLT_DEPTHFILL))
        {
            wined3d_mutex_unlock();
            WARN("DDBLT_DEPTHFILL used on a color buffer, returning DDERR_INVALIDPARAMS.\n");
            return DDERR_INVALIDPARAMS;
        }
    }

    if (flags & DDBLT_ROP)
    {
        if (!fx)
        {
            wined3d_mutex_unlock();
            WARN("DDBLT_ROP used with NULL fx, returning DDERR_INVALIDPARAMS.\n");
            return DDERR_INVALIDPARAMS;
        }

        if (src_impl && src_rect
                && ((ULONG)src_rect->left >= src_rect->right || src_rect->right > src_impl->surface_desc.dwWidth
                || (ULONG)src_rect->top >= src_rect->bottom || src_rect->bottom > src_impl->surface_desc.dwHeight))
        {
            WARN("Invalid source rectangle.\n");
            return DDERR_INVALIDRECT;
        }

        flags &= ~DDBLT_ROP;
        switch (fx->dwROP)
        {
            case SRCCOPY:
                break;

            case WHITENESS:
            case BLACKNESS:
                rop_fx = *fx;

                if (fx->dwROP == WHITENESS)
                    rop_fx.u5.dwFillColor = 0xffffffff;
                else
                    rop_fx.u5.dwFillColor = 0;

                if (dst_impl->surface_desc.ddsCaps.dwCaps & DDSCAPS_ZBUFFER)
                    flags |= DDBLT_DEPTHFILL;
                else
                    flags |= DDBLT_COLORFILL;

                fx = &rop_fx;
                break;

            default:
                wined3d_mutex_unlock();
                WARN("Unsupported ROP %#x used, returning DDERR_NORASTEROPHW.\n", fx->dwROP);
                return DDERR_NORASTEROPHW;
        }
    }

    if (!(flags & (DDBLT_COLORFILL | DDBLT_DEPTHFILL)) && !src_impl)
    {
        WARN("No source surface.\n");
        return DDERR_INVALIDPARAMS;
    }

    if (flags & DDBLT_KEYSRC && (!src_impl || !(src_impl->surface_desc.dwFlags & DDSD_CKSRCBLT)))
    {
        WARN("DDBLT_KEYSRC blit without color key in surface, returning DDERR_INVALIDPARAMS\n");
        wined3d_mutex_unlock();
        return DDERR_INVALIDPARAMS;
    }
    if (flags & DDBLT_KEYDEST && !(dst_impl->surface_desc.dwFlags & DDSD_CKDESTBLT))
    {
        WARN("DDBLT_KEYDEST blit without color key in surface, returning DDERR_INVALIDPARAMS\n");
        wined3d_mutex_unlock();
        return DDERR_INVALIDPARAMS;
    }

    if (fx)
    {
        wined3d_fx.fx = fx->dwDDFX;
        fill_colour = fx->u5.dwFillColor;
        wined3d_fx.dst_color_key.color_space_low_value = fx->ddckDestColorkey.dwColorSpaceLowValue;
        wined3d_fx.dst_color_key.color_space_high_value = fx->ddckDestColorkey.dwColorSpaceHighValue;
        wined3d_fx.src_color_key.color_space_low_value = fx->ddckSrcColorkey.dwColorSpaceLowValue;
        wined3d_fx.src_color_key.color_space_high_value = fx->ddckSrcColorkey.dwColorSpaceHighValue;
    }

    hr = ddraw_surface_blt_clipped(dst_impl, dst_rect, src_impl,
            src_rect, flags, fill_colour, fx ? &wined3d_fx : NULL, WINED3D_TEXF_LINEAR);

    wined3d_mutex_unlock();
    switch(hr)
    {
        case WINED3DERR_NOTAVAILABLE:       return DDERR_UNSUPPORTED;
        default:                            return hr;
    }
}

static HRESULT WINAPI DECLSPEC_HOTPATCH ddraw_surface4_Blt(IDirectDrawSurface4 *iface, RECT *dst_rect,
        IDirectDrawSurface4 *src_surface, RECT *src_rect, DWORD flags, DDBLTFX *fx)
{
    struct ddraw_surface *dst = impl_from_IDirectDrawSurface4(iface);
    struct ddraw_surface *src = unsafe_impl_from_IDirectDrawSurface4(src_surface);

    TRACE("iface %p, dst_rect %s, src_surface %p, src_rect %s, flags %#x, fx %p.\n",
            iface, wine_dbgstr_rect(dst_rect), src_surface, wine_dbgstr_rect(src_rect), flags, fx);

    return ddraw_surface7_Blt(&dst->IDirectDrawSurface7_iface, dst_rect,
            src ? &src->IDirectDrawSurface7_iface : NULL, src_rect, flags, fx);
}

static HRESULT WINAPI DECLSPEC_HOTPATCH ddraw_surface3_Blt(IDirectDrawSurface3 *iface, RECT *dst_rect,
        IDirectDrawSurface3 *src_surface, RECT *src_rect, DWORD flags, DDBLTFX *fx)
{
    struct ddraw_surface *dst = impl_from_IDirectDrawSurface3(iface);
    struct ddraw_surface *src_impl = unsafe_impl_from_IDirectDrawSurface3(src_surface);

    TRACE("iface %p, dst_rect %s, src_surface %p, src_rect %s, flags %#x, fx %p.\n",
            iface, wine_dbgstr_rect(dst_rect), src_surface, wine_dbgstr_rect(src_rect), flags, fx);

    return ddraw_surface7_Blt(&dst->IDirectDrawSurface7_iface, dst_rect,
            src_impl ? &src_impl->IDirectDrawSurface7_iface : NULL, src_rect, flags, fx);
}

static HRESULT WINAPI DECLSPEC_HOTPATCH ddraw_surface2_Blt(IDirectDrawSurface2 *iface, RECT *dst_rect,
        IDirectDrawSurface2 *src_surface, RECT *src_rect, DWORD flags, DDBLTFX *fx)
{
    struct ddraw_surface *dst = impl_from_IDirectDrawSurface2(iface);
    struct ddraw_surface *src_impl = unsafe_impl_from_IDirectDrawSurface2(src_surface);

    TRACE("iface %p, dst_rect %s, src_surface %p, src_rect %s, flags %#x, fx %p.\n",
            iface, wine_dbgstr_rect(dst_rect), src_surface, wine_dbgstr_rect(src_rect), flags, fx);

    return ddraw_surface7_Blt(&dst->IDirectDrawSurface7_iface, dst_rect,
            src_impl ? &src_impl->IDirectDrawSurface7_iface : NULL, src_rect, flags, fx);
}

static HRESULT WINAPI DECLSPEC_HOTPATCH ddraw_surface1_Blt(IDirectDrawSurface *iface, RECT *dst_rect,
        IDirectDrawSurface *src_surface, RECT *src_rect, DWORD flags, DDBLTFX *fx)
{
    struct ddraw_surface *dst = impl_from_IDirectDrawSurface(iface);
    struct ddraw_surface *src_impl = unsafe_impl_from_IDirectDrawSurface(src_surface);

    TRACE("iface %p, dst_rect %s, src_surface %p, src_rect %s, flags %#x, fx %p.\n",
            iface, wine_dbgstr_rect(dst_rect), src_surface, wine_dbgstr_rect(src_rect), flags, fx);

    return ddraw_surface7_Blt(&dst->IDirectDrawSurface7_iface, dst_rect,
            src_impl ? &src_impl->IDirectDrawSurface7_iface : NULL, src_rect, flags, fx);
}

/*****************************************************************************
 * IDirectDrawSurface7::AddAttachedSurface
 *
 * Attaches a surface to another surface. How the surface attachments work
 * is not totally understood yet, and this method is prone to problems.
 * The surface that is attached is AddRef-ed.
 *
 * Tests with complex surfaces suggest that the surface attachments form a
 * tree, but no method to test this has been found yet.
 *
 * The attachment list consists of a first surface (first_attached) and
 * for each surface a pointer to the next attached surface (next_attached).
 * For the first surface, and a surface that has no attachments
 * first_attached points to the surface itself. A surface that has
 * no successors in the chain has next_attached set to NULL.
 *
 * Newly attached surfaces are attached right after the root surface.
 * If a surface is attached to a complex surface compound, it's attached to
 * the surface that the app requested, not the complex root. See
 * GetAttachedSurface for a description how surfaces are found.
 *
 * This is how the current implementation works, and it was coded by looking
 * at the needs of the applications.
 *
 * So far only Z-Buffer attachments are tested, and they are activated in
 * WineD3D. Mipmaps could be tricky to activate in WineD3D.
 * Back buffers should work in 2D mode, but they are not tested(They can be
 * attached in older iface versions). Rendering to the front buffer and
 * switching between that and double buffering is not yet implemented in
 * WineD3D, so for 3D it might have unexpected results.
 *
 * ddraw_surface_attach_surface is the real thing,
 * ddraw_surface7_AddAttachedSurface is a wrapper around it that
 * performs additional checks. Version 7 of this interface is much more restrictive
 * than its predecessors.
 *
 * Params:
 *  Attach: Surface to attach to iface
 *
 * Returns:
 *  DD_OK on success
 *  DDERR_CANNOTATTACHSURFACE if the surface can't be attached for some reason
 *
 *****************************************************************************/
static HRESULT ddraw_surface_attach_surface(struct ddraw_surface *This, struct ddraw_surface *Surf)
{
    TRACE("surface %p, attachment %p.\n", This, Surf);

    if(Surf == This)
        return DDERR_CANNOTATTACHSURFACE; /* unchecked */

    wined3d_mutex_lock();

    /* Check if the surface is already attached somewhere */
    if (Surf->next_attached || Surf->first_attached != Surf)
    {
        /* TODO: Test for the structure of the manual attachment. Is it a
         * chain or a list? What happens if one surface is attached to 2
         * different surfaces? */
        WARN("Surface %p is already attached somewhere. next_attached %p, first_attached %p.\n",
                Surf, Surf->next_attached, Surf->first_attached);

        wined3d_mutex_unlock();
        return DDERR_SURFACEALREADYATTACHED;
    }

    /* This inserts the new surface at the 2nd position in the chain, right after the root surface */
    Surf->next_attached = This->next_attached;
    Surf->first_attached = This->first_attached;
    This->next_attached = Surf;

    /* Check if the WineD3D depth stencil needs updating */
    if (This->ddraw->d3ddevice)
        d3d_device_update_depth_stencil(This->ddraw->d3ddevice);

    wined3d_mutex_unlock();

    return DD_OK;
}

static HRESULT WINAPI ddraw_surface7_AddAttachedSurface(IDirectDrawSurface7 *iface, IDirectDrawSurface7 *attachment)
{
    struct ddraw_surface *This = impl_from_IDirectDrawSurface7(iface);
    struct ddraw_surface *attachment_impl = unsafe_impl_from_IDirectDrawSurface7(attachment);
    HRESULT hr;

    TRACE("iface %p, attachment %p.\n", iface, attachment);

    /* Version 7 of this interface seems to refuse everything except z buffers, as per msdn */
    if(!(attachment_impl->surface_desc.ddsCaps.dwCaps & DDSCAPS_ZBUFFER))
    {

        WARN("Application tries to attach a non Z buffer surface. caps %08x\n",
              attachment_impl->surface_desc.ddsCaps.dwCaps);
        return DDERR_CANNOTATTACHSURFACE;
    }

    hr = ddraw_surface_attach_surface(This, attachment_impl);
    if (FAILED(hr))
    {
        return hr;
    }
    attachment_impl->attached_iface = (IUnknown *)attachment;
    IUnknown_AddRef(attachment_impl->attached_iface);
    return hr;
}

static HRESULT WINAPI ddraw_surface4_AddAttachedSurface(IDirectDrawSurface4 *iface, IDirectDrawSurface4 *attachment)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface4(iface);
    struct ddraw_surface *attachment_impl = unsafe_impl_from_IDirectDrawSurface4(attachment);
    HRESULT hr;

    TRACE("iface %p, attachment %p.\n", iface, attachment);

    /* Tests suggest that
     * -> offscreen plain surfaces can be attached to other offscreen plain surfaces
     * -> offscreen plain surfaces can be attached to primaries
     * -> primaries can be attached to offscreen plain surfaces
     * -> z buffers can be attached to primaries */
    if (surface->surface_desc.ddsCaps.dwCaps & (DDSCAPS_PRIMARYSURFACE | DDSCAPS_OFFSCREENPLAIN)
            && attachment_impl->surface_desc.ddsCaps.dwCaps & (DDSCAPS_PRIMARYSURFACE | DDSCAPS_OFFSCREENPLAIN))
    {
        /* Sizes have to match */
        if (attachment_impl->surface_desc.dwWidth != surface->surface_desc.dwWidth
                || attachment_impl->surface_desc.dwHeight != surface->surface_desc.dwHeight)
        {
            WARN("Surface sizes do not match.\n");
            return DDERR_CANNOTATTACHSURFACE;
        }
    }
    else if (!(surface->surface_desc.ddsCaps.dwCaps & (DDSCAPS_PRIMARYSURFACE | DDSCAPS_3DDEVICE))
            || !(attachment_impl->surface_desc.ddsCaps.dwCaps & (DDSCAPS_ZBUFFER)))
    {
        WARN("Invalid attachment combination.\n");
        return DDERR_CANNOTATTACHSURFACE;
    }

    if (FAILED(hr = ddraw_surface_attach_surface(surface, attachment_impl)))
        return hr;

    attachment_impl->attached_iface = (IUnknown *)attachment;
    IUnknown_AddRef(attachment_impl->attached_iface);
    return hr;
}

static HRESULT WINAPI ddraw_surface3_AddAttachedSurface(IDirectDrawSurface3 *iface, IDirectDrawSurface3 *attachment)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface3(iface);
    struct ddraw_surface *attachment_impl = unsafe_impl_from_IDirectDrawSurface3(attachment);
    HRESULT hr;

    TRACE("iface %p, attachment %p.\n", iface, attachment);

    if (FAILED(hr = ddraw_surface4_AddAttachedSurface(&surface->IDirectDrawSurface4_iface,
            attachment_impl ? &attachment_impl->IDirectDrawSurface4_iface : NULL)))
        return hr;

    attachment_impl->attached_iface = (IUnknown *)attachment;
    IUnknown_AddRef(attachment_impl->attached_iface);
    ddraw_surface4_Release(&attachment_impl->IDirectDrawSurface4_iface);
    return hr;
}

static HRESULT WINAPI ddraw_surface2_AddAttachedSurface(IDirectDrawSurface2 *iface, IDirectDrawSurface2 *attachment)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface2(iface);
    struct ddraw_surface *attachment_impl = unsafe_impl_from_IDirectDrawSurface2(attachment);
    HRESULT hr;

    TRACE("iface %p, attachment %p.\n", iface, attachment);

    if (FAILED(hr = ddraw_surface4_AddAttachedSurface(&surface->IDirectDrawSurface4_iface,
            attachment_impl ? &attachment_impl->IDirectDrawSurface4_iface : NULL)))
        return hr;

    attachment_impl->attached_iface = (IUnknown *)attachment;
    IUnknown_AddRef(attachment_impl->attached_iface);
    ddraw_surface4_Release(&attachment_impl->IDirectDrawSurface4_iface);
    return hr;
}

static HRESULT WINAPI ddraw_surface1_AddAttachedSurface(IDirectDrawSurface *iface, IDirectDrawSurface *attachment)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface(iface);
    struct ddraw_surface *attachment_impl = unsafe_impl_from_IDirectDrawSurface(attachment);
    HRESULT hr;

    TRACE("iface %p, attachment %p.\n", iface, attachment);

    if (FAILED(hr = ddraw_surface4_AddAttachedSurface(&surface->IDirectDrawSurface4_iface,
            attachment_impl ? &attachment_impl->IDirectDrawSurface4_iface : NULL)))
        return hr;

    attachment_impl->attached_iface = (IUnknown *)attachment;
    IUnknown_AddRef(attachment_impl->attached_iface);
    ddraw_surface4_Release(&attachment_impl->IDirectDrawSurface4_iface);
    return hr;
}

/*****************************************************************************
 * IDirectDrawSurface7::DeleteAttachedSurface
 *
 * Removes a surface from the attachment chain. The surface's refcount
 * is decreased by one after it has been removed
 *
 * Params:
 *  Flags: Some flags, not used by this implementation
 *  Attach: Surface to detach
 *
 * Returns:
 *  DD_OK on success
 *  DDERR_SURFACENOTATTACHED if the surface isn't attached to
 *
 *****************************************************************************/
static HRESULT ddraw_surface_delete_attached_surface(struct ddraw_surface *surface,
        struct ddraw_surface *attachment, IUnknown *detach_iface)
{
    struct ddraw_surface *prev = surface;

    TRACE("surface %p, attachment %p, detach_iface %p.\n", surface, attachment, detach_iface);

    wined3d_mutex_lock();
    if (!attachment || (attachment->first_attached != surface) || (attachment == surface) )
    {
        wined3d_mutex_unlock();
        return DDERR_CANNOTDETACHSURFACE;
    }

    if (attachment->attached_iface != detach_iface)
    {
        WARN("attachment->attach_iface %p != detach_iface %p.\n", attachment->attached_iface, detach_iface);
        wined3d_mutex_unlock();
        return DDERR_SURFACENOTATTACHED;
    }

    /* Remove MIPMAPSUBLEVEL if this seemed to be one */
    if (surface->surface_desc.ddsCaps.dwCaps & attachment->surface_desc.ddsCaps.dwCaps & DDSCAPS_MIPMAP)
    {
        attachment->surface_desc.ddsCaps.dwCaps2 &= ~DDSCAPS2_MIPMAPSUBLEVEL;
        /* FIXME: we should probably also subtract from dwMipMapCount of this
         * and all parent surfaces */
    }

    /* Find the predecessor of the detached surface */
    while (prev->next_attached != attachment)
    {
        if (!(prev = prev->next_attached))
        {
            ERR("Failed to find predecessor of %p.\n", attachment);
            wined3d_mutex_unlock();
            return DDERR_SURFACENOTATTACHED;
        }
    }

    /* Unchain the surface */
    prev->next_attached = attachment->next_attached;
    attachment->next_attached = NULL;
    attachment->first_attached = attachment;

    /* Check if the wined3d depth stencil needs updating. Note that we don't
     * just call d3d_device_update_depth_stencil() here since it uses
     * QueryInterface(). Some applications, SCP - Containment Breach in
     * particular, modify the QueryInterface() pointer in the surface vtbl
     * but don't cleanup properly after the relevant dll is unloaded. */
    if (attachment->surface_desc.ddsCaps.dwCaps & DDSCAPS_ZBUFFER
            && wined3d_device_get_depth_stencil_view(surface->ddraw->wined3d_device) == attachment->wined3d_rtv)
        wined3d_device_set_depth_stencil_view(surface->ddraw->wined3d_device, NULL);
    wined3d_mutex_unlock();

    /* Set attached_iface to NULL before releasing it, the surface may go
     * away. */
    attachment->attached_iface = NULL;
    IUnknown_Release(detach_iface);

    return DD_OK;
}

static HRESULT WINAPI ddraw_surface7_DeleteAttachedSurface(IDirectDrawSurface7 *iface,
        DWORD flags, IDirectDrawSurface7 *attachment)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface7(iface);
    struct ddraw_surface *attachment_impl = unsafe_impl_from_IDirectDrawSurface7(attachment);

    TRACE("iface %p, flags %#x, attachment %p.\n", iface, flags, attachment);

    return ddraw_surface_delete_attached_surface(surface, attachment_impl, (IUnknown *)attachment);
}

static HRESULT WINAPI ddraw_surface4_DeleteAttachedSurface(IDirectDrawSurface4 *iface,
        DWORD flags, IDirectDrawSurface4 *attachment)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface4(iface);
    struct ddraw_surface *attachment_impl = unsafe_impl_from_IDirectDrawSurface4(attachment);

    TRACE("iface %p, flags %#x, attachment %p.\n", iface, flags, attachment);

    return ddraw_surface_delete_attached_surface(surface, attachment_impl, (IUnknown *)attachment);
}

static HRESULT WINAPI ddraw_surface3_DeleteAttachedSurface(IDirectDrawSurface3 *iface,
        DWORD flags, IDirectDrawSurface3 *attachment)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface3(iface);
    struct ddraw_surface *attachment_impl = unsafe_impl_from_IDirectDrawSurface3(attachment);

    TRACE("iface %p, flags %#x, attachment %p.\n", iface, flags, attachment);

    return ddraw_surface_delete_attached_surface(surface, attachment_impl, (IUnknown *)attachment);
}

static HRESULT WINAPI ddraw_surface2_DeleteAttachedSurface(IDirectDrawSurface2 *iface,
        DWORD flags, IDirectDrawSurface2 *attachment)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface2(iface);
    struct ddraw_surface *attachment_impl = unsafe_impl_from_IDirectDrawSurface2(attachment);

    TRACE("iface %p, flags %#x, attachment %p.\n", iface, flags, attachment);

    return ddraw_surface_delete_attached_surface(surface, attachment_impl, (IUnknown *)attachment);
}

static HRESULT WINAPI ddraw_surface1_DeleteAttachedSurface(IDirectDrawSurface *iface,
        DWORD flags, IDirectDrawSurface *attachment)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface(iface);
    struct ddraw_surface *attachment_impl = unsafe_impl_from_IDirectDrawSurface(attachment);

    TRACE("iface %p, flags %#x, attachment %p.\n", iface, flags, attachment);

    return ddraw_surface_delete_attached_surface(surface, attachment_impl, (IUnknown *)attachment);
}

/*****************************************************************************
 * IDirectDrawSurface7::AddOverlayDirtyRect
 *
 * "This method is not currently implemented"
 *
 * Params:
 *  Rect: ?
 *
 * Returns:
 *  DDERR_UNSUPPORTED
 *
 *****************************************************************************/
static HRESULT WINAPI ddraw_surface7_AddOverlayDirtyRect(IDirectDrawSurface7 *iface, RECT *Rect)
{
    TRACE("iface %p, rect %s.\n", iface, wine_dbgstr_rect(Rect));

    return DDERR_UNSUPPORTED; /* unchecked */
}

static HRESULT WINAPI ddraw_surface4_AddOverlayDirtyRect(IDirectDrawSurface4 *iface, RECT *rect)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface4(iface);

    TRACE("iface %p, rect %s.\n", iface, wine_dbgstr_rect(rect));

    return ddraw_surface7_AddOverlayDirtyRect(&surface->IDirectDrawSurface7_iface, rect);
}

static HRESULT WINAPI ddraw_surface3_AddOverlayDirtyRect(IDirectDrawSurface3 *iface, RECT *rect)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface3(iface);

    TRACE("iface %p, rect %s.\n", iface, wine_dbgstr_rect(rect));

    return ddraw_surface7_AddOverlayDirtyRect(&surface->IDirectDrawSurface7_iface, rect);
}

static HRESULT WINAPI ddraw_surface2_AddOverlayDirtyRect(IDirectDrawSurface2 *iface, RECT *rect)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface2(iface);

    TRACE("iface %p, rect %s.\n", iface, wine_dbgstr_rect(rect));

    return ddraw_surface7_AddOverlayDirtyRect(&surface->IDirectDrawSurface7_iface, rect);
}

static HRESULT WINAPI ddraw_surface1_AddOverlayDirtyRect(IDirectDrawSurface *iface, RECT *rect)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface(iface);

    TRACE("iface %p, rect %s.\n", iface, wine_dbgstr_rect(rect));

    return ddraw_surface7_AddOverlayDirtyRect(&surface->IDirectDrawSurface7_iface, rect);
}

/*****************************************************************************
 * IDirectDrawSurface7::GetDC
 *
 * Returns a GDI device context for the surface
 *
 * Params:
 *  hdc: Address of a HDC variable to store the dc to
 *
 * Returns:
 *  DD_OK on success
 *  DDERR_INVALIDPARAMS if hdc is NULL
 *
 *****************************************************************************/
static HRESULT WINAPI ddraw_surface7_GetDC(IDirectDrawSurface7 *iface, HDC *dc)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface7(iface);
    HRESULT hr = DD_OK;

    TRACE("iface %p, dc %p.\n", iface, dc);

    if (!dc)
        return DDERR_INVALIDPARAMS;

    wined3d_mutex_lock();
    if (surface->dc)
        hr = DDERR_DCALREADYCREATED;
    else if (surface->surface_desc.ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE)
        hr = ddraw_surface_update_frontbuffer(surface, NULL, TRUE);
    if (SUCCEEDED(hr))
        hr = wined3d_texture_get_dc(surface->wined3d_texture, surface->sub_resource_idx, dc);

    if (SUCCEEDED(hr))
    {
        surface->dc = *dc;

        if (format_is_paletteindexed(&surface->surface_desc.u4.ddpfPixelFormat))
        {
            const struct ddraw_palette *palette;

            if (surface->palette)
                palette = surface->palette;
            else if (surface->ddraw->primary)
                palette = surface->ddraw->primary->palette;
            else
                palette = NULL;

            if (palette)
                wined3d_palette_apply_to_dc(palette->wined3d_palette, *dc);
        }
    }

    wined3d_mutex_unlock();
    switch (hr)
    {
        /* Some, but not all errors set *dc to NULL. E.g. DCALREADYCREATED
         * does not touch *dc. */
        case WINED3DERR_INVALIDCALL:
            *dc = NULL;
            return DDERR_CANTCREATEDC;

        default:
            return hr;
    }
}

static HRESULT WINAPI ddraw_surface4_GetDC(IDirectDrawSurface4 *iface, HDC *dc)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface4(iface);

    TRACE("iface %p, dc %p.\n", iface, dc);

    return ddraw_surface7_GetDC(&surface->IDirectDrawSurface7_iface, dc);
}

static HRESULT WINAPI ddraw_surface3_GetDC(IDirectDrawSurface3 *iface, HDC *dc)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface3(iface);

    TRACE("iface %p, dc %p.\n", iface, dc);

    return ddraw_surface7_GetDC(&surface->IDirectDrawSurface7_iface, dc);
}

static HRESULT WINAPI ddraw_surface2_GetDC(IDirectDrawSurface2 *iface, HDC *dc)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface2(iface);

    TRACE("iface %p, dc %p.\n", iface, dc);

    return ddraw_surface7_GetDC(&surface->IDirectDrawSurface7_iface, dc);
}

static HRESULT WINAPI ddraw_surface1_GetDC(IDirectDrawSurface *iface, HDC *dc)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface(iface);

    TRACE("iface %p, dc %p.\n", iface, dc);

    return ddraw_surface7_GetDC(&surface->IDirectDrawSurface7_iface, dc);
}

/*****************************************************************************
 * IDirectDrawSurface7::ReleaseDC
 *
 * Releases the DC that was constructed with GetDC
 *
 * Params:
 *  hdc: HDC to release
 *
 * Returns:
 *  DD_OK on success, error code otherwise.
 *
 *****************************************************************************/
static HRESULT WINAPI ddraw_surface7_ReleaseDC(IDirectDrawSurface7 *iface, HDC hdc)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface7(iface);
    HRESULT hr;

    TRACE("iface %p, dc %p.\n", iface, hdc);
#ifdef __REACTOS__
    GdiFlush();
#endif
    wined3d_mutex_lock();
    if (!surface->dc)
    {
        hr = DDERR_NODC;
    }
    else if (SUCCEEDED(hr = wined3d_texture_release_dc(surface->wined3d_texture, surface->sub_resource_idx, hdc)))
    {
        surface->dc = NULL;
        if (surface->surface_desc.ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE)
            hr = ddraw_surface_update_frontbuffer(surface, NULL, FALSE);
    }
    wined3d_mutex_unlock();


    return hr;
}

static HRESULT WINAPI ddraw_surface4_ReleaseDC(IDirectDrawSurface4 *iface, HDC dc)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface4(iface);

    TRACE("iface %p, dc %p.\n", iface, dc);

    return ddraw_surface7_ReleaseDC(&surface->IDirectDrawSurface7_iface, dc);
}

static HRESULT WINAPI ddraw_surface3_ReleaseDC(IDirectDrawSurface3 *iface, HDC dc)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface3(iface);

    TRACE("iface %p, dc %p.\n", iface, dc);

    return ddraw_surface7_ReleaseDC(&surface->IDirectDrawSurface7_iface, dc);
}

static HRESULT WINAPI ddraw_surface2_ReleaseDC(IDirectDrawSurface2 *iface, HDC dc)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface2(iface);

    TRACE("iface %p, dc %p.\n", iface, dc);

    return ddraw_surface7_ReleaseDC(&surface->IDirectDrawSurface7_iface, dc);
}

static HRESULT WINAPI ddraw_surface1_ReleaseDC(IDirectDrawSurface *iface, HDC dc)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface(iface);

    TRACE("iface %p, dc %p.\n", iface, dc);

    return ddraw_surface7_ReleaseDC(&surface->IDirectDrawSurface7_iface, dc);
}

/*****************************************************************************
 * IDirectDrawSurface7::GetCaps
 *
 * Returns the surface's caps
 *
 * Params:
 *  Caps: Address to write the caps to
 *
 * Returns:
 *  DD_OK on success
 *  DDERR_INVALIDPARAMS if Caps is NULL
 *
 *****************************************************************************/
static HRESULT WINAPI ddraw_surface7_GetCaps(IDirectDrawSurface7 *iface, DDSCAPS2 *Caps)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface7(iface);

    TRACE("iface %p, caps %p.\n", iface, Caps);

    if(!Caps)
        return DDERR_INVALIDPARAMS;

    *Caps = surface->surface_desc.ddsCaps;

    return DD_OK;
}

static HRESULT WINAPI ddraw_surface4_GetCaps(IDirectDrawSurface4 *iface, DDSCAPS2 *caps)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface4(iface);

    TRACE("iface %p, caps %p.\n", iface, caps);

    return ddraw_surface7_GetCaps(&surface->IDirectDrawSurface7_iface, caps);
}

static HRESULT WINAPI ddraw_surface3_GetCaps(IDirectDrawSurface3 *iface, DDSCAPS *caps)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface3(iface);
    DDSCAPS2 caps2;
    HRESULT hr;

    TRACE("iface %p, caps %p.\n", iface, caps);

    hr = ddraw_surface7_GetCaps(&surface->IDirectDrawSurface7_iface, &caps2);
    if (FAILED(hr)) return hr;

    caps->dwCaps = caps2.dwCaps;
    return hr;
}

static HRESULT WINAPI ddraw_surface2_GetCaps(IDirectDrawSurface2 *iface, DDSCAPS *caps)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface2(iface);
    DDSCAPS2 caps2;
    HRESULT hr;

    TRACE("iface %p, caps %p.\n", iface, caps);

    hr = ddraw_surface7_GetCaps(&surface->IDirectDrawSurface7_iface, &caps2);
    if (FAILED(hr)) return hr;

    caps->dwCaps = caps2.dwCaps;
    return hr;
}

static HRESULT WINAPI ddraw_surface1_GetCaps(IDirectDrawSurface *iface, DDSCAPS *caps)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface(iface);
    DDSCAPS2 caps2;
    HRESULT hr;

    TRACE("iface %p, caps %p.\n", iface, caps);

    hr = ddraw_surface7_GetCaps(&surface->IDirectDrawSurface7_iface, &caps2);
    if (FAILED(hr)) return hr;

    caps->dwCaps = caps2.dwCaps;
    return hr;
}

static HRESULT WINAPI ddraw_surface7_SetPriority(IDirectDrawSurface7 *iface, DWORD priority)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface7(iface);
    DWORD managed = DDSCAPS2_TEXTUREMANAGE | DDSCAPS2_D3DTEXTUREMANAGE;
    HRESULT hr;
    struct wined3d_resource *resource;

    TRACE("iface %p, priority %u.\n", iface, priority);

    wined3d_mutex_lock();
    /* No need to check for offscreen plain surfaces or mipmap sublevels. SetPriority
     * calls on such surfaces segfault on Windows. */
    if (!(surface->surface_desc.ddsCaps.dwCaps2 & managed))
    {
        WARN("Called on non-managed texture returning DDERR_INVALIDPARAMS.\n");
        hr = DDERR_INVALIDPARAMS;
    }
    else
    {
        resource = wined3d_texture_get_resource(surface->wined3d_texture);
        wined3d_resource_set_priority(resource, priority);
        hr = DD_OK;
    }
    wined3d_mutex_unlock();

    return hr;
}

static HRESULT WINAPI ddraw_surface7_GetPriority(IDirectDrawSurface7 *iface, DWORD *priority)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface7(iface);
    const struct wined3d_resource *resource;
    DWORD managed = DDSCAPS2_TEXTUREMANAGE | DDSCAPS2_D3DTEXTUREMANAGE;
    HRESULT hr;

    TRACE("iface %p, priority %p.\n", iface, priority);

    wined3d_mutex_lock();
    if (surface->surface_desc.ddsCaps.dwCaps & DDSCAPS_OFFSCREENPLAIN)
    {
        WARN("Called on offscreenplain surface, returning DDERR_INVALIDOBJECT.\n");
        hr = DDERR_INVALIDOBJECT;
    }
    else if (!(surface->surface_desc.ddsCaps.dwCaps2 & managed) || !surface->is_complex_root)
    {
        WARN("Called on non-managed texture or non-root surface, returning DDERR_INVALIDPARAMS.\n");
        hr = DDERR_INVALIDPARAMS;
    }
    else
    {
        resource = wined3d_texture_get_resource(surface->wined3d_texture);
        *priority = wined3d_resource_get_priority(resource);
        hr = DD_OK;
    }
    wined3d_mutex_unlock();

    return hr;
}

/*****************************************************************************
 * IDirectDrawSurface7::SetPrivateData
 *
 * Stores some data in the surface that is intended for the application's
 * use.
 *
 * Params:
 *  tag: GUID that identifies the data
 *  Data: Pointer to the private data
 *  Size: Size of the private data
 *  Flags: Some flags
 *
 * Returns:
 *  D3D_OK on success, error code otherwise.
 *
 *****************************************************************************/
static HRESULT WINAPI ddraw_surface7_SetPrivateData(IDirectDrawSurface7 *iface,
        REFGUID tag, void *data, DWORD size, DWORD flags)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface7(iface);
    HRESULT hr;

    TRACE("iface %p, tag %s, data %p, data_size %u, flags %#x.\n",
            iface, debugstr_guid(tag), data, size, flags);

    if (!data)
    {
        WARN("data is NULL, returning DDERR_INVALIDPARAMS.\n");
        return DDERR_INVALIDPARAMS;
    }

    wined3d_mutex_lock();
    hr = wined3d_private_store_set_private_data(&surface->private_store, tag, data, size, flags);
    wined3d_mutex_unlock();
    return hr_ddraw_from_wined3d(hr);
}

static HRESULT WINAPI ddraw_surface4_SetPrivateData(IDirectDrawSurface4 *iface,
        REFGUID tag, void *data, DWORD size, DWORD flags)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface4(iface);

    TRACE("iface %p, tag %s, data %p, data_size %u, flags %#x.\n",
                iface, debugstr_guid(tag), data, size, flags);

    return ddraw_surface7_SetPrivateData(&surface->IDirectDrawSurface7_iface, tag, data, size, flags);
}

/*****************************************************************************
 * IDirectDrawSurface7::GetPrivateData
 *
 * Returns the private data set with IDirectDrawSurface7::SetPrivateData
 *
 * Params:
 *  tag: GUID of the data to return
 *  Data: Address where to write the data to
 *  Size: Size of the buffer at Data
 *
 * Returns:
 *  DD_OK on success
 *  DDERR_INVALIDPARAMS if Data is NULL
 *
 *****************************************************************************/
static HRESULT WINAPI ddraw_surface7_GetPrivateData(IDirectDrawSurface7 *iface, REFGUID tag, void *data, DWORD *size)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface7(iface);
    const struct wined3d_private_data *stored_data;
    HRESULT hr;

    TRACE("iface %p, tag %s, data %p, data_size %p.\n",
            iface, debugstr_guid(tag), data, size);

    wined3d_mutex_lock();
    stored_data = wined3d_private_store_get_private_data(&surface->private_store, tag);
    if (!stored_data)
    {
        hr = DDERR_NOTFOUND;
        goto done;
    }
    if (!size)
    {
        hr = DDERR_INVALIDPARAMS;
        goto done;
    }
    if (*size < stored_data->size)
    {
        *size = stored_data->size;
        hr = DDERR_MOREDATA;
        goto done;
    }
    if (!data)
    {
        hr = DDERR_INVALIDPARAMS;
        goto done;
    }

    *size = stored_data->size;
    memcpy(data, stored_data->content.data, stored_data->size);
    hr = DD_OK;

done:
    wined3d_mutex_unlock();
    return hr;
}

static HRESULT WINAPI ddraw_surface4_GetPrivateData(IDirectDrawSurface4 *iface, REFGUID tag, void *data, DWORD *size)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface4(iface);

    TRACE("iface %p, tag %s, data %p, data_size %p.\n",
                iface, debugstr_guid(tag), data, size);

    return ddraw_surface7_GetPrivateData(&surface->IDirectDrawSurface7_iface, tag, data, size);
}

/*****************************************************************************
 * IDirectDrawSurface7::FreePrivateData
 *
 * Frees private data stored in the surface
 *
 * Params:
 *  tag: Tag of the data to free
 *
 * Returns:
 *  D3D_OK on success, error code otherwise.
 *
 *****************************************************************************/
static HRESULT WINAPI ddraw_surface7_FreePrivateData(IDirectDrawSurface7 *iface, REFGUID tag)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface7(iface);
    struct wined3d_private_data *entry;

    TRACE("iface %p, tag %s.\n", iface, debugstr_guid(tag));

    wined3d_mutex_lock();
    entry = wined3d_private_store_get_private_data(&surface->private_store, tag);
    if (!entry)
    {
        wined3d_mutex_unlock();
        return DDERR_NOTFOUND;
    }

    wined3d_private_store_free_private_data(&surface->private_store, entry);
    wined3d_mutex_unlock();

    return DD_OK;
}

static HRESULT WINAPI ddraw_surface4_FreePrivateData(IDirectDrawSurface4 *iface, REFGUID tag)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface4(iface);

    TRACE("iface %p, tag %s.\n", iface, debugstr_guid(tag));

    return ddraw_surface7_FreePrivateData(&surface->IDirectDrawSurface7_iface, tag);
}

/*****************************************************************************
 * IDirectDrawSurface7::PageLock
 *
 * Prevents a sysmem surface from being paged out
 *
 * Params:
 *  Flags: Not used, must be 0(unchecked)
 *
 * Returns:
 *  DD_OK, because it's a stub
 *
 *****************************************************************************/
static HRESULT WINAPI ddraw_surface7_PageLock(IDirectDrawSurface7 *iface, DWORD Flags)
{
    TRACE("iface %p, flags %#x.\n", iface, Flags);

    /* This is Windows memory management related - we don't need this */
    return DD_OK;
}

static HRESULT WINAPI ddraw_surface4_PageLock(IDirectDrawSurface4 *iface, DWORD flags)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface4(iface);

    TRACE("iface %p, flags %#x.\n", iface, flags);

    return ddraw_surface7_PageLock(&surface->IDirectDrawSurface7_iface, flags);
}

static HRESULT WINAPI ddraw_surface3_PageLock(IDirectDrawSurface3 *iface, DWORD flags)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface3(iface);

    TRACE("iface %p, flags %#x.\n", iface, flags);

    return ddraw_surface7_PageLock(&surface->IDirectDrawSurface7_iface, flags);
}

static HRESULT WINAPI ddraw_surface2_PageLock(IDirectDrawSurface2 *iface, DWORD flags)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface2(iface);

    TRACE("iface %p, flags %#x.\n", iface, flags);

    return ddraw_surface7_PageLock(&surface->IDirectDrawSurface7_iface, flags);
}

/*****************************************************************************
 * IDirectDrawSurface7::PageUnlock
 *
 * Allows a sysmem surface to be paged out
 *
 * Params:
 *  Flags: Not used, must be 0(unchecked)
 *
 * Returns:
 *  DD_OK, because it's a stub
 *
 *****************************************************************************/
static HRESULT WINAPI ddraw_surface7_PageUnlock(IDirectDrawSurface7 *iface, DWORD Flags)
{
    TRACE("iface %p, flags %#x.\n", iface, Flags);

    return DD_OK;
}

static HRESULT WINAPI ddraw_surface4_PageUnlock(IDirectDrawSurface4 *iface, DWORD flags)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface4(iface);

    TRACE("iface %p, flags %#x.\n", iface, flags);

    return ddraw_surface7_PageUnlock(&surface->IDirectDrawSurface7_iface, flags);
}

static HRESULT WINAPI ddraw_surface3_PageUnlock(IDirectDrawSurface3 *iface, DWORD flags)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface3(iface);

    TRACE("iface %p, flags %#x.\n", iface, flags);

    return ddraw_surface7_PageUnlock(&surface->IDirectDrawSurface7_iface, flags);
}

static HRESULT WINAPI ddraw_surface2_PageUnlock(IDirectDrawSurface2 *iface, DWORD flags)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface2(iface);

    TRACE("iface %p, flags %#x.\n", iface, flags);

    return ddraw_surface7_PageUnlock(&surface->IDirectDrawSurface7_iface, flags);
}

/*****************************************************************************
 * IDirectDrawSurface7::BltBatch
 *
 * An unimplemented function
 *
 * Params:
 *  ?
 *
 * Returns:
 *  DDERR_UNSUPPORTED
 *
 *****************************************************************************/
static HRESULT WINAPI DECLSPEC_HOTPATCH ddraw_surface7_BltBatch(IDirectDrawSurface7 *iface, DDBLTBATCH *Batch, DWORD Count, DWORD Flags)
{
    TRACE("iface %p, batch %p, count %u, flags %#x.\n", iface, Batch, Count, Flags);

    /* MSDN: "not currently implemented" */
    return DDERR_UNSUPPORTED;
}

static HRESULT WINAPI DECLSPEC_HOTPATCH ddraw_surface4_BltBatch(IDirectDrawSurface4 *iface, DDBLTBATCH *batch, DWORD count, DWORD flags)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface4(iface);

    TRACE("iface %p, batch %p, count %u, flags %#x.\n", iface, batch, count, flags);

    return ddraw_surface7_BltBatch(&surface->IDirectDrawSurface7_iface, batch, count, flags);
}

static HRESULT WINAPI DECLSPEC_HOTPATCH ddraw_surface3_BltBatch(IDirectDrawSurface3 *iface, DDBLTBATCH *batch, DWORD count, DWORD flags)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface3(iface);

    TRACE("iface %p, batch %p, count %u, flags %#x.\n", iface, batch, count, flags);

    return ddraw_surface7_BltBatch(&surface->IDirectDrawSurface7_iface, batch, count, flags);
}

static HRESULT WINAPI DECLSPEC_HOTPATCH ddraw_surface2_BltBatch(IDirectDrawSurface2 *iface, DDBLTBATCH *batch, DWORD count, DWORD flags)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface2(iface);

    TRACE("iface %p, batch %p, count %u, flags %#x.\n", iface, batch, count, flags);

    return ddraw_surface7_BltBatch(&surface->IDirectDrawSurface7_iface, batch, count, flags);
}

static HRESULT WINAPI DECLSPEC_HOTPATCH ddraw_surface1_BltBatch(IDirectDrawSurface *iface, DDBLTBATCH *batch, DWORD count, DWORD flags)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface(iface);

    TRACE("iface %p, batch %p, count %u, flags %#x.\n", iface, batch, count, flags);

    return ddraw_surface7_BltBatch(&surface->IDirectDrawSurface7_iface, batch, count, flags);
}

/*****************************************************************************
 * IDirectDrawSurface7::EnumAttachedSurfaces
 *
 * Enumerates all surfaces attached to this surface
 *
 * Params:
 *  context: Pointer to pass unmodified to the callback
 *  cb: Callback function to call for each surface
 *
 * Returns:
 *  DD_OK on success
 *  DDERR_INVALIDPARAMS if cb is NULL
 *
 *****************************************************************************/
static HRESULT WINAPI ddraw_surface7_EnumAttachedSurfaces(IDirectDrawSurface7 *iface,
        void *context, LPDDENUMSURFACESCALLBACK7 cb)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface7(iface);
    struct ddraw_surface *surf;
    DDSURFACEDESC2 desc;
    int i;

    /* Attached surfaces aren't handled in WineD3D */
    TRACE("iface %p, context %p, callback %p.\n", iface, context, cb);

    if(!cb)
        return DDERR_INVALIDPARAMS;

    wined3d_mutex_lock();

    for(i = 0; i < MAX_COMPLEX_ATTACHED; i++)
    {
        surf = surface->complex_array[i];
        if(!surf) break;

        ddraw_surface7_AddRef(&surf->IDirectDrawSurface7_iface);
        desc = surf->surface_desc;
        /* check: != DDENUMRET_OK or == DDENUMRET_CANCEL? */
        if (cb(&surf->IDirectDrawSurface7_iface, &desc, context) == DDENUMRET_CANCEL)
        {
            wined3d_mutex_unlock();
            return DD_OK;
        }
    }

    for (surf = surface->next_attached; surf != NULL; surf = surf->next_attached)
    {
        ddraw_surface7_AddRef(&surf->IDirectDrawSurface7_iface);
        desc = surf->surface_desc;
        /* check: != DDENUMRET_OK or == DDENUMRET_CANCEL? */
        if (cb(&surf->IDirectDrawSurface7_iface, &desc, context) == DDENUMRET_CANCEL)
        {
            wined3d_mutex_unlock();
            return DD_OK;
        }
    }

    TRACE(" end of enumeration.\n");

    wined3d_mutex_unlock();

    return DD_OK;
}

struct callback_info2
{
    LPDDENUMSURFACESCALLBACK2 callback;
    void *context;
};

struct callback_info
{
    LPDDENUMSURFACESCALLBACK callback;
    void *context;
};

static HRESULT CALLBACK EnumCallback2(IDirectDrawSurface7 *surface, DDSURFACEDESC2 *surface_desc, void *context)
{
    struct ddraw_surface *surface_impl = impl_from_IDirectDrawSurface7(surface);
    const struct callback_info2 *info = context;

    ddraw_surface4_AddRef(&surface_impl->IDirectDrawSurface4_iface);
    ddraw_surface7_Release(surface);

    return info->callback(&surface_impl->IDirectDrawSurface4_iface, surface_desc, info->context);
}

static HRESULT CALLBACK EnumCallback(IDirectDrawSurface7 *surface, DDSURFACEDESC2 *surface_desc, void *context)
{
    struct ddraw_surface *surface_impl = impl_from_IDirectDrawSurface7(surface);
    const struct callback_info *info = context;

    ddraw_surface1_AddRef(&surface_impl->IDirectDrawSurface_iface);
    ddraw_surface7_Release(surface);

    /* FIXME: Check surface_test.dwSize */
    return info->callback(&surface_impl->IDirectDrawSurface_iface,
            (DDSURFACEDESC *)surface_desc, info->context);
}

static HRESULT WINAPI ddraw_surface4_EnumAttachedSurfaces(IDirectDrawSurface4 *iface,
        void *context, LPDDENUMSURFACESCALLBACK2 callback)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface4(iface);
    struct callback_info2 info;

    TRACE("iface %p, context %p, callback %p.\n", iface, context, callback);

    info.callback = callback;
    info.context  = context;

    return ddraw_surface7_EnumAttachedSurfaces(&surface->IDirectDrawSurface7_iface,
            &info, EnumCallback2);
}

static HRESULT WINAPI ddraw_surface3_EnumAttachedSurfaces(IDirectDrawSurface3 *iface,
        void *context, LPDDENUMSURFACESCALLBACK callback)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface3(iface);
    struct callback_info info;

    TRACE("iface %p, context %p, callback %p.\n", iface, context, callback);

    info.callback = callback;
    info.context  = context;

    return ddraw_surface7_EnumAttachedSurfaces(&surface->IDirectDrawSurface7_iface,
            &info, EnumCallback);
}

static HRESULT WINAPI ddraw_surface2_EnumAttachedSurfaces(IDirectDrawSurface2 *iface,
        void *context, LPDDENUMSURFACESCALLBACK callback)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface2(iface);
    struct callback_info info;

    TRACE("iface %p, context %p, callback %p.\n", iface, context, callback);

    info.callback = callback;
    info.context  = context;

    return ddraw_surface7_EnumAttachedSurfaces(&surface->IDirectDrawSurface7_iface,
            &info, EnumCallback);
}

static HRESULT WINAPI ddraw_surface1_EnumAttachedSurfaces(IDirectDrawSurface *iface,
        void *context, LPDDENUMSURFACESCALLBACK callback)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface(iface);
    struct callback_info info;

    TRACE("iface %p, context %p, callback %p.\n", iface, context, callback);

    info.callback = callback;
    info.context  = context;

    return ddraw_surface7_EnumAttachedSurfaces(&surface->IDirectDrawSurface7_iface,
            &info, EnumCallback);
}

/*****************************************************************************
 * IDirectDrawSurface7::EnumOverlayZOrders
 *
 * "Enumerates the overlay surfaces on the specified destination"
 *
 * Params:
 *  Flags: DDENUMOVERLAYZ_BACKTOFRONT  or DDENUMOVERLAYZ_FRONTTOBACK
 *  context: context to pass back to the callback
 *  cb: callback function to call for each enumerated surface
 *
 * Returns:
 *  DD_OK, because it's a stub
 *
 *****************************************************************************/
static HRESULT WINAPI ddraw_surface7_EnumOverlayZOrders(IDirectDrawSurface7 *iface,
        DWORD Flags, void *context, LPDDENUMSURFACESCALLBACK7 cb)
{
    FIXME("iface %p, flags %#x, context %p, callback %p stub!\n", iface, Flags, context, cb);

    return DD_OK;
}

static HRESULT WINAPI ddraw_surface4_EnumOverlayZOrders(IDirectDrawSurface4 *iface,
        DWORD flags, void *context, LPDDENUMSURFACESCALLBACK2 callback)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface4(iface);
    struct callback_info2 info;

    TRACE("iface %p, flags %#x, context %p, callback %p.\n", iface, flags, context, callback);

    info.callback = callback;
    info.context  = context;

    return ddraw_surface7_EnumOverlayZOrders(&surface->IDirectDrawSurface7_iface,
            flags, &info, EnumCallback2);
}

static HRESULT WINAPI ddraw_surface3_EnumOverlayZOrders(IDirectDrawSurface3 *iface,
        DWORD flags, void *context, LPDDENUMSURFACESCALLBACK callback)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface3(iface);
    struct callback_info info;

    TRACE("iface %p, flags %#x, context %p, callback %p.\n", iface, flags, context, callback);

    info.callback = callback;
    info.context  = context;

    return ddraw_surface7_EnumOverlayZOrders(&surface->IDirectDrawSurface7_iface,
            flags, &info, EnumCallback);
}

static HRESULT WINAPI ddraw_surface2_EnumOverlayZOrders(IDirectDrawSurface2 *iface,
        DWORD flags, void *context, LPDDENUMSURFACESCALLBACK callback)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface2(iface);
    struct callback_info info;

    TRACE("iface %p, flags %#x, context %p, callback %p.\n", iface, flags, context, callback);

    info.callback = callback;
    info.context  = context;

    return ddraw_surface7_EnumOverlayZOrders(&surface->IDirectDrawSurface7_iface,
            flags, &info, EnumCallback);
}

static HRESULT WINAPI ddraw_surface1_EnumOverlayZOrders(IDirectDrawSurface *iface,
        DWORD flags, void *context, LPDDENUMSURFACESCALLBACK callback)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface(iface);
    struct callback_info info;

    TRACE("iface %p, flags %#x, context %p, callback %p.\n", iface, flags, context, callback);

    info.callback = callback;
    info.context  = context;

    return ddraw_surface7_EnumOverlayZOrders(&surface->IDirectDrawSurface7_iface,
            flags, &info, EnumCallback);
}

/*****************************************************************************
 * IDirectDrawSurface7::GetBltStatus
 *
 * Returns the blitting status
 *
 * Params:
 *  Flags: DDGBS_CANBLT or DDGBS_ISBLTDONE
 *
 *****************************************************************************/
static HRESULT WINAPI ddraw_surface7_GetBltStatus(IDirectDrawSurface7 *iface, DWORD Flags)
{
    TRACE("iface %p, flags %#x.\n", iface, Flags);

    switch (Flags)
    {
        case WINEDDGBS_CANBLT:
        case WINEDDGBS_ISBLTDONE:
            return DD_OK;

        default:
            return DDERR_INVALIDPARAMS;
    }
}

static HRESULT WINAPI ddraw_surface4_GetBltStatus(IDirectDrawSurface4 *iface, DWORD flags)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface4(iface);

    TRACE("iface %p, flags %#x.\n", iface, flags);

    return ddraw_surface7_GetBltStatus(&surface->IDirectDrawSurface7_iface, flags);
}

static HRESULT WINAPI ddraw_surface3_GetBltStatus(IDirectDrawSurface3 *iface, DWORD flags)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface3(iface);

    TRACE("iface %p, flags %#x.\n", iface, flags);

    return ddraw_surface7_GetBltStatus(&surface->IDirectDrawSurface7_iface, flags);
}

static HRESULT WINAPI ddraw_surface2_GetBltStatus(IDirectDrawSurface2 *iface, DWORD flags)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface2(iface);

    TRACE("iface %p, flags %#x.\n", iface, flags);

    return ddraw_surface7_GetBltStatus(&surface->IDirectDrawSurface7_iface, flags);
}

static HRESULT WINAPI ddraw_surface1_GetBltStatus(IDirectDrawSurface *iface, DWORD flags)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface(iface);

    TRACE("iface %p, flags %#x.\n", iface, flags);

    return ddraw_surface7_GetBltStatus(&surface->IDirectDrawSurface7_iface, flags);
}

/*****************************************************************************
 * IDirectDrawSurface7::GetColorKey
 *
 * Returns the color key assigned to the surface
 *
 * Params:
 *  Flags: Some flags
 *  CKey: Address to store the key to
 *
 * Returns:
 *  DD_OK on success
 *  DDERR_INVALIDPARAMS if CKey is NULL
 *
 *****************************************************************************/
static HRESULT WINAPI ddraw_surface7_GetColorKey(IDirectDrawSurface7 *iface, DWORD Flags, DDCOLORKEY *CKey)
{
    struct ddraw_surface *This = impl_from_IDirectDrawSurface7(iface);

    TRACE("iface %p, flags %#x, color_key %p.\n", iface, Flags, CKey);

    if(!CKey)
        return DDERR_INVALIDPARAMS;

    wined3d_mutex_lock();

    switch (Flags)
    {
    case DDCKEY_DESTBLT:
        if (!(This->surface_desc.dwFlags & DDSD_CKDESTBLT))
        {
            wined3d_mutex_unlock();
            return DDERR_NOCOLORKEY;
        }
        *CKey = This->surface_desc.ddckCKDestBlt;
        break;

    case DDCKEY_DESTOVERLAY:
        if (!(This->surface_desc.dwFlags & DDSD_CKDESTOVERLAY))
        {
            wined3d_mutex_unlock();
            return DDERR_NOCOLORKEY;
        }
        *CKey = This->surface_desc.u3.ddckCKDestOverlay;
        break;

    case DDCKEY_SRCBLT:
        if (!(This->surface_desc.dwFlags & DDSD_CKSRCBLT))
        {
            wined3d_mutex_unlock();
            return DDERR_NOCOLORKEY;
        }
        *CKey = This->surface_desc.ddckCKSrcBlt;
        break;

    case DDCKEY_SRCOVERLAY:
        if (!(This->surface_desc.dwFlags & DDSD_CKSRCOVERLAY))
        {
            wined3d_mutex_unlock();
            return DDERR_NOCOLORKEY;
        }
        *CKey = This->surface_desc.ddckCKSrcOverlay;
        break;

    default:
        wined3d_mutex_unlock();
        return DDERR_INVALIDPARAMS;
    }

    wined3d_mutex_unlock();

    return DD_OK;
}

static HRESULT WINAPI ddraw_surface4_GetColorKey(IDirectDrawSurface4 *iface, DWORD flags, DDCOLORKEY *color_key)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface4(iface);

    TRACE("iface %p, flags %#x, color_key %p.\n", iface, flags, color_key);

    return ddraw_surface7_GetColorKey(&surface->IDirectDrawSurface7_iface, flags, color_key);
}

static HRESULT WINAPI ddraw_surface3_GetColorKey(IDirectDrawSurface3 *iface, DWORD flags, DDCOLORKEY *color_key)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface3(iface);

    TRACE("iface %p, flags %#x, color_key %p.\n", iface, flags, color_key);

    return ddraw_surface7_GetColorKey(&surface->IDirectDrawSurface7_iface, flags, color_key);
}

static HRESULT WINAPI ddraw_surface2_GetColorKey(IDirectDrawSurface2 *iface, DWORD flags, DDCOLORKEY *color_key)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface2(iface);

    TRACE("iface %p, flags %#x, color_key %p.\n", iface, flags, color_key);

    return ddraw_surface7_GetColorKey(&surface->IDirectDrawSurface7_iface, flags, color_key);
}

static HRESULT WINAPI ddraw_surface1_GetColorKey(IDirectDrawSurface *iface, DWORD flags, DDCOLORKEY *color_key)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface(iface);

    TRACE("iface %p, flags %#x, color_key %p.\n", iface, flags, color_key);

    return ddraw_surface7_GetColorKey(&surface->IDirectDrawSurface7_iface, flags, color_key);
}

/*****************************************************************************
 * IDirectDrawSurface7::GetFlipStatus
 *
 * Returns the flipping status of the surface
 *
 * Params:
 *  Flags: DDGFS_CANFLIP of DDGFS_ISFLIPDONE
 *
 *****************************************************************************/
static HRESULT WINAPI ddraw_surface7_GetFlipStatus(IDirectDrawSurface7 *iface, DWORD Flags)
{
    TRACE("iface %p, flags %#x.\n", iface, Flags);

    /* XXX: DDERR_INVALIDSURFACETYPE */

    switch (Flags)
    {
        case WINEDDGFS_CANFLIP:
        case WINEDDGFS_ISFLIPDONE:
            return DD_OK;

        default:
            return DDERR_INVALIDPARAMS;
    }
}

static HRESULT WINAPI ddraw_surface4_GetFlipStatus(IDirectDrawSurface4 *iface, DWORD flags)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface4(iface);

    TRACE("iface %p, flags %#x.\n", iface, flags);

    return ddraw_surface7_GetFlipStatus(&surface->IDirectDrawSurface7_iface, flags);
}

static HRESULT WINAPI ddraw_surface3_GetFlipStatus(IDirectDrawSurface3 *iface, DWORD flags)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface3(iface);

    TRACE("iface %p, flags %#x.\n", iface, flags);

    return ddraw_surface7_GetFlipStatus(&surface->IDirectDrawSurface7_iface, flags);
}

static HRESULT WINAPI ddraw_surface2_GetFlipStatus(IDirectDrawSurface2 *iface, DWORD flags)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface2(iface);

    TRACE("iface %p, flags %#x.\n", iface, flags);

    return ddraw_surface7_GetFlipStatus(&surface->IDirectDrawSurface7_iface, flags);
}

static HRESULT WINAPI ddraw_surface1_GetFlipStatus(IDirectDrawSurface *iface, DWORD flags)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface(iface);

    TRACE("iface %p, flags %#x.\n", iface, flags);

    return ddraw_surface7_GetFlipStatus(&surface->IDirectDrawSurface7_iface, flags);
}

/*****************************************************************************
 * IDirectDrawSurface7::GetOverlayPosition
 *
 * Returns the display coordinates of a visible and active overlay surface
 *
 * Params:
 *  X
 *  Y
 *
 * Returns:
 *  DDERR_NOTAOVERLAYSURFACE, because it's a stub
 *****************************************************************************/
static HRESULT WINAPI ddraw_surface7_GetOverlayPosition(IDirectDrawSurface7 *iface, LONG *x, LONG *y)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface7(iface);
    HRESULT hr;

    TRACE("iface %p, x %p, y %p.\n", iface, x, y);

    wined3d_mutex_lock();
    hr = wined3d_texture_get_overlay_position(surface->wined3d_texture,
            surface->sub_resource_idx, x, y);
    wined3d_mutex_unlock();

    return hr;
}

static HRESULT WINAPI ddraw_surface4_GetOverlayPosition(IDirectDrawSurface4 *iface, LONG *x, LONG *y)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface4(iface);

    TRACE("iface %p, x %p, y %p.\n", iface, x, y);

    return ddraw_surface7_GetOverlayPosition(&surface->IDirectDrawSurface7_iface, x, y);
}

static HRESULT WINAPI ddraw_surface3_GetOverlayPosition(IDirectDrawSurface3 *iface, LONG *x, LONG *y)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface3(iface);

    TRACE("iface %p, x %p, y %p.\n", iface, x, y);

    return ddraw_surface7_GetOverlayPosition(&surface->IDirectDrawSurface7_iface, x, y);
}

static HRESULT WINAPI ddraw_surface2_GetOverlayPosition(IDirectDrawSurface2 *iface, LONG *x, LONG *y)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface2(iface);

    TRACE("iface %p, x %p, y %p.\n", iface, x, y);

    return ddraw_surface7_GetOverlayPosition(&surface->IDirectDrawSurface7_iface, x, y);
}

static HRESULT WINAPI ddraw_surface1_GetOverlayPosition(IDirectDrawSurface *iface, LONG *x, LONG *y)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface(iface);

    TRACE("iface %p, x %p, y %p.\n", iface, x, y);

    return ddraw_surface7_GetOverlayPosition(&surface->IDirectDrawSurface7_iface, x, y);
}

/*****************************************************************************
 * IDirectDrawSurface7::GetPixelFormat
 *
 * Returns the pixel format of the Surface
 *
 * Params:
 *  PixelFormat: Pointer to a DDPIXELFORMAT structure to which the pixel
 *               format should be written
 *
 * Returns:
 *  DD_OK on success
 *  DDERR_INVALIDPARAMS if PixelFormat is NULL
 *
 *****************************************************************************/
static HRESULT WINAPI ddraw_surface7_GetPixelFormat(IDirectDrawSurface7 *iface, DDPIXELFORMAT *PixelFormat)
{
    /* What is DDERR_INVALIDSURFACETYPE for here? */
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface7(iface);

    TRACE("iface %p, pixel_format %p.\n", iface, PixelFormat);

    if(!PixelFormat)
        return DDERR_INVALIDPARAMS;

    wined3d_mutex_lock();
    DD_STRUCT_COPY_BYSIZE(PixelFormat, &surface->surface_desc.u4.ddpfPixelFormat);
    wined3d_mutex_unlock();

    return DD_OK;
}

static HRESULT WINAPI ddraw_surface4_GetPixelFormat(IDirectDrawSurface4 *iface, DDPIXELFORMAT *pixel_format)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface4(iface);

    TRACE("iface %p, pixel_format %p.\n", iface, pixel_format);

    return ddraw_surface7_GetPixelFormat(&surface->IDirectDrawSurface7_iface, pixel_format);
}

static HRESULT WINAPI ddraw_surface3_GetPixelFormat(IDirectDrawSurface3 *iface, DDPIXELFORMAT *pixel_format)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface3(iface);

    TRACE("iface %p, pixel_format %p.\n", iface, pixel_format);

    return ddraw_surface7_GetPixelFormat(&surface->IDirectDrawSurface7_iface, pixel_format);
}

static HRESULT WINAPI ddraw_surface2_GetPixelFormat(IDirectDrawSurface2 *iface, DDPIXELFORMAT *pixel_format)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface2(iface);

    TRACE("iface %p, pixel_format %p.\n", iface, pixel_format);

    return ddraw_surface7_GetPixelFormat(&surface->IDirectDrawSurface7_iface, pixel_format);
}

static HRESULT WINAPI ddraw_surface1_GetPixelFormat(IDirectDrawSurface *iface, DDPIXELFORMAT *pixel_format)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface(iface);

    TRACE("iface %p, pixel_format %p.\n", iface, pixel_format);

    return ddraw_surface7_GetPixelFormat(&surface->IDirectDrawSurface7_iface, pixel_format);
}

/*****************************************************************************
 * IDirectDrawSurface7::GetSurfaceDesc
 *
 * Returns the description of this surface
 *
 * Params:
 *  DDSD: Address of a DDSURFACEDESC2 structure that is to be filled with the
 *        surface desc
 *
 * Returns:
 *  DD_OK on success
 *  DDERR_INVALIDPARAMS if DDSD is NULL
 *
 *****************************************************************************/
static HRESULT WINAPI ddraw_surface7_GetSurfaceDesc(IDirectDrawSurface7 *iface, DDSURFACEDESC2 *DDSD)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface7(iface);

    TRACE("iface %p, surface_desc %p.\n", iface, DDSD);

    if(!DDSD)
        return DDERR_INVALIDPARAMS;

    if (DDSD->dwSize != sizeof(DDSURFACEDESC2))
    {
        WARN("Incorrect struct size %d, returning DDERR_INVALIDPARAMS\n",DDSD->dwSize);
        return DDERR_INVALIDPARAMS;
    }

    wined3d_mutex_lock();
    DD_STRUCT_COPY_BYSIZE(DDSD, &surface->surface_desc);
    TRACE("Returning surface desc:\n");
    if (TRACE_ON(ddraw)) DDRAW_dump_surface_desc(DDSD);
    wined3d_mutex_unlock();

    return DD_OK;
}

static HRESULT WINAPI ddraw_surface4_GetSurfaceDesc(IDirectDrawSurface4 *iface, DDSURFACEDESC2 *DDSD)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface4(iface);

    TRACE("iface %p, surface_desc %p.\n", iface, DDSD);

    return ddraw_surface7_GetSurfaceDesc(&surface->IDirectDrawSurface7_iface, DDSD);
}

static HRESULT WINAPI ddraw_surface3_GetSurfaceDesc(IDirectDrawSurface3 *iface, DDSURFACEDESC *surface_desc)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface3(iface);

    TRACE("iface %p, surface_desc %p.\n", iface, surface_desc);

    if (!surface_desc) return DDERR_INVALIDPARAMS;

    if (surface_desc->dwSize != sizeof(DDSURFACEDESC))
    {
        WARN("Incorrect structure size %u, returning DDERR_INVALIDPARAMS.\n", surface_desc->dwSize);
        return DDERR_INVALIDPARAMS;
    }

    wined3d_mutex_lock();
    DDSD2_to_DDSD(&surface->surface_desc, surface_desc);
    TRACE("Returning surface desc:\n");
    if (TRACE_ON(ddraw))
    {
        /* DDRAW_dump_surface_desc handles the smaller size */
        DDRAW_dump_surface_desc((DDSURFACEDESC2 *)surface_desc);
    }
    wined3d_mutex_unlock();

    return DD_OK;
}

static HRESULT WINAPI ddraw_surface2_GetSurfaceDesc(IDirectDrawSurface2 *iface, DDSURFACEDESC *DDSD)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface2(iface);

    TRACE("iface %p, surface_desc %p.\n", iface, DDSD);

    return ddraw_surface3_GetSurfaceDesc(&surface->IDirectDrawSurface3_iface, DDSD);
}

static HRESULT WINAPI ddraw_surface1_GetSurfaceDesc(IDirectDrawSurface *iface, DDSURFACEDESC *DDSD)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface(iface);

    TRACE("iface %p, surface_desc %p.\n", iface, DDSD);

    return ddraw_surface3_GetSurfaceDesc(&surface->IDirectDrawSurface3_iface, DDSD);
}

/*****************************************************************************
 * IDirectDrawSurface7::Initialize
 *
 * Initializes the surface. This is a no-op in Wine
 *
 * Params:
 *  DD: Pointer to an DirectDraw interface
 *  DDSD: Surface description for initialization
 *
 * Returns:
 *  DDERR_ALREADYINITIALIZED
 *
 *****************************************************************************/
static HRESULT WINAPI ddraw_surface7_Initialize(IDirectDrawSurface7 *iface,
        IDirectDraw *ddraw, DDSURFACEDESC2 *surface_desc)
{
    TRACE("iface %p, ddraw %p, surface_desc %p.\n", iface, ddraw, surface_desc);

    return DDERR_ALREADYINITIALIZED;
}

static HRESULT WINAPI ddraw_surface4_Initialize(IDirectDrawSurface4 *iface,
        IDirectDraw *ddraw, DDSURFACEDESC2 *surface_desc)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface4(iface);

    TRACE("iface %p, ddraw %p, surface_desc %p.\n", iface, ddraw, surface_desc);

    return ddraw_surface7_Initialize(&surface->IDirectDrawSurface7_iface,
            ddraw, surface_desc);
}

static HRESULT WINAPI ddraw_surface3_Initialize(IDirectDrawSurface3 *iface,
        IDirectDraw *ddraw, DDSURFACEDESC *surface_desc)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface3(iface);
    DDSURFACEDESC2 surface_desc2;

    TRACE("iface %p, ddraw %p, surface_desc %p.\n", iface, ddraw, surface_desc);

    if (surface_desc) DDSD_to_DDSD2(surface_desc, &surface_desc2);
    return ddraw_surface7_Initialize(&surface->IDirectDrawSurface7_iface,
            ddraw, surface_desc ? &surface_desc2 : NULL);
}

static HRESULT WINAPI ddraw_surface2_Initialize(IDirectDrawSurface2 *iface,
        IDirectDraw *ddraw, DDSURFACEDESC *surface_desc)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface2(iface);
    DDSURFACEDESC2 surface_desc2;

    TRACE("iface %p, ddraw %p, surface_desc %p.\n", iface, ddraw, surface_desc);

    if (surface_desc) DDSD_to_DDSD2(surface_desc, &surface_desc2);
    return ddraw_surface7_Initialize(&surface->IDirectDrawSurface7_iface,
            ddraw, surface_desc ? &surface_desc2 : NULL);
}

static HRESULT WINAPI ddraw_surface1_Initialize(IDirectDrawSurface *iface,
        IDirectDraw *ddraw, DDSURFACEDESC *surface_desc)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface(iface);
    DDSURFACEDESC2 surface_desc2;

    TRACE("iface %p, ddraw %p, surface_desc %p.\n", iface, ddraw, surface_desc);

    if (surface_desc) DDSD_to_DDSD2(surface_desc, &surface_desc2);
    return ddraw_surface7_Initialize(&surface->IDirectDrawSurface7_iface,
            ddraw, surface_desc ? &surface_desc2 : NULL);
}

/*****************************************************************************
 * IDirect3DTexture1::Initialize
 *
 * The sdk says it's not implemented
 *
 * Params:
 *  ?
 *
 * Returns
 *  DDERR_UNSUPPORTED
 *
 *****************************************************************************/
static HRESULT WINAPI d3d_texture1_Initialize(IDirect3DTexture *iface,
        IDirect3DDevice *device, IDirectDrawSurface *surface)
{
    TRACE("iface %p, device %p, surface %p.\n", iface, device, surface);

    return DDERR_UNSUPPORTED; /* Unchecked */
}

/*****************************************************************************
 * IDirectDrawSurface7::IsLost
 *
 * Checks if the surface is lost
 *
 * Returns:
 *  DD_OK, if the surface is usable
 *  DDERR_ISLOST if the surface is lost
 *
 *****************************************************************************/
static HRESULT WINAPI ddraw_surface7_IsLost(IDirectDrawSurface7 *iface)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface7(iface);

    TRACE("iface %p.\n", iface);

    if (surface->ddraw->device_state != DDRAW_DEVICE_STATE_OK || surface->is_lost)
        return DDERR_SURFACELOST;

    return DD_OK;
}

static HRESULT WINAPI ddraw_surface4_IsLost(IDirectDrawSurface4 *iface)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface4(iface);

    TRACE("iface %p.\n", iface);

    return ddraw_surface7_IsLost(&surface->IDirectDrawSurface7_iface);
}

static HRESULT WINAPI ddraw_surface3_IsLost(IDirectDrawSurface3 *iface)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface3(iface);

    TRACE("iface %p.\n", iface);

    return ddraw_surface7_IsLost(&surface->IDirectDrawSurface7_iface);
}

static HRESULT WINAPI ddraw_surface2_IsLost(IDirectDrawSurface2 *iface)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface2(iface);

    TRACE("iface %p.\n", iface);

    return ddraw_surface7_IsLost(&surface->IDirectDrawSurface7_iface);
}

static HRESULT WINAPI ddraw_surface1_IsLost(IDirectDrawSurface *iface)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface(iface);

    TRACE("iface %p.\n", iface);

    return ddraw_surface7_IsLost(&surface->IDirectDrawSurface7_iface);
}

/*****************************************************************************
 * IDirectDrawSurface7::Restore
 *
 * Restores a lost surface. This makes the surface usable again, but
 * doesn't reload its old contents
 *
 * Returns:
 *  DD_OK on success, error code otherwise.
 *
 *****************************************************************************/
static HRESULT WINAPI ddraw_surface7_Restore(IDirectDrawSurface7 *iface)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface7(iface);

    TRACE("iface %p.\n", iface);

    if (surface->surface_desc.ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE)
    {
        struct wined3d_swapchain *swapchain = surface->ddraw->wined3d_swapchain;
        struct wined3d_sub_resource_desc wined3d_desc;
        struct wined3d_display_mode mode;
        HRESULT hr;

        if (FAILED(hr = wined3d_swapchain_get_display_mode(swapchain, &mode, NULL)))
        {
            WARN("Failed to get display mode, hr %#x.\n", hr);
            return hr;
        }

        if (FAILED(hr = wined3d_texture_get_sub_resource_desc(surface->wined3d_texture, 0, &wined3d_desc)))
        {
            WARN("Failed to get resource desc, hr %#x.\n", hr);
            return hr;
        }

        if (mode.width != wined3d_desc.width || mode.height != wined3d_desc.height)
        {
            WARN("Display mode dimensions %ux%u don't match surface dimensions %ux%u.\n",
                    mode.width, mode.height, wined3d_desc.width, wined3d_desc.height);
            return DDERR_WRONGMODE;
        }

        if (mode.format_id != wined3d_desc.format)
        {
            WARN("Display mode format %#x doesn't match surface format %#x.\n",
                    mode.format_id, wined3d_desc.format);
            return DDERR_WRONGMODE;
        }
    }

    ddraw_update_lost_surfaces(surface->ddraw);
    surface->is_lost = FALSE;

    return DD_OK;
}

static HRESULT WINAPI ddraw_surface4_Restore(IDirectDrawSurface4 *iface)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface4(iface);

    TRACE("iface %p.\n", iface);

    return ddraw_surface7_Restore(&surface->IDirectDrawSurface7_iface);
}

static HRESULT WINAPI ddraw_surface3_Restore(IDirectDrawSurface3 *iface)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface3(iface);

    TRACE("iface %p.\n", iface);

    return ddraw_surface7_Restore(&surface->IDirectDrawSurface7_iface);
}

static HRESULT WINAPI ddraw_surface2_Restore(IDirectDrawSurface2 *iface)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface2(iface);

    TRACE("iface %p.\n", iface);

    return ddraw_surface7_Restore(&surface->IDirectDrawSurface7_iface);
}

static HRESULT WINAPI ddraw_surface1_Restore(IDirectDrawSurface *iface)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface(iface);

    TRACE("iface %p.\n", iface);

    return ddraw_surface7_Restore(&surface->IDirectDrawSurface7_iface);
}

/*****************************************************************************
 * IDirectDrawSurface7::SetOverlayPosition
 *
 * Changes the display coordinates of an overlay surface
 *
 * Params:
 *  X:
 *  Y:
 *
 * Returns:
 *   DDERR_NOTAOVERLAYSURFACE, because we don't support overlays right now
 *****************************************************************************/
static HRESULT WINAPI ddraw_surface7_SetOverlayPosition(IDirectDrawSurface7 *iface, LONG x, LONG y)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface7(iface);
    HRESULT hr;

    TRACE("iface %p, x %d, y %d.\n", iface, x, y);

    wined3d_mutex_lock();
    hr = wined3d_texture_set_overlay_position(surface->wined3d_texture,
            surface->sub_resource_idx, x, y);
    wined3d_mutex_unlock();

    return hr;
}

static HRESULT WINAPI ddraw_surface4_SetOverlayPosition(IDirectDrawSurface4 *iface, LONG x, LONG y)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface4(iface);

    TRACE("iface %p, x %d, y %d.\n", iface, x, y);

    return ddraw_surface7_SetOverlayPosition(&surface->IDirectDrawSurface7_iface, x, y);
}

static HRESULT WINAPI ddraw_surface3_SetOverlayPosition(IDirectDrawSurface3 *iface, LONG x, LONG y)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface3(iface);

    TRACE("iface %p, x %d, y %d.\n", iface, x, y);

    return ddraw_surface7_SetOverlayPosition(&surface->IDirectDrawSurface7_iface, x, y);
}

static HRESULT WINAPI ddraw_surface2_SetOverlayPosition(IDirectDrawSurface2 *iface, LONG x, LONG y)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface2(iface);

    TRACE("iface %p, x %d, y %d.\n", iface, x, y);

    return ddraw_surface7_SetOverlayPosition(&surface->IDirectDrawSurface7_iface, x, y);
}

static HRESULT WINAPI ddraw_surface1_SetOverlayPosition(IDirectDrawSurface *iface, LONG x, LONG y)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface(iface);

    TRACE("iface %p, x %d, y %d.\n", iface, x, y);

    return ddraw_surface7_SetOverlayPosition(&surface->IDirectDrawSurface7_iface, x, y);
}

/*****************************************************************************
 * IDirectDrawSurface7::UpdateOverlay
 *
 * Modifies the attributes of an overlay surface.
 *
 * Params:
 *  SrcRect: The section of the source being used for the overlay
 *  DstSurface: Address of the surface that is overlaid
 *  DstRect: Place of the overlay
 *  Flags: some DDOVER_* flags
 *
 * Returns:
 *  DDERR_UNSUPPORTED, because we don't support overlays
 *
 *****************************************************************************/
static HRESULT WINAPI ddraw_surface7_UpdateOverlay(IDirectDrawSurface7 *iface, RECT *src_rect,
        IDirectDrawSurface7 *dst_surface, RECT *dst_rect, DWORD flags, DDOVERLAYFX *fx)
{
    struct ddraw_surface *src_impl = impl_from_IDirectDrawSurface7(iface);
    struct ddraw_surface *dst_impl = unsafe_impl_from_IDirectDrawSurface7(dst_surface);
    struct wined3d_texture *dst_wined3d_texture = NULL;
    unsigned int dst_sub_resource_idx = 0;
    HRESULT hr;

    TRACE("iface %p, src_rect %s, dst_surface %p, dst_rect %s, flags %#x, fx %p.\n",
            iface, wine_dbgstr_rect(src_rect), dst_surface, wine_dbgstr_rect(dst_rect), flags, fx);

    if (fx)
        FIXME("Ignoring fx %p.\n", fx);

    wined3d_mutex_lock();
    if (dst_impl)
    {
        dst_wined3d_texture = dst_impl->wined3d_texture;
        dst_sub_resource_idx = dst_impl->sub_resource_idx;
    }
    hr = wined3d_texture_update_overlay(src_impl->wined3d_texture, src_impl->sub_resource_idx,
            src_rect, dst_wined3d_texture, dst_sub_resource_idx, dst_rect, flags);
    wined3d_mutex_unlock();

    switch (hr)
    {
        case WINED3DERR_INVALIDCALL:        return DDERR_INVALIDPARAMS;
        case WINEDDERR_NOTAOVERLAYSURFACE:  return DDERR_NOTAOVERLAYSURFACE;
        case WINEDDERR_OVERLAYNOTVISIBLE:   return DDERR_OVERLAYNOTVISIBLE;
        default:
            return hr;
    }
}

static HRESULT WINAPI ddraw_surface4_UpdateOverlay(IDirectDrawSurface4 *iface, RECT *src_rect,
        IDirectDrawSurface4 *dst_surface, RECT *dst_rect, DWORD flags, DDOVERLAYFX *fx)
{
    struct ddraw_surface *src_impl = impl_from_IDirectDrawSurface4(iface);
    struct ddraw_surface *dst_impl = unsafe_impl_from_IDirectDrawSurface4(dst_surface);

    TRACE("iface %p, src_rect %s, dst_surface %p, dst_rect %s, flags %#x, fx %p.\n",
            iface, wine_dbgstr_rect(src_rect), dst_surface, wine_dbgstr_rect(dst_rect), flags, fx);

    return ddraw_surface7_UpdateOverlay(&src_impl->IDirectDrawSurface7_iface, src_rect,
            dst_impl ? &dst_impl->IDirectDrawSurface7_iface : NULL, dst_rect, flags, fx);
}

static HRESULT WINAPI ddraw_surface3_UpdateOverlay(IDirectDrawSurface3 *iface, RECT *src_rect,
        IDirectDrawSurface3 *dst_surface, RECT *dst_rect, DWORD flags, DDOVERLAYFX *fx)
{
    struct ddraw_surface *src_impl = impl_from_IDirectDrawSurface3(iface);
    struct ddraw_surface *dst_impl = unsafe_impl_from_IDirectDrawSurface3(dst_surface);

    TRACE("iface %p, src_rect %s, dst_surface %p, dst_rect %s, flags %#x, fx %p.\n",
            iface, wine_dbgstr_rect(src_rect), dst_surface, wine_dbgstr_rect(dst_rect), flags, fx);

    return ddraw_surface7_UpdateOverlay(&src_impl->IDirectDrawSurface7_iface, src_rect,
            dst_impl ? &dst_impl->IDirectDrawSurface7_iface : NULL, dst_rect, flags, fx);
}

static HRESULT WINAPI ddraw_surface2_UpdateOverlay(IDirectDrawSurface2 *iface, RECT *src_rect,
        IDirectDrawSurface2 *dst_surface, RECT *dst_rect, DWORD flags, DDOVERLAYFX *fx)
{
    struct ddraw_surface *src_impl = impl_from_IDirectDrawSurface2(iface);
    struct ddraw_surface *dst_impl = unsafe_impl_from_IDirectDrawSurface2(dst_surface);

    TRACE("iface %p, src_rect %s, dst_surface %p, dst_rect %s, flags %#x, fx %p.\n",
            iface, wine_dbgstr_rect(src_rect), dst_surface, wine_dbgstr_rect(dst_rect), flags, fx);

    return ddraw_surface7_UpdateOverlay(&src_impl->IDirectDrawSurface7_iface, src_rect,
            dst_impl ? &dst_impl->IDirectDrawSurface7_iface : NULL, dst_rect, flags, fx);
}

static HRESULT WINAPI ddraw_surface1_UpdateOverlay(IDirectDrawSurface *iface, RECT *src_rect,
        IDirectDrawSurface *dst_surface, RECT *dst_rect, DWORD flags, DDOVERLAYFX *fx)
{
    struct ddraw_surface *src_impl = impl_from_IDirectDrawSurface(iface);
    struct ddraw_surface *dst_impl = unsafe_impl_from_IDirectDrawSurface(dst_surface);

    TRACE("iface %p, src_rect %s, dst_surface %p, dst_rect %s, flags %#x, fx %p.\n",
            iface, wine_dbgstr_rect(src_rect), dst_surface, wine_dbgstr_rect(dst_rect), flags, fx);

    return ddraw_surface7_UpdateOverlay(&src_impl->IDirectDrawSurface7_iface, src_rect,
            dst_impl ? &dst_impl->IDirectDrawSurface7_iface : NULL, dst_rect, flags, fx);
}

/*****************************************************************************
 * IDirectDrawSurface7::UpdateOverlayDisplay
 *
 * The DX7 sdk says that it's not implemented
 *
 * Params:
 *  Flags: ?
 *
 * Returns: DDERR_UNSUPPORTED, because we don't support overlays
 *
 *****************************************************************************/
static HRESULT WINAPI ddraw_surface7_UpdateOverlayDisplay(IDirectDrawSurface7 *iface, DWORD Flags)
{
    TRACE("iface %p, flags %#x.\n", iface, Flags);

    return DDERR_UNSUPPORTED;
}

static HRESULT WINAPI ddraw_surface4_UpdateOverlayDisplay(IDirectDrawSurface4 *iface, DWORD flags)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface4(iface);

    TRACE("iface %p, flags %#x.\n", iface, flags);

    return ddraw_surface7_UpdateOverlayDisplay(&surface->IDirectDrawSurface7_iface, flags);
}

static HRESULT WINAPI ddraw_surface3_UpdateOverlayDisplay(IDirectDrawSurface3 *iface, DWORD flags)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface3(iface);

    TRACE("iface %p, flags %#x.\n", iface, flags);

    return ddraw_surface7_UpdateOverlayDisplay(&surface->IDirectDrawSurface7_iface, flags);
}

static HRESULT WINAPI ddraw_surface2_UpdateOverlayDisplay(IDirectDrawSurface2 *iface, DWORD flags)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface2(iface);

    TRACE("iface %p, flags %#x.\n", iface, flags);

    return ddraw_surface7_UpdateOverlayDisplay(&surface->IDirectDrawSurface7_iface, flags);
}

static HRESULT WINAPI ddraw_surface1_UpdateOverlayDisplay(IDirectDrawSurface *iface, DWORD flags)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface(iface);

    TRACE("iface %p, flags %#x.\n", iface, flags);

    return ddraw_surface7_UpdateOverlayDisplay(&surface->IDirectDrawSurface7_iface, flags);
}

/*****************************************************************************
 * IDirectDrawSurface7::UpdateOverlayZOrder
 *
 * Sets an overlay's Z order
 *
 * Params:
 *  Flags: DDOVERZ_* flags
 *  DDSRef: Defines the relative position in the overlay chain
 *
 * Returns:
 *  DDERR_NOTOVERLAYSURFACE, because we don't support overlays
 *
 *****************************************************************************/
static HRESULT WINAPI ddraw_surface7_UpdateOverlayZOrder(IDirectDrawSurface7 *iface,
        DWORD flags, IDirectDrawSurface7 *reference)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface7(iface);

    FIXME("iface %p, flags %#x, reference %p stub!\n", iface, flags, reference);

    wined3d_mutex_lock();
    if (!(surface->surface_desc.ddsCaps.dwCaps & DDSCAPS_OVERLAY))
    {
        WARN("Not an overlay surface.\n");
        wined3d_mutex_unlock();
        return DDERR_NOTAOVERLAYSURFACE;
    }
    wined3d_mutex_unlock();

    return DD_OK;
}

static HRESULT WINAPI ddraw_surface4_UpdateOverlayZOrder(IDirectDrawSurface4 *iface,
        DWORD flags, IDirectDrawSurface4 *reference)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface4(iface);
    struct ddraw_surface *reference_impl = unsafe_impl_from_IDirectDrawSurface4(reference);

    TRACE("iface %p, flags %#x, reference %p.\n", iface, flags, reference);

    return ddraw_surface7_UpdateOverlayZOrder(&surface->IDirectDrawSurface7_iface, flags,
            reference_impl ? &reference_impl->IDirectDrawSurface7_iface : NULL);
}

static HRESULT WINAPI ddraw_surface3_UpdateOverlayZOrder(IDirectDrawSurface3 *iface,
        DWORD flags, IDirectDrawSurface3 *reference)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface3(iface);
    struct ddraw_surface *reference_impl = unsafe_impl_from_IDirectDrawSurface3(reference);

    TRACE("iface %p, flags %#x, reference %p.\n", iface, flags, reference);

    return ddraw_surface7_UpdateOverlayZOrder(&surface->IDirectDrawSurface7_iface, flags,
            reference_impl ? &reference_impl->IDirectDrawSurface7_iface : NULL);
}

static HRESULT WINAPI ddraw_surface2_UpdateOverlayZOrder(IDirectDrawSurface2 *iface,
        DWORD flags, IDirectDrawSurface2 *reference)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface2(iface);
    struct ddraw_surface *reference_impl = unsafe_impl_from_IDirectDrawSurface2(reference);

    TRACE("iface %p, flags %#x, reference %p.\n", iface, flags, reference);

    return ddraw_surface7_UpdateOverlayZOrder(&surface->IDirectDrawSurface7_iface, flags,
            reference_impl ? &reference_impl->IDirectDrawSurface7_iface : NULL);
}

static HRESULT WINAPI ddraw_surface1_UpdateOverlayZOrder(IDirectDrawSurface *iface,
        DWORD flags, IDirectDrawSurface *reference)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface(iface);
    struct ddraw_surface *reference_impl = unsafe_impl_from_IDirectDrawSurface(reference);

    TRACE("iface %p, flags %#x, reference %p.\n", iface, flags, reference);

    return ddraw_surface7_UpdateOverlayZOrder(&surface->IDirectDrawSurface7_iface, flags,
            reference_impl ? &reference_impl->IDirectDrawSurface7_iface : NULL);
}

/*****************************************************************************
 * IDirectDrawSurface7::GetDDInterface
 *
 * Returns the IDirectDraw7 interface pointer of the DirectDraw object this
 * surface belongs to
 *
 * Params:
 *  DD: Address to write the interface pointer to
 *
 * Returns:
 *  DD_OK on success
 *  DDERR_INVALIDPARAMS if DD is NULL
 *
 *****************************************************************************/
static HRESULT WINAPI ddraw_surface7_GetDDInterface(IDirectDrawSurface7 *iface, void **DD)
{
    struct ddraw_surface *This = impl_from_IDirectDrawSurface7(iface);

    TRACE("iface %p, ddraw %p.\n", iface, DD);

    if(!DD)
        return DDERR_INVALIDPARAMS;

    switch(This->version)
    {
        case 7:
            *DD = &This->ddraw->IDirectDraw7_iface;
            break;

        case 4:
            *DD = &This->ddraw->IDirectDraw4_iface;
            break;

        case 2:
            *DD = &This->ddraw->IDirectDraw2_iface;
            break;

        case 1:
            *DD = &This->ddraw->IDirectDraw_iface;
            break;

    }
    IUnknown_AddRef((IUnknown *)*DD);

    return DD_OK;
}

static HRESULT WINAPI ddraw_surface4_GetDDInterface(IDirectDrawSurface4 *iface, void **ddraw)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface4(iface);

    TRACE("iface %p, ddraw %p.\n", iface, ddraw);

    return ddraw_surface7_GetDDInterface(&surface->IDirectDrawSurface7_iface, ddraw);
}

static HRESULT WINAPI ddraw_surface3_GetDDInterface(IDirectDrawSurface3 *iface, void **ddraw)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface3(iface);

    TRACE("iface %p, ddraw %p.\n", iface, ddraw);

    return ddraw_surface7_GetDDInterface(&surface->IDirectDrawSurface7_iface, ddraw);
}

static HRESULT WINAPI ddraw_surface2_GetDDInterface(IDirectDrawSurface2 *iface, void **ddraw)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface2(iface);

    TRACE("iface %p, ddraw %p.\n", iface, ddraw);

    return ddraw_surface7_GetDDInterface(&surface->IDirectDrawSurface7_iface, ddraw);
}

static HRESULT WINAPI ddraw_surface7_ChangeUniquenessValue(IDirectDrawSurface7 *iface)
{
    TRACE("iface %p.\n", iface);

    return DD_OK;
}

static HRESULT WINAPI ddraw_surface4_ChangeUniquenessValue(IDirectDrawSurface4 *iface)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface4(iface);

    TRACE("iface %p.\n", iface);

    return ddraw_surface7_ChangeUniquenessValue(&surface->IDirectDrawSurface7_iface);
}

static HRESULT WINAPI ddraw_surface7_GetUniquenessValue(IDirectDrawSurface7 *iface, DWORD *pValue)
{
    TRACE("iface %p, value %p.\n", iface, pValue);

    *pValue = 0;

    return DD_OK;
}

static HRESULT WINAPI ddraw_surface4_GetUniquenessValue(IDirectDrawSurface4 *iface, DWORD *pValue)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface4(iface);

    TRACE("iface %p, value %p.\n", iface, pValue);

    return ddraw_surface7_GetUniquenessValue(&surface->IDirectDrawSurface7_iface, pValue);
}

/*****************************************************************************
 * IDirectDrawSurface7::SetLOD
 *
 * Sets the level of detail of a texture
 *
 * Params:
 *  MaxLOD: LOD to set
 *
 * Returns:
 *  DD_OK on success
 *  DDERR_INVALIDOBJECT if the surface is invalid for this method
 *
 *****************************************************************************/
static HRESULT WINAPI ddraw_surface7_SetLOD(IDirectDrawSurface7 *iface, DWORD MaxLOD)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface7(iface);
    HRESULT hr;

    TRACE("iface %p, lod %u.\n", iface, MaxLOD);

    wined3d_mutex_lock();
    if (!(surface->surface_desc.ddsCaps.dwCaps2 & DDSCAPS2_TEXTUREMANAGE))
    {
        wined3d_mutex_unlock();
        return DDERR_INVALIDOBJECT;
    }

    hr = wined3d_texture_set_lod(surface->wined3d_texture, MaxLOD);
    wined3d_mutex_unlock();

    return hr;
}

/*****************************************************************************
 * IDirectDrawSurface7::GetLOD
 *
 * Returns the level of detail of a Direct3D texture
 *
 * Params:
 *  MaxLOD: Address to write the LOD to
 *
 * Returns:
 *  DD_OK on success
 *  DDERR_INVALIDPARAMS if MaxLOD is NULL
 *  DDERR_INVALIDOBJECT if the surface is invalid for this method
 *
 *****************************************************************************/
static HRESULT WINAPI ddraw_surface7_GetLOD(IDirectDrawSurface7 *iface, DWORD *MaxLOD)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface7(iface);

    TRACE("iface %p, lod %p.\n", iface, MaxLOD);

    if(!MaxLOD)
        return DDERR_INVALIDPARAMS;

    wined3d_mutex_lock();
    if (!(surface->surface_desc.ddsCaps.dwCaps2 & DDSCAPS2_TEXTUREMANAGE))
    {
        wined3d_mutex_unlock();
        return DDERR_INVALIDOBJECT;
    }

    *MaxLOD = wined3d_texture_get_lod(surface->wined3d_texture);
    wined3d_mutex_unlock();

    return DD_OK;
}

/*****************************************************************************
 * IDirectDrawSurface7::BltFast
 *
 * Performs a fast Blit.
 *
 * Params:
 *  dstx: The x coordinate to blit to on the destination
 *  dsty: The y coordinate to blit to on the destination
 *  Source: The source surface
 *  rsrc: The source rectangle
 *  trans: Type of transfer. Some DDBLTFAST_* flags
 *
 * Returns:
 *  DD_OK on success, error code otherwise.
 *
 *****************************************************************************/
static HRESULT WINAPI DECLSPEC_HOTPATCH ddraw_surface7_BltFast(IDirectDrawSurface7 *iface,
        DWORD dst_x, DWORD dst_y, IDirectDrawSurface7 *src_surface, RECT *src_rect, DWORD trans)
{
    struct ddraw_surface *dst_impl = impl_from_IDirectDrawSurface7(iface);
    struct ddraw_surface *src_impl = unsafe_impl_from_IDirectDrawSurface7(src_surface);
    DWORD flags = WINED3D_BLT_SYNCHRONOUS;
    DWORD src_w, src_h, dst_w, dst_h;
    HRESULT hr = DD_OK;
    RECT dst_rect, s;

    TRACE("iface %p, dst_x %u, dst_y %u, src_surface %p, src_rect %s, flags %#x.\n",
            iface, dst_x, dst_y, src_surface, wine_dbgstr_rect(src_rect), trans);

    dst_w = dst_impl->surface_desc.dwWidth;
    dst_h = dst_impl->surface_desc.dwHeight;

    if (!src_rect)
    {
        SetRect(&s, 0, 0, src_impl->surface_desc.dwWidth, src_impl->surface_desc.dwHeight);
        src_rect = &s;
    }

    src_w = src_rect->right - src_rect->left;
    src_h = src_rect->bottom - src_rect->top;
    if (src_w > dst_w || dst_x > dst_w - src_w
            || src_h > dst_h || dst_y > dst_h - src_h)
    {
        WARN("Destination area out of bounds, returning DDERR_INVALIDRECT.\n");
        return DDERR_INVALIDRECT;
    }

    SetRect(&dst_rect, dst_x, dst_y, dst_x + src_w, dst_y + src_h);
    if (trans & DDBLTFAST_SRCCOLORKEY)
        flags |= WINED3D_BLT_SRC_CKEY;
    if (trans & DDBLTFAST_DESTCOLORKEY)
        flags |= WINED3D_BLT_DST_CKEY;
    if (trans & DDBLTFAST_WAIT)
        flags |= WINED3D_BLT_WAIT;
    if (trans & DDBLTFAST_DONOTWAIT)
        flags |= WINED3D_BLT_DO_NOT_WAIT;

    wined3d_mutex_lock();
    if (dst_impl->clipper)
    {
        wined3d_mutex_unlock();
        WARN("Destination surface has a clipper set, returning DDERR_BLTFASTCANTCLIP.\n");
        return DDERR_BLTFASTCANTCLIP;
    }

    if (src_impl->surface_desc.ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE)
        hr = ddraw_surface_update_frontbuffer(src_impl, src_rect, TRUE);
    if (SUCCEEDED(hr))
        hr = wined3d_texture_blt(dst_impl->wined3d_texture, dst_impl->sub_resource_idx, &dst_rect,
                src_impl->wined3d_texture, src_impl->sub_resource_idx, src_rect, flags, NULL, WINED3D_TEXF_POINT);
    if (SUCCEEDED(hr) && (dst_impl->surface_desc.ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE))
        hr = ddraw_surface_update_frontbuffer(dst_impl, &dst_rect, FALSE);
    wined3d_mutex_unlock();

    switch(hr)
    {
        case WINED3DERR_NOTAVAILABLE:           return DDERR_UNSUPPORTED;
        default:                                return hr;
    }
}

static HRESULT WINAPI DECLSPEC_HOTPATCH ddraw_surface4_BltFast(IDirectDrawSurface4 *iface, DWORD dst_x, DWORD dst_y,
        IDirectDrawSurface4 *src_surface, RECT *src_rect, DWORD flags)
{
    struct ddraw_surface *dst_impl = impl_from_IDirectDrawSurface4(iface);
    struct ddraw_surface *src_impl = unsafe_impl_from_IDirectDrawSurface4(src_surface);

    TRACE("iface %p, dst_x %u, dst_y %u, src_surface %p, src_rect %s, flags %#x.\n",
            iface, dst_x, dst_y, src_surface, wine_dbgstr_rect(src_rect), flags);

    return ddraw_surface7_BltFast(&dst_impl->IDirectDrawSurface7_iface, dst_x, dst_y,
            src_impl ? &src_impl->IDirectDrawSurface7_iface : NULL, src_rect, flags);
}

static HRESULT WINAPI DECLSPEC_HOTPATCH ddraw_surface3_BltFast(IDirectDrawSurface3 *iface, DWORD dst_x, DWORD dst_y,
        IDirectDrawSurface3 *src_surface, RECT *src_rect, DWORD flags)
{
    struct ddraw_surface *dst_impl = impl_from_IDirectDrawSurface3(iface);
    struct ddraw_surface *src_impl = unsafe_impl_from_IDirectDrawSurface3(src_surface);

    TRACE("iface %p, dst_x %u, dst_y %u, src_surface %p, src_rect %s, flags %#x.\n",
            iface, dst_x, dst_y, src_surface, wine_dbgstr_rect(src_rect), flags);

    return ddraw_surface7_BltFast(&dst_impl->IDirectDrawSurface7_iface, dst_x, dst_y,
            src_impl ? &src_impl->IDirectDrawSurface7_iface : NULL, src_rect, flags);
}

static HRESULT WINAPI DECLSPEC_HOTPATCH ddraw_surface2_BltFast(IDirectDrawSurface2 *iface, DWORD dst_x, DWORD dst_y,
        IDirectDrawSurface2 *src_surface, RECT *src_rect, DWORD flags)
{
    struct ddraw_surface *dst_impl = impl_from_IDirectDrawSurface2(iface);
    struct ddraw_surface *src_impl = unsafe_impl_from_IDirectDrawSurface2(src_surface);

    TRACE("iface %p, dst_x %u, dst_y %u, src_surface %p, src_rect %s, flags %#x.\n",
            iface, dst_x, dst_y, src_surface, wine_dbgstr_rect(src_rect), flags);

    return ddraw_surface7_BltFast(&dst_impl->IDirectDrawSurface7_iface, dst_x, dst_y,
            src_impl ? &src_impl->IDirectDrawSurface7_iface : NULL, src_rect, flags);
}

static HRESULT WINAPI DECLSPEC_HOTPATCH ddraw_surface1_BltFast(IDirectDrawSurface *iface, DWORD dst_x, DWORD dst_y,
        IDirectDrawSurface *src_surface, RECT *src_rect, DWORD flags)
{
    struct ddraw_surface *dst_impl = impl_from_IDirectDrawSurface(iface);
    struct ddraw_surface *src_impl = unsafe_impl_from_IDirectDrawSurface(src_surface);

    TRACE("iface %p, dst_x %u, dst_y %u, src_surface %p, src_rect %s, flags %#x.\n",
            iface, dst_x, dst_y, src_surface, wine_dbgstr_rect(src_rect), flags);

    return ddraw_surface7_BltFast(&dst_impl->IDirectDrawSurface7_iface, dst_x, dst_y,
            src_impl ? &src_impl->IDirectDrawSurface7_iface : NULL, src_rect, flags);
}

/*****************************************************************************
 * IDirectDrawSurface7::GetClipper
 *
 * Returns the IDirectDrawClipper interface of the clipper assigned to this
 * surface
 *
 * Params:
 *  Clipper: Address to store the interface pointer at
 *
 * Returns:
 *  DD_OK on success
 *  DDERR_INVALIDPARAMS if Clipper is NULL
 *  DDERR_NOCLIPPERATTACHED if there's no clipper attached
 *
 *****************************************************************************/
static HRESULT WINAPI ddraw_surface7_GetClipper(IDirectDrawSurface7 *iface, IDirectDrawClipper **Clipper)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface7(iface);

    TRACE("iface %p, clipper %p.\n", iface, Clipper);

    if (!Clipper)
        return DDERR_INVALIDPARAMS;

    wined3d_mutex_lock();
    if (!surface->clipper)
    {
        wined3d_mutex_unlock();
        return DDERR_NOCLIPPERATTACHED;
    }

    *Clipper = &surface->clipper->IDirectDrawClipper_iface;
    IDirectDrawClipper_AddRef(*Clipper);
    wined3d_mutex_unlock();

    return DD_OK;
}

static HRESULT WINAPI ddraw_surface4_GetClipper(IDirectDrawSurface4 *iface, IDirectDrawClipper **clipper)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface4(iface);

    TRACE("iface %p, clipper %p.\n", iface, clipper);

    return ddraw_surface7_GetClipper(&surface->IDirectDrawSurface7_iface, clipper);
}

static HRESULT WINAPI ddraw_surface3_GetClipper(IDirectDrawSurface3 *iface, IDirectDrawClipper **clipper)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface3(iface);

    TRACE("iface %p, clipper %p.\n", iface, clipper);

    return ddraw_surface7_GetClipper(&surface->IDirectDrawSurface7_iface, clipper);
}

static HRESULT WINAPI ddraw_surface2_GetClipper(IDirectDrawSurface2 *iface, IDirectDrawClipper **clipper)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface2(iface);

    TRACE("iface %p, clipper %p.\n", iface, clipper);

    return ddraw_surface7_GetClipper(&surface->IDirectDrawSurface7_iface, clipper);
}

static HRESULT WINAPI ddraw_surface1_GetClipper(IDirectDrawSurface *iface, IDirectDrawClipper **clipper)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface(iface);

    TRACE("iface %p, clipper %p.\n", iface, clipper);

    return ddraw_surface7_GetClipper(&surface->IDirectDrawSurface7_iface, clipper);
}

/*****************************************************************************
 * IDirectDrawSurface7::SetClipper
 *
 * Sets a clipper for the surface
 *
 * Params:
 *  Clipper: IDirectDrawClipper interface of the clipper to set
 *
 * Returns:
 *  DD_OK on success
 *
 *****************************************************************************/
static HRESULT WINAPI ddraw_surface7_SetClipper(IDirectDrawSurface7 *iface,
        IDirectDrawClipper *iclipper)
{
    struct ddraw_surface *This = impl_from_IDirectDrawSurface7(iface);
    struct ddraw_clipper *clipper = unsafe_impl_from_IDirectDrawClipper(iclipper);
    struct ddraw_clipper *old_clipper = This->clipper;
    HWND clipWindow;

    TRACE("iface %p, clipper %p.\n", iface, iclipper);

    wined3d_mutex_lock();
    if (clipper == This->clipper)
    {
        wined3d_mutex_unlock();
        return DD_OK;
    }

    This->clipper = clipper;

    if (clipper != NULL)
        IDirectDrawClipper_AddRef(iclipper);
    if (old_clipper)
        IDirectDrawClipper_Release(&old_clipper->IDirectDrawClipper_iface);

    if ((This->surface_desc.ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE) && This->ddraw->wined3d_swapchain)
    {
        clipWindow = NULL;
        if(clipper) {
            IDirectDrawClipper_GetHWnd(iclipper, &clipWindow);
        }

        if (clipWindow)
        {
            wined3d_swapchain_set_window(This->ddraw->wined3d_swapchain, clipWindow);
            ddraw_set_swapchain_window(This->ddraw, clipWindow);
        }
        else
        {
            wined3d_swapchain_set_window(This->ddraw->wined3d_swapchain, This->ddraw->d3d_window);
            ddraw_set_swapchain_window(This->ddraw, This->ddraw->dest_window);
        }
    }

    wined3d_mutex_unlock();

    return DD_OK;
}

static HRESULT WINAPI ddraw_surface4_SetClipper(IDirectDrawSurface4 *iface, IDirectDrawClipper *clipper)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface4(iface);

    TRACE("iface %p, clipper %p.\n", iface, clipper);

    return ddraw_surface7_SetClipper(&surface->IDirectDrawSurface7_iface, clipper);
}

static HRESULT WINAPI ddraw_surface3_SetClipper(IDirectDrawSurface3 *iface, IDirectDrawClipper *clipper)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface3(iface);

    TRACE("iface %p, clipper %p.\n", iface, clipper);

    return ddraw_surface7_SetClipper(&surface->IDirectDrawSurface7_iface, clipper);
}

static HRESULT WINAPI ddraw_surface2_SetClipper(IDirectDrawSurface2 *iface, IDirectDrawClipper *clipper)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface2(iface);

    TRACE("iface %p, clipper %p.\n", iface, clipper);

    return ddraw_surface7_SetClipper(&surface->IDirectDrawSurface7_iface, clipper);
}

static HRESULT WINAPI ddraw_surface1_SetClipper(IDirectDrawSurface *iface, IDirectDrawClipper *clipper)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface(iface);

    TRACE("iface %p, clipper %p.\n", iface, clipper);

    return ddraw_surface7_SetClipper(&surface->IDirectDrawSurface7_iface, clipper);
}

/*****************************************************************************
 * IDirectDrawSurface7::SetSurfaceDesc
 *
 * Sets the surface description. It can override the pixel format, the surface
 * memory, ...
 * It's not really tested.
 *
 * Params:
 * DDSD: Pointer to the new surface description to set
 * Flags: Some flags
 *
 * Returns:
 *  DD_OK on success
 *  DDERR_INVALIDPARAMS if DDSD is NULL
 *
 *****************************************************************************/
static HRESULT WINAPI ddraw_surface7_SetSurfaceDesc(IDirectDrawSurface7 *iface, DDSURFACEDESC2 *DDSD, DWORD Flags)
{
    struct ddraw_surface *This = impl_from_IDirectDrawSurface7(iface);
    HRESULT hr;
    const DWORD allowed_flags = DDSD_LPSURFACE | DDSD_PIXELFORMAT | DDSD_WIDTH
            | DDSD_HEIGHT | DDSD_PITCH | DDSD_CAPS;
    enum wined3d_format_id format_id;
    UINT pitch, width, height;

    TRACE("iface %p, surface_desc %p, flags %#x.\n", iface, DDSD, Flags);

    if (!DDSD)
    {
        WARN("DDSD is NULL, returning DDERR_INVALIDPARAMS\n");
        return DDERR_INVALIDPARAMS;
    }
    if (Flags)
    {
        WARN("Flags is %x, returning DDERR_INVALIDPARAMS\n", Flags);
        return DDERR_INVALIDPARAMS;
    }
    if (!(This->surface_desc.ddsCaps.dwCaps & DDSCAPS_SYSTEMMEMORY)
            || This->surface_desc.ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE
            || This->surface_desc.ddsCaps.dwCaps2 & (DDSCAPS2_TEXTUREMANAGE | DDSCAPS2_D3DTEXTUREMANAGE))
    {
        WARN("Surface is not in system memory, returning DDERR_INVALIDSURFACETYPE.\n");
        return DDERR_INVALIDSURFACETYPE;
    }

    /* Tests show that only LPSURFACE and PIXELFORMAT can be set, and LPSURFACE is required
     * for PIXELFORMAT to work */
    if (DDSD->dwFlags & ~allowed_flags)
    {
        WARN("Invalid flags (0x%08x) set, returning DDERR_INVALIDPARAMS\n", DDSD->dwFlags);
        return DDERR_INVALIDPARAMS;
    }
    if (!(DDSD->dwFlags & DDSD_LPSURFACE) || !DDSD->lpSurface)
    {
        WARN("DDSD_LPSURFACE is not set or lpSurface is NULL, returning DDERR_INVALIDPARAMS\n");
        return DDERR_INVALIDPARAMS;
    }
    if ((DDSD->dwFlags & DDSD_CAPS) && DDSD->ddsCaps.dwCaps)
    {
        WARN("DDSD_CAPS is set, returning DDERR_INVALIDCAPS.\n");
        return DDERR_INVALIDCAPS;
    }
    if (DDSD->dwFlags & DDSD_WIDTH)
    {
        if (!(DDSD->dwFlags & DDSD_PITCH))
        {
            WARN("DDSD_WIDTH is set, but DDSD_PITCH is not, returning DDERR_INVALIDPARAMS.\n");
            return DDERR_INVALIDPARAMS;
        }
        if (!DDSD->dwWidth || DDSD->u1.lPitch <= 0 || DDSD->u1.lPitch & 0x3)
        {
            WARN("Pitch is %d, width is %u, returning DDERR_INVALIDPARAMS.\n",
                    DDSD->u1.lPitch, DDSD->dwWidth);
            return DDERR_INVALIDPARAMS;
        }
        if (DDSD->dwWidth != This->surface_desc.dwWidth)
            TRACE("Surface width changed from %u to %u.\n", This->surface_desc.dwWidth, DDSD->dwWidth);
        if (DDSD->u1.lPitch != This->surface_desc.u1.lPitch)
            TRACE("Surface pitch changed from %u to %u.\n", This->surface_desc.u1.lPitch, DDSD->u1.lPitch);
        pitch = DDSD->u1.lPitch;
        width = DDSD->dwWidth;
    }
    else if (DDSD->dwFlags & DDSD_PITCH)
    {
        WARN("DDSD_PITCH is set, but DDSD_WIDTH is not, returning DDERR_INVALIDPARAMS.\n");
        return DDERR_INVALIDPARAMS;
    }
    else
    {
        pitch = This->surface_desc.u1.lPitch;
        width = This->surface_desc.dwWidth;
    }

    if (DDSD->dwFlags & DDSD_HEIGHT)
    {
        if (!DDSD->dwHeight)
        {
            WARN("Height is 0, returning DDERR_INVALIDPARAMS.\n");
            return DDERR_INVALIDPARAMS;
        }
        if (DDSD->dwHeight != This->surface_desc.dwHeight)
            TRACE("Surface height changed from %u to %u.\n", This->surface_desc.dwHeight, DDSD->dwHeight);
        height = DDSD->dwHeight;
    }
    else
    {
        height = This->surface_desc.dwHeight;
    }

    wined3d_mutex_lock();
    if (DDSD->dwFlags & DDSD_PIXELFORMAT)
    {
        enum wined3d_format_id current_format_id;
        format_id = wined3dformat_from_ddrawformat(&DDSD->u4.ddpfPixelFormat);

        if (format_id == WINED3DFMT_UNKNOWN)
        {
            ERR("Requested to set an unknown pixelformat\n");
            wined3d_mutex_unlock();
            return DDERR_INVALIDPARAMS;
        }
        current_format_id = wined3dformat_from_ddrawformat(&This->surface_desc.u4.ddpfPixelFormat);
        if (format_id != current_format_id)
            TRACE("Surface format changed from %#x to %#x.\n", current_format_id, format_id);
    }
    else
    {
        format_id = wined3dformat_from_ddrawformat(&This->surface_desc.u4.ddpfPixelFormat);
    }

    if (FAILED(hr = wined3d_texture_update_desc(This->wined3d_texture, width, height,
            format_id, WINED3D_MULTISAMPLE_NONE, 0, DDSD->lpSurface, pitch)))
    {
        WARN("Failed to update surface desc, hr %#x.\n", hr);
        wined3d_mutex_unlock();
        return hr_ddraw_from_wined3d(hr);
    }

    if (DDSD->dwFlags & DDSD_WIDTH)
        This->surface_desc.dwWidth = width;
    if (DDSD->dwFlags & DDSD_PITCH)
        This->surface_desc.u1.lPitch = DDSD->u1.lPitch;
    if (DDSD->dwFlags & DDSD_HEIGHT)
        This->surface_desc.dwHeight = height;
    if (DDSD->dwFlags & DDSD_PIXELFORMAT)
        This->surface_desc.u4.ddpfPixelFormat = DDSD->u4.ddpfPixelFormat;

    wined3d_mutex_unlock();

    return DD_OK;
}

static HRESULT WINAPI ddraw_surface4_SetSurfaceDesc(IDirectDrawSurface4 *iface,
        DDSURFACEDESC2 *surface_desc, DWORD flags)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface4(iface);

    TRACE("iface %p, surface_desc %p, flags %#x.\n", iface, surface_desc, flags);

    return ddraw_surface7_SetSurfaceDesc(&surface->IDirectDrawSurface7_iface,
            surface_desc, flags);
}

static HRESULT WINAPI ddraw_surface3_SetSurfaceDesc(IDirectDrawSurface3 *iface,
        DDSURFACEDESC *surface_desc, DWORD flags)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface3(iface);
    DDSURFACEDESC2 surface_desc2;

    TRACE("iface %p, surface_desc %p, flags %#x.\n", iface, surface_desc, flags);

    if (surface_desc) DDSD_to_DDSD2(surface_desc, &surface_desc2);
    return ddraw_surface7_SetSurfaceDesc(&surface->IDirectDrawSurface7_iface,
            surface_desc ? &surface_desc2 : NULL, flags);
}

static HRESULT WINAPI ddraw_surface7_GetPalette(IDirectDrawSurface7 *iface, IDirectDrawPalette **palette)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface7(iface);
    struct ddraw_palette *palette_impl;
    HRESULT hr = DD_OK;

    TRACE("iface %p, palette %p.\n", iface, palette);

    if (!palette)
        return DDERR_INVALIDPARAMS;
    if (IDirectDrawSurface7_IsLost(iface) == DDERR_SURFACELOST)
    {
        WARN("Surface lost, returning DDERR_SURFACELOST.\n");
        return DDERR_SURFACELOST;
    }

    wined3d_mutex_lock();
    if ((palette_impl = surface->palette))
    {
        *palette = &palette_impl->IDirectDrawPalette_iface;
        IDirectDrawPalette_AddRef(*palette);
    }
    else
    {
        *palette = NULL;
        hr = DDERR_NOPALETTEATTACHED;
    }
    wined3d_mutex_unlock();

    return hr;
}

static HRESULT WINAPI ddraw_surface4_GetPalette(IDirectDrawSurface4 *iface, IDirectDrawPalette **palette)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface4(iface);

    TRACE("iface %p, palette %p.\n", iface, palette);

    return ddraw_surface7_GetPalette(&surface->IDirectDrawSurface7_iface, palette);
}

static HRESULT WINAPI ddraw_surface3_GetPalette(IDirectDrawSurface3 *iface, IDirectDrawPalette **palette)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface3(iface);

    TRACE("iface %p, palette %p.\n", iface, palette);

    return ddraw_surface7_GetPalette(&surface->IDirectDrawSurface7_iface, palette);
}

static HRESULT WINAPI ddraw_surface2_GetPalette(IDirectDrawSurface2 *iface, IDirectDrawPalette **palette)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface2(iface);

    TRACE("iface %p, palette %p.\n", iface, palette);

    return ddraw_surface7_GetPalette(&surface->IDirectDrawSurface7_iface, palette);
}

static HRESULT WINAPI ddraw_surface1_GetPalette(IDirectDrawSurface *iface, IDirectDrawPalette **palette)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface(iface);

    TRACE("iface %p, palette %p.\n", iface, palette);

    return ddraw_surface7_GetPalette(&surface->IDirectDrawSurface7_iface, palette);
}

static HRESULT ddraw_surface_set_color_key(struct ddraw_surface *surface, DWORD flags, DDCOLORKEY *color_key)
{
    DDCOLORKEY fixed_color_key;
    HRESULT hr = WINED3D_OK;

    if (flags & DDCKEY_COLORSPACE)
    {
        if (color_key && color_key->dwColorSpaceLowValue != color_key->dwColorSpaceHighValue)
        {
            WARN("Range color keys are not supported, returning DDERR_NOCOLORKEYHW.\n");
            return DDERR_NOCOLORKEYHW;
        }
        flags &= ~DDCKEY_COLORSPACE;
    }

    wined3d_mutex_lock();

    if (color_key)
    {
        fixed_color_key.dwColorSpaceLowValue = fixed_color_key.dwColorSpaceHighValue = color_key->dwColorSpaceLowValue;
        switch (flags & ~DDCKEY_COLORSPACE)
        {
            case DDCKEY_DESTBLT:
                surface->surface_desc.ddckCKDestBlt = fixed_color_key;
                surface->surface_desc.dwFlags |= DDSD_CKDESTBLT;
                break;

            case DDCKEY_DESTOVERLAY:
                surface->surface_desc.u3.ddckCKDestOverlay = fixed_color_key;
                surface->surface_desc.dwFlags |= DDSD_CKDESTOVERLAY;
                break;

            case DDCKEY_SRCOVERLAY:
                surface->surface_desc.ddckCKSrcOverlay = fixed_color_key;
                surface->surface_desc.dwFlags |= DDSD_CKSRCOVERLAY;
                break;

            case DDCKEY_SRCBLT:
                surface->surface_desc.ddckCKSrcBlt = fixed_color_key;
                surface->surface_desc.dwFlags |= DDSD_CKSRCBLT;
                break;

            default:
                wined3d_mutex_unlock();
                return DDERR_INVALIDPARAMS;
        }
    }
    else
    {
        switch (flags & ~DDCKEY_COLORSPACE)
        {
            case DDCKEY_DESTBLT:
                surface->surface_desc.dwFlags &= ~DDSD_CKDESTBLT;
                break;

            case DDCKEY_DESTOVERLAY:
                surface->surface_desc.dwFlags &= ~DDSD_CKDESTOVERLAY;
                break;

            case DDCKEY_SRCOVERLAY:
                surface->surface_desc.dwFlags &= ~DDSD_CKSRCOVERLAY;
                break;

            case DDCKEY_SRCBLT:
                surface->surface_desc.dwFlags &= ~DDSD_CKSRCBLT;
                break;

            default:
                wined3d_mutex_unlock();
                return DDERR_INVALIDPARAMS;
        }
    }

    if (surface->is_complex_root)
        hr = wined3d_texture_set_color_key(surface->wined3d_texture, flags,
                color_key ? (struct wined3d_color_key *)&fixed_color_key : NULL);

    wined3d_mutex_unlock();

    return hr_ddraw_from_wined3d(hr);
}

static HRESULT WINAPI ddraw_surface7_SetColorKey(IDirectDrawSurface7 *iface, DWORD flags, DDCOLORKEY *color_key)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface7(iface);

    TRACE("iface %p, flags %#x, color_key %p.\n", iface, flags, color_key);

    if (surface->surface_desc.ddsCaps.dwCaps2 & DDSCAPS2_MIPMAPSUBLEVEL)
        return DDERR_NOTONMIPMAPSUBLEVEL;

    return ddraw_surface_set_color_key(surface, flags, color_key);
}

static HRESULT WINAPI ddraw_surface4_SetColorKey(IDirectDrawSurface4 *iface, DWORD flags, DDCOLORKEY *color_key)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface4(iface);

    TRACE("iface %p, flags %#x, color_key %p.\n", iface, flags, color_key);

    return ddraw_surface_set_color_key(surface, flags, color_key);
}

static HRESULT WINAPI ddraw_surface3_SetColorKey(IDirectDrawSurface3 *iface, DWORD flags, DDCOLORKEY *color_key)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface3(iface);

    TRACE("iface %p, flags %#x, color_key %p.\n", iface, flags, color_key);

    return ddraw_surface_set_color_key(surface, flags, color_key);
}

static HRESULT WINAPI ddraw_surface2_SetColorKey(IDirectDrawSurface2 *iface, DWORD flags, DDCOLORKEY *color_key)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface2(iface);

    TRACE("iface %p, flags %#x, color_key %p.\n", iface, flags, color_key);

    return ddraw_surface_set_color_key(surface, flags, color_key);
}

static HRESULT WINAPI ddraw_surface1_SetColorKey(IDirectDrawSurface *iface, DWORD flags, DDCOLORKEY *color_key)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface(iface);

    TRACE("iface %p, flags %#x, color_key %p.\n", iface, flags, color_key);

    return ddraw_surface_set_color_key(surface, flags, color_key);
}

static HRESULT WINAPI ddraw_surface7_SetPalette(IDirectDrawSurface7 *iface, IDirectDrawPalette *palette)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface7(iface);

    TRACE("iface %p, palette %p.\n", iface, palette);

    if (surface->surface_desc.ddsCaps.dwCaps2 & DDSCAPS2_MIPMAPSUBLEVEL)
        return DDERR_NOTONMIPMAPSUBLEVEL;
    if (IDirectDrawSurface7_IsLost(iface) == DDERR_SURFACELOST)
    {
        WARN("Surface lost, returning DDERR_SURFACELOST.\n");
        return DDERR_SURFACELOST;
    }

    return ddraw_surface_set_palette(surface, palette);
}

static HRESULT WINAPI ddraw_surface4_SetPalette(IDirectDrawSurface4 *iface, IDirectDrawPalette *palette)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface4(iface);

    TRACE("iface %p, palette %p.\n", iface, palette);

    if (IDirectDrawSurface4_IsLost(iface) == DDERR_SURFACELOST)
    {
        WARN("Surface lost, returning DDERR_SURFACELOST.\n");
        return DDERR_SURFACELOST;
    }

    return ddraw_surface_set_palette(surface, palette);
}

static HRESULT WINAPI ddraw_surface3_SetPalette(IDirectDrawSurface3 *iface, IDirectDrawPalette *palette)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface3(iface);

    TRACE("iface %p, palette %p.\n", iface, palette);

    if (IDirectDrawSurface3_IsLost(iface) == DDERR_SURFACELOST)
    {
        WARN("Surface lost, returning DDERR_SURFACELOST.\n");
        return DDERR_SURFACELOST;
    }

    return ddraw_surface_set_palette(surface, palette);
}

static HRESULT WINAPI ddraw_surface2_SetPalette(IDirectDrawSurface2 *iface, IDirectDrawPalette *palette)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface2(iface);

    TRACE("iface %p, palette %p.\n", iface, palette);

    if (IDirectDrawSurface2_IsLost(iface) == DDERR_SURFACELOST)
    {
        WARN("Surface lost, returning DDERR_SURFACELOST.\n");
        return DDERR_SURFACELOST;
    }

    return ddraw_surface_set_palette(surface, palette);
}

static HRESULT WINAPI ddraw_surface1_SetPalette(IDirectDrawSurface *iface, IDirectDrawPalette *palette)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawSurface(iface);

    TRACE("iface %p, palette %p.\n", iface, palette);

    if (IDirectDrawSurface_IsLost(iface) == DDERR_SURFACELOST)
    {
        WARN("Surface lost, returning DDERR_SURFACELOST.\n");
        return DDERR_SURFACELOST;
    }

    return ddraw_surface_set_palette(surface, palette);
}

/**********************************************************
 * IDirectDrawGammaControl::GetGammaRamp
 *
 * Returns the current gamma ramp for a surface
 *
 * Params:
 *  flags: Ignored
 *  gamma_ramp: Address to write the ramp to
 *
 * Returns:
 *  DD_OK on success
 *  DDERR_INVALIDPARAMS if gamma_ramp is NULL
 *
 **********************************************************/
static HRESULT WINAPI ddraw_gamma_control_GetGammaRamp(IDirectDrawGammaControl *iface,
        DWORD flags, DDGAMMARAMP *gamma_ramp)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawGammaControl(iface);

    TRACE("iface %p, flags %#x, gamma_ramp %p.\n", iface, flags, gamma_ramp);

    if (!gamma_ramp)
    {
        WARN("Invalid gamma_ramp passed.\n");
        return DDERR_INVALIDPARAMS;
    }

    wined3d_mutex_lock();
    if (surface->surface_desc.ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE)
    {
        /* Note: DDGAMMARAMP is compatible with struct wined3d_gamma_ramp. */
        wined3d_device_get_gamma_ramp(surface->ddraw->wined3d_device, 0, (struct wined3d_gamma_ramp *)gamma_ramp);
    }
    else
    {
        ERR("Not implemented for non-primary surfaces.\n");
    }
    wined3d_mutex_unlock();

    return DD_OK;
}

/**********************************************************
 * IDirectDrawGammaControl::SetGammaRamp
 *
 * Sets the red, green and blue gamma ramps for
 *
 * Params:
 *  flags: Can be DDSGR_CALIBRATE to request calibration
 *  gamma_ramp: Structure containing the new gamma ramp
 *
 * Returns:
 *  DD_OK on success
 *  DDERR_INVALIDPARAMS if gamma_ramp is NULL
 *
 **********************************************************/
static HRESULT WINAPI ddraw_gamma_control_SetGammaRamp(IDirectDrawGammaControl *iface,
        DWORD flags, DDGAMMARAMP *gamma_ramp)
{
    struct ddraw_surface *surface = impl_from_IDirectDrawGammaControl(iface);

    TRACE("iface %p, flags %#x, gamma_ramp %p.\n", iface, flags, gamma_ramp);

    if (!gamma_ramp)
    {
        WARN("Invalid gamma_ramp passed.\n");
        return DDERR_INVALIDPARAMS;
    }

    wined3d_mutex_lock();
    if (surface->surface_desc.ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE)
    {
        /* Note: DDGAMMARAMP is compatible with struct wined3d_gamma_ramp. */
        wined3d_device_set_gamma_ramp(surface->ddraw->wined3d_device,
                0, flags, (struct wined3d_gamma_ramp *)gamma_ramp);
    }
    else
    {
        ERR("Not implemented for non-primary surfaces.\n");
    }
    wined3d_mutex_unlock();

    return DD_OK;
}

/*****************************************************************************
 * IDirect3DTexture2::PaletteChanged
 *
 * Informs the texture about a palette change
 *
 * Params:
 *  start: Start index of the change
 *  count: The number of changed entries
 *
 * Returns
 *  D3D_OK, because it's a stub
 *
 *****************************************************************************/
static HRESULT WINAPI d3d_texture2_PaletteChanged(IDirect3DTexture2 *iface, DWORD start, DWORD count)
{
    FIXME("iface %p, start %u, count %u stub!\n", iface, start, count);

    return D3D_OK;
}

static HRESULT WINAPI d3d_texture1_PaletteChanged(IDirect3DTexture *iface, DWORD start, DWORD count)
{
    struct ddraw_surface *surface = impl_from_IDirect3DTexture(iface);

    TRACE("iface %p, start %u, count %u.\n", iface, start, count);

    return d3d_texture2_PaletteChanged(&surface->IDirect3DTexture2_iface, start, count);
}

/*****************************************************************************
 * IDirect3DTexture::Unload
 *
 * DX5 SDK: "The IDirect3DTexture2::Unload method is not implemented
 *
 *
 * Returns:
 *  DDERR_UNSUPPORTED
 *
 *****************************************************************************/
static HRESULT WINAPI d3d_texture1_Unload(IDirect3DTexture *iface)
{
    WARN("iface %p. Not implemented.\n", iface);

    return DDERR_UNSUPPORTED;
}

/*****************************************************************************
 * IDirect3DTexture2::GetHandle
 *
 * Returns handle for the texture.
 *
 * Params:
 *  device: Device this handle is assigned to
 *  handle: Address to store the handle at.
 *
 * Returns:
 *  D3D_OK
 *
 *****************************************************************************/
static HRESULT WINAPI d3d_texture2_GetHandle(IDirect3DTexture2 *iface,
        IDirect3DDevice2 *device, D3DTEXTUREHANDLE *handle)
{
    struct ddraw_surface *surface = impl_from_IDirect3DTexture2(iface);
    struct d3d_device *device_impl = unsafe_impl_from_IDirect3DDevice2(device);

    TRACE("iface %p, device %p, handle %p.\n", iface, device, handle);

    wined3d_mutex_lock();

    if (!surface->Handle)
    {
        DWORD h = ddraw_allocate_handle(&device_impl->handle_table, surface, DDRAW_HANDLE_SURFACE);
        if (h == DDRAW_INVALID_HANDLE)
        {
            ERR("Failed to allocate a texture handle.\n");
            wined3d_mutex_unlock();
            return DDERR_OUTOFMEMORY;
        }

        surface->Handle = h + 1;
    }

    TRACE("Returning handle %08x.\n", surface->Handle);
    *handle = surface->Handle;

    wined3d_mutex_unlock();

    return D3D_OK;
}

static HRESULT WINAPI d3d_texture1_GetHandle(IDirect3DTexture *iface,
        IDirect3DDevice *device, D3DTEXTUREHANDLE *handle)
{
    struct ddraw_surface *surface = impl_from_IDirect3DTexture(iface);
    struct d3d_device *device_impl = unsafe_impl_from_IDirect3DDevice(device);

    TRACE("iface %p, device %p, handle %p.\n", iface, device, handle);

    return d3d_texture2_GetHandle(&surface->IDirect3DTexture2_iface,
            device_impl ? &device_impl->IDirect3DDevice2_iface : NULL, handle);
}

/*****************************************************************************
 * get_sub_mimaplevel
 *
 * Helper function that returns the next mipmap level
 *
 * tex_ptr: Surface of which to return the next level
 *
 *****************************************************************************/
static struct ddraw_surface *get_sub_mimaplevel(struct ddraw_surface *surface)
{
    /* Now go down the mipmap chain to the next surface */
    static DDSCAPS2 mipmap_caps = { DDSCAPS_MIPMAP | DDSCAPS_TEXTURE, 0, 0, {0} };
    IDirectDrawSurface7 *next_level;
    HRESULT hr;

    hr = ddraw_surface7_GetAttachedSurface(&surface->IDirectDrawSurface7_iface, &mipmap_caps, &next_level);
    if (FAILED(hr)) return NULL;

    ddraw_surface7_Release(next_level);

    return impl_from_IDirectDrawSurface7(next_level);
}

static BOOL compare_format(DDPIXELFORMAT *format1, DDPIXELFORMAT *format2)
{
    if ((format1->dwFlags & (DDPF_RGB|DDPF_YUV|DDPF_FOURCC)) !=
        (format2->dwFlags & (DDPF_RGB|DDPF_YUV|DDPF_FOURCC)))
        return FALSE;

    if (format1->dwFlags & (DDPF_RGB|DDPF_YUV))
    {
        if (!(format1->dwFlags & DDPF_ALPHA))
        {
            /* The RGB and YUV bits are stored in the same fields */
            if (format1->u1.dwRGBBitCount != format2->u1.dwRGBBitCount)
                return FALSE;

            if (format1->u2.dwRBitMask != format2->u2.dwRBitMask)
                return FALSE;

            if (format1->u3.dwGBitMask != format2->u3.dwGBitMask)
                return FALSE;

            if (format1->u4.dwBBitMask != format2->u4.dwBBitMask)
                return FALSE;
        }

        if (format1->dwFlags & (DDPF_ALPHAPIXELS | DDPF_ALPHA))
        {
            if (format1->u5.dwRGBAlphaBitMask != format2->u5.dwRGBAlphaBitMask)
                return FALSE;
        }
    }

    if (format1->dwFlags & DDPF_FOURCC)
    {
        if (format1->dwFourCC != format2->dwFourCC)
            return FALSE;
    }

    return TRUE;
}

/*****************************************************************************
 * IDirect3DTexture2::Load
 *
 * Loads a texture created with the DDSCAPS_ALLOCONLOAD
 *
 * This function isn't relayed to WineD3D because the whole interface is
 * implemented in DDraw only. For speed improvements an implementation which
 * takes OpenGL more into account could be placed into WineD3D.
 *
 * Params:
 *  src_texture: Address of the texture to load
 *
 * Returns:
 *  D3D_OK on success
 *  D3DERR_TEXTURE_LOAD_FAILED.
 *
 *****************************************************************************/
static HRESULT WINAPI d3d_texture2_Load(IDirect3DTexture2 *iface, IDirect3DTexture2 *src_texture)
{
    struct ddraw_surface *dst_surface = impl_from_IDirect3DTexture2(iface);
    struct ddraw_surface *src_surface = unsafe_impl_from_IDirect3DTexture2(src_texture);
    RECT src_rect, dst_rect;
    HRESULT hr;

    TRACE("iface %p, src_texture %p.\n", iface, src_texture);

    if (src_surface == dst_surface)
    {
        TRACE("copying surface %p to surface %p, why?\n", src_surface, dst_surface);
        return D3D_OK;
    }

    wined3d_mutex_lock();

    for (;;)
    {
        DDSURFACEDESC *src_desc = (DDSURFACEDESC *)&src_surface->surface_desc;

        TRACE("Copying surface %p to surface %p.\n", src_surface, dst_surface);

        if (compare_format(&src_surface->surface_desc.u4.ddpfPixelFormat,
                           &dst_surface->surface_desc.u4.ddpfPixelFormat))
        {
            struct ddraw_palette *dst_pal, *src_pal;

            /* Get the palettes */
            dst_pal = dst_surface->palette;
            src_pal = src_surface->palette;

            if (src_pal)
            {
                PALETTEENTRY palent[256];

                if (!dst_pal)
                {
                    wined3d_mutex_unlock();
                    return DDERR_NOPALETTEATTACHED;
                }
                IDirectDrawPalette_GetEntries(&src_pal->IDirectDrawPalette_iface, 0, 0, 256, palent);
                IDirectDrawPalette_SetEntries(&dst_pal->IDirectDrawPalette_iface, 0, 0, 256, palent);
            }

            if (src_desc->dwFlags & DDSD_CKSRCBLT)
            {
                IDirectDrawSurface7_SetColorKey(&dst_surface->IDirectDrawSurface7_iface,
                        DDCKEY_SRCBLT, &src_desc->ddckCKSrcBlt);
            }
        }
        else
        {
            if (src_desc->dwFlags & DDSD_CKSRCBLT)
                return E_FAIL;
        }

        /* Suppress the ALLOCONLOAD flag */
        dst_surface->surface_desc.ddsCaps.dwCaps &= ~DDSCAPS_ALLOCONLOAD;

        SetRect(&src_rect, 0, 0, src_surface->surface_desc.dwWidth, src_surface->surface_desc.dwHeight);
        SetRect(&dst_rect, 0, 0, dst_surface->surface_desc.dwWidth, dst_surface->surface_desc.dwHeight);

        hr = wined3d_texture_blt(dst_surface->wined3d_texture, dst_surface->sub_resource_idx, &dst_rect,
                                 src_surface->wined3d_texture, src_surface->sub_resource_idx, &src_rect,
                                 0, NULL, WINED3D_TEXF_LINEAR);
        if (FAILED(hr))
        {
            ERR("Failed to blit surface, hr %#x.\n", hr);
            wined3d_mutex_unlock();
            return hr;
        }

        if (src_surface->surface_desc.ddsCaps.dwCaps & DDSCAPS_MIPMAP)
            src_surface = get_sub_mimaplevel(src_surface);
        else
            src_surface = NULL;

        if (dst_surface->surface_desc.ddsCaps.dwCaps & DDSCAPS_MIPMAP)
            dst_surface = get_sub_mimaplevel(dst_surface);
        else
            dst_surface = NULL;

        if (src_surface && !dst_surface)
            return DDERR_NOTFOUND;

        if (!src_surface || !dst_surface)
            break;
    }

    wined3d_mutex_unlock();

    return hr;
}

static HRESULT WINAPI d3d_texture1_Load(IDirect3DTexture *iface, IDirect3DTexture *src_texture)
{
    struct ddraw_surface *dst_surface = impl_from_IDirect3DTexture(iface);
    struct ddraw_surface *src_surface = unsafe_impl_from_IDirect3DTexture(src_texture);

    TRACE("iface %p, src_texture %p.\n", iface, src_texture);

    return d3d_texture2_Load(&dst_surface->IDirect3DTexture2_iface,
            src_surface ? &src_surface->IDirect3DTexture2_iface : NULL);
}

/*****************************************************************************
 * The VTable
 *****************************************************************************/

static const struct IDirectDrawSurface7Vtbl ddraw_surface7_vtbl =
{
    /* IUnknown */
    ddraw_surface7_QueryInterface,
    ddraw_surface7_AddRef,
    ddraw_surface7_Release,
    /* IDirectDrawSurface */
    ddraw_surface7_AddAttachedSurface,
    ddraw_surface7_AddOverlayDirtyRect,
    ddraw_surface7_Blt,
    ddraw_surface7_BltBatch,
    ddraw_surface7_BltFast,
    ddraw_surface7_DeleteAttachedSurface,
    ddraw_surface7_EnumAttachedSurfaces,
    ddraw_surface7_EnumOverlayZOrders,
    ddraw_surface7_Flip,
    ddraw_surface7_GetAttachedSurface,
    ddraw_surface7_GetBltStatus,
    ddraw_surface7_GetCaps,
    ddraw_surface7_GetClipper,
    ddraw_surface7_GetColorKey,
    ddraw_surface7_GetDC,
    ddraw_surface7_GetFlipStatus,
    ddraw_surface7_GetOverlayPosition,
    ddraw_surface7_GetPalette,
    ddraw_surface7_GetPixelFormat,
    ddraw_surface7_GetSurfaceDesc,
    ddraw_surface7_Initialize,
    ddraw_surface7_IsLost,
    ddraw_surface7_Lock,
    ddraw_surface7_ReleaseDC,
    ddraw_surface7_Restore,
    ddraw_surface7_SetClipper,
    ddraw_surface7_SetColorKey,
    ddraw_surface7_SetOverlayPosition,
    ddraw_surface7_SetPalette,
    ddraw_surface7_Unlock,
    ddraw_surface7_UpdateOverlay,
    ddraw_surface7_UpdateOverlayDisplay,
    ddraw_surface7_UpdateOverlayZOrder,
    /* IDirectDrawSurface2 */
    ddraw_surface7_GetDDInterface,
    ddraw_surface7_PageLock,
    ddraw_surface7_PageUnlock,
    /* IDirectDrawSurface3 */
    ddraw_surface7_SetSurfaceDesc,
    /* IDirectDrawSurface4 */
    ddraw_surface7_SetPrivateData,
    ddraw_surface7_GetPrivateData,
    ddraw_surface7_FreePrivateData,
    ddraw_surface7_GetUniquenessValue,
    ddraw_surface7_ChangeUniquenessValue,
    /* IDirectDrawSurface7 */
    ddraw_surface7_SetPriority,
    ddraw_surface7_GetPriority,
    ddraw_surface7_SetLOD,
    ddraw_surface7_GetLOD,
};

static const struct IDirectDrawSurface4Vtbl ddraw_surface4_vtbl =
{
    /* IUnknown */
    ddraw_surface4_QueryInterface,
    ddraw_surface4_AddRef,
    ddraw_surface4_Release,
    /* IDirectDrawSurface */
    ddraw_surface4_AddAttachedSurface,
    ddraw_surface4_AddOverlayDirtyRect,
    ddraw_surface4_Blt,
    ddraw_surface4_BltBatch,
    ddraw_surface4_BltFast,
    ddraw_surface4_DeleteAttachedSurface,
    ddraw_surface4_EnumAttachedSurfaces,
    ddraw_surface4_EnumOverlayZOrders,
    ddraw_surface4_Flip,
    ddraw_surface4_GetAttachedSurface,
    ddraw_surface4_GetBltStatus,
    ddraw_surface4_GetCaps,
    ddraw_surface4_GetClipper,
    ddraw_surface4_GetColorKey,
    ddraw_surface4_GetDC,
    ddraw_surface4_GetFlipStatus,
    ddraw_surface4_GetOverlayPosition,
    ddraw_surface4_GetPalette,
    ddraw_surface4_GetPixelFormat,
    ddraw_surface4_GetSurfaceDesc,
    ddraw_surface4_Initialize,
    ddraw_surface4_IsLost,
    ddraw_surface4_Lock,
    ddraw_surface4_ReleaseDC,
    ddraw_surface4_Restore,
    ddraw_surface4_SetClipper,
    ddraw_surface4_SetColorKey,
    ddraw_surface4_SetOverlayPosition,
    ddraw_surface4_SetPalette,
    ddraw_surface4_Unlock,
    ddraw_surface4_UpdateOverlay,
    ddraw_surface4_UpdateOverlayDisplay,
    ddraw_surface4_UpdateOverlayZOrder,
    /* IDirectDrawSurface2 */
    ddraw_surface4_GetDDInterface,
    ddraw_surface4_PageLock,
    ddraw_surface4_PageUnlock,
    /* IDirectDrawSurface3 */
    ddraw_surface4_SetSurfaceDesc,
    /* IDirectDrawSurface4 */
    ddraw_surface4_SetPrivateData,
    ddraw_surface4_GetPrivateData,
    ddraw_surface4_FreePrivateData,
    ddraw_surface4_GetUniquenessValue,
    ddraw_surface4_ChangeUniquenessValue,
};

static const struct IDirectDrawSurface3Vtbl ddraw_surface3_vtbl =
{
    /* IUnknown */
    ddraw_surface3_QueryInterface,
    ddraw_surface3_AddRef,
    ddraw_surface3_Release,
    /* IDirectDrawSurface */
    ddraw_surface3_AddAttachedSurface,
    ddraw_surface3_AddOverlayDirtyRect,
    ddraw_surface3_Blt,
    ddraw_surface3_BltBatch,
    ddraw_surface3_BltFast,
    ddraw_surface3_DeleteAttachedSurface,
    ddraw_surface3_EnumAttachedSurfaces,
    ddraw_surface3_EnumOverlayZOrders,
    ddraw_surface3_Flip,
    ddraw_surface3_GetAttachedSurface,
    ddraw_surface3_GetBltStatus,
    ddraw_surface3_GetCaps,
    ddraw_surface3_GetClipper,
    ddraw_surface3_GetColorKey,
    ddraw_surface3_GetDC,
    ddraw_surface3_GetFlipStatus,
    ddraw_surface3_GetOverlayPosition,
    ddraw_surface3_GetPalette,
    ddraw_surface3_GetPixelFormat,
    ddraw_surface3_GetSurfaceDesc,
    ddraw_surface3_Initialize,
    ddraw_surface3_IsLost,
    ddraw_surface3_Lock,
    ddraw_surface3_ReleaseDC,
    ddraw_surface3_Restore,
    ddraw_surface3_SetClipper,
    ddraw_surface3_SetColorKey,
    ddraw_surface3_SetOverlayPosition,
    ddraw_surface3_SetPalette,
    ddraw_surface3_Unlock,
    ddraw_surface3_UpdateOverlay,
    ddraw_surface3_UpdateOverlayDisplay,
    ddraw_surface3_UpdateOverlayZOrder,
    /* IDirectDrawSurface2 */
    ddraw_surface3_GetDDInterface,
    ddraw_surface3_PageLock,
    ddraw_surface3_PageUnlock,
    /* IDirectDrawSurface3 */
    ddraw_surface3_SetSurfaceDesc,
};

static const struct IDirectDrawSurface2Vtbl ddraw_surface2_vtbl =
{
    /* IUnknown */
    ddraw_surface2_QueryInterface,
    ddraw_surface2_AddRef,
    ddraw_surface2_Release,
    /* IDirectDrawSurface */
    ddraw_surface2_AddAttachedSurface,
    ddraw_surface2_AddOverlayDirtyRect,
    ddraw_surface2_Blt,
    ddraw_surface2_BltBatch,
    ddraw_surface2_BltFast,
    ddraw_surface2_DeleteAttachedSurface,
    ddraw_surface2_EnumAttachedSurfaces,
    ddraw_surface2_EnumOverlayZOrders,
    ddraw_surface2_Flip,
    ddraw_surface2_GetAttachedSurface,
    ddraw_surface2_GetBltStatus,
    ddraw_surface2_GetCaps,
    ddraw_surface2_GetClipper,
    ddraw_surface2_GetColorKey,
    ddraw_surface2_GetDC,
    ddraw_surface2_GetFlipStatus,
    ddraw_surface2_GetOverlayPosition,
    ddraw_surface2_GetPalette,
    ddraw_surface2_GetPixelFormat,
    ddraw_surface2_GetSurfaceDesc,
    ddraw_surface2_Initialize,
    ddraw_surface2_IsLost,
    ddraw_surface2_Lock,
    ddraw_surface2_ReleaseDC,
    ddraw_surface2_Restore,
    ddraw_surface2_SetClipper,
    ddraw_surface2_SetColorKey,
    ddraw_surface2_SetOverlayPosition,
    ddraw_surface2_SetPalette,
    ddraw_surface2_Unlock,
    ddraw_surface2_UpdateOverlay,
    ddraw_surface2_UpdateOverlayDisplay,
    ddraw_surface2_UpdateOverlayZOrder,
    /* IDirectDrawSurface2 */
    ddraw_surface2_GetDDInterface,
    ddraw_surface2_PageLock,
    ddraw_surface2_PageUnlock,
};

static struct IDirectDrawSurfaceVtbl ddraw_surface1_vtbl =
{
    /* IUnknown */
    ddraw_surface1_QueryInterface,
    ddraw_surface1_AddRef,
    ddraw_surface1_Release,
    /* IDirectDrawSurface */
    ddraw_surface1_AddAttachedSurface,
    ddraw_surface1_AddOverlayDirtyRect,
    ddraw_surface1_Blt,
    ddraw_surface1_BltBatch,
    ddraw_surface1_BltFast,
    ddraw_surface1_DeleteAttachedSurface,
    ddraw_surface1_EnumAttachedSurfaces,
    ddraw_surface1_EnumOverlayZOrders,
    ddraw_surface1_Flip,
    ddraw_surface1_GetAttachedSurface,
    ddraw_surface1_GetBltStatus,
    ddraw_surface1_GetCaps,
    ddraw_surface1_GetClipper,
    ddraw_surface1_GetColorKey,
    ddraw_surface1_GetDC,
    ddraw_surface1_GetFlipStatus,
    ddraw_surface1_GetOverlayPosition,
    ddraw_surface1_GetPalette,
    ddraw_surface1_GetPixelFormat,
    ddraw_surface1_GetSurfaceDesc,
    ddraw_surface1_Initialize,
    ddraw_surface1_IsLost,
    ddraw_surface1_Lock,
    ddraw_surface1_ReleaseDC,
    ddraw_surface1_Restore,
    ddraw_surface1_SetClipper,
    ddraw_surface1_SetColorKey,
    ddraw_surface1_SetOverlayPosition,
    ddraw_surface1_SetPalette,
    ddraw_surface1_Unlock,
    ddraw_surface1_UpdateOverlay,
    ddraw_surface1_UpdateOverlayDisplay,
    ddraw_surface1_UpdateOverlayZOrder,
};

static const struct IDirectDrawGammaControlVtbl ddraw_gamma_control_vtbl =
{
    ddraw_gamma_control_QueryInterface,
    ddraw_gamma_control_AddRef,
    ddraw_gamma_control_Release,
    ddraw_gamma_control_GetGammaRamp,
    ddraw_gamma_control_SetGammaRamp,
};

static const struct IDirect3DTexture2Vtbl d3d_texture2_vtbl =
{
    d3d_texture2_QueryInterface,
    d3d_texture2_AddRef,
    d3d_texture2_Release,
    d3d_texture2_GetHandle,
    d3d_texture2_PaletteChanged,
    d3d_texture2_Load,
};

static const struct IDirect3DTextureVtbl d3d_texture1_vtbl =
{
    d3d_texture1_QueryInterface,
    d3d_texture1_AddRef,
    d3d_texture1_Release,
    d3d_texture1_Initialize,
    d3d_texture1_GetHandle,
    d3d_texture1_PaletteChanged,
    d3d_texture1_Load,
    d3d_texture1_Unload,
};

/* Some games (e.g. Tomb Raider 3) pass the wrong version of the
 * IDirectDrawSurface interface to ddraw methods. */
struct ddraw_surface *unsafe_impl_from_IDirectDrawSurface7(IDirectDrawSurface7 *iface)
{
    if (!iface) return NULL;
    if (iface->lpVtbl != &ddraw_surface7_vtbl)
    {
        HRESULT hr = IDirectDrawSurface7_QueryInterface(iface, &IID_IDirectDrawSurface7, (void **)&iface);
        if (FAILED(hr))
        {
            WARN("Object %p doesn't expose interface IDirectDrawSurface7.\n", iface);
            return NULL;
        }
        IDirectDrawSurface7_Release(iface);
    }
    return CONTAINING_RECORD(iface, struct ddraw_surface, IDirectDrawSurface7_iface);
}

struct ddraw_surface *unsafe_impl_from_IDirectDrawSurface4(IDirectDrawSurface4 *iface)
{
    if (!iface) return NULL;
    if (iface->lpVtbl != &ddraw_surface4_vtbl)
    {
        HRESULT hr = IDirectDrawSurface4_QueryInterface(iface, &IID_IDirectDrawSurface4, (void **)&iface);
        if (FAILED(hr))
        {
            WARN("Object %p doesn't expose interface IDirectDrawSurface4.\n", iface);
            return NULL;
        }
        IDirectDrawSurface4_Release(iface);
    }
    return CONTAINING_RECORD(iface, struct ddraw_surface, IDirectDrawSurface4_iface);
}

static struct ddraw_surface *unsafe_impl_from_IDirectDrawSurface3(IDirectDrawSurface3 *iface)
{
    if (!iface) return NULL;
    if (iface->lpVtbl != &ddraw_surface3_vtbl)
    {
        HRESULT hr = IDirectDrawSurface3_QueryInterface(iface, &IID_IDirectDrawSurface3, (void **)&iface);
        if (FAILED(hr))
        {
            WARN("Object %p doesn't expose interface IDirectDrawSurface3.\n", iface);
            return NULL;
        }
        IDirectDrawSurface3_Release(iface);
    }
    return CONTAINING_RECORD(iface, struct ddraw_surface, IDirectDrawSurface3_iface);
}

static struct ddraw_surface *unsafe_impl_from_IDirectDrawSurface2(IDirectDrawSurface2 *iface)
{
    if (!iface) return NULL;
    if (iface->lpVtbl != &ddraw_surface2_vtbl)
    {
        HRESULT hr = IDirectDrawSurface2_QueryInterface(iface, &IID_IDirectDrawSurface2, (void **)&iface);
        if (FAILED(hr))
        {
            WARN("Object %p doesn't expose interface IDirectDrawSurface2.\n", iface);
            return NULL;
        }
        IDirectDrawSurface2_Release(iface);
    }
    return CONTAINING_RECORD(iface, struct ddraw_surface, IDirectDrawSurface2_iface);
}

struct ddraw_surface *unsafe_impl_from_IDirectDrawSurface(IDirectDrawSurface *iface)
{
    if (!iface) return NULL;
    if (iface->lpVtbl != &ddraw_surface1_vtbl)
    {
        HRESULT hr = IDirectDrawSurface_QueryInterface(iface, &IID_IDirectDrawSurface, (void **)&iface);
        if (FAILED(hr))
        {
            WARN("Object %p doesn't expose interface IDirectDrawSurface.\n", iface);
            return NULL;
        }
        IDirectDrawSurface_Release(iface);
    }
    return CONTAINING_RECORD(iface, struct ddraw_surface, IDirectDrawSurface_iface);
}

struct ddraw_surface *unsafe_impl_from_IDirect3DTexture2(IDirect3DTexture2 *iface)
{
    if (!iface) return NULL;
    assert(iface->lpVtbl == &d3d_texture2_vtbl);
    return CONTAINING_RECORD(iface, struct ddraw_surface, IDirect3DTexture2_iface);
}

struct ddraw_surface *unsafe_impl_from_IDirect3DTexture(IDirect3DTexture *iface)
{
    if (!iface) return NULL;
    assert(iface->lpVtbl == &d3d_texture1_vtbl);
    return CONTAINING_RECORD(iface, struct ddraw_surface, IDirect3DTexture_iface);
}

static void STDMETHODCALLTYPE ddraw_surface_wined3d_object_destroyed(void *parent)
{
    struct ddraw_surface *surface = parent;

    TRACE("surface %p.\n", surface);

    /* This shouldn't happen, ddraw_surface_release_iface() should prevent the
     * surface from being destroyed in this case. */
    if (surface->first_attached != surface)
        ERR("Surface is still attached to surface %p.\n", surface->first_attached);

    while (surface->next_attached)
        if (FAILED(ddraw_surface_delete_attached_surface(surface,
                surface->next_attached, surface->next_attached->attached_iface)))
            ERR("DeleteAttachedSurface failed.\n");

    /* Having a texture handle set implies that the device still exists. */
    if (surface->Handle)
        ddraw_free_handle(&surface->ddraw->d3ddevice->handle_table, surface->Handle - 1, DDRAW_HANDLE_SURFACE);

    /* Reduce the ddraw surface count. */
    list_remove(&surface->surface_list_entry);

    if (surface->clipper)
        IDirectDrawClipper_Release(&surface->clipper->IDirectDrawClipper_iface);

    if (surface == surface->ddraw->primary)
        surface->ddraw->primary = NULL;

    wined3d_private_store_cleanup(&surface->private_store);

    heap_free(surface);
}

static const struct wined3d_parent_ops ddraw_surface_wined3d_parent_ops =
{
    ddraw_surface_wined3d_object_destroyed,
};

static void STDMETHODCALLTYPE ddraw_texture_wined3d_object_destroyed(void *parent)
{
    TRACE("parent %p.\n", parent);

    heap_free(parent);
}

static const struct wined3d_parent_ops ddraw_texture_wined3d_parent_ops =
{
    ddraw_texture_wined3d_object_destroyed,
};

static HRESULT CDECL ddraw_reset_enum_callback(struct wined3d_resource *resource)
{
    return DD_OK;
}

HRESULT ddraw_surface_create(struct ddraw *ddraw, const DDSURFACEDESC2 *surface_desc,
        struct ddraw_surface **surface, IUnknown *outer_unknown, unsigned int version)
{
    struct wined3d_sub_resource_desc wined3d_mip_desc;
    struct ddraw_surface *root, *mip, **attach;
    struct wined3d_resource_desc wined3d_desc;
    struct wined3d_texture *wined3d_texture;
    struct wined3d_display_mode mode;
    DDSURFACEDESC2 *desc, *mip_desc;
    struct ddraw_texture *texture;
    unsigned int layers = 1;
    unsigned int pitch = 0;
    UINT levels, i, j;
    HRESULT hr;

    TRACE("ddraw %p, surface_desc %p, surface %p, outer_unknown %p, version %u.\n",
            ddraw, surface_desc, surface, outer_unknown, version);
    if (TRACE_ON(ddraw))
    {
        TRACE("Requesting surface desc:\n");
        DDRAW_dump_surface_desc(surface_desc);
    }

    if (outer_unknown)
        return CLASS_E_NOAGGREGATION;

    if (!surface)
        return E_POINTER;

    if (!(texture = heap_alloc(sizeof(*texture))))
        return E_OUTOFMEMORY;

    texture->version = version;
    texture->surface_desc = *surface_desc;
    desc = &texture->surface_desc;

    /* Ensure DDSD_CAPS is always set. */
    desc->dwFlags |= DDSD_CAPS;

    if (desc->ddsCaps.dwCaps & DDSCAPS_FLIP)
    {
        if (!(desc->dwFlags & DDSD_BACKBUFFERCOUNT) || !desc->u5.dwBackBufferCount)
        {
            WARN("Tried to create a flippable surface without any back buffers.\n");
            heap_free(texture);
            return DDERR_INVALIDCAPS;
        }

        if (!(desc->ddsCaps.dwCaps & DDSCAPS_COMPLEX))
        {
            WARN("Tried to create a flippable surface without DDSCAPS_COMPLEX.\n");
            heap_free(texture);
            return DDERR_INVALIDCAPS;
        }

        if (desc->ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP)
        {
            WARN("Tried to create a flippable cubemap.\n");
            heap_free(texture);
            return DDERR_INVALIDPARAMS;
        }

        if (desc->ddsCaps.dwCaps & DDSCAPS_TEXTURE)
        {
            FIXME("Flippable textures not implemented.\n");
            heap_free(texture);
            return DDERR_INVALIDCAPS;
        }
    }
    else
    {
        if (desc->dwFlags & DDSD_BACKBUFFERCOUNT)
        {
            WARN("Tried to specify a back buffer count for a non-flippable surface.\n");
            hr = desc->ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP ? DDERR_INVALIDPARAMS : DDERR_INVALIDCAPS;
            heap_free(texture);
            return hr;
        }
    }

    if (desc->ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE)
    {
        if (desc->ddsCaps.dwCaps & DDSCAPS_TEXTURE)
        {
            WARN("Tried to create a primary surface with DDSCAPS_TEXTURE.\n");
            heap_free(texture);
            return DDERR_INVALIDCAPS;
        }

        if ((desc->ddsCaps.dwCaps & DDSCAPS_COMPLEX) && !(desc->ddsCaps.dwCaps & DDSCAPS_FLIP))
        {
            WARN("Tried to create a flippable primary surface without both DDSCAPS_FLIP and DDSCAPS_COMPLEX.\n");
            heap_free(texture);
            return DDERR_INVALIDCAPS;
        }

        if ((desc->ddsCaps.dwCaps & DDSCAPS_FLIP) && !(ddraw->cooperative_level & DDSCL_EXCLUSIVE))
        {
            WARN("Tried to create a flippable primary surface without DDSCL_EXCLUSIVE.\n");
            heap_free(texture);
            return DDERR_NOEXCLUSIVEMODE;
        }
    }

    /* This is a special case in ddrawex, but not allowed in ddraw. */
    if ((desc->ddsCaps.dwCaps & (DDSCAPS_VIDEOMEMORY | DDSCAPS_SYSTEMMEMORY))
            == (DDSCAPS_VIDEOMEMORY | DDSCAPS_SYSTEMMEMORY))
    {
        WARN("Tried to create a surface in both system and video memory.\n");
        heap_free(texture);
        return DDERR_INVALIDCAPS;
    }

    if ((desc->ddsCaps.dwCaps & (DDSCAPS_ALLOCONLOAD | DDSCAPS_MIPMAP))
            && !(desc->ddsCaps.dwCaps & DDSCAPS_TEXTURE))
    {
        WARN("Caps %#x require DDSCAPS_TEXTURE.\n", desc->ddsCaps.dwCaps);
        heap_free(texture);
        return DDERR_INVALIDCAPS;
    }

    if ((desc->ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP_ALLFACES)
            && !(desc->ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP))
    {
        WARN("Cube map faces requested without cube map flag.\n");
        heap_free(texture);
        return DDERR_INVALIDCAPS;
    }

    if ((desc->ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP)
            && !(desc->ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP_ALLFACES))
    {
        WARN("Cube map without faces requested.\n");
        heap_free(texture);
        return DDERR_INVALIDPARAMS;
    }

    if ((desc->ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP)
            && (desc->ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP_ALLFACES) != DDSCAPS2_CUBEMAP_ALLFACES)
        FIXME("Partial cube maps not implemented.\n");

    if (desc->ddsCaps.dwCaps2 & (DDSCAPS2_TEXTUREMANAGE | DDSCAPS2_D3DTEXTUREMANAGE))
    {
        if (!(desc->ddsCaps.dwCaps & DDSCAPS_TEXTURE))
        {
            WARN("DDSCAPS2_TEXTUREMANAGE used without DDSCAPS_TEXTURE, returning DDERR_INVALIDCAPS.\n");
            heap_free(texture);
            return DDERR_INVALIDCAPS;
        }
        if (desc->ddsCaps.dwCaps & (DDSCAPS_VIDEOMEMORY | DDSCAPS_SYSTEMMEMORY))
        {
            WARN("DDSCAPS2_TEXTUREMANAGE used width DDSCAPS_VIDEOMEMORY "
                    "or DDSCAPS_SYSTEMMEMORY, returning DDERR_INVALIDCAPS.\n");
            heap_free(texture);
            return DDERR_INVALIDCAPS;
        }
    }

    if (FAILED(hr = wined3d_get_adapter_display_mode(ddraw->wined3d, WINED3DADAPTER_DEFAULT, &mode, NULL)))
    {
        ERR("Failed to get display mode, hr %#x.\n", hr);
        heap_free(texture);
        return hr_ddraw_from_wined3d(hr);
    }

    /* No pixelformat given? Use the current screen format. */
    if (!(desc->dwFlags & DDSD_PIXELFORMAT))
    {
        desc->dwFlags |= DDSD_PIXELFORMAT;
        desc->u4.ddpfPixelFormat.dwSize = sizeof(desc->u4.ddpfPixelFormat);
        ddrawformat_from_wined3dformat(&desc->u4.ddpfPixelFormat, mode.format_id);
    }

    wined3d_desc.resource_type = WINED3D_RTYPE_TEXTURE_2D;
    wined3d_desc.format = wined3dformat_from_ddrawformat(&desc->u4.ddpfPixelFormat);
    if (wined3d_desc.format == WINED3DFMT_UNKNOWN)
    {
        WARN("Unsupported / unknown pixelformat.\n");
        heap_free(texture);
        return DDERR_INVALIDPIXELFORMAT;
    }

    /* No width or no height? Use the screen size. */
    if (!(desc->dwFlags & DDSD_WIDTH) || !(desc->dwFlags & DDSD_HEIGHT))
    {
        if (!(desc->ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE))
        {
            WARN("No width / height specified.\n");
            heap_free(texture);
            return DDERR_INVALIDPARAMS;
        }

        desc->dwFlags |= DDSD_WIDTH | DDSD_HEIGHT;
        desc->dwWidth = mode.width;
        desc->dwHeight = mode.height;
    }

    if (!desc->dwWidth || !desc->dwHeight)
    {
        heap_free(texture);
        return DDERR_INVALIDPARAMS;
    }

    if (desc->ddsCaps.dwCaps & DDSCAPS_FLIP)
        desc->ddsCaps.dwCaps |= DDSCAPS_FRONTBUFFER;

    if (desc->ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE)
    {
        /* The first surface is a front buffer, the back buffers are created
         * afterwards. */
        desc->ddsCaps.dwCaps |= DDSCAPS_VISIBLE;
        if (ddraw->cooperative_level & DDSCL_EXCLUSIVE)
        {
            struct wined3d_swapchain_desc swapchain_desc;

            wined3d_swapchain_get_desc(ddraw->wined3d_swapchain, &swapchain_desc);
            swapchain_desc.backbuffer_width = mode.width;
            swapchain_desc.backbuffer_height = mode.height;
            swapchain_desc.backbuffer_format = mode.format_id;

            if (FAILED(hr = wined3d_device_reset(ddraw->wined3d_device,
                    &swapchain_desc, NULL, ddraw_reset_enum_callback, TRUE)))
            {
                ERR("Failed to reset device.\n");
                heap_free(texture);
                return hr_ddraw_from_wined3d(hr);
            }

            wined3d_device_set_render_state(ddraw->wined3d_device, WINED3D_RS_ZENABLE,
                    !!swapchain_desc.enable_auto_depth_stencil);
        }
    }

    wined3d_desc.multisample_type = WINED3D_MULTISAMPLE_NONE;
    wined3d_desc.multisample_quality = 0;
    wined3d_desc.usage = 0;
    wined3d_desc.access = WINED3D_RESOURCE_ACCESS_GPU | WINED3D_RESOURCE_ACCESS_MAP_R | WINED3D_RESOURCE_ACCESS_MAP_W;
    wined3d_desc.width = desc->dwWidth;
    wined3d_desc.height = desc->dwHeight;
    wined3d_desc.depth = 1;
    wined3d_desc.size = 0;

    if ((desc->ddsCaps.dwCaps & DDSCAPS_3DDEVICE) && (ddraw->flags & DDRAW_NO3D))
    {
        WARN("The application requests a 3D capable surface, but the ddraw object was created without 3D support.\n");
        /* Do not fail surface creation, only fail 3D device creation. */
    }

    /* Mipmap count fixes */
    if (desc->ddsCaps.dwCaps & DDSCAPS_MIPMAP)
    {
        if (desc->ddsCaps.dwCaps & DDSCAPS_COMPLEX)
        {
            if (desc->dwFlags & DDSD_MIPMAPCOUNT)
            {
                /* Mipmap count is given, should not be 0. */
                if (!desc->u2.dwMipMapCount)
                {
                    heap_free(texture);
                    return DDERR_INVALIDPARAMS;
                }
            }
            else
            {
                /* Undocumented feature: Create sublevels until either the
                 * width or the height is 1. */
                if (version == 7)
                    desc->u2.dwMipMapCount = wined3d_log2i(max(desc->dwWidth, desc->dwHeight)) + 1;
                else
                    desc->u2.dwMipMapCount = wined3d_log2i(min(desc->dwWidth, desc->dwHeight)) + 1;
            }
        }
        else
        {
            desc->u2.dwMipMapCount = 1;
        }

        desc->dwFlags |= DDSD_MIPMAPCOUNT;
        levels = desc->u2.dwMipMapCount;
    }
    else
    {
        levels = 1;
    }

    if (!(desc->ddsCaps.dwCaps & (DDSCAPS_VIDEOMEMORY | DDSCAPS_SYSTEMMEMORY)))
    {
        if (!(desc->ddsCaps.dwCaps2 & (DDSCAPS2_TEXTUREMANAGE | DDSCAPS2_D3DTEXTUREMANAGE)))
        {
            DWORD usage = 0;

            if (desc->ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP)
                usage |= WINED3DUSAGE_LEGACY_CUBEMAP | WINED3DUSAGE_TEXTURE;
            else if (desc->ddsCaps.dwCaps & DDSCAPS_TEXTURE)
                usage |= WINED3DUSAGE_TEXTURE;

            if (desc->ddsCaps.dwCaps & DDSCAPS_ZBUFFER)
                usage = WINED3DUSAGE_DEPTHSTENCIL;
            else if (desc->ddsCaps.dwCaps & DDSCAPS_3DDEVICE)
                usage = WINED3DUSAGE_RENDERTARGET;

            if (SUCCEEDED(hr = wined3d_check_device_format(ddraw->wined3d, WINED3DADAPTER_DEFAULT,
                    WINED3D_DEVICE_TYPE_HAL, mode.format_id, usage, WINED3D_RTYPE_TEXTURE_2D, wined3d_desc.format)))
                desc->ddsCaps.dwCaps |= DDSCAPS_VIDEOMEMORY;
            else
                desc->ddsCaps.dwCaps |= DDSCAPS_SYSTEMMEMORY;
        }
        else if (!(desc->ddsCaps.dwCaps & DDSCAPS_TEXTURE))
        {
            /* Tests show surfaces without memory flags get these flags added
             * right after creation. */
            desc->ddsCaps.dwCaps |= DDSCAPS_LOCALVIDMEM | DDSCAPS_VIDEOMEMORY;
        }
    }

    if ((desc->ddsCaps.dwCaps & (DDSCAPS_OVERLAY | DDSCAPS_SYSTEMMEMORY))
            == (DDSCAPS_OVERLAY | DDSCAPS_SYSTEMMEMORY))
    {
        WARN("System memory overlays are not allowed.\n");
        heap_free(texture);
        return DDERR_NOOVERLAYHW;
    }

    if (desc->ddsCaps.dwCaps & DDSCAPS_SYSTEMMEMORY)
    {
        /*
         * The ddraw RGB device allows to use system memory surfaces as rendering target.
         * This does not cause problems because the RGB device does software rasterization
         * though it will fail with hardware accelerated ddraw. In order to be partially
         * compatible with games requesting explicitly the RGB device, we ignore the
         * specified location and try to create rendering targets in video memory if
         * possible.
         */
        if ((desc->ddsCaps.dwCaps & DDSCAPS_3DDEVICE) &&
            SUCCEEDED(hr = wined3d_check_device_format(ddraw->wined3d, WINED3DADAPTER_DEFAULT,
                        WINED3D_DEVICE_TYPE_HAL, mode.format_id, WINED3DUSAGE_RENDERTARGET,
                        WINED3D_RTYPE_TEXTURE_2D, wined3d_desc.format)))
        {
            FIXME("Application wants to create rendering target in system memory, using video memory instead\n");
            wined3d_desc.usage |= WINED3DUSAGE_RENDERTARGET;
        }
        else
            wined3d_desc.access = WINED3D_RESOURCE_ACCESS_CPU
                | WINED3D_RESOURCE_ACCESS_MAP_R | WINED3D_RESOURCE_ACCESS_MAP_W;
    }
    else
    {
        if (desc->ddsCaps.dwCaps & DDSCAPS_TEXTURE)
            wined3d_desc.usage |= WINED3DUSAGE_TEXTURE;
        if (desc->ddsCaps.dwCaps & DDSCAPS_ZBUFFER)
            wined3d_desc.usage |= WINED3DUSAGE_DEPTHSTENCIL;
        else if (desc->ddsCaps.dwCaps & DDSCAPS_3DDEVICE)
            wined3d_desc.usage |= WINED3DUSAGE_RENDERTARGET;

        if (desc->ddsCaps.dwCaps2 & (DDSCAPS2_TEXTUREMANAGE | DDSCAPS2_D3DTEXTUREMANAGE))
        {
            wined3d_desc.access = WINED3D_RESOURCE_ACCESS_GPU | WINED3D_RESOURCE_ACCESS_CPU
                    | WINED3D_RESOURCE_ACCESS_MAP_R | WINED3D_RESOURCE_ACCESS_MAP_W;
            /* Managed textures have the system memory flag set. */
            desc->ddsCaps.dwCaps |= DDSCAPS_SYSTEMMEMORY;
        }
        else if (desc->ddsCaps.dwCaps & DDSCAPS_VIDEOMEMORY)
        {
            /* Videomemory adds localvidmem. This is mutually exclusive with
             * systemmemory and texturemanage. */
            desc->ddsCaps.dwCaps |= DDSCAPS_LOCALVIDMEM;
            wined3d_desc.usage |= WINED3DUSAGE_DYNAMIC;
        }
    }

    if (desc->dwFlags & DDSD_LPSURFACE)
    {
        if (wined3d_desc.access & WINED3D_RESOURCE_ACCESS_GPU)
        {
            WARN("User memory surfaces should not be GPU accessible.\n");
            heap_free(texture);
            return DDERR_INVALIDCAPS;
        }

        if (version < 4)
        {
            WARN("User memory surfaces not supported before version 4.\n");
            heap_free(texture);
            return DDERR_INVALIDPARAMS;
        }

        if (!desc->lpSurface)
        {
            WARN("NULL surface memory pointer specified.\n");
            heap_free(texture);
            return DDERR_INVALIDPARAMS;
        }

        if (format_is_compressed(&desc->u4.ddpfPixelFormat))
        {
            if (version != 4 && (desc->dwFlags & DDSD_PITCH))
            {
                WARN("Pitch specified on a compressed user memory surface.\n");
                heap_free(texture);
                return DDERR_INVALIDPARAMS;
            }

            if (!(desc->dwFlags & (DDSD_LINEARSIZE | DDSD_PITCH)))
            {
                WARN("Compressed user memory surfaces should explicitly specify the linear size.\n");
                heap_free(texture);
                return DDERR_INVALIDPARAMS;
            }

            if ((desc->dwFlags & DDSD_LINEARSIZE)
                    && desc->u1.dwLinearSize < wined3d_calculate_format_pitch(ddraw->wined3d, WINED3DADAPTER_DEFAULT,
                            wined3d_desc.format, wined3d_desc.width) * ((desc->dwHeight + 3) / 4))
            {
                WARN("Invalid linear size %u specified.\n", desc->u1.dwLinearSize);
                heap_free(texture);
                return DDERR_INVALIDPARAMS;
            }
        }
        else
        {
            if (!(desc->dwFlags & DDSD_PITCH))
            {
                WARN("User memory surfaces should explicitly specify the pitch.\n");
                heap_free(texture);
                return DDERR_INVALIDPARAMS;
            }

            if (desc->u1.lPitch < wined3d_calculate_format_pitch(ddraw->wined3d, WINED3DADAPTER_DEFAULT,
                    wined3d_desc.format, wined3d_desc.width) || desc->u1.lPitch & 3)
            {
                WARN("Invalid pitch %u specified.\n", desc->u1.lPitch);
                heap_free(texture);
                return DDERR_INVALIDPARAMS;
            }

            pitch = desc->u1.lPitch;
        }
    }

    if (((desc->dwFlags & DDSD_CKDESTOVERLAY)
            && desc->u3.ddckCKDestOverlay.dwColorSpaceLowValue != desc->u3.ddckCKDestOverlay.dwColorSpaceHighValue)
            || ((desc->dwFlags & DDSD_CKDESTBLT)
            && desc->ddckCKDestBlt.dwColorSpaceLowValue != desc->ddckCKDestBlt.dwColorSpaceHighValue)
            || ((desc->dwFlags & DDSD_CKSRCOVERLAY)
            && desc->ddckCKSrcOverlay.dwColorSpaceLowValue != desc->ddckCKSrcOverlay.dwColorSpaceHighValue)
            || ((desc->dwFlags & DDSD_CKSRCBLT)
            && desc->ddckCKSrcBlt.dwColorSpaceLowValue != desc->ddckCKSrcBlt.dwColorSpaceHighValue))
    {
        WARN("Range color keys not supported, returning DDERR_NOCOLORKEYHW.\n");
        heap_free(texture);
        return DDERR_NOCOLORKEYHW;
    }

    if (desc->ddsCaps.dwCaps & (DDSCAPS_OVERLAY))
        wined3d_desc.usage |= WINED3DUSAGE_OVERLAY;

    if (desc->ddsCaps.dwCaps & DDSCAPS_OWNDC)
        wined3d_desc.usage |= WINED3DUSAGE_OWNDC;

    if (desc->ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP)
    {
        wined3d_desc.usage |= WINED3DUSAGE_LEGACY_CUBEMAP;
        layers = 6;
    }

    /* Some applications assume surfaces will always be mapped at the same
     * address. Some of those also assume that this address is valid even when
     * the surface isn't mapped, and that updates done this way will be
     * visible on the screen. The game Nox is such an application,
     * Commandos: Behind Enemy Lines is another. Setting
     * WINED3D_TEXTURE_CREATE_GET_DC_LENIENT will ensure this. */
    if (FAILED(hr = wined3d_texture_create(ddraw->wined3d_device, &wined3d_desc, layers, levels,
            WINED3D_TEXTURE_CREATE_GET_DC_LENIENT, NULL, texture,
            &ddraw_texture_wined3d_parent_ops, &wined3d_texture)))
    {
        WARN("Failed to create wined3d texture, hr %#x.\n", hr);
        heap_free(texture);
        return hr_ddraw_from_wined3d(hr);
    }

    root = wined3d_texture_get_sub_resource_parent(wined3d_texture, 0);
    wined3d_texture_decref(wined3d_texture);
    root->is_complex_root = TRUE;
    texture->root = root;
    wined3d_device_incref(texture->wined3d_device = ddraw->wined3d_device);

    if (desc->dwFlags & DDSD_CKDESTOVERLAY)
        wined3d_texture_set_color_key(wined3d_texture, DDCKEY_DESTOVERLAY,
                (struct wined3d_color_key *)&desc->u3.ddckCKDestOverlay);
    if (desc->dwFlags & DDSD_CKDESTBLT)
        wined3d_texture_set_color_key(wined3d_texture, DDCKEY_DESTBLT,
                (struct wined3d_color_key *)&desc->ddckCKDestBlt);
    if (desc->dwFlags & DDSD_CKSRCOVERLAY)
        wined3d_texture_set_color_key(wined3d_texture, DDCKEY_SRCOVERLAY,
                (struct wined3d_color_key *)&desc->ddckCKSrcOverlay);
    if (desc->dwFlags & DDSD_CKSRCBLT)
        wined3d_texture_set_color_key(wined3d_texture, DDCKEY_SRCBLT,
                (struct wined3d_color_key *)&desc->ddckCKSrcBlt);

    for (i = 0; i < layers; ++i)
    {
        attach = &root->complex_array[layers - 1 - i];

        for (j = 0; j < levels; ++j)
        {
            mip = wined3d_texture_get_sub_resource_parent(wined3d_texture, i * levels + j);
            mip_desc = &mip->surface_desc;

            if (j)
            {
                wined3d_texture_get_sub_resource_desc(wined3d_texture, i * levels + j, &wined3d_mip_desc);
                mip_desc->dwWidth = wined3d_mip_desc.width;
                mip_desc->dwHeight = wined3d_mip_desc.height;

                mip_desc->ddsCaps.dwCaps2 |= DDSCAPS2_MIPMAPSUBLEVEL;
            }
            else
            {
                mip_desc->ddsCaps.dwCaps2 &= ~DDSCAPS2_MIPMAPSUBLEVEL;
            }

            if (mip_desc->ddsCaps.dwCaps2 & DDSCAPS2_CUBEMAP)
            {
                mip_desc->ddsCaps.dwCaps2 &= ~DDSCAPS2_CUBEMAP_ALLFACES;

                switch (i)
                {
                    case WINED3D_CUBEMAP_FACE_POSITIVE_X:
                        mip_desc->ddsCaps.dwCaps2 |= DDSCAPS2_CUBEMAP_POSITIVEX;
                        break;
                    case WINED3D_CUBEMAP_FACE_NEGATIVE_X:
                        mip_desc->ddsCaps.dwCaps2 |= DDSCAPS2_CUBEMAP_NEGATIVEX;
                        break;
                    case WINED3D_CUBEMAP_FACE_POSITIVE_Y:
                        mip_desc->ddsCaps.dwCaps2 |= DDSCAPS2_CUBEMAP_POSITIVEY;
                        break;
                    case WINED3D_CUBEMAP_FACE_NEGATIVE_Y:
                        mip_desc->ddsCaps.dwCaps2 |= DDSCAPS2_CUBEMAP_NEGATIVEY;
                        break;
                    case WINED3D_CUBEMAP_FACE_POSITIVE_Z:
                        mip_desc->ddsCaps.dwCaps2 |= DDSCAPS2_CUBEMAP_POSITIVEZ;
                        break;
                    case WINED3D_CUBEMAP_FACE_NEGATIVE_Z:
                        mip_desc->ddsCaps.dwCaps2 |= DDSCAPS2_CUBEMAP_NEGATIVEZ;
                        break;
                }

            }

            if (mip == root)
                continue;

            *attach = mip;
            attach = &mip->complex_array[0];
        }
    }

    if ((desc->dwFlags & DDSD_LPSURFACE) && FAILED(hr = wined3d_texture_update_desc(wined3d_texture,
            wined3d_desc.width, wined3d_desc.height, wined3d_desc.format,
            WINED3D_MULTISAMPLE_NONE, 0, desc->lpSurface, pitch)))
    {
        ERR("Failed to set surface memory, hr %#x.\n", hr);
        goto fail;
    }

    if (desc->dwFlags & DDSD_BACKBUFFERCOUNT)
    {
        unsigned int count = desc->u5.dwBackBufferCount;
        struct ddraw_surface *last = root;

        attach = &last->complex_array[0];
        for (i = 0; i < count; ++i)
        {
            if (!(texture = heap_alloc(sizeof(*texture))))
            {
                hr = E_OUTOFMEMORY;
                goto fail;
            }

            texture->version = version;
            texture->surface_desc = root->surface_desc;
            desc = &texture->surface_desc;

            /* Only one surface in the flipping chain is a back buffer, one is
             * a front buffer, the others are just flippable surfaces. */
            desc->ddsCaps.dwCaps &= ~(DDSCAPS_VISIBLE | DDSCAPS_PRIMARYSURFACE | DDSCAPS_FRONTBUFFER
                    | DDSCAPS_BACKBUFFER);
            if (!i)
                desc->ddsCaps.dwCaps |= DDSCAPS_BACKBUFFER;
            desc->u5.dwBackBufferCount = 0;

            if (FAILED(hr = wined3d_texture_create(ddraw->wined3d_device, &wined3d_desc, 1, 1,
                    WINED3D_TEXTURE_CREATE_GET_DC_LENIENT, NULL, texture,
                    &ddraw_texture_wined3d_parent_ops, &wined3d_texture)))
            {
                heap_free(texture);
                hr = hr_ddraw_from_wined3d(hr);
                goto fail;
            }

            last = wined3d_texture_get_sub_resource_parent(wined3d_texture, 0);
            wined3d_texture_decref(wined3d_texture);
            texture->root = last;
            wined3d_device_incref(texture->wined3d_device = ddraw->wined3d_device);

            if (desc->dwFlags & DDSD_CKDESTOVERLAY)
                wined3d_texture_set_color_key(wined3d_texture, DDCKEY_DESTOVERLAY,
                        (struct wined3d_color_key *)&desc->u3.ddckCKDestOverlay);
            if (desc->dwFlags & DDSD_CKDESTBLT)
                wined3d_texture_set_color_key(wined3d_texture, DDCKEY_DESTBLT,
                        (struct wined3d_color_key *)&desc->ddckCKDestBlt);
            if (desc->dwFlags & DDSD_CKSRCOVERLAY)
                wined3d_texture_set_color_key(wined3d_texture, DDCKEY_SRCOVERLAY,
                        (struct wined3d_color_key *)&desc->ddckCKSrcOverlay);
            if (desc->dwFlags & DDSD_CKSRCBLT)
                wined3d_texture_set_color_key(wined3d_texture, DDCKEY_SRCBLT,
                        (struct wined3d_color_key *)&desc->ddckCKSrcBlt);

            *attach = last;
            attach = &last->complex_array[0];
        }
        *attach = root;
    }

    if (surface_desc->ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE)
        ddraw->primary = root;
    *surface = root;

    return DD_OK;

fail:
    if (version == 7)
        IDirectDrawSurface7_Release(&root->IDirectDrawSurface7_iface);
    else if (version == 4)
        IDirectDrawSurface4_Release(&root->IDirectDrawSurface4_iface);
    else
        IDirectDrawSurface_Release(&root->IDirectDrawSurface_iface);

    return hr;
}

void ddraw_surface_init(struct ddraw_surface *surface, struct ddraw *ddraw,
        struct wined3d_texture *wined3d_texture, unsigned int sub_resource_idx,
        const struct wined3d_parent_ops **parent_ops)
{
    struct ddraw_texture *texture = wined3d_texture_get_parent(wined3d_texture);
    unsigned int texture_level, row_pitch, slice_pitch;
    DDSURFACEDESC2 *desc = &surface->surface_desc;
    unsigned int version = texture->version;

    surface->IDirectDrawSurface7_iface.lpVtbl = &ddraw_surface7_vtbl;
    surface->IDirectDrawSurface4_iface.lpVtbl = &ddraw_surface4_vtbl;
    surface->IDirectDrawSurface3_iface.lpVtbl = &ddraw_surface3_vtbl;
    surface->IDirectDrawSurface2_iface.