summaryrefslogtreecommitdiff
path: root/packages/ptc/src/win32/directx/win32directxconsolei.inc
blob: 3aec43e58ad480d698cd7b1c1d24f33b65a0289b (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
{
    Free Pascal port of the OpenPTC C++ library.
    Copyright (C) 2001-2003, 2006, 2007, 2009-2013, 2016  Nikolay Nikolov (nickysn@users.sourceforge.net)
    Original C++ version by Glenn Fiedler (ptc@gaffer.org)

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version
    with the following modification:

    As a special exception, the copyright holders of this library give you
    permission to link this library with independent modules to produce an
    executable, regardless of the license terms of these independent modules,and
    to copy and distribute the resulting executable under terms of your choice,
    provided that you also meet, for each linked independent module, the terms
    and conditions of the license of that module. An independent module is a
    module which is not derived from or based on this library. If you modify
    this library, you may extend this exception to your version of the library,
    but you are not obligated to do so. If you do not wish to do so, delete this
    exception statement from your version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
}

{$MACRO ON}

{$DEFINE DEFAULT_WIDTH:=320}
{$DEFINE DEFAULT_HEIGHT:=200}
{$DEFINE DEFAULT_FORMAT:=TPTCFormat.Create(32, $00FF0000, $0000FF00, $000000FF)}
{$IFDEF DEBUG}
{$DEFINE DEFAULT_OUTPUT:=WINDOWED}
{$ELSE}
{$DEFINE DEFAULT_OUTPUT:=DEFAULT}
{$ENDIF}
{$IFNDEF DEBUG}
{$DEFINE CHECK_OPEN:=//}
{$DEFINE CHECK_LOCK:=//}
{$ENDIF}

function PChar2String(Q: PChar): string;
var
  I: Integer;
  S: string;
begin
  S := '';
  I := 0;
  while Q[I] <> #0 do
  begin
    S := S + Q[I];
    Inc(I);
  end;
  PChar2String := S;
end;

constructor TDirectXConsole.Create;
begin
  inherited Create;

  FCopy := TPTCCopy.Create;
  FWin32Cursor := TWin32Cursor.Create;
  FLibrary := TDirectXLibrary.Create;
  FDisplay := TDirectXDisplay.Create;
  FPrimary := TDirectXPrimary.Create;

  { defaults }
  FOpen := False;
  FLocked := False;
  FCursor := True;
  FGrabMouse := False;

  { clear strings }
  FTitle := '';

  { default option data }
  FFrequency := 0;
  FDefaultWidth := DEFAULT_WIDTH;
  FDefaultHeight := DEFAULT_HEIGHT;
  FDefaultFormat := DEFAULT_FORMAT;
  FCenterWindow := False;
  FSynchronizedUpdate := True;
  FOutputMode := DEFAULT_OUTPUT;
  FWindowMode := RESIZABLE;
  FPrimaryModeWindowed := SECONDARY;
  FPrimaryModeFullscreen := DIRECT;
  FNearestMode := NEAREST_DEFAULT;
  FCursorMode := CURSOR_DEFAULT;

  { configure console }
  Configure('ptcpas.cfg');

  { setup display object }
  FDisplay.Setup(FLibrary.lpDD2);
end;

destructor TDirectXConsole.Destroy;
begin
  { close }
  Close;

  FHook.Free;
  FResize.Free;
  FMouse.Free;
  FKeyboard.Free;
  FWindow.Free;

  FPrimary.Free;
  FDisplay.Free;
  FLibrary.Free;
  FEventQueue.Free;
  FWin32Cursor.Free;
  FCopy.Free;
  inherited Destroy;
end;

procedure TDirectXConsole.Configure(const AFileName: String);
var
  F: TextFile;
  S: string;
begin
  AssignFile(F, AFileName);
  {$push}{$I-}
  Reset(F);
  {$pop}
  if IOResult <> 0 then
    exit;
  while not EoF(F) do
  begin
    {$push}{$I-}
    Readln(F, S);
    {$pop}
    if IOResult <> 0 then
      Break;
    Option(S);
  end;
  CloseFile(F);
end;

function TDirectXConsole.Option(const AOption: String): Boolean;
var
  tmp, tmp2: Integer;
begin
  LOG('console option', AOption);
  Result := True;
  if AOption = 'default output' then
  begin
    FOutputMode := DEFAULT;
    exit;
  end;
  if AOption = 'windowed output' then
  begin
    FOutputMode := WINDOWED;
    exit;
  end;
  if AOption = 'fullscreen output' then
  begin
    FOutputMode := FULLSCREEN;
    exit;
  end;
  if System.Copy(AOption, 1, 13) = 'default width' then
  begin
    if Length(AOption) > 13 then
    begin
      Val(System.Copy(AOption, 14, Length(AOption)-13), FDefaultWidth, tmp);
      if FDefaultWidth = 0 then
        FDefaultWidth := DEFAULT_WIDTH;
    end
    else
    begin
      FDefaultWidth := DEFAULT_WIDTH;
    end;
  end;
  if System.Copy(AOption, 1, 14) = 'default height' then
  begin
    if Length(AOption) > 14 then
    begin
      Val(System.Copy(AOption, 15, Length(AOption)-14), FDefaultHeight, tmp);
      if FDefaultHeight = 0 then
        FDefaultHeight := DEFAULT_HEIGHT;
    end
    else
    begin
      FDefaultHeight := DEFAULT_HEIGHT;
    end;
  end;
  if System.Copy(AOption, 1, 12) = 'default bits' then
  begin
    if Length(AOption) > 12 then
    begin
      Val(System.Copy(AOption, 13, Length(AOption)-12), tmp, tmp2);
      case tmp of
        8: FDefaultFormat := TPTCFormat.Create(8);
        16: FDefaultFormat := TPTCFormat.Create(16, $F800, $07E0, $001F);
        24: FDefaultFormat := TPTCFormat.Create(24, $00FF0000, $0000FF00, $000000FF);
        32: FDefaultFormat := TPTCFormat.Create(32, $00FF0000, $0000FF00, $000000FF);
        else
          exit(False);
      end;
    end
    else
    begin
      FDefaultFormat := DEFAULT_FORMAT;
    end;
  end;
  if AOption = 'resizable window' then
  begin
    FWindowMode := RESIZABLE;
    exit;
  end;
  if AOption = 'fixed window' then
  begin
    FWindowMode := FIXED;
    exit;
  end;
  if AOption = 'windowed primary direct' then
  begin
    FPrimaryModeWindowed := DIRECT;
    exit;
  end;
  if AOption = 'windowed primary secondary' then
  begin
    FPrimaryModeWindowed := SECONDARY;
    exit;
  end;
  if AOption = 'fullscreen primary direct' then
  begin
    FPrimaryModeFullscreen := DIRECT;
    exit;
  end;
  if AOption = 'fullscreen primary secondary' then
  begin
    FPrimaryModeFullscreen := SECONDARY;
    exit;
  end;
  if AOption = 'center window' then
  begin
    FCenterWindow := True;
    exit;
  end;
  if AOption = 'default window position' then
  begin
    FCenterWindow := False;
    exit;
  end;
  if AOption = 'synchronized update' then
  begin
    FSynchronizedUpdate := True;
    exit;
  end;
  if AOption = 'unsynchronized update' then
  begin
    FSynchronizedUpdate := False;
    exit;
  end;
  if AOption = 'default nearest' then
  begin
    FNearestMode := NEAREST_DEFAULT;
    exit;
  end;
  if AOption = 'center nearest' then
  begin
    FNearestMode := NEAREST_CENTERING;
    exit;
  end;
  if AOption = 'default stretch' then
  begin
    FNearestMode := NEAREST_STRETCHING;
    exit;
  end;
  if AOption = 'default cursor' then
  begin
    FCursorMode := CURSOR_DEFAULT;
    UpdateCursor;
    exit;
  end;
  if AOption = 'show cursor' then
  begin
    FCursorMode := CURSOR_SHOW;
    UpdateCursor;
    exit;
  end;
  if AOption = 'hide cursor' then
  begin
    FCursorMode := CURSOR_HIDE;
    UpdateCursor;
    exit;
  end;
  if AOption = 'grab mouse' then
  begin
    if FOpen and (not FFullscreen) then
      FWindow.ConfineCursor(True);
    FGrabMouse := True;
    exit;
  end;
  if AOption = 'ungrab mouse' then
  begin
    if FOpen and (not FFullscreen) then
      FWindow.ConfineCursor(False);
    FGrabMouse := False;
    exit;
  end;
  if System.Copy(AOption, 1, 9) = 'frequency' then
  begin
    if Length(AOption) > 9 then
    begin
      Val(System.Copy(AOption, 10, Length(AOption)-9), FFrequency, tmp);
    end
    else
      FFrequency := 0;
  end;
  if AOption = 'enable key buffering' then
  begin
    if FKeyboard = nil then
    begin
      Result := False;
      exit;
    end;
    FKeyboard.Enable;
  end;
  if AOption = 'disable key buffering' then
  begin
    if FKeyboard = nil then
    begin
      Result := False;
      exit;
    end;
    FKeyboard.Disable;
  end;
  if AOption = 'enable blocking' then
  begin
    FPrimary.blocking(True);
    exit;
  end;
  if AOption = 'disable blocking' then
  begin
    FPrimary.blocking(False);
    exit;
  end;
  if AOption = 'intercept window close' then
  begin
    InterceptClose := True;
    Result := True;
    exit;
  end;
  if AOption = 'enable logging' then
  begin
    LOG_enabled := True;
    Result := True;
    exit;
  end;
  if AOption = 'disable logging' then
  begin
    LOG_enabled := False;
    Result := True;
    exit;
  end;

  Result := FCopy.Option(AOption);
end;

function TDirectXConsole.Modes: TPTCModeList;
begin
  Result := FDisplay.Modes;
end;

procedure TDirectXConsole.Open(const ATitle: string; APages: Integer = 0);
begin
  Open(ATitle, FDefaultFormat, APages);
end;

procedure TDirectXConsole.Open(const ATitle: string; AFormat: IPTCFormat;
                           APages: Integer = 0);
begin
  Open(ATitle, FDefaultWidth, FDefaultHeight, AFormat, APages);
end;

procedure TDirectXConsole.Open(const ATitle: string; AWidth, AHeight: Integer;
                           AFormat: IPTCFormat; APages: Integer = 0);
var
  mode: IPTCMode;
begin
  { internal open nearest mode }
  mode := TPTCMode.Create(AWidth, AHeight, AFormat);
  internal_open(ATitle, 0, mode, APages, False);
end;

procedure TDirectXConsole.Open(const ATitle: string; AMode: IPTCMode;
                           APages: Integer = 0);
begin
  { internal open exact mode }
  internal_open(ATitle, 0, AMode, APages, True);
end;

procedure TDirectXConsole.Close;
begin
  if FOpen then
  begin
    if FLocked then
      raise TPTCError.Create('console is still locked');

    { flush all key presses }
    while KeyPressed do
      ReadKey;
  end;
  internal_close;
  FWin32Cursor.Show;
end;

procedure TDirectXConsole.InternalResize(AWidth, AHeight: Integer);
begin
  CHECK_OPEN('TDirectXConsole.InternalResize');
  CHECK_LOCK('TDirectXConsole.InternalResize');

  if FFullscreen then
    raise TPTCError.Create('TDirectXConsole.InternalResize only works in windowed mode');
  if FWindowMode <> RESIZABLE then
    raise TPTCError.Create('TDirectXConsole.InternalResize only works in resizable window mode');

  FPrimary.InternalResize(AWidth, AHeight);
  if FPrimaryModeWindowed = SECONDARY then
    FPrimary.secondary(AWidth, AHeight);
  FMouse.SetConsoleSize(AWidth, AHeight);
end;

procedure TDirectXConsole.Flush;
begin
  CHECK_OPEN('TDirectXConsole.Flush');
  CHECK_LOCK('TDirectXConsole.Flush');
  { [platform dependent code to flush all console operations] }

  { handle cursor show flag }
{  if not FCursor then
    SetCursor(0);}

  { update window }
  FWindow.Update;
end;

procedure TDirectXConsole.Finish;
begin
  CHECK_OPEN('TDirectXConsole.Finish');
  CHECK_LOCK('TDirectXConsole.Finish');
  { [platform dependent code to finish all console operations] }

  { handle cursor show flag }
{  if not FCursor then
    SetCursor(0);}

  { update window }
  FWindow.Update;
end;

procedure TDirectXConsole.Update;
begin
  CHECK_OPEN('TDirectXConsole.Update');
  CHECK_LOCK('TDirectXConsole.Update');

  { update primary surface }
  FPrimary.Update;

  { handle cursor show flag }
{  if not FCursor then
    SetCursor(0);}

  { update window }
  FWindow.Update;
end;

procedure TDirectXConsole.Update(AArea: IPTCArea);
begin
  { update }
  Update;
end;

function TDirectXConsole.NextEvent(out AEvent: IPTCEvent; AWait: Boolean; const AEventMask: TPTCEventMask): Boolean;
var
  UseGetMessage: Boolean;
begin
  CHECK_OPEN('TDirectXConsole.NextEvent');
//  CHECK_LOCK('TDirectXConsole.NextEvent');

  UseGetMessage := False;
  repeat
    FPrimary.Block;

    { update window }
    FWindow.Update(False, UseGetMessage);

    { try to find an event that matches the EventMask }
    AEvent := FEventQueue.NextEvent(AEventMask);
    if AWait then
      UseGetMessage := True;
  until (not AWait) or (AEvent <> nil);
  Result := AEvent <> nil;
end;

function TDirectXConsole.PeekEvent(AWait: Boolean; const AEventMask: TPTCEventMask): IPTCEvent;
var
  UseGetMessage: Boolean;
begin
  CHECK_OPEN('TDirectXConsole.PeekEvent');
//  CHECK_LOCK('TDirectXConsole.PeekEvent');

  UseGetMessage := False;
  repeat
    FPrimary.Block;

    { update window }
    FWindow.Update(False, UseGetMessage);

    { try to find an event that matches the EventMask }
    Result := FEventQueue.PeekEvent(AEventMask);
    if AWait then
      UseGetMessage := True;
  until (not AWait) or (Result <> nil);
end;

procedure TDirectXConsole.Copy(ASurface: IPTCSurface);
var
  pixels: Pointer;
begin
  CHECK_OPEN('TDirectXConsole.Copy(ASurface)');
  CHECK_LOCK('TDirectXConsole.Copy(ASurface)');
  pixels := Lock;
  try
    ASurface.Load(Pixels, Width, Height, Pitch, Format, Palette);
    Unlock;
  except
    on error: TPTCError do
    begin
      Unlock;
      raise TPTCError.Create('failed to copy console to surface', error);
    end;
  end;
end;

procedure TDirectXConsole.Copy(ASurface: IPTCSurface;
                               ASource, ADestination: IPTCArea);
var
  pixels: Pointer;
begin
  CHECK_OPEN('TDirectXConsole.Copy(ASurface, ASource, ADestination)');
  CHECK_LOCK('TDirectXConsole.Copy(ASurface, ASource, ADestination)');
  pixels := Lock;
  try
    ASurface.Load(Pixels, Width, Height, Pitch, Format, Palette, ASource, ADestination);
    Unlock;
  except
    on error: TPTCError do
    begin
      Unlock;
      raise TPTCError.Create('failed to copy console to surface', error);
    end;
  end;
end;

function TDirectXConsole.Lock: Pointer;
begin
  CHECK_OPEN('TDirectXConsole.Lock');
  { fail if the console is already locked }
  if FLocked then
    raise TPTCError.Create('console is already locked');

  { lock primary surface }
  Result := FPrimary.Lock;

  { surface is locked }
  FLocked := True;
end;

procedure TDirectXConsole.Unlock;
begin
  CHECK_OPEN('TDirectXConsole.Unlock');
  { fail if the console is not locked }
  if not FLocked then
    raise TPTCError.Create('console is not locked');

  { unlock primary surface }
  FPrimary.Unlock;

  { we are unlocked }
  FLocked := False;
end;

procedure TDirectXConsole.Load(const APixels: Pointer;
                           AWidth, AHeight, APitch: Integer;
                           AFormat: IPTCFormat;
                           APalette: IPTCPalette);
var
  console_pixels: Pointer;
begin
  CHECK_OPEN('TDirectXConsole.Load(APixels, AWidth, AHeight, APitch, AFormat, APalette)');
  CHECK_LOCK('TDirectXConsole.Load(APixels, AWidth, AHeight, APitch, AFormat, APalette)');
  if Clip.Equals(Area) then
  begin
    console_pixels := Lock;
    try
      try
        FCopy.Request(AFormat, Format);
        FCopy.Palette(APalette, Palette);
        FCopy.Copy(APixels, 0, 0, AWidth, AHeight, APitch, console_pixels, 0, 0,
                    Width, Height, Pitch);
      except
        on error: TPTCError do
        begin
          raise TPTCError.Create('failed to load pixels to console', error);
        end;
      end;
    finally
      Unlock;
    end;
  end
  else
    Load(APixels, AWidth, AHeight, APitch, AFormat, APalette, TPTCArea.Create(0, 0, Width, Height), area);
end;

procedure TDirectXConsole.Load(const APixels: Pointer;
                               AWidth, AHeight, APitch: Integer;
                               AFormat: IPTCFormat;
                               APalette: IPTCPalette;
                               ASource, ADestination: IPTCArea);
var
  console_pixels: Pointer;
  clipped_source, clipped_destination: IPTCArea;
begin
  CHECK_OPEN('TDirectXConsole.Load(APixels, AWidth, AHeight, APitch, AFormat, APalette, ASource, ADestination)');
  CHECK_LOCK('TDirectXConsole.Load(APixels, AWidth, AHeight, APitch, AFormat, APalette, ASource, ADestination)');
  console_pixels := Lock;
  try
    try
      TPTCClipper.Clip(ASource, TPTCArea.Create(0, 0, AWidth, AHeight), clipped_source, ADestination, Clip, clipped_destination);
      FCopy.Request(AFormat, Format);
      FCopy.Palette(APalette, Palette);
      FCopy.Copy(APixels, clipped_source.Left, clipped_source.Top, clipped_source.Width, clipped_source.Height, APitch,
                 console_pixels, clipped_destination.Left, clipped_destination.Top, clipped_destination.Width, clipped_destination.Height, Pitch);
    except
      on error:TPTCError do
      begin
        raise TPTCError.Create('failed to load pixels to console area', error);
      end;
    end;
  finally
    Unlock;
  end;
end;

procedure TDirectXConsole.Save(APixels: Pointer;
                               AWidth, AHeight, APitch: Integer;
                               AFormat: IPTCFormat;
                               APalette: IPTCPalette);
var
  console_pixels: Pointer;
begin
  CHECK_OPEN('TDirectXConsole.Save(APixels, AWidth, AHeight, APitch, AFormat, APalette)');
  CHECK_LOCK('TDirectXConsole.Save(APixels, AWidth, AHeight, APitch, AFormat, APalette)');
  if Clip.Equals(Area) then
  begin
    console_pixels := Lock;
    try
      try
        FCopy.Request(Format, AFormat);
        FCopy.Palette(Palette, APalette);
        FCopy.Copy(console_pixels, 0, 0, Width, Height, Pitch, APixels, 0, 0,
                    AWidth, AHeight, APitch);
      except
        on error: TPTCError do
        begin
          raise TPTCError.Create('failed to save console pixels', error);
        end;
      end;
    finally
      Unlock;
    end;
  end
  else
    Save(APixels, AWidth, AHeight, APitch, AFormat, APalette, Area, TPTCArea.Create(0, 0, Width, Height));
end;

procedure TDirectXConsole.Save(APixels: Pointer;
                           AWidth, AHeight, APitch: Integer;
                           AFormat: IPTCFormat;
                           APalette: IPTCPalette;
                           ASource, ADestination: IPTCArea);
var
  console_pixels: Pointer;
  clipped_source, clipped_destination: IPTCArea;
begin
  CHECK_OPEN('TDirectXConsole.Save(APixels, AWidth, AHeight, APitch, AFormat, APalette, ASource, ADestination)');
  CHECK_LOCK('TDirectXConsole.Save(APixels, AWidth, AHeight, APitch, AFormat, APalette, ASource, ADestination)');
  console_pixels := Lock;
  try
    try
      TPTCClipper.Clip(ASource, Clip, clipped_source, ADestination, TPTCArea.Create(0, 0, AWidth, AHeight), clipped_destination);
      FCopy.Request(Format, AFormat);
      FCopy.Palette(Palette, APalette);
      FCopy.Copy(console_pixels, clipped_source.Left, clipped_source.Top, clipped_source.Width, clipped_source.Height, Pitch,
                 APixels, clipped_destination.Left, clipped_destination.Top, clipped_destination.Width, clipped_destination.Height, APitch);
    except
      on error:TPTCError do
      begin
        raise TPTCError.Create('failed to save console area pixels', error);
      end;
    end;
  finally
    Unlock;
  end;
end;

procedure TDirectXConsole.Clear;
var
  Color: IPTCColor;
begin
  CHECK_OPEN('TDirectXConsole.Clear');
  CHECK_LOCK('TDirectXConsole.Clear');
  if format.direct then
    Color := TPTCColor.Create(0, 0, 0, 0)
  else
    Color := TPTCColor.Create(0);
  Clear(Color);
end;

procedure TDirectXConsole.Clear(AColor: IPTCColor);
var
  tmp: TPTCArea;
begin
  CHECK_OPEN('TDirectXConsole.Clear(AColor)');
  CHECK_LOCK('TDirectXConsole.Clear(AColor)');
  Clear(AColor, TPTCArea.Create);
end;

procedure TDirectXConsole.Clear(AColor: IPTCColor;
                                AArea: IPTCArea);
begin
  CHECK_OPEN('TDirectXConsole.Clear(AColor, AArea)');
  CHECK_LOCK('TDirectXConsole.Clear(AColor, AArea)');
  FPrimary.Clear(AColor, AArea);
end;

procedure TDirectXConsole.palette(APalette: IPTCPalette);
begin
  CHECK_OPEN('TDirectXConsole.Palette(APalette)');
  FPrimary.Palette(APalette);
end;

function TDirectXConsole.Palette: IPTCPalette;
begin
  CHECK_OPEN('TDirectXConsole.Palette');
  Result := FPrimary.palette;
end;

procedure TDirectXConsole.Clip(AArea: IPTCArea);
begin
  CHECK_OPEN('TDirectXConsole.Clip(AArea)');
  FPrimary.Clip(AArea);
end;

function TDirectXConsole.GetWidth: Integer;
begin
  CHECK_OPEN('TDirectXConsole.GetWidth');
  Result := FPrimary.width;
end;

function TDirectXConsole.GetHeight: Integer;
begin
  CHECK_OPEN('TDirectXConsole.GetHeight');
  Result := FPrimary.height;
end;

function TDirectXConsole.GetPitch: Integer;
begin
  CHECK_OPEN('TDirectXConsole.GetPitch');
  Result := FPrimary.pitch;
end;

function TDirectXConsole.GetPages: Integer;
begin
  CHECK_OPEN('TDirectXConsole.GetPages');
  Result := FPrimary.pages;
end;

function TDirectXConsole.GetArea: IPTCArea;
begin
  CHECK_OPEN('TDirectXConsole.GetArea');
  Result := FPrimary.Area;
end;

function TDirectXConsole.Clip: IPTCArea;
begin
  CHECK_OPEN('TDirectXConsole.Clip');
  Result := FPrimary.Clip;
end;

function TDirectXConsole.GetFormat: IPTCFormat;
begin
  CHECK_OPEN('TDirectXConsole.GetFormat');
  Result := FPrimary.format;
end;

function TDirectXConsole.GetName: string;
begin
  Result := 'DirectX';
end;

function TDirectXConsole.GetTitle: string;
begin
  CHECK_OPEN('TDirectXConsole.GetTitle');
  Result := FTitle;
end;

function TDirectXConsole.GetInformation: string;
begin
  CHECK_OPEN('TDirectXConsole.GetInformation');
  Result := FDisplay.information;
end;

procedure TDirectXConsole.internal_open(const _title: string; window: HWND; const mode: IPTCMode; _pages: Integer; exact: Boolean);
var
  _width, _height: Integer;
  _format: IPTCFormat;
begin
  try
    { recycle an already open console }
    internal_recycle(_title, window, mode, _pages, exact);
    exit;
  except
    on TPTCError do
    { could not recycle };
  end;

  { check that the mode is valid }
  if not mode.valid then
    raise TPTCError.Create('invalid mode');

  { get mode information }
  _width := mode.width;
  _height := mode.height;
  _format := mode.format;

  { start internal open }
  internal_open_start(_title, window);

  { check output mode }
  case FOutputMode of
    DEFAULT :
    try
      { start fullscreen open }
      internal_open_fullscreen_start(window, mode, exact);

      { change fullscreen display }
      internal_open_fullscreen_change(mode, exact);

      { setup fullscreen display surfaces }
      internal_open_fullscreen_surface(mode, _pages);

      { finish fullscreen open }
      internal_open_fullscreen_finish;
    except
      on TPTCError do
      begin
        { internal open reset }
        internal_open_reset;

        { start windowed open }
        internal_open_windowed_start(window, mode, exact);

        { change windowed display display mode }
        internal_open_windowed_change(mode, exact);

        { setup windowed display }
        internal_open_windowed_surface(mode, _pages);

        { finish windowed open }
        internal_open_windowed_finish;
      end;
    end;
    WINDOWED: begin
      { start windowed open }
      internal_open_windowed_start(window, mode, exact);

      { change windowed display display mode }
      internal_open_windowed_change(mode, exact);

      { setup windowed display }
      internal_open_windowed_surface(mode, _pages);

      { finish windowed open }
      internal_open_windowed_finish;
    end;
    FULLSCREEN: begin
      { start fullscreen open }
      internal_open_fullscreen_start(window, mode, exact);

      { change fullscreen display }
      internal_open_fullscreen_change(mode, exact);

      { setup fullscreen display surfaces }
      internal_open_fullscreen_surface(mode, _pages);

      { finish fullscreen open }
      internal_open_fullscreen_finish;
    end;
  end;

  { finish internal open }
  internal_open_finish;
end;

procedure TDirectXConsole.internal_recycle(const _title: string; window: HWND; const mode: IPTCMode; _pages: Integer; exact: Boolean);
begin
  { Check if the console is open }
  if not FOpen then
    raise TPTCError.Create('cannot recycle because it is not already open');
  if window <> 0 then
  begin
    if (FWindow.handle <> window) or (not (FWindow.managed)) then
      raise TPTCError.Create('cannot recycle with this user window');
  end;
  case FOutputMode of
    DEFAULT :
      if FDisplay.fullscreen then
      begin
        try
          internal_recycle_fullscreen(_title, window, mode, _pages, exact);
        except
          on TPTCError do
            raise TPTCError.Create('recycling fullscreen to windowed is not implemented');
        end;
      end
      else
        raise TPTCError.Create('recycling windowed to fullscreen is not implemented');
    FULLSCREEN: internal_recycle_fullscreen(_title, window, mode, _pages, exact);
    WINDOWED: internal_recycle_fullscreen(_title, window, mode, _pages, exact);
  end;
end;

procedure TDirectXConsole.internal_close;
begin
  FOpen := False;
  FreeAndNil(FResize);
  FreeAndNil(FMouse);
  FreeAndNil(FKeyboard);
  FreeAndNil(FHook);
  FreeAndNil(FEventQueue);
  if FPrimary <> nil then
    FPrimary.Close;
  if FDisplay <> nil then
    FDisplay.Close;
  FreeAndNil(FWindow);
  if FDisplay <> nil then
    FDisplay.Restore;
end;

procedure TDirectXConsole.internal_shutdown;
begin
  FLibrary.Close;
end;

procedure TDirectXConsole.internal_open_start(const _title: string; window: HWND);
var
  tmp: array [0..1023] of Char;
begin
  { close_down }
  internal_close;

  { check window }
  if window = 0 then
  begin
    FTitle := _title;
  end
  else
  begin
    GetWindowText(window, @tmp, SizeOf(tmp));
    FTitle := PChar2String(@tmp);
  end;
end;

procedure TDirectXConsole.internal_open_finish;
begin
  FreeAndNil(FResize);
  FreeAndNil(FMouse);
  FreeAndNil(FKeyboard);
  FreeAndNil(FEventQueue);
  FEventQueue := TEventQueue.Create;
  FKeyboard := TWin32Keyboard.Create(FWindow.handle, FWindow.thread, False, FEventQueue);
  FMouse := TWin32Mouse.Create(FWindow.handle, FWindow.thread, False, FEventQueue, FPrimary.Fullscreen, FPrimary.width, FPrimary.height);
  if FPrimary.Fullscreen then
    FMouse.SetWindowArea(0, 0, FDisplay.Mode.Width - 1, FDisplay.Mode.Height - 1);
  if not FPrimary.Fullscreen then
    FResize := TWin32Resize.Create(FWindow.handle, FWindow.thread, FEventQueue);
  FWindow.update;
  FOpen := True;
end;

procedure TDirectXConsole.internal_open_reset;
begin
  FreeAndNil(FResize);
  FreeAndNil(FMouse);
  FreeAndNil(FKeyboard);
  FreeAndNil(FHook);
  FPrimary.close;
  FreeAndNil(FWindow);
  FreeAndNil(FEventQueue);
  FDisplay.restore;
end;

procedure TDirectXConsole.internal_open_fullscreen_start(window: HWND; const mode: IPTCMode; exact: Boolean);
begin
  FFullscreen := True;

  { test if display mode exists... }
  if not FDisplay.test(mode, exact) then
    raise TPTCError.Create('display mode test failed!');

  { handle cursor show mode }
  if FCursorMode = CURSOR_SHOW then
    FCursor := True
  else
    FCursor := False;

  { save display }
  FDisplay.save;

  { check window }
  if window = 0 then
    FWindow := TWin32Window.Create('PTC_DIRECTX_FULLSCREEN',
                                    FTitle,
                                    WS_EX_TOPMOST,
                                    DWord(WS_POPUP or WS_SYSMENU or WS_VISIBLE), // fpc windows RTL bug - WS_POPUP should be a DWord!!!
                                    CS_VREDRAW or CS_HREDRAW,
                                    SW_NORMAL,
                                    0, 0,
                                    GetSystemMetrics(SM_CXSCREEN),
                                    GetSystemMetrics(SM_CYSCREEN),
                                    False, False, FCursor, InterceptClose)
  else
    FWindow := TWin32Window.Create(window);

  if FCursor then
    FWin32Cursor.Show
  else
    FWin32Cursor.Hide;

  { set cooperative level }
  FDisplay.cooperative(FWindow.handle, True);
end;

procedure TDirectXConsole.internal_open_fullscreen_change(const mode: IPTCMode; exact: Boolean);
begin
  FDisplay.open(mode, exact, FFrequency);
  FPrimary.blocking(True);
end;

procedure TDirectXConsole.internal_open_fullscreen_surface(const mode: IPTCMode; _pages: Integer);
var
  primary: Boolean;
  _secondary: Boolean;
  _palette: Boolean;
  complex: Boolean;
begin
  _secondary := (FPrimaryModeFullscreen = SECONDARY) or (not FDisplay.mode.Equals(mode));
  _palette := FDisplay.mode.format.indexed;
  FPrimary.initialize(FWindow, FLibrary.lpDD2);
  complex := True; { Complex = false sucks; according to the DirectX 7 docs, AddAttachedSurface must be used only for Z-buffer surfaces }
  primary := False;

  { todo: log errors }
  if _pages >= 1 then
  try
    FPrimary.primary(_pages, True, True, _palette, complex);
    primary := True;
  except
    on TPTCError Do;
  end;

  if not primary then
  try
    FPrimary.primary(3, True, True, _palette, complex);
    primary := True;
  except
    on TPTCError Do;
  end;

  if not primary then
  try
    FPrimary.primary(2, True, True, _palette, complex);
    primary := True;
  except
    on TPTCError Do;
  end;

  if not Primary then
  try
    if not _secondary then
      FPrimary.primary(2, False, True, _palette, complex)
    else
      FPrimary.primary(1, False, True, _palette, complex);
    primary := True;
  except
    on TPTCError do
      raise TPTCError.Create('Could not create primary surface');
  end;

  if _secondary then
    FPrimary.secondary(mode.width, mode.height);
  if FNearestMode = NEAREST_CENTERING then
    FPrimary.centering(True);
  if FNearestMode = NEAREST_STRETCHING then
    FPrimary.centering(False);
  {
  original primary setup code (1.0.17)
  ...
  }

  FPrimary.synchronize(FSynchronizedUpdate);
end;

procedure TDirectXConsole.internal_open_fullscreen_finish;
begin
  FreeAndNil(FHook);

  { create hook on window }
  FHook := TDirectXHook.Create(Self, FWindow.handle, GetCurrentThreadId, FCursor, FWindow.managed, True);
end;

procedure TDirectXConsole.internal_open_windowed_start(window: HWND; const mode: IPTCMode; exact: Boolean);
var
  extended: Integer;
begin
  FFullscreen := False;
  if FCursorMode = CURSOR_HIDE then
    FCursor := False
  else
    FCursor := True;
  FreeAndNil(FWindow);
  if window <> 0 then
  begin
    FWindow := TWin32Window.Create(window);
  end
  else
  begin
    extended := 0;
    if FPrimaryModeWindowed = DIRECT then
      extended := WS_EX_TOPMOST;
    case FWindowMode of
      RESIZABLE: FWindow := TWin32Window.Create('PTC_DIRECTX_WINDOWED_RESIZABLE', FTitle,
                                              extended, WS_OVERLAPPEDWINDOW or WS_VISIBLE, CS_VREDRAW or CS_HREDRAW, SW_NORMAL, CW_USEDEFAULT, CW_USEDEFAULT, mode.width, mode.height, FCenterWindow, False, FCursor, InterceptClose);
      FIXED: FWindow := TWin32Window.Create('PTC_DIRECTX_WINDOWED_FIXED', FTitle,
                                              extended, WS_VISIBLE or WS_SYSMENU or WS_CAPTION or WS_MINIMIZEBOX, CS_VREDRAW or CS_HREDRAW, SW_NORMAL, CW_USEDEFAULT, CW_USEDEFAULT, mode.width, mode.height, FCenterWindow, False, FCursor, InterceptClose);
    end;
  end;
  FDisplay.cooperative(FWindow.handle, False);
end;

procedure TDirectXConsole.internal_open_windowed_change(const mode: IPTCMode; exact: Boolean);
begin
  FDisplay.open;
  if FPrimaryModeWindowed = DIRECT then
    FPrimary.blocking(True)
  else
    FPrimary.blocking(False);
end;

procedure TDirectXConsole.internal_open_windowed_surface(const mode: IPTCMode; _pages: Integer);
begin
  FPrimary.initialize(FWindow, FLibrary.lpDD2);
  FPrimary.primary(1, False, False, False, False);
  if FPrimaryModeWindowed = SECONDARY then
    FPrimary.secondary(mode.width, mode.height);
end;

procedure TDirectXConsole.internal_open_windowed_finish;
begin
  FreeAndNil(FHook);

  { create hook on window }
  FHook := TDirectXHook.Create(Self, FWindow.handle, GetCurrentThreadId, FCursor, FWindow.managed, False);
end;

procedure TDirectXConsole.internal_recycle_fullscreen(const _title: string; window: HWND; const mode: IPTCMode; _pages: Integer; exact: Boolean);
begin
  LOG('fullscreen open recycle');
  FPrimary.close;
  internal_open_fullscreen_change(mode, exact);
  internal_open_fullscreen_surface(mode, _pages);
end;

procedure TDirectXConsole.internal_recycle_windowed(const _title: string; window: HWND; const mode: IPTCMode; _pages: Integer; exact: Boolean);
begin
  LOG('windowed open recycle');
  FPrimary.close;
  FWindow.resize(mode.width, mode.height);
  internal_open_windowed_change(mode, exact);
  internal_open_windowed_surface(mode, _pages);
end;

procedure TDirectXConsole.Paint;
begin
  if FLocked or (not FOpen) then
    exit;
  FPrimary.Paint;
end;

procedure TDirectXConsole.UpdateCursor;
begin
  if not FOpen then
    exit;
  if FDisplay.Fullscreen then
    if FCursorMode = CURSOR_SHOW then
      FCursor := True
    else
      FCursor := False
  else
    if FCursorMode = CURSOR_HIDE then
      FCursor := False
    else
      FCursor := True;

  { update hook cursor }
  FHook.Cursor(FCursor);

  { update window cursor }
  FWindow.Cursor(FCursor);

  { hide/show cursor globally if running fullscreen }
  if FDisplay.Fullscreen then
    if FCursor then
      FWin32Cursor.Show
    else
      FWin32Cursor.Hide;
end;

procedure TDirectXConsole.SetInterceptClose(AInterceptClose: Boolean);
begin
  FInterceptClose := AInterceptClose;
  if Assigned(FWindow) then
    FWindow.InterceptClose := AInterceptClose;
end;

function TDirectXConsole.MoveMouseTo(X, Y: Integer): Boolean;
begin
  CHECK_OPEN('TDirectXConsole.MoveMouseTo');
  Result := FMouse.MoveMouseTo(X, Y);
end;

{$IFDEF DEBUG}
procedure TDirectXConsole.CHECK_OPEN(AMsg: String);
begin
  if not FOpen then
  try
    raise TPTCError.Create('console is not open');
  except
    on error: TPTCError do
      raise TPTCError.Create(AMsg, error);
  end;
end;

procedure TDirectXConsole.CHECK_LOCK(AMsg: String);
begin
  if FLocked then
  try
    raise TPTCError.Create('console is locked');
  except
    on error: TPTCError do
      raise TPTCError.Create(AMsg, error);
  end;
end;
{$ENDIF}