aboutsummaryrefslogtreecommitdiff
path: root/NorthstarDedicatedTest/latencyflex.cpp
blob: 3e2cecd7d55dd77e5df67b975dc370e0e01a4e46 (plain)
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
#include "pch.h"
#include "latencyflex.h"
#include "hookutils.h"
#include "convar.h"

typedef void (*OnRenderStartType)();
OnRenderStartType OnRenderStart;

ConVar* Cvar_r_latencyflex;

HMODULE m_lfxModule {};
typedef void (*PFN_lfx_WaitAndBeginFrame)();
PFN_lfx_WaitAndBeginFrame m_lfx_WaitAndBeginFrame {};

void OnRenderStartHook()
{
	// Sleep before next frame as needed to reduce latency.
	if (Cvar_r_latencyflex->GetInt())
	{
		if (m_lfx_WaitAndBeginFrame)
		{
			m_lfx_WaitAndBeginFrame();
		}
	}

	OnRenderStart();
}

void InitialiseLatencyFleX(HMODULE baseAddress)
{
	// Connect to the LatencyFleX service
	// LatencyFleX is an open source vendor agnostic replacement for Nvidia Reflex input latency reduction technology.
	// https://ishitatsuyuki.github.io/post/latencyflex/
	const auto lfxModuleName = "latencyflex_layer.dll";
	const auto lfxModuleNameFallback = "latencyflex_wine.dll";
	auto useFallbackEntrypoints = false;

	// Load LatencyFleX library.
	m_lfxModule = ::LoadLibraryA(lfxModuleName);
	if (m_lfxModule == nullptr && ::GetLastError() == ERROR_MOD_NOT_FOUND)
	{
		spdlog::info("LFX: Primary LatencyFleX library not found, trying fallback.");

		m_lfxModule = ::LoadLibraryA(lfxModuleNameFallback);
		if (m_lfxModule == nullptr)
		{
			if (::GetLastError() == ERROR_MOD_NOT_FOUND)
			{
				spdlog::info("LFX: Fallback LatencyFleX library not found.");
			}
			else
			{
				spdlog::info("LFX: Error loading fallback LatencyFleX library - Code: {}", ::GetLastError());
			}

			return;
		}

		useFallbackEntrypoints = true;
	}
	else if (m_lfxModule == nullptr)
	{
		spdlog::info("LFX: Error loading primary LatencyFleX library - Code: {}", ::GetLastError());
		return;
	}

	m_lfx_WaitAndBeginFrame = reinterpret_cast<PFN_lfx_WaitAndBeginFrame>(reinterpret_cast<void*>(
		GetProcAddress(m_lfxModule, !useFallbackEntrypoints ? "lfx_WaitAndBeginFrame" : "winelfx_WaitAndBeginFrame")));

	spdlog::info("LFX: Initialized.");

	Cvar_r_latencyflex = new ConVar("r_latencyflex", "1", FCVAR_ARCHIVE, "Whether or not to use LatencyFleX input latency reduction.");

	HookEnabler hook;
	ENABLER_CREATEHOOK(hook, (char*)baseAddress + 0x1952C0, &OnRenderStartHook, reinterpret_cast<LPVOID*>(&OnRenderStart));
}