DEADSOFTWARE

df44683f8276c42d790daa11396ed1d141f32a33
[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;
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 end;
520 SDL_JOYBUTTONDOWN, SDL_JOYBUTTONUP:
521 if (ev.jbutton.which < e_MaxJoys) and (ev.jbutton.button < e_MaxJoyBtns) then
522 begin
523 key := e_JoyButtonToKey(ev.jbutton.which, ev.jbutton.button);
524 down := ev.type_ = SDL_JOYBUTTONDOWN;
525 if g_dbg_input then
526 e_LogWritefln('Input Debug: jbutton, joy=%s, button=%s, keycode=%s, press=%s', [ev.jbutton.which, ev.jbutton.button, key, down]);
527 e_KeyUpDown(key, down);
528 g_Console_ProcessBind(key, down);
529 end
530 else
531 begin
532 if g_dbg_input then
533 begin
534 down := ev.type_ = SDL_JOYBUTTONDOWN;
535 e_LogWritefln('Input Debug: NOT IN RANGE! jbutton, joy=%s, button=%s, press=%s', [ev.jbutton.which, ev.jbutton.button, down])
536 end
537 end;
539 SDL_JOYAXISMOTION:
540 if (ev.jaxis.which < e_MaxJoys) and (ev.jaxis.axis < e_MaxJoyAxes) then
541 begin
542 key := e_JoyAxisToKey(ev.jaxis.which, ev.jaxis.axis, AX_PLUS);
543 minuskey := e_JoyAxisToKey(ev.jaxis.which, ev.jaxis.axis, AX_MINUS);
545 if g_dbg_input then
546 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]]);
548 if ev.jaxis.value < JoystickZeroAxes[ev.jaxis.which, ev.jaxis.axis] - e_JoystickDeadzones[ev.jaxis.which] then
549 begin
550 if (e_KeyPressed(key)) then
551 begin
552 e_KeyUpDown(key, False);
553 g_Console_ProcessBind(key, False);
554 end;
555 e_KeyUpDown(minuskey, True);
556 g_Console_ProcessBind(minuskey, True);
557 end
558 else if ev.jaxis.value > JoystickZeroAxes[ev.jaxis.which, ev.jaxis.axis] + e_JoystickDeadzones[ev.jaxis.which] then
559 begin
560 if (e_KeyPressed(minuskey)) then
561 begin
562 e_KeyUpDown(minuskey, False);
563 g_Console_ProcessBind(minuskey, False);
564 end;
565 e_KeyUpDown(key, True);
566 g_Console_ProcessBind(key, True);
567 end
568 else
569 begin
570 if (e_KeyPressed(minuskey)) then
571 begin
572 e_KeyUpDown(minuskey, False);
573 g_Console_ProcessBind(minuskey, False);
574 end;
575 if (e_KeyPressed(key)) then
576 begin
577 e_KeyUpDown(key, False);
578 g_Console_ProcessBind(key, False);
579 end;
580 end;
581 end
582 else
583 begin
584 if g_dbg_input then
585 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]])
586 end;
588 SDL_JOYHATMOTION:
589 if (ev.jhat.which < e_MaxJoys) and (ev.jhat.hat < e_MaxJoyHats) then
590 begin
591 if g_dbg_input then
592 e_LogWritefln('Input Debug: jhat, joy=%s, hat=%s, value=%s', [ev.jhat.which, ev.jhat.hat, ev.jhat.value]);
593 hat[HAT_UP] := LongBool(ev.jhat.value and SDL_HAT_UP);
594 hat[HAT_DOWN] := LongBool(ev.jhat.value and SDL_HAT_DOWN);
595 hat[HAT_LEFT] := LongBool(ev.jhat.value and SDL_HAT_LEFT);
596 hat[HAT_RIGHT] := LongBool(ev.jhat.value and SDL_HAT_RIGHT);
597 for i := HAT_LEFT to HAT_DOWN do
598 begin
599 if JoystickHatState[ev.jhat.which, ev.jhat.hat, i] <> hat[i] then
600 begin
601 down := hat[i];
602 key := e_JoyHatToKey(ev.jhat.which, ev.jhat.hat, i);
603 e_KeyUpDown(key, down);
604 g_Console_ProcessBind(key, down);
605 end
606 end;
607 JoystickHatState[ev.jhat.which, ev.jhat.hat] := hat
608 end
609 else
610 begin
611 if g_dbg_input then
612 e_LogWritefln('Input Debug: NOT IN RANGE! jhat, joy=%s, hat=%s, value=%s', [ev.jhat.which, ev.jhat.hat, ev.jhat.value])
613 end;
615 SDL_JOYDEVICEADDED:
616 if (ev.jdevice.which < e_MaxJoys) then
617 begin
618 JoystickHandle[ev.jdevice.which] := SDL_JoystickOpen(ev.jdevice.which);
619 if JoystickHandle[ev.jdevice.which] <> nil then
620 begin
621 e_LogWritefln('Added Joystick %s', [ev.jdevice.which]);
622 e_JoystickAvailable[ev.jdevice.which] := True;
623 for i := 0 to Min(SDL_JoystickNumAxes(JoystickHandle[ev.jdevice.which]), e_MaxJoyAxes) - 1 do
624 JoystickZeroAxes[ev.jdevice.which, i] := SDL_JoystickGetAxis(JoystickHandle[ev.jdevice.which], i)
625 end
626 else
627 e_LogWritefln('Warning! Failed to open Joystick %s', [ev.jdevice.which])
628 end
629 else
630 begin
631 e_LogWritefln('Warning! Added Joystick %s, but we support only <= %s', [ev.jdevice.which, e_MaxJoys])
632 end;
634 SDL_JOYDEVICEREMOVED:
635 begin
636 e_LogWritefln('Removed Joystick %s', [ev.jdevice.which]);
637 if (ev.jdevice.which < e_MaxJoys) then
638 begin
639 e_JoystickAvailable[ev.jdevice.which] := False;
640 if JoystickHandle[ev.jdevice.which] <> nil then
641 SDL_JoystickClose(JoystickHandle[ev.jdevice.which]);
642 JoystickHandle[ev.jdevice.which] := nil
643 end
644 end;
646 {$IF not DEFINED(HEADLESS) and DEFINED(ENABLE_HOLMES)}
647 SDL_MOUSEBUTTONDOWN, SDL_MOUSEBUTTONUP, SDL_MOUSEWHEEL, SDL_MOUSEMOTION:
648 fuiOnSDLEvent(ev);
649 {$ENDIF}
651 SDL_TEXTINPUT:
652 begin
653 if g_dbg_input then
654 e_LogWritefln('Input Debug: text, text=%s', [ev.text.text]);
655 Utf8ToUnicode(@uc, PChar(ev.text.text), 1);
656 keychr := Word(uc);
657 if (keychr > 127) then keychr := Word(wchar2win(WideChar(keychr)));
658 if (keychr > 0) and (keychr <= 255) then CharPress(AnsiChar(keychr));
659 end;
661 SDL_FINGERMOTION, SDL_FINGERDOWN, SDL_FINGERUP:
662 g_Touch_HandleEvent(ev.tfinger);
664 // other key presses and joysticks are handled in e_input
665 end;
666 end;
669 procedure SwapBuffers ();
670 begin
671 {$IF not DEFINED(HEADLESS)}
672 SDL_GL_SwapWindow(h_Wnd);
673 {$ENDIF}
674 end;
677 function CreateGLWindow (Title: PChar): Boolean;
678 begin
679 result := false;
681 gWinSizeX := gScreenWidth;
682 gWinSizeY := gScreenHeight;
684 {$IF not DEFINED(HEADLESS)}
685 wTitle := Title;
686 {$ENDIF}
687 e_WriteLog('Creating window', TMsgType.Notify);
689 if not g_Window_SetDisplay() then
690 begin
691 KillGLWindow(false);
692 e_WriteLog('Window creation error (resolution not supported?)', TMsgType.Fatal);
693 exit;
694 end;
696 {$IF not DEFINED(HEADLESS)}
697 h_GL := SDL_GL_CreateContext(h_Wnd);
698 if (h_GL = nil) then exit;
699 {$IFDEF ENABLE_HOLMES}
700 fuiScrWdt := gScreenWidth;
701 fuiScrHgt := gScreenHeight;
702 {$ENDIF}
703 SDL_GL_MakeCurrent(h_Wnd, h_GL);
704 {$IFDEF USE_NANOGL}
705 if nanoGL_Init() = 0 then
706 begin
707 KillGLWindow(false);
708 e_WriteLog('nanoGL initialization error', TMsgType.Fatal);
709 exit;
710 end;
711 {$ENDIF}
712 {$IFDEF USE_NOGL}
713 nogl_Init;
714 {$ENDIF}
715 {$IFDEF ENABLE_HOLMES}
716 if (assigned(oglInitCB)) then oglInitCB();
717 {$ENDIF}
718 if (h_GL <> nil) then g_SetVSync(gVSync);
719 {$ENDIF}
721 e_ResizeWindow(gScreenWidth, gScreenHeight);
722 e_InitGL();
724 result := true;
725 end;
728 {$IFDEF WINDOWS}
729 // windoze sux; in headless mode `GetTickCount()` (and SDL) returns shit
730 function GetTimer (): Int64;
731 var
732 F, C: Int64;
733 begin
734 QueryPerformanceFrequency(F);
735 QueryPerformanceCounter(C);
736 result := Round(C/F*1000{000});
737 end;
738 {$ELSE}
739 function GetTimer (): Int64;
740 var
741 t: Uint32;
742 tt: Int64;
743 begin
744 t := SDL_GetTicks();
745 if (ticksOverflow = -1) then
746 begin
747 ticksOverflow := 0;
748 lastTicks := t;
749 end
750 else
751 begin
752 if (lastTicks > t) then
753 begin
754 // overflow, increment overflow ;-)
755 ticksOverflow := ticksOverflow+(Int64($ffffffff)+Int64(1));
756 tt := (Int64($ffffffff)+Int64(1))+Int64(t);
757 t := Uint32(tt-lastTicks);
758 end;
759 end;
760 lastTicks := t;
761 result := ticksOverflow+Int64(t);
762 end;
763 {$ENDIF}
766 procedure ResetTimer ();
767 begin
768 wNeedTimeReset := true;
769 end;
772 procedure PushExitEvent ();
773 var
774 ev: TSDL_Event;
775 begin
776 ev.type_ := SDL_QUITEV;
777 SDL_PushEvent(@ev);
778 end;
781 var
782 prevLoadingUpdateTime: UInt64 = 0;
784 procedure ProcessLoading (forceUpdate: Boolean=false);
785 var
786 ev: TSDL_Event;
787 ID: LongWord;
788 stt: UInt64;
789 begin
790 FillChar(ev, sizeof(ev), 0);
791 wLoadingProgress := true;
793 while (SDL_PollEvent(@ev) > 0) do
794 begin
795 EventHandler(ev);
796 if (ev.type_ = SDL_QUITEV) then break;
797 end;
798 //e_PollJoysticks();
800 if (ev.type_ = SDL_QUITEV) or (gExit = EXIT_QUIT) then
801 begin
802 wLoadingProgress := false;
803 exit;
804 end;
806 if not wMinimized then
807 begin
808 if forceUpdate then
809 begin
810 prevLoadingUpdateTime := getTimeMilli();
811 end
812 else
813 begin
814 stt := getTimeMilli();
815 if (stt < prevLoadingUpdateTime) or (stt-prevLoadingUpdateTime >= ProgressUpdateMSecs) then
816 begin
817 prevLoadingUpdateTime := stt;
818 forceUpdate := true;
819 end;
820 end;
822 if forceUpdate then
823 begin
824 if g_Texture_Get('INTER', ID) then
825 begin
826 e_DrawSize(ID, 0, 0, 0, false, false, gScreenWidth, gScreenHeight);
827 e_DarkenQuadWH(0, 0, gScreenWidth, gScreenHeight, 150);
828 end
829 else
830 begin
831 e_Clear(GL_COLOR_BUFFER_BIT, 0, 0, 0);
832 end;
834 DrawLoadingStat();
835 SwapBuffers();
836 end;
837 end;
839 e_SoundUpdate();
841 if NetMode = NET_SERVER then
842 begin
843 g_Net_Host_Update();
844 end
845 else
846 begin
847 if (NetMode = NET_CLIENT) and (NetState <> NET_STATE_AUTH) then g_Net_Client_UpdateWhileLoading();
848 end;
850 wLoadingProgress := false;
851 end;
854 function g_ProcessMessages (): Boolean;
855 var
856 ev: TSDL_Event;
857 begin
858 result := false;
859 FillChar(ev, SizeOf(ev), 0);
860 while (SDL_PollEvent(@ev) > 0) do
861 begin
862 result := EventHandler(ev);
863 if (ev.type_ = SDL_QUITEV) then exit;
864 end;
865 //e_PollJoysticks();
866 end;
869 function ProcessMessage (): Boolean;
870 var
871 i, t: Integer;
872 begin
873 result := g_ProcessMessages();
875 Time := GetTimer();
876 Time_Delta := Time-Time_Old;
878 flag := false;
880 if wNeedTimeReset then
881 begin
882 Time_Delta := 28;
883 wNeedTimeReset := false;
884 end;
886 g_Map_ProfilersBegin();
887 g_Mons_ProfilersBegin();
889 t := Time_Delta div 28;
890 if (t > 0) then
891 begin
892 flag := true;
893 for i := 1 to t do
894 begin
895 if (NetMode = NET_SERVER) then g_Net_Host_Update()
896 else if (NetMode = NET_CLIENT) then g_Net_Client_Update();
897 Update();
898 end;
899 end
900 else
901 begin
902 if (NetMode = NET_SERVER) then g_Net_Host_Update()
903 else if (NetMode = NET_CLIENT) then g_Net_Client_Update();
904 end;
906 g_Map_ProfilersEnd();
907 g_Mons_ProfilersEnd();
909 if wLoadingQuit then
910 begin
911 g_Game_Free();
912 g_Game_Quit();
913 end;
915 if (gExit = EXIT_QUIT) then
916 begin
917 result := true;
918 exit;
919 end;
921 // Âðåìÿ ïðåäûäóùåãî îáíîâëåíèÿ
922 if flag then
923 begin
924 Time_Old := Time-(Time_Delta mod 28);
925 if (not wMinimized) then
926 begin
927 Draw();
928 SwapBuffers();
929 end;
930 end
931 else
932 begin
933 Sleep(1); // release time slice, so we won't eat 100% CPU
934 end;
936 e_SoundUpdate();
937 end;
940 procedure ReDrawWindow ();
941 begin
942 SwapBuffers();
943 end;
946 procedure g_SetVSync (vsync: Boolean);
947 {$IF not DEFINED(HEADLESS)}
948 var
949 v: Byte;
950 {$ENDIF}
951 begin
952 {$IF not DEFINED(HEADLESS)}
953 if vsync then v := 1 else v := 0;
954 if (SDL_GL_SetSwapInterval(v) <> 0) then
955 begin
956 e_WriteLog('oops; can''t change vsync option, restart required', TMsgType.Warning);
957 end
958 else
959 begin
960 if vsync then e_WriteLog('VSync: ON', TMsgType.Notify) else e_WriteLog('VSync: OFF', TMsgType.Notify);
961 end;
962 {$ENDIF}
963 end;
966 procedure InitOpenGL ();
967 begin
968 {$IF not DEFINED(HEADLESS)}
969 {$IFDEF USE_GLES1}
970 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 1);
971 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
972 SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES);
973 {$ELSE}
974 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
975 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
976 SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
977 SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
978 SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
979 SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
980 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
981 SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); // lights; it is enough to have 1-bit stencil buffer for lighting, but...
982 {$ENDIF}
983 {$ENDIF}
984 end;
987 function glHasExtension (const name: AnsiString): Boolean;
988 var
989 exts: PChar;
990 i: Integer;
991 found: Boolean;
992 extName: ShortString;
993 begin
994 result := false;
995 if (Length(name) = 0) then exit;
996 exts := glGetString(GL_EXTENSIONS);
997 if (exts = nil) then exit;
998 while (exts[0] <> #0) and (exts[0] = ' ') do Inc(exts);
999 while (exts[0] <> #0) do
1000 begin
1001 if gwin_dump_extensions then
1002 begin
1003 i := 0;
1004 while (exts[i] <> #0) and (exts[i] <> ' ') do Inc(i);
1005 if i > 255 then
1006 begin
1007 e_WriteLog('FUUUUUUUUUUUUU', TMsgType.Warning);
1008 end
1009 else
1010 begin
1011 Move(exts^, extName[1], i);
1012 extName[0] := Char(i);
1013 e_WriteLog(Format('EXT: %s', [extName]), TMsgType.Notify);
1014 end;
1015 end;
1016 found := true;
1017 for i := 0 to length(name)-1 do
1018 begin
1019 if (exts[i] = #0) then begin found := false; break; end;
1020 if (exts[i] <> name[i+1]) then begin found := false; break; end;
1021 end;
1022 if found and ((exts[Length(name)] = #0) or (exts[Length(name)] = ' ')) then begin result := true; exit; end;
1023 while (exts[0] <> #0) and (exts[0] <> ' ') do Inc(exts);
1024 while (exts[0] <> #0) and (exts[0] = ' ') do Inc(exts);
1025 end;
1026 end;
1029 function SDLMain (): Integer;
1030 var
1031 idx: Integer;
1032 {$IF not DEFINED(HEADLESS)}
1033 ltmp: Integer;
1034 {$ENDIF}
1035 arg: AnsiString;
1036 mdfo: TStream;
1037 {$IFDEF ENABLE_HOLMES}
1038 itmp: Integer;
1039 valres: Word;
1040 {$ENDIF}
1041 begin
1042 {$IFDEF HEADLESS}
1043 e_NoGraphics := true;
1044 {$ELSE}
1045 {$IFDEF ENABLE_HOLMES}
1046 if (not g_holmes_imfunctional) then
1047 begin
1048 uiInitialize();
1049 uiContext.font := 'win14';
1050 end;
1051 {$ENDIF}
1052 {$ENDIF}
1054 idx := 1;
1055 while (idx <= ParamCount) do
1056 begin
1057 arg := ParamStr(idx);
1058 Inc(idx);
1059 if arg = '--opengl-dump-exts' then gwin_dump_extensions := true;
1060 //if arg = '--twinkletwinkle' then gwin_k8_enable_light_experiments := true;
1061 if arg = '--jah' then g_profile_history_size := 100;
1062 if arg = '--no-particles' then gpart_dbg_enabled := false;
1063 if arg = '--no-los' then gmon_dbg_los_enabled := false;
1065 if arg = '--profile-render' then g_profile_frame_draw := true;
1066 if arg = '--profile-coldet' then g_profile_collision := true;
1067 if arg = '--profile-los' then g_profile_los := true;
1069 if arg = '--no-part-phys' then gpart_dbg_phys_enabled := false;
1070 if arg = '--no-part-physics' then gpart_dbg_phys_enabled := false;
1071 if arg = '--no-particles-phys' then gpart_dbg_phys_enabled := false;
1072 if arg = '--no-particles-physics' then gpart_dbg_phys_enabled := false;
1073 if arg = '--no-particle-phys' then gpart_dbg_phys_enabled := false;
1074 if arg = '--no-particle-physics' then gpart_dbg_phys_enabled := false;
1076 if arg = '--debug-input' then g_dbg_input := True;
1078 {.$IF DEFINED(D2F_DEBUG)}
1079 if arg = '--aimline' then g_dbg_aimline_on := true;
1080 {.$ENDIF}
1082 {$IFDEF ENABLE_HOLMES}
1083 if arg = '--holmes' then begin g_holmes_enabled := true; g_Game_SetDebugMode(); end;
1085 if (arg = '--holmes-ui-scale') or (arg = '-holmes-ui-scale') then
1086 begin
1087 if (idx <= ParamCount) then
1088 begin
1089 if not conParseFloat(fuiRenderScale, ParamStr(idx)) then fuiRenderScale := 1.0;
1090 Inc(idx);
1091 end;
1092 end;
1094 if (arg = '--holmes-font') or (arg = '-holmes-font') then
1095 begin
1096 if (idx <= ParamCount) then
1097 begin
1098 itmp := 0;
1099 val(ParamStr(idx), itmp, valres);
1100 {$IFNDEF HEADLESS}
1101 if (valres = 0) and (not g_holmes_imfunctional) then
1102 begin
1103 case itmp of
1104 8: uiContext.font := 'win8';
1105 14: uiContext.font := 'win14';
1106 16: uiContext.font := 'win16';
1107 end;
1108 end;
1109 {$ELSE}
1110 // fuck off, fpc!
1111 itmp := itmp;
1112 valres := valres;
1113 {$ENDIF}
1114 Inc(idx);
1115 end;
1116 end;
1117 {$ENDIF}
1119 if (arg = '--game-scale') or (arg = '-game-scale') then
1120 begin
1121 if (idx <= ParamCount) then
1122 begin
1123 if not conParseFloat(g_dbg_scale, ParamStr(idx)) then g_dbg_scale := 1.0;
1124 Inc(idx);
1125 end;
1126 end;
1128 if (arg = '--write-mapdef') or (arg = '-write-mapdef') then
1129 begin
1130 mdfo := createDiskFile('mapdef.txt');
1131 mdfo.WriteBuffer(defaultMapDef[1], Length(defaultMapDef));
1132 mdfo.Free();
1133 Halt(0);
1134 end;
1135 end;
1137 e_WriteLog('Initializing OpenGL', TMsgType.Notify);
1138 InitOpenGL();
1140 e_WriteLog('Creating GL window', TMsgType.Notify);
1141 if not CreateGLWindow(PChar(Format('Doom 2D: Forever %s', [GAME_VERSION]))) then
1142 begin
1143 result := 0;
1144 e_WriteLog('Unable to create GL window: ' + SDL_GetError(), TMsgType.Fatal);
1145 exit;
1146 end;
1148 {EnumDisplayModes();}
1150 {$IFDEF HEADLESS}
1151 //gwin_k8_enable_light_experiments := false;
1152 gwin_has_stencil := false;
1153 glLegacyNPOT := false;
1154 gwin_dump_extensions := false;
1155 {$ELSE}
1156 SDL_GL_GetAttribute(SDL_GL_STENCIL_SIZE, @ltmp);
1157 e_LogWritefln('stencil buffer size: %s', [ltmp]);
1158 gwin_has_stencil := (ltmp > 0);
1160 if glHasExtension('GL_ARB_texture_non_power_of_two') or
1161 glHasExtension('GL_OES_texture_npot') then
1162 begin
1163 e_WriteLog('NPOT textures: YES', TMsgType.Notify);
1164 glLegacyNPOT := false;
1165 end
1166 else
1167 begin
1168 e_WriteLog('NPOT textures: NO', TMsgType.Warning);
1169 glLegacyNPOT := true;
1170 end;
1171 gwin_dump_extensions := false;
1172 {$ENDIF}
1174 Init();
1175 Time_Old := GetTimer();
1177 // Êîìàíäíàÿ ñòðîêà
1178 if (ParamCount > 0) then g_Game_Process_Params();
1180 // Çàïðîñ ÿçûêà
1181 if (not gGameOn) and gAskLanguage then g_Menu_AskLanguage();
1183 e_WriteLog('Entering the main loop', TMsgType.Notify);
1185 // main loop
1186 while not ProcessMessage() do begin end;
1188 Release();
1189 KillGLWindow(false);
1191 result := 0;
1192 end;
1195 initialization
1196 conRegVar('d_input', @g_dbg_input, '', '')
1197 end.