summaryrefslogtreecommitdiff
path: root/rtl/go32v2/vesa.inc
blob: d1aaed0427c636b8deb3d811df9929f3322ce7a6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
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
{
    This file is part of the Free Pascal run time library.
    Copyright (c) 1999-2000 by Carl Eric Codere

    This include implements VESA basic access.

    See the file COPYING.FPC, included in this distribution,
    for details about the copyright.

    This program 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.

 **********************************************************************}
type

  palrec = packed record              { record used for set/get DAC palette }
       blue, green, red, align: byte;
  end;

const
  { VESA attributes     }
  attrSwitchDAC        = $01;    { DAC is switchable           (1.2)   }
  attrNotVGACompatible = $02;    { Video is NOT VGA compatible (2.0)   }
  attrSnowCheck        = $04;    { Video must use snow checking(2.0)   }

  { mode attribute bits }
  modeAvail          = $01;      { Hardware supports this mode (1.0)   }
  modeExtendInfo     = $02;      { Extended information        (1.0)   }
  modeBIOSSupport    = $04;      { TTY BIOS Support            (1.0)   }
  modeColor          = $08;      { This is a color mode        (1.0)   }
  modeGraphics       = $10;      { This is a graphics mode     (1.0)   }
  modeNotVGACompatible = $20;    { this mode is NOT I/O VGA compatible (2.0)}
  modeNoWindowed     = $40;      { This mode does not support Windows (2.0) }
  modeLinearBuffer   = $80;      { This mode supports linear buffers  (2.0) }

  { window attributes }
  winSupported       = $01;
  winReadable        = $02;
  winWritable        = $04;

  { memory model }
  modelText          = $00;
  modelCGA           = $01;
  modelHerc          = $02;
  model4plane        = $03;
  modelPacked        = $04;
  modelModeX         = $05;
  modelRGB           = $06;
  modelYUV           = $07;

