From 87e9c8aa568d96b043364b4e23d4654d46c56cbd Mon Sep 17 00:00:00 2001 From: Alug Date: Wed, 1 Jul 2026 18:07:05 +0200 Subject: [PATCH] =?UTF-8?q?port=20RR=C2=B4s=20lua=20hook=20profiling=20stu?= =?UTF-8?q?ff?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit very scuffed up since we dont have the srb2::Draw lib so it may display stuff out of screen bounds needs to be fixed up sometime --- src/CMakeLists.txt | 2 + src/Makefile | 2 +- src/Sourcefile | 1 + src/d_clisrv.c | 3 + src/d_main.c | 7 ++ src/d_netcmd.c | 6 + src/d_netcmd.h | 2 + src/lua_hooklib.c | 46 ++++++- src/lua_infolib.c | 6 +- src/lua_profile.cpp | 295 ++++++++++++++++++++++++++++++++++++++++++++ src/lua_profile.h | 38 ++++++ src/m_perfstats.c | 1 + src/m_perfstats.h | 1 + src/p_tick.c | 8 +- 14 files changed, 414 insertions(+), 4 deletions(-) create mode 100644 src/lua_profile.cpp create mode 100644 src/lua_profile.h diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index b1a06080b..55c85c1b3 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -276,6 +276,7 @@ if(${SRB2_CONFIG_HAVE_BLUA}) lua_hooklib.c lua_hudlib.c lua_hudlib_drawlist.c + lua_profile.cpp lua_infolib.c lua_maplib.c lua_mathlib.c @@ -291,6 +292,7 @@ if(${SRB2_CONFIG_HAVE_BLUA}) lua_hook.h lua_hud.h lua_hudlib_drawlist.h + lua_profile.ch lua_libs.h lua_script.h lua_udatalib.h diff --git a/src/Makefile b/src/Makefile index 4ee7cf1a9..77c9f7129 100644 --- a/src/Makefile +++ b/src/Makefile @@ -307,7 +307,7 @@ opts+=$(WFLAGS) $(CFLAGS) cxxopts:=$(opts) $(CXXFLAGS) opts+=$(CWFLAGS) # warning flags that shouldnt be passed to c++ compiler -libs+=$(LDFLAGS) -lstdc++ -lpthread +libs+=$(LDFLAGS) -lstdc++ -lpthread -lfmt asflags:=$(ASFLAGS) -x assembler-with-cpp diff --git a/src/Sourcefile b/src/Sourcefile index 08c18ebf0..f09a143bd 100644 --- a/src/Sourcefile +++ b/src/Sourcefile @@ -99,3 +99,4 @@ lua_skinlib.c lua_thinkerlib.c lua_udatalib.c lua_glib.c +lua_profile.cpp diff --git a/src/d_clisrv.c b/src/d_clisrv.c index 68a1bd4a5..52998689b 100644 --- a/src/d_clisrv.c +++ b/src/d_clisrv.c @@ -6848,7 +6848,10 @@ boolean TryRunTics(tic_t realtics) DEBFILE(va("============ Running tic %d (local %d)\n", gametic, leveltime)); if (update_stats) + { + ps_prevtictime = ps_tictime; PS_START_TIMING(ps_tictime); + } G_Ticker((gametic % NEWTICRATERATIO) == 0); ExtraDataTicker(); diff --git a/src/d_main.c b/src/d_main.c index 6abc6d681..e67129b08 100644 --- a/src/d_main.c +++ b/src/d_main.c @@ -79,6 +79,8 @@ #include "core/memory.h" #include "lua_script.h" +#include "lua_profile.h" + #include "m_random.h" /* Manually defined asset hashes for non-CMake builds @@ -668,6 +670,11 @@ static boolean D_Display(void) // so we can properly "pace" our frames D_LimitFps(); + if (cv_lua_profile.value > 0) + { + LUA_RenderTimers(); + } + PS_START_TIMING(ps_swaptime); I_FinishUpdate(); // page flip or blit buffer PS_STOP_TIMING(ps_swaptime); diff --git a/src/d_netcmd.c b/src/d_netcmd.c index 9d7d697cd..1937584db 100644 --- a/src/d_netcmd.c +++ b/src/d_netcmd.c @@ -47,6 +47,7 @@ #include "z_zone.h" #include "lua_script.h" #include "lua_hook.h" +#include "lua_profile.h" #include "m_cond.h" #include "m_anigif.h" #include "k_kart.h" // SRB2kart @@ -506,6 +507,9 @@ static CV_PossibleValue_t ps_descriptor_cons_t[] = { {1, "Average"}, {2, "SD"}, {3, "Minimum"}, {4, "Maximum"}, {0, NULL}}; consvar_t cv_ps_descriptor = {"ps_descriptor", "Average", 0, ps_descriptor_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; +//consvar_t cv_lua_profile = {"lua_profile", "0").values(CV_Unsigned).onchange(lua_profile_OnChange).description("Show hook timings over an average of N tics"); +consvar_t cv_lua_profile = {"lua_profile", "0", CV_CALL, CV_Unsigned, lua_profile_OnChange, 0, NULL, NULL, 0, 0, NULL}; + // only there to better keep track of it globally consvar_t cv_director = {"director", "Off", CV_HIDEN, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; @@ -935,6 +939,8 @@ void D_RegisterClientCommands(void) CV_RegisterVar(&cv_palette); CV_RegisterVar(&cv_palettenum); + CV_RegisterVar(&cv_lua_profile); + // m_menu.c CV_RegisterVar(&cv_chatheight); CV_RegisterVar(&cv_chatwidth); diff --git a/src/d_netcmd.h b/src/d_netcmd.h index 46ec396ec..25e050a13 100644 --- a/src/d_netcmd.h +++ b/src/d_netcmd.h @@ -189,6 +189,8 @@ extern consvar_t cv_ps_thinkframe_page; extern consvar_t cv_ps_samplesize; extern consvar_t cv_ps_descriptor; +extern consvar_t cv_lua_profile; + extern consvar_t cv_director, cv_kartdebugdirector, cv_showdirectorhud; extern consvar_t cv_showtrackaddon; diff --git a/src/lua_hooklib.c b/src/lua_hooklib.c index 90d8ec367..bed23cf36 100644 --- a/src/lua_hooklib.c +++ b/src/lua_hooklib.c @@ -25,6 +25,7 @@ #include "lua_libs.h" #include "lua_hook.h" #include "lua_hud.h" // hud_running errors +#include "lua_profile.h" /* ========================================================================= ABSTRACTION @@ -445,11 +446,54 @@ FUNCINLINE static ATTRINLINE void get_hook_from_table(Hook_State *hook, int n) lua_getref(gL, hookRefs[hook->id]); } +static int pcall(Hook_State *hook) +{ + return lua_pcall(gL, hook->values, hook->results, EINDEX); +} + +static const char *hook_name(Hook_State *hook) +{ + if (hud_running) + { + return hudHookNames[hook->hook_type]; + } + else if (hook->string) + { + return stringHookNames[hook->hook_type]; + } + //else if (hook->mobj_type > 0) + else if (hook->mobj_type != NONMOHOOK) + { + return mobjHookNames[hook->hook_type]; + } + else + { + return hookNames[hook->hook_type]; + } +} + +static int pcall_timed_or_untimed(Hook_State *hook) +{ + if (!hud_running && cv_lua_profile.value > 0) + { + lua_timer_t *timer = LUA_BeginFunctionTimer(gL, -1 - hook->values, hook_name(hook)); + int k = pcall(hook); + LUA_EndFunctionTimer(timer); + + return k; + } + else + { + return pcall(hook); + } +} + static int call_single_hook_no_copy(Hook_State *hook) { hook_important = hook->important; - if (lua_pcall(gL, hook->values, hook->results, EINDEX) == 0) + //if (lua_pcall(gL, hook->values, hook->results, EINDEX) == 0) + if (pcall_timed_or_untimed(hook) == 0) { if (hook->results > 0) { diff --git a/src/lua_infolib.c b/src/lua_infolib.c index 4c84c48d5..5f2f4f80c 100644 --- a/src/lua_infolib.c +++ b/src/lua_infolib.c @@ -22,7 +22,8 @@ #include "lua_script.h" #include "lua_libs.h" #include "lua_hud.h" // hud_running errors -#include "lua_hook.h" // cmd errors +#include "lua_hook.h" // hook_cmd_running errors +#include "lua_profile.h" boolean LUA_CallAction(enum actionnum actionnum, mobj_t *actor); state_t *astate = NULL; @@ -110,7 +111,10 @@ static void A_Lua(mobj_t *actor) LUA_PushUserdata(gL, actor, META_MOBJ); lua_pushinteger(gL, var1); lua_pushinteger(gL, var2); + + lua_timer_t *timer = LUA_BeginFunctionTimer(gL, -4, "A_Lua"); LUA_Call(gL, 3, 0, 1); + LUA_EndFunctionTimer(timer); lua_pop(gL, 1); // pop error handler diff --git a/src/lua_profile.cpp b/src/lua_profile.cpp new file mode 100644 index 000000000..a25646a74 --- /dev/null +++ b/src/lua_profile.cpp @@ -0,0 +1,295 @@ +// DR. ROBOTNIK'S RING RACERS +//----------------------------------------------------------------------------- +// Copyright (C) 2025 by James Robert Roman +// Copyright (C) 2025 by Kart Krew +// +// This program is free software distributed under the +// terms of the GNU General Public License, version 2. +// See the 'LICENSE' file for more details. +//----------------------------------------------------------------------------- + +#include "screen.h" +#include +#include +#include +#include +#include +#include + +#include +#include + +extern "C" { +#include "blua/lua.h" +}; + +#include "v_video.h" + +#include "command.h" +#include "doomtype.h" +#include "i_system.h" +#include "lua_profile.h" +#include "m_perfstats.h" + +extern "C" consvar_t cv_lua_profile; + +namespace +{ + +precise_t g_time_reference; +int g_tics_counted; + +double g_running_tic_time; +double g_avg_tic_time; + +bool g_invalid; + +}; // namespace + +struct lua_timer_t +{ + struct Stat + { + double calls = 0; + double time = 0.0; + }; + + Stat running, avg; +}; + +namespace +{ + +std::unordered_map g_tic_timers; + +}; // namespace + +lua_timer_t* LUA_BeginFunctionTimer(lua_State* L, int fn_idx, const char* name) +{ + lua_Debug ar; + + lua_pushvalue(L, fn_idx); + lua_getinfo(L, ">S", &ar); + + auto label = [&] + { + using sv = std::string_view; + sv view{ar.source}; + + switch (view.front()) + { + case '@': // file + if (std::size_t p = view.rfind('/'); p != sv::npos) // lump or base + { + return view.substr(p + 1); + } + break; + + case '=': // ?? + view.remove_prefix(1); + break; + } + + return view; + }; + + auto [it, ins] = g_tic_timers.try_emplace(fmt::format("{}:{} ({})", label(), ar.linedefined, name)); + auto& [key, timer] = *it; + + g_time_reference = I_GetPreciseTime(); + + return &timer; +} + +void LUA_EndFunctionTimer(lua_timer_t* timer) +{ + precise_t t = I_GetPreciseTime() - g_time_reference; + double precision = I_GetPrecisePrecision(); + + timer->running.time += t / precision; + timer->running.calls += 1.0; +} + +void LUA_ResetTicTimers(void) +{ + if (cv_lua_profile.value <= 0) + { + return; + } + + if (g_tics_counted < cv_lua_profile.value) + { + g_tics_counted++; + + double precision = I_GetPrecisePrecision(); + g_running_tic_time += ps_prevtictime.value.p / precision; + } + else + { + double counted = g_tics_counted; + + for (auto& [key, timer] : g_tic_timers) + { + timer.avg = {timer.running.calls / counted, timer.running.time / counted}; + timer.running = {}; + } + + g_avg_tic_time = g_running_tic_time / counted; + g_running_tic_time = 0.0; + + g_tics_counted = 1; + + g_invalid = false; + } +} + +void LUA_RenderTimers(void) +{ + ///using srb2::Draw; + + constexpr int kRowHeight = 4; + //constexpr float kScale = 0.5f; + + // pretty much what the whole srb2::Draw does lol + auto draw_row = [](float x, float y, INT32 flags, const std::string& str) + { + V_DrawSmallStringAtFixed( + FloatToFixed(x), + FloatToFixed(y), + V_MONOSPACE|V_ALLOWLOWERCASE|flags, + str.c_str() + ); + }; + + float row_y = kRowHeight - 60; + draw_row(0.f, row_y - kRowHeight, 0, fmt::format("-- AVERAGES PER TIC (over {} tics) --", cv_lua_profile.value)); + + //Draw row = Draw(0, kRowHeight).font(Draw::Font::kConsole).align(Draw::Align::kLeft).scale(0.5).flags(V_MONOSPACE); + //row.y(-kRowHeight).text("-- AVERAGES PER TIC (over {} tics) --", cv_lua_profile.value); + + if (g_invalid) + { + row_y += kRowHeight; + //row.flags(V_GRAYMAP).text(" "); + draw_row(0.f, row_y - kRowHeight, V_GRAYMAP, " "); + return; + } + + std::vector view; + view.reserve(g_tic_timers.size()); + + auto color_flag = [](double t) + { + if (t < 10.0) + { + return V_GRAYMAP; + } + else if (t >= 100.0) + { + return V_YELLOWMAP; + } + else + { + return 0; + } + }; + + { + double cum = 0.0; + + for (auto it = g_tic_timers.begin(); it != g_tic_timers.end(); ++it) + { + auto& [key, timer] = *it; + + cum += timer.avg.time; + + if (timer.avg.time > 0.0) + { + view.push_back(it); + } + } + + /* + Draw tally = row.flags(color_flag(cum * 1'000'000.0)); + + tally.text("{:8.2f} us - TOTAL", cum * 1'000'000.0); + tally.y(kRowHeight).text("{:8.2f} ms", cum * 1000.0); + tally.y(kRowHeight * 2).text( + "{:8.2f}% overhead ({:.2f} / {:.2f}) <-- not counting rendering time", + (cum / g_avg_tic_time) * 100.0, + cum * TICRATE, + g_avg_tic_time * TICRATE + ); + + row = row.y(kRowHeight * 4); + */ + + { + const INT32 tally_flags = color_flag(cum * 1'000'000.0); + + draw_row(0.f, row_y, tally_flags, fmt::format("{:8.2f} us - TOTAL", cum * 1'000'000.0)); + draw_row(0.f, row_y + kRowHeight, tally_flags, fmt::format("{:8.2f} ms", cum * 1000.0)); + draw_row(0.f, row_y + kRowHeight * 2, tally_flags, fmt::format( + "{:8.2f}% overhead ({:.2f} / {:.2f}) <-- not counting rendering time", + (cum / g_avg_tic_time) * 100.0, + (cum * (double)TICRATE), + (g_avg_tic_time * (double)TICRATE) + )); + } + + row_y += kRowHeight * 4; // row = row.y(kRowHeight * 4) + + } + + std::sort( + view.rbegin(), + view.rend(), + [](auto a, auto b) + { + auto& [k1, t1] = *a; + auto& [k2, t2] = *b; + return t1.avg.time < t2.avg.time; + } + ); + + for (auto it : view) + { + auto& [key, timer] = *it; + + double t = timer.avg.time * 1'000'000.0; + + /* + row.flags(color_flag(t)).text( + "{:>8.2f} us {:>8.2f} calls - {}", + t, + timer.avg.calls, + key + ); + + row = row.y(kRowHeight); + */ + + draw_row(0.f, row_y, color_flag(t), fmt::format( + "{:>8.2f} us {:>8.2f} calls - {}", + t, + timer.avg.calls, + key + )); + + row_y += kRowHeight; // row = row.y(kRowHeight) + + // FIXME this is all ugly and sucks + if (row_y >= BASEVIDHEIGHT) + break; + } +} + +extern "C" void lua_profile_OnChange(void) +{ + g_invalid = true; + + if (cv_lua_profile.value == 0) + { + g_tic_timers = {}; + } +} diff --git a/src/lua_profile.h b/src/lua_profile.h new file mode 100644 index 000000000..80475613d --- /dev/null +++ b/src/lua_profile.h @@ -0,0 +1,38 @@ +// DR. ROBOTNIK'S RING RACERS +//----------------------------------------------------------------------------- +// Copyright (C) 2025 by James Robert Roman +// Copyright (C) 2025 by Kart Krew +// +// This program is free software distributed under the +// terms of the GNU General Public License, version 2. +// See the 'LICENSE' file for more details. +//----------------------------------------------------------------------------- + +#ifndef lua_profile_h +#define lua_profile_h + +#include "blua/lua.h" +#include "doomtype.h" +//#include "typedef.h" + +#ifdef __cplusplus +extern "C" { +#endif + +struct lua_timer_t; +typedef struct lua_timer_t lua_timer_t; + +void LUA_ResetTicTimers(void); + +lua_timer_t *LUA_BeginFunctionTimer(lua_State *L, int fn_idx, const char *name); +void LUA_EndFunctionTimer(lua_timer_t *timer); + +void LUA_RenderTimers(void); + +void lua_profile_OnChange(void); + +#ifdef __cplusplus +} // extern "C" +#endif + +#endif/*lua_profile_h*/ diff --git a/src/m_perfstats.c b/src/m_perfstats.c index 49a855686..90bde47e9 100644 --- a/src/m_perfstats.c +++ b/src/m_perfstats.c @@ -47,6 +47,7 @@ struct perfstatrow { static ps_metric_t ps_frametime = {0}; ps_metric_t ps_tictime = {0}; +ps_metric_t ps_prevtictime = {0}; ps_metric_t ps_playerthink_time = {0}; ps_metric_t ps_thinkertime = {0}; diff --git a/src/m_perfstats.h b/src/m_perfstats.h index 083656d61..474c6c841 100644 --- a/src/m_perfstats.h +++ b/src/m_perfstats.h @@ -36,6 +36,7 @@ typedef struct #define PS_STOP_TIMING(metric) metric.value.p = I_GetPreciseTime() - metric.value.p extern ps_metric_t ps_tictime; +extern ps_metric_t ps_prevtictime; extern ps_metric_t ps_playerthink_time; extern ps_metric_t ps_thinkertime; diff --git a/src/p_tick.c b/src/p_tick.c index d0d25be69..455a8d5ac 100644 --- a/src/p_tick.c +++ b/src/p_tick.c @@ -38,6 +38,8 @@ #include "i_video.h" // rendermode #include "m_perfstats.h" +#include "lua_profile.h" + // Object place #include "m_cheat.h" @@ -622,6 +624,8 @@ void P_Ticker(boolean run) } } + LUA_ResetTicTimers(); + ps_lua_mobjhooks.value.i = 0; ps_checkposition_calls.value.i = 0; @@ -629,6 +633,7 @@ void P_Ticker(boolean run) LUA_HookPreThinkFrame(); PS_STOP_TIMING(ps_lua_prethinkframe_time); + // OK! Now that we got all of that sorted, players can think! PS_START_TIMING(ps_playerthink_time); for (i = 0; i < MAXPLAYERS; i++) { @@ -675,6 +680,7 @@ void P_Ticker(boolean run) PS_STOP_TIMING(ps_lua_thinkframe_time); } + // Run shield positioning P_RunOverlays(); P_RunShadows(); @@ -796,7 +802,7 @@ void P_Ticker(boolean run) if (!player->mo) continue; - const boolean skybox = (skyboxmo[0] && cv_skybox.value); + const boolean skybox = (skyboxmo[0] && cv_skybox.value); // True if there's a skybox object and skyboxes are on if (skyVisiblePerPlayer[i] && skybox) {