Implement new real time timers. Works when the game is paused

This commit is contained in:
nox7
2026-09-18 13:54:43 -05:00
committed by Cole Green
parent 9c59c28b26
commit c992c8cb0c
6 changed files with 95 additions and 11 deletions
+14 -8
View File
@@ -1,6 +1,7 @@
#include "luamanagerimp.hpp"
#include <cassert>
#include <chrono>
#include <filesystem>
#include <functional>
@@ -275,14 +276,19 @@ namespace MWLua
mLuaEvents.finalizeEventBatch();
MWWorld::DateTimeManager& timeManager = *MWBase::Environment::get().getWorld()->getTimeManager();
if (!timeManager.isPaused())
{
mMenuScripts.processTimers(timeManager.getSimulationTime(), timeManager.getGameTime());
mGlobalScripts.processTimers(timeManager.getSimulationTime(), timeManager.getGameTime());
forEachActive(mActiveLocalScripts, [&](LocalScripts* scripts) {
scripts->processTimers(timeManager.getSimulationTime(), timeManager.getGameTime());
});
}
auto now = std::chrono::high_resolution_clock::now().time_since_epoch();
double realTime = std::chrono::duration<double>(now).count();
double simulationTime = timeManager.isPaused() ? 0 : timeManager.getSimulationTime();
double gameTime = timeManager.isPaused() ? 0 : timeManager.getGameTime();
// Always process real-time timers (runs even when paused), but only process game/simulation timers when not
// paused
mMenuScripts.processTimers(simulationTime, gameTime, realTime);
mGlobalScripts.processTimers(simulationTime, gameTime, realTime);
forEachActive(mActiveLocalScripts, [&](LocalScripts* scripts) {
scripts->processTimers(simulationTime, gameTime, realTime);
});
// Run event handlers for events that were sent before `finalizeEventBatch`.
mLuaEvents.callEventHandlers();
+2 -1
View File
@@ -74,10 +74,11 @@ namespace ESM
struct LuaTimer
{
enum class Type : bool
enum class Type : unsigned char
{
SIMULATION_TIME = 0,
GAME_TIME = 1,
REAL_TIME = 2,
};
Type mType;
+16
View File
@@ -1,5 +1,7 @@
#include "asyncpackage.hpp"
#include <chrono>
namespace sol
{
template <>
@@ -91,6 +93,20 @@ namespace LuaUtil
asyncId.mContainer->setupUnsavableTimer(
TimerType::GAME_TIME, gameTimeFn() + delay, asyncId.mScriptId, std::move(callback));
};
api["newRealTimeTimer"]
= [](const AsyncPackageId&, double delay, const TimerCallback& callback, sol::main_object callbackArg) {
auto now = std::chrono::high_resolution_clock::now().time_since_epoch();
double currentRealTime = std::chrono::duration<double>(now).count();
callback.mAsyncId.mContainer->setupSerializableRealTimeTimer(
currentRealTime + delay, callback.mAsyncId.mScriptId, callback.mName, std::move(callbackArg));
};
api["newUnsavableRealTimeTimer"]
= [](const AsyncPackageId& asyncId, double delay, sol::main_protected_function callback) {
auto now = std::chrono::high_resolution_clock::now().time_since_epoch();
double currentRealTime = std::chrono::duration<double>(now).count();
asyncId.mContainer->setupUnsavableRealTimeTimer(
currentRealTime + delay, asyncId.mScriptId, std::move(callback));
};
sol::table callbackMeta = Callback::makeMetatable(state);
api["callback"] = [callbackMeta](const AsyncPackageId& asyncId, sol::main_protected_function fn) -> sol::table {
+36 -1
View File
@@ -436,6 +436,8 @@ namespace LuaUtil
saveTimerFn(timer, TimerType::SIMULATION_TIME);
for (const Timer& timer : loadedData.mGameTimersQueue)
saveTimerFn(timer, TimerType::GAME_TIME);
for (const Timer& timer : loadedData.mRealTimeTimersQueue)
saveTimerFn(timer, TimerType::REAL_TIME);
data.mScripts.clear();
for (auto& [scriptId, script] : loadedData.mScripts)
{
@@ -599,6 +601,8 @@ namespace LuaUtil
if (savedTimer.mType == TimerType::GAME_TIME)
data.mGameTimersQueue.push_back(std::move(timer));
else if (savedTimer.mType == TimerType::REAL_TIME)
data.mRealTimeTimersQueue.push_back(std::move(timer));
else
data.mSimulationTimersQueue.push_back(std::move(timer));
}
@@ -612,6 +616,7 @@ namespace LuaUtil
std::make_heap(data.mSimulationTimersQueue.begin(), data.mSimulationTimersQueue.end());
std::make_heap(data.mGameTimersQueue.begin(), data.mGameTimersQueue.end());
std::make_heap(data.mRealTimeTimersQueue.begin(), data.mRealTimeTimersQueue.end());
if (mTracker)
mTracker->onLoad(*this);
@@ -662,6 +667,7 @@ namespace LuaUtil
variant.mEventHandlers.clear();
variant.mSimulationTimersQueue.clear();
variant.mGameTimersQueue.clear();
variant.mRealTimeTimersQueue.clear();
variant.mPublicInterfaces.clear();
}
},
@@ -718,6 +724,34 @@ namespace LuaUtil
insertTimer(type == TimerType::GAME_TIME ? data.mGameTimersQueue : data.mSimulationTimersQueue, std::move(t));
}
void ScriptsContainer::setupSerializableRealTimeTimer(
double time, int scriptId, std::string_view callbackName, sol::main_object callbackArg)
{
Timer t;
t.mCallback = std::string(callbackName);
t.mScriptId = scriptId;
t.mSerializable = true;
t.mTime = time;
t.mArg = std::move(callbackArg);
t.mSerializedArg = serialize(t.mArg, mSerializer);
LoadedData& data = ensureLoaded();
insertTimer(data.mRealTimeTimersQueue, std::move(t));
}
void ScriptsContainer::setupUnsavableRealTimeTimer(double time, int scriptId, sol::main_protected_function callback)
{
Timer t;
t.mScriptId = scriptId;
t.mSerializable = false;
t.mTime = time;
t.mCallback = mTemporaryCallbackCounter;
getScript(t.mScriptId).mTemporaryCallbacks.emplace(mTemporaryCallbackCounter, std::move(callback));
mTemporaryCallbackCounter++;
LoadedData& data = ensureLoaded();
insertTimer(data.mRealTimeTimersQueue, std::move(t));
}
void ScriptsContainer::callTimer(const Timer& t)
{
try
@@ -755,12 +789,13 @@ namespace LuaUtil
}
}
void ScriptsContainer::processTimers(double simulationTime, double gameTime)
void ScriptsContainer::processTimers(double simulationTime, double gameTime, double realTime)
{
mLua.protectedCall([&](LuaView& view) {
LoadedData& data = ensureLoaded();
updateTimerQueue(data.mSimulationTimersQueue, simulationTime);
updateTimerQueue(data.mGameTimersQueue, gameTime);
updateTimerQueue(data.mRealTimeTimersQueue, realTime);
});
}
+13 -1
View File
@@ -123,7 +123,7 @@ namespace LuaUtil
bool hasScript(int scriptId) const;
void removeScript(int scriptId);
void processTimers(double simulationTime, double gameTime);
void processTimers(double simulationTime, double gameTime, double realTime);
// Calls `onUpdate` (if present) for every script in the container.
// Handlers are called in the same order as scripts were added.
@@ -173,6 +173,17 @@ namespace LuaUtil
// because they can not be stored in saves. I.e. loading a saved game will not fully restore the state.
void setupUnsavableTimer(TimerType type, double time, int scriptId, sol::main_protected_function callback);
// Sets up a real-time timer, that can be automatically saved and loaded.
// time - the absolute real time (in seconds, system clock) when the timer should be executed.
// scriptPath - script path in VFS is used as script id. The script with the given path should already present
// in the container. callbackName - callback (should be registered in advance) for this timer. callbackArg -
// parameter for the callback (should be serializable).
void setupSerializableRealTimeTimer(
double time, int scriptId, std::string_view callbackName, sol::main_object callbackArg);
// Creates an unsavable real-time timer. Real-time timers run even when the game is paused.
void setupUnsavableRealTimeTimer(double time, int scriptId, sol::main_protected_function callback);
// decayedInstructionCount applies deferred decay.
void statsNextFrame() { ++mStatsFrame; }
@@ -327,6 +338,7 @@ namespace LuaUtil
std::vector<Timer> mSimulationTimersQueue;
std::vector<Timer> mGameTimersQueue;
std::vector<Timer> mRealTimeTimersQueue;
};
using UnloadedData = ESM::LuaScripts;
+14
View File
@@ -12,6 +12,7 @@ local time = {
day = 3600 * 24,
GameTime = 'GameTime',
SimulationTime = 'SimulationTime',
RealTime = 'RealTime',
}
---
@@ -49,6 +50,19 @@ function time.newSimulationTimer(delay, callback, callbackArg)
return async:newSimulationTimer(delay, callback, callbackArg)
end
---
-- Alias of async:newRealTimeTimer ; call callback(arg) in `delay` real seconds.
-- Real-time timers run even when the game is paused.
-- Callback must be registered in advance.
-- @function [parent=#time] newRealTimeTimer
-- @param #number delay
-- @param openmw.async#TimerCallback callback A callback returned by `registerTimerCallback`
-- @param arg An argument for `callback`; can be `nil`.
function time.newRealTimeTimer(delay, callback, callbackArg)
local async = require('openmw.async')
return async:newRealTimeTimer(delay, callback, callbackArg)
end
---
-- Run given function repeatedly.
-- Note that loading a save stops the evaluation. If it should always work, call it during the initialization of the script (i.e. not in a handler)