-
Notifications
You must be signed in to change notification settings - Fork 162
/
Copy pathengine.cpp
1416 lines (1240 loc) · 46.1 KB
/
engine.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//=============================================================================
//
// Adventure Game Studio (AGS)
//
// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
// The full list of copyright holders can be found in the Copyright.txt
// file, which is part of this source code distribution.
//
// The AGS source code is provided under the Artistic License 2.0.
// A copy of this license can be found in the file License.txt and at
// http://www.opensource.org/licenses/artistic-license-2.0.php
//
//=============================================================================
//
// Engine initialization
//
#include "core/platform.h"
#include <errno.h>
#include <stdio.h>
#if AGS_PLATFORM_OS_WINDOWS
#include <process.h> // _spawnl
#endif
#include <allegro.h> // allegro_install and _exit
#include "ac/asset_helper.h"
#include "ac/common.h"
#include "ac/character.h"
#include "ac/characterextras.h"
#include "ac/characterinfo.h"
#include "ac/draw.h"
#include "ac/game.h"
#include "ac/gamesetup.h"
#include "ac/gamesetupstruct.h"
#include "ac/gamestate.h"
#include "ac/global_character.h"
#include "ac/global_game.h"
#include "ac/gui.h"
#include "ac/lipsync.h"
#include "ac/path_helper.h"
#include "ac/route_finder.h"
#include "ac/sys_events.h"
#include "ac/roomstatus.h"
#include "ac/speech.h"
#include "ac/spritecache.h"
#include "ac/translation.h"
#include "ac/viewframe.h"
#include "ac/dynobj/scriptobject.h"
#include "ac/dynobj/scriptsystem.h"
#include "core/assetmanager.h"
#include "debug/debug_log.h"
#include "debug/debugger.h"
#include "debug/out.h"
#include "device/mousew32.h"
#include "font/agsfontrenderer.h"
#include "font/fonts.h"
#include "gfx/graphicsdriver.h"
#include "gfx/gfxdriverfactory.h"
#include "gfx/ddb.h"
#include "media/audio/sound.h"
#include "main/config.h"
#include "main/game_file.h"
#include "main/game_start.h"
#include "main/engine.h"
#include "main/engine_setup.h"
#include "main/graphics_mode.h"
#include "main/main.h"
#include "media/audio/audio_core.h"
#include "platform/base/sys_main.h"
#include "platform/base/agsplatformdriver.h"
#include "util/directory.h"
#include "util/error.h"
#include "util/path.h"
#include "util/string_utils.h"
using namespace AGS::Common;
using namespace AGS::Engine;
extern char check_dynamic_sprites_at_exit;
extern int our_eip;
extern volatile char want_exit, abort_engine;
extern bool justRunSetup;
extern GameSetupStruct game;
extern int proper_exit;
extern char pexbuf[STD_BUFFER_SIZE];
extern SpriteCache spriteset;
extern ScriptObject scrObj[MAX_ROOM_OBJECTS];
extern std::vector<ViewStruct> views;
extern int displayed_room;
extern int eip_guinum;
extern int eip_guiobj;
extern SpeechLipSyncLine *splipsync;
extern int numLipLines, curLipLine, curLipLinePhoneme;
extern ScriptSystem scsystem;
extern IGraphicsDriver *gfxDriver;
extern RGB palette[256];
extern CharacterInfo*playerchar;
ResourcePaths ResPaths;
t_engine_pre_init_callback engine_pre_init_callback = nullptr;
bool engine_init_backend()
{
our_eip = -199;
platform->PreBackendInit();
// Initialize SDL
Debug::Printf(kDbgMsg_Info, "Initializing backend libs");
if (sys_main_init())
{
const char *err = SDL_GetError();
const char *user_hint = platform->GetBackendFailUserHint();
platform->DisplayAlert("Unable to initialize SDL library.\n%s\n\n%s",
(err && err[0]) ? err : "SDL provided no further information on the problem.",
user_hint);
return false;
}
// Initialize stripped allegro library
if (install_allegro(SYSTEM_NONE, &errno, atexit))
{
platform->DisplayAlert("Internal error: unable to initialize stripped Allegro 4 library.");
return false;
}
platform->PostBackendInit();
return true;
}
void winclosehook()
{
want_exit = 1;
abort_engine = 1;
check_dynamic_sprites_at_exit = 0;
AbortGame();
}
void engine_setup_window()
{
Debug::Printf(kDbgMsg_Info, "Setting up window");
our_eip = -198;
sys_window_set_title(game.gamename);
sys_window_set_icon();
sys_evt_set_quit_callback(winclosehook);
our_eip = -197;
}
// Fills map with game settings, to e.g. let setup application(s)
// display correct properties to the user
static void fill_game_properties(StringOrderMap &map)
{
map["title"] = game.gamename;
map["guid"] = game.guid;
map["legacy_uniqueid"] = StrUtil::IntToString(game.uniqueid);
map["legacy_resolution"] = StrUtil::IntToString(game.GetResolutionType());
map["legacy_letterbox"] = StrUtil::IntToString(game.options[OPT_LETTERBOX]);;
map["resolution_width"] = StrUtil::IntToString(game.GetDefaultRes().Width);
map["resolution_height"] = StrUtil::IntToString(game.GetDefaultRes().Height);
map["resolution_bpp"] = StrUtil::IntToString(game.GetColorDepth());
map["render_at_screenres"] = StrUtil::IntToString(
game.options[OPT_RENDERATSCREENRES] == kRenderAtScreenRes_UserDefined ? -1 :
(game.options[OPT_RENDERATSCREENRES] == kRenderAtScreenRes_Enabled ? 1 : 0));
}
// Starts up setup application, if capable.
// Returns TRUE if should continue running the game, otherwise FALSE.
bool engine_run_setup(const ConfigTree &cfg, int &app_res)
{
app_res = EXIT_NORMAL;
#if AGS_PLATFORM_OS_WINDOWS
{
Debug::Printf(kDbgMsg_Info, "Running Setup");
ConfigTree cfg_with_meta = cfg;
fill_game_properties(cfg_with_meta["gameproperties"]);
ConfigTree cfg_out;
SetupReturnValue res = platform->RunSetup(cfg_with_meta, cfg_out);
if (res != kSetup_Cancel)
{
String cfg_file = PreparePathForWriting(GetGameUserConfigDir(), DefaultConfigFileName);
if (cfg_file.IsEmpty())
{
platform->DisplayAlert("Unable to write into directory '%s'.\n%s",
GetGameUserConfigDir().FullDir.GetCStr(), platform->GetDiskWriteAccessTroubleshootingText());
}
else if (!IniUtil::Merge(cfg_file, cfg_out))
{
platform->DisplayAlert("Unable to write to the configuration file (error code 0x%08X).\n%s",
platform->GetLastSystemError(), platform->GetDiskWriteAccessTroubleshootingText());
}
}
if (res != kSetup_RunGame)
return false;
// TODO: investigate if the full program restart may (should) be avoided
// Just re-reading the config file seems to cause a caching
// problem on Win9x, so let's restart the process.
sys_main_shutdown();
allegro_exit();
String args = String::FromFormat("\"%s\"", appPath.GetCStr());
_spawnl(_P_OVERLAY, appPath.GetCStr(), args.GetCStr(), NULL);
}
#else
(void)cfg;
#endif
return true;
}
// Scans given directory for the AGS game config. If such config exists
// and it contains data file name, then returns one.
// Otherwise returns empty string.
static String find_game_data_in_config(const String &path)
{
// First look for config
ConfigTree cfg;
String def_cfg_file = Path::ConcatPaths(path, DefaultConfigFileName);
if (IniUtil::Read(def_cfg_file, cfg))
{
String data_file = CfgReadString(cfg, "misc", "datafile");
Debug::Printf("Found game config: %s", def_cfg_file.GetCStr());
Debug::Printf(" Cfg: data file: %s", data_file.GetCStr());
// Only accept if it's a relative path
if (!data_file.IsEmpty() && Path::IsRelativePath(data_file))
return Path::ConcatPaths(path, data_file);
}
return ""; // not found in config
}
// Scans for game data in several common locations.
// When it does so, it first looks for game config file, which contains
// explicit directions to game data in its settings.
// If such config is not found, it scans same location for *any* game data instead.
String search_for_game_data_file(String &was_searching_in)
{
Debug::Printf("Looking for the game data.\n Cwd: %s\n Path arg: %s",
Directory::GetCurrentDirectory().GetCStr(),
cmdGameDataPath.GetCStr());
// 1. From command line argument, which may be a directory or actual file
if (!cmdGameDataPath.IsEmpty())
{
if (File::IsFile(cmdGameDataPath))
return cmdGameDataPath; // this path is a file
if (!File::IsDirectory(cmdGameDataPath))
return ""; // path is neither file nor directory
was_searching_in = cmdGameDataPath;
Debug::Printf("Searching in (cmd arg): %s", was_searching_in.GetCStr());
// first scan for config
String data_path = find_game_data_in_config(cmdGameDataPath);
if (!data_path.IsEmpty())
return data_path;
// if not found in config, lookup for data in same dir
return FindGameData(cmdGameDataPath);
}
// 2. Look in other known locations
// 2.1. Look for attachment in the running executable
if (!appPath.IsEmpty() && Common::AssetManager::IsDataFile(appPath))
{
Debug::Printf("Found game data embedded in executable");
was_searching_in = Path::GetDirectoryPath(appPath);
return appPath;
}
// 2.2 Look in current working directory
String cur_dir = Directory::GetCurrentDirectory();
was_searching_in = cur_dir;
Debug::Printf("Searching in (cwd): %s", was_searching_in.GetCStr());
// first scan for config
String data_path = find_game_data_in_config(cur_dir);
if (!data_path.IsEmpty())
return data_path;
// if not found in config, lookup for data in same dir
data_path = FindGameData(cur_dir);
if (!data_path.IsEmpty())
return data_path;
// 2.3 Look in executable's directory (if it's different from current dir)
if (Path::ComparePaths(appDirectory, cur_dir) == 0)
return ""; // no luck
was_searching_in = appDirectory;
Debug::Printf("Searching in (exe dir): %s", was_searching_in.GetCStr());
// first scan for config
data_path = find_game_data_in_config(appDirectory);
if (!data_path.IsEmpty())
return data_path;
// if not found in config, lookup for data in same dir
return FindGameData(appDirectory);
}
void engine_init_fonts()
{
Debug::Printf(kDbgMsg_Info, "Initializing TTF renderer");
init_font_renderer();
}
void engine_init_mouse()
{
int res = minstalled();
if (res < 0)
Debug::Printf(kDbgMsg_Info, "Initializing mouse: failed");
else
Debug::Printf(kDbgMsg_Info, "Initializing mouse: number of buttons reported is %d", res);
Mouse::SetSpeed(usetup.mouse_speed);
}
void engine_locate_speech_pak()
{
init_voicepak("");
}
void engine_locate_audio_pak()
{
play.separate_music_lib = false;
String music_file = game.GetAudioVOXName();
String music_filepath = find_assetlib(music_file);
if (!music_filepath.IsEmpty())
{
if (AssetMgr->AddLibrary(music_filepath) == kAssetNoError)
{
Debug::Printf(kDbgMsg_Info, "%s found and initialized.", music_file.GetCStr());
play.separate_music_lib = true;
ResPaths.AudioPak.Name = music_file;
ResPaths.AudioPak.Path = music_filepath;
}
else
{
platform->DisplayAlert("Unable to initialize digital audio pack '%s', file could be corrupt or of unsupported format.",
music_file.GetCStr());
}
}
else if (!ResPaths.AudioDir2.IsEmpty() &&
Path::ComparePaths(ResPaths.DataDir, ResPaths.AudioDir2) != 0)
{
Debug::Printf(kDbgMsg_Info, "Audio pack was not found, but explicit audio directory is defined.");
}
}
// Assign asset locations to the AssetManager
void engine_assign_assetpaths()
{
AssetMgr->AddLibrary(ResPaths.GamePak.Path, ",audio"); // main pack may have audio bundled too
// The asset filters are currently a workaround for limiting search to certain locations;
// this is both an optimization and to prevent unexpected behavior.
// - empty filter is for regular files
// audio - audio clips
// voice - voice-over clips
// NOTE: we add extra optional directories first because they should have higher priority
// TODO: maybe change AssetManager library order to stack-like later (last added = top priority)?
if (!ResPaths.DataDir2.IsEmpty() && Path::ComparePaths(ResPaths.DataDir2, ResPaths.DataDir) != 0)
AssetMgr->AddLibrary(ResPaths.DataDir2, ",audio,voice"); // dir may have anything
if (!ResPaths.AudioDir2.IsEmpty() && Path::ComparePaths(ResPaths.AudioDir2, ResPaths.DataDir) != 0)
AssetMgr->AddLibrary(ResPaths.AudioDir2, "audio");
if (!ResPaths.VoiceDir2.IsEmpty() && Path::ComparePaths(ResPaths.VoiceDir2, ResPaths.DataDir) != 0)
AssetMgr->AddLibrary(ResPaths.VoiceDir2, "voice");
AssetMgr->AddLibrary(ResPaths.DataDir, ",audio,voice"); // dir may have anything
if (!ResPaths.AudioPak.Path.IsEmpty())
AssetMgr->AddLibrary(ResPaths.AudioPak.Path, "audio");
if (!ResPaths.SpeechPak.Path.IsEmpty())
AssetMgr->AddLibrary(ResPaths.SpeechPak.Path, "voice");
}
void engine_init_keyboard()
{
/* do nothing */
}
void engine_init_timer()
{
Debug::Printf(kDbgMsg_Info, "Install timer");
skipMissedTicks();
}
void engine_init_audio()
{
if (usetup.audio_enabled)
{
Debug::Printf("Initializing audio");
bool res = sys_audio_init(usetup.audio_driver);
if (res)
{
try {
audio_core_init(); // audio core system
}
catch (std::runtime_error ex) {
Debug::Printf(kDbgMsg_Error, "Failed to initialize audio system: %s", ex.what());
res = false;
}
}
usetup.audio_enabled = res;
}
if (usetup.audio_enabled)
{
soundcache_set_rules(usetup.SoundLoadAtOnceSize, usetup.SoundCacheSize);
}
else
{
// all audio is disabled
play.voice_avail = false;
play.separate_music_lib = false;
Debug::Printf(kDbgMsg_Info, "Audio is disabled");
}
}
void engine_init_debug()
{
if (usetup.show_fps)
display_fps = kFPS_Forced;
if ((debug_flags & (~DBG_DEBUGMODE)) >0) {
platform->DisplayAlert("Engine debugging enabled.\n"
"\nNOTE: You have selected to enable one or more engine debugging options.\n"
"These options cause many parts of the game to behave abnormally, and you\n"
"may not see the game as you are used to it. The point is to test whether\n"
"the engine passes a point where it is crashing on you normally.\n"
"[Debug flags enabled: 0x%02X]",debug_flags);
}
}
void atexit_handler() {
if (proper_exit==0) {
platform->DisplayAlert("Error: the program has exited without requesting it.\n"
"Program pointer: %+03d (write this number down), ACI version %s\n"
"If you see a list of numbers above, please write them down and contact\n"
"developers. Otherwise, note down any other information displayed.",
our_eip, EngineVersion.LongString.GetCStr());
}
}
void engine_init_exit_handler()
{
Debug::Printf(kDbgMsg_Info, "Install exit handler");
atexit(atexit_handler);
}
void engine_init_rand()
{
play.randseed = time(nullptr);
srand (play.randseed);
}
void engine_init_pathfinder()
{
init_pathfinder(loaded_game_file_version);
}
void engine_pre_init_gfx()
{
//Debug::Printf("Initialize gfx");
//platform->InitialiseAbufAtStartup();
}
int engine_load_game_data()
{
Debug::Printf("Load game data");
our_eip=-17;
HError err = load_game_file();
if (!err)
{
proper_exit=1;
display_game_file_error(err);
return EXIT_ERROR;
}
return 0;
}
// Replace special tokens inside a user path option
static void resolve_configured_path(String &option)
{
option.Replace("$GAMENAME$", game.gamename);
}
// Setup paths and directories that may be affected by user configuration
void engine_init_user_directories()
{
resolve_configured_path(usetup.user_data_dir);
resolve_configured_path(usetup.shared_data_dir);
if (!usetup.user_conf_dir.IsEmpty())
Debug::Printf(kDbgMsg_Info, "User config directory: %s", usetup.user_conf_dir.GetCStr());
if (!usetup.user_data_dir.IsEmpty())
Debug::Printf(kDbgMsg_Info, "User data directory: %s", usetup.user_data_dir.GetCStr());
if (!usetup.shared_data_dir.IsEmpty())
Debug::Printf(kDbgMsg_Info, "Shared data directory: %s", usetup.shared_data_dir.GetCStr());
// Initialize default save directory early, for we'll need it to set restart point
SetDefaultSaveDirectory();
}
// TODO: remake/remove this nonsense
int check_write_access() {
if (platform->GetDiskFreeSpaceMB() < 2)
return 0;
our_eip = -1895;
// The Save Game Dir is the only place that we should write to
String svg_dir = get_save_game_directory();
String tempPath = String::FromFormat("%s""tmptest.tmp", svg_dir.GetCStr());
Stream *temp_s = Common::File::CreateFile(tempPath);
if (!temp_s)
return 0;
our_eip = -1896;
temp_s->Write("just to test the drive free space", 30);
delete temp_s;
our_eip = -1897;
if (!File::DeleteFile(tempPath))
return 0;
return 1;
}
int engine_check_disk_space()
{
Debug::Printf(kDbgMsg_Info, "Checking for disk space");
if (check_write_access()==0) {
platform->DisplayAlert("Unable to write in the savegame directory.\n%s", platform->GetDiskWriteAccessTroubleshootingText());
proper_exit = 1;
return EXIT_ERROR;
}
return 0;
}
int engine_check_font_was_loaded()
{
if (!font_first_renderer_loaded())
{
platform->DisplayAlert("No game fonts found. At least one font is required to run the game.");
proper_exit = 1;
return EXIT_ERROR;
}
return 0;
}
// Do the preload graphic if available
void show_preload()
{
RGB temppal[256];
Bitmap *splashsc = BitmapHelper::CreateRawBitmapOwner( load_pcx("preload.pcx",temppal) );
if (splashsc != nullptr)
{
Debug::Printf("Displaying preload image");
if (splashsc->GetColorDepth() == 8)
set_palette_range(temppal, 0, 255, 0);
if (gfxDriver->UsesMemoryBackBuffer())
gfxDriver->GetMemoryBackBuffer()->Clear();
const Rect &view = play.GetMainViewport();
Bitmap *tsc = BitmapHelper::CreateBitmapCopy(splashsc, game.GetColorDepth());
if (!gfxDriver->HasAcceleratedTransform() && view.GetSize() != tsc->GetSize())
{
Bitmap *stretched = new Bitmap(view.GetWidth(), view.GetHeight(), tsc->GetColorDepth());
stretched->StretchBlt(tsc, RectWH(0, 0, view.GetWidth(), view.GetHeight()));
delete tsc;
tsc = stretched;
}
IDriverDependantBitmap *ddb = gfxDriver->CreateDDBFromBitmap(tsc, false, true);
ddb->SetStretch(view.GetWidth(), view.GetHeight());
gfxDriver->ClearDrawLists();
gfxDriver->DrawSprite(0, 0, ddb);
render_to_screen();
gfxDriver->DestroyDDB(ddb);
delete splashsc;
delete tsc;
platform->Delay(500);
}
}
int engine_init_sprites()
{
Debug::Printf(kDbgMsg_Info, "Initialize sprites");
HError err = spriteset.InitFile(SpriteFile::DefaultSpriteFileName, SpriteFile::DefaultSpriteIndexName);
if (!err)
{
sys_main_shutdown();
allegro_exit();
proper_exit=1;
platform->DisplayAlert("Could not load sprite set file %s\n%s",
SpriteFile::DefaultSpriteFileName.GetCStr(),
err->FullMessage().GetCStr());
return EXIT_ERROR;
}
if (usetup.SpriteCacheSize > 0)
spriteset.SetMaxCacheSize(usetup.SpriteCacheSize);
return 0;
}
void engine_init_game_settings()
{
our_eip=-7;
Debug::Printf("Initialize game settings");
// Setup a text encoding mode depending on the game data hint
if (game.options[OPT_GAMETEXTENCODING] == 65001) // utf-8 codepage number
set_uformat(U_UTF8);
else
set_uformat(U_ASCII);
int ee;
for (ee=0;ee<256;ee++) {
if (game.paluses[ee]!=PAL_BACKGROUND)
palette[ee]=game.defpal[ee];
}
for (ee = 0; ee < game.numcursors; ee++)
{
// The cursor graphics are assigned to mousecurs[] and so cannot
// be removed from memory
if (game.mcurs[ee].pic >= 0)
spriteset.Precache(game.mcurs[ee].pic);
// just in case they typed an invalid view number in the editor
if (game.mcurs[ee].view >= game.numviews)
game.mcurs[ee].view = -1;
if (game.mcurs[ee].view >= 0)
precache_view (game.mcurs[ee].view);
}
// may as well preload the character gfx
if (playerchar->view >= 0)
precache_view (playerchar->view);
/* dummygui.guiId = -1;
dummyguicontrol.guin = -1;
dummyguicontrol.objn = -1;*/
our_eip=-6;
// game.chars[0].talkview=4;
//init_language_text(game.langcodes[0]);
for (ee = 0; ee < MAX_ROOM_OBJECTS; ee++) {
scrObj[ee].id = ee;
// 64 bit: Using the id instead
// scrObj[ee].obj = NULL;
}
for (ee=0;ee<game.numcharacters;ee++) {
memset(&game.chars[ee].inv[0],0,MAX_INV*sizeof(short));
game.chars[ee].activeinv=-1;
game.chars[ee].following=-1;
game.chars[ee].followinfo=97 | (10 << 8);
if (loaded_game_file_version < kGameVersion_360)
game.chars[ee].idletime=20; // default to 20 seconds
game.chars[ee].idleleft=game.chars[ee].idletime;
game.chars[ee].transparency = 0;
game.chars[ee].baseline = -1;
game.chars[ee].walkwaitcounter = 0;
game.chars[ee].z = 0;
charextra[ee].xwas = INVALID_X;
charextra[ee].zoom = 100;
if (game.chars[ee].view >= 0) {
// set initial loop to 0
game.chars[ee].loop = 0;
// or to 1 if they don't have up/down frames
if (views[game.chars[ee].view].loops[0].numFrames < 1)
game.chars[ee].loop = 1;
}
charextra[ee].process_idle_this_time = 0;
charextra[ee].invorder_count = 0;
charextra[ee].slow_move_counter = 0;
charextra[ee].animwait = 0;
}
our_eip=-5;
for (ee=0;ee<game.numinvitems;ee++) {
if (game.invinfo[ee].flags & IFLG_STARTWITH) playerchar->inv[ee]=1;
else playerchar->inv[ee]=0;
}
play.score=0;
play.sierra_inv_color=7;
// copy the value set by the editor
if (game.options[OPT_GLOBALTALKANIMSPD] >= 0)
{
play.talkanim_speed = game.options[OPT_GLOBALTALKANIMSPD];
game.options[OPT_GLOBALTALKANIMSPD] = 1;
}
else
{
play.talkanim_speed = -game.options[OPT_GLOBALTALKANIMSPD] - 1;
game.options[OPT_GLOBALTALKANIMSPD] = 0;
}
play.inv_item_wid = 40;
play.inv_item_hit = 22;
play.messagetime=-1;
play.disabled_user_interface=0;
play.gscript_timer=-1;
play.debug_mode=game.options[OPT_DEBUGMODE];
play.inv_top=0;
play.inv_numdisp=0;
play.obsolete_inv_numorder=0;
play.text_speed=15;
play.text_min_display_time_ms = 1000;
play.ignore_user_input_after_text_timeout_ms = 500;
play.ClearIgnoreInput();
play.lipsync_speed = 15;
play.close_mouth_speech_time = 10;
play.disable_antialiasing = 0;
play.rtint_enabled = false;
play.rtint_level = 0;
play.rtint_light = 0;
play.text_speed_modifier = 0;
play.text_align = kHAlignLeft;
// Make the default alignment to the right with right-to-left text
if (game.options[OPT_RIGHTLEFTWRITE])
play.text_align = kHAlignRight;
play.speech_bubble_width = get_fixed_pixel_size(100);
play.bg_frame=0;
play.bg_frame_locked=0;
play.bg_anim_delay=0;
play.anim_background_speed = 0;
play.silent_midi = 0;
play.current_music_repeating = 0;
play.skip_until_char_stops = -1;
play.get_loc_name_last_time = -1;
play.get_loc_name_save_cursor = -1;
play.restore_cursor_mode_to = -1;
play.restore_cursor_image_to = -1;
play.ground_level_areas_disabled = 0;
play.next_screen_transition = -1;
play.temporarily_turned_off_character = -1;
play.inv_backwards_compatibility = 0;
play.gamma_adjustment = 100;
play.do_once_tokens.resize(0);
play.music_queue_size = 0;
play.shakesc_length = 0;
play.wait_counter=0;
play.SetWaitSkipResult(SKIP_NONE);
play.key_skip_wait = SKIP_NONE;
play.cur_music_number=-1;
play.music_repeat=1;
play.music_master_volume=100 + LegacyMusicMasterVolumeAdjustment;
play.digital_master_volume = 100;
play.screen_flipped=0;
play.speech_mode = kSpeech_VoiceText;
play.cant_skip_speech = user_to_internal_skip_speech((SkipSpeechStyle)game.options[OPT_NOSKIPTEXT]);
play.sound_volume = 255;
play.speech_volume = 255;
play.normal_font = 0;
play.speech_font = 1;
play.speech_text_shadow = 16;
play.screen_tint = -1;
play.bad_parsed_word[0] = 0;
play.swap_portrait_side = 0;
play.swap_portrait_lastchar = -1;
play.swap_portrait_lastlastchar = -1;
play.in_conversation = 0;
play.skip_display = 3;
play.no_multiloop_repeat = 0;
play.in_cutscene = 0;
play.fast_forward = 0;
play.totalscore = game.totalscore;
play.roomscript_finished = 0;
play.no_textbg_when_voice = 0;
play.max_dialogoption_width = get_fixed_pixel_size(180);
play.no_hicolor_fadein = 0;
play.bgspeech_game_speed = 0;
play.bgspeech_stay_on_display = 0;
play.unfactor_speech_from_textlength = 0;
play.mp3_loop_before_end = 70;
play.speech_music_drop = 60;
play.room_changes = 0;
play.check_interaction_only = 0;
play.replay_hotkey_unused = -1; // StartRecording: not supported.
play.dialog_options_x = 0;
play.dialog_options_y = 0;
play.min_dialogoption_width = 0;
play.disable_dialog_parser = 0;
play.ambient_sounds_persist = 0;
play.screen_is_faded_out = 0;
play.player_on_region = 0;
play.top_bar_backcolor = 8;
play.top_bar_textcolor = 16;
play.top_bar_bordercolor = 8;
play.top_bar_borderwidth = 1;
play.top_bar_ypos = 25;
play.top_bar_font = -1;
play.screenshot_width = 160;
play.screenshot_height = 100;
play.speech_text_align = kHAlignCenter;
play.auto_use_walkto_points = 1;
play.inventory_greys_out = 0;
play.skip_speech_specific_key = 0;
play.abort_key = 324; // Alt+X
play.fade_to_red = 0;
play.fade_to_green = 0;
play.fade_to_blue = 0;
play.show_single_dialog_option = 0;
play.keep_screen_during_instant_transition = 0;
play.read_dialog_option_colour = -1;
play.speech_portrait_placement = 0;
play.speech_portrait_x = 0;
play.speech_portrait_y = 0;
play.speech_display_post_time_ms = 0;
play.dialog_options_highlight_color = DIALOG_OPTIONS_HIGHLIGHT_COLOR_DEFAULT;
play.speech_has_voice = false;
play.speech_voice_blocking = false;
play.speech_in_post_state = false;
play.complete_overlay_on = 0;
play.text_overlay_on = 0;
play.narrator_speech = game.playercharacter;
play.crossfading_out_channel = 0;
play.speech_textwindow_gui = game.options[OPT_TWCUSTOM];
if (play.speech_textwindow_gui == 0)
play.speech_textwindow_gui = -1;
snprintf(play.game_name, sizeof(play.game_name), "%s", game.gamename);
play.lastParserEntry[0] = 0;
play.follow_change_room_timer = 150;
for (ee = 0; ee < MAX_ROOM_BGFRAMES; ee++)
play.raw_modified[ee] = 0;
play.game_speed_modifier = 0;
if (debug_flags & DBG_DEBUGMODE)
play.debug_mode = 1;
play.shake_screen_yoff = 0;
GUI::Options.DisabledStyle = static_cast<GuiDisableStyle>(game.options[OPT_DISABLEOFF]);
GUI::Options.ClipControls = game.options[OPT_CLIPGUICONTROLS] != 0;
memset(&play.walkable_areas_on[0],1,MAX_WALK_AREAS+1);
memset(&play.script_timers[0],0,MAX_TIMERS * sizeof(int));
memset(&play.default_audio_type_volumes[0], -1, MAX_AUDIO_TYPES * sizeof(int));
// reset graphical script vars (they're still used by some games)
for (ee = 0; ee < MAXGLOBALVARS; ee++)
play.globalvars[ee] = 0;
for (ee = 0; ee < MAXGSVALUES; ee++)
play.globalscriptvars[ee] = 0;
for (ee = 0; ee < MAXGLOBALSTRINGS; ee++)
play.globalstrings[ee][0] = 0;
if (!usetup.translation.IsEmpty())
Game_ChangeTranslation(usetup.translation.GetCStr());
update_invorder();
displayed_room = -10;
currentcursor=0;
our_eip=-4;
mousey=100; // stop icon bar popping up
// We use same variable to read config and be used at runtime for now,
// so update it here with regards to game design option
usetup.RenderAtScreenRes =
(game.options[OPT_RENDERATSCREENRES] == kRenderAtScreenRes_UserDefined && usetup.RenderAtScreenRes) ||
game.options[OPT_RENDERATSCREENRES] == kRenderAtScreenRes_Enabled;
}
void engine_setup_scsystem_auxiliary()
{
// ScriptSystem::aci_version is only 10 chars long
strncpy(scsystem.aci_version, EngineVersion.LongString.GetCStr(), 10);
if (usetup.override_script_os > eOS_Unknown)
{
scsystem.os = usetup.override_script_os;
}
else
{
scsystem.os = platform->GetSystemOSID();
}
}
void engine_prepare_to_start_game()
{
Debug::Printf("Prepare to start game");
engine_setup_scsystem_auxiliary();
if (usetup.load_latest_save)
{
int slot = GetLastSaveSlot();
if (slot >= 0)
loadSaveGameOnStartup = get_save_game_path(slot);
}
}
// TODO: move to test unit
Bitmap *test_allegro_bitmap;
IDriverDependantBitmap *test_allegro_ddb;
void allegro_bitmap_test_init()
{
test_allegro_bitmap = nullptr;
// Switched the test off for now
//test_allegro_bitmap = AllegroBitmap::CreateBitmap(320,200,32);
}
// Define location of the game data either using direct settings or searching
// for the available resource packs in common locations.
// Returns two paths:
// - startup_dir: this is where engine found game config and/or data;
// - data_path: full path of the main data pack;
// data_path's directory (may or not be eq to startup_dir) should be considered data directory,
// and this is where engine look for all game data.
HError define_gamedata_location_checkall(String &data_path, String &startup_dir)
{
// First try if they provided a startup option
if (!cmdGameDataPath.IsEmpty())
{
// If not a valid path - bail out
if (!File::IsFileOrDir(cmdGameDataPath))
return new Error(String::FromFormat("Provided game location is not a valid path.\n Cwd: %s\n Path: %s",
Directory::GetCurrentDirectory().GetCStr(),
cmdGameDataPath.GetCStr()));
// If it's a file, then keep it and proceed
if (File::IsFile(cmdGameDataPath))
{
Debug::Printf("Using provided game data path: %s", cmdGameDataPath.GetCStr());
startup_dir = Path::GetDirectoryPath(cmdGameDataPath);
data_path = cmdGameDataPath;
return HError::None();
}
}
#if AGS_SEARCH_FOR_GAME_ON_LAUNCH
// No direct filepath provided, search in common locations.
data_path = search_for_game_data_file(startup_dir);
if (data_path.IsEmpty())
{
return new Error("Engine was not able to find any compatible game data.",
startup_dir.IsEmpty() ? String() : String::FromFormat("Searched in: %s", startup_dir.GetCStr()));
}
data_path = Path::MakeAbsolutePath(data_path);
Debug::Printf(kDbgMsg_Info, "Located game data pak: %s", data_path.GetCStr());
return HError::None();
#else
data_path = platform->GetGameDataFile();
if (!data_path.IsEmpty())
{
return HError::None();
}
return new Error("The game location was not defined by startup settings.");
#endif
}
// Define location of the game data
bool define_gamedata_location()
{
String data_path, startup_dir;
HError err = define_gamedata_location_checkall(data_path, startup_dir);
if (!err)
{
platform->DisplayAlert("ERROR: Unable to determine game data.\n%s", err->FullMessage().GetCStr());
main_print_help();
return false;
}
// On success: set all the necessary path and filename settings
usetup.startup_dir = startup_dir;
usetup.main_data_file = data_path;
usetup.main_data_dir = Path::GetDirectoryPath(data_path);
return true;
}
// Find and preload main game data
bool engine_init_gamedata()
{
Debug::Printf(kDbgMsg_Info, "Initializing game data");
// First, find data location
if (!define_gamedata_location())
return false;
// Try init game lib
AssetError asset_err = AssetMgr->AddLibrary(usetup.main_data_file);
if (asset_err != kAssetNoError)
{
platform->DisplayAlert("ERROR: The game data is missing, is of unsupported format or corrupt.\nFile: '%s'", usetup.main_data_file.GetCStr());
return false;
}
// Pre-load game name and savegame folder names from data file
// TODO: research if that is possible to avoid this step and just
// read the full head game data at this point. This might require
// further changes of the order of initialization.
HError err = preload_game_data();
if (!err)
{
display_game_file_error(err);
return false;
}
// Setup ResPaths, so that we know out main locations further
ResPaths.GamePak.Path = usetup.main_data_file;
ResPaths.GamePak.Name = Path::GetFilename(usetup.main_data_file);
ResPaths.DataDir = usetup.install_dir.IsEmpty() ? usetup.main_data_dir : Path::MakeAbsolutePath(usetup.install_dir);
ResPaths.DataDir2 = Path::MakeAbsolutePath(usetup.opt_data_dir);