1 (* Copyright (C) Doom 2D: Forever Developers
3 * This program is free software: you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation, either version 3 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 {$INCLUDE ../shared/a_modes.inc}
24 function SDLMain (): Integer;
25 function GetTimer (): Int64;
26 procedure ResetTimer ();
27 procedure PushExitEvent ();
28 function ProcessMessage (): Boolean;
29 procedure ReDrawWindow ();
30 procedure SwapBuffers ();
31 procedure Sleep (ms
: LongWord);
32 function GetDisplayModes (dbpp
: LongWord; var selres
: LongWord): SSArray
;
33 function g_Window_SetDisplay (preserveGL
: Boolean=false): Boolean;
34 function g_Window_SetSize (w
, h
: Word; fullscreen
: Boolean): Boolean;
36 procedure ProcessLoading (forceUpdate
: Boolean=false);
38 // returns `true` if quit event was received
39 function g_ProcessMessages (): Boolean;
43 gwin_dump_extensions
: Boolean = false;
44 gwin_has_stencil
: Boolean = false;
45 gwin_k8_enable_light_experiments
: Boolean = false;
46 g_dbg_aimline_on
: Boolean = false;
52 {$IFDEF WINDOWS}Windows
,{$ENDIF}
53 SysUtils
, Classes
, MAPDEF
,
54 SDL2
, GL
, GLExt
, e_graphics
, e_log
, e_texture
, g_main
,
55 g_console
, e_input
, g_options
, g_game
,
56 g_basic
, g_textures
, e_sound
, g_sound
, g_menu
, ENet
, g_net
,
57 g_map
, g_gfx
, g_monsters
, g_holmes
, xprofiler
,
62 ProgressUpdateMSecs
= 1;//100;
65 h_Wnd
: PSDL_Window
= nil;
66 h_GL
: TSDL_GLContext
= nil;
67 Time
, Time_Delta
, Time_Old
: Int64;
69 {$IF not DEFINED(HEADLESS)}
72 wNeedTimeReset
: Boolean = false;
73 wMinimized
: Boolean = false;
74 wLoadingProgress
: Boolean = false;
75 wLoadingQuit
: Boolean = false;
77 ticksOverflow
: Int64 = -1;
78 lastTicks
: Uint32
= 0; // to detect overflow
82 procedure KillGLWindow (preserveGL
: Boolean);
84 if (h_GL
<> nil) and (not preserveGL
) then begin if (assigned(oglDeinitCB
)) then oglDeinitCB(); end;
85 if (h_Wnd
<> nil) then SDL_DestroyWindow(h_Wnd
);
86 if (h_GL
<> nil) and (not preserveGL
) then SDL_GL_DeleteContext(h_GL
);
88 if (not preserveGL
) then h_GL
:= nil;
92 function g_Window_SetDisplay (preserveGL
: Boolean = false): Boolean;
93 {$IF not DEFINED(HEADLESS)}
95 mode
, cmode
: TSDL_DisplayMode
;
100 {$IF not DEFINED(HEADLESS)}
103 e_WriteLog('Setting display mode...', TMsgType
.Notify
);
105 wFlags
:= SDL_WINDOW_OPENGL
; // or SDL_WINDOW_RESIZABLE;
106 if gFullscreen
then wFlags
:= wFlags
or SDL_WINDOW_FULLSCREEN
or SDL_WINDOW_BORDERLESS
else wFlags
:= wFlags
or SDL_WINDOW_RESIZABLE
;
107 //if gWinMaximized then wFlags := wFlags or SDL_WINDOW_MAXIMIZED;
111 mode
.w
:= gScreenWidth
;
112 mode
.h
:= gScreenHeight
;
114 mode
.refresh_rate
:= 0;
115 mode
.driverdata
:= nil;
116 if (SDL_GetClosestDisplayMode(0, @mode
, @cmode
) = nil) then
118 e_WriteLog('SDL: cannot find display mode for '+IntToStr(gScreenWidth
), TMsgType
.Notify
);
120 gScreenHeight
:= 600;
124 e_WriteLog('SDL: found display mode for '+IntToStr(gScreenWidth
)+'x'+IntToStr(gScreenHeight
)+': '+IntToStr(cmode
.w
)+'x'+IntToStr(cmode
.h
), TMsgType
.Notify
);
125 gScreenWidth
:= cmode
.w
;
126 gScreenHeight
:= cmode
.h
;
130 KillGLWindow(preserveGL
);
132 h_Wnd
:= SDL_CreateWindow(PChar(wTitle
), gWinRealPosX
, gWinRealPosY
, gScreenWidth
, gScreenHeight
, wFlags
);
133 if (h_Wnd
= nil) then exit
;
135 SDL_GL_MakeCurrent(h_Wnd
, h_GL
);
136 SDL_ShowCursor(SDL_DISABLE
);
137 if (gFullscreen
) then
141 SDL_GetWindowSize(h_Wnd
, @nw
, @nh
);
142 if (nw
> 128) and (nh
> 128) then
144 e_WriteLog('SDL: fullscreen window got size '+IntToStr(nw
)+'x'+IntToStr(nh
)+': '+IntToStr(gScreenWidth
)+'x'+IntToStr(gScreenHeight
), TMsgType
.Notify
);
150 e_WriteLog('SDL: fullscreen window got invalid size: '+IntToStr(nw
)+'x'+IntToStr(nh
), TMsgType
.Notify
);
153 fuiScrWdt
:= gScreenWidth
;
154 fuiScrHgt
:= gScreenHeight
;
155 if (h_GL
<> nil) and (not preserveGL
) then begin if (assigned(oglInitCB
)) then oglInitCB(); end;
162 function GetDisplayModes (dbpp
: LongWord; var selres
: LongWord): SSArray
;
164 mode
: TSDL_DisplayMode
;
165 res
, i
, k
, n
, pw
, ph
: Integer;
167 SetLength(result
, 0);
168 {$IFDEF HEADLESS}exit
;{$ENDIF}
170 n
:= SDL_GetNumDisplayModes(0);
174 res
:= SDL_GetDisplayMode(0, i
, @mode
);
175 if res
< 0 then continue
;
176 if SDL_BITSPERPIXEL(mode
.format
) = gBPP
then continue
;
177 if (mode
.w
= pw
) and (mode
.h
= ph
) then continue
;
178 if (mode
.w
= gScreenWidth
) and (mode
.h
= gScreenHeight
) then
181 SetLength(result
, k
);
182 result
[k
-1] := IntToStr(mode
.w
) + 'x' + IntToStr(mode
.h
);
183 pw
:= mode
.w
; ph
:= mode
.h
186 e_WriteLog('SDL: Got ' + IntToStr(k
) + ' resolutions.', TMsgType
.Notify
);
190 procedure Sleep (ms
: LongWord);
196 procedure ChangeWindowSize ();
198 gWinSizeX
:= gScreenWidth
;
199 gWinSizeY
:= gScreenHeight
;
200 {$IF not DEFINED(HEADLESS)}
201 fuiScrWdt
:= gScreenWidth
;
202 fuiScrHgt
:= gScreenHeight
;
203 e_ResizeWindow(gScreenWidth
, gScreenHeight
);
204 g_Game_SetupScreenSize();
206 g_Game_ClearLoading();
211 function g_Window_SetSize (w
, h
: Word; fullscreen
: Boolean): Boolean;
212 {$IF not DEFINED(HEADLESS)}
218 {$IF not DEFINED(HEADLESS)}
221 if (gScreenWidth
<> w
) or (gScreenHeight
<> h
) then
229 if (gFullscreen
<> fullscreen
) then
233 gFullscreen
:= fullscreen
;
239 g_Window_SetDisplay(preserve
);
246 function WindowEventHandler (constref ev
: TSDL_WindowEvent
): Boolean;
248 wActivate
, wDeactivate
: Boolean;
252 wDeactivate
:= false;
255 SDL_WINDOWEVENT_MOVED
:
257 if not (gFullscreen
or gWinMaximized
) then
259 gWinRealPosX
:= ev
.data1
;
260 gWinRealPosY
:= ev
.data2
;
264 SDL_WINDOWEVENT_MINIMIZED
:
267 if not wMinimized
then
269 e_ResizeWindow(0, 0);
271 if g_debug_WinMsgs
then
273 g_Console_Add('Now minimized');
274 e_WriteLog('[DEBUG] WinMsgs: Now minimized', TMsgType
.Notify
);
280 SDL_WINDOWEVENT_RESIZED
:
282 gScreenWidth
:= ev
.data1
;
283 gScreenHeight
:= ev
.data2
;
286 if g_debug_WinMsgs
then
288 g_Console_Add('Resized to ' + IntToStr(ev
.data1
) + 'x' + IntToStr(ev
.data2
));
289 e_WriteLog('[DEBUG] WinMsgs: Resized to ' + IntToStr(ev
.data1
) + 'x' + IntToStr(ev
.data2
), TMsgType
.Notify
);
293 SDL_WINDOWEVENT_EXPOSED
:
296 SDL_WINDOWEVENT_MAXIMIZED
:
300 e_ResizeWindow(gScreenWidth
, gScreenHeight
);
304 if not gWinMaximized
then
306 gWinMaximized
:= true;
307 if g_debug_WinMsgs
then
309 g_Console_Add('Now maximized');
310 e_WriteLog('[DEBUG] WinMsgs: Now maximized', TMsgType
.Notify
);
315 SDL_WINDOWEVENT_RESTORED
:
319 e_ResizeWindow(gScreenWidth
, gScreenHeight
);
323 if gWinMaximized
then gWinMaximized
:= false;
324 if g_debug_WinMsgs
then
326 g_Console_Add('Now restored');
327 e_WriteLog('[DEBUG] WinMsgs: Now restored', TMsgType
.Notify
);
331 SDL_WINDOWEVENT_FOCUS_GAINED
:
334 //e_WriteLog('window gained focus!', MSG_NOTIFY);
337 SDL_WINDOWEVENT_FOCUS_LOST
:
341 //e_WriteLog('window lost focus!', MSG_NOTIFY);
349 e_WriteLog('deactivating window', TMsgType
.Notify
);
350 e_EnableInput
:= false;
351 e_ClearInputBuffer();
353 if gMuteWhenInactive
then
355 //e_WriteLog('deactivating sounds', MSG_NOTIFY);
356 e_MuteChannels(true);
359 if g_debug_WinMsgs
then
361 g_Console_Add('Now inactive');
362 e_WriteLog('[DEBUG] WinMsgs: Now inactive', TMsgType
.Notify
);
367 if assigned(winBlurCB
) then winBlurCB();
370 else if wActivate
then
372 if not gWinActive
then
374 //e_WriteLog('activating window', MSG_NOTIFY);
375 e_EnableInput
:= true;
377 if gMuteWhenInactive
then
379 //e_WriteLog('activating sounds', MSG_NOTIFY);
380 e_MuteChannels(false);
383 if g_debug_WinMsgs
then
385 g_Console_Add('Now active');
386 e_WriteLog('[DEBUG] WinMsgs: Now active', TMsgType
.Notify
);
390 if assigned(winFocusCB
) then winFocusCB();
396 function EventHandler (var ev
: TSDL_Event
): Boolean;
406 result
:= WindowEventHandler(ev
.window
);
410 if (gExit
<> EXIT_QUIT
) then
412 if not wLoadingProgress
then
419 wLoadingQuit
:= true;
425 SDL_KEYDOWN
, SDL_KEYUP
:
427 key
:= ev
.key
.keysym
.scancode
;
428 down
:= (ev
.type_
= SDL_KEYDOWN
);
429 {$IF not DEFINED(HEADLESS)}
430 if fuiOnSDLEvent(ev
) then
432 // event eaten, but...
433 if not down
then e_KeyUpDown(key
, false);
437 if down
then KeyPress(key
);
438 e_KeyUpDown(key
, down
);
441 {$IF not DEFINED(HEADLESS)}
442 SDL_MOUSEBUTTONDOWN
, SDL_MOUSEBUTTONUP
, SDL_MOUSEWHEEL
, SDL_MOUSEMOTION
:
448 Utf8ToUnicode(@uc
, PChar(ev
.text.text), 1);
450 if (keychr
> 127) then keychr
:= Word(wchar2win(WideChar(keychr
)));
451 if (keychr
> 0) and (keychr
<= 255) then CharPress(AnsiChar(keychr
));
454 // other key presses and joysticks are handled in e_input
459 procedure SwapBuffers ();
461 {$IF not DEFINED(HEADLESS)}
462 SDL_GL_SwapWindow(h_Wnd
);
467 function CreateGLWindow (Title
: PChar): Boolean;
471 gWinSizeX
:= gScreenWidth
;
472 gWinSizeY
:= gScreenHeight
;
474 {$IF not DEFINED(HEADLESS)}
477 e_WriteLog('Creating window', TMsgType
.Notify
);
479 if not g_Window_SetDisplay() then
482 e_WriteLog('Window creation error (resolution not supported?)', TMsgType
.Fatal
);
486 {$IF not DEFINED(HEADLESS)}
487 h_GL
:= SDL_GL_CreateContext(h_Wnd
);
488 if (h_GL
= nil) then exit
;
489 fuiScrWdt
:= gScreenWidth
;
490 fuiScrHgt
:= gScreenHeight
;
491 if (assigned(oglInitCB
)) then oglInitCB();
494 e_ResizeWindow(gScreenWidth
, gScreenHeight
);
502 // windoze sux; in headless mode `GetTickCount()` (and SDL) returns shit
503 function GetTimer (): Int64;
507 QueryPerformanceFrequency(F
);
508 QueryPerformanceCounter(C
);
509 result
:= Round(C
/F
*1000{000});
512 function GetTimer (): Int64;
518 if (ticksOverflow
= -1) then
525 if (lastTicks
> t
) then
527 // overflow, increment overflow ;-)
528 ticksOverflow
:= ticksOverflow
+(Int64($ffffffff)+Int64(1));
529 tt
:= (Int64($ffffffff)+Int64(1))+Int64(t
);
530 t
:= Uint32(tt
-lastTicks
);
534 result
:= ticksOverflow
+Int64(t
);
539 procedure ResetTimer ();
541 wNeedTimeReset
:= true;
545 procedure PushExitEvent ();
549 ev
.type_
:= SDL_QUITEV
;
555 prevLoadingUpdateTime
: UInt64 = 0;
557 procedure ProcessLoading (forceUpdate
: Boolean=false);
563 FillChar(ev
, sizeof(ev
), 0);
564 wLoadingProgress
:= true;
566 while (SDL_PollEvent(@ev
) > 0) do
569 if (ev
.type_
= SDL_QUITEV
) then break
;
573 if (ev
.type_
= SDL_QUITEV
) or (gExit
= EXIT_QUIT
) then
575 wLoadingProgress
:= false;
579 if not wMinimized
then
583 prevLoadingUpdateTime
:= getTimeMilli();
587 stt
:= getTimeMilli();
588 if (stt
< prevLoadingUpdateTime
) or (stt
-prevLoadingUpdateTime
>= ProgressUpdateMSecs
) then
590 prevLoadingUpdateTime
:= stt
;
597 if g_Texture_Get('INTER', ID
) then
599 e_DrawSize(ID
, 0, 0, 0, false, false, gScreenWidth
, gScreenHeight
);
600 e_DarkenQuadWH(0, 0, gScreenWidth
, gScreenHeight
, 150);
604 e_Clear(GL_COLOR_BUFFER_BIT
, 0, 0, 0);
614 if NetMode
= NET_SERVER
then
620 if (NetMode
= NET_CLIENT
) and (NetState
<> NET_STATE_AUTH
) then g_Net_Client_UpdateWhileLoading();
623 wLoadingProgress
:= false;
627 function g_ProcessMessages (): Boolean;
632 FillChar(ev
, SizeOf(ev
), 0);
633 while (SDL_PollEvent(@ev
) > 0) do
635 result
:= EventHandler(ev
);
636 if (ev
.type_
= SDL_QUITEV
) then exit
;
642 function ProcessMessage (): Boolean;
646 result
:= g_ProcessMessages();
649 Time_Delta
:= Time
-Time_Old
;
653 if wNeedTimeReset
then
656 wNeedTimeReset
:= false;
659 g_Map_ProfilersBegin();
660 g_Mons_ProfilersBegin();
662 t
:= Time_Delta
div 28;
668 if (NetMode
= NET_SERVER
) then g_Net_Host_Update()
669 else if (NetMode
= NET_CLIENT
) then g_Net_Client_Update();
675 if (NetMode
= NET_SERVER
) then g_Net_Host_Update()
676 else if (NetMode
= NET_CLIENT
) then g_Net_Client_Update();
679 g_Map_ProfilersEnd();
680 g_Mons_ProfilersEnd();
688 if (gExit
= EXIT_QUIT
) then
694 // Âðåìÿ ïðåäûäóùåãî îáíîâëåíèÿ
697 Time_Old
:= Time
-(Time_Delta
mod 28);
698 if (not wMinimized
) then
706 Sleep(1); // release time slice, so we won't eat 100% CPU
713 procedure ReDrawWindow ();
719 procedure InitOpenGL (vsync
: Boolean);
720 {$IF not DEFINED(HEADLESS)}
725 {$IF not DEFINED(HEADLESS)}
726 if vsync
then v
:= 1 else v
:= 0;
727 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION
, 2);
728 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION
, 1);
729 SDL_GL_SetAttribute(SDL_GL_RED_SIZE
, 8);
730 SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE
, 8);
731 SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE
, 8);
732 SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE
, 16);
733 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER
, 1);
734 SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE
, 8); // lights; it is enough to have 1-bit stencil buffer for lighting, but...
735 SDL_GL_SetSwapInterval(v
);
740 function glHasExtension (const name
: AnsiString): Boolean;
745 extName
: ShortString;
748 if (Length(name
) = 0) then exit
;
749 exts
:= glGetString(GL_EXTENSIONS
);
750 if (exts
= nil) then exit
;
751 while (exts
[0] <> #0) and (exts
[0] = ' ') do Inc(exts
);
752 while (exts
[0] <> #0) do
754 if gwin_dump_extensions
then
757 while (exts
[i
] <> #0) and (exts
[i
] <> ' ') do Inc(i
);
760 e_WriteLog('FUUUUUUUUUUUUU', TMsgType
.Warning
);
764 Move(exts
^, extName
[1], i
);
765 extName
[0] := Char(i
);
766 e_WriteLog(Format('EXT: %s', [extName
]), TMsgType
.Notify
);
770 for i
:= 0 to length(name
)-1 do
772 if (exts
[i
] = #0) then begin found
:= false; break
; end;
773 if (exts
[i
] <> name
[i
+1]) then begin found
:= false; break
; end;
775 if found
and ((exts
[Length(name
)] = #0) or (exts
[Length(name
)] = ' ')) then begin result
:= true; exit
; end;
776 while (exts
[0] <> #0) and (exts
[0] <> ' ') do Inc(exts
);
777 while (exts
[0] <> #0) and (exts
[0] = ' ') do Inc(exts
);
782 function SDLMain (): Integer;
785 {$IF not DEFINED(HEADLESS)}
794 e_NoGraphics
:= true;
796 if (not g_holmes_imfunctional
) then
799 uiContext
.font
:= 'win14';
804 while (idx
<= ParamCount
) do
806 arg
:= ParamStr(idx
);
808 if arg
= '--opengl-dump-exts' then gwin_dump_extensions
:= true;
809 //if arg = '--twinkletwinkle' then gwin_k8_enable_light_experiments := true;
810 if arg
= '--jah' then g_profile_history_size
:= 100;
811 if arg
= '--no-particles' then gpart_dbg_enabled
:= false;
812 if arg
= '--no-los' then gmon_dbg_los_enabled
:= false;
814 if arg
= '--profile-render' then g_profile_frame_draw
:= true;
815 if arg
= '--profile-coldet' then g_profile_collision
:= true;
816 if arg
= '--profile-los' then g_profile_los
:= true;
818 if arg
= '--no-part-phys' then gpart_dbg_phys_enabled
:= false;
819 if arg
= '--no-part-physics' then gpart_dbg_phys_enabled
:= false;
820 if arg
= '--no-particles-phys' then gpart_dbg_phys_enabled
:= false;
821 if arg
= '--no-particles-physics' then gpart_dbg_phys_enabled
:= false;
822 if arg
= '--no-particle-phys' then gpart_dbg_phys_enabled
:= false;
823 if arg
= '--no-particle-physics' then gpart_dbg_phys_enabled
:= false;
825 {.$IF DEFINED(D2F_DEBUG)}
826 if arg
= '--aimline' then g_dbg_aimline_on
:= true;
829 if arg
= '--holmes' then begin g_holmes_enabled
:= true; g_Game_SetDebugMode(); end;
831 if (arg
= '--holmes-ui-scale') or (arg
= '-holmes-ui-scale') then
833 if (idx
<= ParamCount
) then
835 if not conParseFloat(fuiRenderScale
, ParamStr(idx
)) then fuiRenderScale
:= 1.0;
840 if (arg
= '--holmes-font') or (arg
= '-holmes-font') then
842 if (idx
<= ParamCount
) then
845 val(ParamStr(idx
), itmp
, valres
);
847 if (valres
= 0) and (not g_holmes_imfunctional
) then
850 8: uiContext
.font
:= 'win8';
851 14: uiContext
.font
:= 'win14';
852 16: uiContext
.font
:= 'win16';
864 if (arg
= '--game-scale') or (arg
= '-game-scale') then
866 if (idx
<= ParamCount
) then
868 if not conParseFloat(g_dbg_scale
, ParamStr(idx
)) then g_dbg_scale
:= 1.0;
873 if (arg
= '--write-mapdef') or (arg
= '-write-mapdef') then
875 mdfo
:= createDiskFile('mapdef.txt');
876 mdfo
.WriteBuffer(defaultMapDef
[1], Length(defaultMapDef
));
882 e_WriteLog('Initializing OpenGL', TMsgType
.Notify
);
885 e_WriteLog('Creating GL window', TMsgType
.Notify
);
886 if not CreateGLWindow(PChar(Format('Doom 2D: Forever %s', [GAME_VERSION
]))) then
892 {EnumDisplayModes();}
895 //gwin_k8_enable_light_experiments := false;
896 gwin_has_stencil
:= false;
897 glLegacyNPOT
:= false;
898 gwin_dump_extensions
:= false;
900 SDL_GL_GetAttribute(SDL_GL_STENCIL_SIZE
, @ltmp
);
901 e_LogWritefln('stencil buffer size: %s', [ltmp
]);
902 gwin_has_stencil
:= (ltmp
> 0);
904 if not glHasExtension('GL_ARB_texture_non_power_of_two') then
906 e_WriteLog('NPOT textures: NO', TMsgType
.Warning
);
907 glLegacyNPOT
:= true;
911 e_WriteLog('NPOT textures: YES', TMsgType
.Notify
);
912 glLegacyNPOT
:= false;
914 gwin_dump_extensions
:= false;
918 Time_Old
:= GetTimer();
921 if (ParamCount
> 0) then g_Game_Process_Params();
924 if (not gGameOn
) and gAskLanguage
then g_Menu_AskLanguage();
926 e_WriteLog('Entering the main loop', TMsgType
.Notify
);
929 while not ProcessMessage() do begin end;