{$ifndef dpmi}
{$i vesah.inc}
{ otherwise it's already included in graph.pp }
{$endif dpmi}

var

  BytesPerLine: word;              { Number of bytes per scanline }
  YOffset : word;                  { Pixel offset for VESA page flipping }

  { window management }
  ReadWindow : byte;      { Window number for reading. }
  WriteWindow: byte;      { Window number for writing. }
  winReadSeg : word;      { Address of segment for read  }
  winWriteSeg: word;      { Address of segment for writes}
  CurrentReadBank : integer; { active read bank          }
  CurrentWriteBank: integer; { active write bank         }

  BankShift : word;       { address to shift by when switching banks. }

  { linear mode specific stuff }
  InLinear  : boolean;    { true if in linear mode }
  LinearPageOfs : longint; { offset used to set active page }
  FrameBufferLinearAddress : longint;

  ScanLines: word;        { maximum number of scan lines for mode }

function hexstr(val : longint;cnt : byte) : string;
const
  HexTbl : array[0..15] of char='0123456789ABCDEF';
var
  i : longint;
begin
  hexstr[0]:=char(cnt);
  for i:=cnt downto 1 do
   begin
     hexstr[i]:=hextbl[val and $f];
     val:=val shr 4;
   end;
end;


{$IFDEF DPMI}

  function getVESAInfo(var VESAInfo: TVESAInfo) : boolean;
   var
    ptrlong : longint;
    VESAPtr : ^TVESAInfo;
    st : string[4];
    regs : TDPMIRegisters;
{$ifndef fpc}
    ModeSel: word;
    offs: longint;
{$endif fpc}
    { added... }
    modelist: PmodeList;
    i: longint;
    RealSeg : word;
   begin
    { Allocate real mode buffer }
{$ifndef fpc}
    Ptrlong:=GlobalDosAlloc(sizeof(TVESAInfo));
    { Get selector value }
    VESAPtr := pointer(Ptrlong shl 16);
{$else fpc}
    Ptrlong:=Global_Dos_Alloc(sizeof(TVESAInfo));
    New(VESAPtr);
{$endif fpc}
    { Get segment value }
    RealSeg := word(Ptrlong shr 16);
    if not assigned(VESAPtr) then
      RunError(203);
    FillChar(regs, sizeof(regs), #0);

    { Get VESA Mode information ... }
    regs.eax := $4f00;
    regs.es := RealSeg;
    regs.edi := $00;
    RealIntr($10, regs);
{$ifdef fpc}
   { no far pointer support in FPC yet, so move the vesa info into a memory }
   { block in the DS slector space (JM)                                     }
    dosmemget(RealSeg,0,VesaPtr^,SizeOf(TVESAInfo));
{$endif fpc}
    St:=Vesaptr^.signature;
    if st<>'VESA' then
     begin
{$ifdef logging}
         LogLn('No VESA detected.');
{$endif logging}
         getVesaInfo := FALSE;
{$ifndef fpc}
         GlobalDosFree(word(PtrLong and $ffff));
{$else fpc}
         If not Global_Dos_Free(word(PtrLong and $ffff)) then
           RunError(216);
         { also free the extra allocated buffer }
         Dispose(VESAPtr);
{$endif fpc}
         exit;
     end
    else
      getVesaInfo := TRUE;

{$ifndef fpc}
    { The mode pointer buffer points to a real mode memory }
    { Therefore steps to get the modes:                    }
    {  1. Allocate Selector and SetLimit to max number of  }
    {     of possible modes.                               }
    ModeSel := AllocSelector(0);
    SetSelectorLimit(ModeSel, 256*sizeof(word));

    {  2. Set Selector linear address to the real mode pointer }
    {     returned.                                            }
    offs := longint(longint(VESAPtr^.ModeList) shr 16) shl 4;
   {shouldn't the OR in the next line be a + ?? (JM)}
    offs :=  offs OR (Longint(VESAPtr^.ModeList) and $ffff);
    SetSelectorBase(ModeSel, offs);

     { copy VESA mode information to a protected mode buffer and }
     { then free the real mode buffer...                         }
     Move(VESAPtr^, VESAInfo, sizeof(VESAInfo));
     GlobalDosFree(word(PtrLong and $ffff));

    { ModeList points to the mode list     }
    { We must copy it somewhere...         }
    ModeList := Ptr(ModeSel, 0);

{$else fpc}
    { No far pointer support, so the Ptr(ModeSel, 0) doesn't work.     }
    { Immediately copy everything to a buffer in the DS selector space }
     New(ModeList);
    { The following may copy data from outside the VESA buffer, but it   }
    { shouldn't get past the 1MB limit, since that would mean the buffer }
    { has been allocated in the BIOS or high memory region, which seems  }
    { impossible to me (JM)}
     DosMemGet(word(longint(VESAPtr^.ModeList) shr 16),
        word(longint(VESAPtr^.ModeList) and $ffff), ModeList^,256*sizeof(word));

     { copy VESA mode information to a protected mode buffer and }
     { then free the real mode buffer...                         }
     Move(VESAPtr^, VESAInfo, sizeof(VESAInfo));
     If not Global_Dos_Free(word(PtrLong and $ffff)) then
       RunError(216);
     Dispose(VESAPtr);
{$endif fpc}

    i:=0;
    new(VESAInfo.ModeList);
    while ModeList^[i]<> $ffff do
     begin
{$ifdef logging}
      LogLn('Found mode $'+hexstr(ModeList^[i],4));
{$endif loggin}
      VESAInfo.ModeList^[i] := ModeList^[i];
      Inc(i);
     end;
    VESAInfo.ModeList^[i]:=$ffff;
    { Free the temporary selector used to get mode information }
{$ifdef logging}
    LogLn(strf(i) + ' modes found.');
{$endif logging}
{$ifndef fpc}
    FreeSelector(ModeSel);
{$else fpc}
    Dispose(ModeList);
{$endif fpc}
   end;

  function getVESAModeInfo(var ModeInfo: TVESAModeInfo;mode:word):boolean;
   var
    Ptr: longint;
{$ifndef fpc}
    VESAPtr : ^TVESAModeInfo;
{$endif fpc}
    regs : TDPMIRegisters;
    RealSeg: word;
   begin
    { Alllocate real mode buffer }
{$ifndef fpc}
    Ptr:=GlobalDosAlloc(sizeof(TVESAModeInfo));
    { get the selector value }
    VESAPtr := pointer(longint(Ptr shl 16));
    if not assigned(VESAPtr) then
      RunError(203);
{$else fpc}
    Ptr:=Global_Dos_Alloc(sizeof(TVESAModeInfo));
{$endif fpc}
    { get the segment value }
    RealSeg := word(Ptr shr 16);
    { setup interrupt registers }
    FillChar(regs, sizeof(regs), #0);
    { call VESA mode information...}
    regs.eax := $4f01;
    regs.es := RealSeg;
    regs.edi := $00;
    regs.ecx := mode;
    RealIntr($10, regs);
    if word(regs.eax) <> $4f then
      getVESAModeInfo := FALSE
    else
      getVESAModeInfo := TRUE;
    { copy to protected mode buffer ... }
{$ifndef fpc}
    Move(VESAPtr^, ModeInfo, sizeof(ModeInfo));
{$else fpc}
    DosMemGet(RealSeg,0,ModeInfo,sizeof(ModeInfo));
{$endif fpc}
    { free real mode memory  }
{$ifndef fpc}
    GlobalDosFree(Word(Ptr and $ffff));
{$else fpc}
    If not Global_Dos_Free(Word(Ptr and $ffff)) then
      RunError(216);
{$endif fpc}
   end;

{$ELSE}
  function getVESAInfo(var VESAInfo: TVESAInfo) : boolean; assembler;
  asm
       mov ax,4F00h
       les di,VESAInfo
       int 10h
       sub ax,004Fh  {make sure we got 004Fh back}
       cmp ax,1
       sbb al,al
       cmp word ptr es:[di],'V'or('E'shl 8)  {signature should be 'VESA'}
       jne @@ERR
       cmp word ptr es:[di+2],'S'or('A'shl 8)
       je @@X
     @@ERR:
       mov al,0
     @@X:
  end;


  function getVESAModeInfo(var ModeInfo: TVESAModeInfo;mode:word):boolean;assembler;
   asm
     mov ax,4F01h
     mov cx,mode
     les di,ModeInfo
     int 10h
     sub ax,004Fh   {make sure it's 004Fh}
     cmp ax,1
     sbb al,al
   end;

{$ENDIF}

  function SearchVESAModes(mode: Word): boolean;
  {********************************************************}
  { Searches for a specific DEFINED vesa mode. If the mode }
  { is not available for some reason, then returns FALSE   }
  { otherwise returns TRUE.                                }
  {********************************************************}
   var
     i: word;
     ModeSupported : Boolean;
    begin
      i:=0;
      { let's assume it's not available ... }
      ModeSupported := FALSE;
      { This is a STUB VESA implementation  }
      if VESAInfo.ModeList^[0] = $FFFF then exit;
      repeat
        if VESAInfo.ModeList^[i] = mode then
         begin
            { we found it, the card supports this mode... }
            ModeSupported := TRUE;
            break;
         end;
        Inc(i);
      until VESAInfo.ModeList^[i] = $ffff;
      { now check if the hardware supports it... }
      If ModeSupported then
        begin
          { we have to init everything to zero, since VBE < 1.1  }
          { may not setup fields correctly.                      }
          FillChar(VESAModeInfo, sizeof(VESAModeInfo), #0);
          If GetVESAModeInfo(VESAModeInfo, Mode) And
             ((VESAModeInfo.attr and modeAvail) <> 0) then
            ModeSupported := TRUE
          else
            ModeSupported := FALSE;
        end;
       SearchVESAModes := ModeSupported;
    end;



  procedure SetBankIndex(win: byte; BankNr: Integer); assembler;
   asm
{$IFDEF REGCALL}
     mov  bl, al
{$ELSE REGCALL}
     mov  bl,[Win]
{$ENDIF REGCALL}
     mov  ax,4f05h
     mov  bh,00h
{$IFNDEF REGCALL}
     mov  dx,[BankNr]
{$ENDIF REGCALL}
{$ifdef fpc}
     push ebp
{$endif fpc}
     int  10h
{$ifdef fpc}
     pop ebp
{$endif fpc}
   end;

  {********************************************************}
  { There are two routines for setting banks. This may in  }
  { in some cases optimize a bit some operations, if the   }
  { hardware supports it, because one window is used for   }
  { reading and one window is used for writing.            }
  {********************************************************}
  procedure SetReadBank(BankNr: Integer);
   begin
     { check if this is the current bank... if so do nothing. }
     if BankNr = CurrentReadBank then exit;
{$ifdef logging}
{     LogLn('Setting read bank to '+strf(BankNr));}
{$endif logging}
     CurrentReadBank := BankNr;          { save current bank number     }
     BankNr := BankNr shl BankShift;     { adjust to window granularity }
     { we set both banks, since one may read only }
     SetBankIndex(ReadWindow, BankNr);
     { if the hardware supports only one window }
     { then there is only one single bank, so   }
     { update both bank numbers.                }
     if ReadWindow = WriteWindow then
       CurrentWriteBank := CurrentReadBank;
   end;

  procedure SetWriteBank(BankNr: Integer);
   begin
     { check if this is the current bank... if so do nothing. }
     if BankNr = CurrentWriteBank then exit;
{$ifdef logging}
{     LogLn('Setting write bank to '+strf(BankNr));}
{$endif logging}
     CurrentWriteBank := BankNr;          { save current bank number     }
     BankNr := BankNr shl BankShift;     { adjust to window granularity }
     { we set both banks, since one may read only }
     SetBankIndex(WriteWindow, BankNr);
     { if the hardware supports only one window }
     { then there is only one single bank, so   }
     { update both bank numbers.                }
     if ReadWindow = WriteWindow then
       CurrentReadBank := CurrentWriteBank;
   end;

 {************************************************************************}
 {*                     8-bit pixels VESA mode routines                  *}
 {************************************************************************}

  procedure PutPixVESA256(x, y : integer; color : word); {$ifndef fpc}far;{$endif fpc}
  var
     offs : longint;
  begin
     X:= X + StartXViewPort;
     Y:= Y + StartYViewPort;
     { convert to absolute coordinates and then verify clipping...}
     if ClipPixels then
     Begin
       if (X < StartXViewPort) or (X > (StartXViewPort + ViewWidth)) then
         exit;
       if (Y < StartYViewPort) or (Y > (StartYViewPort + ViewHeight)) then
         exit;
     end;
     Y := Y + YOffset; { adjust pixel for correct virtual page }
     offs := longint(y) * BytesPerLine + x;
       begin
         SetWriteBank(integer(offs shr 16));
         mem[WinWriteSeg : word(offs)] := byte(color);
       end;
  end;

  procedure DirectPutPixVESA256(x, y : integer); {$ifndef fpc}far;{$endif fpc}
  var
     offs : longint;
     col : byte;
  begin
     offs := (longint(y) + YOffset) * BytesPerLine + x;
     Case CurrentWriteMode of
       XorPut:
         Begin
           SetReadBank(integer(offs shr 16));
           col := mem[WinReadSeg : word(offs)] xor byte(CurrentColor);
         End;
       AndPut:
         Begin
           SetReadBank(integer(offs shr 16));
           col := mem[WinReadSeg : word(offs)] And byte(CurrentColor);
         End;
       OrPut:
         Begin
           SetReadBank(integer(offs shr 16));
           col := mem[WinReadSeg : word(offs)] or byte(currentcolor);
         End
       else
         Begin
           If CurrentWriteMode <> NotPut then
             col := Byte(CurrentColor)
           else col := Not(Byte(CurrentColor));
         End
     End;
     SetWriteBank(integer(offs shr 16));
     mem[WinWriteSeg : word(offs)] := Col;
  end;

  function GetPixVESA256(x, y : integer): word; {$ifndef fpc}far;{$endif fpc}
  var
     offs : longint;
  begin
     X:= X + StartXViewPort;
     Y:= Y + StartYViewPort + YOffset;
     offs := longint(y) * BytesPerLine + x;
     SetReadBank(integer(offs shr 16));
     GetPixVESA256:=mem[WinReadSeg : word(offs)];
  end;

  Procedure GetScanLineVESA256(x1, x2, y: integer; var data); {$ifndef fpc}far;{$endif}
  var offs: Longint;
      l, amount, bankrest, index, pixels: longint;
      curbank: integer;
  begin
    inc(x1,StartXViewPort);
    inc(x2,StartXViewPort);
    {$ifdef logging}
    LogLn('getscanline256 '+strf(x1)+' - '+strf(x2)+' at '+strf(y+StartYViewPort));
    {$endif logging}
    index := 0;
    amount := x2-x1+1;
    Offs:=(Longint(y)+StartYViewPort+YOffset)*bytesperline+x1;
    Repeat
      curbank := integer(offs shr 16);
      SetReadBank(curbank);
      {$ifdef logging}
      LogLn('set bank '+strf(curbank)+' for offset '+hexstr(offs,8));
      {$endif logging}
      If ((amount >= 4) and
          ((offs and 3) = 0)) or
         (amount >= 4+4-(offs and 3)) Then
      { allign target }
        Begin
          If (offs and 3) <> 0 then
          { this cannot go past a window boundary bacause the }
          { size of a window is always a multiple of 4        }
            Begin
              {$ifdef logging}
              LogLn('Alligning by reading '+strf(4-(offs and 3))+' pixels');
              {$endif logging}
              for l := 1 to 4-(offs and 3) do
                WordArray(Data)[index+l-1] :=
                  Mem[WinReadSeg:word(offs)+l-1];
              inc(index, l);
              inc(offs, l);
              dec(amount, l);
            End;
          {$ifdef logging}
          LogLn('Offset is now '+hexstr(offs,8)+', amount left: '+strf(amount));
          {$endif logging}
          { offs is now 4-bytes alligned }
          If amount <= ($10000-(Offs and $ffff)) Then
             bankrest := amount
          else {the rest won't fit anymore in the current window }
            bankrest := $10000 - (Offs and $ffff);
          { it is possible that by aligning, we ended up in a new }
          { bank, so set the correct bank again to make sure      }
          setreadbank(offs shr 16);
          {$ifdef logging}
          LogLn('Rest to be read from this window: '+strf(bankrest));
          {$endif logging}
          For l := 0 to (Bankrest div 4)-1 Do
            begin
              pixels := MemL[WinWriteSeg:word(offs)+l*4];
              WordArray(Data)[index+l*4] := pixels and $ff;
              pixels := pixels shr 8;
              WordArray(Data)[index+l*4+1] := pixels and $ff;
              pixels := pixels shr 8;
              WordArray(Data)[index+l*4+2] := pixels and $ff;
              pixels := pixels shr 8;
              WordArray(Data)[index+l*4+3] := pixels{ and $ff};
            end;
          inc(index,l*4+4);
          inc(offs,l*4+4);
          dec(amount,l*4+4);
          {$ifdef logging}
          LogLn('Offset is now '+hexstr(offs,8)+', amount left: '+strf(amount));
          {$endif logging}
        End
      Else
        Begin
          {$ifdef logging}
          LogLn('Leftover: '+strf(amount)+' at offset '+hexstr(offs,8));
          {$endif logging}
          For l := 0 to amount - 1 do
            begin
              { this may cross a bank at any time, so adjust          }
              { because this loop alwys runs for very little pixels,  }
              { there's little gained by splitting it up              }
              setreadbank(offs shr 16);
              WordArray(Data)[index+l] := mem[WinReadSeg:word(offs)];
              inc(offs);
            end;
          amount := 0
        End
    Until amount = 0;
  end;

  procedure HLineVESA256(x,x2,y: integer); {$ifndef fpc}far;{$endif fpc}

   var Offs: Longint;
       mask, l, bankrest: longint;
       curbank, hlength: integer;
   Begin
    { must we swap the values? }
    if x > x2 then
      Begin
        x := x xor x2;
        x2 := x xor x2;
        x:= x xor x2;
      end;
    { First convert to global coordinates }
    X   := X + StartXViewPort;
    X2  := X2 + StartXViewPort;
    Y   := Y + StartYViewPort;
    if ClipPixels then
      Begin
         if LineClipped(x,y,x2,y,StartXViewPort,StartYViewPort,
                StartXViewPort+ViewWidth, StartYViewPort+ViewHeight) then
            exit;
      end;
    {$ifdef logging2}
    LogLn('hline '+strf(x)+' - '+strf(x2)+' on '+strf(y)+' in mode '+strf(currentwritemode));
    {$endif logging2}
    HLength := x2 - x + 1;
    {$ifdef logging2}
    LogLn('length: '+strf(hlength));
    {$endif logging2}
    if HLength>0 then
      begin
         Offs:=(Longint(y)+YOffset)*bytesperline+x;
         {$ifdef logging2}
         LogLn('Offs: '+strf(offs)+' -- '+hexstr(offs,8));
         {$endif logging2}
         Mask := byte(CurrentColor)+byte(CurrentColor) shl 8;
         Mask := Mask + Mask shl 16;
         Case CurrentWriteMode of
           AndPut:
             Begin
               Repeat
                 curbank := integer(offs shr 16);
                 SetWriteBank(curbank);
                 SetReadBank(curbank);
                 {$ifdef logging2}
                 LogLn('set bank '+strf(curbank)+' for offset '+hexstr(offs,8));
                 {$endif logging2}
                 If ((HLength >= 4) and
                     ((offs and 3) = 0)) or
                    (HLength >= 4+4-(offs and 3)) Then
                 { align target }
                   Begin
                     l := 0;
                     If (offs and 3) <> 0 then
                     { this cannot go past a window boundary bacause the }
                     { size of a window is always a multiple of 4        }
                       Begin
                         {$ifdef logging2}
                         LogLn('Alligning by drawing '+strf(4-(offs and 3))+' pixels');
                         {$endif logging2}
                         for l := 1 to 4-(offs and 3) do
                           Mem[WinWriteSeg:word(offs)+l-1] :=
                             Mem[WinReadSeg:word(offs)+l-1] And Byte(CurrentColor);
                       End;
                     Dec(HLength, l);
                     inc(offs, l);
                     {$ifdef logging2}
                     LogLn('Offset is now '+hexstr(offs,8)+', length left: '+strf(hlength));
                     {$endif logging}
                     { offs is now 4-bytes alligned }
                     If HLength <= ($10000-(Offs and $ffff)) Then
                        bankrest := HLength
                     else {the rest won't fit anymore in the current window }
                       bankrest := $10000 - (Offs and $ffff);
                     { it is possible that by aligningm we ended up in a new }
                     { bank, so set the correct bank again to make sure      }
                     setwritebank(offs shr 16);
                     setreadbank(offs shr 16);
                     {$ifdef logging2}
                     LogLn('Rest to be drawn in this window: '+strf(bankrest));
                     {$endif logging}
                     For l := 0 to (Bankrest div 4)-1 Do
                       MemL[WinWriteSeg:word(offs)+l*4] :=
                         MemL[WinReadSeg:word(offs)+l*4] And Mask;
                     inc(offs,l*4+4);
                     dec(hlength,l*4+4);
                     {$ifdef logging2}
                     LogLn('Offset is now '+hexstr(offs,8)+', length left: '+strf(hlength));
                     {$endif logging}
                   End
                 Else
                   Begin
                     {$ifdef logging2}
                     LogLn('Drawing leftover: '+strf(HLength)+' at offset '+hexstr(offs,8));
                     {$endif logging}
                     For l := 0 to HLength - 1 do
                       begin
                         { this may cross a bank at any time, so adjust          }
                         { becauese this loop alwys runs for very little pixels, }
                         { there's little gained by splitting it up              }
                         setreadbank(offs shr 16);
                         setwritebank(offs shr 16);
                         Mem[WinWriteSeg:word(offs)] :=
                           Mem[WinReadSeg:word(offs)] And byte(currentColor);
                         inc(offs);
                       end;
                     HLength := 0
                   End
               Until HLength = 0;
             End;
           XorPut:
             Begin
               Repeat
                 curbank := integer(offs shr 16);
                 SetWriteBank(curbank);
                 SetReadBank(curbank);
                 {$ifdef logging2}
                 LogLn('set bank '+strf(curbank)+' for offset '+hexstr(offs,8));
                 {$endif logging}
                 If ((HLength >= 4) and
                     ((offs and 3) = 0)) or
                    (HLength >= 4+4-(offs and 3)) Then
                 { allign target }
                   Begin
                     l := 0;
                     If (offs and 3) <> 0 then
                     { this cannot go past a window boundary bacause the }
                     { size of a window is always a multiple of 4        }
                       Begin
                         {$ifdef logging2}
                         LogLn('Alligning by drawing '+strf(4-(offs and 3))+' pixels');
                         {$endif logging}
                         for l := 1 to 4-(offs and 3) do
                           Mem[WinWriteSeg:word(offs)+l-1] :=
                             Mem[WinReadSeg:word(offs)+l-1] Xor Byte(CurrentColor);
                       End;
                     Dec(HLength, l);
                     inc(offs, l);
                     {$ifdef logging2}
                     LogLn('Offset is now '+hexstr(offs,8)+', length left: '+strf(hlength));
                     {$endif logging}
                     { offs is now 4-bytes alligned }
                     If HLength <= ($10000-(Offs and $ffff)) Then
                        bankrest := HLength
                     else {the rest won't fit anymore in the current window }
                       bankrest := $10000 - (Offs and $ffff);
                     { it is possible that by aligningm we ended up in a new }
                     { bank, so set the correct bank again to make sure      }
                     setwritebank(offs shr 16);
                     setreadbank(offs shr 16);
                     {$ifdef logging2}
                     LogLn('Rest to be drawn in this window: '+strf(bankrest));
                     {$endif logging}
                     For l := 0 to (Bankrest div 4)-1 Do
                       MemL[WinWriteSeg:word(offs)+l*4] :=
                         MemL[WinReadSeg:word(offs)+l*4] Xor Mask;
                     inc(offs,l*4+4);
                     dec(hlength,l*4+4);
                     {$ifdef logging2}
                     LogLn('Offset is now '+hexstr(offs,8)+', length left: '+strf(hlength));
                     {$endif logging}
                   End
                 Else
                   Begin
                     {$ifdef logging2}
                     LogLn('Drawing leftover: '+strf(HLength)+' at offset '+hexstr(offs,8));
                     {$endif logging}
                     For l := 0 to HLength - 1 do
                       begin
                         { this may cross a bank at any time, so adjust          }
                         { because this loop alwys runs for very little pixels,  }
                         { there's little gained by splitting it up              }
                         setreadbank(offs shr 16);
                         setwritebank(offs shr 16);
                         Mem[WinWriteSeg:word(offs)] :=
                           Mem[WinReadSeg:word(offs)] xor byte(currentColor);
                         inc(offs);
                       end;
                     HLength := 0
                   End
               Until HLength = 0;
             End;
           OrPut:
             Begin
               Repeat
                 curbank := integer(offs shr 16);
                 SetWriteBank(curbank);
                 SetReadBank(curbank);
                 {$ifdef logging2}
                 LogLn('set bank '+strf(curbank)+' for offset '+hexstr(offs,8));
                 {$endif logging}
                 If ((HLength >= 4) and
                     ((offs and 3) = 0)) or
                    (HLength >= 4+4-(offs and 3)) Then
                 { allign target }
                   Begin
                     l := 0;
                     If (offs and 3) <> 0 then
                     { this cannot go past a window boundary bacause the }
                     { size of a window is always a multiple of 4        }
                       Begin
                         {$ifdef logging2}
                         LogLn('Alligning by drawing '+strf(4-(offs and 3))+' pixels');
                         {$endif logging}
                         for l := 1 to 4-(offs and 3) do
                           Mem[WinWriteSeg:word(offs)+l-1] :=
                             Mem[WinReadSeg:word(offs)+l-1] Or Byte(CurrentColor);
                       End;
                     Dec(HLength, l);
                     inc(offs, l);
                     { it is possible that by aligningm we ended up in a new }
                     { bank, so set the correct bank again to make sure      }
                     setwritebank(offs shr 16);
                     setreadbank(offs shr 16);
                     {$ifdef logging2}
                     LogLn('Offset is now '+hexstr(offs,8)+', length left: '+strf(hlength));
                     {$endif logging}
                     { offs is now 4-bytes alligned }
                     If HLength <= ($10000-(Offs and $ffff)) Then
                        bankrest := HLength
                     else {the rest won't fit anymore in the current window }
                       bankrest := $10000 - (Offs and $ffff);
                     {$ifdef logging2}
                     LogLn('Rest to be drawn in this window: '+strf(bankrest));
                     {$endif logging}
                     For l := 0 to (Bankrest div 4)-1 Do
                       MemL[WinWriteSeg:offs+l*4] :=
                         MemL[WinReadSeg:word(offs)+l*4] Or Mask;
                     inc(offs,l*4+4);
                     dec(hlength,l*4+4);
                     {$ifdef logging2}
                     LogLn('Offset is now '+hexstr(offs,8)+', length left: '+strf(hlength));
                     {$endif logging}
                   End
                 Else
                   Begin
                     {$ifdef logging2}
                     LogLn('Drawing leftover: '+strf(HLength)+' at offset '+hexstr(offs,8));
                     {$endif logging}
                     For l := 0 to HLength - 1 do
                       begin
                         { this may cross a bank at any time, so adjust          }
                         { because this loop alwys runs for very little pixels,  }
                         { there's little gained by splitting it up              }
                         setreadbank(offs shr 16);
                         setwritebank(offs shr 16);
                         Mem[WinWriteSeg:word(offs)] :=
                           Mem[WinReadSeg:word(offs)] And byte(currentColor);
                         inc(offs);
                       end;
                     HLength := 0
                   End
               Until HLength = 0;
             End
           Else
             Begin
               If CurrentWriteMode = NotPut Then
                 Mask := Not(Mask);
               Repeat
                 curbank := integer(offs shr 16);
                 SetWriteBank(curbank);
                 {$ifdef logging2}
                 LogLn('set bank '+strf(curbank)+' for offset '+hexstr(offs,8)+' -- '+strf(offs));
                 {$endif logging}
                 If ((HLength >= 4) and
                     ((offs and 3) = 0)) or
                    (HLength >= 4+4-(offs and 3)) Then
                 { allign target }
                   Begin
                     l := 0;
                     If (offs and 3) <> 0 then
                     { this cannot go past a window boundary bacause the }
                     { size of a window is always a multiple of 4        }
                       Begin
                         {$ifdef logging2}
                         LogLn('Alligning by drawing '+strf(4-(offs and 3))+' pixels');
                         {$endif logging}
                         for l := 1 to 4-(offs and 3) do
                           Mem[WinWriteSeg:word(offs)+l-1] := Byte(Mask);
                       End;
                     Dec(HLength, l);
                     inc(offs, l);
                     {$ifdef logging2}
                     LogLn('Offset is now '+hexstr(offs,8)+', length left: '+strf(hlength));
                     {$endif logging}
                     { offs is now 4-bytes alligned }
                     If HLength <= ($10000-(Offs and $ffff)) Then
                        bankrest := HLength
                     else {the rest won't fit anymore in the current window }
                       bankrest := $10000 - (Offs and $ffff);
                     { it is possible that by aligningm we ended up in a new }
                     { bank, so set the correct bank again to make sure      }
                     setwritebank(offs shr 16);
                     {$ifdef logging2}
                     LogLn('Rest to be drawn in this window: '+strf(bankrest)+' -- '+hexstr(bankrest,8));
                     {$endif logging}
                     For l := 0 to (Bankrest div 4)-1 Do
                       MemL[WinWriteSeg:word(offs)+l*4] := Mask;
                     inc(offs,l*4+4);
                     dec(hlength,l*4+4);
                     {$ifdef logging2}
                     LogLn('Offset is now '+hexstr(offs,8)+', length left: '+strf(hlength));
                     {$endif logging}
                   End
                 Else
                   Begin
                     {$ifdef logging2}
                     LogLn('Drawing leftover: '+strf(HLength)+' at offset '+hexstr(offs,8));
                     {$endif logging}
                     For l := 0 to HLength - 1 do
                       begin
                         { this may cross a bank at any time, so adjust          }
                         { because this loop alwys runs for very little pixels,  }
                         { there's little gained by splitting it up              }
                         setwritebank(offs shr 16);
                         Mem[WinWriteSeg:word(offs)] := byte(mask);
                         inc(offs);
                       end;
                     HLength := 0
                   End
               Until HLength = 0;
             End;
         End;
       end;
   end;

  procedure VLineVESA256(x,y,y2: integer); {$ifndef fpc}far;{$endif fpc}

   var Offs: Longint;
       l, bankrest: longint;
       curbank, vlength: integer;
       col: byte;
   Begin
    { must we swap the values? }
    if y > y2 then
      Begin
        y := y xor y2;
        y2 := y xor y2;
        y:= y xor y2;
      end;
    { First convert to global coordinates }
    X   := X + StartXViewPort;
    Y   := Y + StartYViewPort;
    Y2  := Y2 + StartYViewPort;
    if ClipPixels then
      Begin
         if LineClipped(x,y,x,y2,StartXViewPort,StartYViewPort,
                StartXViewPort+ViewWidth, StartYViewPort+ViewHeight) then
            exit;
      end;
    Col := Byte(CurrentColor);
    {$ifdef logging2}
    LogLn('vline '+strf(y)+' - '+strf(y2)+' on '+strf(x)+' in mode '+strf(currentwritemode));
    {$endif logging}
    VLength := y2 - y + 1;
    {$ifdef logging2}
    LogLn('length: '+strf(vlength));
    {$endif logging}
    if VLength>0 then
      begin
         Offs:=(Longint(y)+YOffset)*bytesperline+x;
         {$ifdef logging2}
         LogLn('Offs: '+strf(offs)+' -- '+hexstr(offs,8));
         {$endif logging}
         Case CurrentWriteMode of
           AndPut:
             Begin
               Repeat
                 curbank := integer(offs shr 16);
                 SetWriteBank(curbank);
                 SetReadBank(curbank);
                 {$ifdef logging2}
                 LogLn('set bank '+strf(curbank)+' for offset '+hexstr(offs,8));
                 {$endif logging}
                 If (VLength-1)*bytesperline <= ($10000-(Offs and $ffff)) Then
                   bankrest := VLength
                 else {the rest won't fit anymore in the current window }
                   bankrest := (($10000 - (Offs and $ffff)) div bytesperline)+1;
                 {$ifdef logging2}
                 LogLn('Rest to be drawn in this window: '+strf(bankrest));
                 {$endif logging}
                 For l := 0 to Bankrest-1 Do
                   begin
                     Mem[WinWriteSeg:word(offs)] :=
                       Mem[WinReadSeg:word(offs)] And Col;
                     inc(offs,bytesperline);
                   end;
                 dec(VLength,l+1);
                 {$ifdef logging2}
                 LogLn('Offset is now '+hexstr(offs,8)+', length left: '+strf(vlength));
                 {$endif logging}
               Until VLength = 0;
             End;
           XorPut:
             Begin
               Repeat
                 curbank := integer(offs shr 16);
                 SetWriteBank(curbank);
                 SetReadBank(curbank);
                 {$ifdef logging2}
                 LogLn('set bank '+strf(curbank)+' for offset '+hexstr(offs,8));
                 {$endif logging}
                 If (VLength-1)*bytesperline <= ($10000-(Offs and $ffff)) Then
                   bankrest := VLength
                 else {the rest won't fit anymore in the current window }
                   bankrest := (($10000 - (Offs and $ffff)) div bytesperline)+1;
                 {$ifdef logging2}
                 LogLn('Rest to be drawn in this window: '+strf(bankrest));
                 {$endif logging}
                 For l := 0 to Bankrest-1 Do
                   begin
                     Mem[WinWriteSeg:word(offs)] :=
                       Mem[WinReadSeg:word(offs)] Xor Col;
                     inc(offs,bytesperline);
                   end;
                 dec(VLength,l+1);
                 {$ifdef logging2}
                 LogLn('Offset is now '+hexstr(offs,8)+', length left: '+strf(vlength));
                 {$endif logging}
               Until VLength = 0;
             End;
           OrPut:
             Begin
               Repeat
                 curbank := integer(offs shr 16);
                 SetWriteBank(curbank);
                 SetReadBank(curbank);
                 {$ifdef logging2}
                 LogLn('set bank '+strf(curbank)+' for offset '+hexstr(offs,8));
                 {$endif logging}
                 If (VLength-1)*bytesperline <= ($10000-(Offs and $ffff)) Then
                   bankrest := VLength
                 else {the rest won't fit anymore in the current window }
                   bankrest := (($10000 - (Offs and $ffff)) div bytesperline)+1;
                 {$ifdef logging2}
                 LogLn('Rest to be drawn in this window: '+strf(bankrest));
                 {$endif logging}
                 For l := 0 to Bankrest-1 Do
                   begin
                     Mem[WinWriteSeg:word(offs)] :=
                       Mem[WinReadSeg:word(offs)] Or Col;
                     inc(offs,bytesperline);
                   end;
                 dec(VLength,l+1);
                 {$ifdef logging2}
                 LogLn('Offset is now '+hexstr(offs,8)+', length left: '+strf(vlength));
                 {$endif logging}
               Until VLength = 0;
             End;
           Else
             Begin
               If CurrentWriteMode = NotPut Then
                 Col := Not(Col);
               Repeat
                 curbank := integer(offs shr 16);
                 SetWriteBank(curbank);
                 {$ifdef logging2}
                 LogLn('set bank '+strf(curbank)+' for offset '+hexstr(offs,8));
                 {$endif logging}
                 If (VLength-1)*bytesperline <= ($10000-(Offs and $ffff)) Then
                   bankrest := VLength
                 else {the rest won't fit anymore in the current window }
                   bankrest := (($10000 - (Offs and $ffff)) div bytesperline)+1;
                 {$ifdef logging2}
                 LogLn('Rest to be drawn in this window: '+strf(bankrest));
                 {$endif logging}
                 For l := 0 to Bankrest-1 Do
                   begin
                     Mem[WinWriteSeg:word(offs)] := Col;
                     inc(offs,bytesperline);
                   end;
                 dec(VLength,l+1);
                 {$ifdef logging2}
                 LogLn('Offset is now '+hexstr(offs,8)+', length left: '+strf(vlength));
                 {$endif logging}
               Until VLength = 0;
             End;
         End;
       end;
   end;

  procedure PatternLineVESA256(x1,x2,y: smallint); {$ifndef fpc}far;{$endif fpc}
  {********************************************************}
  { Draws a horizontal patterned line according to the     }
  { current Fill Settings.                                 }
  {********************************************************}
  { Important notes:                                       }
  {  - CurrentColor must be set correctly before entering  }
  {    this routine.                                       }
  {********************************************************}
   type
     TVESA256Fill = Record
       case byte of
         0: (data1, data2: longint);
         1: (pat: array[0..7] of byte);
     end;

   var
    fill: TVESA256Fill;
    bankrest, l : longint;
    offs, amount: longint;
    i           : smallint;
    j           : smallint;
    OldWriteMode : word;
    TmpFillPattern, patternPos : byte;
   begin
     { convert to global coordinates ... }
     x1 := x1 + StartXViewPort;
     x2 := x2 + StartXViewPort;
     y  := y + StartYViewPort;
     { if line was fully clipped then exit...}
     if LineClipped(x1,y,x2,y,StartXViewPort,StartYViewPort,
        StartXViewPort+ViewWidth, StartYViewPort+ViewHeight) then
         exit;
     OldWriteMode := CurrentWriteMode;
     CurrentWriteMode := NormalPut;
     { Get the current pattern }
     TmpFillPattern := FillPatternTable
       [FillSettings.Pattern][((y + startYViewPort) and $7)+1];
     {$ifdef logging2}
     LogLn('patternline '+strf(x1)+' - '+strf(x2)+' on '+strf(y));
     {$endif logging2}
     { how long is the line }
     amount := x2 - x1 + 1;
     { offset to start at }
     offs := (longint(y)+yoffset)*bytesperline+x1;
     { convert the pattern data into the actual color sequence }
     j := 1;
     FillChar(fill,sizeOf(fill),byte(currentBkColor));
     for i := 0 to 7 do
       begin
         if TmpFillPattern and j <> 0 then
           fill.pat[7-i] := currentColor;
{$ifopt q+}
{$q-}
{$define overflowOn}
{$endif}
         j := j shl 1;
{$ifdef overflowOn}
{$q+}
{$undef overflowOn}
{$endif}
       end;
     Repeat
       SetWriteBank(integer(offs shr 16));
       If (amount > 7) and
          (((offs and 7) = 0) or
           (amount > 7+8-(offs and 7))) Then
         Begin
           { align target }
           l := 0;
           If (offs and 7) <> 0 then
           { this cannot go past a window boundary bacause the }
           { size of a window is always a multiple of 8        }
             Begin
               { position in the pattern where to start }
               patternPos := offs and 7;
               {$ifdef logging2}
               LogLn('Aligning by drawing '+strf(8-(offs and 7))+' pixels');
               {$endif logging2}
               for l := 1 to 8-(offs and 7) do
                 begin
                   Mem[WinWriteSeg:word(offs)+l-1] := fill.pat[patternPos and 7];
                   inc(patternPos)
                 end;
             End;
           Dec(amount, l);
           inc(offs, l);
           {$ifdef logging2}
           LogLn('Offset is now '+hexstr(offs,8)+', length left: '+strf(amount));
           {$endif logging2}
           { offs is now 8-bytes alligned }
           If amount <= ($10000-(Offs and $ffff)) Then
              bankrest := amount
           else {the rest won't fit anymore in the current window }
             bankrest := $10000 - (Offs and $ffff);
           { it is possible that by aligningm we ended up in a new }
           { bank, so set the correct bank again to make sure      }
           setwritebank(offs shr 16);
           {$ifdef logging2}
           LogLn('Rest to be drawn in this window: '+strf(bankrest));
           {$endif logging2}
           for l := 0 to (bankrest div 8)-1 Do
             begin
               MemL[WinWriteSeg:word(offs)+l*8] := fill.data1;
               MemL[WinWriteSeg:word(offs)+l*8+4] := fill.data2;
             end;
           inc(offs,l*8+8);
           dec(amount,l*8+8);
           {$ifdef logging2}
           LogLn('Offset is now '+hexstr(offs,8)+', length left: '+strf(amount));
           {$endif logging2}
         End
       Else
         Begin
           {$ifdef logging2}
           LogLn('Drawing leftover: '+strf(amount)+' at offset '+hexstr(offs,8));
           {$endif logging2}
           patternPos := offs and 7;
           For l := 0 to amount - 1 do
             begin
               { this may cross a bank at any time, so adjust          }
               { because this loop alwys runs for very little pixels,  }
               { there's little gained by splitting it up              }
               setwritebank(offs shr 16);
               Mem[WinWriteSeg:word(offs)] := fill.pat[patternPos and 7];
               inc(offs);
               inc(patternPos);
             end;
           amount := 0;
         End
     Until amount = 0;
     currentWriteMode := oldWriteMode;
   end;


 {************************************************************************}
 {*                    256 colors VESA mode routines  Linear mode        *}
 {************************************************************************}
{$ifdef FPC}
type
  pbyte = ^byte;
  pword = ^word;

  procedure DirectPutPixVESA256Linear(x, y : integer); {$ifndef fpc}far;{$endif fpc}
  var
     offs : longint;
     col : byte;
  begin
     offs := longint(y) * BytesPerLine + x;
     Case CurrentWriteMode of
       XorPut:
         Begin
           if UseNoSelector then
             col:=pbyte(LFBPointer+offs+LinearPageOfs)^
           else
             seg_move(WinWriteSeg,offs+LinearPageOfs,get_ds,longint(@col),1);
           col := col xor byte(CurrentColor);
         End;
       AndPut:
         Begin
           if UseNoSelector then
             col:=pbyte(LFBPointer+offs+LinearPageOfs)^
           else
             seg_move(WinWriteSeg,offs+LinearPageOfs,get_ds,longint(@col),1);
           col := col and byte(CurrentColor);
         End;
       OrPut:
         Begin
           if UseNoSelector then
             col:=pbyte(LFBPointer+offs+LinearPageOfs)^
           else
             seg_move(WinWriteSeg,offs+LinearPageOfs,get_ds,longint(@col),1);
           col := col or byte(CurrentColor);
         End
       else
         Begin
           If CurrentWriteMode <> NotPut then
             col := Byte(CurrentColor)
           else col := Not(Byte(CurrentColor));
         End
     End;
     if UseNoSelector then
       pbyte(LFBPointer+offs+LinearPageOfs)^:=col
     else
       seg_move(get_ds,longint(@col),WinWriteSeg,offs+LinearPageOfs,1);
  end;

  procedure PutPixVESA256Linear(x, y : integer; color : word); {$ifndef fpc}far;{$endif fpc}
  var
     offs : longint;
  begin
     X:= X + StartXViewPort;
     Y:= Y + StartYViewPort;
     { convert to absolute coordinates and then verify clipping...}
     if ClipPixels then
     Begin
       if (X < StartXViewPort) or (X > (StartXViewPort + ViewWidth)) then
         exit;
       if (Y < StartYViewPort) or (Y > (StartYViewPort + ViewHeight)) then
         exit;
     end;
     offs := longint(y) * BytesPerLine + x;
     {$ifdef logging}
     logln('putpix offset: '+hexstr(offs,8)+', color: '+strf(color)+', lpo: $'+
       hexstr(LinearPageOfs,8));
     {$endif logging}
     if UseNoSelector then
       pbyte(LFBPointer+offs+LinearPageOfs)^:=byte(color)
     else
       seg_move(get_ds,longint(@color),WinWriteSeg,offs+LinearPageOfs,1);
  end;

  function GetPixVESA256Linear(x, y : integer): word; {$ifndef fpc}far;{$endif fpc}
  var
     offs : longint;
     col : byte;
  begin
     X:= X + StartXViewPort;
     Y:= Y + StartYViewPort;
     offs := longint(y) * BytesPerLine + x;
     {$ifdef logging}
     logln('getpix offset: '+hexstr(offs,8)+', lpo: $'+
       hexstr(LinearPageOfs,8));
     {$endif logging}
     if UseNoSelector then
       col:=pbyte(LFBPointer+offs+LinearPageOfs)^
     else
       seg_move(WinWriteSeg,offs+LinearPageOfs,get_ds,longint(@col),1);
     GetPixVESA256Linear:=col;
  end;
(*
function SetVESADisplayStart(PageNum : word;x,y : integer):Boolean;
var
  dregs : registers;
begin
  if PageNum>VesaModeInfo.NumberOfPages then
    PageNum:=0;
{$ifdef DEBUG}
  if PageNum>0 then
    writeln(stderr,'Setting Display Page ',PageNum);
{$endif DEBUG}
  dregs.RealEBX:=0{ $80 for Wait for retrace };
  dregs.RealECX:=x;
  dregs.RealEDX:=y+PageNum*maxy;
  dregs.RealSP:=0;
  dregs.RealSS:=0;
  dregs.RealEAX:=$4F07; RealIntr($10,dregs);
  { idem as above !!! }
  if (dregs.RealEAX and $1FF) <> $4F then
    begin
{$ifdef DEBUG}
       writeln(stderr,'Set Display start error');
{$endif DEBUG}
       SetVESADisplayStart:=false;
    end
  else
    SetVESADisplayStart:=true;
end;
*)
{$endif FPC}


 {************************************************************************}
 {*                    15/16bit pixels VESA mode routines                *}
 {************************************************************************}

  procedure PutPixVESA32kOr64k(x, y : integer; color : word); {$ifndef fpc}far;{$endif fpc}
  var
     offs : longint;
  begin
{$ifdef logging}
     logln('putpixvesa32kor64k('+strf(x)+','+strf(y)+')');
{$endif logging}
     X:= X + StartXViewPort;
     Y:= Y + StartYViewPort;
     { convert to absolute coordinates and then verify clipping...}
     if ClipPixels then
     Begin
       if (X < StartXViewPort) or (X > (StartXViewPort + ViewWidth)) then
         exit;
       if (Y < StartYViewPort) or (Y > (StartYViewPort + ViewHeight)) then
         exit;
     end;
     Y := Y + YOffset; { adjust pixel for correct virtual page }
     offs := longint(y) * BytesPerLine + 2*x;
     SetWriteBank(integer(offs shr 16));
{$ifdef logging}
     logln('putpixvesa32kor64k offset: '+strf(word(offs)));
{$endif logging}
     memW[WinWriteSeg : word(offs)] := color;
  end;

  function GetPixVESA32kOr64k(x, y : integer): word; {$ifndef fpc}far;{$endif fpc}
  var
     offs : longint;
  begin
     X:= X + StartXViewPort;
     Y:= Y + StartYViewPort + YOffset;
     offs := longint(y) * BytesPerLine + 2*x;
     SetReadBank(integer(offs shr 16));
     GetPixVESA32kOr64k:=memW[WinReadSeg : word(offs)];
  end;

  procedure DirectPutPixVESA32kOr64k(x, y : integer); {$ifndef fpc}far;{$endif fpc}
  var
     offs : longint;
     col : word;
  begin
{$ifdef logging}
     logln('directputpixvesa32kor64k('+strf(x)+','+strf(y)+')');
{$endif logging}
     y:= Y + YOffset;
     offs := longint(y) * BytesPerLine + 2*x;
     SetWriteBank(integer((offs shr 16) and $ff));
     Case CurrentWriteMode of
       XorPut:
         Begin
           SetReadBank(integer(offs shr 16));
           memW[WinWriteSeg : word(offs)] := memW[WinReadSeg : word(offs)] xor currentcolor;
         End;
       AndPut:
         Begin
           SetReadBank(integer(offs shr 16));
           memW[WinWriteSeg : word(offs)] := memW[WinReadSeg : word(offs)] And currentcolor;
         End;
       OrPut:
         Begin
           SetReadBank(integer(offs shr 16));
           memW[WinWriteSeg : word(offs)] := memW[WinReadSeg : word(offs)] or currentcolor;
         End
       else
         Begin
           If CurrentWriteMode <> NotPut Then
             col := CurrentColor
           Else col := Not(CurrentColor);
{$ifdef logging}
           logln('directputpixvesa32kor64k offset: '+strf(word(offs)));
{$endif logging}
           memW[WinWriteSeg : word(offs)] := Col;
         End
     End;
  end;

{$ifdef FPC}
 {************************************************************************}
 {*                    15/16bit pixels VESA mode routines  Linear mode   *}
 {************************************************************************}

  procedure PutPixVESA32kor64kLinear(x, y : integer; color : word); {$ifndef fpc}far;{$endif fpc}
  var
     offs : longint;
  begin
     X:= X + StartXViewPort;
     Y:= Y + StartYViewPort;
     { convert to absolute coordinates and then verify clipping...}
     if ClipPixels then
     Begin
       if (X < StartXViewPort) or (X > (StartXViewPort + ViewWidth)) then
         exit;
       if (Y < StartYViewPort) or (Y > (StartYViewPort + ViewHeight)) then
         exit;
     end;
     offs := longint(y) * BytesPerLine + 2*x;
     if UseNoSelector then
       pword(LFBPointer+offs+LinearPageOfs)^:=color
     else
       seg_move(get_ds,longint(@color),WinWriteSeg,offs+LinearPageOfs,2);
  end;

  function GetPixVESA32kor64kLinear(x, y : integer): word; {$ifndef fpc}far;{$endif fpc}
  var
     offs : longint;
     color : word;
  begin
     X:= X + StartXViewPort;
     Y:= Y + StartYViewPort;
     offs := longint(y) * BytesPerLine + 2*x;
     if UseNoSelector then
       color:=pword(LFBPointer+offs+LinearPageOfs)^
     else
       seg_move(WinWriteSeg,offs+LinearPageOfs,get_ds,longint(@color),2);
     GetPixVESA32kor64kLinear:=color;
  end;

  procedure DirectPutPixVESA32kor64kLinear(x, y : integer); {$ifndef fpc}far;{$endif fpc}
  var
     offs : longint;
     col : word;
  begin
     offs := longint(y) * BytesPerLine + 2*x;
     Case CurrentWriteMode of
       XorPut:
         Begin
           if UseNoSelector then
             col:=pword(LFBPointer+offs+LinearPageOfs)^
           else
             seg_move(WinWriteSeg,offs+LinearPageOfs,get_ds,longint(@col),2);
           col := col xor currentcolor;
         End;
       AndPut:
         Begin
           if UseNoSelector then
             col:=pword(LFBPointer+offs+LinearPageOfs)^
           else
             seg_move(WinWriteSeg,offs+LinearPageOfs,get_ds,longint(@col),2);
           col := col and currentcolor;
         End;
       OrPut:
         Begin
           if UseNoSelector then
             col:=pword(LFBPointer+offs+LinearPageOfs)^
           else
             seg_move(WinWriteSeg,offs+LinearPageOfs,get_ds,longint(@col),2);
           col := col or currentcolor;
         End
       else
         Begin
           If CurrentWriteMode <> NotPut Then
             col := CurrentColor
           Else col := Not(CurrentColor);
         End
     End;
     if UseNoSelector then
       pword(LFBPointer+offs+LinearPageOfs)^:=col
     else
       seg_move(get_ds,longint(@col),WinWriteSeg,offs+LinearPageOfs,2);
  end;

{$endif FPC}

 {************************************************************************}
 {*                     4-bit pixels VESA mode routines                  *}
 {************************************************************************}

  procedure PutPixVESA16(x, y : integer; color : word); {$ifndef fpc}far;{$endif fpc}
    var
     offs : longint;
     dummy : byte;
  begin
     X:= X + StartXViewPort;
     Y:= Y + StartYViewPort;
     { convert to absolute coordinates and then verify clipping...}
    if ClipPixels then
     Begin
       if (X < StartXViewPort) or (X > (StartXViewPort + ViewWidth)) then
         exit;
       if (Y < StartYViewPort) or (Y > (StartYViewPort + ViewHeight)) then
         exit;
     end;
     Y := Y + YOffset; { adjust pixel for correct virtual page }
     { }
     offs := longint(y) * BytesPerLine + (x div 8);
     SetWriteBank(integer(offs shr 16));

     PortW[$3ce] := $0f01;       { Index 01 : Enable ops on all 4 planes }
     PortW[$3ce] := color shl 8; { Index 00 : Enable correct plane and write color }

     Port[$3ce] := 8;           { Index 08 : Bitmask register.          }
     Port[$3cf] := $80 shr (x and $7); { Select correct bits to modify }

     dummy := Mem[WinWriteSeg: offs];  { Latch the data into host space.  }
     Mem[WinWriteSeg: offs] := dummy;  { Write the data into video memory }
     PortW[$3ce] := $ff08;         { Enable all bit planes.           }
     PortW[$3ce] := $0001;         { Index 01 : Disable ops on all four planes.         }
     { }
  end;


 Function GetPixVESA16(X,Y: Integer):word; {$ifndef fpc}far;{$endif fpc}
 Var dummy, offset: Word;
     shift: byte;
  Begin
    X:= X + StartXViewPort;
    Y:= Y + StartYViewPort + YOffset;
    offset := longint(Y) * BytesPerLine + (x div 8);
    SetReadBank(integer(offset shr 16));
    Port[$3ce] := 4;
    shift := 7 - (X and 7);
    Port[$3cf] := 0;
    dummy := (Mem[WinReadSeg:offset] shr shift) and 1;
    Port[$3cf] := 1;
    dummy := dummy or (((Mem[WinReadSeg:offset] shr shift) and 1) shl 1);
    Port[$3cf] := 2;
    dummy := dummy or (((Mem[WinReadSeg:offset] shr shift) and 1) shl 2);
    Port[$3cf] := 3;
    dummy := dummy or (((Mem[WinReadSeg:offset] shr shift) and 1) shl 3);
    GetPixVESA16 := dummy;
  end;


  procedure DirectPutPixVESA16(x, y : integer); {$ifndef fpc}far;{$endif fpc}
    var
     offs : longint;
     dummy : byte;
     Color : word;
  begin
    y:= Y + YOffset;
    case CurrentWriteMode of
      XORPut:
        begin
      { getpixel wants local/relative coordinates }
          Color := GetPixVESA16(x-StartXViewPort,y-StartYViewPort);
          Color := CurrentColor Xor Color;
        end;
      OrPut:
        begin
      { getpixel wants local/relative coordinates }
          Color := GetPixVESA16(x-StartXViewPort,y-StartYViewPort);
          Color := CurrentColor Or Color;
        end;
      AndPut:
        begin
      { getpixel wants local/relative coordinates }
          Color := GetPixVESA16(x-StartXViewPort,y-StartYViewPort);
          Color := CurrentColor And Color;
        end;
      NotPut:
        begin
          Color := Not Color;
        end
      else
        Color := CurrentColor;
    end;
     offs := longint(y) * BytesPerLine + (x div 8);
     SetWriteBank(integer(offs shr 16));
     PortW[$3ce] := $0f01;       { Index 01 : Enable ops on all 4 planes }
     PortW[$3ce] := color shl 8; { Index 00 : Enable correct plane and write color }

     Port[$3ce] := 8;           { Index 08 : Bitmask register.          }
     Port[$3cf] := $80 shr (x and $7); { Select correct bits to modify }

     dummy := Mem[WinWriteSeg: offs];  { Latch the data into host space.  }
     Mem[WinWriteSeg: offs] := dummy;  { Write the data into video memory }
     PortW[$3ce] := $ff08;         { Enable all bit planes.           }
     PortW[$3ce] := $0001;         { Index 01 : Disable ops on all four planes.         }
  end;




 {************************************************************************}
 {*                     VESA Palette entries                             *}
 {************************************************************************}


{$IFDEF DPMI}
{$ifdef fpc}
   Procedure SetVESARGBAllPalette(const Palette:PaletteType);
    var
     pal: array[0..255] of palrec;
     regs: TDPMIRegisters;
     c, Ptr: longint;
     RealSeg: word;
     FunctionNr : byte;   { use blankbit or normal RAMDAC programming? }
    begin
      if DirectColor then
        Begin
          _GraphResult := grError;
          exit;
        end;
      { use the set/get palette function }
      if VESAInfo.Version >= $0200 then
        Begin
          { check if blanking bit must be set when programming }
          { the RAMDAC.                                        }
          if (VESAInfo.caps and attrSnowCheck) <> 0 then
            FunctionNr := $80
          else
            FunctionNr := $00;

          fillChar(pal,sizeof(pal),0);
          { Convert to vesa format }
          for c := 0 to 255 do
            begin
              pal[c].red := byte(palette.colors[c].red);
              pal[c].green := byte(palette.colors[c].green);
              pal[c].blue := byte(palette.colors[c].blue);
            end;

        { Alllocate real mode buffer }
          Ptr:=Global_Dos_Alloc(sizeof(pal));
          {get the segment value}
          RealSeg := word(Ptr shr 16);
          { setup interrupt registers }
          FillChar(regs, sizeof(regs), #0);
          { copy palette values to real mode buffer }
          DosMemPut(RealSeg,0,pal,sizeof(pal));
          regs.eax := $4F09;
          regs.ebx := FunctionNr;
          regs.ecx := 256;
          regs.edx := 0;
          regs.es  := RealSeg;
          regs.edi := 0;         { offset is always zero }
          RealIntr($10, regs);

          { free real mode memory  }
          If not Global_Dos_Free(word(Ptr and $ffff)) then
            RunError(216);

          if word(regs.eax) <> $004F then
            begin
              _GraphResult := grError;
              exit;
            end;
        end
      else
        { assume it's fully VGA compatible palette-wise. }
        Begin
          SetVGARGBAllPalette(palette);
        end;
      setallpalettedefault(palette);
    end;
{$endif fpc}

   Procedure SetVESARGBPalette(ColorNum, RedValue, GreenValue,
      BlueValue : Integer);
    var
     pal: palrec;
     regs: TDPMIRegisters;
     Ptr: longint;
{$ifndef fpc}
     PalPtr : ^PalRec;
{$endif fpc}
     RealSeg: word;
     FunctionNr : byte;   { use blankbit or normal RAMDAC programming? }
    begin
      if DirectColor then
        Begin
{$ifdef logging}
          logln('setvesargbpalette called with directcolor = true');
{$endif logging}
          _GraphResult := grError;
          exit;
        end;
        pal.align := 0;
        pal.red := byte(RedValue) shr 2;
        pal.green := byte(GreenValue) shr 2;
        pal.blue := byte(BlueValue) shr 2;
        { use the set/get palette function }
        if VESAInfo.Version >= $0200 then
          Begin
            { check if blanking bit must be set when programming }
            { the RAMDAC.                                        }
            if (VESAInfo.caps and attrSnowCheck) <> 0 then
              FunctionNr := $80
            else
              FunctionNr := $00;

            { Alllocate real mode buffer }
{$ifndef fpc}
            Ptr:=GlobalDosAlloc(sizeof(palrec));
            { get the selector values }
            PalPtr := pointer(Ptr shl 16);
            if not assigned(PalPtr) then
               RunError(203);
{$else fpc}
            Ptr:=Global_Dos_Alloc(sizeof(palrec));
{$endif fpc}
            {get the segment value}
            RealSeg := word(Ptr shr 16);
            { setup interrupt registers }
            FillChar(regs, sizeof(regs), #0);
            { copy palette values to real mode buffer }
{$ifndef fpc}
            move(pal, palptr^, sizeof(pal));
{$else fpc}
            DosMemPut(RealSeg,0,pal,sizeof(pal));
{$endif fpc}
            regs.eax := $4F09;
            regs.ebx := FunctionNr;
            regs.ecx := $01;
            regs.edx := ColorNum;
            regs.es  := RealSeg;
            regs.edi := 0;         { offset is always zero }
            RealIntr($10, regs);

            { free real mode memory  }
{$ifndef fpc}
            GlobalDosFree(word(Ptr and $ffff));
{$else fpc}
            If not Global_Dos_Free(word(Ptr and $ffff)) then
              RunError(216);
{$endif fpc}

            if word(regs.eax) <> $004F then
              begin
{$ifdef logging}
                logln('setvesargbpalette failed while directcolor = false!');
{$endif logging}
                _GraphResult := grError;
                exit;
              end;
          end
        else
          { assume it's fully VGA compatible palette-wise. }
          Begin
            SetVGARGBPalette(ColorNum, RedValue, GreenValue, BlueValue);
          end;
    end;


  Procedure GetVESARGBPalette(ColorNum: integer; Var
      RedValue, GreenValue, BlueValue : integer);
   var
    pal: PalRec;
{$ifndef fpc}
    palptr : ^PalRec;
{$endif fpc}
    regs : TDPMIRegisters;
    RealSeg: word;
    ptr: longint;
   begin
      if DirectColor then
        Begin
{$ifdef logging}
         logln('getvesargbpalette called with directcolor = true');
{$endif logging}
          _GraphResult := grError;
          exit;
        end;
        { use the set/get palette function }
        if VESAInfo.Version >= $0200 then
          Begin
            { Alllocate real mode buffer }
{$ifndef fpc}
            Ptr:=GlobalDosAlloc(sizeof(palrec));
            { get the selector value }
            PalPtr := pointer(longint(Ptr and $0000ffff) shl 16);
            if not assigned(PalPtr) then
               RunError(203);
{$else fpc}
            Ptr:=Global_Dos_Alloc(sizeof(palrec));
{$endif fpc}
            { get the segment value }
            RealSeg := word(Ptr shr 16);
            { setup interrupt registers }
            FillChar(regs, sizeof(regs), #0);

            regs.eax := $4F09;
            regs.ebx := $01;       { get palette data      }
            regs.ecx := $01;
            regs.edx := ColorNum;
            regs.es  := RealSeg;
            regs.edi := 0;         { offset is always zero }
            RealIntr($10, regs);

           { copy to protected mode buffer ... }
{$ifndef fpc}
           Move(PalPtr^, Pal, sizeof(pal));
{$else fpc}
           DosMemGet(RealSeg,0,Pal,sizeof(pal));
{$endif fpc}
           { free real mode memory  }
{$ifndef fpc}
           GlobalDosFree(word(Ptr and $ffff));
{$else fpc}
           If not Global_Dos_Free(word(Ptr and $ffff)) then
             RunError(216);
{$endif fpc}

            if word(regs.eax) <> $004F then
              begin
{$ifdef logging}
                logln('getvesargbpalette failed while directcolor = false!');
{$endif logging}
                _GraphResult := grError;
                exit;
              end
            else
              begin
                RedValue := Integer(pal.Red);
                GreenValue := Integer(pal.Green);
                BlueValue := Integer(pal.Blue);
              end;
          end
        else
            GetVGARGBPalette(ColorNum, RedValue, GreenValue, BlueValue);
   end;
{$ELSE}

   Procedure SetVESARGBPalette(ColorNum, RedValue, GreenValue,
      BlueValue : Integer); far;
    var
     FunctionNr : byte;   { use blankbit or normal RAMDAC programming? }
     pal: ^palrec;
     Error : boolean;     { VBE call error                             }
    begin
      if DirectColor then
        Begin
          _GraphResult := grError;
          exit;
        end;
        Error := FALSE;
        new(pal);
        if not assigned(pal) then RunError(203);
        pal^.align := 0;
        pal^.red := byte(RedValue);
        pal^.green := byte(GreenValue);
        pal^.blue := byte(BlueValue);
        { use the set/get palette function }
        if VESAInfo.Version >= $0200 then
          Begin
            { check if blanking bit must be set when programming }
            { the RAMDAC.                                        }
            if (VESAInfo.caps and attrSnowCheck) <> 0 then
              FunctionNr := $80
            else
              FunctionNr := $00;
            asm
              mov  ax, 4F09h         { Set/Get Palette data    }
              mov  bl, [FunctionNr]  { Set palette data        }
              mov  cx, 01h           { update one palette reg. }
              mov  dx, [ColorNum]    { register number to update }
              les  di, [pal]         { get palette address     }
              int  10h
              cmp  ax, 004Fh         { check if success        }
              jz   @noerror
              mov  [Error], TRUE
             @noerror:
            end;
            if not Error then
                Dispose(pal)
            else
              begin
                _GraphResult := grError;
                exit;
              end;
          end
        else
          { assume it's fully VGA compatible palette-wise. }
          Begin
            SetVGARGBPalette(ColorNum, RedValue, GreenValue, BlueValue);
          end;
    end;




  Procedure GetVESARGBPalette(ColorNum: integer; Var RedValue, GreenValue,
              BlueValue : integer); far;
   var
    Error: boolean;
    pal: ^palrec;
   begin
      if DirectColor then
        Begin
          _GraphResult := grError;
          exit;
        end;
      Error := FALSE;
      new(pal);
      if not assigned(pal) then RunError(203);
      FillChar(pal^, sizeof(palrec), #0);
      { use the set/get palette function }
      if VESAInfo.Version >= $0200 then
        Begin
          asm
            mov  ax, 4F09h         { Set/Get Palette data    }
            mov  bl, 01h           { Set palette data        }
            mov  cx, 01h           { update one palette reg. }
            mov  dx, [ColorNum]    { register number to update }
            les  di, [pal]         { get palette address     }
            int  10h
            cmp  ax, 004Fh         { check if success        }
            jz   @noerror
            mov  [Error], TRUE
          @noerror:
          end;
          if not Error then
            begin
              RedValue := Integer(pal^.Red);
              GreenValue := Integer(pal^.Green);
              BlueValue := Integer(pal^.Blue);
              Dispose(pal);
            end
          else
            begin
              _GraphResult := grError;
              exit;
            end;
        end
        else
            GetVGARGBPalette(ColorNum, RedValue, GreenValue, BlueValue);

   end;
{$ENDIF}


(*
type
  heaperrorproc=function(size:longint):integer;

Const
  HeapErrorIsHooked : boolean = false;
  OldHeapError : HeapErrorProc = nil;
  DsLimit : dword = 0;

  function NewHeapError(size : longint) : integer;
    begin
      set_segment_limit(get_ds,DsLimit);
      NewHeapError:=OldHeapError(size);
      DsLimit:=get_segment_limit(get_ds);
      { The base of ds can be changed
        we need to compute the address again PM }
      LFBPointer:=pointer(FrameBufferLinearAddress-get_segment_base_address(get_ds));
      if dword(LFBPointer)+dword(VESAInfo.TotalMem shl 16)-1 > DsLimit then
        set_segment_limit(get_ds,dword(LFBPointer)+dword(VESAInfo.TotalMem shl 16)-1);
    end;

  procedure HookHeapError;
    begin
      if HeapErrorIsHooked then
        exit;
      DsLimit:=get_segment_limit(get_ds);
      OldHeapError:=HeapErrorProc(HeapError);
      HeapError:=@NewHeapError;
      HeapErrorIsHooked:=true;
    end;

  procedure UnHookHeapError;
    begin
      if not HeapErrorIsHooked then
        exit;
      LFBPointer:=nil;
      set_segment_limit(get_ds,DsLimit);
      HeapError:=OldHeapError;
      HeapErrorIsHooked:=false;
    end;
*)

  function SetupLinear(var ModeInfo: TVESAModeInfo;mode : word) : boolean;
   begin
     SetUpLinear:=false;
{$ifdef FPC}
     case mode of
       m320x200x32k,
       m320x200x64k,
       m640x480x32k,
       m640x480x64k,
       m800x600x32k,
       m800x600x64k,
       m1024x768x32k,
       m1024x768x64k,
       m1280x1024x32k,
       m1280x1024x64k :
         begin
           DirectPutPixel:=@DirectPutPixVESA32kor64kLinear;
           PutPixel:=@PutPixVESA32kor64kLinear;
           GetPixel:=@GetPixVESA32kor64kLinear;
           { linear mode for lines not yet implemented PM }
           HLine:=@HLineDefault;
           VLine:=@VLineDefault;
           GetScanLine := @GetScanLineDefault;
           PatternLine := @PatternLineDefault;
         end;
       m640x400x256,
       m640x480x256,
       m800x600x256,
       m1024x768x256,
       m1280x1024x256:
         begin
           DirectPutPixel:=@DirectPutPixVESA256Linear;
           PutPixel:=@PutPixVESA256Linear;
           GetPixel:=@GetPixVESA256Linear;
           { linear mode for lines not yet implemented PM }
           HLine:=@HLineDefault;
           VLine:=@VLineDefault;
           GetScanLine := @GetScanLineDefault;
           PatternLine := @PatternLineDefault;
         end;
     else
       exit;
     end;
     FrameBufferLinearAddress:=Get_linear_addr(VESAModeInfo.PhysAddress and $FFFF0000,
       VESAInfo.TotalMem shl 16);
{$ifdef logging}
     logln('framebuffer linear address: '+hexstr(FrameBufferLinearAddress div (1024*1024),8));
     logln('total mem shl 16: '+strf(vesainfo.totalmem shl 16));
{$endif logging}
     if int31error<>0 then
       begin
{$ifdef logging}
         logln('Unable to get linear address for '+hexstr(VESAModeInfo.PhysAddress,8));
{$endif logging}
         writeln(stderr,'Unable to get linear address for ',hexstr(VESAModeInfo.PhysAddress,8));
         exit;
       end;
     if UseNoSelector then
       begin
{         HookHeapError; }
         LFBPointer:=pointer(FrameBufferLinearAddress-get_segment_base_address(get_ds));
         if dword(LFBPointer)+dword(VESAInfo.TotalMem shl 16)-1 > dword(get_segment_limit(get_ds)) then
           set_segment_limit(get_ds,dword(LFBPointer)+dword(VESAInfo.TotalMem shl 16)-1);
       end
     else
       begin
         WinWriteSeg:=allocate_ldt_descriptors(1);
{$ifdef logging}
         logln('writeseg1: '+hexstr(winwriteseg,8));
{$endif logging}
         set_segment_base_address(WinWriteSeg,FrameBufferLinearAddress);
         set_segment_limit(WinWriteSeg,(VESAInfo.TotalMem shl 16)-1);
         lock_linear_region(FrameBufferLinearAddress,(VESAInfo.TotalMem shl 16));
         if int31error<>0 then
           begin
{$ifdef logging}
             logln('Error in linear memory selectors creation');
{$endif logging}
             writeln(stderr,'Error in linear memory selectors creation');
             exit;
           end;
       end;
     LinearPageOfs := 0;
     InLinear:=true;
     SetUpLinear:=true;
     { WinSize:=(VGAInfo.TotalMem shl 16);
     WinLoMask:=(VGAInfo.TotalMem shl 16)-1;
     WinShift:=15;
     Temp:=VGAInfo.TotalMem;
     while Temp>0 do
       begin
         inc(WinShift);
         Temp:=Temp shr 1;
       end; }
{$endif FPC}
   end;

  procedure SetupWindows(var ModeInfo: TVESAModeInfo);
   begin
     InLinear:=false;
     { now we check the windowing scheme ...}
     if (ModeInfo.WinAAttr and WinSupported) <> 0 then
       { is this window supported ... }
       begin
         { now check if the window is R/W }
         if (ModeInfo.WinAAttr and WinReadable) <> 0 then
         begin
           ReadWindow := 0;
           WinReadSeg := ModeInfo.WinASeg;
         end;
         if (ModeInfo.WinAAttr and WinWritable) <> 0 then
         begin
           WriteWindow := 0;
           WinWriteSeg := ModeInfo.WinASeg;
         end;
       end;
     if (ModeInfo.WinBAttr and WinSupported) <> 0 then
       { is this window supported ... }
       begin

         { OPTIMIZATION ... }
         { if window A supports both read/write, then we try to optimize }
         { everything, by using a different window for Read and/or write.}
         if (WinReadSeg <> 0) and (WinWriteSeg <> 0) then
           begin
              { check if winB supports read }
              if (ModeInfo.WinBAttr and winReadable) <> 0 then
                begin
                  WinReadSeg := ModeInfo.WinBSeg;
                  ReadWindow := 1;
                end
              else
              { check if WinB supports write }
              if (ModeInfo.WinBAttr and WinWritable) <> 0 then
                begin
                  WinWriteSeg := ModeInfo.WinBSeg;
                  WriteWindow := 1;
                end;
           end
         else
         { Window A only supported Read OR Write, no we have to make }
         { sure that window B supports the other mode.               }
         if (WinReadSeg = 0) and (WinWriteSeg<>0) then
           begin
              if (ModeInfo.WinBAttr and WinReadable <> 0) then
                begin
                  ReadWindow := 1;
                  WinReadSeg := ModeInfo.WinBSeg;
                end
              else
                { impossible, this VESA mode is WRITE only! }
                begin
                  WriteLn('Invalid VESA Window attribute.');
                  Halt(255);
                end;
           end
         else
         if (winWriteSeg = 0) and (WinReadSeg<>0) then
           begin
             if (ModeInfo.WinBAttr and WinWritable) <> 0 then
               begin
                 WriteWindow := 1;
                 WinWriteSeg := ModeInfo.WinBSeg;
               end
             else
               { impossible, this VESA mode is READ only! }
               begin
                  WriteLn('Invalid VESA Window attribute.');
                  Halt(255);
               end;
           end
         else
         if (winReadSeg = 0) and (winWriteSeg = 0) then
         { no read/write in this mode! }
           begin
                  WriteLn('Invalid VESA Window attribute.');
                  Halt(255);
           end;
         YOffset := 0;
       end;

     { if both windows are not supported, then we can assume }
     { that there is ONE single NON relocatable window.      }
     if (WinWriteSeg = 0) and (WinReadSeg = 0) then
       begin
         WinWriteSeg := ModeInfo.WinASeg;
         WinReadSeg := ModeInfo.WinASeg;
       end;

    { 16-bit Protected mode checking code...  }
    { change segment values to protected mode }
    { selectors.                              }
    if WinReadSeg = $A000 then
      WinReadSeg := SegA000
    else
    if WinReadSeg = $B000 then
      WinReadSeg := SegB000
    else
    if WinReadSeg = $B800 then
      WinReadSeg := SegB800
    else
      begin
        WriteLn('Invalid segment address.');
        Halt(255);
      end;
    if WinWriteSeg = $A000 then
      WinWriteSeg := SegA000
    else
    if WinWriteSeg = $B000 then
      WinWriteSeg := SegB000
    else
    if WinWriteSeg = $B800 then
      WinWriteSeg := SegB800
    else
      begin
        WriteLn('Invalid segment address.');
        Halt(255);
      end;

   end;



  function setVESAMode(mode:word):boolean;
    var i:word;
        res: boolean;
  begin
   { Init mode information, for compatibility with VBE < 1.1 }
   FillChar(VESAModeInfo, sizeof(TVESAModeInfo), #0);
   { get the video mode information }
   if getVESAModeInfo(VESAmodeinfo, mode) then
   begin
     { checks if the hardware supports the video mode. }
     if (VESAModeInfo.attr and modeAvail) = 0 then
       begin
         SetVESAmode := FALSE;
{$ifdef logging}
         logln('  vesa mode '+strf(mode)+' not supported!!!');
{$endif logging}
         _GraphResult := grError;
         exit;
       end;

     SetVESAMode := TRUE;
     BankShift := 0;
     while (64 shr BankShift) <> VESAModeInfo.WinGranularity do
        Inc(BankShift);
     CurrentWriteBank := -1;
     CurrentReadBank := -1;
     BytesPerLine := VESAModeInfo.BytesPerScanLine;

     { These are the window adresses ... }
     WinWriteSeg := 0;  { This is the segment to use for writes }
     WinReadSeg := 0;   { This is the segment to use for reads  }
     ReadWindow := 0;
     WriteWindow := 0;

     { VBE 2.0 and higher supports >= non VGA linear buffer types...}
     { this is backward compatible.                                 }
     if (((VESAModeInfo.Attr and ModeNoWindowed) <> 0) or UseLFB) and
          ((VESAModeInfo.Attr and ModeLinearBuffer) <> 0) then
        begin
          if not SetupLinear(VESAModeInfo,mode) then
            SetUpWindows(VESAModeInfo);
        end
     else
     { if linear and windowed is supported, then use windowed }
     { method.                                                }
        SetUpWindows(VESAModeInfo);

{$ifdef logging}
  LogLn('Entering vesa mode '+strf(mode));
  LogLn('Read segment: $'+hexstr(winreadseg,4));
  LogLn('Write segment: $'+hexstr(winwriteseg,4));
  LogLn('Window granularity: '+strf(VESAModeInfo.WinGranularity)+'kb');
  LogLn('Window size: '+strf(VESAModeInfo.winSize)+'kb');
  LogLn('Bytes per line: '+strf(bytesperline));
{$endif logging}
   { Select the correct mode number if we're going to use linear access! }
   if InLinear then
     inc(mode,$4000);

   asm
    mov ax,4F02h
    mov bx,mode
{$ifdef fpc}
    push ebp
{$endif fpc}
    int 10h
{$ifdef fpc}
    pop ebp
{$endif fpc}
    sub ax,004Fh
    cmp ax,1
    sbb al,al
    mov res,al
   end;
   if not res then
     _GraphResult := GrNotDetected
   else _GraphResult := grOk;
  end;
 end;

(*
 function getVESAMode:word;assembler;
   asm  {return -1 if error}
    mov ax,4F03h
{$ifdef fpc}
    push ebp
{$endif fpc}
    int 10h
{$ifdef fpc}
    pop ebp
{$endif fpc}
    cmp ax,004Fh
    je @@OK
    mov ax,-1
    jmp @@X
  @@OK:
    mov ax,bx
  @@X:
   end;
*)



 {************************************************************************}
 {*                     VESA Modes inits                                 *}
 {************************************************************************}

{$IFDEF DPMI}

  {******************************************************** }
  { Function GetMaxScanLines()                              }
  {-------------------------------------------------------- }
  { This routine returns the maximum number of scan lines   }
  { possible for this mode. This is done using the Get      }
  { Scan Line length VBE function.                          }
  {******************************************************** }
  function GetMaxScanLines: word;
   var
    regs : TDPMIRegisters;
   begin
     FillChar(regs, sizeof(regs), #0);
     { play it safe, call the real mode int, the 32-bit entry point }
     { may not be defined as stated in VBE v3.0                     }
     regs.eax := $4f06; {_ setup function      }
     regs.ebx := $0001; { get scan line length }
     RealIntr($10, regs);
     GetMaxScanLines := (regs.edx and $0000ffff);
   end;

{$ELSE}

  function GetMaxScanLines: word; assembler;
     asm
      mov ax, 4f06h
      mov bx, 0001h
      int 10h
      mov ax, dx
   end;

{$ENDIF}

 procedure Init1280x1024x64k; {$ifndef fpc}far;{$endif fpc}
  begin
    SetVesaMode(m1280x1024x64k);
    { Get maximum number of scanlines for page flipping }
    ScanLines := GetMaxScanLines;
  end;

 procedure Init1280x1024x32k; {$ifndef fpc}far;{$endif fpc}
  begin
    SetVESAMode(m1280x1024x32k);
    { Get maximum number of scanlines for page flipping }
    ScanLines := GetMaxScanLines;
  end;

 procedure Init1280x1024x256; {$ifndef fpc}far;{$endif fpc}
  begin
    SetVESAMode(m1280x1024x256);
    { Get maximum number of scanlines for page flipping }
    ScanLines := GetMaxScanLines;
  end;


 procedure Init1280x1024x16; {$ifndef fpc}far;{$endif fpc}
  begin
    SetVESAMode(m1280x1024x16);
    { Get maximum number of scanlines for page flipping }
    ScanLines := GetMaxScanLines;
  end;

 procedure Init1024x768x64k; {$ifndef fpc}far;{$endif fpc}
  begin
    SetVESAMode(m1024x768x64k);
    { Get maximum number of scanlines for page flipping }
    ScanLines := GetMaxScanLines;
  end;

 procedure Init640x480x32k; {$ifndef fpc}far;{$endif fpc}
  begin
    SetVESAMode(m640x480x32k);
    { Get maximum number of scanlines for page flipping }
    ScanLines := GetMaxScanLines;
  end;

 procedure Init1024x768x256; {$ifndef fpc}far;{$endif fpc}
  begin
    SetVESAMode(m1024x768x256);
    { Get maximum number of scanlines for page flipping }
    ScanLines := GetMaxScanLines;
  end;

 procedure Init1024x768x16; {$ifndef fpc}far;{$endif fpc}
  begin
    SetVESAMode(m1024x768x16);
    { Get maximum number of scanlines for page flipping }
    ScanLines := GetMaxScanLines;
  end;

 procedure Init800x600x64k; {$ifndef fpc}far;{$endif fpc}
  begin
    SetVESAMode(m800x600x64k);
    { Get maximum number of scanlines for page flipping }
    ScanLines := GetMaxScanLines;
  end;

 procedure Init800x600x32k; {$ifndef fpc}far;{$endif fpc}
  begin
    SetVESAMode(m800x600x32k);
    { Get maximum number of scanlines for page flipping }
    ScanLines := GetMaxScanLines;
  end;

 procedure Init800x600x256; {$ifndef fpc}far;{$endif fpc}
  begin
    SetVESAMode(m800x600x256);
    { Get maximum number of scanlines for page flipping }
    ScanLines := GetMaxScanLines;
  end;

 procedure Init800x600x16; {$ifndef fpc}far;{$endif fpc}
  begin
    SetVesaMode(m800x600x16);
    { Get maximum number of scanlines for page flipping }
    ScanLines := GetMaxScanLines;
  end;

 procedure Init640x480x64k; {$ifndef fpc}far;{$endif fpc}
  begin
    SetVESAMode(m640x480x64k);
    { Get maximum number of scanlines for page flipping }
    ScanLines := GetMaxScanLines;
  end;


 procedure Init640x480x256; {$ifndef fpc}far;{$endif fpc}
  begin
    SetVESAMode(m640x480x256);
    { Get maximum number of scanlines for page flipping }
    ScanLines := GetMaxScanLines;
  end;

 procedure Init640x400x256; {$ifndef fpc}far;{$endif fpc}
  begin
    SetVESAMode(m640x400x256);
    { Get maximum number of scanlines for page flipping }
    ScanLines := GetMaxScanLines;
  end;

 procedure Init320x200x64k; {$ifndef fpc}far;{$endif fpc}
  begin
    SetVESAMode(m320x200x64k);
    { Get maximum number of scanlines for page flipping }
    ScanLines := GetMaxScanLines;
  end;

 procedure Init320x200x32k; {$ifndef fpc}far;{$endif fpc}
  begin
    SetVESAMode(m320x200x32k);
    { Get maximum number of scanlines for page flipping }
    ScanLines := GetMaxScanLines;
  end;


{$IFDEF DPMI}

 Procedure SaveStateVESA; {$ifndef fpc}far;{$endif fpc}
 var
  PtrLong: longint;
  regs: TDPMIRegisters;
  begin
    SaveSupported := FALSE;
    SavePtr := nil;
{$ifdef logging}
        LogLn('Get the video mode...');
{$endif logging}
    { Get the video mode }
    asm
      mov  ah,0fh
{$ifdef fpc}
      push ebp
{$endif fpc}
      int  10h
{$ifdef fpc}
      pop ebp
{$endif fpc}
      mov  [VideoMode], al
    end;
    { saving/restoring video state screws up Windows (JM) }
    if inWindows then
      exit;
{$ifdef logging}
        LogLn('Prepare to save VESA video state');
{$endif logging}
    { Prepare to save video state...}
    asm
      mov  ax, 4F04h       { get buffer size to save state }
      mov  dx, 00h
      mov  cx, 00001111b   { Save DAC / Data areas / Hardware states }
{$ifdef fpc}
      push ebp
{$endif fpc}
      int  10h
{$ifdef fpc}
      pop ebp
{$endif fpc}
      mov  [StateSize], bx
      cmp  al,04fh
      jnz  @notok
      mov  [SaveSupported],TRUE
     @notok:
    end;
    regs.eax := $4f04;
    regs.edx := $0000;
    regs.ecx := $000F;
    RealIntr($10, regs);
    StateSize := word(regs.ebx);
    if byte(regs.eax) = $4f then
      SaveSupported := TRUE;
    if SaveSupported then
      begin
{$ifdef logging}
        LogLn('allocating VESA save buffer of '+strf(64*StateSize));
{$endif logging}
{$ifndef fpc}
        PtrLong:=GlobalDosAlloc(64*StateSize);  { values returned in 64-byte blocks }
{$else fpc}
        PtrLong:=Global_Dos_Alloc(64*StateSize);  { values returned in 64-byte blocks }
{$endif fpc}
        if PtrLong = 0 then
           RunError(203);
        SavePtr := pointer(longint(PtrLong and $0000ffff) shl 16);
{$ifndef fpc}
        { In FPC mode, we can't do anything with this (no far pointers)  }
        { However, we still need to keep it to be able to free the       }
        { memory afterwards. Since this data is not accessed in PM code, }
        { there's no need to save it in a seperate buffer (JM)           }
        if not assigned(SavePtr) then
           RunError(203);
{$endif fpc}
        RealStateSeg := word(PtrLong shr 16);

        FillChar(regs, sizeof(regs), #0);
        { call the real mode interrupt ... }
        regs.eax := $4F04;      { save the state buffer                   }
        regs.ecx := $0F;        { Save DAC / Data areas / Hardware states }
        regs.edx := $01;        { save state                              }
        regs.es := RealStateSeg;
        regs.ebx := 0;
        RealIntr($10,regs);
        FillChar(regs, sizeof(regs), #0);
        { restore state, according to Ralph Brown Interrupt list }
        { some BIOS corrupt the hardware after a save...         }
        regs.eax := $4F04;      { restore the state buffer                }
        regs.ecx := $0F;        { rest DAC / Data areas / Hardware states }
        regs.edx := $02;
        regs.es := RealStateSeg;
        regs.ebx := 0;
        RealIntr($10,regs);
      end;
  end;

 procedure RestoreStateVESA; {$ifndef fpc}far;{$endif fpc}
  var
   regs:TDPMIRegisters;
  begin
     { go back to the old video mode...}
     asm
      mov  ah,00
      mov  al,[VideoMode]
{$ifdef fpc}
      push ebp
{$endif fpc}
      int  10h
{$ifdef fpc}
      pop ebp
{$endif fpc}
     end;
     { then restore all state information }
{$ifndef fpc}
     if assigned(SavePtr) and (SaveSupported=TRUE) then
{$else fpc}
     { No far pointer support, so it's possible that that assigned(SavePtr) }
     { would return false under FPC. Just check if it's different from nil. }
     if (SavePtr <> nil) and (SaveSupported=TRUE) then
{$endif fpc}
       begin
        FillChar(regs, sizeof(regs), #0);
        { restore state, according to Ralph Brown Interrupt list }
        { some BIOS corrupt the hardware after a save...         }
         regs.eax := $4F04;      { restore the state buffer                }
         regs.ecx := $0F;        { rest DAC / Data areas / Hardware states }
         regs.edx := $02;        { restore state                           }
         regs.es := RealStateSeg;
         regs.ebx := 0;
         RealIntr($10,regs);
{$ifndef fpc}
         if GlobalDosFree(longint(SavePtr) shr 16)<>0 then
{$else fpc}
         if Not(Global_Dos_Free(longint(SavePtr) shr 16)) then
{$endif fpc}
          RunError(216);
         SavePtr := nil;
       end;
  end;

{$ELSE}

      {**************************************************************}
      {*                     Real mode routines                     *}
      {**************************************************************}

 Procedure SaveStateVESA; far;
  begin
    SavePtr := nil;
    SaveSupported := FALSE;
    { Get the video mode }
    asm
      mov  ah,0fh
      int  10h
      mov  [VideoMode], al
    end;
    { Prepare to save video state...}
    asm
      mov  ax, 4f04h       { get buffer size to save state }
      mov  cx, 00001111b   { Save DAC / Data areas / Hardware states }
      mov  dx, 00h
      int  10h
      mov  [StateSize], bx
      cmp  al,04fh
      jnz  @notok
      mov  [SaveSupported],TRUE
     @notok:
    end;
    if SaveSupported then
      Begin
        GetMem(SavePtr, 64*StateSize); { values returned in 64-byte blocks }
        if not assigned(SavePtr) then
           RunError(203);
        asm
         mov  ax, 4F04h       { save the state buffer                   }
         mov  cx, 00001111b   { Save DAC / Data areas / Hardware states }
         mov  dx, 01h
         mov  es, WORD PTR [SavePtr+2]
         mov  bx, WORD PTR [SavePtr]
         int  10h
        end;
        { restore state, according to Ralph Brown Interrupt list }
        { some BIOS corrupt the hardware after a save...         }
        asm
         mov  ax, 4F04h       { save the state buffer                   }
         mov  cx, 00001111b   { Save DAC / Data areas / Hardware states }
         mov  dx, 02h
         mov  es, WORD PTR [SavePtr+2]
         mov  bx, WORD PTR [SavePtr]
         int  10h
        end;
      end;
  end;

 procedure RestoreStateVESA; far;
  begin
     { go back to the old video mode...}
     asm
      mov  ah,00
      mov  al,[VideoMode]
      int  10h
     end;

     { then restore all state information }
     if assigned(SavePtr) and (SaveSupported=TRUE) then
       begin
         { restore state, according to Ralph Brown Interrupt list }
         asm
           mov  ax, 4F04h       { save the state buffer                   }
           mov  cx, 00001111b   { Save DAC / Data areas / Hardware states }
           mov  dx, 02h         { restore state                           }
           mov  es, WORD PTR [SavePtr+2]
           mov  bx, WORD PTR [SavePtr]
           int  10h
         end;
         FreeMem(SavePtr, 64*StateSize);
         SavePtr := nil;
       end;
  end;
{$ENDIF DPMI}

 {************************************************************************}
 {*                     VESA Page flipping routines                      *}
 {************************************************************************}
 { Note: These routines, according  to the VBE3 specification, will NOT   }
 { work with the 24 bpp modes, because of the alignment.                  }
 {************************************************************************}

  {******************************************************** }
  { Procedure SetVisualVESA()                               }
  {-------------------------------------------------------- }
  { This routine changes the page which will be displayed   }
  { on the screen, since the method has changed somewhat    }
  { between VBE versions , we will use the old method where }
  { the new pixel offset is used to display different pages }
  {******************************************************** }
 procedure SetVisualVESA(page: word); {$ifndef fpc}far;{$endif fpc}
  var
   newStartVisible : word;
  begin
    if page > HardwarePages then
      begin
        _graphresult := grError;
        exit;
      end;
    newStartVisible := (MaxY+1)*page;
    if newStartVisible > ScanLines then
      begin
        _graphresult := grError;
        exit;
      end;
    asm
      mov ax, 4f07h
      mov bx, 0000h   { set display start }
      mov cx, 0000h   { pixel zero !      }
      mov dx, [NewStartVisible]  { new scanline }
{$ifdef fpc}
      push    ebp
{$endif}
      int     10h
{$ifdef fpc}
      pop     ebp
{$endif}
    end;
  end;

 procedure SetActiveVESA(page: word); {$ifndef fpc}far;{$endif fpc}
  begin
    { video offset is in pixels under VESA VBE! }
    { This value is reset after a mode set to page ZERO = YOffset = 0 ) }
    if page > HardwarePages then
      begin
        _graphresult := grError;
        exit;
      end;
    YOffset := (MaxY+1)*page;
    LinearPageOfs := YOffset*(MaxX+1);
  end;

{
  $Log: vesa.inc,v $
  Revision 1.12  2005/02/14 17:13:22  peter
    * truncate log

  Revision 1.11  2005/02/02 11:57:19  jonas
    * fix from Tomas for calling conventions

}