DEADSOFTWARE

5689ceb04d822cf81896f28629ec50ee6a58f23f
[d2df-sdl.git] / src / game / g_window.pas
1 (* Copyright (C) Doom 2D: Forever Developers
2 *
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.
7 *
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.
12 *
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/>.
15 *)
16 {$INCLUDE ../shared/a_modes.inc}
17 unit g_window;
19 interface
21 uses
22 utils;
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;
35 procedure g_SetVSync (vsync: Boolean);
37 procedure ProcessLoading (forceUpdate: Boolean=false);
39 // returns `true` if quit event was received
40 function g_ProcessMessages (): Boolean;
43 var
44 gwin_dump_extensions: Boolean = false;
45 gwin_has_stencil: Boolean = false;
46 gwin_k8_enable_light_experiments: Boolean = false;
47 g_dbg_aimline_on: Boolean = false;
50 implementation
52 uses
53 {$IFDEF WINDOWS}Windows,{$ENDIF}
54 {$INCLUDE ../nogl/noGLuses.inc}
55 {$IFDEF ENABLE_HOLMES}
56 g_holmes, sdlcarcass, fui_ctls,
57 {$ENDIF}
58 SysUtils, Classes, MAPDEF,
59 SDL2, e_graphics, e_log, e_texture, g_main,
60 g_console, e_input, g_options, g_game,
61 g_basic, g_textures, e_sound, g_sound, g_menu, ENet, g_net,
62 g_map, g_gfx, g_monsters, xprofiler,
63 g_touch;
66 const
67 ProgressUpdateMSecs = 1;//100;
69 var
70 h_Wnd: PSDL_Window = nil;
71 h_GL: TSDL_GLContext = nil;
72 Time, Time_Delta, Time_Old: Int64;
73 flag: Boolean;
74 {$IF not DEFINED(HEADLESS)}
75 wTitle: PChar = nil;
76 wasFullscreen: Boolean = true; // so we need to recreate the window
77 {$ENDIF}
78 wNeedTimeReset: Boolean = false;
79 wMinimized: Boolean = false;
80 wMaximized: Boolean = false;
81 wLoadingProgress: Boolean = false;
82 wLoadingQuit: Boolean = false;
83 {$IFNDEF WINDOWS}
84 ticksOverflow: Int64 = -1;
85 lastTicks: Uint32 = 0; // to detect overflow
86 {$ENDIF}
87 JoystickHatState: array [0..e_MaxJoyHats, HAT_LEFT..HAT_DOWN] of Boolean;
89 procedure KillGLWindow (preserveGL: Boolean);
90 begin
91 {$IFDEF ENABLE_HOLMES}
92 if (h_GL <> nil) and (not preserveGL) then begin if (assigned(oglDeinitCB)) then oglDeinitCB(); end;
93 {$ENDIF}
94 if (h_Wnd <> nil) then SDL_DestroyWindow(h_Wnd);
95 if (h_GL <> nil) and (not preserveGL) then
96 begin
98 {$IFDEF USE_NANOGL}
99 nanoGL_Destroy;
100 {$ENDIF}
102 {$IFDEF USE_NOGL}
103 nogl_Quit;
104 {$ENDIF}
106 SDL_GL_DeleteContext(h_GL);
107 end;
108 h_Wnd := nil;
109 if (not preserveGL) then h_GL := nil;
110 end;
113 function g_Window_SetDisplay (preserveGL: Boolean = false): Boolean;
114 {$IF not DEFINED(HEADLESS)}
115 var
116 mode, cmode: TSDL_DisplayMode;
117 wFlags: LongWord = 0;
118 nw, nh: Integer;
119 {$ENDIF}
120 begin
121 {$IF not DEFINED(HEADLESS)}
122 result := false;
124 e_WriteLog('Setting display mode...', TMsgType.Notify);
126 wFlags := SDL_WINDOW_OPENGL {or SDL_WINDOW_RESIZABLE};
127 if gFullscreen then wFlags := wFlags {or SDL_WINDOW_FULLSCREEN} else wFlags := wFlags or SDL_WINDOW_RESIZABLE;
128 if (not gFullscreen) and (not preserveGL) and gWinMaximized then wFlags := wFlags or SDL_WINDOW_MAXIMIZED else gWinMaximized := false;
130 if gFullscreen then
131 begin
132 mode.w := gScreenWidth;
133 mode.h := gScreenHeight;
134 mode.format := 0;
135 mode.refresh_rate := 0;
136 mode.driverdata := nil;
137 if (SDL_GetClosestDisplayMode(0, @mode, @cmode) = nil) then
138 begin
139 e_WriteLog('SDL: cannot find display mode for '+IntToStr(gScreenWidth), TMsgType.Notify);
140 gScreenWidth := 800;
141 gScreenHeight := 600;
142 end
143 else
144 begin
145 e_WriteLog('SDL: found display mode for '+IntToStr(gScreenWidth)+'x'+IntToStr(gScreenHeight)+': '+IntToStr(cmode.w)+'x'+IntToStr(cmode.h), TMsgType.Notify);
146 gScreenWidth := cmode.w;
147 gScreenHeight := cmode.h;
148 end;
149 end;
151 if (preserveGL) and (h_Wnd <> nil) and (not gFullscreen) and (not wasFullscreen) then
152 begin
153 //SDL_SetWindowMaximumSize(h_Wnd, gScreenWidth, gScreenHeight);
154 //SDL_SetWindowDisplayMode(h_Wnd, @cmode);
155 if (wMaximized) then SDL_RestoreWindow(h_Wnd);
156 wMaximized := false;
157 gWinMaximized := false;
158 SDL_SetWindowSize(h_Wnd, gScreenWidth, gScreenHeight);
159 //SDL_SetWindowFullscreen(h_Wnd, SDL_WINDOW_FULLSCREEN);
160 //SDL_SetWindowFullscreen(h_Wnd, 0);
161 end
162 else
163 begin
164 KillGLWindow(preserveGL);
165 h_Wnd := SDL_CreateWindow(PChar(wTitle), gWinRealPosX, gWinRealPosY, gScreenWidth, gScreenHeight, wFlags);
166 if gFullscreen then
167 SDL_SetWindowFullscreen(h_Wnd, SDL_WINDOW_FULLSCREEN);
168 if (h_Wnd = nil) then exit;
169 end;
170 wasFullscreen := gFullscreen;
172 SDL_GL_MakeCurrent(h_Wnd, h_GL);
173 SDL_ShowCursor(SDL_DISABLE);
174 if (h_GL <> nil) then g_SetVSync(gVSync);
175 if (gFullscreen) then
176 begin
177 nw := 0;
178 nh := 0;
179 SDL_GetWindowSize(h_Wnd, @nw, @nh);
180 if (nw > 128) and (nh > 128) then
181 begin
182 e_WriteLog('SDL: fullscreen window got size '+IntToStr(nw)+'x'+IntToStr(nh)+': '+IntToStr(gScreenWidth)+'x'+IntToStr(gScreenHeight), TMsgType.Notify);
183 gScreenWidth := nw;
184 gScreenHeight := nh;
185 end
186 else
187 begin
188 e_WriteLog('SDL: fullscreen window got invalid size: '+IntToStr(nw)+'x'+IntToStr(nh), TMsgType.Notify);
189 end;
190 end;
192 {$IFDEF ENABLE_HOLMES}
193 fuiScrWdt := gScreenWidth;
194 fuiScrHgt := gScreenHeight;
195 if (h_GL <> nil) and (not preserveGL) then begin if (assigned(oglInitCB)) then oglInitCB(); end;
196 {$ENDIF}
197 {$ENDIF}
199 result := true;
200 end;
203 function GetDisplayModes (dbpp: LongWord; var selres: LongWord): SSArray;
204 var
205 mode: TSDL_DisplayMode;
206 res, i, k, n, pw, ph: Integer;
207 begin
208 SetLength(result, 0);
209 {$IFDEF HEADLESS}exit;{$ENDIF}
210 k := 0; selres := 0;
211 n := SDL_GetNumDisplayModes(0);
212 pw := 0; ph := 0;
213 for i := 0 to n do
214 begin
215 res := SDL_GetDisplayMode(0, i, @mode);
216 if res < 0 then continue;
217 if SDL_BITSPERPIXEL(mode.format) = gBPP then continue;
218 if (mode.w = pw) and (mode.h = ph) then continue;
219 if (mode.w = gScreenWidth) and (mode.h = gScreenHeight) then
220 selres := k;
221 Inc(k);
222 SetLength(result, k);
223 result[k-1] := IntToStr(mode.w) + 'x' + IntToStr(mode.h);
224 pw := mode.w; ph := mode.h
225 end;
227 e_WriteLog('SDL: Got ' + IntToStr(k) + ' resolutions.', TMsgType.Notify);
228 end;
231 procedure Sleep (ms: LongWord);
232 begin
233 SDL_Delay(ms);
234 end;
237 procedure ChangeWindowSize (requested: Boolean);
238 begin
239 e_LogWritefln(' ChangeWindowSize: (ws=%dx%d) (ss=%dx%d)', [gWinSizeX, gWinSizeY, gScreenWidth, gScreenHeight]);
240 gWinSizeX := gScreenWidth;
241 gWinSizeY := gScreenHeight;
242 {$IF not DEFINED(HEADLESS)}
243 {$IFDEF ENABLE_HOLMES}
244 fuiScrWdt := gScreenWidth;
245 fuiScrHgt := gScreenHeight;
246 {$ENDIF}
247 e_ResizeWindow(gScreenWidth, gScreenHeight);
248 g_Game_SetupScreenSize();
249 {$IF DEFINED(ANDROID)}
250 (* This will fix menu reset on keyboard showing *)
251 if requested then
252 g_Menu_Reset;
253 {$ELSE}
254 g_Menu_Reset;
255 {$ENDIF}
256 g_Game_ClearLoading();
257 {$ENDIF}
258 end;
261 function g_Window_SetSize (w, h: Word; fullscreen: Boolean): Boolean;
262 {$IF not DEFINED(HEADLESS)}
263 var
264 preserve: Boolean;
265 {$ENDIF}
266 begin
267 result := false;
268 {$IF not DEFINED(HEADLESS)}
269 preserve := false;
271 if (gScreenWidth <> w) or (gScreenHeight <> h) then
272 begin
273 result := true;
274 preserve := true;
275 gScreenWidth := w;
276 gScreenHeight := h;
277 end;
279 if (gFullscreen <> fullscreen) then
280 begin
281 result := true;
282 preserve := true;
283 gFullscreen := fullscreen;
284 preserve := true;
285 end;
287 if result then
288 begin
289 g_Window_SetDisplay(preserve);
290 ChangeWindowSize(true);
291 end;
292 {$ENDIF}
293 end;
296 function WindowEventHandler (constref ev: TSDL_WindowEvent): Boolean;
297 var
298 wActivate, wDeactivate: Boolean;
299 begin
300 result := false;
301 wActivate := false;
302 wDeactivate := false;
304 case ev.event of
305 SDL_WINDOWEVENT_MOVED:
306 begin
307 if not (gFullscreen or gWinMaximized) then
308 begin
309 gWinRealPosX := ev.data1;
310 gWinRealPosY := ev.data2;
311 end;
312 end;
314 SDL_WINDOWEVENT_MINIMIZED:
315 begin
316 e_UnpressAllKeys();
317 if not wMinimized then
318 begin
319 e_ResizeWindow(0, 0);
320 wMinimized := true;
321 if g_debug_WinMsgs then
322 begin
323 g_Console_Add('Now minimized');
324 e_WriteLog('[DEBUG] WinMsgs: Now minimized', TMsgType.Notify);
325 end;
326 wDeactivate := true;
327 end;
328 end;
330 SDL_WINDOWEVENT_RESIZED:
331 begin
332 e_LogWritefln('Resize: (os=%dx%d) (ns=%dx%d)', [gScreenWidth, gScreenHeight, Integer(ev.data1), Integer(ev.data2)]);
333 {if (gFullscreen) then
334 begin
335 e_LogWriteln(' fullscreen fix applied.');
336 if (gScreenWidth <> ev.data1) or (gScreenHeight <> ev.data2) then
337 begin
338 SDL_SetWindowSize(h_Wnd, gScreenWidth, gScreenHeight);
339 end;
340 end
341 else}
342 begin
343 gScreenWidth := ev.data1;
344 gScreenHeight := ev.data2;
345 end;
346 ChangeWindowSize(false);
347 SwapBuffers();
348 if g_debug_WinMsgs then
349 begin
350 g_Console_Add('Resized to ' + IntToStr(ev.data1) + 'x' + IntToStr(ev.data2));
351 e_WriteLog('[DEBUG] WinMsgs: Resized to ' + IntToStr(ev.data1) + 'x' + IntToStr(ev.data2), TMsgType.Notify);
352 end;
353 end;
355 SDL_WINDOWEVENT_EXPOSED:
356 SwapBuffers();
358 SDL_WINDOWEVENT_MAXIMIZED:
359 begin
360 wMaximized := true;
361 if wMinimized then
362 begin
363 e_ResizeWindow(gScreenWidth, gScreenHeight);
364 wMinimized := false;
365 wActivate := true;
366 end;
367 if (not gWinMaximized) and (not gFullscreen) then
368 begin
369 gWinMaximized := true;
370 if g_debug_WinMsgs then
371 begin
372 g_Console_Add('Now maximized');
373 e_WriteLog('[DEBUG] WinMsgs: Now maximized', TMsgType.Notify);
374 end;
375 end;
376 end;
378 SDL_WINDOWEVENT_RESTORED:
379 begin
380 wMaximized := false;
381 if wMinimized then
382 begin
383 e_ResizeWindow(gScreenWidth, gScreenHeight);
384 wMinimized := false;
385 wActivate := true;
386 end;
387 gWinMaximized := false;
388 if g_debug_WinMsgs then
389 begin
390 g_Console_Add('Now restored');
391 e_WriteLog('[DEBUG] WinMsgs: Now restored', TMsgType.Notify);
392 end;
393 end;
395 SDL_WINDOWEVENT_FOCUS_GAINED:
396 begin
397 wActivate := true;
398 //e_WriteLog('window gained focus!', MSG_NOTIFY);
399 end;
401 SDL_WINDOWEVENT_FOCUS_LOST:
402 begin
403 wDeactivate := true;
404 e_UnpressAllKeys();
405 //e_WriteLog('window lost focus!', MSG_NOTIFY);
406 end;
407 end;
409 if wDeactivate then
410 begin
411 if gWinActive then
412 begin
413 e_WriteLog('deactivating window', TMsgType.Notify);
414 e_EnableInput := false;
415 e_ClearInputBuffer();
417 if gMuteWhenInactive then
418 begin
419 //e_WriteLog('deactivating sounds', MSG_NOTIFY);
420 e_MuteChannels(true);
421 end;
423 if g_debug_WinMsgs then
424 begin
425 g_Console_Add('Now inactive');
426 e_WriteLog('[DEBUG] WinMsgs: Now inactive', TMsgType.Notify);
427 end;
429 gWinActive := false;
431 {$IFDEF ENABLE_HOLMES}
432 if assigned(winBlurCB) then winBlurCB();
433 {$ENDIF}
434 end;
435 end
436 else if wActivate then
437 begin
438 if not gWinActive then
439 begin
440 //e_WriteLog('activating window', MSG_NOTIFY);
441 e_EnableInput := true;
443 if gMuteWhenInactive then
444 begin
445 //e_WriteLog('activating sounds', MSG_NOTIFY);
446 e_MuteChannels(false);
447 end;
449 if g_debug_WinMsgs then
450 begin
451 g_Console_Add('Now active');
452 e_WriteLog('[DEBUG] WinMsgs: Now active', TMsgType.Notify);
453 end;
455 gWinActive := true;
457 {$IFDEF ENABLE_HOLMES}
458 if assigned(winFocusCB) then winFocusCB();
459 {$ENDIF}
460 end;
461 end;
462 end;
465 function EventHandler (var ev: TSDL_Event): Boolean;
466 var
467 key, keychr: Word;
468 uc: UnicodeChar;
469 down: Boolean;
470 i: Integer;
471 hat: array [HAT_LEFT..HAT_DOWN] of Boolean;
472 begin
473 result := false;
475 case ev.type_ of
476 SDL_WINDOWEVENT:
477 result := WindowEventHandler(ev.window);
479 SDL_QUITEV:
480 begin
481 if (gExit <> EXIT_QUIT) then
482 begin
483 if not wLoadingProgress then
484 begin
485 g_Game_Free();
486 g_Game_Quit();
487 end
488 else
489 begin
490 wLoadingQuit := true;
491 end;
492 end;
493 result := true;
494 end;
496 SDL_KEYDOWN, SDL_KEYUP:
497 begin
498 key := ev.key.keysym.scancode;
499 if key = SDL_SCANCODE_AC_BACK then
500 key := SDL_SCANCODE_ESCAPE;
501 down := (ev.type_ = SDL_KEYDOWN);
502 {$IF not DEFINED(HEADLESS) and DEFINED(ENABLE_HOLMES)}
503 if fuiOnSDLEvent(ev) then
504 begin
505 // event eaten, but...
506 if not down then e_KeyUpDown(key, false);
507 exit;
508 end;
509 {$ENDIF}
510 if ev.key._repeat = 0 then
511 begin
512 e_KeyUpDown(key, down);
513 g_Console_ProcessBind(key, down)
514 end;
515 if down then KeyPress(key);
516 end;
518 SDL_JOYBUTTONDOWN, SDL_JOYBUTTONUP:
519 if (ev.jbutton.which < e_MaxJoys) and (ev.jbutton.button < e_MaxJoyBtns) then
520 begin
521 key := e_JoyButtonToKey(ev.jbutton.which, ev.jbutton.button);
522 down := ev.type_ = SDL_JOYBUTTONDOWN;
523 e_KeyUpDown(key, down);
524 g_Console_ProcessBind(key, down);
525 if down then KeyPress(key)
526 end;
528 SDL_JOYAXISMOTION:
529 if (ev.jaxis.which < e_MaxJoys) and (ev.jaxis.axis < e_MaxJoyAxes) then
530 begin
531 down := ev.jaxis.value <> Joysticks[ev.jaxis.which].AxisZero[ev.jaxis.axis];
532 if ev.jaxis.value < Joysticks[ev.jaxis.which].AxisZero[ev.jaxis.axis] - e_JoystickDeadzones[ev.jaxis.which] then
533 key := e_JoyAxisToKey(ev.jaxis.which, ev.jaxis.axis, AX_MINUS)
534 else
535 key := e_JoyAxisToKey(ev.jaxis.which, ev.jaxis.axis, AX_PLUS);
536 e_KeyUpDown(key, down);
537 g_Console_ProcessBind(key, down);
538 if down then KeyPress(key)
539 end;
541 SDL_JOYHATMOTION:
542 if (ev.jhat.which < e_MaxJoys) and (ev.jhat.hat < e_MaxJoyHats) then
543 begin
544 hat[HAT_UP] := LongBool(ev.jhat.value and SDL_HAT_UP);
545 hat[HAT_DOWN] := LongBool(ev.jhat.value and SDL_HAT_DOWN);
546 hat[HAT_LEFT] := LongBool(ev.jhat.value and SDL_HAT_LEFT);
547 hat[HAT_RIGHT] := LongBool(ev.jhat.value and SDL_HAT_RIGHT);
548 for i := HAT_LEFT to HAT_DOWN do
549 begin
550 if JoystickHatState[ev.jhat.which, i] <> hat[i] then
551 begin
552 down := hat[i];
553 key := e_JoyHatToKey(ev.jhat.which, ev.jhat.hat, i);
554 e_KeyUpDown(key, down);
555 g_Console_ProcessBind(key, down);
556 if down then KeyPress(key)
557 end
558 end;
559 JoystickHatState[ev.jhat.which] := hat
560 end;
562 (*
563 SDL_JOYDEVICEADDED, SDL_JOYDEVICEREMOVED:
564 begin
565 // TODO update menu here
566 end
567 *)
569 {$IF not DEFINED(HEADLESS) and DEFINED(ENABLE_HOLMES)}
570 SDL_MOUSEBUTTONDOWN, SDL_MOUSEBUTTONUP, SDL_MOUSEWHEEL, SDL_MOUSEMOTION:
571 fuiOnSDLEvent(ev);
572 {$ENDIF}
574 SDL_TEXTINPUT:
575 begin
576 Utf8ToUnicode(@uc, PChar(ev.text.text), 1);
577 keychr := Word(uc);
578 if (keychr > 127) then keychr := Word(wchar2win(WideChar(keychr)));
579 if (keychr > 0) and (keychr <= 255) then CharPress(AnsiChar(keychr));
580 end;
582 SDL_FINGERMOTION, SDL_FINGERDOWN, SDL_FINGERUP:
583 g_Touch_HandleEvent(ev.tfinger);
585 // other key presses and joysticks are handled in e_input
586 end;
587 end;
590 procedure SwapBuffers ();
591 begin
592 {$IF not DEFINED(HEADLESS)}
593 SDL_GL_SwapWindow(h_Wnd);
594 {$ENDIF}
595 end;
598 function CreateGLWindow (Title: PChar): Boolean;
599 begin
600 result := false;
602 gWinSizeX := gScreenWidth;
603 gWinSizeY := gScreenHeight;
605 {$IF not DEFINED(HEADLESS)}
606 wTitle := Title;
607 {$ENDIF}
608 e_WriteLog('Creating window', TMsgType.Notify);
610 if not g_Window_SetDisplay() then
611 begin
612 KillGLWindow(false);
613 e_WriteLog('Window creation error (resolution not supported?)', TMsgType.Fatal);
614 exit;
615 end;
617 {$IF not DEFINED(HEADLESS)}
618 h_GL := SDL_GL_CreateContext(h_Wnd);
619 if (h_GL = nil) then exit;
620 {$IFDEF ENABLE_HOLMES}
621 fuiScrWdt := gScreenWidth;
622 fuiScrHgt := gScreenHeight;
623 {$ENDIF}
624 SDL_GL_MakeCurrent(h_Wnd, h_GL);
625 {$IFDEF USE_NANOGL}
626 if nanoGL_Init() = 0 then
627 begin
628 KillGLWindow(false);
629 e_WriteLog('nanoGL initialization error', TMsgType.Fatal);
630 exit;
631 end;
632 {$ENDIF}
633 {$IFDEF USE_NOGL}
634 nogl_Init;
635 {$ENDIF}
636 {$IFDEF ENABLE_HOLMES}
637 if (assigned(oglInitCB)) then oglInitCB();
638 {$ENDIF}
639 if (h_GL <> nil) then g_SetVSync(gVSync);
640 {$ENDIF}
642 e_ResizeWindow(gScreenWidth, gScreenHeight);
643 e_InitGL();
645 result := true;
646 end;
649 {$IFDEF WINDOWS}
650 // windoze sux; in headless mode `GetTickCount()` (and SDL) returns shit
651 function GetTimer (): Int64;
652 var
653 F, C: Int64;
654 begin
655 QueryPerformanceFrequency(F);
656 QueryPerformanceCounter(C);
657 result := Round(C/F*1000{000});
658 end;
659 {$ELSE}
660 function GetTimer (): Int64;
661 var
662 t: Uint32;
663 tt: Int64;
664 begin
665 t := SDL_GetTicks();
666 if (ticksOverflow = -1) then
667 begin
668 ticksOverflow := 0;
669 lastTicks := t;
670 end
671 else
672 begin
673 if (lastTicks > t) then
674 begin
675 // overflow, increment overflow ;-)
676 ticksOverflow := ticksOverflow+(Int64($ffffffff)+Int64(1));
677 tt := (Int64($ffffffff)+Int64(1))+Int64(t);
678 t := Uint32(tt-lastTicks);
679 end;
680 end;
681 lastTicks := t;
682 result := ticksOverflow+Int64(t);
683 end;
684 {$ENDIF}
687 procedure ResetTimer ();
688 begin
689 wNeedTimeReset := true;
690 end;
693 procedure PushExitEvent ();
694 var
695 ev: TSDL_Event;
696 begin
697 ev.type_ := SDL_QUITEV;
698 SDL_PushEvent(@ev);
699 end;
702 var
703 prevLoadingUpdateTime: UInt64 = 0;
705 procedure ProcessLoading (forceUpdate: Boolean=false);
706 var
707 ev: TSDL_Event;
708 ID: LongWord;
709 stt: UInt64;
710 begin
711 FillChar(ev, sizeof(ev), 0);
712 wLoadingProgress := true;
714 while (SDL_PollEvent(@ev) > 0) do
715 begin
716 EventHandler(ev);
717 if (ev.type_ = SDL_QUITEV) then break;
718 end;
719 //e_PollJoysticks();
721 if (ev.type_ = SDL_QUITEV) or (gExit = EXIT_QUIT) then
722 begin
723 wLoadingProgress := false;
724 exit;
725 end;
727 if not wMinimized then
728 begin
729 if forceUpdate then
730 begin
731 prevLoadingUpdateTime := getTimeMilli();
732 end
733 else
734 begin
735 stt := getTimeMilli();
736 if (stt < prevLoadingUpdateTime) or (stt-prevLoadingUpdateTime >= ProgressUpdateMSecs) then
737 begin
738 prevLoadingUpdateTime := stt;
739 forceUpdate := true;
740 end;
741 end;
743 if forceUpdate then
744 begin
745 if g_Texture_Get('INTER', ID) then
746 begin
747 e_DrawSize(ID, 0, 0, 0, false, false, gScreenWidth, gScreenHeight);
748 e_DarkenQuadWH(0, 0, gScreenWidth, gScreenHeight, 150);
749 end
750 else
751 begin
752 e_Clear(GL_COLOR_BUFFER_BIT, 0, 0, 0);
753 end;
755 DrawLoadingStat();
756 SwapBuffers();
757 end;
758 end;
760 e_SoundUpdate();
762 if NetMode = NET_SERVER then
763 begin
764 g_Net_Host_Update();
765 end
766 else
767 begin
768 if (NetMode = NET_CLIENT) and (NetState <> NET_STATE_AUTH) then g_Net_Client_UpdateWhileLoading();
769 end;
771 wLoadingProgress := false;
772 end;
775 function g_ProcessMessages (): Boolean;
776 var
777 ev: TSDL_Event;
778 begin
779 result := false;
780 FillChar(ev, SizeOf(ev), 0);
781 while (SDL_PollEvent(@ev) > 0) do
782 begin
783 result := EventHandler(ev);
784 if (ev.type_ = SDL_QUITEV) then exit;
785 end;
786 //e_PollJoysticks();
787 end;
790 function ProcessMessage (): Boolean;
791 var
792 i, t: Integer;
793 begin
794 result := g_ProcessMessages();
796 Time := GetTimer();
797 Time_Delta := Time-Time_Old;
799 flag := false;
801 if wNeedTimeReset then
802 begin
803 Time_Delta := 28;
804 wNeedTimeReset := false;
805 end;
807 g_Map_ProfilersBegin();
808 g_Mons_ProfilersBegin();
810 t := Time_Delta div 28;
811 if (t > 0) then
812 begin
813 flag := true;
814 for i := 1 to t do
815 begin
816 if (NetMode = NET_SERVER) then g_Net_Host_Update()
817 else if (NetMode = NET_CLIENT) then g_Net_Client_Update();
818 Update();
819 end;
820 end
821 else
822 begin
823 if (NetMode = NET_SERVER) then g_Net_Host_Update()
824 else if (NetMode = NET_CLIENT) then g_Net_Client_Update();
825 end;
827 g_Map_ProfilersEnd();
828 g_Mons_ProfilersEnd();
830 if wLoadingQuit then
831 begin
832 g_Game_Free();
833 g_Game_Quit();
834 end;
836 if (gExit = EXIT_QUIT) then
837 begin
838 result := true;
839 exit;
840 end;
842 // Âðåìÿ ïðåäûäóùåãî îáíîâëåíèÿ
843 if flag then
844 begin
845 Time_Old := Time-(Time_Delta mod 28);
846 if (not wMinimized) then
847 begin
848 Draw();
849 SwapBuffers();
850 end;
851 end
852 else
853 begin
854 Sleep(1); // release time slice, so we won't eat 100% CPU
855 end;
857 e_SoundUpdate();
858 end;
861 procedure ReDrawWindow ();
862 begin
863 SwapBuffers();
864 end;
867 procedure g_SetVSync (vsync: Boolean);
868 {$IF not DEFINED(HEADLESS)}
869 var
870 v: Byte;
871 {$ENDIF}
872 begin
873 {$IF not DEFINED(HEADLESS)}
874 if vsync then v := 1 else v := 0;
875 if (SDL_GL_SetSwapInterval(v) <> 0) then
876 begin
877 e_WriteLog('oops; can''t change vsync option, restart required', TMsgType.Warning);
878 end
879 else
880 begin
881 if vsync then e_WriteLog('VSync: ON', TMsgType.Notify) else e_WriteLog('VSync: OFF', TMsgType.Notify);
882 end;
883 {$ENDIF}
884 end;
887 procedure InitOpenGL ();
888 begin
889 {$IF not DEFINED(HEADLESS)}
890 {$IFDEF USE_GLES1}
891 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 1);
892 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
893 SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES);
894 {$ELSE}
895 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
896 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
897 SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
898 SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
899 SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
900 SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
901 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
902 SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); // lights; it is enough to have 1-bit stencil buffer for lighting, but...
903 {$ENDIF}
904 {$ENDIF}
905 end;
908 function glHasExtension (const name: AnsiString): Boolean;
909 var
910 exts: PChar;
911 i: Integer;
912 found: Boolean;
913 extName: ShortString;
914 begin
915 result := false;
916 if (Length(name) = 0) then exit;
917 exts := glGetString(GL_EXTENSIONS);
918 if (exts = nil) then exit;
919 while (exts[0] <> #0) and (exts[0] = ' ') do Inc(exts);
920 while (exts[0] <> #0) do
921 begin
922 if gwin_dump_extensions then
923 begin
924 i := 0;
925 while (exts[i] <> #0) and (exts[i] <> ' ') do Inc(i);
926 if i > 255 then
927 begin
928 e_WriteLog('FUUUUUUUUUUUUU', TMsgType.Warning);
929 end
930 else
931 begin
932 Move(exts^, extName[1], i);
933 extName[0] := Char(i);
934 e_WriteLog(Format('EXT: %s', [extName]), TMsgType.Notify);
935 end;
936 end;
937 found := true;
938 for i := 0 to length(name)-1 do
939 begin
940 if (exts[i] = #0) then begin found := false; break; end;
941 if (exts[i] <> name[i+1]) then begin found := false; break; end;
942 end;
943 if found and ((exts[Length(name)] = #0) or (exts[Length(name)] = ' ')) then begin result := true; exit; end;
944 while (exts[0] <> #0) and (exts[0] <> ' ') do Inc(exts);
945 while (exts[0] <> #0) and (exts[0] = ' ') do Inc(exts);
946 end;
947 end;
950 function SDLMain (): Integer;
951 var
952 idx: Integer;
953 {$IF not DEFINED(HEADLESS)}
954 ltmp: Integer;
955 {$ENDIF}
956 arg: AnsiString;
957 mdfo: TStream;
958 {$IFDEF ENABLE_HOLMES}
959 itmp: Integer;
960 valres: Word;
961 {$ENDIF}
962 begin
963 {$IFDEF HEADLESS}
964 e_NoGraphics := true;
965 {$ELSE}
966 {$IFDEF ENABLE_HOLMES}
967 if (not g_holmes_imfunctional) then
968 begin
969 uiInitialize();
970 uiContext.font := 'win14';
971 end;
972 {$ENDIF}
973 {$ENDIF}
975 idx := 1;
976 while (idx <= ParamCount) do
977 begin
978 arg := ParamStr(idx);
979 Inc(idx);
980 if arg = '--opengl-dump-exts' then gwin_dump_extensions := true;
981 //if arg = '--twinkletwinkle' then gwin_k8_enable_light_experiments := true;
982 if arg = '--jah' then g_profile_history_size := 100;
983 if arg = '--no-particles' then gpart_dbg_enabled := false;
984 if arg = '--no-los' then gmon_dbg_los_enabled := false;
986 if arg = '--profile-render' then g_profile_frame_draw := true;
987 if arg = '--profile-coldet' then g_profile_collision := true;
988 if arg = '--profile-los' then g_profile_los := true;
990 if arg = '--no-part-phys' then gpart_dbg_phys_enabled := false;
991 if arg = '--no-part-physics' then gpart_dbg_phys_enabled := false;
992 if arg = '--no-particles-phys' then gpart_dbg_phys_enabled := false;
993 if arg = '--no-particles-physics' then gpart_dbg_phys_enabled := false;
994 if arg = '--no-particle-phys' then gpart_dbg_phys_enabled := false;
995 if arg = '--no-particle-physics' then gpart_dbg_phys_enabled := false;
997 {.$IF DEFINED(D2F_DEBUG)}
998 if arg = '--aimline' then g_dbg_aimline_on := true;
999 {.$ENDIF}
1001 {$IFDEF ENABLE_HOLMES}
1002 if arg = '--holmes' then begin g_holmes_enabled := true; g_Game_SetDebugMode(); end;
1004 if (arg = '--holmes-ui-scale') or (arg = '-holmes-ui-scale') then
1005 begin
1006 if (idx <= ParamCount) then
1007 begin
1008 if not conParseFloat(fuiRenderScale, ParamStr(idx)) then fuiRenderScale := 1.0;
1009 Inc(idx);
1010 end;
1011 end;
1013 if (arg = '--holmes-font') or (arg = '-holmes-font') then
1014 begin
1015 if (idx <= ParamCount) then
1016 begin
1017 itmp := 0;
1018 val(ParamStr(idx), itmp, valres);
1019 {$IFNDEF HEADLESS}
1020 if (valres = 0) and (not g_holmes_imfunctional) then
1021 begin
1022 case itmp of
1023 8: uiContext.font := 'win8';
1024 14: uiContext.font := 'win14';
1025 16: uiContext.font := 'win16';
1026 end;
1027 end;
1028 {$ELSE}
1029 // fuck off, fpc!
1030 itmp := itmp;
1031 valres := valres;
1032 {$ENDIF}
1033 Inc(idx);
1034 end;
1035 end;
1036 {$ENDIF}
1038 if (arg = '--game-scale') or (arg = '-game-scale') then
1039 begin
1040 if (idx <= ParamCount) then
1041 begin
1042 if not conParseFloat(g_dbg_scale, ParamStr(idx)) then g_dbg_scale := 1.0;
1043 Inc(idx);
1044 end;
1045 end;
1047 if (arg = '--write-mapdef') or (arg = '-write-mapdef') then
1048 begin
1049 mdfo := createDiskFile('mapdef.txt');
1050 mdfo.WriteBuffer(defaultMapDef[1], Length(defaultMapDef));
1051 mdfo.Free();
1052 Halt(0);
1053 end;
1054 end;
1056 e_WriteLog('Initializing OpenGL', TMsgType.Notify);
1057 InitOpenGL();
1059 e_WriteLog('Creating GL window', TMsgType.Notify);
1060 if not CreateGLWindow(PChar(Format('Doom 2D: Forever %s', [GAME_VERSION]))) then
1061 begin
1062 result := 0;
1063 e_WriteLog('Unable to create GL window: ' + SDL_GetError(), TMsgType.Fatal);
1064 exit;
1065 end;
1067 {EnumDisplayModes();}
1069 {$IFDEF HEADLESS}
1070 //gwin_k8_enable_light_experiments := false;
1071 gwin_has_stencil := false;
1072 glLegacyNPOT := false;
1073 gwin_dump_extensions := false;
1074 {$ELSE}
1075 SDL_GL_GetAttribute(SDL_GL_STENCIL_SIZE, @ltmp);
1076 e_LogWritefln('stencil buffer size: %s', [ltmp]);
1077 gwin_has_stencil := (ltmp > 0);
1079 if glHasExtension('GL_ARB_texture_non_power_of_two') or
1080 glHasExtension('GL_OES_texture_npot') then
1081 begin
1082 e_WriteLog('NPOT textures: YES', TMsgType.Notify);
1083 glLegacyNPOT := false;
1084 end
1085 else
1086 begin
1087 e_WriteLog('NPOT textures: NO', TMsgType.Warning);
1088 glLegacyNPOT := true;
1089 end;
1090 gwin_dump_extensions := false;
1091 {$ENDIF}
1093 Init();
1094 Time_Old := GetTimer();
1096 // Êîìàíäíàÿ ñòðîêà
1097 if (ParamCount > 0) then g_Game_Process_Params();
1099 // Çàïðîñ ÿçûêà
1100 if (not gGameOn) and gAskLanguage then g_Menu_AskLanguage();
1102 e_WriteLog('Entering the main loop', TMsgType.Notify);
1104 // main loop
1105 while not ProcessMessage() do begin end;
1107 Release();
1108 KillGLWindow(false);
1110 result := 0;
1111 end;
1114 end.