DEADSOFTWARE

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