DEADSOFTWARE

render: move screen resize handler from io-driver
[d2df-sdl.git] / src / game / sdl2 / g_system.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, version 3 of the License ONLY.
6 *
7 * This program is distributed in the hope that it will be useful,
8 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 * GNU General Public License for more details.
11 *
12 * You should have received a copy of the GNU General Public License
13 * along with this program. If not, see <http://www.gnu.org/licenses/>.
14 *)
15 {$INCLUDE ../shared/a_modes.inc}
16 unit g_system;
18 interface
20 uses Utils;
22 (* --- Utils --- *)
23 function sys_GetTicks (): Int64;
24 procedure sys_Delay (ms: Integer);
26 (* --- Graphics --- *)
27 function sys_GetDisplayModes (bpp: Integer): SSArray;
28 function sys_SetDisplayMode (w, h, bpp: Integer; fullscreen, maximized: Boolean): Boolean;
29 procedure sys_EnableVSync (yes: Boolean);
30 procedure sys_Repaint;
32 (* --- Input --- *)
33 function sys_HandleInput (): Boolean;
34 procedure sys_RequestQuit;
36 (* --- Init --- *)
37 procedure sys_Init;
38 procedure sys_Final;
40 var (* hooks *)
41 sys_CharPress: procedure (ch: AnsiChar) = nil;
42 sys_ScreenResize: procedure (w, h: Integer) = nil;
44 implementation
46 uses
47 SysUtils, SDL2, Math, ctypes,
48 e_log, r_graphics, e_input, e_sound,
49 {$INCLUDE ../nogl/noGLuses.inc}
50 {$IFDEF ENABLE_HOLMES}
51 g_holmes, sdlcarcass, fui_ctls,
52 {$ENDIF}
53 g_touch, g_options, g_console, g_game, g_menu, g_gui, g_basic;
55 const
56 GameTitle = 'Doom 2D: Forever (SDL 2, %s)';
58 var
59 window: PSDL_Window;
60 context: TSDL_GLContext;
61 display, wx, wy: Integer;
62 wc: Boolean;
63 JoystickHandle: array [0..e_MaxJoys - 1] of PSDL_Joystick;
64 JoystickHatState: array [0..e_MaxJoys - 1, 0..e_MaxJoyHats - 1, HAT_LEFT..HAT_DOWN] of Boolean;
65 JoystickZeroAxes: array [0..e_MaxJoys - 1, 0..e_MaxJoyAxes - 1] of Integer;
67 (* --------- Utils --------- *)
69 function sys_GetTicks (): Int64;
70 begin
71 result := SDL_GetTicks()
72 end;
74 procedure sys_Delay (ms: Integer);
75 begin
76 SDL_Delay(ms)
77 end;
79 (* --------- Graphics --------- *)
81 function LoadGL: Boolean;
82 begin
83 result := true;
84 {$IFDEF NOGL_INIT}
85 nogl_Init;
86 if glRenderToFBO and (not nogl_ExtensionSupported('GL_OES_framebuffer_object')) then
87 {$ELSE}
88 if glRenderToFBO and (not Load_GL_ARB_framebuffer_object) then
89 {$ENDIF}
90 begin
91 e_LogWriteln('GL: framebuffer objects not supported; disabling FBO rendering');
92 glRenderToFBO := false;
93 end;
94 end;
96 procedure FreeGL;
97 begin
98 {$IFDEF NOGL_INIT}
99 nogl_Quit();
100 {$ENDIF}
101 end;
103 function GetTitle (): PChar;
104 var info: AnsiString;
105 begin
106 info := g_GetBuildHash(false);
107 if info = 'custom build' then
108 info := info + ' by ' + g_GetBuilderName() + ' ' + GAME_BUILDDATE + ' ' + GAME_BUILDTIME;
109 result := PChar(Format(GameTitle, [info]))
110 end;
112 function InitWindow (w, h, bpp: Integer; fullScreen, maximized: Boolean): Boolean;
113 var flags: UInt32; x, y: cint;
114 begin
115 // note: on window close make: if assigned(oglDeinitCB) then oglDeinitCB;
116 e_LogWritefln('InitWindow %s %s %s %s', [w, h, bpp, fullScreen]);
117 result := false;
118 if window = nil then
119 begin
120 {$IFDEF USE_GLES1}
121 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 1);
122 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
123 SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES);
124 {$ELSE}
125 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
126 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
127 SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
128 SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
129 SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
130 SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
131 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
132 SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); // lights; it is enough to have 1-bit stencil buffer for lighting, but...
133 {$ENDIF}
134 flags := SDL_WINDOW_OPENGL or SDL_WINDOW_RESIZABLE;
135 if fullScreen then flags := flags or SDL_WINDOW_FULLSCREEN;
136 if maximized then flags := flags or SDL_WINDOW_MAXIMIZED;
137 if wc then
138 begin
139 x := SDL_WINDOWPOS_CENTERED;
140 y := SDL_WINDOWPOS_CENTERED
141 end
142 else
143 begin
144 x := wx;
145 y := wy
146 end;
147 window := SDL_CreateWindow(GetTitle(), x, y, w, h, flags);
148 if window <> nil then
149 begin
150 context := SDL_GL_CreateContext(window);
151 if context <> nil then
152 begin
153 if not LoadGL then
154 begin
155 e_LogWriteln('GL: unable to load OpenGL functions', TMsgType.Fatal);
156 SDL_GL_DeleteContext(context); context := nil;
157 exit;
158 end;
159 if (fullscreen = false) and (maximized = false) and (wc = false) then
160 begin
161 SDL_GetWindowPosition(window, @x, @y);
162 wx := x; wy := y
163 end;
164 gFullScreen := fullscreen;
165 gWinMaximized := maximized;
166 gRC_FullScreen := fullscreen;
167 gRC_Maximized := maximized;
168 if @sys_ScreenResize <> nil then
169 sys_ScreenResize(w, h);
170 result := true
171 end
172 else
173 begin
174 // SDL_DestroyWindow(window);
175 e_LogWritefln('SDL: unable to create OpenGL context: %s', [SDL_GetError])
176 end
177 end
178 else
179 begin
180 e_LogWritefln('SDL: unable to create window: %s', [SDL_GetError])
181 end
182 end
183 else
184 begin
185 if fullScreen then flags := SDL_WINDOW_FULLSCREEN else flags := 0;
186 SDL_SetWindowFullscreen(window, flags);
187 SDL_SetWindowSize(window, w, h);
188 if maximized then SDL_MaximizeWindow(window);
189 // always reset to center when changing fullscreen->windowed for safety purposes
190 if wc or (gFullscreen and not fullscreen) or (gWinMaximized and not maximized) then
191 begin
192 x := SDL_WINDOWPOS_CENTERED;
193 y := SDL_WINDOWPOS_CENTERED
194 end
195 else
196 begin
197 x := wx;
198 y := wy
199 end;
200 SDL_SetWindowPosition(window, x, y);
201 if (fullscreen = false) and (maximized = false) and (wc = false) then
202 begin
203 SDL_GetWindowPosition(window, @x, @y);
204 wx := x; wy := y
205 end;
206 gFullScreen := fullscreen;
207 gWinMaximized := maximized;
208 gRC_FullScreen := fullscreen;
209 gRC_Maximized := maximized;
210 if @sys_ScreenResize <> nil then
211 sys_ScreenResize(w, h);
212 result := true
213 end
214 end;
216 procedure sys_Repaint;
217 begin
218 SDL_GL_SwapWindow(window)
219 end;
221 procedure sys_EnableVSync (yes: Boolean);
222 begin
223 if yes then
224 SDL_GL_SetSwapInterval(1)
225 else
226 SDL_GL_SetSwapInterval(0)
227 end;
229 function sys_GetDisplayModes (bpp: Integer): SSArray;
230 var i, count, num, pw, ph: Integer; m: TSDL_DisplayMode;
231 begin
232 result := nil;
233 num := SDL_GetNumDisplayModes(display);
234 if num < 0 then
235 e_LogWritefln('SDL: unable to get numer of available display modes: %s', [SDL_GetError]);
236 if num > 0 then
237 begin
238 e_LogWritefln('Video modes for display %s:', [display]);
239 SetLength(result, num);
240 i := 0; count := 0; pw := 0; ph := 0;
241 while i < num do
242 begin
243 SDL_GetDisplayMode(display, i, @m);
244 if ((pw <> m.w) or (ph <> m.h)) then
245 begin
246 e_LogWritefln('* %sx%sx%s@%s', [m.w, m.h, SDL_BITSPERPIXEL(m.format), m.refresh_rate]);
247 pw := m.w; ph := m.h;
248 result[count] := IntToStr(m.w) + 'x' + IntToStr(m.h);
249 Inc(count);
250 end
251 else
252 begin
253 e_LogWritefln('- %sx%sx%s@%s', [m.w, m.h, SDL_BITSPERPIXEL(m.format), m.refresh_rate]);
254 end;
255 Inc(i)
256 end;
257 SetLength(result, count)
258 end
259 end;
261 function sys_SetDisplayMode (w, h, bpp: Integer; fullScreen, maximized: Boolean): Boolean;
262 begin
263 result := InitWindow(w, h, bpp, fullScreen, maximized)
264 end;
266 (* --------- Joystick --------- *)
268 procedure HandleJoyButton (var ev: TSDL_JoyButtonEvent);
269 var down: Boolean; key: Integer;
270 begin
271 if (ev.which < e_MaxJoys) and (ev.button < e_MaxJoyBtns) then
272 begin
273 key := e_JoyButtonToKey(ev.which, ev.button);
274 down := ev.type_ = SDL_JOYBUTTONDOWN;
275 if g_dbg_input then
276 e_LogWritefln('Input Debug: jbutton, joy=%s, button=%s, keycode=%s, press=%s', [ev.which, ev.button, key, down]);
277 e_KeyUpDown(key, down);
278 g_Console_ProcessBind(key, down)
279 end
280 else
281 begin
282 if g_dbg_input then
283 begin
284 down := ev.type_ = SDL_JOYBUTTONDOWN;
285 e_LogWritefln('Input Debug: NOT IN RANGE! jbutton, joy=%s, button=%s, press=%s', [ev.which, ev.button, down])
286 end
287 end
288 end;
290 procedure HandleJoyAxis (var ev: TSDL_JoyAxisEvent);
291 var key, minuskey: Integer;
292 begin
293 if (ev.which < e_MaxJoys) and (ev.axis < e_MaxJoyAxes) then
294 begin
295 key := e_JoyAxisToKey(ev.which, ev.axis, AX_PLUS);
296 minuskey := e_JoyAxisToKey(ev.which, ev.axis, AX_MINUS);
298 if g_dbg_input then
299 e_LogWritefln('Input Debug: jaxis, joy=%s, axis=%s, value=%s, zeroaxes=%s, deadzone=%s', [ev.which, ev.axis, ev.value, JoystickZeroAxes[ev.which, ev.axis], e_JoystickDeadzones[ev.which]]);
301 if ev.value < JoystickZeroAxes[ev.which, ev.axis] - e_JoystickDeadzones[ev.which] then
302 begin
303 if (e_KeyPressed(key)) then
304 begin
305 e_KeyUpDown(key, False);
306 g_Console_ProcessBind(key, False)
307 end;
308 e_KeyUpDown(minuskey, True);
309 g_Console_ProcessBind(minuskey, True)
310 end
311 else if ev.value > JoystickZeroAxes[ev.which, ev.axis] + e_JoystickDeadzones[ev.which] then
312 begin
313 if (e_KeyPressed(minuskey)) then
314 begin
315 e_KeyUpDown(minuskey, False);
316 g_Console_ProcessBind(minuskey, False)
317 end;
318 e_KeyUpDown(key, True);
319 g_Console_ProcessBind(key, True)
320 end
321 else
322 begin
323 if (e_KeyPressed(minuskey)) then
324 begin
325 e_KeyUpDown(minuskey, False);
326 g_Console_ProcessBind(minuskey, False)
327 end;
328 if (e_KeyPressed(key)) then
329 begin
330 e_KeyUpDown(key, False);
331 g_Console_ProcessBind(key, False)
332 end
333 end
334 end
335 else
336 begin
337 if g_dbg_input then
338 e_LogWritefln('Input Debug: NOT IN RANGE! jaxis, joy=%s, axis=%s, value=%s, zeroaxes=%s, deadzone=%s', [ev.which, ev.axis, ev.value, JoystickZeroAxes[ev.which, ev.axis], e_JoystickDeadzones[ev.which]])
339 end
340 end;
342 procedure HandleJoyHat (var ev: TSDL_JoyHatEvent);
343 var
344 down: Boolean;
345 i, key: Integer;
346 hat: array [HAT_LEFT..HAT_DOWN] of Boolean;
347 begin
348 if (ev.which < e_MaxJoys) and (ev.hat < e_MaxJoyHats) then
349 begin
350 if g_dbg_input then
351 e_LogWritefln('Input Debug: jhat, joy=%s, hat=%s, value=%s', [ev.which, ev.hat, ev.value]);
352 hat[HAT_UP] := LongBool(ev.value and SDL_HAT_UP);
353 hat[HAT_DOWN] := LongBool(ev.value and SDL_HAT_DOWN);
354 hat[HAT_LEFT] := LongBool(ev.value and SDL_HAT_LEFT);
355 hat[HAT_RIGHT] := LongBool(ev.value and SDL_HAT_RIGHT);
356 for i := HAT_LEFT to HAT_DOWN do
357 begin
358 if JoystickHatState[ev.which, ev.hat, i] <> hat[i] then
359 begin
360 down := hat[i];
361 key := e_JoyHatToKey(ev.which, ev.hat, i);
362 e_KeyUpDown(key, down);
363 g_Console_ProcessBind(key, down)
364 end
365 end;
366 JoystickHatState[ev.which, ev.hat] := hat
367 end
368 else
369 begin
370 if g_dbg_input then
371 e_LogWritefln('Input Debug: NOT IN RANGE! jhat, joy=%s, hat=%s, value=%s', [ev.which, ev.hat, ev.value])
372 end
373 end;
375 procedure HandleJoyAdd (var ev: TSDL_JoyDeviceEvent);
376 var i: Integer;
377 begin
378 if (ev.which < e_MaxJoys) then
379 begin
380 JoystickHandle[ev.which] := SDL_JoystickOpen(ev.which);
381 if JoystickHandle[ev.which] <> nil then
382 begin
383 e_LogWritefln('Added Joystick %s', [ev.which]);
384 e_JoystickAvailable[ev.which] := True;
385 for i := 0 to Min(SDL_JoystickNumAxes(JoystickHandle[ev.which]), e_MaxJoyAxes) - 1 do
386 JoystickZeroAxes[ev.which, i] := SDL_JoystickGetAxis(JoystickHandle[ev.which], i)
387 end
388 else
389 begin
390 e_LogWritefln('Warning! Failed to open Joystick %s', [ev.which])
391 end
392 end
393 else
394 begin
395 e_LogWritefln('Warning! Added Joystick %s, but we support only <= %s', [ev.which, e_MaxJoys])
396 end
397 end;
399 procedure HandleJoyRemove (var ev: TSDL_JoyDeviceEvent);
400 begin
401 e_LogWritefln('Removed Joystick %s', [ev.which]);
402 if (ev.which < e_MaxJoys) then
403 begin
404 e_JoystickAvailable[ev.which] := False;
405 if JoystickHandle[ev.which] <> nil then
406 SDL_JoystickClose(JoystickHandle[ev.which]);
407 JoystickHandle[ev.which] := nil
408 end
409 end;
411 (* --------- Input --------- *)
413 function HandleWindow (var ev: TSDL_WindowEvent): Boolean;
414 begin
415 result := false;
416 if g_dbg_input then
417 e_LogWritefln('Window Event: event = %s, data1 = %s, data2 = %s', [ev.event, ev.data1, ev.data2]);
418 case ev.event of
419 SDL_WINDOWEVENT_RESIZED:
420 if @sys_ScreenResize <> nil then
421 sys_ScreenResize(ev.data1, ev.data2);
422 SDL_WINDOWEVENT_EXPOSED: sys_Repaint;
423 SDL_WINDOWEVENT_CLOSE: result := true;
424 SDL_WINDOWEVENT_MOVED:
425 begin
426 wx := ev.data1;
427 wy := ev.data2
428 end;
429 SDL_WINDOWEVENT_FOCUS_LOST, SDL_WINDOWEVENT_MINIMIZED:
430 begin
431 e_UnpressAllKeys;
432 if gMuteWhenInactive then
433 e_MuteChannels(true);
434 {$IFDEF ENABLE_HOLMES}
435 if assigned(winBlurCB) then winBlurCB;
436 {$ENDIF}
437 end;
438 SDL_WINDOWEVENT_FOCUS_GAINED, SDL_WINDOWEVENT_MAXIMIZED, SDL_WINDOWEVENT_RESTORED:
439 begin
440 if ev.event = SDL_WINDOWEVENT_MAXIMIZED then
441 begin
442 gWinMaximized := true;
443 gRC_Maximized := true
444 end
445 else if ev.event = SDL_WINDOWEVENT_RESTORED then
446 begin
447 gWinMaximized := false;
448 gRC_Maximized := false
449 end;
450 e_MuteChannels(false);
451 {$IFDEF ENABLE_HOLMES}
452 if assigned(winFocusCB) then winFocusCB;
453 {$ENDIF}
454 end;
455 end
456 end;
458 procedure HandleKeyboard (var ev: TSDL_KeyboardEvent);
459 var down: Boolean; key: Integer;
460 begin
461 key := ev.keysym.scancode;
462 down := (ev.type_ = SDL_KEYDOWN);
463 if key = SDL_SCANCODE_AC_BACK then
464 key := SDL_SCANCODE_ESCAPE;
465 {$IFDEF ENABLE_HOLMES}
466 if fuiOnSDLEvent(PSDL_Event(@ev)^) then
467 begin
468 // event eaten, but...
469 if not down then e_KeyUpDown(key, false);
470 exit;
471 end;
472 {$ENDIF}
473 if ev._repeat = 0 then
474 begin
475 if g_dbg_input then
476 e_LogWritefln('Input Debug: keysym, press=%s, scancode=%s', [down, key]);
477 e_KeyUpDown(key, down);
478 g_Console_ProcessBind(key, down);
479 end
480 else
481 begin
482 if g_dbg_input then
483 e_LogWritefln('Input Debug: keyrep, scancode=%s', [key]);
484 g_Console_ProcessBindRepeat(key);
485 end
486 end;
488 procedure HandleTextInput (var ev: TSDL_TextInputEvent);
489 var ch: UnicodeChar; sch: AnsiChar;
490 begin
491 Utf8ToUnicode(@ch, PChar(ev.text), 1);
492 sch := AnsiChar(wchar2win(ch));
493 if g_dbg_input then
494 e_LogWritefln('Input Debug: text, text="%s", ch = %s, sch = %s', [ev.text, Ord(ch), Ord(sch)]);
495 if @sys_CharPress <> nil then
496 if IsValid1251(Word(ch)) and IsPrintable1251(ch) then
497 sys_CharPress(sch)
498 end;
500 function sys_HandleInput (): Boolean;
501 var ev: TSDL_Event;
502 begin
503 result := false;
504 ZeroMemory(@ev, sizeof(ev));
505 while SDL_PollEvent(@ev) <> 0 do
506 begin
507 case ev.type_ of
508 SDL_QUITEV: result := true;
509 SDL_WINDOWEVENT: result := HandleWindow(ev.window);
510 SDL_KEYUP, SDL_KEYDOWN: HandleKeyboard(ev.key);
511 SDL_JOYBUTTONDOWN, SDL_JOYBUTTONUP: HandleJoyButton(ev.jbutton);
512 SDL_JOYAXISMOTION: HandleJoyAxis(ev.jaxis);
513 SDL_JOYHATMOTION: HandleJoyHat(ev.jhat);
514 SDL_JOYDEVICEADDED: HandleJoyAdd(ev.jdevice);
515 SDL_JOYDEVICEREMOVED: HandleJoyRemove(ev.jdevice);
516 SDL_TEXTINPUT: HandleTextInput(ev.text);
517 SDL_FINGERMOTION, SDL_FINGERDOWN, SDL_FINGERUP: g_Touch_HandleEvent(ev.tfinger);
518 {$IFDEF ENABLE_HOLMES}
519 SDL_MOUSEBUTTONDOWN, SDL_MOUSEBUTTONUP, SDL_MOUSEWHEEL, SDL_MOUSEMOTION: fuiOnSDLEvent(ev);
520 {$ENDIF}
521 end
522 end
523 end;
525 procedure sys_RequestQuit;
526 var ev: TSDL_Event;
527 begin
528 ev.type_ := SDL_QUITEV;
529 SDL_PushEvent(@ev)
530 end;
532 (* --------- Init --------- *)
534 procedure sys_Init;
535 var flags: UInt32;
536 begin
537 e_WriteLog('Init SDL2', TMsgType.Notify);
538 {$IFDEF HEADLESS}
539 {$IFDEF USE_SDLMIXER}
540 flags := SDL_INIT_TIMER or SDL_INIT_AUDIO or $00004000;
541 {$ELSE}
542 flags := SDL_INIT_TIMER or $00004000;
543 {$ENDIF}
544 {$ELSE}
545 flags := SDL_INIT_TIMER or SDL_INIT_VIDEO;
546 {$ENDIF}
547 SDL_SetHint(SDL_HINT_ACCELEROMETER_AS_JOYSTICK, '0');
548 if SDL_Init(flags) <> 0 then
549 raise Exception.Create('SDL: Init failed: ' + SDL_GetError);
550 {$IFNDEF HEADLESS}
551 if SDL_InitSubSystem(SDL_INIT_JOYSTICK) <> 0 then
552 e_LogWritefln('SDL: Init subsystem failed: %s', [SDL_GetError()]);
553 {$ENDIF}
554 SDL_ShowCursor(SDL_DISABLE);
555 end;
557 procedure sys_Final;
558 begin
559 e_WriteLog('Releasing SDL2', TMsgType.Notify);
560 if context <> nil then
561 begin
562 FreeGL;
563 SDL_GL_DeleteContext(context);
564 context := nil;
565 end;
566 if window <> nil then
567 begin
568 SDL_DestroyWindow(window);
569 window := nil;
570 end;
571 SDL_Quit
572 end;
574 initialization
575 conRegVar('sdl2_display_index', @display, 'use display index as base', '');
576 conRegVar('sdl2_window_x', @wx, 'window position x', '');
577 conRegVar('sdl2_window_y', @wy, 'window position y', '');
578 conRegVar('sdl2_window_center', @wc, 'force window creation at center', '');
579 display := 0;
580 wx := SDL_WINDOWPOS_CENTERED;
581 wy := SDL_WINDOWPOS_CENTERED;
582 wc := false
583 end.