Widescreen experiment: native render size via dxwrapper, classic menus

- mods/widescreen: redirect the world view's reads of the 1024.0/768.0
  constants and the 3D ortho extents to our variables; render size =
  monitor; relocate the world view's tile draw list (1750 entries, no
  bounds check) into an enlarged object (16384 entries).
- mods/dxwrapper: route DirectDraw through dxwrapper (Dd7to9, D3D9) since
  Windows' D3D7 cannot render to targets larger than 2048; fix the game's
  device info GUID pointer that dxwrapper's enumeration leaves invalid.
  Pinned release fetched by CMake (hash-checked), installed next to the DLL.
- Main menu (UI thread) and loading screen render in a 1024x768 viewport
  and are presented scaled ("classic" layout); in-game uses the full size.
- re/patch: verified code patches (operand redirect, push immediates,
  displacements) and startup hooks; build.ps1/CMake download fixes.

In-game view untested yet; HUD still at the top-left.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
khallaandClaude Opus 5.5 committed 2026-10-14 00:47:03 +02:00
1 parent c8dc689bc6
commit 795fe8f087
19 files changed
+860 -28

No files matched your search

+54 -23
View File
@@ -26,12 +26,15 @@
// SetCursorPos by a game-pixel delta, which is not scaled to screen pixels.
#include <algorithm>
#include <atomic>
#include <windows.h>
#include <windowsx.h>
#include "game/engine/input.h"
#include "game/render/dx_driver7.h"
#include "mods/dxwrapper.h"
#include "mods/widescreen.h"
#include "re/config.h"
#include "game/addresses.h"
#include "re/hook.h"
@@ -39,17 +42,28 @@
namespace {
struct Viewport {
bool active = false;
HWND window = nullptr;
bool runInBackground = false;
// Where a gameWidth x gameHeight image appears in the window.
struct Layout {
int gameWidth = 0;
int gameHeight = 0;
RECT client = {}; // scaled game image, window client coordinates
RECT screen = {}; // same rectangle, screen coordinates
};
struct Viewport {
bool active = false;
HWND window = nullptr;
bool runInBackground = false;
Layout full; // the whole back buffer
Layout classic; // its top-left 1024x768 (menus, loading screen; widescreen mod)
};
Viewport g_viewport;
std::atomic<bool> g_classicShown = false; // which layout the last presented frame used
const Layout& CurrentLayout() {
return g_classicShown ? g_viewport.classic : g_viewport.full;
}
bool Enabled() {
return re::ConfigInt("borderless", "Enabled", 1) != 0;
@@ -86,35 +100,43 @@ void ApplyBorderless(game::DxDriver7* driver) {
SetWindowLongW(window, GWL_STYLE, WS_POPUP | WS_VISIBLE);
SetWindowPos(window, HWND_TOP, area.left, area.top, areaWidth, areaHeight, SWP_FRAMECHANGED | SWP_SHOWWINDOW);
const bool integerScale = re::ConfigInt("borderless", "IntegerScale", 0) != 0;
auto makeLayout = [&](int width, int height) {
Layout layout;
layout.gameWidth = width;
layout.gameHeight = height;
layout.client = FitRect(areaWidth, areaHeight, width, height, integerScale);
layout.screen = layout.client;
OffsetRect(&layout.screen, area.left, area.top);
return layout;
};
Viewport viewport;
viewport.window = window;
viewport.runInBackground = re::ConfigInt("borderless", "RunInBackground", 1) != 0;
viewport.gameWidth = driver->mode.width;
viewport.gameHeight = driver->mode.height;
viewport.client = FitRect(areaWidth, areaHeight, viewport.gameWidth, viewport.gameHeight,
re::ConfigInt("borderless", "IntegerScale", 0) != 0);
viewport.screen = viewport.client;
OffsetRect(&viewport.screen, area.left, area.top);
viewport.full = makeLayout(driver->mode.width, driver->mode.height);
viewport.classic = makeLayout(std::min<int>(driver->mode.width, 1024), std::min<int>(driver->mode.height, 768));
viewport.active = true;
g_viewport = viewport;
g_classicShown = false;
// Paint the bars: the window class background brush is black.
InvalidateRect(window, nullptr, TRUE);
re::Log("borderless: %dx%d game -> %ldx%ld monitor, image at (%ld,%ld) %ldx%ld", viewport.gameWidth,
viewport.gameHeight, static_cast<long>(areaWidth), static_cast<long>(areaHeight), viewport.client.left,
viewport.client.top, viewport.client.right - viewport.client.left,
viewport.client.bottom - viewport.client.top);
const RECT& image = viewport.full.client;
re::Log("borderless: %dx%d game -> %ldx%ld monitor, image at (%ld,%ld) %ldx%ld", viewport.full.gameWidth,
viewport.full.gameHeight, static_cast<long>(areaWidth), static_cast<long>(areaHeight), image.left,
image.top, image.right - image.left, image.bottom - image.top);
}
// Window client coordinates -> game pixels.
POINT ToGame(POINT p) {
const Viewport& v = g_viewport;
const int width = v.client.right - v.client.left;
const int height = v.client.bottom - v.client.top;
const Layout& layout = CurrentLayout();
const int width = layout.client.right - layout.client.left;
const int height = layout.client.bottom - layout.client.top;
POINT result;
result.x = std::clamp(MulDiv(p.x - v.client.left, v.gameWidth, width), 0, v.gameWidth - 1);
result.y = std::clamp(MulDiv(p.y - v.client.top, v.gameHeight, height), 0, v.gameHeight - 1);
result.x = std::clamp(MulDiv(p.x - layout.client.left, layout.gameWidth, width), 0, layout.gameWidth - 1);
result.y = std::clamp(MulDiv(p.y - layout.client.top, layout.gameHeight, height), 0, layout.gameHeight - 1);
return result;
}
@@ -122,9 +144,9 @@ POINT ToGame(POINT p) {
void PaintBars(HDC dc) {
RECT window;
GetClientRect(g_viewport.window, &window);
const RECT& image = CurrentLayout().client;
const int saved = SaveDC(dc);
ExcludeClipRect(dc, g_viewport.client.left, g_viewport.client.top, g_viewport.client.right,
g_viewport.client.bottom);
ExcludeClipRect(dc, image.left, image.top, image.right, image.bottom);
FillRect(dc, &window, static_cast<HBRUSH>(GetStockObject(BLACK_BRUSH)));
RestoreDC(dc, saved);
}
@@ -146,11 +168,13 @@ RE_HOOK(addr::MainWindowProc, MainWindowProc);
int __fastcall DxDriver7_SetDisplayMode(DxDriver7* self, void* edx, void* deviceCaps, const DxDisplayMode* mode,
uint32_t unknown) {
mods::dxwrapper::FixDeviceInfo(deviceCaps);
if (!Enabled()) {
return DxDriver7_SetDisplayMode_original(self, edx, deviceCaps, mode, unknown);
}
DxDisplayMode windowed = *mode;
windowed.fullscreen = 0;
mods::widescreen::ApplyRenderSize(windowed, self->window);
g_viewport.active = false;
const int result = DxDriver7_SetDisplayMode_original(self, edx, deviceCaps, &windowed, unknown);
if (result) {
@@ -163,8 +187,15 @@ int __fastcall DxDriver7_Flip(DxDriver7* self, void* edx) {
// The original computes the blit rectangles once, for a centred window of
// exactly the game's size; override them on every present.
if (g_viewport.active && self->window == g_viewport.window) {
self->blitSource = {0, 0, g_viewport.gameWidth, g_viewport.gameHeight};
self->blitDest = g_viewport.screen;
// Menus and the loading screen only fill the top-left 1024x768 of a
// widened back buffer; show just that part, scaled like before.
const bool classic = mods::widescreen::IsClassicFrame();
if (g_classicShown.exchange(classic) != classic) {
InvalidateRect(self->window, nullptr, TRUE); // repaint the bars for the new layout
}
const Layout& layout = CurrentLayout();
self->blitSource = {0, 0, layout.gameWidth, layout.gameHeight};
self->blitDest = layout.screen;
}
return DxDriver7_Flip_original(self, edx);
}
+116
View File
@@ -0,0 +1,116 @@
// Route the game's DirectDraw 7 / Direct3D 7 through dxwrapper (Dd7to9:
// translation to Direct3D 9). Windows' own D3D7 runtime cannot render to
// surfaces larger than 2048x2048, which the widescreen mod needs.
//
// The build puts dxwrapper's ddraw.dll stub, dxwrapper.dll and our
// config/dxwrapper.ini into dxwrapper/ next to sacred_re.dll; the game folder
// is not touched. sacred.exe imports three functions from DDRAW.dll; we hook
// them and forward to the wrapper, which is loaded on the first call (never
// from DllMain). Calls made while the wrapper is running (it may use the real
// DirectDraw itself) go to the original functions.
//
// sacred_re.ini:
// [renderer]
// DxWrapper=1 ; 0 = Windows' DirectDraw (render size limited to 2048)
#include "mods/dxwrapper.h"
#include <cstdint>
#include <cstring>
#include <string>
#include <windows.h>
#include <ddraw.h>
#include "re/config.h"
#include "re/hook.h"
#include "re/log.h"
namespace mods::dxwrapper {
namespace {
HMODULE g_wrapper = nullptr;
bool g_loadAttempted = false;
thread_local int g_insideWrapper = 0;
std::wstring WrapperPath() {
return re::ModuleDirectory() + L"dxwrapper\\ddraw.dll";
}
bool Enabled() {
return re::ConfigInt("renderer", "DxWrapper", 1) != 0;
}
FARPROC WrapperFunction(const char* name) {
if (!g_loadAttempted) {
g_loadAttempted = true;
const std::wstring path = WrapperPath();
g_wrapper = LoadLibraryW(path.c_str());
if (g_wrapper) {
re::Log("dxwrapper: loaded %ls", path.c_str());
} else {
re::Log("dxwrapper: could not load %ls (error %lu), using Windows' DirectDraw", path.c_str(),
GetLastError());
}
}
return g_wrapper ? GetProcAddress(g_wrapper, name) : nullptr;
}
// Calls `function` from the wrapper if possible, else `original`.
template <typename Function, typename... Args>
HRESULT Forward(const char* name, Function original, Args... args) {
if (g_insideWrapper == 0 && Enabled()) {
if (auto wrapped = reinterpret_cast<Function>(WrapperFunction(name))) {
++g_insideWrapper;
const HRESULT result = wrapped(args...);
--g_insideWrapper;
return result;
}
}
return original(args...);
}
} // namespace
bool IsActive() {
if (!Enabled()) {
return false;
}
if (g_loadAttempted) {
return g_wrapper != nullptr;
}
return GetFileAttributesW(WrapperPath().c_str()) != INVALID_FILE_ATTRIBUTES;
}
void FixDeviceInfo(void* deviceInfo) {
auto* bytes = static_cast<uint8_t*>(deviceInfo);
const uint32_t guidAddress = static_cast<uint32_t>(reinterpret_cast<uintptr_t>(bytes + 0x3f4));
uint32_t guidPointer;
memcpy(&guidPointer, bytes + 4, 4);
if (guidPointer != guidAddress) {
re::Log("dxwrapper: device info GUID pointer was 0x%08x, set to 0x%08x", guidPointer, guidAddress);
memcpy(bytes + 4, &guidAddress, 4);
}
}
HRESULT WINAPI DirectDrawCreateExViaWrapper(GUID* guid, LPVOID* directDraw, REFIID iid, IUnknown* outer);
HRESULT WINAPI DirectDrawCreateViaWrapper(GUID* guid, LPDIRECTDRAW* directDraw, IUnknown* outer);
HRESULT WINAPI DirectDrawEnumerateExAViaWrapper(LPDDENUMCALLBACKEXA callback, LPVOID context, DWORD flags);
RE_HOOK_API(DirectDrawCreateEx, DirectDrawCreateExViaWrapper);
RE_HOOK_API(DirectDrawCreate, DirectDrawCreateViaWrapper);
RE_HOOK_API(DirectDrawEnumerateExA, DirectDrawEnumerateExAViaWrapper);
HRESULT WINAPI DirectDrawCreateExViaWrapper(GUID* guid, LPVOID* directDraw, REFIID iid, IUnknown* outer) {
return Forward("DirectDrawCreateEx", DirectDrawCreateExViaWrapper_original, guid, directDraw, iid, outer);
}
HRESULT WINAPI DirectDrawCreateViaWrapper(GUID* guid, LPDIRECTDRAW* directDraw, IUnknown* outer) {
return Forward("DirectDrawCreate", DirectDrawCreateViaWrapper_original, guid, directDraw, outer);
}
HRESULT WINAPI DirectDrawEnumerateExAViaWrapper(LPDDENUMCALLBACKEXA callback, LPVOID context, DWORD flags) {
return Forward("DirectDrawEnumerateExA", DirectDrawEnumerateExAViaWrapper_original, callback, context, flags);
}
} // namespace mods::dxwrapper
+16
View File
@@ -0,0 +1,16 @@
#pragma once
namespace mods::dxwrapper {
// True when the game's DirectDraw calls go to dxwrapper (Direct3D 9), which
// has no 2048x2048 render target limit.
bool IsActive();
// The device info the game passes to DxDriver7::SetDisplayMode keeps a pointer
// to its own device GUID at +4 (the GUID itself is at +0x3f4); the game uses
// it for EnumZBufferFormats. Under dxwrapper the game's device enumeration
// leaves garbage there (0x3c0) and dxwrapper crashes dereferencing it.
// Restores the pointer Windows' DirectDraw would have produced.
void FixDeviceInfo(void* deviceInfo);
} // namespace mods::dxwrapper
+249
View File
@@ -0,0 +1,249 @@
// Widescreen: render the world 1:1 at the monitor's resolution, showing more
// of it, instead of scaling a 1024x768 image.
//
// The world view sizes itself from zoom * 1024.0 / 768.0 (float constants that
// the UI also reads) and projects 3D models with an ortho camera of
// +-267 x +-200 world units (times zoom). We redirect only the world view's
// reads of those constants to our own variables, so the UI keeps its
// 1024x768 layout, and set the variables from the render size.
// See docs/widescreen.md.
//
// sacred_re.ini:
// [widescreen]
// Enabled=1
// Width=0 ; 0 = monitor width
// Height=0 ; 0 = monitor height
//
// Windows' Direct3D 7 limits the render size to 2048x2048 unless the dxwrapper
// mod (Direct3D 9) is active; the borderless mod centres a smaller image 1:1.
//
// Experimental: the UI is still drawn at the top-left 1024x768, and creatures
// are only active within the original distance.
#include "mods/widescreen.h"
#include <algorithm>
#include <atomic>
#include <bit>
#include <iterator>
#include <cstdint>
#include <cstring>
#include "game/addresses.h"
#include "game/ui/ui_manager.h"
#include "mods/dxwrapper.h"
#include "re/config.h"
#include "re/hook.h"
#include "re/log.h"
#include "re/patch.h"
namespace mods::widescreen {
namespace {
constexpr float kOriginalWidth = 1024.0f;
constexpr float kOriginalHeight = 768.0f;
constexpr double kOriginalOrthoX = 267.0;
constexpr double kOriginalOrthoY = 200.0;
// Read by the patched world view instructions; the initial values reproduce
// the original behaviour until a render size is applied.
float g_viewWidth = kOriginalWidth;
float g_viewHeight = kOriginalHeight;
double g_orthoLeft = -kOriginalOrthoX;
double g_orthoRight = kOriginalOrthoX;
double g_orthoBottom = -kOriginalOrthoY;
double g_orthoTop = kOriginalOrthoY;
bool g_pushesPatched = false;
// Render size once applied (0 = original 1024x768 behaviour).
int g_renderWidth = 0;
int g_renderHeight = 0;
// Frames from the main menu thread and the loading screen are laid out for
// 1024x768 ("classic"); everything else is the widened in-game view.
std::atomic<DWORD> g_menuThread = 0;
thread_local int g_loadingScreenDepth = 0;
// D3DVIEWPORT7 (d3d.h is not in current Windows SDKs).
struct Viewport7 {
DWORD x, y, width, height;
float minZ, maxZ;
};
bool Enabled() {
return re::ConfigInt("widescreen", "Enabled", 1) != 0;
}
// The world view's tile draw list only holds ~1750 entries (enough for
// 1024x768, unchecked). Allocate the view larger and move the list to the new
// space at its end, by rewriting the field displacements of every instruction
// that addresses it.
constexpr uint32_t kTileListCapacity = 16384;
void RelocateTileList() {
using namespace game::addr;
const uint32_t newOffset = kWorldViewSize;
const uint32_t newSize = kWorldViewSize + kTileListCapacity * kTileListEntrySize;
if (!re::PatchPushImm32(kWorldViewAllocSizePush, kWorldViewSize, newSize)) {
re::Log("widescreen: world view allocation not patched, tile list stays at 1750 entries");
return;
}
int patched = 0;
for (uint32_t instruction : kTileListUsers) {
// The displacement is kTileListOffset + field; find it in the instruction.
const auto* code = reinterpret_cast<const uint8_t*>(static_cast<uintptr_t>(instruction));
for (int offset = 1; offset <= 7; ++offset) {
uint32_t value;
memcpy(&value, code + offset, 4);
if (value >= kTileListOffset && value < kTileListOffset + kTileListEntrySize) {
patched += re::PatchInstructionDword(instruction, value, newOffset + (value - kTileListOffset));
break;
}
}
}
re::Log("widescreen: tile draw list moved to +0x%x (%u entries), %d/%d instructions patched", newOffset,
kTileListCapacity, patched, static_cast<int>(std::size(kTileListUsers)));
}
void RedirectWorldView() {
if (!Enabled()) {
return;
}
int patched = 0;
int total = 0;
for (uint32_t instruction : game::addr::kViewWidthUsers) {
patched += re::RedirectOperand(instruction, game::addr::kScreenWidthF, &g_viewWidth);
++total;
}
for (uint32_t instruction : game::addr::kViewHeightUsers) {
patched += re::RedirectOperand(instruction, game::addr::kScreenHeightF, &g_viewHeight);
++total;
}
for (const auto& site : game::addr::kOrthoZoomedUsers) {
patched += re::RedirectOperand(site[0], game::addr::kOrthoTopD, &g_orthoTop);
patched += re::RedirectOperand(site[1], game::addr::kOrthoBottomD, &g_orthoBottom);
patched += re::RedirectOperand(site[2], game::addr::kOrthoRightD, &g_orthoRight);
patched += re::RedirectOperand(site[3], game::addr::kOrthoLeftD, &g_orthoLeft);
total += 4;
}
re::Log("widescreen: %d/%d world view operands redirected", patched, total);
RelocateTileList();
}
RE_STARTUP(WidescreenRedirect, RedirectWorldView);
uint32_t FloatBits(float value) {
return std::bit_cast<uint32_t>(value);
}
// The unzoomed projection is pushed as immediates; rewrite them once.
void PatchOrthoPushes(float right, float top) {
if (g_pushesPatched) {
return;
}
int patched = 0;
for (uint32_t site : game::addr::kOrthoPushSequences) {
patched += re::PatchPushImm32(site + 0, FloatBits(200.0f), FloatBits(top));
patched += re::PatchPushImm32(site + 5, FloatBits(-200.0f), FloatBits(-top));
patched += re::PatchPushImm32(site + 10, FloatBits(267.0f), FloatBits(right));
patched += re::PatchPushImm32(site + 15, FloatBits(-267.0f), FloatBits(-right));
}
g_pushesPatched = true;
re::Log("widescreen: %d/%d projection immediates patched", patched,
static_cast<int>(std::size(game::addr::kOrthoPushSequences)) * 4);
}
} // namespace
void ApplyRenderSize(game::DxDisplayMode& mode, HWND window) {
if (!Enabled()) {
return;
}
MONITORINFO monitor = {sizeof(monitor)};
GetMonitorInfoW(MonitorFromWindow(window, MONITOR_DEFAULTTOPRIMARY), &monitor);
int width = re::ConfigInt("widescreen", "Width", 0);
int height = re::ConfigInt("widescreen", "Height", 0);
if (width <= 0) {
width = monitor.rcMonitor.right - monitor.rcMonitor.left;
}
if (height <= 0) {
height = monitor.rcMonitor.bottom - monitor.rcMonitor.top;
}
// Windows' Direct3D 7 runtime cannot create a device for a render target
// wider or taller than 2048 pixels (CreateDevice fails with
// DDERR_INVALIDOBJECT); anything larger needs a different renderer.
constexpr int kMaxD3D7Surface = 2048;
if (!mods::dxwrapper::IsActive() && (width > kMaxD3D7Surface || height > kMaxD3D7Surface)) {
re::Log("widescreen: %dx%d exceeds the Direct3D 7 limit, clamping to %d", width, height, kMaxD3D7Surface);
width = std::min(width, kMaxD3D7Surface);
height = std::min(height, kMaxD3D7Surface);
}
// The game's own layout needs at least its original size.
if (width < kOriginalWidth || height < kOriginalHeight) {
re::Log("widescreen: %dx%d is smaller than 1024x768, keeping the original size", width, height);
return;
}
mode.width = static_cast<uint16_t>(width);
mode.height = static_cast<uint16_t>(height);
g_viewWidth = static_cast<float>(width);
g_viewHeight = static_cast<float>(height);
const double scaleX = width / kOriginalWidth;
const double scaleY = height / kOriginalHeight;
g_orthoRight = kOriginalOrthoX * scaleX;
g_orthoLeft = -g_orthoRight;
g_orthoTop = kOriginalOrthoY * scaleY;
g_orthoBottom = -g_orthoTop;
PatchOrthoPushes(static_cast<float>(g_orthoRight), static_cast<float>(g_orthoTop));
g_renderWidth = width;
g_renderHeight = height;
re::Log("widescreen: render size %dx%d, ortho x +-%.1f y +-%.1f", width, height, g_orthoRight, g_orthoTop);
}
bool IsClassicFrame() {
if (g_renderWidth == 0) {
return false;
}
return g_loadingScreenDepth > 0 || GetCurrentThreadId() == g_menuThread.load();
}
} // namespace mods::widescreen
namespace game {
using namespace mods::widescreen;
RE_HOOK(addr::UiManager_ThreadLoop, UiManager_ThreadLoop);
RE_HOOK(addr::DxDriver7_LoadingScreen, DxDriver7_LoadingScreen);
RE_HOOK(addr::DxDriver7_BeginScene, DxDriver7_BeginScene);
void __fastcall UiManager_ThreadLoop(void* self, void* edx) {
g_menuThread = GetCurrentThreadId();
UiManager_ThreadLoop_original(self, edx);
g_menuThread = 0;
}
void __fastcall DxDriver7_LoadingScreen(DxDriver7* self, void* edx, uint32_t progress, const char* text) {
++g_loadingScreenDepth;
DxDriver7_LoadingScreen_original(self, edx, progress, text);
--g_loadingScreenDepth;
}
// Menus draw their 3D parts for a 1024x768 screen: give them a 1024x768
// viewport (the borderless mod then presents just that area, scaled), and the
// world the full render size.
int __fastcall DxDriver7_BeginScene(DxDriver7* self, void* edx) {
if (g_renderWidth != 0 && self->sceneDepth == 0 && self->device) {
const bool classic = IsClassicFrame();
Viewport7 viewport = {0, 0, classic ? 1024u : static_cast<DWORD>(g_renderWidth),
classic ? 768u : static_cast<DWORD>(g_renderHeight), 0.0f, 1.0f};
using SetViewportFn = HRESULT(__stdcall*)(void* device, Viewport7* viewport);
auto setViewport = reinterpret_cast<SetViewportFn>((*static_cast<void***>(self->device))[13]);
setViewport(self->device, &viewport);
}
return DxDriver7_BeginScene_original(self, edx);
}
} // namespace game
+18
View File
@@ -0,0 +1,18 @@
#pragma once
#include <windows.h>
#include "game/render/dx_driver7.h"
namespace mods::widescreen {
// Called by the borderless mod before the renderer creates its surfaces:
// sets the render size to the monitor (or the configured size) and resizes
// the world view to match. No-op when disabled.
void ApplyRenderSize(game::DxDisplayMode& mode, HWND window);
// True while the current thread renders a frame laid out for 1024x768 (main
// menu, loading screen); the borderless mod then presents only that area.
bool IsClassicFrame();
} // namespace mods::widescreen