Skip to content

Commit

Permalink
Lua: Only load scripts after scene is valid
Browse files Browse the repository at this point in the history
  • Loading branch information
praydog committed May 17, 2024
1 parent 440cca9 commit 82cbd4b
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
52 changes: 52 additions & 0 deletions src/mods/ScriptRunner.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -838,6 +838,58 @@ void ScriptRunner::hook_battle_rule() {
}

void ScriptRunner::on_frame() {
if (!m_scene_okay) try {
if (!m_checked_scene_once) {
m_checked_scene_once = true;
m_scene_check_time = std::chrono::system_clock::now();
}

// Just bail out of this if 5 seconds have passed and we still haven't found the scene or scene manager.
if (std::chrono::system_clock::now() - m_scene_check_time > std::chrono::seconds(5)) {
m_scene_okay = true;
spdlog::warn("[ScriptRunner] Scene or scene manager not found after 5 seconds. Loading scripts anyways...");
return;
}

const auto scene_manager_t = sdk::find_type_definition("via.SceneManager");
if (scene_manager_t == nullptr) {
return;
}

const auto get_CurrentScene = scene_manager_t->get_method("get_CurrentScene");

if (get_CurrentScene == nullptr) {
return;
}

const auto scene_manager = sdk::get_native_singleton("via.SceneManager");

if (scene_manager == nullptr) {
return;
}

const auto context = sdk::get_thread_context();

if (context == nullptr) {
return;
}

const auto scene = get_CurrentScene->call_safe<void*>(context, scene_manager);

if (scene == nullptr) {
return;
}

m_scene_okay = true;
spdlog::info("[ScriptRunner] Scene and scene manager found. Loading scripts...");
} catch (const std::exception& e) {
spdlog::error("[ScriptRunner] Error while checking for scene: {}", e.what());
return;
} catch (...) {
spdlog::error("[ScriptRunner] Unknown error while checking for scene.");
return;
}

std::scoped_lock _{m_access_mutex};

hook_battle_rule();
Expand Down
3 changes: 3 additions & 0 deletions src/mods/ScriptRunner.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -338,6 +338,9 @@ class ScriptRunner : public Mod {
std::shared_mutex m_script_error_mutex{};
std::chrono::system_clock::time_point m_last_script_error_time{};

std::chrono::system_clock::time_point m_scene_check_time{};
bool m_checked_scene_once{false};
bool m_scene_okay{false};
bool m_console_spawned{false};
bool m_needs_first_reset{true};
bool m_last_online_match_state{false};
Expand Down

0 comments on commit 82cbd4b

Please sign in to comment.