DEADSOFTWARE

5e91cc0f285e0dfbeb08bea4a3e2e4227bbc6f18
[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 var ltmp: Integer;
83 begin
84 result := true;
85 {$IFDEF NOGL_INIT}
86 nogl_Init;
87 if glRenderToFBO and (not nogl_ExtensionSupported('GL_OES_framebuffer_object')) then
88 begin
89 e_LogWriteln('GL: framebuffer objects not supported; disabling FBO rendering');
90 glRenderToFBO := false;
91 end;
92 {$ELSE}
93 if glRenderToFBO and (not Load_GL_ARB_framebuffer_object) then
94 begin
95 e_LogWriteln('GL: framebuffer objects not supported; disabling FBO rendering');
96 glRenderToFBO := false;
97 end;
98 {$ENDIF}
99 if SDL_GL_GetAttribute(SDL_GL_STENCIL_SIZE, @ltmp) = 0 then
100 begin
101 e_LogWritefln('stencil buffer size: %s', [ltmp]);
102 gwin_has_stencil := (ltmp > 0);
103 end;
104 end;
106 procedure FreeGL;
107 begin
108 {$IFDEF NOGL_INIT}
109 nogl_Quit();
110 {$ENDIF}
111 end;
113 function GetTitle (): AnsiString;
114 var info: AnsiString;
115 begin
116 info := g_GetBuildHash(false);
117 if info = 'custom build' then
118 info := info + ' by ' + g_GetBuilderName() + ' ' + GAME_BUILDDATE + ' ' + GAME_BUILDTIME;
119 result := Format(GameTitle, [info]);
120 end;
122 function InitWindow (w, h, bpp: Integer; fullScreen, maximized: Boolean): Boolean;
123 var flags: UInt32; x, y: cint; title: AnsiString;
124 begin
125 // note: on window close make: if assigned(oglDeinitCB) then oglDeinitCB;
126 e_LogWritefln('InitWindow %s %s %s %s', [w, h, bpp, fullScreen]);
127 result := false;
128 if window = nil then
129 begin
130 {$IFDEF USE_GLES1}
131 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 1);
132 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
133 SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES);
134 {$ELSE}
135 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
136 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
137 SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
138 SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
139 SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
140 SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
141 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
142 SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); // lights; it is enough to have 1-bit stencil buffer for lighting, but...
143 {$ENDIF}
144 flags := SDL_WINDOW_OPENGL or SDL_WINDOW_RESIZABLE;
145 if fullScreen then flags := flags or SDL_WINDOW_FULLSCREEN;
146 if maximized then flags := flags or SDL_WINDOW_MAXIMIZED;
147 if wc then
148 begin
149 x := SDL_WINDOWPOS_CENTERED;
150 y := SDL_WINDOWPOS_CENTERED
151 end
152 else
153 begin
154 x := wx;
155 y := wy
156 end;
157 title := GetTitle();
158 window := SDL_CreateWindow(PChar(title), x, y, w, h, flags);
159 if window <> nil then
160 begin
161 context := SDL_GL_CreateContext(window);
162 if context <> nil then
163 begin
164 if not LoadGL then
165 begin
166 e_LogWriteln('GL: unable to load OpenGL functions', TMsgType.Fatal);
167 SDL_GL_DeleteContext(context); context := nil;
168 exit;
169 end;
170 if (fullscreen = false) and (maximized = false) and (wc = false) then
171 begin
172 SDL_GetWindowPosition(window, @x, @y);
173 wx := x; wy := y
174 end;
175 gFullScreen := fullscreen;
176 gWinMaximized := maximized;
177 gRC_FullScreen := fullscreen;
178 gRC_Maximized := maximized;
179 if @sys_ScreenResize <> nil then
180 sys_ScreenResize(w, h);
181 result := true
182 end
183 else
184 begin
185 // SDL_DestroyWindow(window);
186 e_LogWritefln('SDL: unable to create OpenGL context: %s', [SDL_GetError])
187 end
188 end
189 else
190 begin
191 e_LogWritefln('SDL: unable to create window: %s', [SDL_GetError])
192 end
193 end
194 else
195 begin
196 if fullScreen then flags := SDL_WINDOW_FULLSCREEN else flags := 0;
197 SDL_SetWindowFullscreen(window, flags);
198 SDL_SetWindowSize(window, w, h);
199 if maximized then SDL_MaximizeWindow(window);
200 // always reset to center when changing fullscreen->windowed for safety purposes
201 if wc or (gFullscreen and not fullscreen) or (gWinMaximized and not maximized) then
202 begin
203 x := SDL_WINDOWPOS_CENTERED;
204 y := SDL_WINDOWPOS_CENTERED
205 end
206 else
207 begin
208 x := wx;
209 y := wy
210 end;
211 SDL_SetWindowPosition(window, x, y);
212 if (fullscreen = false) and (maximized = false) and (wc = false) then
213 begin
214 SDL_GetWindowPosition(window, @x, @y);
215 wx := x; wy := y
216 end;
217 gFullScreen := fullscreen;
218 gWinMaximized := maximized;
219 gRC_FullScreen := fullscreen;
220 gRC_Maximized := maximized;
221 if @sys_ScreenResize <> nil then
222 sys_ScreenResize(w, h);
223 result := true
224 end
225 end;
227 procedure sys_Repaint;
228 begin
229 SDL_GL_SwapWindow(window)
230 end;
232 procedure sys_EnableVSync (yes: Boolean);
233 begin
234 if yes then
235 SDL_GL_SetSwapInterval(1)
236 else
237 SDL_GL_SetSwapInterval(0)
238 end;
240 function sys_GetDisplayModes (bpp: Integer): SSArray;
241 var i, count, num, pw, ph: Integer; m: TSDL_DisplayMode;
242 begin
243 result := nil;
244 num := SDL_GetNumDisplayModes(display);
245 if num < 0 then
246 e_LogWritefln('SDL: unable to get numer of available display modes: %s', [SDL_GetError]);
247 if num > 0 then
248 begin
249 e_LogWritefln('Video modes for display %s:', [display]);
250 SetLength(result, num);
251 i := 0; count := 0; pw := 0; ph := 0;
252 while i < num do
253 begin
254 SDL_GetDisplayMode(display, i, @m);
255 if ((pw <> m.w) or (ph <> m.h)) then
256 begin
257 e_LogWritefln('* %sx%sx%s@%s', [m.w, m.h, SDL_BITSPERPIXEL(m.format), m.refresh_rate]);
258 pw := m.w; ph := m.h;
259 result[count] := IntToStr(m.w) + 'x' + IntToStr(m.h);
260 Inc(count);
261 end
262 else
263 begin
264 e_LogWritefln('- %sx%sx%s@%s', [m.w, m.h, SDL_BITSPERPIXEL(m.format), m.refresh_rate]);
265 end;
266 Inc(i)
267 end;
268 SetLength(result, count)
269 end
270 end;
272 function sys_SetDisplayMode (w, h, bpp: Integer; fullScreen, maximized: Boolean): Boolean;
273 begin
274 result := InitWindow(w, h, bpp, fullScreen, maximized)
275 end;
277 (* --------- Joystick --------- *)
279 procedure HandleJoyButton (var ev: TSDL_JoyButtonEvent);
280 var down: Boolean; key: Integer;
281 begin
282 if (ev.which < e_MaxJoys) and (ev.button < e_MaxJoyBtns) then
283 begin
284 key := e_JoyButtonToKey(ev.which, ev.button);
285 down := ev.type_ = SDL_JOYBUTTONDOWN;
286 if g_dbg_input then
287 e_LogWritefln('Input Debug: jbutton, joy=%s, button=%s, keycode=%s, press=%s', [ev.which, ev.button, key, down]);
288 e_KeyUpDown(key, down);
289 g_Console_ProcessBind(key, down)
290 end
291 else
292 begin
293 if g_dbg_input then
294 begin
295 down := ev.type_ = SDL_JOYBUTTONDOWN;
296 e_LogWritefln('Input Debug: NOT IN RANGE! jbutton, joy=%s, button=%s, press=%s', [ev.which, ev.button, down])
297 end
298 end
299 end;
301 procedure HandleJoyAxis (var ev: TSDL_JoyAxisEvent);
302 var key, minuskey: Integer;
303 begin
304 if (ev.which < e_MaxJoys) and (ev.axis < e_MaxJoyAxes) then
305 begin
306 key := e_JoyAxisToKey(ev.which, ev.axis, AX_PLUS);
307 minuskey := e_JoyAxisToKey(ev.which, ev.axis, AX_MINUS);
309 if g_dbg_input then
310 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]]);
312 if ev.value < JoystickZeroAxes[ev.which, ev.axis] - e_JoystickDeadzones[ev.which] then
313 begin
314 if (e_KeyPressed(key)) then
315 begin
316 e_KeyUpDown(key, False);
317 g_Console_ProcessBind(key, False)
318 end;
319 e_KeyUpDown(minuskey, True);
320 g_Console_ProcessBind(minuskey, True)
321 end
322 else if ev.value > JoystickZeroAxes[ev.which, ev.axis] + e_JoystickDeadzones[ev.which] then
323 begin
324 if (e_KeyPressed(minuskey)) then
325 begin
326 e_KeyUpDown(minuskey, False);
327 g_Console_ProcessBind(minuskey, False)
328 end;
329 e_KeyUpDown(key, True);
330 g_Console_ProcessBind(key, True)
331 end
332 else
333 begin
334 if (e_KeyPressed(minuskey)) then
335 begin
336 e_KeyUpDown(minuskey, False);
337 g_Console_ProcessBind(minuskey, False)
338 end;
339 if (e_KeyPressed(key)) then
340 begin
341 e_KeyUpDown(key, False);
342 g_Console_ProcessBind(key, False)
343 end
344 end
345 end
346 else
347 begin
348 if g_dbg_input then
349 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]])
350 end
351 end;
353 procedure HandleJoyHat (var ev: TSDL_JoyHatEvent);
354 var
355 down: Boolean;
356 i, key: Integer;
357 hat: array [HAT_LEFT..HAT_DOWN] of Boolean;
358 begin
359 if (ev.which < e_MaxJoys) and (ev.hat < e_MaxJoyHats) then
360 begin
361 if g_dbg_input then
362 e_LogWritefln('Input Debug: jhat, joy=%s, hat=%s, value=%s', [ev.which, ev.hat, ev.value]);
363 hat[HAT_UP] := LongBool(ev.value and SDL_HAT_UP);
364 hat[HAT_DOWN] := LongBool(ev.value and SDL_HAT_DOWN);
365 hat[HAT_LEFT] := LongBool(ev.value and SDL_HAT_LEFT);
366 hat[HAT_RIGHT] := LongBool(ev.value and SDL_HAT_RIGHT);
367 for i := HAT_LEFT to HAT_DOWN do
368 begin
369 if JoystickHatState[ev.which, ev.hat, i] <> hat[i] then
370 begin
371 down := hat[i];
372 key := e_JoyHatToKey(ev.which, ev.hat, i);
373 e_KeyUpDown(key, down);
374 g_Console_ProcessBind(key, down)
375 end
376 end;
377 JoystickHatState[ev.which, ev.hat] := hat
378 end
379 else
380 begin
381 if g_dbg_input then
382 e_LogWritefln('Input Debug: NOT IN RANGE! jhat, joy=%s, hat=%s, value=%s', [ev.which, ev.hat, ev.value])
383 end
384 end;
386 procedure HandleJoyAdd (var ev: TSDL_JoyDeviceEvent);
387 var i: Integer;
388 begin
389 if (ev.which < e_MaxJoys) then
390 begin
391 JoystickHandle[ev.which] := SDL_JoystickOpen(ev.which);
392 if JoystickHandle[ev.which] <> nil then
393 begin
394 e_LogWritefln('Added Joystick %s', [ev.which]);
395 e_JoystickAvailable[ev.which] := True;
396 for i := 0 to Min(SDL_JoystickNumAxes(JoystickHandle[ev.which]), e_MaxJoyAxes) - 1 do
397 JoystickZeroAxes[ev.which, i] := SDL_JoystickGetAxis(JoystickHandle[ev.which], i)
398 end
399 else
400 begin
401 e_LogWritefln('Warning! Failed to open Joystick %s', [ev.which])
402 end
403 end
404 else
405 begin
406 e_LogWritefln('Warning! Added Joystick %s, but we support only <= %s', [ev.which, e_MaxJoys])
407 end
408 end;
410 procedure HandleJoyRemove (var ev: TSDL_JoyDeviceEvent);
411 begin
412 e_LogWritefln('Removed Joystick %s', [ev.which]);
413 if (ev.which < e_MaxJoys) then
414 begin
415 e_JoystickAvailable[ev.which] := False;
416 if JoystickHandle[ev.which] <> nil then
417 SDL_JoystickClose(JoystickHandle[ev.which]);
418 JoystickHandle[ev.which] := nil
419 end
420 end;
422 (* --------- Input --------- *)
424 function HandleWindow (var ev: TSDL_WindowEvent): Boolean;
425 begin
426 result := false;
427 if g_dbg_input then
428 e_LogWritefln('Window Event: event = %s, data1 = %s, data2 = %s', [ev.event, ev.data1, ev.data2]);
429 case ev.event of
430 SDL_WINDOWEVENT_RESIZED:
431 if @sys_ScreenResize <> nil then
432 sys_ScreenResize(ev.data1, ev.data2);
433 SDL_WINDOWEVENT_EXPOSED: sys_Repaint;
434 SDL_WINDOWEVENT_CLOSE: result := true;
435 SDL_WINDOWEVENT_MOVED:
436 begin
437 wx := ev.data1;
438 wy := ev.data2
439 end;
440 SDL_WINDOWEVENT_FOCUS_LOST, SDL_WINDOWEVENT_MINIMIZED:
441 begin
442 e_UnpressAllKeys;
443 if gMuteWhenInactive then
444 e_MuteChannels(true);
445 {$IFDEF ENABLE_HOLMES}
446 if assigned(winBlurCB) then winBlurCB;
447 {$ENDIF}
448 end;
449 SDL_WINDOWEVENT_FOCUS_GAINED, SDL_WINDOWEVENT_MAXIMIZED, SDL_WINDOWEVENT_RESTORED:
450 begin
451 if ev.event = SDL_WINDOWEVENT_MAXIMIZED then
452 begin
453 gWinMaximized := true;
454 gRC_Maximized := true
455 end
456 else if ev.event = SDL_WINDOWEVENT_RESTORED then
457 begin
458 gWinMaximized := false;
459 gRC_Maximized := false
460 end;
461 e_MuteChannels(false);
462 {$IFDEF ENABLE_HOLMES}
463 if assigned(winFocusCB) then winFocusCB;
464 {$ENDIF}
465 end;
466 end
467 end;
469 procedure HandleKeyboard (var ev: TSDL_KeyboardEvent);
470 var down: Boolean; key: Integer;
471 begin
472 key := ev.keysym.scancode;
473 down := (ev.type_ = SDL_KEYDOWN);
474 if key = SDL_SCANCODE_AC_BACK then
475 key := SDL_SCANCODE_ESCAPE;
476 {$IFDEF ENABLE_HOLMES}
477 if fuiOnSDLEvent(PSDL_Event(@ev)^) then
478 begin
479 // event eaten, but...
480 if not down then e_KeyUpDown(key, false);
481 exit;
482 end;
483 {$ENDIF}
484 if ev._repeat = 0 then
485 begin
486 if g_dbg_input then
487 e_LogWritefln('Input Debug: keysym, press=%s, scancode=%s', [down, key]);
488 e_KeyUpDown(key, down);
489 g_Console_ProcessBind(key, down);
490 end
491 else
492 begin
493 if g_dbg_input then
494 e_LogWritefln('Input Debug: keyrep, scancode=%s', [key]);
495 g_Console_ProcessBindRepeat(key);
496 end
497 end;
499 procedure HandleTextInput (var ev: TSDL_TextInputEvent);
500 var ch: UnicodeChar; sch: AnsiChar;
501 begin
502 Utf8ToUnicode(@ch, PChar(ev.text), 1);
503 sch := AnsiChar(wchar2win(ch));
504 if g_dbg_input then
505 e_LogWritefln('Input Debug: text, text="%s", ch = %s, sch = %s', [ev.text, Ord(ch), Ord(sch)]);
506 if @sys_CharPress <> nil then
507 if IsValid1251(Word(ch)) and IsPrintable1251(ch) then
508 sys_CharPress(sch)
509 end;
511 function sys_HandleInput (): Boolean;
512 var ev: TSDL_Event;
513 begin
514 result := false;
515 ZeroMemory(@ev, sizeof(ev));
516 while SDL_PollEvent(@ev) <> 0 do
517 begin
518 case ev.type_ of
519 SDL_QUITEV: result := true;
520 SDL_WINDOWEVENT: result := HandleWindow(ev.window);
521 SDL_KEYUP, SDL_KEYDOWN: HandleKeyboard(ev.key);
522 SDL_JOYBUTTONDOWN, SDL_JOYBUTTONUP: HandleJoyButton(ev.jbutton);
523 SDL_JOYAXISMOTION: HandleJoyAxis(ev.jaxis);
524 SDL_JOYHATMOTION: HandleJoyHat(ev.jhat);
525 SDL_JOYDEVICEADDED: HandleJoyAdd(ev.jdevice);
526 SDL_JOYDEVICEREMOVED: HandleJoyRemove(ev.jdevice);
527 SDL_TEXTINPUT: HandleTextInput(ev.text);
528 SDL_FINGERMOTION, SDL_FINGERDOWN, SDL_FINGERUP: g_Touch_HandleEvent(ev.tfinger);
529 {$IFDEF ENABLE_HOLMES}
530 SDL_MOUSEBUTTONDOWN, SDL_MOUSEBUTTONUP, SDL_MOUSEWHEEL, SDL_MOUSEMOTION: fuiOnSDLEvent(ev);
531 {$ENDIF}
532 end
533 end
534 end;
536 procedure sys_RequestQuit;
537 var ev: TSDL_Event;
538 begin
539 ev.type_ := SDL_QUITEV;
540 SDL_PushEvent(@ev)
541 end;
543 (* --------- Init --------- *)
545 procedure sys_Init;
546 var flags: UInt32;
547 begin
548 e_WriteLog('Init SDL2', TMsgType.Notify);
549 {$IFDEF HEADLESS}
550 {$IFDEF USE_SDLMIXER}
551 flags := SDL_INIT_TIMER or SDL_INIT_AUDIO or $00004000;
552 {$ELSE}
553 flags := SDL_INIT_TIMER or $00004000;
554 {$ENDIF}
555 {$ELSE}
556 flags := SDL_INIT_TIMER or SDL_INIT_VIDEO;
557 {$ENDIF}
558 SDL_SetHint(SDL_HINT_ACCELEROMETER_AS_JOYSTICK, '0');
559 if SDL_Init(flags) <> 0 then
560 raise Exception.Create('SDL: Init failed: ' + SDL_GetError);
561 {$IFNDEF HEADLESS}
562 if SDL_InitSubSystem(SDL_INIT_JOYSTICK) <> 0 then
563 e_LogWritefln('SDL: Init subsystem failed: %s', [SDL_GetError()]);
564 {$ENDIF}
565 SDL_ShowCursor(SDL_DISABLE);
566 end;
568 procedure sys_Final;
569 begin
570 e_WriteLog('Releasing SDL2', TMsgType.Notify);
571 if context <> nil then
572 begin
573 FreeGL;
574 SDL_GL_DeleteContext(context);
575 context := nil;
576 end;
577 if window <> nil then
578 begin
579 SDL_DestroyWindow(window);
580 window := nil;
581 end;
582 SDL_Quit
583 end;
585 initialization
586 conRegVar('sdl2_display_index', @display, 'use display index as base', '');
587 conRegVar('sdl2_window_x', @wx, 'window position x', '');
588 conRegVar('sdl2_window_y', @wy, 'window position y', '');
589 conRegVar('sdl2_window_center', @wc, 'force window creation at center', '');
590 display := 0;
591 wx := SDL_WINDOWPOS_CENTERED;
592 wy := SDL_WINDOWPOS_CENTERED;
593 wc := false
594 end.