-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathApus.Engine.Game.pas
2389 lines (2159 loc) · 70.4 KB
/
Apus.Engine.Game.pas
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
// Main runtime unit of the engine
//
// IMPORTANT: Nevertheless BasicGame is implemented as class, it is
// NOT thread-safe itself i.e. does not allow multiple instances!
// (at least between Run/Stop calls)
// If you want to access private data (buffers, images) from other
// threads, use your own synchronization methods
//
// Copyright (C) 2003-2013 Apus Software (www.apus-software.com)
// Author: Ivan Polyacov ([email protected])
// This file is licensed under the terms of BSD-3 license (see license.txt)
// This file is a part of the Apus Game Engine (http://apus-software.com/engine/)
{$IFDEF IOS}{$S-}{$ENDIF}
{$R-}
unit Apus.Engine.Game;
interface
uses Classes, Apus.CrossPlatform, Apus.Common, Apus.Engine.Types, Types, Apus.Engine.API;
var
onFrameDelay:integer=0; // Sleep this time every frame
disableDRT:boolean=false; // always render directly to the backbuffer - no
useDepthTexture:boolean=false; // when default RT is used, allocate a depth buffer texture instead of regular depth buffer
type
{ TGame }
TGame=class(TGameBase)
constructor Create(systemPlatform:ISystemPlatform;gfxSystem:IGraphicsSystem); // Создать экземпляр
procedure Run; override; // запустить движок (создание окна, переключение режима и пр.)
procedure Stop; override; // остановить и освободить все ресурсы (требуется повторный запуск через Run)
destructor Destroy; override; // автоматически останавливает, если это не было сделано
procedure SwitchToAltSettings; override; // Alt+Enter
// Events
// Этот метод вызывается из главного цикла всякий раз перед попыткой рендеринга кадра, даже если программа неактивна или девайс потерян
function OnFrame:boolean; override; // true означает что на экране что-то должно изменится поэтому экран нужно перерисовать. Иначе перерисовка выполнена не будет (движение мыши отслеживается отдельно)
procedure RenderFrame; override; // этот метод должен отрисовать кадр в backbuffer
// Scenes
procedure AddScene(scene:TGameScene); override; // Добавить сцену в список сцен
procedure RemoveScene(scene:TGameScene); override; // Убрать сцену из списка сцен
function TopmostVisibleScene(fullScreenOnly:boolean=false):TGameScene; override; // Find the topmost active scene
function GetScene(name:string):TGameScene; override;
procedure SwitchToScene(name:string); override;
procedure ShowWindowScene(name:string;modal:boolean=true); override;
procedure HideWindowScene(name:string); override;
// Cursors
procedure RegisterCursor(CursorID,priority:integer;cursorHandle:THandle); override;
function GetCursorForID(cursorID:integer):THandle; override;
procedure ToggleCursor(CursorID:integer;state:boolean=true); override;
procedure HideAllCursors; override;
// Translate coordinates in window's client area
procedure ClientToGame(var p:TPoint); override;
procedure GameToClient(var p:TPoint); override;
function RunAsync(threadFunc:TAsyncProc;param:UIntPtr=0;ttl:single=0;name:string=''):THandle; override;
function GetThreadResult(h:THandle):integer; override;
procedure FLog(st:string); override;
function GetStatus(n:integer):string; override;
procedure FireMessage(st:string8); override;
procedure DebugFeature(feature:TDebugFeature;enable:boolean); override;
procedure ToggleDebugFeature(feature:TDebugFeature);
procedure EnterCritSect; override;
procedure LeaveCritSect; override;
// Устанавливает флаги о необходимости сделать скриншот (JPEG or PNG)
procedure RequestScreenshot(saveAsJpeg:boolean=true); override;
procedure RequestFrameCapture(obj:TObject=nil); override;
procedure StartVideoCap(filename:string); override;
procedure FinishVideoCap; override;
// Utility functions
function MouseInRect(r:TRect):boolean; overload; override;
function MouseInRect(r:TRect2s):boolean; overload; override;
function MouseInRect(x,y,width,height:single):boolean; overload; override;
function MouseIsNear(x,y,radius:single):boolean; overload; override;
function MouseWasInRect(r:TRect):boolean; overload; override;
function MouseWasInRect(r:TRect2s):boolean; overload; override;
procedure WaitFor(pb:PBoolean;msg:string=''); override;
// Keyboard events utility functions
procedure SuppressKbdEvent; override;
function GetDepthBufferTex:TTexture; override;
procedure Minimize; override;
procedure MoveWindowTo(x, y, width, height: integer); override;
procedure SetWindowCaption(text: string); override;
procedure SetSettings(s:TGameSettings); override; // этот метод служит для изменения режима или его параметров
function GetSettings:TGameSettings; override; // этот метод служит для изменения режима или его параметров
procedure DPadCustomPoint(x,y:single); override;
protected
useMainThread:boolean; // true - launch "main" thread with main loop,
// false - no main thread, catch frame events
canExitNow:boolean; // флаг того, что теперь можно начать деинициализацию
params,newParams:TGameSettings;
aspectRatio:single; // Initial aspect ratio (width/height)
altWidth,altHeight:integer; // saved window size for Alt+Enter
mainThread:TThread;
controlThreadId:TThreadID;
cursors:array of TObject;
crSect:TMyCriticalSection;
scenes:array of TGameScene;
LastOnFrameTime:int64; // момент последнего вызова обработки кадра
LastRenderTime:int64; // Момент последней отрисовки кадра
capturedName:string;
capturedTime:int64;
// Screen capture
captureSingleFrame:boolean; // request frame capture
// что сделать с захваченным кадром
// 0 - keep in frameCaptureData, 1 - save as BMP, 2 - save as JPEG, 3 - save as TGA
frameCaptureTarget:integer;
frameCaptureData:TObject;
videoCaptureMode:boolean; // режим видеозахвата
videoCapturePath:string; // путь для сохранения файлов видеозахвата (по умолчанию - тек. каталог)
// FPS calc
fpsAccumTime:integer;
fpsAccumFrames:integer;
curPrior:integer; // приоритет текущего отображаемого курсора
wndCursor:THandle; // current system cursor
suppressCharEvent:boolean; // suppress next keyboard event (to avoid duplicated handle of both CHAR and KEY events)
frameLog,prevFrameLog:string;
avgTime,avgTime2:double;
timerFrame:cardinal;
customPoints,activeCustomPoints:array of TPoint; // custom navigation points
// Debug utilities
debugOverlay:integer; // индекс отладочного оверлея, включаемого клавишами Alt+Fn (0 - отсутствует)
magnifierTex:TTexture;
debugFeatures:set of TDebugFeature;
dRT:TTexture; // default render target (can be nil)
dRTdepth:TTexture; // depth buffer texture
procedure ApplyNewSettings; virtual; // apply newParams to params - must be called from main thread!
procedure SetVSync(divider:integer);
// вызов только из главного потока
procedure InitGraph; virtual; // Инициализация графической части (переключить режим и все такое прочее)
procedure InitDefaultResources; virtual;
procedure AfterInitGraph; virtual; // Вызывается после инициализации графики
// Set window size/style/position
//procedure ConfigureMainWindow; virtual;
// Настраивает отрисовку
// Производит настройку подчинённых объектов/интерфейсов (Painter, UI и т.д)
// Вызывается после инициализации а также при изменения размеров окна, области или режима отрисовки
procedure SetupRenderArea; virtual;
// Create default RT (if needed)
procedure InitDefaultRenderTarget; virtual;
procedure InitMainLoop; virtual;
procedure FrameLoop; virtual; // One iteration of the frame loop
procedure RenderAndPresentFrame; virtual; // May be called from the message handlers
procedure PresentFrame; virtual; // Displays back buffer
procedure DoneGraph; virtual; // Финализация графической части
// Производит захват кадра и производит с ним необходимые действия
procedure CaptureFrame; virtual;
procedure DrawCursor; virtual;
procedure DrawOverlays; virtual;
procedure NotifyScenesAboutMouseMove; virtual;
procedure NotifyScenesAboutMouseBtn(c:byte;pressed:boolean); virtual;
// находит сцену, которая должна получать сигналы о клавиатурном вводе
function TopmostSceneForKbd:TGameScene; virtual;
// Events
// Called when ENGINE\* event is fired
procedure onEngineEvent(event:string;tag:NativeInt); virtual;
// Called when ENGINE\CMD\* event is fired
procedure onCmdEvent(event:string;tag:NativeInt); virtual;
// Called when KBD\* event is fired
procedure onKbdEvent(event:string;tag:NativeInt); virtual;
// Called when MOUSE\* event is fired
procedure onMouseEvent(event:string;tag:NativeInt); virtual;
// Called when JOYSTICK\* event is fired
procedure onJoystickEvent(event:string;tag:NativeInt); virtual;
// Called when GAMEPAD\* event is fired
procedure onGamepadEvent(event:string;tag:NativeInt); virtual;
// Event processors
procedure MouseMovedTo(newX,newY:integer); virtual;
procedure CharEntered(charCode,scanCode:integer); virtual;
procedure KeyPressed(keyCode,scanCode:integer;pressed:boolean=true); virtual;
procedure MouseButtonPressed(btn:integer;pressed:boolean=true); virtual;
procedure MouseWheelMoved(value:integer); virtual;
procedure SizeChanged(newWidth,newHeight:integer); virtual;
procedure Activate(activeState:boolean); virtual;
// Utils
procedure CreateDebugLogs; virtual;
// Draw magnified part of the screen under mouse
procedure DrawMagnifier; virtual;
// Internal hotkeys such as PrintScreen, Alt+F1 etc
procedure HandleInternalHotkeys(keyCode:integer;pressed:boolean); virtual;
procedure HandleGamepadNavigation;
end;
// Для использования из главного потока
procedure Delay(time:integer);
implementation
uses SysUtils, TypInfo, Apus.Engine.CmdProc, Apus.Images, Apus.FastGFX, Apus.Engine.ImageTools
{$IFDEF VIDEOCAPTURE},Apus.Engine.VideoCapture{$ENDIF},
Apus.EventMan, Apus.Engine.Scene, Apus.Engine.UI, Apus.Engine.UITypes, Apus.Engine.UIScene,
Apus.Engine.Console, Apus.Publics, Apus.GfxFormats, Apus.Clipboard, Apus.Engine.TextDraw,
Apus.Engine.Controller;
type
TMainThread=class(TThread)
errorMsg:string;
procedure Execute; override;
end;
TCustomThread=class(TThread)
id:cardinal;
TimeToKill:int64;
running:boolean;
func:TAsyncProc;
FinishTime:int64;
param:UIntPtr;
name:string;
procedure Execute; override;
end;
TGameCursor=class
ID:integer;
priority:integer;
handle:THandle;
visible:boolean;
end;
TVarTypeGameClass=class(TVarTypeStruct)
class function GetField(variable:pointer;fieldName:string;out varClass:TVarClass):pointer; override;
class function ListFields:string; override;
end;
var
lastThreadID:NativeInt;
threads:array[1..16] of TCustomThread;
RA_sect:TMyCriticalSection;
gameEx:TGame;
{$IFDEF FREETYPE}
// Default vector font is Open Sans
{$I defaultFont.inc}
{$ELSE}
// Default raster fonts (exact sizes are 6.0, 7.0 and 9.0)
{$I defaultFont8.inc}
{$I defaultFont10.inc}
{$I defaultFont12.inc}
{$ENDIF}
{ TGame }
procedure TGame.HandleGamepadNavigation;
var
i:integer;
scene:TUIScene;
procedure Traverse(e:TUIElement);
var
child:TUIElement;
pnt:TPoint;
begin
if e=nil then exit;
with e do begin
if not (enabled and visible) then exit;
pnt:=GetPosOnScreen.CenterPoint;
if e is TUIButton then activeCustomPoints:=activeCustomPoints+[pnt];
for child in children do Traverse(child);
end;
end;
begin
if gamepadNavigationMode=gnmDisabled then exit;
EnterCritSect;
try
activeCustomPoints:=customPoints;
SetLength(customPoints,0);
if gamepadNavigationMode=gnmAuto then begin
// Add clickable UI objects
if topmostScene is TUIScene then scene:=TUIScene(topmostScene)
else exit;
Traverse(scene.UI);
end;
finally
LeaveCritSect;
end;
end;
procedure TGame.HandleInternalHotkeys(keyCode:integer; pressed:boolean);
procedure ToggleDebugOverlay(n:integer);
begin
if debugOverlay=n then debugOverlay:=0
else debugOverlay:=n;
end;
begin
if pressed then begin
// Alt+Enter - switch display settings
if (keyCode=VK_RETURN) and (shiftstate and sscAlt>0) then
if (params.mode.displayMode<>params.altMode.displayMode) and
(params.altMode.displayMode<>dmNone) then
SwitchToAltSettings;
// Alt+F11
if (keyCode=VK_F11) and HasFlag(shiftState,sscAlt) then begin
SetVSync(params.VSync xor 1); // toggle vsync
if params.VSync=0 then Include(debugFeatures,dfShowFPS)
else Exclude(debugFeatures,dfShowFPS);
end;
// F12 or PrintScreen - screenshot (JPEG), Alt+F12 - (loseless)
if (keyCode=VK_SNAPSHOT) or (keyCode=VK_F12) then
RequestScreenshot(not HasFlag(shiftState,sscAlt));
if HasFlag(shiftState,sscAlt) then
if (debugHotKey=dhAltFx) or (debugHotkey=dhCtrlAltFx) and HasFlag(shiftState,sscCtrl) then begin
if keyCode=VK_F1 then begin
if debugOverlay=0 then begin
debugOverlay:=1;
DebugFeature(dfShowFPS,true);
end else begin
debugOverlay:=0;
debugFeatures:=[];
end;
end else
if keyCode=VK_F3 then
ToggleDebugFeature(dfShowMagnifier);
end;
// [Alt]+[1] .. [Alt]+[9] - switch debug overlay when enabled
if (debugOverlay>0) and (keyCode in [ord('1')..ord('9')]) and HasFlag(shiftState,sscAlt) then
debugOverlay:=1+keyCode-ord('1');
// Shift+Alt+F1 - Create debug logs
if (keyCode=VK_F1) and
(shiftState and sscAlt>0) and
(shiftState and sscShift>0) then CreateDebugLogs;
end;
end;
procedure TGame.RequestScreenshot(saveAsJpeg:boolean=true);
begin
EnterCritSect;
try
if saveAsJPEG then frameCaptureTarget:=2
else frameCaptureTarget:=3;
captureSingleFrame:=true;
finally
LeaveCritSect;
end;
end;
procedure TGame.RequestFrameCapture(obj:TObject=nil);
begin
EnterCritSect;
try
captureSingleFrame:=true;
frameCaptureTarget:=0;
frameCaptureData:=obj;
finally
LeaveCritSect;
end;
end;
procedure TGame.ApplyNewSettings;
var
resChanged,pfChanged:boolean;
i:integer;
begin
resChanged:=(newParams.width<>params.width) or (newParams.height<>params.height);
pfChanged:=newParams.colorDepth<>params.colorDepth;
params:=newParams;
if (params.mode.displayMode=dmFullScreen) and (altWidth=0) or (altHeight=0) then begin
// save size for windowed mode
altWidth:=params.width;
altHeight:=params.height;
end;
if running then begin // смена параметров во время работы
with params.mode do
LogMessage('Change mode to: %s,%s,%s %d x %d ',
[displayMode.ToString, displayFitMode.ToString, displayScaleMode.ToString,
params.width, params.height]);
systemPlatform.SetupWindow(params);
if gfx.target<>nil then gfx.target.Backbuffer;
SetupRenderArea;
for i:=low(scenes) to high(scenes) do
scenes[i].ModeChanged;
end;
end;
procedure TGame.SetVSync(divider: integer);
begin
if (mainThread<>nil) and (mainThread.ThreadID<>GetCurrentThreadID) then begin
Signal('ENGINE\Cmd\SetSwapInterval',divider);
exit;
end;
params.VSync:=divider;
if gfx.config.SetVSyncDivider(divider) then exit;
if systemPlatform.SetSwapInterval(divider) then exit;
PutMsg('Failed to set VSync: no method available');
end;
procedure TGame.SetSettings(s: TGameSettings);
begin
if not systemPlatform.canChangeSettings then exit;
newParams:=s;
if useMainThread and (mainThread=nil) then begin
ApplyNewSettings; exit;
end;
if (mainThread=nil) or (GetCurrentThreadID<>mainThread.ThreadID) then
Signal('Engine\CMD\ChangeSettings')
else
ApplyNewSettings;
end;
function TGame.MouseInRect(r:TRect):boolean;
begin
result:=(mouseX>=r.Left) and (mouseY>=r.Top) and
(mouseX<r.Right) and (mouseY<r.Bottom);
end;
function TGame.MouseInRect(r:TRect2s):boolean;
begin
result:=(mouseX>=r.x1) and (mouseY>=r.y1) and
(mouseX<r.x2) and (mouseY<r.y2);
end;
function TGame.MouseInRect(x,y,width,height:single):boolean;
begin
result:=(mouseX>=x) and (mouseY>=y) and
(mouseX<x+width) and (mouseY<y+height);
end;
function TGame.MouseIsNear(x,y,radius:single):boolean;
begin
result:=Sqr(mouseX-x)+Sqr(mouseY-y)<=sqr(radius);
end;
procedure TGame.MouseMovedTo(newX,newY:integer);
begin
oldMouseX:=mouseX;
oldMouseY:=MouseY;
mouseX:=newX;
mouseY:=newY;
mouseMovedTime:=MyTickCount;
Signal('MOUSE\MOVE',mouseX and $FFFF+(mouseY and $FFFF) shl 16);
TGame(game).NotifyScenesAboutMouseMove;
// Если курсор рисуется вручную, то нужно обновить экран
if not params.showSystemCursor then screenChanged:=true;
end;
procedure TGame.CharEntered(charCode,scanCode:integer);
var
i:integer;
scene:TGameScene;
key:cardinal;
wst:WideString;
ast:AnsiString;
begin
if suppressCharEvent then begin
suppressCharEvent:=false; exit;
end;
if shiftstate=sscCtrl then exit; // Ignore Ctrl+*
// Send to active scene
scene:=TopmostSceneForKbd;
if scene<>nil then begin
wst:=WideChar(charcode);
ast:=AnsiString(wst); // convert to ANSI
key:=byte(ast[1])+(scancode and $FF) shl 8+(charcode and $FFFF) shl 16;
scene.WriteKey(key);
end;
end;
procedure TGame.KeyPressed(keyCode,scanCode:integer;pressed:boolean=true);
var
scene:TGameScene;
code,uCode:cardinal;
begin
ASSERT(scancode in [0..255]);
code:=keyCode and $FFFF+shiftstate shl 16+scancode shl 24;
uCode:=keyCode and $FFFF+scanCode shl 24;
scene:=TopmostSceneForKbd;
if pressed and (scene<>nil) then
scene.WriteKey(scancode shl 8+keyCode);
HandleInternalHotkeys(keyCode,pressed);
if pressed then begin
keyState[scanCode]:=keyState[scanCode] or 1;
//LogMessage('KeyDown %d, KS[%d]=%2x ',[lParam,scanCode,keystate[scanCode]]);
if scene<>nil then Signal('SCENE\'+scene.name+'\KeyDown',uCode);
end else begin
keyState[scanCode]:=keyState[scanCode] and $FE;
//LogMessage('KeyUp %d, KS[$d]=%2x ',[lParam,scanCode,keystate[scanCode]]);
if scene<>nil then Signal('SCENE\'+scene.name+'\KeyUp',uCode);
end;
end;
procedure TGame.MouseButtonPressed(btn:integer;pressed:boolean=true);
begin
NotifyScenesAboutMouseBtn(btn,pressed);
end;
procedure TGame.MouseWheelMoved(value:integer);
var
i:integer;
begin
for i:=low(scenes) to high(scenes) do
if scenes[i].IsActive then
scenes[i].onMouseWheel(value);
end;
procedure TGame.SizeChanged(newWidth,newHeight:integer);
begin
if (windowWidth<>newWidth) or (windowHeight<>newHeight) then begin
windowWidth:=newWidth;
windowHeight:=newHeight;
LogMessage('RESIZED: %d,%d',[windowWidth,windowHeight]);
SetupRenderArea;
screenChanged:=true;
end;
end;
procedure TGame.Activate(activeState:boolean);
begin
active:=activeState;
if not active and (params.mode.displayMode=dmFullScreen) then Minimize;
LogMessage('ACTIVATE: %d',[byte(active)]);
Signal('Engine\ActivateWnd',byte(active));
if params.showSystemCursor then wndCursor:=0;
end;
function TGame.MouseWasInRect(r:TRect):boolean;
begin
result:=(oldMouseX>=r.Left) and (oldmouseY>=r.Top) and
(oldmouseX<r.Right) and (oldmouseY<r.Bottom);
end;
function TGame.MouseWasInRect(r:TRect2s):boolean;
begin
result:=(oldmouseX>=r.x1) and (oldmouseY>=r.y1) and
(oldmouseX<r.x2) and (oldmouseY<r.y2);
end;
constructor TGame.Create(systemPlatform:ISystemPlatform;
gfxSystem: IGraphicsSystem);
begin
inherited Create(systemPlatform,gfxSystem);
ForceLogMessage('Creating '+self.ClassName);
game:=self;
running:=false;
terminated:=false;
canExitNow:=false;
useMainThread:=true;
controlThreadId:=GetCurrentThreadId;
active:=false;
paused:=false;
mainThread:=nil;
FrameNum:=0;
fps:=60;
smoothFPS:=60;
params.VSync:=1;
fillchar(keystate,sizeof(keystate),0);
InitCritSect(crSect,'MainGameObj',20);
// Primary display
systemPlatform.GetScreenSize(screenWidth,screenHeight);
screenDPI:=systemPlatform.GetScreenDPI;
LogMessage('Screen: %dx%d DPI=%d',[screenWidth,screenHeight,screenDPI]);
SetLength(scenes,0);
PublishVar(@renderWidth,'RenderWidth',TVarTypeInteger);
PublishVar(@renderHeight,'RenderHeight',TVarTypeInteger);
PublishVar(@windowWidth,'WindowWidth',TVarTypeInteger);
PublishVar(@windowHeight,'WindowHeight',TVarTypeInteger);
PublishVar(@screenDPI,'ScreenDPI',TVarTypeInteger);
PublishVar(@game,'game',TVarTypeGameClass);
end;
function TGame.GetScene(name:string):TGameScene;
begin
EnterCritSect;
try
result:=TGameScene.FindByName(name) as TGameScene;
finally
LeaveCritSect;
end;
ASSERT(result<>nil,'Scene '+name+' not found!');
end;
function TGame.GetSettings:TGameSettings;
begin
result:=params;
end;
function TGame.GetStatus(n:integer):string;
begin
end;
destructor TGame.Destroy;
begin
if running then Stop;
DeleteCritSect(crSect);
inherited;
end;
procedure TGame.DoneGraph;
begin
Signal('Engine\BeforeDoneGraph');
gfx.Done;
LogMessage('DoneGraph');
systemPlatform.ShowWindow(false);
Signal('Engine\AfterDoneGraph');
end;
procedure TGame.DPadCustomPoint(x, y: single);
begin
EnterCritSect;
try
customPoints:=customPoints+[Point(round(x),round(y))];
finally
LeaveCritSect;
end;
end;
procedure TGame.DrawMagnifier;
var
width,height,left:integer;
u,v,du,dv:single;
cx,cy,zoom,ox,oy:integer;
text:string;
color:cardinal;
rawImage:TRawImage;
screenScale:single;
mSize:integer;
begin
if magnifierTex=nil then begin
magnifierTex:=AllocImage(128,128,ipfARGB,aiTexture,'Magnifier');
end;
cx:=mouseX-64;
cy:=mouseY+64;
EditImage(magnifierTex);
FillRect(0,0,127,127,$FF000000);
rawImage:=magnifierTex.GetRawImage;
gfx.CopyFromBackbuffer(cx,renderHeight-cy,rawImage);
rawImage.Free;
color:=GetPixel(64,63);
magnifierTex.Unlock;
magnifierTex.SetFilter(TTexFilter.fltNearest);
gfx.shader.UseTexture(magnifierTex);
screenScale:=screenDPI/96;
mSize:=round(512*screenScale);
mSize:=mSize and $FFFFFFF0;
width:=min2(mSize,round(renderWidth*0.4));
height:=min2(mSize,renderHeight);
if mouseX<renderWidth div 2 then left:=renderWidth-width
else left:=0;
zoom:=round(4*screenScale);
if (shiftstate and sscShift)>0 then zoom:=zoom*2;
du:=width/(256*zoom); dv:=-height/(256*zoom);
u:=0.5; v:=0.5;
draw.TexturedRect(left,0,left+width{-1},height{-1},magnifierTex,u-du,v-dv,u+du,v-dv,u+du,v+dv,$FF808080);
draw.Rect(left,0,left+width,height,clWhite);
// Color picker
if zoom>6*screenScale then begin
ox:=left+(width div 2);
oy:=(height div 2);
draw.Rect(ox,oy,ox+zoom,oy+zoom,$80FFFFFF);
draw.Rect(ox-1,oy-1,ox+zoom+1,oy+zoom+1,$80000000);
// Pixel color value (hex)
draw.FillRect(ox-50*screenScale,height-30*screenScale,ox+50*screenScale,height-2*screenScale,$80000000);
text:=Format('%2x %2x %2x',[(color shr 16) and $FF,(color shr 8) and $FF,color and $FF]);
txt.WriteW(defaultFont,ox,height-17*screenScale,$FFFFFFFF,Str16(text),taCenter);
// Pixel coordinates
text:=Format('x: %d y: %d',[mousex,mouseY]);
txt.WriteW(smallFont,ox,height-5*screenScale,$FFFFFFFF,Str16(text),taCenter);
end;
end;
procedure TGame.FLog(st: string);
begin
FrameLog:=FrameLog+st+#13#10;
end;
procedure TGame.EnterCritSect;
begin
EnterCriticalSection(crSect,GetCaller);
end;
procedure TGame.LeaveCritSect;
begin
LeaveCriticalSection(crSect);
end;
procedure TGame.InitDefaultResources;
var
x,y:integer;
size:single;
begin
// Built-in fonts
{$IFDEF FREETYPE}
txt.LoadVectorFont(TBuffer.CreateFrom(@OpenSans_Regular,OpenSans_Regular_Size),'Default');
{$ELSE}
txt.LoadRasterFont(TBuffer.CreateFrom(@defaultFont8,length(defaultFont8)));
txt.LoadRasterFont(TBuffer.CreateFrom(@defaultFont10,length(defaultFont10)));
txt.LoadRasterFont(TBuffer.CreateFrom(@defaultFont12,length(defaultFont12)));
{$ENDIF}
size:=2+0.056*screenDPI;
defaultFont:=txt.GetFont('Default',size);
smallFont:=txt.GetFont('Default',size*0.8);
largerFont:=txt.GetFont('Default',size*1.25);
// Default checker texture
defaultTexture:=AllocImage(32,32,ipfARGB,aiTexture+aiAutoMipMap,'defaultTex');
DrawToTexture(defaultTexture);
for y:=0 to defaultTexture.height-1 do
for x:=0 to defaultTexture.width-1 do
PutPixel(x,y,$FF606060+$404040*(((x div 8) xor (y div 8)) and 1));
defaultTexture.Unlock;
//defaultTexture.SetFilter(TTexFilter.fltNearest);
// Mouse cursors
if params.showSystemCursor then begin
RegisterCursor(CursorID.Default,1,systemPlatform.GetSystemCursor(CursorID.Default));
RegisterCursor(CursorID.Link,2,systemPlatform.GetSystemCursor(CursorID.Link));
RegisterCursor(CursorID.Wait,9,systemPlatform.GetSystemCursor(CursorID.Wait));
RegisterCursor(CursorID.Input,3,systemPlatform.GetSystemCursor(CursorID.Input));
RegisterCursor(CursorID.Help,3,systemPlatform.GetSystemCursor(CursorID.Help));
RegisterCursor(CursorID.ResizeH,5,systemPlatform.GetSystemCursor(CursorID.ResizeH));
RegisterCursor(CursorID.ResizeW,5,systemPlatform.GetSystemCursor(CursorID.ResizeW));
RegisterCursor(CursorID.ResizeHW,6,systemPlatform.GetSystemCursor(CursorID.ResizeHW));
RegisterCursor(CursorID.Cross,6,systemPlatform.GetSystemCursor(CursorID.Cross));
RegisterCursor(CursorID.None,99,0);
end;
end;
procedure TGame.InitGraph;
var
baseDPI:integer;
begin
LogMessage('InitGraph');
Signal('Engine\BeforeInitGraph');
aspectRatio:=params.width/params.height;
systemPlatform.SetupWindow(params);
gfx.Init(systemPlatform);
// Choose pixel formats
gfx.config.ChoosePixelFormats(pfTrueColor,pfTrueColorAlpha,pfRenderTarget,pfRenderTargetAlpha);
LogMessage('Selected pixel formats:');
LogMessage(' TrueColor: '+PixFmt2Str(pfTrueColor));
LogMessage(' TrueColorAlpha: '+PixFmt2Str(pfTrueColorAlpha));
LogMessage(' as render target:');
LogMessage(' Opaque: '+PixFmt2Str(pfRenderTarget));
LogMessage(' Alpha: '+PixFmt2Str(pfRenderTargetAlpha));
SetVSync(params.VSync);
//
InitDefaultRenderTarget;
SetupRenderArea;
screenScale:=1.0;
if params.mode.displayScaleMode=dsmDontScale then begin
baseDPI:=96;
{$IFDEF ANDROID}
baseDPI:=192;
{$ENDIF}
{$IFDEF IOS}
baseDPI:=192;
{$ENDIF}
if screenDPI>0.95*baseDPI*1.2 then screenScale:=1.2;
if screenDPI>0.94*baseDPI*1.5 then screenScale:=1.5;
if screenDPI>0.93*baseDPI*2.0 then screenScale:=2.0;
if screenDPI>0.92*baseDPI*2.5 then screenScale:=2.5;
end;
InitDefaultResources;
globalTintColor:=$FF808080;
systemPlatform.ProcessSystemMessages;
consoleSettings.popupCriticalMessages:=params.mode.displayMode<>dmSwitchResolution;
AfterInitGraph;
end;
procedure TGame.AfterInitGraph;
begin
Signal('Engine\AfterInitGraph');
end;
procedure TGame.InitMainLoop;
begin
try
LogMessage('Init main loop');
InitGraph;
LastOnFrameTime:=MyTickCount;
LastRenderTime:=MyTickCount;
Signal('Engine\BeforeMainLoop');
LogMessage('Game is running...');
running:=true;
{$IFDEF ANDROID}
active:=true; // window is initially active
{$ENDIF}
except
on e:Exception do begin
ForceLogMessage('Error in InitMainLoop: '+ExceptionMsg(e));
ErrorMessage(ExceptionMsg(e));
running:=false;
Halt(254);
end;
end;
end;
procedure TGame.InitDefaultRenderTarget;
var
fl:boolean;
flags:cardinal;
begin
try
LogMessage('Default RT');
fl:=HasParam('-nodrt');
if fl then LogMessage('Modern rendering model disabled by -noDRT switsh');
if disableDRT then begin
fl:=true;
LogMessage('Default RT disabled');
end;
if not fl and
gfx.config.ShouldUseTextureAsDefaultRT and
(gfx.config.QueryMaxRTSize>=params.width) then begin
LogMessage('Switching to the modern rendering model');
flags:=aiRenderTarget;
if (params.zbuffer>0) and not useDepthTexture then
flags:=flags+aiDepthBuffer;
dRT:=AllocImage(params.width,params.height,pfRenderTarget,flags,'DefaultRT');
if useDepthTexture then begin
dRTdepth:=AllocImage(params.width,params.height,ipfDepth32f,aiDepthBuffer+aiRenderTarget,'DefaultDepth');
gfx.resman.AttachDepthBuffer(dRT,dRTdepth);
end;
end;
except
on e:exception do begin
ForceLogMessage('Error in GLG:IO '+ExceptionMsg(e));
ErrorMessage('Game engine failure (GLG:IO): '+ExceptionMsg(e));
Halt;
end;
end;
end;
procedure TGame.SuppressKbdEvent;
begin
suppressCharEvent:=true;
end;
procedure TGame.CreateDebugLogs;
var
i:integer;
f:text;
function SceneInfo(s:TGameScene):string;
begin
if s=nil then exit;
result:=Format(' %-20s Z=%-10d status=%-2d type=%-2d eff=%s',
[s.name,s.zorder,ord(s.status),byte(s.fullscreen),PtrToStr(s.effect)]);
if s is TUIScene then
result:=result+Format(' UI=%s (%s)',[TUIScene(s).UI.name, PtrToStr(TUIScene(s).UI)]);
end;
begin
with game do begin
crSect.Enter;
try
// Frame log
assign(f,'framelog.log');
SetTextCodePage(f,CP_UTF8);
rewrite(f);
writeln(f,'Previous:');
write(f,prevFrameLog);
writeln(f,'Current:');
write(f,FrameLog);
close(f);
// Scenes & UI log
assign(f,'UIdata.log');
SetTextCodePage(f,CP_UTF8);
rewrite(f);
writeln(f,'Scenes:');
for i:=0 to high(scenes) do writeln(f,i:3,SceneInfo(scenes[i]));
writeln(f,'Topmost scene = ',game.TopmostVisibleScene(false).name);
writeln(f,'Topmost fullscreen scene = ',game.TopmostVisibleScene(true).name);
writeln(f);
writeln(f,DumpUI);
close(f);
gfx.resman.Dump('User request');
finally
crSect.Leave;
end;
end;
end;
procedure EngineEvent(event:TEventStr;tag:TTag);
begin
if game=nil then exit;
TGame(game).onEngineEvent(event,tag);
end;
procedure EngineCmdEvent(event:TEventStr;tag:TTag);
begin
if game=nil then exit;
TGame(game).onCmdEvent(event,tag);
end;
procedure GameKbdEvent(event:TEventStr;tag:TTag);
begin
if game=nil then exit;
TGame(game).onKbdEvent(event,tag);
end;
procedure GameMouseEvent(event:TEventStr;tag:TTag);
begin
if game=nil then exit;
TGame(game).onMouseEvent(event,tag);
end;
procedure GameJoystickEvent(event:TEventStr;tag:TTag);
begin
if game=nil then exit;
TGame(game).onJoystickEvent(event,tag);
end;
procedure GameGamepadEvent(event:TEventStr;tag:TTag);
begin
if game=nil then exit;
TGame(game).onGamepadEvent(event,tag);
end;
procedure TGame.Run;
var
i:integer;
res:boolean;
begin
if running then exit;
game:=self;
gameEx:=self;
if useMainThread then begin
mainThread:=TMainThread.Create(false);
end else begin
mainThread:=nil;
SetEventHandler('Engine\Cmd',EngineCmdEvent,emQueued);
SetEventHandler('Engine\',EngineEvent,emInstant);
Signal('Engine\MainLoopInit');
end;
SetEventHandler('KBD\',GameKbdEvent,emInstant);
SetEventHandler('MOUSE\',GameMouseEvent,emInstant);
SetEventHandler('JOYSTICK\',GameJoystickEvent,emInstant);
SetEventHandler('GAMEPAD\',GameGamepadEvent,emInstant);
for i:=1 to 400 do
if not running then sleep(50) else break;
if not running then begin
ForceLogMessage('Main thread timeout');
{$IFDEF MSWINDOWS}
if TMainThread(mainThread).errormsg>'' then ErrorMessage(TMainThread(mainThread).errormsg);
{$ENDIF}
raise EFatalError.Create('Can''t run: see log for details.');
end;
end;
procedure TGame.StartVideoCap(filename: string);
begin
{$IFDEF VIDEOCAPTURE}
if videoCaptureMode then exit;
videoCaptureMode:=true;
if pos('\',filename)=0 then filename:=videoCapturePath+filename;