-
Notifications
You must be signed in to change notification settings - Fork 196
/
Copy pathplayer.cpp
1599 lines (1379 loc) · 49.9 KB
/
player.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
/*
* This file is part of EasyRPG Player.
*
* EasyRPG Player is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* EasyRPG Player is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with EasyRPG Player. If not, see <http://www.gnu.org/licenses/>.
*/
// Headers
#include <algorithm>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <memory>
#ifdef _WIN32
# include "platform/windows/utils.h"
# include <windows.h>
#elif defined(EMSCRIPTEN)
# include <emscripten.h>
#endif
#include "async_handler.h"
#include "audio.h"
#include "cache.h"
#include "rand.h"
#include "cmdline_parser.h"
#include "game_dynrpg.h"
#include "filefinder.h"
#include "filefinder_rtp.h"
#include "fileext_guesser.h"
#include "filesystem_hook.h"
#include "game_actors.h"
#include "game_battle.h"
#include "game_destiny.h"
#include "game_map.h"
#include "game_message.h"
#include "game_enemyparty.h"
#include "game_ineluki.h"
#include "game_party.h"
#include "game_player.h"
#include "game_switches.h"
#include "game_screen.h"
#include "game_pictures.h"
#include "game_system.h"
#include "game_variables.h"
#include "game_strings.h"
#include "game_targets.h"
#include "game_windows.h"
#include "graphics.h"
#include <lcf/inireader.h>
#include "input.h"
#include <lcf/ldb/reader.h>
#include <lcf/lmt/reader.h>
#include <lcf/lsd/reader.h>
#include "main_data.h"
#include "output.h"
#include "player.h"
#include <lcf/reader_lcf.h>
#include <lcf/reader_util.h>
#include "scene_battle.h"
#include "scene_logo.h"
#include "scene_map.h"
#include "utils.h"
#include "version.h"
#include "game_quit.h"
#include "scene_settings.h"
#include "scene_title.h"
#include "instrumentation.h"
#include "transition.h"
#include <lcf/scope_guard.h>
#include <lcf/log_handler.h>
#include "baseui.h"
#include "game_clock.h"
#include "message_overlay.h"
#include "audio_midi.h"
#ifdef __ANDROID__
#include "platform/android/android.h"
#endif
#ifndef EMSCRIPTEN
// This is not used on Emscripten.
#include "exe_reader.h"
#endif
using namespace std::chrono_literals;
namespace Player {
int screen_width = SCREEN_TARGET_WIDTH;
int screen_height = SCREEN_TARGET_HEIGHT;
int menu_offset_x = (screen_width - MENU_WIDTH) / 2;
int menu_offset_y = (screen_height - MENU_HEIGHT) / 2;
int message_box_offset_x = (screen_width - MENU_WIDTH) / 2;
bool has_custom_resolution = false;
int exit_code = EXIT_SUCCESS;
bool exit_flag = false;
bool reset_flag = false;
bool debug_flag;
bool hide_title_flag;
int load_game_id;
int party_x_position;
int party_y_position;
std::vector<int> party_members;
int start_map_id;
bool no_rtp_flag;
std::string rtp_path;
bool no_audio_flag;
bool is_easyrpg_project;
std::string encoding;
std::string escape_symbol;
uint32_t escape_char;
std::string game_title;
std::shared_ptr<Meta> meta;
FileExtGuesser::RPG2KFileExtRemap fileext_map;
std::string startup_language;
Translation translation;
int frames;
std::string replay_input_path;
std::string record_input_path;
std::string command_line;
int speed_modifier_a;
int speed_modifier_b;
int rng_seed = -1;
Game_ConfigPlayer player_config;
Game_ConfigGame game_config;
#ifdef EMSCRIPTEN
std::string emscripten_game_name;
#endif
}
namespace {
std::vector<std::string> arguments;
// Overwritten by --encoding
std::string forced_encoding;
FileRequestBinding system_request_id;
FileRequestBinding save_request_id;
FileRequestBinding map_request_id;
}
void Player::Init(std::vector<std::string> args) {
lcf::LogHandler::SetHandler([](lcf::LogHandler::Level level, StringView message, lcf::LogHandler::UserData) {
Output::Debug("lcf ({}): {}", lcf::LogHandler::kLevelTags.tag(level), message);
});
frames = 0;
// Must be called before the first call to Output
Graphics::Init();
#ifdef _WIN32
SetConsoleOutputCP(65001);
#endif
// First parse command line arguments
arguments = args;
auto cfg = ParseCommandLine();
// Display a nice version string
auto header = GetFullVersionString() + " started";
Output::Debug("{}", header);
for (auto& c : header)
c = '=';
Output::Debug("{}", header);
#if defined(_WIN32)
WindowsUtils::InitMiniDumpWriter();
#endif
Output::Debug("CLI: {}", command_line);
Game_Clock::logClockInfo();
if (rng_seed < 0) {
Rand::SeedRandomNumberGenerator(time(NULL));
} else {
Rand::SeedRandomNumberGenerator(rng_seed);
}
Main_Data::Init();
DisplayUi.reset();
if(! DisplayUi) {
DisplayUi = BaseUi::CreateUi(Player::screen_width, Player::screen_height, cfg);
}
Input::Init(cfg.input, replay_input_path, record_input_path);
Input::AddRecordingData(Input::RecordingData::CommandLine, command_line);
player_config = std::move(cfg.player);
speed_modifier_a = cfg.input.speed_modifier_a.Get();
speed_modifier_b = cfg.input.speed_modifier_b.Get();
}
void Player::Run() {
Instrumentation::Init("EasyRPG-Player");
Scene::Push(std::make_shared<Scene_Logo>());
Graphics::UpdateSceneCallback();
reset_flag = false;
Game_Clock::ResetFrame(Game_Clock::now());
// Main loop
#if defined(USE_LIBRETRO) || defined(EMSCRIPTEN)
// emscripten implemented in main.cpp
// libretro invokes the MainLoop through a retro_run-callback
#else
while (Transition::instance().IsActive() || (Scene::instance && Scene::instance->type != Scene::Null)) {
MainLoop();
}
#endif
}
void Player::MainLoop() {
Instrumentation::FrameScope iframe;
const auto frame_time = Game_Clock::now();
Game_Clock::OnNextFrame(frame_time);
Player::UpdateInput();
if (!DisplayUi->ProcessEvents()) {
Scene::PopUntil(Scene::Null);
Player::Exit();
return;
}
int num_updates = 0;
while (Game_Clock::NextGameTimeStep()) {
if (num_updates > 0) {
Player::UpdateInput();
if (!DisplayUi->ProcessEvents()) {
Scene::PopUntil(Scene::Null);
Player::Exit();
return;
}
}
Scene::old_instances.clear();
Scene::instance->MainFunction();
Graphics::GetMessageOverlay().Update();
++num_updates;
}
if (num_updates == 0) {
// If no logical frames ran, we need to update the system keys only.
Input::UpdateSystem();
}
Player::Draw();
Scene::old_instances.clear();
if (!Transition::instance().IsActive() && Scene::instance->type == Scene::Null) {
Exit();
return;
}
auto frame_limit = DisplayUi->GetFrameLimit();
if (frame_limit == Game_Clock::duration()) {
return;
}
// Still time after graphic update? Yield until it's time for next one.
auto now = Game_Clock::now();
auto next = frame_time + frame_limit;
if (Game_Clock::now() < next) {
iframe.End();
Game_Clock::SleepFor(next - now);
}
}
void Player::Pause() {
Audio().BGM_Pause();
}
void Player::Resume() {
Input::ResetKeys();
Audio().BGM_Resume();
Game_Clock::ResetFrame(Game_Clock::now());
}
void Player::UpdateInput() {
// Input Logic:
if (Input::IsSystemTriggered(Input::TOGGLE_FPS)) {
DisplayUi->ToggleShowFps();
}
if (Input::IsSystemTriggered(Input::TAKE_SCREENSHOT)) {
Output::TakeScreenshot();
}
if (Input::IsSystemTriggered(Input::SHOW_LOG)) {
Output::ToggleLog();
}
if (Input::IsSystemTriggered(Input::TOGGLE_ZOOM)) {
DisplayUi->ToggleZoom();
}
float speed = 1.0;
if (Input::IsSystemPressed(Input::FAST_FORWARD_A)) {
speed = speed_modifier_a;
}
if (Input::IsSystemPressed(Input::FAST_FORWARD_B)) {
speed = speed_modifier_b;
}
Game_Clock::SetGameSpeedFactor(speed);
if (Main_Data::game_quit) {
reset_flag |= Main_Data::game_quit->ShouldQuit();
}
}
void Player::Update(bool update_scene) {
std::shared_ptr<Scene> old_instance = Scene::instance;
if (exit_flag) {
Scene::PopUntil(Scene::Null);
} else if (reset_flag && !Scene::IsAsyncPending()) {
reset_flag = false;
if (Scene::ReturnToTitleScene()) {
// Fade out music and stop sound effects before returning
Main_Data::game_system->BgmFade(800);
Audio().SE_Stop();
// Do not update this scene until it's properly set up in the next main loop
update_scene = false;
}
}
if (update_scene) {
IncFrame();
}
Audio().Update();
Input::Update();
// Game events can query full screen status and change their behavior, so this needs to
// be a game key and not a system key.
if (Input::IsTriggered(Input::TOGGLE_FULLSCREEN)) {
DisplayUi->ToggleFullscreen();
}
if (Main_Data::game_quit) {
Main_Data::game_quit->Update();
}
auto& transition = Transition::instance();
if (transition.IsActive()) {
transition.Update();
} else {
// If we aren't waiting on a transition, but we are waiting for scene delay.
Scene::instance->UpdateDelayFrames();
}
if (update_scene) {
if (Main_Data::game_ineluki) {
Main_Data::game_ineluki->Update();
}
Scene::instance->Update();
}
#ifdef __ANDROID__
EpAndroid::invoke();
#endif
}
void Player::Draw() {
Graphics::Update();
Graphics::Draw(*DisplayUi->GetDisplaySurface());
DisplayUi->UpdateDisplay();
}
void Player::IncFrame() {
++frames;
if (Main_Data::game_system) {
Main_Data::game_system->IncFrameCounter();
}
}
int Player::GetFrames() {
return frames;
}
void Player::Exit() {
if (player_config.settings_autosave.Get()) {
Scene_Settings::SaveConfig(true);
}
Graphics::UpdateSceneCallback();
#ifdef EMSCRIPTEN
BitmapRef surface = DisplayUi->GetDisplaySurface();
std::string message = "It's now safe to turn off\n your browser.";
DisplayUi->CleanDisplay();
Text::Draw(*surface, 84, DisplayUi->GetHeight() / 2 - 16, *Font::DefaultBitmapFont(), Color(221, 123, 64, 255), message);
DisplayUi->UpdateDisplay();
auto ret = FileFinder::Root().OpenOutputStream("/tmp/message.png", std::ios_base::binary | std::ios_base::out | std::ios_base::trunc);
if (ret) Output::TakeScreenshot(ret);
#endif
Player::ResetGameObjects();
Font::Dispose();
Graphics::Quit();
Output::Quit();
FileFinder::Quit();
DisplayUi.reset();
}
Game_Config Player::ParseCommandLine() {
debug_flag = false;
hide_title_flag = false;
exit_flag = false;
reset_flag = false;
load_game_id = -1;
party_x_position = -1;
party_y_position = -1;
start_map_id = -1;
no_rtp_flag = false;
no_audio_flag = false;
is_easyrpg_project = false;
Game_Battle::battle_test.enabled = false;
std::stringstream ss;
for (size_t i = 1; i < arguments.size(); ++i) {
ss << arguments[i] << " ";
}
command_line = ss.str();
CmdlineParser cp(arguments);
auto cfg = Game_Config::Create(cp);
bool battletest_handled = false;
cp.Rewind();
if (!cp.Done()) {
// BattleTest argument handling in a RPG_RT compatible way is very ugly because the arguments do not follow
// directly. Try to parse it and afterwards rewind the parser to parse the rest.
CmdlineArg arg;
long li_value = 0;
// Legacy BattleTest handling: When BattleTest is argument 1, then the values are:
// - arg4: troop_id
// - arg5-7: formation, condition, terrain_id (2k3 only)
// - arg2-3 are unrelated ("ShowTitle Window")
if (cp.ParseNext(arg, 6, {"battletest"})) {
Game_Battle::battle_test.enabled = true;
Game_Battle::battle_test.troop_id = 0;
// Starting from 3 to reach arg4 from arg1
if (arg.NumValues() >= 3) {
if (arg.ParseValue(2, li_value)) {
Game_Battle::battle_test.troop_id = li_value;
}
}
if (arg.NumValues() >= 6) {
if (arg.ParseValue(3, li_value)) {
Game_Battle::battle_test.formation = static_cast<lcf::rpg::System::BattleFormation>(li_value);
}
if (arg.ParseValue(4, li_value)) {
Game_Battle::battle_test.condition = static_cast<lcf::rpg::System::BattleCondition>(li_value);
}
if (arg.ParseValue(5, li_value)) {
Game_Battle::battle_test.terrain_id = static_cast<lcf::rpg::System::BattleFormation>(li_value);
}
}
battletest_handled = true;
}
}
cp.Rewind();
while (!cp.Done()) {
CmdlineArg arg;
long li_value = 0;
if (cp.ParseNext(arg, 0, "window")) {
// Legacy RPG_RT argument - window
cfg.video.fullscreen.Set(false);
continue;
}
if (cp.ParseNext(arg, 0, {"testplay", "--test-play"})) {
// Legacy RPG_RT argument - testplay
debug_flag = true;
continue;
}
if (cp.ParseNext(arg, 0, {"hidetitle", "--hide-title"})) {
// Legacy RPG_RT argument - hidetitle
hide_title_flag = true;
continue;
}
if(!battletest_handled && cp.ParseNext(arg, 4, {"battletest", "--battle-test"})) {
// Legacy RPG_RT argument - battletest
Game_Battle::battle_test.enabled = true;
Game_Battle::battle_test.troop_id = 0;
if (arg.NumValues() > 0) {
if (arg.ParseValue(0, li_value)) {
Game_Battle::battle_test.troop_id = li_value;
}
}
if (arg.NumValues() >= 4) {
// 2k3 passes formation, condition and terrain_id as args 5-7
if (arg.ParseValue(1, li_value)) {
Game_Battle::battle_test.formation = static_cast<lcf::rpg::System::BattleFormation>(li_value);
} else {
// When the argument is not a number, args5-7 were likely not specified and are something different
// Rewind to prevent losing other args
cp.RewindBy(3);
continue;
}
if (arg.ParseValue(2, li_value)) {
Game_Battle::battle_test.condition = static_cast<lcf::rpg::System::BattleCondition>(li_value);
}
if (arg.ParseValue(3, li_value)) {
Game_Battle::battle_test.terrain_id = static_cast<lcf::rpg::System::BattleFormation>(li_value);
}
} else if (arg.NumValues() >= 2) {
// Only troop-id was provided: Rewind to prevent losing other args
cp.RewindBy(arg.NumValues() - 1);
}
continue;
}
if (cp.ParseNext(arg, 1, "--project-path") && arg.NumValues() > 0) {
if (arg.NumValues() > 0) {
auto gamefs = FileFinder::Root().Create(FileFinder::MakeCanonical(arg.Value(0), 0));
if (!gamefs) {
Output::Error("Invalid --project-path {}", arg.Value(0));
}
FileFinder::SetGameFilesystem(gamefs);
}
continue;
}
if (cp.ParseNext(arg, 1, "--save-path")) {
if (arg.NumValues() > 0) {
auto savefs = FileFinder::Root().Create(FileFinder::MakeCanonical(arg.Value(0), 0));
if (!savefs) {
Output::Error("Invalid --save-path {}", arg.Value(0));
}
FileFinder::SetSaveFilesystem(savefs);
}
continue;
}
if (cp.ParseNext(arg, 1, "--load-game-id")) {
if (arg.ParseValue(0, li_value)) {
load_game_id = li_value;
}
continue;
}
/*else if (*it == "--load-game") {
// load game by filename
}
else if (*it == "--database") {
// overwrite database file
}
else if (*it == "--map-tree") {
// overwrite map tree file
}
else if (*it == "--start-map") {
// overwrite start map by filename
}*/
if (cp.ParseNext(arg, 1, "--seed")) {
if (arg.ParseValue(0, li_value) && li_value > 0) {
rng_seed = li_value;
}
continue;
}
if (cp.ParseNext(arg, 1, "--start-map-id")) {
if (arg.ParseValue(0, li_value)) {
start_map_id = li_value;
}
continue;
}
if (cp.ParseNext(arg, 2, "--start-position")) {
if (arg.ParseValue(0, li_value)) {
party_x_position = li_value;
}
if (arg.ParseValue(1, li_value)) {
party_y_position = li_value;
}
continue;
}
if (cp.ParseNext(arg, 4, "--start-party")) {
for (int i = 0; i < arg.NumValues(); ++i) {
if (arg.ParseValue(i, li_value)) {
party_members.push_back(li_value);
}
}
continue;
}
if (cp.ParseNext(arg, 1, "--record-input")) {
if (arg.NumValues() > 0) {
record_input_path = arg.Value(0);
}
continue;
}
if (cp.ParseNext(arg, 1, "--replay-input")) {
if (arg.NumValues() > 0) {
replay_input_path = arg.Value(0);
}
continue;
}
if (cp.ParseNext(arg, 1, "--encoding")) {
if (arg.NumValues() > 0) {
forced_encoding = arg.Value(0);
}
continue;
}
if (cp.ParseNext(arg, 0, {"--no-audio", "--disable-audio"})) {
no_audio_flag = true;
continue;
}
if (cp.ParseNext(arg, 0, {"--no-rtp", "--disable-rtp"})) {
no_rtp_flag = true;
continue;
}
if (cp.ParseNext(arg, 1, "--rtp-path")) {
if (arg.NumValues() > 0) {
rtp_path = arg.Value(0);
}
continue;
}
if (cp.ParseNext(arg, 0, "--no-log-color")) {
Output::SetTermColor(false);
continue;
}
if (cp.ParseNext(arg, 1, "--language")) {
if (arg.NumValues() > 0) {
startup_language = arg.Value(0);
if (startup_language == "default") {
startup_language.clear();
}
}
continue;
}
if (cp.ParseNext(arg, 0, "--version", 'v')) {
std::cout << GetFullVersionString() << std::endl;
exit(0);
break;
}
if (cp.ParseNext(arg, 0, {"--help", "/?"}, 'h')) {
PrintUsage();
exit(0);
break;
}
#ifdef EMSCRIPTEN
if (cp.ParseNext(arg, 1, "--game")) {
if (arg.NumValues() > 0) {
emscripten_game_name = arg.Value(0);
}
continue;
}
#endif
cp.SkipNext();
}
return cfg;
}
void Player::CreateGameObjects() {
// Parse game specific settings
CmdlineParser cp(arguments);
game_config = Game_ConfigGame::Create(cp);
// Reinit MIDI
MidiDecoder::Reset();
// Load the meta information file.
// Note: This should eventually be split across multiple folders as described in Issue #1210
std::string meta_file = FileFinder::Game().FindFile(META_NAME);
meta.reset(new Meta(meta_file));
// Guess non-standard extensions (for the DB) before loading the encoding
GuessNonStandardExtensions();
GetEncoding();
escape_symbol = lcf::ReaderUtil::Recode("\\", encoding);
if (escape_symbol.empty()) {
Output::Error("Invalid encoding: {}.", encoding);
}
escape_char = Utils::DecodeUTF32(Player::escape_symbol).front();
// Special handling for games with altered files
FileFinder::SetGameFilesystem(HookFilesystem::Detect(FileFinder::Game()));
// Check for translation-related directories and load language names.
translation.InitTranslations();
std::string game_path = FileFinder::GetFullFilesystemPath(FileFinder::Game());
std::string save_path = FileFinder::GetFullFilesystemPath(FileFinder::Save());
if (game_path == save_path) {
Output::DebugStr("Game and Save Directory:");
FileFinder::DumpFilesystem(FileFinder::Game());
} else {
Output::Debug("Game Directory:");
FileFinder::DumpFilesystem(FileFinder::Game());
Output::Debug("SaveDirectory:", save_path);
FileFinder::DumpFilesystem(FileFinder::Save());
}
LoadDatabase();
bool no_rtp_warning_flag = false;
Player::has_custom_resolution = false;
{ // Scope lifetime of variables for ini parsing
std::string ini_file = FileFinder::Game().FindFile(INI_NAME);
auto ini_stream = FileFinder::Game().OpenInputStream(ini_file, std::ios_base::in);
if (ini_stream) {
lcf::INIReader ini(ini_stream);
if (ini.ParseError() != -1) {
std::string title = ini.Get("RPG_RT", "GameTitle", GAME_TITLE);
game_title = lcf::ReaderUtil::Recode(title, encoding);
no_rtp_warning_flag = ini.Get("RPG_RT", "FullPackageFlag", "0") == "1" ? true : no_rtp_flag;
if (ini.HasValue("RPG_RT", "WinW") || ini.HasValue("RPG_RT", "WinH")) {
Player::screen_width = ini.GetInteger("RPG_RT", "WinW", SCREEN_TARGET_WIDTH);
Player::screen_height = ini.GetInteger("RPG_RT", "WinH", SCREEN_TARGET_HEIGHT);
Player::has_custom_resolution = true;
}
}
}
}
std::stringstream title;
if (!game_title.empty()) {
Output::Debug("Loading game {}", game_title);
title << game_title << " - ";
Input::AddRecordingData(Input::RecordingData::GameTitle, game_title);
} else {
Output::Debug("Could not read game title.");
}
title << GAME_TITLE;
DisplayUi->SetTitle(title.str());
if (no_rtp_warning_flag) {
Output::Debug("Game does not need RTP (FullPackageFlag=1)");
}
// ExFont parsing
Cache::exfont_custom.clear();
// Check for bundled ExFont
auto exfont_stream = FileFinder::OpenImage("Font", "ExFont");
if (!exfont_stream) {
// Backwards compatible with older Player versions
exfont_stream = FileFinder::OpenImage(".", "ExFont");
}
int& engine = game_config.engine;
#ifndef EMSCRIPTEN
// Attempt reading ExFont and version information from RPG_RT.exe (not supported on Emscripten)
std::unique_ptr<EXEReader> exe_reader;
auto exeis = FileFinder::Game().OpenFile(EXE_NAME);
if (exeis) {
exe_reader.reset(new EXEReader(std::move(exeis)));
Cache::exfont_custom = exe_reader->GetExFont();
if (engine == EngineNone) {
auto version_info = exe_reader->GetFileInfo();
version_info.Print();
bool is_patch_maniac;
engine = version_info.GetEngineType(is_patch_maniac);
if (!game_config.patch_override) {
game_config.patch_maniac.Set(is_patch_maniac);
}
}
if (engine == EngineNone) {
Output::Debug("Unable to detect version from exe");
}
} else {
Output::Debug("Cannot find RPG_RT");
}
#endif
if (exfont_stream) {
Output::Debug("Using custom ExFont: {}", FileFinder::GetPathInsideGamePath(exfont_stream.GetName()));
Cache::exfont_custom = Utils::ReadStream(exfont_stream);
}
if (engine == EngineNone) {
if (lcf::Data::system.ldb_id == 2003) {
engine = EngineRpg2k3;
if (!FileFinder::Game().FindFile("ultimate_rt_eb.dll").empty()) {
engine |= EngineEnglish | EngineMajorUpdated;
}
} else {
engine = EngineRpg2k;
if (lcf::Data::data.version >= 1) {
engine |= EngineEnglish | EngineMajorUpdated;
}
}
if (!(engine & EngineMajorUpdated)) {
if (FileFinder::IsMajorUpdatedTree()) {
engine |= EngineMajorUpdated;
}
}
}
Output::Debug("Engine configured as: 2k={} 2k3={} MajorUpdated={} Eng={}", Player::IsRPG2k(), Player::IsRPG2k3(), Player::IsMajorUpdatedVersion(), Player::IsEnglish());
Main_Data::filefinder_rtp = std::make_unique<FileFinder_RTP>(no_rtp_flag, no_rtp_warning_flag, rtp_path);
if (!game_config.patch_override) {
if (!FileFinder::Game().FindFile("harmony.dll").empty()) {
game_config.patch_key_patch.Set(true);
}
if (!FileFinder::Game().FindFile("dynloader.dll").empty()) {
game_config.patch_dynrpg.Set(true);
Output::Debug("This game uses DynRPG. Depending on the plugins used it will not run properly.");
}
if (!FileFinder::Game().FindFile("accord.dll").empty()) {
game_config.patch_maniac.Set(true);
}
if (!FileFinder::Game().FindFile(DESTINY_DLL).empty()) {
game_config.patch_destiny.Set(true);
}
}
game_config.PrintActivePatches();
ResetGameObjects();
LoadFonts();
if (Player::IsPatchKeyPatch()) {
Main_Data::game_ineluki->ExecuteScriptList(FileFinder::Game().FindFile("autorun.script"));
}
if (Player::IsPatchDestiny()) {
Main_Data::game_destiny->Load();
}
}
bool Player::ChangeResolution(int width, int height) {
if (!DisplayUi->ChangeDisplaySurfaceResolution(width, height)) {
Output::Warning("Resolution change to {}x{} failed", width, height);
return false;
}
Player::screen_width = width;
Player::screen_height = height;
Player::menu_offset_x = std::max<int>((Player::screen_width - MENU_WIDTH) / 2, 0);
Player::menu_offset_y = std::max<int>((Player::screen_height - MENU_HEIGHT) / 2, 0);
Player::message_box_offset_x = std::max<int>((Player::screen_width - MENU_WIDTH) / 2, 0);
Graphics::GetMessageOverlay().OnResolutionChange();
if (Main_Data::game_quit) {
Main_Data::game_quit->OnResolutionChange();
}
Output::Debug("Resolution changed to {}x{}", width, height);
return true;
}
void Player::RestoreBaseResolution() {
if (Player::screen_width == SCREEN_TARGET_WIDTH && Player::screen_height == SCREEN_TARGET_HEIGHT) {
return;
}
if (!Player::ChangeResolution(SCREEN_TARGET_WIDTH, SCREEN_TARGET_HEIGHT)) {
// Considering that this is the base resolution this should never fail
Output::Error("Failed restoring base resolution");
}
}
void Player::ResetGameObjects() {
// The init order is important
Main_Data::Cleanup();
Main_Data::game_switches = std::make_unique<Game_Switches>();
Main_Data::game_switches->SetLowerLimit(lcf::Data::switches.size());
auto min_var = lcf::Data::system.easyrpg_variable_min_value;
if (min_var == 0) {
if ((Player::game_config.patch_maniac.Get() & 1) == 1) {
min_var = std::numeric_limits<Game_Variables::Var_t>::min();
} else {
min_var = Player::IsRPG2k3() ? Game_Variables::min_2k3 : Game_Variables::min_2k;
}
}
auto max_var = lcf::Data::system.easyrpg_variable_max_value;
if (max_var == 0) {
if ((Player::game_config.patch_maniac.Get() & 1) == 1) {
max_var = std::numeric_limits<Game_Variables::Var_t>::max();
} else {
max_var = Player::IsRPG2k3() ? Game_Variables::max_2k3 : Game_Variables::max_2k;
}
}
Main_Data::game_variables = std::make_unique<Game_Variables>(min_var, max_var);
Main_Data::game_variables->SetLowerLimit(lcf::Data::variables.size());
Main_Data::game_strings = std::make_unique<Game_Strings>();
// Prevent a crash when Game_Map wants to reset the screen content
// because Setup() modified pictures array
Main_Data::game_screen = std::make_unique<Game_Screen>();
Main_Data::game_pictures = std::make_unique<Game_Pictures>();
Main_Data::game_windows = std::make_unique<Game_Windows>();
Main_Data::game_actors = std::make_unique<Game_Actors>();
Game_Map::Init();
Main_Data::game_system = std::make_unique<Game_System>();
Main_Data::game_targets = std::make_unique<Game_Targets>();
Main_Data::game_enemyparty = std::make_unique<Game_EnemyParty>();
Main_Data::game_party = std::make_unique<Game_Party>();
Main_Data::game_player = std::make_unique<Game_Player>();
Main_Data::game_quit = std::make_unique<Game_Quit>();
Main_Data::game_switches_global = std::make_unique<Game_Switches>();
Main_Data::game_variables_global = std::make_unique<Game_Variables>(min_var, max_var);
Main_Data::game_dynrpg = std::make_unique<Game_DynRpg>();
Main_Data::game_ineluki = std::make_unique<Game_Ineluki>();
Main_Data::game_destiny = std::make_unique<Game_Destiny>();
Game_Clock::ResetFrame(Game_Clock::now());
Main_Data::game_system->ReloadSystemGraphic();
Input::ResetMask();
}
static bool DefaultLmuStartFileExists(const FilesystemView& fs) {
// Compute map_id based on command line.
int map_id = Player::start_map_id == -1 ? lcf::Data::treemap.start.party_map_id : Player::start_map_id;
std::string mapName = Game_Map::ConstructMapName(map_id, false);
// Now see if the file exists.
return !fs.FindFile(mapName).empty();
}
void Player::GuessNonStandardExtensions() {
// Check all conditions, but check the remap last (since it is potentially slower).
FileExtGuesser::RPG2KNonStandardFilenameGuesser rpg2kRemap;
if (!FileFinder::IsRPG2kProject(FileFinder::Game()) &&
!FileFinder::IsEasyRpgProject(FileFinder::Game())) {
rpg2kRemap = FileExtGuesser::GetRPG2kProjectWithRenames(FileFinder::Game());
if (rpg2kRemap.Empty()) {
// Unlikely to happen because of the game browser only launches valid games
Output::Error("{}\n\n{}\n\n{}\n\n{}","No valid game was found.",
"EasyRPG must be run from a game folder containing\nRPG_RT.ldb and RPG_RT.lmt.",
"This engine only supports RPG Maker 2000 and 2003\ngames.",
"RPG Maker XP, VX, VX Ace and MV are NOT supported.");
}
}
// At this point we haven't yet determined if this is an easyrpg project or not.
// There are several ways to handle this, but we just put 'is_easyrpg_project' in the header
// and calculate it here.
// Try loading EasyRPG project files first, then fallback to normal RPG Maker
std::string edb = FileFinder::Game().FindFile(DATABASE_NAME_EASYRPG);
std::string emt = FileFinder::Game().FindFile(TREEMAP_NAME_EASYRPG);
is_easyrpg_project = !edb.empty() && !emt.empty();
// Non-standard extensions only apply to non-EasyRPG projects
if (!is_easyrpg_project && !rpg2kRemap.Empty()) {
fileext_map = rpg2kRemap.guessExtensions(*meta);
} else {
fileext_map = FileExtGuesser::RPG2KFileExtRemap();
}
}
void Player::LoadDatabase() {
// Load lcf::Database
lcf::Data::Clear();
if (is_easyrpg_project) {
std::string edb = FileFinder::Game().FindFile(DATABASE_NAME_EASYRPG);
auto edb_stream = FileFinder::Game().OpenInputStream(edb, std::ios_base::in);
if (!edb_stream) {
Output::Error("Error loading {}", DATABASE_NAME_EASYRPG);
return;
}
auto db = lcf::LDB_Reader::LoadXml(edb_stream);
if (!db) {
Output::ErrorStr(lcf::LcfReader::GetError());