DEADSOFTWARE

Game: Warn about ports;
[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;
48 g_dbg_input: Boolean = False;
51 implementation
53 uses
54 {$IFDEF WINDOWS}Windows,{$ENDIF}
55 {$INCLUDE ../nogl/noGLuses.inc}
56 {$IFDEF ENABLE_HOLMES}
57 g_holmes, sdlcarcass, fui_ctls,
58 {$ENDIF}
59 SysUtils, Classes, MAPDEF, Math,
60 SDL2, e_graphics, e_log, e_texture, g_main,
61 g_console, e_input, g_options, g_game,
62 g_basic, g_textures, e_sound, g_sound, g_menu, ENet, g_net,
63 g_map, g_gfx, g_monsters, xprofiler,
64 g_touch, g_gui;
67 const
68 ProgressUpdateMSecs = 1;//100;
70 var
71 h_Wnd: PSDL_Window = nil;
72 h_GL: TSDL_GLContext = nil;
73 Time, Time_Delta, Time_Old: Int64;
74 flag: Boolean;
75 {$IF not DEFINED(HEADLESS)}
76 wTitle: PChar = nil;
77 wasFullscreen: Boolean = true; // so we need to recreate the window
78 {$ENDIF}
79 wNeedTimeReset: Boolean = false;
80 wMinimized: Boolean = false;
81 wMaximized: Boolean = false;
82 wLoadingProgress: Boolean = false;
83 wLoadingQuit: Boolean = false;
84 {$IFNDEF WINDOWS}
85 ticksOverflow: Int64 = -1;
86 lastTicks: Uint32 = 0; // to detect overflow
87 {$ENDIF}
88 JoystickHandle: array [0..e_MaxJoys - 1] of PSDL_Joystick;
89 JoystickHatState: array [0..e_MaxJoys - 1, 0..e_MaxJoyHats - 1, HAT_LEFT..HAT_DOWN] of Boolean;
90 JoystickZeroAxes: array [0..e_MaxJoys - 1, 0..e_MaxJoyAxes - 1] of Integer;
92 procedure KillGLWindow (preserveGL: Boolean);
93 begin
94 {$IFDEF ENABLE_HOLMES}
95 if (h_GL <> nil) and (not preserveGL) then begin if (assigned(oglDeinitCB)) then oglDeinitCB(); end;
96 {$ENDIF}
97 if (h_Wnd <> nil) then SDL_DestroyWindow(h_Wnd);
98 if (h_GL <> nil) and (not preserveGL) then
99 begin
101 {$IFDEF USE_NANOGL}
102 nanoGL_Destroy;
103 {$ENDIF}
105 {$IFDEF USE_NOGL}
106 nogl_Quit;
107 {$ENDIF}
109 SDL_GL_DeleteContext(h_GL);
110 end;
111 h_Wnd := nil;
112 if (not preserveGL) then h_GL := nil;
113 end;
116 function g_Window_SetDisplay (preserveGL: Boolean = false): Boolean;
117 {$IF not DEFINED(HEADLESS)}
118 var
119 mode, cmode: TSDL_DisplayMode;
120 wFlags: LongWord = 0;
121 nw, nh: Integer;
122 {$ENDIF}
123 begin
124 {$IF not DEFINED(HEADLESS)}
125 result := false;
127 e_WriteLog('Setting display mode...', TMsgType.Notify);
129 wFlags := SDL_WINDOW_OPENGL {or SDL_WINDOW_RESIZABLE};
130 if gFullscreen then wFlags := wFlags {or SDL_WINDOW_FULLSCREEN} else wFlags := wFlags or SDL_WINDOW_RESIZABLE;
131 if (not gFullscreen) and (not preserveGL) and gWinMaximized then wFlags := wFlags or SDL_WINDOW_MAXIMIZED else gWinMaximized := false;
133 if gFullscreen then
134 begin
135 mode.w := gScreenWidth;
136 mode.h := gScreenHeight;
137 mode.format := 0;
138 mode.refresh_rate := 0;
139 mode.driverdata := nil;
140 if (SDL_GetClosestDisplayMode(0, @mode, @cmode) = nil) then
141 begin
142 e_WriteLog('SDL: cannot find display mode for '+IntToStr(gScreenWidth), TMsgType.Notify);
143 gScreenWidth := 800;
144 gScreenHeight := 600;
145 end
146 else
147 begin
148 e_WriteLog('SDL: found display mode for '+IntToStr(gScreenWidth)+'x'+IntToStr(gScreenHeight)+': '+IntToStr(cmode.w)+'x'+IntToStr(cmode.h), TMsgType.Notify);
149 gScreenWidth := cmode.w;
150 gScreenHeight := cmode.h;
151 end;
152 end;
154 if (preserveGL) and (h_Wnd <> nil) and (not gFullscreen) and (not wasFullscreen) then
155 begin
156 //SDL_SetWindowMaximumSize(h_Wnd, gScreenWidth, gScreenHeight);
157 //SDL_SetWindowDisplayMode(h_Wnd, @cmode);
158 if (wMaximized) then SDL_RestoreWindow(h_Wnd);
159 wMaximized := false;
160 gWinMaximized := false;
161 SDL_SetWindowSize(h_Wnd, gScreenWidth, gScreenHeight);
162 //SDL_SetWindowFullscreen(h_Wnd, SDL_WINDOW_FULLSCREEN);
163 //SDL_SetWindowFullscreen(h_Wnd, 0);
164 end
165 else
166 begin
167 KillGLWindow(preserveGL);
168 h_Wnd := SDL_CreateWindow(PChar(wTitle), gWinRealPosX, gWinRealPosY, gScreenWidth, gScreenHeight, wFlags);
169 if gFullscreen then
170 SDL_SetWindowFullscreen(h_Wnd, SDL_WINDOW_FULLSCREEN);
171 if (h_Wnd = nil) then exit;
172 end;
173 wasFullscreen := gFullscreen;
175 SDL_GL_MakeCurrent(h_Wnd, h_GL);
176 SDL_ShowCursor(SDL_DISABLE);
177 if (h_GL <> nil) then g_SetVSync(gVSync);
178 if (gFullscreen) then
179 begin
180 nw := 0;
181 nh := 0;
182 SDL_GetWindowSize(h_Wnd, @nw, @nh);
183 if (nw > 128) and (nh > 128) then
184 begin
185 e_WriteLog('SDL: fullscreen window got size '+IntToStr(nw)+'x'+IntToStr(nh)+': '+IntToStr(gScreenWidth)+'x'+IntToStr(gScreenHeight), TMsgType.Notify);
186 gScreenWidth := nw;
187 gScreenHeight := nh;
188 end
189 else
190 begin
191 e_WriteLog('SDL: fullscreen window got invalid size: '+IntToStr(nw)+'x'+IntToStr(nh), TMsgType.Notify);
192 end;
193 end;
195 {$IFDEF ENABLE_HOLMES}
196 fuiScrWdt := gScreenWidth;
197 fuiScrHgt := gScreenHeight;
198 if (h_GL <> nil) and (not preserveGL) then begin if (assigned(oglInitCB)) then oglInitCB(); end;
199 {$ENDIF}
200 {$ENDIF}
202 result := true;
203 end;
206 function GetDisplayModes (dbpp: LongWord; var selres: LongWord): SSArray;
207 var
208 mode: TSDL_DisplayMode;
209 res, i, k, n, pw, ph: Integer;
210 begin
211 SetLength(result, 0);
212 {$IFDEF HEADLESS}exit;{$ENDIF}
213 k := 0; selres := 0;
214 n := SDL_GetNumDisplayModes(0);
215 pw := 0; ph := 0;
216 for i := 0 to n do
217 begin
218 res := SDL_GetDisplayMode(0, i, @mode);
219 if res < 0 then continue;
220 if SDL_BITSPERPIXEL(mode.format) = gBPP then continue;
221 if (mode.w = pw) and (mode.h = ph) then continue;
222 if (mode.w = gScreenWidth) and (mode.h = gScreenHeight) then
223 selres := k;
224 Inc(k);
225 SetLength(result, k);
226 result[k-1] := IntToStr(mode.w) + 'x' + IntToStr(mode.h);
227 pw := mode.w; ph := mode.h
228 end;
230 e_WriteLog('SDL: Got ' + IntToStr(k) + ' resolutions.', TMsgType.Notify);
231 end;
234 procedure Sleep (ms: LongWord);
235 begin
236 SDL_Delay(ms);
237 end;
240 procedure ChangeWindowSize (requested: Boolean);
241 begin
242 e_LogWritefln(' ChangeWindowSize: (ws=%dx%d) (ss=%dx%d)', [gWinSizeX, gWinSizeY, gScreenWidth, gScreenHeight]);
243 gWinSizeX := gScreenWidth;
244 gWinSizeY := gScreenHeight;
245 {$IF not DEFINED(HEADLESS)}
246 {$IFDEF ENABLE_HOLMES}
247 fuiScrWdt := gScreenWidth;
248 fuiScrHgt := gScreenHeight;
249 {$ENDIF}
250 e_ResizeWindow(gScreenWidth, gScreenHeight);
251 g_Game_SetupScreenSize();
252 {$IF DEFINED(ANDROID)}
253 (* This will fix menu reset on keyboard showing *)
254 if requested then
255 g_Menu_Reset;
256 {$ELSE}
257 g_Menu_Reset;
258 {$ENDIF}
259 g_Game_ClearLoading();
260 {$ENDIF}
261 end;
264 function g_Window_SetSize (w, h: Word; fullscreen: Boolean): Boolean;
265 {$IF not DEFINED(HEADLESS)}
266 var
267 preserve: Boolean;
268 {$ENDIF}
269 begin
270 result := false;
271 {$IF not DEFINED(HEADLESS)}
272 preserve := false;
274 if (gScreenWidth <> w) or (gScreenHeight <> h) then
275 begin
276 result := true;
277 preserve := true;
278 gScreenWidth := w;
279 gScreenHeight := h;
280 end;
282 if (gFullscreen <> fullscreen) then
283 begin
284 result := true;
285 preserve := true;
286 gFullscreen := fullscreen;
287 preserve := true;
288 end;
290 if result then
291 begin
292 g_Window_SetDisplay(preserve);
293 ChangeWindowSize(true);
294 end;
295 {$ENDIF}
296 end;
299 function WindowEventHandler (constref ev: TSDL_WindowEvent): Boolean;
300 var
301 wActivate, wDeactivate: Boolean;
302 begin
303 result := false;
304 wActivate := false;
305 wDeactivate := false;
307 case ev.event of
308 SDL_WINDOWEVENT_MOVED:
309 begin
310 if not (gFullscreen or gWinMaximized) then
311 begin
312 gWinRealPosX := ev.data1;
313 gWinRealPosY := ev.data2;
314 end;
315 end;
317 SDL_WINDOWEVENT_MINIMIZED:
318 begin
319 e_UnpressAllKeys();
320 if not wMinimized then
321 begin
322 e_ResizeWindow(0, 0);
323 wMinimized := true;
324 if g_debug_WinMsgs then
325 begin
326 g_Console_Add('Now minimized');
327 e_WriteLog('[DEBUG] WinMsgs: Now minimized', TMsgType.Notify);
328 end;
329 wDeactivate := true;
330 end;
331 end;
333 SDL_WINDOWEVENT_RESIZED:
334 begin
335 e_LogWritefln('Resize: (os=%dx%d) (ns=%dx%d)', [gScreenWidth, gScreenHeight, Integer(ev.data1), Integer(ev.data2)]);
336 {if (gFullscreen) then
337 begin
338 e_LogWriteln(' fullscreen fix applied.');
339 if (gScreenWidth <> ev.data1) or (gScreenHeight <> ev.data2) then
340 begin
341 SDL_SetWindowSize(h_Wnd, gScreenWidth, gScreenHeight);
342 end;
343 end
344 else}
345 begin
346 gScreenWidth := ev.data1;
347 gScreenHeight := ev.data2;
348 end;
349 ChangeWindowSize(false);
350 SwapBuffers();
351 if g_debug_WinMsgs then
352 begin
353 g_Console_Add('Resized to ' + IntToStr(ev.data1) + 'x' + IntToStr(ev.data2));
354 e_WriteLog('[DEBUG] WinMsgs: Resized to ' + IntToStr(ev.data1) + 'x' + IntToStr(ev.data2), TMsgType.Notify);
355 end;
356 end;
358 SDL_WINDOWEVENT_EXPOSED:
359 SwapBuffers();
361 SDL_WINDOWEVENT_MAXIMIZED:
362 begin
363 wMaximized := true;
364 if wMinimized then
365 begin
366 e_ResizeWindow(gScreenWidth, gScreenHeight);
367 wMinimized := false;
368 wActivate := true;
369 end;
370 if (not gWinMaximized) and (not gFullscreen) then
371 begin
372 gWinMaximized := true;
373 if g_debug_WinMsgs then
374 begin
375 g_Console_Add('Now maximized');
376 e_WriteLog('[DEBUG] WinMsgs: Now maximized', TMsgType.Notify);
377 end;
378 end;
379 end;
381 SDL_WINDOWEVENT_RESTORED:
382 begin
383 wMaximized := false;
384 if wMinimized then
385 begin
386 e_ResizeWindow(gScreenWidth, gScreenHeight);
387 wMinimized := false;
388 wActivate := true;
389 end;
390 gWinMaximized := false;
391 if g_debug_WinMsgs then
392 begin
393 g_Console_Add('Now restored');
394 e_WriteLog('[DEBUG] WinMsgs: Now restored', TMsgType.Notify);
395 end;
396 end;
398 SDL_WINDOWEVENT_FOCUS_GAINED:
399 begin
400 wActivate := true;
401 //e_WriteLog('window gained focus!', MSG_NOTIFY);
402 end;
404 SDL_WINDOWEVENT_FOCUS_LOST:
405 begin
406 wDeactivate := true;
407 e_UnpressAllKeys();
408 //e_WriteLog('window lost focus!', MSG_NOTIFY);
409 end;
410 end;
412 if wDeactivate then
413 begin
414 if gWinActive then
415 begin
416 e_WriteLog('deactivating window', TMsgType.Notify);
417 e_UnpressAllKeys;
419 if gMuteWhenInactive then
420 begin
421 //e_WriteLog('deactivating sounds', MSG_NOTIFY);
422 e_MuteChannels(true);
423 end;
425 if g_debug_WinMsgs then
426 begin
427 g_Console_Add('Now inactive');
428 e_WriteLog('[DEBUG] WinMsgs: Now inactive', TMsgType.Notify);
429 end;
431 gWinActive := false;
433 {$IFDEF ENABLE_HOLMES}
434 if assigned(winBlurCB) then winBlurCB();
435 {$ENDIF}
436 end;
437 end
438 else if wActivate then
439 begin
440 if not gWinActive then
441 begin
442 //e_WriteLog('activating window', MSG_NOTIFY);
444 if gMuteWhenInactive then
445 begin
446 //e_WriteLog('activating sounds', MSG_NOTIFY);
447 e_MuteChannels(false);
448 end;
450 if g_debug_WinMsgs then
451 begin
452 g_Console_Add('Now active');
453 e_WriteLog('[DEBUG] WinMsgs: Now active', TMsgType.Notify);
454 end;
456 gWinActive := true;
458 {$IFDEF ENABLE_HOLMES}
459 if assigned(winFocusCB) then winFocusCB();
460 {$ENDIF}
461 end;
462 end;
463 end;
466 function EventHandler (var ev: TSDL_Event): Boolean;
467 var
468 key, keychr, minuskey: Word;
469 uc: UnicodeChar;
470 down: Boolean;
471 i: Integer;
472 hat: array [HAT_LEFT..HAT_DOWN] of Boolean;
473 begin
474 result := false;
476 case ev.type_ of
477 SDL_WINDOWEVENT:
478 result := WindowEventHandler(ev.window);
480 SDL_QUITEV:
481 begin
482 if (gExit <> EXIT_QUIT) then
483 begin
484 if not wLoadingProgress then
485 begin
486 g_Game_Free();
487 g_Game_Quit();
488 end
489 else
490 begin
491 wLoadingQuit := true;
492 end;
493 end;
494 result := true;
495 end;
497 SDL_KEYDOWN, SDL_KEYUP:
498 begin
499 key := ev.key.keysym.scancode;
500 if key = SDL_SCANCODE_AC_BACK then
501 key := SDL_SCANCODE_ESCAPE;
502 down := (ev.type_ = SDL_KEYDOWN);
503 {$IF not DEFINED(HEADLESS) and DEFINED(ENABLE_HOLMES)}
504 if fuiOnSDLEvent(ev) then
505 begin
506 // event eaten, but...
507 if not down then e_KeyUpDown(key, false);
508 exit;
509 end;
510 {$ENDIF}
511 if ev.key._repeat = 0 then
512 begin
513 if g_dbg_input then
514 e_LogWritefln('Input Debug: keysym, press=%s, scancode=%s', [down, key]);
515 e_KeyUpDown(key, down);
516 g_Console_ProcessBind(key, down);
517 end
518 else if gConsoleShow or gChatShow or (g_ActiveWindow <> nil) then
519 begin
520 // key repeat in menus and shit
521 KeyPress(key);
522 end;
523 end;
525 SDL_JOYBUTTONDOWN, SDL_JOYBUTTONUP:
526 if (ev.jbutton.which < e_MaxJoys) and (ev.jbutton.button < e_MaxJoyBtns) then
527 begin
528 key := e_JoyButtonToKey(ev.jbutton.which, ev.jbutton.button);
529 down := ev.type_ = SDL_JOYBUTTONDOWN;
530 if g_dbg_input then
531 e_LogWritefln('Input Debug: jbutton, joy=%s, button=%s, keycode=%s, press=%s', [ev.jbutton.which, ev.jbutton.button, key, down]);
532 e_KeyUpDown(key, down);
533 g_Console_ProcessBind(key, down);
534 end
535 else
536 begin
537 if g_dbg_input then
538 begin
539 down := ev.type_ = SDL_JOYBUTTONDOWN;
540 e_LogWritefln('Input Debug: NOT IN RANGE! jbutton, joy=%s, button=%s, press=%s', [ev.jbutton.which, ev.jbutton.button, down])
541 end
542 end;
544 SDL_JOYAXISMOTION:
545 if (ev.jaxis.which < e_MaxJoys) and (ev.jaxis.axis < e_MaxJoyAxes) then
546 begin
547 key := e_JoyAxisToKey(ev.jaxis.which, ev.jaxis.axis, AX_PLUS);
548 minuskey := e_JoyAxisToKey(ev.jaxis.which, ev.jaxis.axis, AX_MINUS);
550 if g_dbg_input then
551 e_LogWritefln('Input Debug: jaxis, joy=%s, axis=%s, value=%s, zeroaxes=%s, deadzone=%s', [ev.jaxis.which, ev.jaxis.axis, ev.jaxis.value, JoystickZeroAxes[ev.jaxis.which, ev.jaxis.axis], e_JoystickDeadzones[ev.jaxis.which]]);
553 if ev.jaxis.value < JoystickZeroAxes[ev.jaxis.which, ev.jaxis.axis] - e_JoystickDeadzones[ev.jaxis.which] then
554 begin
555 if (e_KeyPressed(key)) then
556 begin
557 e_KeyUpDown(key, False);
558 g_Console_ProcessBind(key, False);
559 end;
560 e_KeyUpDown(minuskey, True);
561 g_Console_ProcessBind(minuskey, True);
562 end
563 else if ev.jaxis.value > JoystickZeroAxes[ev.jaxis.which, ev.jaxis.axis] + e_JoystickDeadzones[ev.jaxis.which] then
564 begin
565 if (e_KeyPressed(minuskey)) then
566 begin
567 e_KeyUpDown(minuskey, False);
568 g_Console_ProcessBind(minuskey, False);
569 end;
570 e_KeyUpDown(key, True);
571 g_Console_ProcessBind(key, True);
572 end
573 else
574 begin
575 if (e_KeyPressed(minuskey)) then
576 begin
577 e_KeyUpDown(minuskey, False);
578 g_Console_ProcessBind(minuskey, False);
579 end;
580 if (e_KeyPressed(key)) then
581 begin
582 e_KeyUpDown(key, False);
583 g_Console_ProcessBind(key, False);
584 end;
585 end;
586 end
587 else
588 begin
589 if g_dbg_input then
590 e_LogWritefln('Input Debug: NOT IN RANGE! jaxis, joy=%s, axis=%s, value=%s, zeroaxes=%s, deadzone=%s', [ev.jaxis.which, ev.jaxis.axis, ev.jaxis.value, JoystickZeroAxes[ev.jaxis.which, ev.jaxis.axis], e_JoystickDeadzones[ev.jaxis.which]])
591 end;
593 SDL_JOYHATMOTION:
594 if (ev.jhat.which < e_MaxJoys) and (ev.jhat.hat < e_MaxJoyHats) then
595 begin
596 if g_dbg_input then
597 e_LogWritefln('Input Debug: jhat, joy=%s, hat=%s, value=%s', [ev.jhat.which, ev.jhat.hat, ev.jhat.value]);
598 hat[HAT_UP] := LongBool(ev.jhat.value and SDL_HAT_UP);
599 hat[HAT_DOWN] := LongBool(ev.jhat.value and SDL_HAT_DOWN);
600 hat[HAT_LEFT] := LongBool(ev.jhat.value and SDL_HAT_LEFT);
601 hat[HAT_RIGHT] := LongBool(ev.jhat.value and SDL_HAT_RIGHT);
602 for i := HAT_LEFT to HAT_DOWN do
603 begin
604 if JoystickHatState[ev.jhat.which, ev.jhat.hat, i] <> hat[i] then
605 begin
606 down := hat[i];
607 key := e_JoyHatToKey(ev.jhat.which, ev.jhat.hat, i);
608 e_KeyUpDown(key, down);
609 g_Console_ProcessBind(key, down);
610 end
611 end;
612 JoystickHatState[ev.jhat.which, ev.jhat.hat] := hat
613 end
614 else
615 begin
616 if g_dbg_input then
617 e_LogWritefln('Input Debug: NOT IN RANGE! jhat, joy=%s, hat=%s, value=%s', [ev.jhat.which, ev.jhat.hat, ev.jhat.value])
618 end;
620 SDL_JOYDEVICEADDED:
621 if (ev.jdevice.which < e_MaxJoys) then
622 begin
623 JoystickHandle[ev.jdevice.which] := SDL_JoystickOpen(ev.jdevice.which);
624 if JoystickHandle[ev.jdevice.which] <> nil then
625 begin
626 e_LogWritefln('Added Joystick %s', [ev.jdevice.which]);
627 e_JoystickAvailable[ev.jdevice.which] := True;
628 for i := 0 to Min(SDL_JoystickNumAxes(JoystickHandle[ev.jdevice.which]), e_MaxJoyAxes) - 1 do
629 JoystickZeroAxes[ev.jdevice.which, i] := SDL_JoystickGetAxis(JoystickHandle[ev.jdevice.which], i)
630 end
631 else
632 e_LogWritefln('Warning! Failed to open Joystick %s', [ev.jdevice.which])
633 end
634 else
635 begin
636 e_LogWritefln('Warning! Added Joystick %s, but we support only <= %s', [ev.jdevice.which, e_MaxJoys])
637 end;
639 SDL_JOYDEVICEREMOVED:
640 begin
641 e_LogWritefln('Removed Joystick %s', [ev.jdevice.which]);
642 if (ev.jdevice.which < e_MaxJoys) then
643 begin
644 e_JoystickAvailable[ev.jdevice.which] := False;
645 if JoystickHandle[ev.jdevice.which] <> nil then
646 SDL_JoystickClose(JoystickHandle[ev.jdevice.which]);
647 JoystickHandle[ev.jdevice.which] := nil
648 end
649 end;
651 {$IF not DEFINED(HEADLESS) and DEFINED(ENABLE_HOLMES)}
652 SDL_MOUSEBUTTONDOWN, SDL_MOUSEBUTTONUP, SDL_MOUSEWHEEL, SDL_MOUSEMOTION:
653 fuiOnSDLEvent(ev);
654 {$ENDIF}
656 SDL_TEXTINPUT:
657 begin
658 if g_dbg_input then
659 e_LogWritefln('Input Debug: text, text=%s', [ev.text.text]);
660 Utf8ToUnicode(@uc, PChar(ev.text.text), 1);
661 keychr := Word(uc);
662 if (keychr > 127) then keychr := Word(wchar2win(WideChar(keychr)));
663 if (keychr > 0) and (keychr <= 255) then CharPress(AnsiChar(keychr));
664 end;
666 SDL_FINGERMOTION, SDL_FINGERDOWN, SDL_FINGERUP:
667 g_Touch_HandleEvent(ev.tfinger);
669 // other key presses and joysticks are handled in e_input
670 end;
671 end;
674 procedure SwapBuffers ();
675 begin
676 {$IF not DEFINED(HEADLESS)}
677 SDL_GL_SwapWindow(h_Wnd);
678 {$ENDIF}
679 end;
682 function CreateGLWindow (Title: PChar): Boolean;
683 begin
684 result := false;
686 gWinSizeX := gScreenWidth;
687 gWinSizeY := gScreenHeight;
689 {$IF not DEFINED(HEADLESS)}
690 wTitle := Title;
691 {$ENDIF}
692 e_WriteLog('Creating window', TMsgType.Notify);
694 if not g_Window_SetDisplay() then
695 begin
696 KillGLWindow(false);
697 e_WriteLog('Window creation error (resolution not supported?)', TMsgType.Fatal);
698 exit;
699 end;
701 {$IF not DEFINED(HEADLESS)}
702 h_GL := SDL_GL_CreateContext(h_Wnd);
703 if (h_GL = nil) then exit;
704 {$IFDEF ENABLE_HOLMES}
705 fuiScrWdt := gScreenWidth;
706 fuiScrHgt := gScreenHeight;
707 {$ENDIF}
708 SDL_GL_MakeCurrent(h_Wnd, h_GL);
709 {$IFDEF USE_NANOGL}
710 if nanoGL_Init() = 0 then
711 begin
712 KillGLWindow(false);
713 e_WriteLog('nanoGL initialization error', TMsgType.Fatal);
714 exit;
715 end;
716 {$ENDIF}
717 {$IFDEF USE_NOGL}
718 nogl_Init;
719 {$ENDIF}
720 {$IFDEF ENABLE_HOLMES}
721 if (assigned(oglInitCB)) then oglInitCB();
722 {$ENDIF}
723 if (h_GL <> nil) then g_SetVSync(gVSync);
724 {$ENDIF}
726 e_ResizeWindow(gScreenWidth, gScreenHeight);
727 e_InitGL();
729 result := true;
730 end;
733 {$IFDEF WINDOWS}
734 // windoze sux; in headless mode `GetTickCount()` (and SDL) returns shit
735 function GetTimer (): Int64;
736 var
737 F, C: Int64;
738 begin
739 QueryPerformanceFrequency(F);
740 QueryPerformanceCounter(C);
741 result := Round(C/F*1000{000});
742 end;
743 {$ELSE}
744 function GetTimer (): Int64;
745 var
746 t: Uint32;
747 tt: Int64;
748 begin
749 t := SDL_GetTicks();
750 if (ticksOverflow = -1) then
751 begin
752 ticksOverflow := 0;
753 lastTicks := t;
754 end
755 else
756 begin
757 if (lastTicks > t) then
758 begin
759 // overflow, increment overflow ;-)
760 ticksOverflow := ticksOverflow+(Int64($ffffffff)+Int64(1));
761 tt := (Int64($ffffffff)+Int64(1))+Int64(t);
762 t := Uint32(tt-lastTicks);
763 end;
764 end;
765 lastTicks := t;
766 result := ticksOverflow+Int64(t);
767 end;
768 {$ENDIF}
771 procedure ResetTimer ();
772 begin
773 wNeedTimeReset := true;
774 end;
777 procedure PushExitEvent ();
778 var
779 ev: TSDL_Event;
780 begin
781 ev.type_ := SDL_QUITEV;
782 SDL_PushEvent(@ev);
783 end;
786 var
787 prevLoadingUpdateTime: UInt64 = 0;
789 procedure ProcessLoading (forceUpdate: Boolean=false);
790 var
791 ev: TSDL_Event;
792 stt: UInt64;
793 begin
794 FillChar(ev, sizeof(ev), 0);
795 wLoadingProgress := true;
797 while (SDL_PollEvent(@ev) > 0) do
798 begin
799 EventHandler(ev);
800 if (ev.type_ = SDL_QUITEV) then break;
801 end;
802 //e_PollJoysticks();
804 if (ev.type_ = SDL_QUITEV) or (gExit = EXIT_QUIT) then
805 begin
806 wLoadingProgress := false;
807 exit;
808 end;
810 if not wMinimized then
811 begin
812 if forceUpdate then
813 begin
814 prevLoadingUpdateTime := getTimeMilli();
815 end
816 else
817 begin
818 stt := getTimeMilli();
819 if (stt < prevLoadingUpdateTime) or (stt-prevLoadingUpdateTime >= ProgressUpdateMSecs) then
820 begin
821 prevLoadingUpdateTime := stt;
822 forceUpdate := true;
823 end;
824 end;
826 if forceUpdate then
827 begin
828 DrawMenuBackground('INTER');
829 e_DarkenQuadWH(0, 0, gScreenWidth, gScreenHeight, 150);
831 DrawLoadingStat();
832 g_Console_Draw(True);
833 SwapBuffers();
834 end;
835 end;
837 e_SoundUpdate();
839 if NetMode = NET_SERVER then
840 begin
841 g_Net_Host_Update();
842 end
843 else
844 begin
845 if (NetMode = NET_CLIENT) and (NetState <> NET_STATE_AUTH) then g_Net_Client_UpdateWhileLoading();
846 end;
848 wLoadingProgress := false;
849 end;
852 function g_ProcessMessages (): Boolean;
853 var
854 ev: TSDL_Event;
855 begin
856 result := false;
857 FillChar(ev, SizeOf(ev), 0);
858 while (SDL_PollEvent(@ev) > 0) do
859 begin
860 result := EventHandler(ev);
861 if (ev.type_ = SDL_QUITEV) then exit;
862 end;
863 //e_PollJoysticks();
864 end;
867 function ProcessMessage (): Boolean;
868 var
869 i, t: Integer;
870 begin
871 result := g_ProcessMessages();
873 Time := GetTimer();
874 Time_Delta := Time-Time_Old;
876 flag := false;
878 if wNeedTimeReset then
879 begin
880 Time_Delta := 28;
881 wNeedTimeReset := false;
882 end;
884 g_Map_ProfilersBegin();
885 g_Mons_ProfilersBegin();
887 t := Time_Delta div 28;
888 if (t > 0) then
889 begin
890 flag := true;
891 for i := 1 to t do
892 begin
893 if (NetMode = NET_SERVER) then g_Net_Host_Update()
894 else if (NetMode = NET_CLIENT) then g_Net_Client_Update();
895 Update();
896 end;
897 end
898 else
899 begin
900 if (NetMode = NET_SERVER) then g_Net_Host_Update()
901 else if (NetMode = NET_CLIENT) then g_Net_Client_Update();
902 end;
904 g_Map_ProfilersEnd();
905 g_Mons_ProfilersEnd();
907 if wLoadingQuit then
908 begin
909 g_Game_Free();
910 g_Game_Quit();
911 end;
913 if (gExit = EXIT_QUIT) then
914 begin
915 result := true;
916 exit;
917 end;
919 // Âðåìÿ ïðåäûäóùåãî îáíîâëåíèÿ
920 if flag then
921 begin
922 Time_Old := Time-(Time_Delta mod 28);
923 if (not wMinimized) then
924 begin
925 Draw();
926 SwapBuffers();
927 end;
928 end
929 else
930 begin
931 Sleep(1); // release time slice, so we won't eat 100% CPU
932 end;
934 e_SoundUpdate();
935 end;
938 procedure ReDrawWindow ();
939 begin
940 SwapBuffers();
941 end;
944 procedure g_SetVSync (vsync: Boolean);
945 {$IF not DEFINED(HEADLESS)}
946 var
947 v: Byte;
948 {$ENDIF}
949 begin
950 {$IF not DEFINED(HEADLESS)}
951 if vsync then v := 1 else v := 0;
952 if (SDL_GL_SetSwapInterval(v) <> 0) then
953 begin
954 e_WriteLog('oops; can''t change vsync option, restart required', TMsgType.Warning);
955 end
956 else
957 begin
958 if vsync then e_WriteLog('VSync: ON', TMsgType.Notify) else e_WriteLog('VSync: OFF', TMsgType.Notify);
959 end;
960 {$ENDIF}
961 end;
964 procedure InitOpenGL ();
965 begin
966 {$IF not DEFINED(HEADLESS)}
967 {$IFDEF USE_GLES1}
968 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 1);
969 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
970 SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES);
971 {$ELSE}
972 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
973 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
974 SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
975 SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
976 SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
977 SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
978 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
979 SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); // lights; it is enough to have 1-bit stencil buffer for lighting, but...
980 {$ENDIF}
981 {$ENDIF}
982 end;
985 function glHasExtension (const name: AnsiString): Boolean;
986 var
987 exts: PChar;
988 i: Integer;
989 found: Boolean;
990 extName: ShortString;
991 begin
992 result := false;
993 if (Length(name) = 0) then exit;
994 exts := glGetString(GL_EXTENSIONS);
995 if (exts = nil) then exit;
996 while (exts[0] <> #0) and (exts[0] = ' ') do Inc(exts);
997 while (exts[0] <> #0) do
998 begin
999 if gwin_dump_extensions then
1000 begin
1001 i := 0;
1002 while (exts[i] <> #0) and (exts[i] <> ' ') do Inc(i);
1003 if i > 255 then
1004 begin
1005 e_WriteLog('FUUUUUUUUUUUUU', TMsgType.Warning);
1006 end
1007 else
1008 begin
1009 Move(exts^, extName[1], i);
1010 extName[0] := Char(i);
1011 e_WriteLog(Format('EXT: %s', [extName]), TMsgType.Notify);
1012 end;
1013 end;
1014 found := true;
1015 for i := 0 to length(name)-1 do
1016 begin
1017 if (exts[i] = #0) then begin found := false; break; end;
1018 if (exts[i] <> name[i+1]) then begin found := false; break; end;
1019 end;
1020 if found and ((exts[Length(name)] = #0) or (exts[Length(name)] = ' ')) then begin result := true; exit; end;
1021 while (exts[0] <> #0) and (exts[0] <> ' ') do Inc(exts);
1022 while (exts[0] <> #0) and (exts[0] = ' ') do Inc(exts);
1023 end;
1024 end;
1027 function SDLMain (): Integer;
1028 var
1029 idx: Integer;
1030 {$IF not DEFINED(HEADLESS)}
1031 ltmp: Integer;
1032 {$ENDIF}
1033 arg: AnsiString;
1034 mdfo: TStream;
1035 {$IFDEF ENABLE_HOLMES}
1036 itmp: Integer;
1037 valres: Word;
1038 {$ENDIF}
1039 begin
1040 {$IFDEF HEADLESS}
1041 e_NoGraphics := true;
1042 {$ELSE}
1043 {$IFDEF ENABLE_HOLMES}
1044 if (not g_holmes_imfunctional) then
1045 begin
1046 uiInitialize();
1047 uiContext.font := 'win14';
1048 end;
1049 {$ENDIF}
1050 {$ENDIF}
1052 idx := 1;
1053 while (idx <= ParamCount) do
1054 begin
1055 arg := ParamStr(idx);
1056 Inc(idx);
1057 if arg = '--opengl-dump-exts' then gwin_dump_extensions := true;
1058 //if arg = '--twinkletwinkle' then gwin_k8_enable_light_experiments := true;
1059 if arg = '--jah' then g_profile_history_size := 100;
1060 if arg = '--no-particles' then gpart_dbg_enabled := false;
1061 if arg = '--no-los' then gmon_dbg_los_enabled := false;
1063 if arg = '--profile-render' then g_profile_frame_draw := true;
1064 if arg = '--profile-coldet' then g_profile_collision := true;
1065 if arg = '--profile-los' then g_profile_los := true;
1067 if arg = '--no-part-phys' then gpart_dbg_phys_enabled := false;
1068 if arg = '--no-part-physics' then gpart_dbg_phys_enabled := false;
1069 if arg = '--no-particles-phys' then gpart_dbg_phys_enabled := false;
1070 if arg = '--no-particles-physics' then gpart_dbg_phys_enabled := false;
1071 if arg = '--no-particle-phys' then gpart_dbg_phys_enabled := false;
1072 if arg = '--no-particle-physics' then gpart_dbg_phys_enabled := false;
1074 if arg = '--debug-input' then g_dbg_input := True;
1076 {.$IF DEFINED(D2F_DEBUG)}
1077 if arg = '--aimline' then g_dbg_aimline_on := true;
1078 {.$ENDIF}
1080 {$IFDEF ENABLE_HOLMES}
1081 if arg = '--holmes' then begin g_holmes_enabled := true; g_Game_SetDebugMode(); end;
1083 if (arg = '--holmes-ui-scale') or (arg = '-holmes-ui-scale') then
1084 begin
1085 if (idx <= ParamCount) then
1086 begin
1087 if not conParseFloat(fuiRenderScale, ParamStr(idx)) then fuiRenderScale := 1.0;
1088 Inc(idx);
1089 end;
1090 end;
1092 if (arg = '--holmes-font') or (arg = '-holmes-font') then
1093 begin
1094 if (idx <= ParamCount) then
1095 begin
1096 itmp := 0;
1097 val(ParamStr(idx), itmp, valres);
1098 {$IFNDEF HEADLESS}
1099 if (valres = 0) and (not g_holmes_imfunctional) then
1100 begin
1101 case itmp of
1102 8: uiContext.font := 'win8';
1103 14: uiContext.font := 'win14';
1104 16: uiContext.font := 'win16';
1105 end;
1106 end;
1107 {$ELSE}
1108 // fuck off, fpc!
1109 itmp := itmp;
1110 valres := valres;
1111 {$ENDIF}
1112 Inc(idx);
1113 end;
1114 end;
1115 {$ENDIF}
1117 if (arg = '--game-scale') or (arg = '-game-scale') then
1118 begin
1119 if (idx <= ParamCount) then
1120 begin
1121 if not conParseFloat(g_dbg_scale, ParamStr(idx)) then g_dbg_scale := 1.0;
1122 Inc(idx);
1123 end;
1124 end;
1126 if (arg = '--write-mapdef') or (arg = '-write-mapdef') then
1127 begin
1128 mdfo := createDiskFile('mapdef.txt');
1129 mdfo.WriteBuffer(defaultMapDef[1], Length(defaultMapDef));
1130 mdfo.Free();
1131 Halt(0);
1132 end;
1133 end;
1135 e_WriteLog('Initializing OpenGL', TMsgType.Notify);
1136 InitOpenGL();
1138 e_WriteLog('Creating GL window', TMsgType.Notify);
1139 if not CreateGLWindow(PChar(Format('Doom 2D: Forever %s', [GAME_VERSION]))) then
1140 begin
1141 result := 0;
1142 e_WriteLog('Unable to create GL window: ' + SDL_GetError(), TMsgType.Fatal);
1143 exit;
1144 end;
1146 {EnumDisplayModes();}
1148 {$IFDEF HEADLESS}
1149 //gwin_k8_enable_light_experiments := false;
1150 gwin_has_stencil := false;
1151 glLegacyNPOT := false;
1152 gwin_dump_extensions := false;
1153 {$ELSE}
1154 SDL_GL_GetAttribute(SDL_GL_STENCIL_SIZE, @ltmp);
1155 e_LogWritefln('stencil buffer size: %s', [ltmp]);
1156 gwin_has_stencil := (ltmp > 0);
1158 if glHasExtension('GL_ARB_texture_non_power_of_two') or
1159 glHasExtension('GL_OES_texture_npot') then
1160 begin
1161 e_WriteLog('NPOT textures: YES', TMsgType.Notify);
1162 glLegacyNPOT := false;
1163 end
1164 else
1165 begin
1166 e_WriteLog('NPOT textures: NO', TMsgType.Warning);
1167 glLegacyNPOT := true;
1168 end;
1169 gwin_dump_extensions := false;
1170 {$ENDIF}
1172 Init();
1173 Time_Old := GetTimer();
1175 // Êîìàíäíàÿ ñòðîêà
1176 if (ParamCount > 0) then g_Game_Process_Params();
1178 // Çàïðîñ ÿçûêà
1179 if (not gGameOn) and gAskLanguage then g_Menu_AskLanguage();
1181 e_WriteLog('Entering the main loop', TMsgType.Notify);
1183 // main loop
1184 while not ProcessMessage() do begin end;
1186 Release();
1187 KillGLWindow(false);
1189 result := 0;
1190 end;
1193 initialization
1194 conRegVar('d_input', @g_dbg_input, '', '')
1195 end.