DEADSOFTWARE

cleanup: move init and main loop code from g_window
[d2df-sdl.git] / src / game / Doom2DF.lpr
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 {$IFDEF ANDROID}library{$ELSE}program{$ENDIF} Doom2DF;
18 {$IFNDEF HEADLESS}
19 {$IFDEF WINDOWS}
20 {$APPTYPE GUI}
21 {$ENDIF}
22 {$ENDIF}
23 {$HINTS OFF}
25 uses
26 {$IFDEF ANDROID}
27 ctypes,
28 {$ENDIF}
29 {$IFDEF UNIX}
30 cthreads, BaseUnix,
31 {$ENDIF}
32 {$IFDEF DARWIN}
33 MacOSAll, CocoaAll,
34 {$ENDIF}
35 mempool in '../shared/mempool.pas',
36 conbuf in '../shared/conbuf.pas',
37 geom in '../shared/geom.pas',
38 math,
40 {$IFDEF USE_MINIUPNPC}
41 miniupnpc in '../lib/miniupnpc/miniupnpc.pas',
42 {$ENDIF}
44 {$IFDEF USE_SDL}
45 SDL,
46 {$IFDEF USE_SDLMIXER}
47 SDL_mixer,
48 {$ENDIF}
49 {$ENDIF}
50 {$IFDEF USE_SDL2}
51 SDL2 in '../lib/sdl2/sdl2.pas',
52 {$IFDEF USE_SDLMIXER}
53 SDL2_mixer in '../lib/sdl2/SDL2_mixer.pas',
54 {$ENDIF}
55 {$ENDIF}
56 {$IFDEF USE_SYSSTUB}
57 {$IFDEF USE_SDLMIXER}
58 SDL2 in '../lib/sdl2/sdl2.pas',
59 SDL2_mixer in '../lib/sdl2/SDL2_mixer.pas',
60 {$ENDIF}
61 {$ENDIF}
63 {$IFDEF USE_OPENAL}
64 AL in '../lib/openal/al.pas',
65 e_soundfile in '../engine/e_soundfile.pas',
66 {$IF DEFINED(USE_SDL) OR DEFINED(USE_SDL2)}
67 e_soundfile_wav in '../engine/e_soundfile_wav.pas',
68 {$ENDIF}
69 {$IFDEF USE_VORBIS}
70 vorbis in '../lib/vorbis/vorbis.pas',
71 e_soundfile_vorbis in '../engine/e_soundfile_vorbis.pas',
72 {$ENDIF}
73 {$IFDEF USE_FLUIDSYNTH}
74 fluidsynth in '../lib/fluidsynth/fluidsynth.pas',
75 e_soundfile_fluid in '../engine/e_soundfile_fluid.pas',
76 {$ENDIF}
77 {$IFDEF USE_MODPLUG}
78 modplug in '../lib/modplug/modplug.pas',
79 e_soundfile_modplug in '../engine/e_soundfile_modplug.pas',
80 {$ENDIF}
81 {$IFDEF USE_XMP}
82 xmp in '../lib/xmp/xmp.pas',
83 e_soundfile_xmp in '../engine/e_soundfile_xmp.pas',
84 {$ENDIF}
85 {$IFDEF USE_GME}
86 gme in '../lib/gme/gme.pas',
87 e_soundfile_gme in '../engine/e_soundfile_gme.pas',
88 {$ENDIF}
89 {$IFDEF USE_MPG123}
90 mpg123 in '../lib/mpg123/mpg123.pas',
91 e_soundfile_mp3 in '../engine/e_soundfile_mp3.pas',
92 {$ENDIF}
93 {$IFDEF USE_OPUS}
94 opus in '../lib/opus/opus.pas',
95 e_soundfile_opus in '../engine/e_soundfile_opus.pas',
96 {$ENDIF}
97 {$IF DEFINED(USE_VORBIS) OR DEFINED(USE_OPUS)}
98 ogg in '../lib/vorbis/ogg.pas', // this has to come last because link order
99 {$ENDIF}
100 {$ENDIF}
102 ENet in '../lib/enet/enet.pp',
103 e_input in '../engine/e_input.pas',
104 e_log in '../engine/e_log.pas',
105 e_sound in '../engine/e_sound.pas',
106 e_msg in '../engine/e_msg.pas',
107 e_res in '../engine/e_res.pas',
108 utils in '../shared/utils.pas',
109 xstreams in '../shared/xstreams.pas',
110 sfs in '../sfs/sfs.pas',
111 sfsPlainFS in '../sfs/sfsPlainFS.pas',
112 sfsZipFS in '../sfs/sfsZipFS.pas',
113 wadreader in '../shared/wadreader.pas',
114 MAPDEF in '../shared/MAPDEF.pas',
115 CONFIG in '../shared/CONFIG.pas',
116 g_base in 'g_base.pas',
117 g_basic in 'g_basic.pas',
118 g_console in 'g_console.pas',
119 g_net in 'g_net.pas',
120 g_netmsg in 'g_netmsg.pas',
121 g_nethandler in 'g_nethandler.pas',
122 g_netmaster in 'g_netmaster.pas',
123 g_res_downloader in 'g_res_downloader.pas',
124 g_grid in 'g_grid.pas',
125 g_game in 'g_game.pas',
126 g_gfx in 'g_gfx.pas',
127 g_gui in 'g_gui.pas',
128 g_items in 'g_items.pas',
129 g_map in 'g_map.pas',
130 g_menu in 'g_menu.pas',
131 g_monsters in 'g_monsters.pas',
132 g_options in 'g_options.pas',
133 g_phys in 'g_phys.pas',
134 g_player in 'g_player.pas',
135 g_playermodel in 'g_playermodel.pas',
136 g_saveload in 'g_saveload.pas',
137 g_sound in 'g_sound.pas',
138 g_textures in 'g_textures.pas',
139 g_triggers in 'g_triggers.pas',
140 g_weapons in 'g_weapons.pas',
141 g_window in 'g_window.pas',
142 {$IFDEF USE_SYSSTUB}
143 g_system in 'stub/g_system.pas',
144 g_touch in 'stub/g_touch.pas',
145 {$ENDIF}
146 {$IFDEF USE_SDL}
147 g_system in 'sdl/g_system.pas',
148 g_touch in 'sdl/g_touch.pas',
149 {$ENDIF}
150 {$IFDEF USE_SDL2}
151 g_system in 'sdl2/g_system.pas',
152 g_touch in 'sdl2/g_touch.pas',
153 {$ENDIF}
155 r_console in 'opengl/r_console.pas',
156 r_game in 'opengl/r_game.pas',
157 r_gfx in 'opengl/r_gfx.pas',
158 r_graphics in 'opengl/r_graphics.pas',
159 r_items in 'opengl/r_items.pas',
160 r_map in 'opengl/r_map.pas',
161 r_monsters in 'opengl/r_monsters.pas',
162 r_netmaster in 'opengl/r_netmaster.pas',
163 r_panel in 'opengl/r_panel.pas',
164 r_player in 'opengl/r_player.pas',
165 r_playermodel in 'opengl/r_playermodel.pas',
166 r_texture in 'opengl/r_texture.pas',
167 r_weapons in 'opengl/r_weapons.pas',
168 r_window in 'opengl/r_window.pas',
170 {$IFDEF USE_FMOD}
171 fmod in '../lib/FMOD/fmod.pas',
172 fmoderrors in '../lib/FMOD/fmoderrors.pas',
173 fmodpresets in '../lib/FMOD/fmodpresets.pas',
174 fmodtypes in '../lib/FMOD/fmodtypes.pas',
175 {$ENDIF}
176 xprofiler in '../shared/xprofiler.pas',
177 binheap in '../shared/binheap.pas',
178 hashtable in '../shared/hashtable.pas',
179 fhashdb in '../shared/fhashdb.pas',
180 idpool in '../shared/idpool.pas',
181 xparser in '../shared/xparser.pas',
182 xdynrec in '../shared/xdynrec.pas',
183 exoma in '../shared/exoma.pas',
184 envvars in '../shared/envvars.pas',
185 g_panel in 'g_panel.pas',
186 g_language in 'g_language.pas',
188 {$IFDEF ENABLE_HOLMES}
189 g_holmes in 'g_holmes.pas',
191 sdlcarcass in '../flexui/sdlcarcass.pas',
192 //sdlstandalone in '../flexui/sdlstandalone.pas',
194 fui_wadread in '../flexui/fui_wadread.pas',
195 fui_common in '../flexui/fui_common.pas',
196 fui_gfx_gl in '../flexui/fui_gfx_gl.pas',
197 fui_events in '../flexui/fui_events.pas',
198 fui_style in '../flexui/fui_style.pas',
199 fui_flexlay in '../flexui/fui_flexlay.pas',
200 fui_ctls in '../flexui/fui_ctls.pas',
201 {$ENDIF}
202 {$I ../shared/vampimg.inc}
204 SysUtils, Classes;
206 {$IFDEF WINDOWS}
207 {$R *.res}
208 {$ENDIF}
210 var
211 noct: Boolean = False;
212 binPath: AnsiString = '';
213 forceBinDir: Boolean = False;
215 wLoadingQuit: Boolean = false;
216 Time, Time_Delta, Time_Old: Int64;
217 Frame: Int64;
218 flag: Boolean = false;
220 procedure Update ();
221 begin
222 // remember old mobj positions, prepare for update
223 g_Game_PreUpdate();
224 // server: receive client commands for new frame
225 // client: receive game state changes from server
226 if (NetMode = NET_SERVER) then g_Net_Host_Update()
227 else if (NetMode = NET_CLIENT) then g_Net_Client_Update();
228 // think
229 g_Game_Update();
230 // server: send any accumulated outgoing data to clients
231 if NetMode = NET_SERVER then g_Net_Flush();
232 end;
234 procedure Init();
235 var
236 NoSound: Boolean;
237 begin
238 Randomize;
240 {$IFDEF HEADLESS}
241 {$IFDEF USE_SDLMIXER}
242 NoSound := False; // hope env has set SDL_AUDIODRIVER to dummy
243 {$ELSE}
244 NoSound := True; // FMOD backend will sort it out
245 {$ENDIF}
246 {$ELSE}
247 NoSound := False;
248 {$ENDIF}
250 g_Touch_Init;
252 (*
253 if (e_JoysticksAvailable > 0) then
254 e_WriteLog('Input: Joysticks available.', TMsgType.Notify)
255 else
256 e_WriteLog('Input: No Joysticks.', TMsgType.Notify);
257 *)
259 if (not gNoSound) then
260 begin
261 e_WriteLog('Initializing sound system', TMsgType.Notify);
262 e_InitSoundSystem(NoSound);
263 end;
265 e_WriteLog('Init game', TMsgType.Notify);
266 g_Game_Init();
268 // FillChar(charbuff, sizeof(charbuff), ' ');
269 end;
271 procedure Release();
272 begin
273 e_WriteLog('Releasing engine', TMsgType.Notify);
274 e_ReleaseEngine();
276 e_WriteLog('Releasing input', TMsgType.Notify);
277 e_ReleaseInput();
279 if not gNoSound then
280 begin
281 e_WriteLog('Releasing sound', TMsgType.Notify);
282 e_ReleaseSoundSystem();
283 end;
284 end;
286 function ProcessMessage (): Boolean;
287 var
288 i, t: Integer;
289 begin
290 result := sys_HandleInput();
292 Time := sys_GetTicks();
293 Time_Delta := Time-Time_Old;
295 flag := false;
297 if wNeedTimeReset then
298 begin
299 Frame := 0;
300 Time_Delta := 28;
301 wNeedTimeReset := false;
302 end;
304 g_Map_ProfilersBegin();
305 g_Mons_ProfilersBegin();
307 t := Time_Delta div 28;
308 if (t > 0) then
309 begin
310 flag := true;
311 for i := 1 to t do
312 Update();
313 end;
315 g_Map_ProfilersEnd();
316 g_Mons_ProfilersEnd();
318 if wLoadingQuit then
319 begin
320 g_Game_Free();
321 g_Game_Quit();
322 end;
324 if (gExit = EXIT_QUIT) then
325 begin
326 result := true;
327 exit;
328 end;
330 // Время предыдущего обновления
331 if flag then
332 Time_Old := Time - (Time_Delta mod 28);
334 // don't wait if VSync is on, GL already probably waits enough
335 if gLerpActors then
336 flag := (Time - Frame >= gFrameTime) or gVSync;
338 if flag then
339 begin
340 if gPause or (not gLerpActors) or (gState = STATE_FOLD) then
341 gLerpFactor := 1.0
342 else
343 gLerpFactor := nmin(1.0, (Time - Time_Old) / 28.0);
344 r_Game_Draw;
345 sys_Repaint;
346 Frame := Time
347 end
348 else
349 sys_Delay(1);
351 e_SoundUpdate();
352 end;
355 function SDLMain (): Integer;
356 var
357 idx: Integer;
358 arg: AnsiString;
359 mdfo: TStream;
360 {$IFDEF ENABLE_HOLMES}
361 itmp: Integer;
362 valres: Word;
363 {$ENDIF}
364 begin
366 idx := 1;
367 while (idx <= ParamCount) do
368 begin
369 arg := ParamStr(idx);
370 Inc(idx);
371 //if arg = '--twinkletwinkle' then gwin_k8_enable_light_experiments := true;
372 if arg = '--jah' then g_profile_history_size := 100;
373 if arg = '--no-particles' then gpart_dbg_enabled := false;
374 if arg = '--no-los' then gmon_dbg_los_enabled := false;
376 if arg = '--profile-render' then g_profile_frame_draw := true;
377 if arg = '--profile-coldet' then g_profile_collision := true;
378 if arg = '--profile-los' then g_profile_los := true;
380 if arg = '--no-part-phys' then gpart_dbg_phys_enabled := false;
381 if arg = '--no-part-physics' then gpart_dbg_phys_enabled := false;
382 if arg = '--no-particles-phys' then gpart_dbg_phys_enabled := false;
383 if arg = '--no-particles-physics' then gpart_dbg_phys_enabled := false;
384 if arg = '--no-particle-phys' then gpart_dbg_phys_enabled := false;
385 if arg = '--no-particle-physics' then gpart_dbg_phys_enabled := false;
387 if arg = '--debug-input' then g_dbg_input := True;
389 {.$IF DEFINED(D2F_DEBUG)}
390 if arg = '--aimline' then g_dbg_aimline_on := true;
391 {.$ENDIF}
393 {$IFDEF ENABLE_HOLMES}
394 if arg = '--holmes' then begin g_holmes_enabled := true; g_Game_SetDebugMode(); end;
396 if (arg = '--holmes-ui-scale') or (arg = '-holmes-ui-scale') then
397 begin
398 if (idx <= ParamCount) then
399 begin
400 if not conParseFloat(fuiRenderScale, ParamStr(idx)) then fuiRenderScale := 1.0;
401 Inc(idx);
402 end;
403 end;
405 if (arg = '--holmes-font') or (arg = '-holmes-font') then
406 begin
407 if (idx <= ParamCount) then
408 begin
409 itmp := 0;
410 val(ParamStr(idx), itmp, valres);
411 {$IFNDEF HEADLESS}
412 if (valres = 0) and (not g_holmes_imfunctional) then
413 begin
414 case itmp of
415 8: uiContext.font := 'win8';
416 14: uiContext.font := 'win14';
417 16: uiContext.font := 'win16';
418 end;
419 end;
420 {$ELSE}
421 // fuck off, fpc!
422 itmp := itmp;
423 valres := valres;
424 {$ENDIF}
425 Inc(idx);
426 end;
427 end;
428 {$ENDIF}
430 if (arg = '--game-scale') or (arg = '-game-scale') then
431 begin
432 if (idx <= ParamCount) then
433 begin
434 if not conParseFloat(g_dbg_scale, ParamStr(idx)) then g_dbg_scale := 1.0;
435 Inc(idx);
436 end;
437 end;
439 if (arg = '--write-mapdef') or (arg = '-write-mapdef') then
440 begin
441 mdfo := createDiskFile('mapdef.txt');
442 mdfo.WriteBuffer(defaultMapDef[1], Length(defaultMapDef));
443 mdfo.Free();
444 Halt(0);
445 end;
447 if (arg = '--pixel-scale') or (arg = '-pixel-scale') then
448 begin
449 if (idx <= ParamCount) then
450 begin
451 if not conParseFloat(r_pixel_scale, ParamStr(idx)) then r_pixel_scale := 1.0;
452 Inc(idx);
453 end;
454 end;
455 end;
457 r_Window_Initialize;
459 Init;
460 Time_Old := sys_GetTicks();
462 g_Net_InitLowLevel();
464 // game commad line
465 if (ParamCount > 0) then g_Game_Process_Params();
467 {$IFNDEF HEADLESS}
468 if (not gGameOn) and gAskLanguage then g_Menu_AskLanguage();
469 {$ENDIF}
471 e_WriteLog('Entering the main loop', TMsgType.Notify);
473 // main loop
474 while not ProcessMessage() do begin end;
476 g_Net_Slist_ShutdownAll();
478 Release();
480 g_Net_DeinitLowLevel();
481 result := 0;
482 end;
484 function GetBinaryPath (): AnsiString;
485 {$IFDEF LINUX}
486 var sl: AnsiString;
487 {$ENDIF}
488 begin
489 result := ExtractFilePath(ParamStr(0));
490 {$IFDEF LINUX}
491 // it may be a symlink; do some guesswork here
492 sl := fpReadLink(ExtractFileName(ParamStr(0)));
493 if (sl = ParamStr(0)) then
494 begin
495 // use current directory, as we don't have anything better
496 //result := '.';
497 GetDir(0, result);
498 end;
499 {$ENDIF}
500 result := fixSlashes(result);
501 if (length(result) > 0) and (result[length(result)] <> '/') then
502 result := result + '/';
503 end;
505 procedure PrintDirs (msg: AnsiString; dirs: SSArray);
506 var dir: AnsiString;
507 begin
508 e_LogWriteln(msg + ':');
509 for dir in dirs do
510 e_LogWriteln(' ' + dir);
511 end;
513 {$IFDEF DARWIN}
514 function NSStringToAnsiString (s: NSString): AnsiString;
515 var i: Integer;
516 begin
517 result := '';
518 for i := 0 to s.length - 1 do
519 result := result + AnsiChar(s.characterAtIndex(i));
520 end;
522 function GetBundlePath (): AnsiString;
523 var pathRef: CFURLRef; pathCFStr: CFStringRef; pathStr: ShortString;
524 begin
525 pathRef := CFBundleCopyBundleURL(CFBundleGetMainBundle());
526 pathCFStr := CFURLCopyFileSystemPath(pathRef, kCFURLPOSIXPathStyle);
527 CFStringGetPascalString(pathCFStr, @pathStr, 255, CFStringGetSystemEncoding());
528 CFRelease(pathRef);
529 CFRelease(pathCFStr);
530 Result := pathStr;
531 end;
532 {$ENDIF}
534 procedure InitPath;
535 var i: Integer; rwdir, rodir: AnsiString; rwdirs, rodirs: SSArray;
537 procedure AddDir (var dirs: SSArray; append: AnsiString);
538 begin
539 SetLength(dirs, Length(dirs) + 1);
540 dirs[High(dirs)] := ExpandFileName(append)
541 end;
543 function IsSep (ch: Char): Boolean;
544 begin
545 {$IFDEF WINDOWS}
546 result := (ch = '/') or (ch = '\');
547 {$ELSE}
548 result := (ch = '/');
549 {$ENDIF}
550 end;
552 function OptimizePath (dir: AnsiString): AnsiString;
553 var i, len: Integer; s: AnsiString;
554 begin
555 i := 1; len := Length(dir); s := '';
556 while i <= len do
557 begin
558 if IsSep(dir[i]) then
559 begin
560 s := s + DirectorySeparator;
561 Inc(i);
562 while (i <= len) and IsSep(dir[i]) do Inc(i);
563 if (i <= len) and (dir[i] = '.') then
564 begin
565 if (i = len) or IsSep(dir[i + 1]) then
566 begin
567 Inc(i)
568 end
569 else if (i + 1 <= len) and (dir[i + 1] = '.') then
570 begin
571 if (i + 1 = len) or IsSep(dir[i + 2]) then
572 begin
573 s := e_UpperDir(s);
574 Inc(i, 2)
575 end
576 end
577 end
578 end
579 else
580 begin
581 s := s + dir[i];
582 Inc(i)
583 end
584 end;
585 result := s
586 end;
588 procedure OptimizeDirs (var dirs: SSArray);
589 var i, j, k: Integer;
590 begin
591 for i := 0 to High(dirs) do
592 dirs[i] := OptimizePath(dirs[i]);
593 // deduplicate
594 i := High(dirs);
595 while i >= 0 do
596 begin
597 j := 0;
598 while j < i do
599 begin
600 if dirs[j] = dirs[i] then
601 begin
602 for k := j + 1 to High(dirs) do
603 dirs[k - 1] := dirs[k];
604 Dec(i);
605 SetLength(dirs, High(dirs))
606 end
607 else
608 begin
609 Inc(j)
610 end
611 end;
612 Dec(i)
613 end
614 end;
616 procedure AddDef (var dirs: SSArray; base: SSArray; append: AnsiString);
617 var s: AnsiString;
618 begin
619 if Length(dirs) = 0 then
620 for s in base do
621 AddDir(dirs, e_CatPath(s, append));
622 OptimizeDirs(dirs)
623 end;
625 function GetDefaultRODirs (): SSArray;
626 {$IF DEFINED(UNIX) AND NOT DEFINED(DARWIN) AND NOT DEFINED(ANDROID)}
627 var home: AnsiString;
628 {$ENDIF}
629 {$IFDEF WINDOWS}
630 var appdata: AnsiString;
631 {$ENDIF}
632 {$IFDEF DARWIN}
633 var bundle, s: AnsiString; dirArr: NSArray; i: Integer;
634 {$ENDIF}
635 begin
636 result := nil;
637 {$IFDEF DARWIN}
638 bundle := GetBundlePath();
639 if ExtractFileExt(bundle) <> '.app' then
640 AddDir(result, binpath);
641 {$ELSE}
642 AddDir(result, binPath);
643 {$ENDIF}
644 if forceBinDir = false then
645 begin
646 {$IFDEF USE_SDL2}
647 AddDir(result, SDL_GetBasePath());
648 AddDir(result, SDL_GetPrefPath('', 'doom2df'));
649 {$ENDIF}
650 {$IFDEF WINDOWS}
651 appdata := GetEnvironmentVariable('APPDATA') + '\doom2df';
652 if appdata <> '' then
653 AddDir(result, appdata);
654 {$ENDIF}
655 {$IF DEFINED(UNIX) AND NOT DEFINED(DARWIN) AND NOT DEFINED(ANDROID)}
656 AddDir(result, '/usr/share/doom2df');
657 AddDir(result, '/usr/local/share/doom2df');
658 home := GetEnvironmentVariable('HOME');
659 if home <> '' then
660 AddDir(result, e_CatPath(home, '.doom2df'));
661 {$ENDIF}
662 {$IFDEF DARWIN}
663 bundle := GetBundlePath();
664 if bundle <> '' then
665 AddDir(result, e_CatPath(bundle, 'Contents/Resources'));
666 dirArr := NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, true);
667 for i := 0 to dirArr.count - 1 do
668 begin
669 s := NSStringToAnsiString(dirArr.objectAtIndex(i));
670 AddDir(result, e_CatPath(s, 'Doom 2D Forever'))
671 end;
672 {$ENDIF}
673 {$IF DEFINED(ANDROID) AND DEFINED(USE_SDL2)}
674 AddDir(result, SDL_AndroidGetInternalStoragePath());
675 if SDL_AndroidGetExternalStorageState() <> 0 then
676 AddDir(result, SDL_AndroidGetExternalStoragePath());
677 {$ENDIF}
678 end
679 end;
681 function GetDefaultRWDirs (): SSArray;
682 {$IF DEFINED(UNIX) AND NOT DEFINED(DARWIN) AND NOT DEFINED(ANDROID)}
683 var home: AnsiString;
684 {$ENDIF}
685 {$IFDEF WINDOWS}
686 var appdata: AnsiString;
687 {$ENDIF}
688 {$IFDEF DARWIN}
689 var bundle, s: AnsiString; dirArr: NSArray; i: Integer;
690 {$ENDIF}
691 begin
692 result := nil;
693 {$IFDEF DARWIN}
694 bundle := GetBundlePath();
695 if ExtractFileExt(bundle) <> '.app' then
696 AddDir(result, binPath);
697 {$ELSE}
698 AddDir(result, binPath);
699 {$ENDIF}
700 if forceBinDir = false then
701 begin
702 {$IFDEF USE_SDL2}
703 AddDir(result, SDL_GetPrefPath('', 'doom2df'));
704 {$ENDIF}
705 {$IFDEF WINDOWS}
706 appdata := GetEnvironmentVariable('APPDATA') + '\doom2df';
707 if appdata <> '' then
708 AddDir(result, appdata);
709 {$ENDIF}
710 {$IF DEFINED(UNIX) AND NOT DEFINED(DARWIN) AND NOT DEFINED(ANDROID)}
711 home := GetEnvironmentVariable('HOME');
712 if home <> '' then
713 AddDir(result, e_CatPath(home, '.doom2df'));
714 {$ENDIF}
715 {$IFDEF DARWIN}
716 dirArr := NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, true);
717 for i := 0 to dirArr.count - 1 do
718 begin
719 s := NSStringToAnsiString(dirArr.objectAtIndex(i));
720 AddDir(result, e_CatPath(s, 'Doom 2D Forever'))
721 end;
722 {$ENDIF}
723 {$IF DEFINED(ANDROID) AND DEFINED(USE_SDL2)}
724 if SDL_AndroidGetExternalStorageState() <> 0 then
725 AddDir(result, SDL_AndroidGetExternalStoragePath());
726 {$ENDIF}
727 end
728 end;
730 begin
731 forceBinDir := false;
732 binPath := GetBinaryPath();
734 i := 1;
735 while i < ParamCount do
736 begin
737 case ParamStr(i) of
738 '--like-windoze': forceBinDir := true;
739 '--rw-dir':
740 begin
741 Inc(i);
742 rwdir := ParamStr(i);
743 (* RW *)
744 AddDir(LogDirs, e_CatPath(rwdir, ''));
745 AddDir(SaveDirs, e_CatPath(rwdir, 'data'));
746 AddDir(CacheDirs, e_CatPath(rwdir, 'data/cache'));
747 AddDir(ConfigDirs, e_CatPath(rwdir, ''));
748 AddDir(MapDownloadDirs, e_CatPath(rwdir, 'maps/downloads'));
749 AddDir(WadDownloadDirs, e_CatPath(rwdir, 'wads/downloads'));
750 AddDir(ScreenshotDirs, e_CatPath(rwdir, 'screenshots'));
751 AddDir(StatsDirs, e_CatPath(rwdir, 'stats'));
752 (* RO *)
753 AddDir(DataDirs, e_CatPath(rwdir, 'data'));
754 AddDir(ModelDirs, e_CatPath(rwdir, 'data/models'));
755 AddDir(MegawadDirs, e_CatPath(rwdir, 'maps/megawads'));
756 AddDir(MapDirs, e_CatPath(rwdir, 'maps'));
757 AddDir(WadDirs, e_CatPath(rwdir, 'wads'));
758 end;
759 '--ro-dir':
760 begin
761 Inc(i);
762 rodir := ParamStr(i);
763 (* RO *)
764 AddDir(DataDirs, e_CatPath(rodir, 'data'));
765 AddDir(ModelDirs, e_CatPath(rodir, 'data/models'));
766 AddDir(MegawadDirs, e_CatPath(rodir, 'maps/megawads'));
767 AddDir(MapDirs, e_CatPath(rodir, 'maps'));
768 AddDir(WadDirs, e_CatPath(rodir, 'wads'));
769 end;
770 '--game-wad':
771 begin
772 Inc(i);
773 GameWADName := ParamStr(i);
774 end;
775 '--config':
776 begin
777 Inc(i);
778 gConfigScript := ParamStr(i);
779 end;
780 end;
781 Inc(i)
782 end;
784 // prefer bin dir if it writable and contains game.wad
785 if forceBinDir = false then
786 begin
787 if findDiskWad(binPath + 'data' + '/' + GameWADName) <> '' then
788 if e_CanCreateFilesAt(binPath) then
789 forceBinDir := true
790 end;
792 (* RO *)
793 rodirs := GetDefaultRODirs();
794 AddDef(DataDirs, rodirs, 'data');
795 AddDef(ModelDirs, rodirs, 'data/models');
796 AddDef(MegawadDirs, rodirs, 'maps/megawads');
797 AddDef(MapDirs, rodirs, 'maps');
798 AddDef(WadDirs, rodirs, 'wads');
800 (* RW *)
801 rwdirs := GetDefaultRWDirs();
802 AddDef(LogDirs, rwdirs, '');
803 AddDef(SaveDirs, rwdirs, 'data');
804 AddDef(CacheDirs, rwdirs, 'data/cache');
805 AddDef(ConfigDirs, rwdirs, '');
806 AddDef(MapDownloadDirs, rwdirs, 'maps/downloads');
807 AddDef(WadDownloadDirs, rwdirs, 'wads/downloads');
808 AddDef(ScreenshotDirs, rwdirs, 'screenshots');
809 AddDef(StatsDirs, rwdirs, 'stats');
811 for i := 0 to High(MapDirs) do
812 AddDir(AllMapDirs, MapDirs[i]);
813 for i := 0 to High(MegawadDirs) do
814 AddDir(AllMapDirs, MegawadDirs[i]);
815 OptimizeDirs(AllMapDirs);
817 if LogFileName = '' then
818 begin
819 rwdir := e_GetWriteableDir(LogDirs, false);
820 if rwdir <> '' then
821 begin
822 {$IFDEF HEADLESS}
823 LogFileName := e_CatPath(rwdir, 'Doom2DF_H.log');
824 {$ELSE}
825 LogFileName := e_CatPath(rwdir, 'Doom2DF.log');
826 {$ENDIF}
827 end
828 end;
830 // HACK: ensure the screenshots folder also has a stats subfolder in it
831 rwdir := e_GetWriteableDir(ScreenshotDirs, false);
832 if rwdir <> '' then CreateDir(rwdir + '/stats');
833 end;
835 procedure InitPrep;
836 {$IF DEFINED(ANDROID) AND DEFINED(USE_SDLMIXER)}
837 var timiditycfg: AnsiString;
838 {$ENDIF}
839 var i: Integer;
840 begin
841 {$IFDEF HEADLESS}
842 conbufDumpToStdOut := true;
843 {$ENDIF}
844 for i := 1 to ParamCount do
845 begin
846 case ParamStr(i) of
847 '--con-stdout': conbufDumpToStdOut := true;
848 '--no-fbo': glRenderToFBO := false;
849 end
850 end;
852 if LogFileName <> '' then
853 e_InitLog(LogFileName, TWriteMode.WM_NEWFILE);
854 e_InitWritelnDriver();
855 e_WriteLog('Doom 2D: Forever version ' + GAME_VERSION + ' proto ' + IntToStr(NET_PROTOCOL_VER), TMsgType.Notify);
856 e_WriteLog('Build date: ' + GAME_BUILDDATE + ' ' + GAME_BUILDTIME, TMsgType.Notify);
857 e_WriteLog('Build hash: ' + g_GetBuildHash(), TMsgType.Notify);
858 e_WriteLog('Build by: ' + g_GetBuilderName(), TMsgType.Notify);
860 e_LogWritefln('Force bin dir: %s', [forceBinDir], TMsgType.Notify);
861 e_LogWritefln('BINARY PATH: [%s]', [binPath], TMsgType.Notify);
863 PrintDirs('DataDirs', DataDirs);
864 PrintDirs('ModelDirs', ModelDirs);
865 PrintDirs('MegawadDirs', MegawadDirs);
866 PrintDirs('MapDirs', MapDirs);
867 PrintDirs('WadDirs', WadDirs);
869 PrintDirs('LogDirs', LogDirs);
870 PrintDirs('SaveDirs', SaveDirs);
871 PrintDirs('CacheDirs', CacheDirs);
872 PrintDirs('ConfigDirs', ConfigDirs);
873 PrintDirs('ScreenshotDirs', ScreenshotDirs);
874 PrintDirs('StatsDirs', StatsDirs);
875 PrintDirs('MapDownloadDirs', MapDownloadDirs);
876 PrintDirs('WadDownloadDirs', WadDownloadDirs);
878 GameWAD := e_FindWad(DataDirs, GameWADName);
879 if GameWad = '' then
880 begin
881 e_WriteLog('WAD ' + GameWADName + ' not found in data directories.', TMsgType.Fatal);
882 {$IF DEFINED(USE_SDL2) AND NOT DEFINED(HEADLESS)}
883 if forceBinDir = false then
884 SDL_ShowSimpleMessageBox(
885 SDL_MESSAGEBOX_ERROR,
886 'Doom 2D Forever',
887 PChar('WAD ' + GameWADName + ' not found in data directories.'),
888 nil
889 );
890 {$ENDIF}
891 e_DeinitLog;
892 Halt(1);
893 end;
895 {$IF DEFINED(ANDROID) AND DEFINED(USE_SDLMIXER)}
896 timiditycfg := 'timidity.cfg';
897 if e_FindResource(ConfigDirs, timiditycfg) = true then
898 begin
899 timiditycfg := ExpandFileName(timiditycfg);
900 SetEnvVar('TIMIDITY_CFG', timiditycfg);
901 e_LogWritefln('Set TIMIDITY_CFG = "%s"', [timiditycfg]);
902 end;
903 {$ENDIF}
904 end;
906 procedure Main;
907 {$IFDEF ENABLE_HOLMES}
908 var flexloaded: Boolean;
909 {$ENDIF}
910 begin
911 InitPath;
912 InitPrep;
913 e_InitInput;
914 sys_Init;
916 sys_CharPress := @CharPress;
918 g_Options_SetDefault;
919 g_Options_SetDefaultVideo;
920 g_Console_SysInit;
921 if sys_SetDisplayMode(gRC_Width, gRC_Height, gBPP, gRC_FullScreen, gRC_Maximized) = False then
922 raise Exception.Create('Failed to set videomode on startup.');
924 e_WriteLog(gLanguage, TMsgType.Notify);
925 g_Language_Set(gLanguage);
927 {$IF not DEFINED(HEADLESS) and DEFINED(ENABLE_HOLMES)}
928 flexloaded := true;
929 if not fuiAddWad('flexui.wad') then
930 begin
931 if not fuiAddWad('./data/flexui.wad') then fuiAddWad('./flexui.wad');
932 end;
933 try
934 fuiGfxLoadFont('win8', 'flexui/fonts/win8.fuifont');
935 fuiGfxLoadFont('win14', 'flexui/fonts/win14.fuifont');
936 fuiGfxLoadFont('win16', 'flexui/fonts/win16.fuifont');
937 fuiGfxLoadFont('dos8', 'flexui/fonts/dos8.fuifont');
938 fuiGfxLoadFont('msx6', 'flexui/fonts/msx6.fuifont');
939 except on e: Exception do
940 begin
941 writeln('ERROR loading FlexUI fonts');
942 flexloaded := false;
943 //raise;
944 end;
945 else
946 begin
947 flexloaded := false;
948 //raise;
949 end;
950 end;
951 if (flexloaded) then
952 begin
953 try
954 e_LogWriteln('FlexUI: loading stylesheet...');
955 uiLoadStyles('flexui/widgets.wgs');
956 except on e: TParserException do
957 begin
958 writeln('ERROR at (', e.tokLine, ',', e.tokCol, '): ', e.message);
959 //raise;
960 flexloaded := false;
961 end;
962 else
963 begin
964 //raise;
965 flexloaded := false;
966 end;
967 end;
968 end;
969 g_holmes_imfunctional := not flexloaded;
971 if (not g_holmes_imfunctional) then
972 begin
973 uiInitialize();
974 uiContext.font := 'win14';
975 end;
977 if assigned(oglInitCB) then oglInitCB;
978 {$ENDIF}
980 //g_Res_CreateDatabases(true); // it will be done before connecting to the server for the first time
982 e_WriteLog('Entering SDLMain', TMsgType.Notify);
984 {$WARNINGS OFF}
985 SDLMain();
986 {$WARNINGS ON}
988 {$IFDEF ENABLE_HOLMES}
989 if assigned(oglDeinitCB) then oglDeinitCB;
990 {$ENDIF}
992 g_Console_WriteGameConfig;
993 sys_Final;
994 end;
997 procedure EntryParams;
998 var f: Integer;
999 begin
1000 f := 1;
1001 while f <= ParamCount do
1002 begin
1003 case ParamStr(f) of
1004 '--gdb': noct := true;
1005 '--log': conbufDumpToStdOut := true;
1006 '--safe-log': e_SetSafeSlowLog(true);
1007 '--log-file':
1008 if f + 1 <= ParamCount then
1009 begin
1010 Inc(f);
1011 LogFileName := ParamStr(f)
1012 end
1013 end;
1014 Inc(f)
1015 end
1016 end;
1018 procedure EntryPoint;
1019 begin
1020 SetExceptionMask([exInvalidOp, exDenormalized, exZeroDivide, exOverflow, exUnderflow, exPrecision]); //k8: fuck off, that's why
1021 EntryParams;
1022 if noct then
1023 Main
1024 else
1025 try
1026 Main;
1027 e_WriteLog('Shutdown with no errors.', TMsgType.Notify)
1028 except on e: Exception do
1029 e_WriteStackTrace(e.message)
1030 else
1031 e_WriteStackTrace('FATAL ERROR')
1032 end;
1034 e_DeinitLog;
1035 end;
1037 {$IFDEF ANDROID}
1038 function SDL_main (argc: CInt; argv: PPChar): CInt; cdecl;
1039 begin
1040 // TODO pass argc+argv to rtl
1041 EntryPoint;
1042 result := 0
1043 end;
1045 exports SDL_main;
1046 {$ELSE}
1047 begin
1048 EntryPoint
1049 {$ENDIF}
1051 end.