Crusader_Decomp/rebuild/remorse/src/windowed_game_main.cpp
Maddo b3975ca41b Refactor collision handling and item management in the Remorse project
- Introduced new structures for handling sweep impacts and collision results, including SweepItemImpact, SweepCandidateImpact, and SweepCollisionResult.
- Implemented functions to check if a world point or sweep footprint is within a defined fast area.
- Enhanced LiveFixedMapItems to manage contained items and support item allocation with parent-child relationships.
- Updated collision detection logic to handle solid item impacts and collect sweep impacts from live items.
- Added tests for new collision functionalities, including sweep impact resolution and candidate selection.
- Modified existing tests to validate new item management features and ensure proper integration with the collision system.
2026-09-26 19:50:26 +02:00

869 lines
No EOL
40 KiB
C++

#define NOMINMAX
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include "remorse/animation_archive.h"
#include "remorse/collision.h"
#include "remorse/entity_dispatch_entry.h"
#include "remorse/file_system.h"
#include "remorse/fixed_map.h"
#include "remorse/glob_archive.h"
#include "remorse/isometric_controls.h"
#include "remorse/map_renderer.h"
#include "remorse/palette.h"
#include "remorse/runtime.h"
#include "remorse/shape_archive.h"
#include "remorse/type_flags.h"
#include "remorse/usecode_archive.h"
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <cstring>
#include <iomanip>
#include <mutex>
#include <optional>
#include <sstream>
#include <string>
#include <thread>
#include <vector>
namespace {
constexpr wchar_t windowClassName[] = L"CrusaderRemorseGameWindow";
constexpr UINT timerId = 1;
constexpr UINT sceneReadyMessage = WM_APP + 1;
constexpr remorse::u32 backingWidth = 2560;
constexpr remorse::u32 backingHeight = 1440;
constexpr int initialClientWidth = 1280;
constexpr int initialClientHeight = 760;
constexpr double simulationTickSeconds = 0.025;
constexpr remorse::s32 diagnosticItemRange = 48;
struct AppState {
remorse::GameDataRoot root;
remorse::u32 mapIndex = 1;
remorse::ProcessKernel diagnosticKernel;
remorse::u16 diagnosticGroupCounts[32]{};
remorse::StandProcessEntry* diagnosticStand = nullptr;
remorse::KeyboardProcessEntry* diagnosticKeyboard = nullptr;
std::optional<remorse::LiveFixedMapItems> liveItems;
std::optional<remorse::StagedFixedMapItem> diagnosticItem;
remorse::u16 diagnosticItemProcessId = 0;
remorse::u16 diagnosticReleaseEventItem = 0;
std::string diagnosticReleaseClass;
std::size_t diagnosticReleaseBodyBytes = 0;
bool diagnosticItemCompleted = false;
remorse::u32 standWakeCount = 0;
remorse::u32 diagnosticKeyEvents = 0;
std::mutex sceneMutex;
std::optional<remorse::RenderedMapImage> scene;
std::optional<remorse::AnimationClip> standAnimation;
std::optional<remorse::AnimationClip> walkAnimation;
std::optional<remorse::AnimationClip> runAnimation;
std::vector<std::optional<remorse::DecodedShapeFrame>> playerFrames;
remorse::CollisionBody playerCollisionBody{};
std::vector<remorse::CollisionBody> collisionBodies;
std::vector<remorse::ShapeTypeInfo> shapeTypes;
std::optional<remorse::FlexArchive> usecodeArchive;
std::vector<remorse::u8> usecodeOwnerRows;
remorse::Palette256 playerPalette{};
std::vector<std::uint8_t> dibPixels;
std::vector<std::uint8_t> viewPixels;
remorse::WorldPoint spawn{};
remorse::WorldPoint playerWorld{};
remorse::s32 minWorldX = 0;
remorse::s32 minWorldY = 0;
remorse::s32 maxWorldX = 0;
remorse::s32 maxWorldY = 0;
double playerOffsetX = 0.0;
double playerOffsetY = 0.0;
double simulationAccumulator = 0.0;
remorse::u8 playerAnimation = 0;
remorse::u8 playerDirection = 14;
remorse::u8 playerFrame = 0;
std::wstring loadError;
bool sceneLoaded = false;
std::thread sceneThread;
HDC backBufferDc = nullptr;
HBITMAP backBufferBitmap = nullptr;
HBITMAP previousBackBufferBitmap = nullptr;
int backBufferWidth = 0;
int backBufferHeight = 0;
LARGE_INTEGER lastTick{};
LARGE_INTEGER ticksPerSecond{};
};
remorse::u32 standSleepStart(const remorse::StandProcessEntry& stand)
{
const auto& bytes = stand.base.bytes;
return bytes[0x0a] | (static_cast<remorse::u32>(bytes[0x0b]) << 8) |
(static_cast<remorse::u32>(bytes[0x0c]) << 16) |
(static_cast<remorse::u32>(bytes[0x0d]) << 24);
}
std::wstring widen(const std::string& value)
{
if (value.empty()) {
return {};
}
const int length = MultiByteToWideChar(CP_UTF8, 0, value.data(), static_cast<int>(value.size()), nullptr, 0);
if (length <= 0) {
return L"Map loading failed.";
}
std::wstring result(static_cast<std::size_t>(length), L'\0');
MultiByteToWideChar(CP_UTF8, 0, value.data(), static_cast<int>(value.size()), result.data(), length);
return result;
}
void setLoadFailure(AppState& state, const std::wstring& message)
{
std::lock_guard<std::mutex> lock(state.sceneMutex);
state.loadError = message;
state.sceneLoaded = true;
}
void loadSceneAsync(HWND window, AppState& state)
{
state.sceneThread = std::thread([window, &state]() {
try {
const auto fixedPath = remorse::resolveGameDataPath(
state.root, std::filesystem::path("STATIC") / "FIXED.DAT");
const auto typeFlagsPath = remorse::resolveGameDataPath(
state.root, std::filesystem::path("STATIC") / "TYPEFLAG.DAT");
const auto globPath = remorse::resolveGameDataPath(
state.root, std::filesystem::path("STATIC") / "GLOB.FLX");
if (!fixedPath) {
setLoadFailure(state, L"STATIC\\FIXED.DAT was not found under the game data root.");
PostMessageW(window, sceneReadyMessage, 0, 0);
return;
}
if (!typeFlagsPath || !globPath) {
setLoadFailure(state, L"STATIC\\TYPEFLAG.DAT or STATIC\\GLOB.FLX was not found.");
PostMessageW(window, sceneReadyMessage, 0, 0);
return;
}
const auto archive = remorse::loadFixedMapArchive(*fixedPath);
const auto map = archive ? remorse::loadFixedMap(*archive, state.mapIndex) : std::nullopt;
if (!map || map->entries.empty()) {
setLoadFailure(state, L"The selected map could not be loaded or contains no records.");
PostMessageW(window, sceneReadyMessage, 0, 0);
return;
}
const auto stagedItems = remorse::stageFixedMapItems(*map);
const auto shapeTypes = remorse::loadTypeFlags(*typeFlagsPath);
const auto globObjects = remorse::loadGlobObjects(*globPath);
if (!shapeTypes || !globObjects || shapeTypes->size() <= 1) {
setLoadFailure(state, L"Collision shape metadata could not be loaded.");
PostMessageW(window, sceneReadyMessage, 0, 0);
return;
}
std::vector<remorse::StagedContainedFixedMapItem> containedItems;
if (map->index != 0) {
const auto contained = remorse::stageContainedFixedMapItems(*map, *shapeTypes);
if (!contained) {
setLoadFailure(state, L"Contained map items could not be staged.");
PostMessageW(window, sceneReadyMessage, 0, 0);
return;
}
containedItems = std::move(*contained);
}
auto collisionBodies = remorse::collectMapCollisionBodies(*map, *shapeTypes, *globObjects);
const auto usecodePath = remorse::resolveGameDataPath(
state.root, std::filesystem::path("USECODE") / "EUSECODE.FLX");
auto usecodeArchive = usecodePath ? remorse::loadFlexArchive(*usecodePath) : std::nullopt;
const auto usecodeOwnerRows = usecodeArchive
? remorse::loadUsecodeOwnerRows(*usecodeArchive) : std::nullopt;
const auto animationPath = remorse::resolveGameDataPath(
state.root, std::filesystem::path("STATIC") / "ANIM.DAT");
const auto shapesPath = remorse::resolveGameDataPath(
state.root, std::filesystem::path("STATIC") / "SHAPES.FLX");
const auto palettePath = remorse::resolveGameDataPath(
state.root, std::filesystem::path("STATIC") / "GAMEPAL.PAL");
if (!animationPath || !shapesPath || !palettePath) {
setLoadFailure(state, L"The player animation, shape, or palette resource is missing.");
PostMessageW(window, sceneReadyMessage, 0, 0);
return;
}
const auto animationArchive = remorse::loadAnimationArchive(*animationPath);
const auto shapeArchive = remorse::loadShapeArchive(*shapesPath);
const auto palette = remorse::loadPalette256(*palettePath);
const auto standAnimation = animationArchive
? remorse::loadAnimationClip(*animationArchive, 1, 0) : std::nullopt;
const auto walkAnimation = animationArchive
? remorse::loadAnimationClip(*animationArchive, 1, 1) : std::nullopt;
const auto runAnimation = animationArchive
? remorse::loadAnimationClip(*animationArchive, 1, 3) : std::nullopt;
const auto shapeFrames = shapeArchive
? remorse::loadShapeFrames(*shapeArchive, 1) : std::nullopt;
if (!shapeArchive || !palette || !standAnimation || !walkAnimation || !runAnimation || !shapeFrames) {
setLoadFailure(state, L"The player stand, walk, or run animation could not be loaded.");
PostMessageW(window, sceneReadyMessage, 0, 0);
return;
}
std::vector<std::optional<remorse::DecodedShapeFrame>> playerFrames(shapeFrames->size());
const auto cacheAnimationFrames = [&](const remorse::AnimationClip& clip) {
for (remorse::u8 direction = 0; direction < 16; ++direction) {
for (remorse::u32 frameIndex = 0; frameIndex < clip.frameCount; ++frameIndex) {
const auto metadata = remorse::getAnimationFrame(
clip, direction, static_cast<remorse::u8>(frameIndex));
if (!metadata) {
return false;
}
const remorse::u16 shapeFrame = remorse::getAnimationShapeFrame(*metadata);
if (shapeFrame >= playerFrames.size()) {
return false;
}
if (!playerFrames[shapeFrame]) {
auto decoded = remorse::decodeShapeFrame(*shapeArchive, 1, shapeFrame);
if (!decoded) {
return false;
}
playerFrames[shapeFrame] = std::move(*decoded);
}
}
}
return true;
};
if (!cacheAnimationFrames(*standAnimation) || !cacheAnimationFrames(*walkAnimation) ||
!cacheAnimationFrames(*runAnimation)) {
setLoadFailure(state, L"A player animation references a missing shape frame.");
PostMessageW(window, sceneReadyMessage, 0, 0);
return;
}
remorse::s32 minX = map->entries.front().x;
remorse::s32 minY = map->entries.front().y;
remorse::s32 maxX = minX;
remorse::s32 maxY = minY;
for (const remorse::FixedMapEntry& entry : map->entries) {
minX = std::min(minX, static_cast<remorse::s32>(entry.x));
minY = std::min(minY, static_cast<remorse::s32>(entry.y));
maxX = std::max(maxX, static_cast<remorse::s32>(entry.x));
maxY = std::max(maxY, static_cast<remorse::s32>(entry.y));
}
const remorse::WorldPoint spawn{(minX + maxX) / 2, (minY + maxY) / 2, 0};
remorse::MapRenderOptions options;
options.mapIndex = state.mapIndex;
options.maxWidth = backingWidth;
options.maxHeight = backingHeight;
options.viewCenter = spawn;
auto scene = remorse::renderMapPreview(state.root, options);
if (!scene) {
setLoadFailure(state, L"Map graphics or palette data could not be loaded.");
PostMessageW(window, sceneReadyMessage, 0, 0);
return;
}
std::vector<std::uint8_t> dibPixels(scene->pixels.size() * 3);
for (std::size_t index = 0; index < scene->pixels.size(); ++index) {
dibPixels[index * 3] = scene->pixels[index].blue;
dibPixels[index * 3 + 1] = scene->pixels[index].green;
dibPixels[index * 3 + 2] = scene->pixels[index].red;
}
{
std::lock_guard<std::mutex> lock(state.sceneMutex);
state.spawn = spawn;
state.playerWorld = spawn;
state.playerCollisionBody = remorse::makeCollisionBody(spawn, (*shapeTypes)[1]);
state.collisionBodies = std::move(collisionBodies);
state.shapeTypes = *shapeTypes;
state.usecodeArchive = std::move(usecodeArchive);
if (usecodeOwnerRows) {
state.usecodeOwnerRows = *usecodeOwnerRows;
}
state.minWorldX = minX;
state.minWorldY = minY;
state.maxWorldX = maxX;
state.maxWorldY = maxY;
state.scene = std::move(scene);
state.dibPixels = std::move(dibPixels);
state.standAnimation = *standAnimation;
state.walkAnimation = *walkAnimation;
state.runAnimation = *runAnimation;
state.playerFrames = std::move(playerFrames);
state.playerPalette = *palette;
if (stagedItems) {
state.liveItems.emplace(std::move(*stagedItems), std::move(containedItems));
}
state.sceneLoaded = true;
}
} catch (const std::exception& error) {
setLoadFailure(state, widen(error.what()));
} catch (...) {
setLoadFailure(state, L"An unexpected error occurred while building the map scene.");
}
PostMessageW(window, sceneReadyMessage, 0, 0);
});
}
void drawCenteredText(HDC device, const RECT& bounds, const wchar_t* text, COLORREF color, HFONT font)
{
const int saved = SaveDC(device);
SetBkMode(device, TRANSPARENT);
SetTextColor(device, color);
SelectObject(device, font);
DrawTextW(device, text, -1, const_cast<RECT*>(&bounds), DT_CENTER | DT_VCENTER | DT_SINGLELINE);
RestoreDC(device, saved);
}
bool isKeyDown(int key)
{
return (GetAsyncKeyState(key) & 0x8000) != 0;
}
std::optional<remorse::u8> readMovementDirection()
{
if (isKeyDown(VK_HOME) || isKeyDown(VK_NUMPAD7) || isKeyDown('Q')) return remorse::controllerDirectionFromScan(0x47);
if (isKeyDown(VK_PRIOR) || isKeyDown(VK_NUMPAD9) || isKeyDown('E')) return remorse::controllerDirectionFromScan(0x49);
if (isKeyDown(VK_END) || isKeyDown(VK_NUMPAD1) || isKeyDown('Z')) return remorse::controllerDirectionFromScan(0x4f);
if (isKeyDown(VK_NEXT) || isKeyDown(VK_NUMPAD3) || isKeyDown('C')) return remorse::controllerDirectionFromScan(0x51);
const bool up = isKeyDown(VK_UP) || isKeyDown('W') || isKeyDown(VK_NUMPAD8);
const bool right = isKeyDown(VK_RIGHT) || isKeyDown('D') || isKeyDown(VK_NUMPAD6);
const bool down = isKeyDown(VK_DOWN) || isKeyDown('S') || isKeyDown(VK_NUMPAD2);
const bool left = isKeyDown(VK_LEFT) || isKeyDown('A') || isKeyDown(VK_NUMPAD4);
if (up && left) return remorse::controllerDirectionFromScan(0x47);
if (up && right) return remorse::controllerDirectionFromScan(0x49);
if (down && left) return remorse::controllerDirectionFromScan(0x4f);
if (down && right) return remorse::controllerDirectionFromScan(0x51);
if (up) return remorse::controllerDirectionFromScan(0x48);
if (right) return remorse::controllerDirectionFromScan(0x4d);
if (down) return remorse::controllerDirectionFromScan(0x50);
if (left) return remorse::controllerDirectionFromScan(0x4b);
return std::nullopt;
}
bool isWalkRequested()
{
remorse::u16 modifiers = (GetKeyState(VK_CAPITAL) & 1) != 0 ? 0x40 : 0;
if (isKeyDown(VK_LSHIFT)) modifiers |= 0x01;
if (isKeyDown(VK_RSHIFT)) modifiers |= 0x02;
return remorse::controllerWalkRequested(modifiers);
}
void compositePlayer(HDC device, AppState& state, int viewWidth, int viewHeight,
int sourceLeft, int sourceTop, std::size_t viewStride)
{
const remorse::AnimationClip* clip = nullptr;
if (state.playerAnimation == 1 && state.walkAnimation) {
clip = &*state.walkAnimation;
} else if (state.playerAnimation == 3 && state.runAnimation) {
clip = &*state.runAnimation;
} else if (state.standAnimation) {
clip = &*state.standAnimation;
}
if (!clip || state.playerFrames.empty()) {
return;
}
const remorse::u8 frameIndex = state.playerAnimation == 0 ? 0 : state.playerFrame;
const auto metadata = remorse::getAnimationFrame(*clip, state.playerDirection, frameIndex);
if (!metadata) {
return;
}
const remorse::u16 shapeFrame = remorse::getAnimationShapeFrame(*metadata);
if (shapeFrame >= state.playerFrames.size() || !state.playerFrames[shapeFrame]) {
return;
}
const remorse::DecodedShapeFrame& sprite = *state.playerFrames[shapeFrame];
const int actorX = static_cast<int>(state.scene->width / 2) +
static_cast<int>(std::lround(state.playerOffsetX)) - sourceLeft;
const int actorY = static_cast<int>(state.scene->height / 2) +
static_cast<int>(std::lround(state.playerOffsetY)) - sourceTop;
const int spriteLeft = actorX + sprite.frame.xOffset;
const int spriteTop = actorY + sprite.frame.yOffset;
const bool flipped = remorse::isAnimationFrameFlipped(*metadata);
for (remorse::u32 y = 0; y < sprite.frame.height; ++y) {
const int destinationY = spriteTop + static_cast<int>(y);
if (destinationY < 0 || destinationY >= viewHeight) {
continue;
}
for (remorse::u32 x = 0; x < sprite.frame.width; ++x) {
const int destinationX = spriteLeft + static_cast<int>(x);
if (destinationX < 0 || destinationX >= viewWidth) {
continue;
}
const remorse::u32 sourceX = flipped ? sprite.frame.width - 1 - x : x;
const remorse::s16 paletteIndex = sprite.pixels[
static_cast<std::size_t>(y) * sprite.frame.width + sourceX];
if (paletteIndex < 0) {
continue;
}
const remorse::RgbColor& color = state.playerPalette.colors[
static_cast<remorse::u8>(paletteIndex)];
const std::size_t pixelOffset = static_cast<std::size_t>(destinationY) * viewStride +
static_cast<std::size_t>(destinationX) * 3;
state.viewPixels[pixelOffset] = static_cast<std::uint8_t>(color.blue * 255 / 63);
state.viewPixels[pixelOffset + 1] = static_cast<std::uint8_t>(color.green * 255 / 63);
state.viewPixels[pixelOffset + 2] = static_cast<std::uint8_t>(color.red * 255 / 63);
}
}
BITMAPINFO bitmap{};
bitmap.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bitmap.bmiHeader.biWidth = viewWidth;
bitmap.bmiHeader.biHeight = -viewHeight;
bitmap.bmiHeader.biPlanes = 1;
bitmap.bmiHeader.biBitCount = 24;
bitmap.bmiHeader.biCompression = BI_RGB;
StretchDIBits(device, 0, 0, viewWidth, viewHeight, 0, 0, viewWidth, viewHeight,
state.viewPixels.data(), &bitmap, DIB_RGB_COLORS, SRCCOPY);
}
void drawLoadingScreen(HDC device, const RECT& client, const AppState& state)
{
HBRUSH background = CreateSolidBrush(RGB(13, 23, 28));
FillRect(device, &client, background);
DeleteObject(background);
RECT title = client;
title.bottom = title.top + 70;
HFONT titleFont = CreateFontW(-30, 0, 0, 0, FW_BOLD, FALSE, FALSE, FALSE,
DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY,
DEFAULT_PITCH | FF_DONTCARE, L"Bahnschrift");
drawCenteredText(device, title, L"CRUSADER / NO REMORSE", RGB(228, 220, 191), titleFont);
DeleteObject(titleFont);
RECT status = client;
status.top = title.bottom;
HFONT bodyFont = CreateFontW(-18, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE,
DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY,
DEFAULT_PITCH | FF_DONTCARE, L"Consolas");
const std::wstring message = state.loadError.empty()
? L"Building the retail map scene..."
: state.loadError;
drawCenteredText(device, status, message.c_str(), state.loadError.empty()
? RGB(74, 207, 184) : RGB(245, 157, 119), bodyFont);
DeleteObject(bodyFont);
}
void paintWindow(HWND window, AppState& state)
{
PAINTSTRUCT paint{};
HDC paintDc = BeginPaint(window, &paint);
RECT client{};
GetClientRect(window, &client);
const int clientWidth = static_cast<int>(std::max(1L, client.right - client.left));
const int clientHeight = static_cast<int>(std::max(1L, client.bottom - client.top));
if (state.backBufferWidth != clientWidth || state.backBufferHeight != clientHeight) {
if (state.backBufferDc) {
SelectObject(state.backBufferDc, state.previousBackBufferBitmap);
DeleteObject(state.backBufferBitmap);
DeleteDC(state.backBufferDc);
state.backBufferDc = nullptr;
state.backBufferBitmap = nullptr;
state.previousBackBufferBitmap = nullptr;
}
state.backBufferDc = CreateCompatibleDC(paintDc);
if (state.backBufferDc) {
state.backBufferBitmap = CreateCompatibleBitmap(paintDc, clientWidth, clientHeight);
if (state.backBufferBitmap) {
state.previousBackBufferBitmap = static_cast<HBITMAP>(
SelectObject(state.backBufferDc, state.backBufferBitmap));
state.backBufferWidth = clientWidth;
state.backBufferHeight = clientHeight;
} else {
DeleteDC(state.backBufferDc);
state.backBufferDc = nullptr;
}
}
}
HDC device = state.backBufferDc ? state.backBufferDc : paintDc;
const auto finishPaint = [&]() {
if (device != paintDc) {
BitBlt(paintDc, 0, 0, clientWidth, clientHeight, device, 0, 0, SRCCOPY);
}
EndPaint(window, &paint);
};
std::lock_guard<std::mutex> lock(state.sceneMutex);
if (!state.sceneLoaded || !state.scene) {
drawLoadingScreen(device, client, state);
finishPaint();
return;
}
if (!state.loadError.empty()) {
drawLoadingScreen(device, client, state);
finishPaint();
return;
}
HBRUSH clearBrush = CreateSolidBrush(RGB(10, 17, 22));
FillRect(device, &client, clearBrush);
DeleteObject(clearBrush);
const int viewWidth = std::min(clientWidth, static_cast<int>(state.scene->width));
const int viewHeight = std::min(clientHeight, static_cast<int>(state.scene->height));
const int centeredLeft = static_cast<int>(state.scene->width / 2) +
static_cast<int>(std::lround(state.playerOffsetX)) - viewWidth / 2;
const int centeredTop = static_cast<int>(state.scene->height / 2) +
static_cast<int>(std::lround(state.playerOffsetY)) - viewHeight / 2;
const int sourceLeft = std::clamp(centeredLeft, 0, static_cast<int>(state.scene->width) - viewWidth);
const int sourceTop = std::clamp(centeredTop, 0, static_cast<int>(state.scene->height) - viewHeight);
const std::size_t viewStride = (static_cast<std::size_t>(viewWidth) * 3 + 3) & ~std::size_t(3);
state.viewPixels.resize(viewStride * static_cast<std::size_t>(viewHeight));
const std::size_t sceneStride = static_cast<std::size_t>(state.scene->width) * 3;
for (int row = 0; row < viewHeight; ++row) {
const std::size_t sceneOffset = static_cast<std::size_t>(sourceTop + row) * sceneStride +
static_cast<std::size_t>(sourceLeft) * 3;
const std::size_t viewOffset = static_cast<std::size_t>(row) * viewStride;
std::memcpy(state.viewPixels.data() + viewOffset, state.dibPixels.data() + sceneOffset,
static_cast<std::size_t>(viewWidth) * 3);
}
compositePlayer(device, state, viewWidth, viewHeight, sourceLeft, sourceTop, viewStride);
RECT hud{0, 0, viewWidth, 80};
HBRUSH hudBrush = CreateSolidBrush(RGB(14, 24, 29));
FillRect(device, &hud, hudBrush);
DeleteObject(hudBrush);
HPEN hudLine = CreatePen(PS_SOLID, 1, RGB(43, 204, 178));
HGDIOBJ oldPen = SelectObject(device, hudLine);
MoveToEx(device, 0, hud.bottom - 1, nullptr);
LineTo(device, viewWidth, hud.bottom - 1);
SelectObject(device, oldPen);
DeleteObject(hudLine);
std::wostringstream label;
label << L"MAP " << std::setw(3) << std::setfill(L'0') << state.mapIndex
<< L" X " << state.playerWorld.x
<< L" Y " << state.playerWorld.y
<< L" Z " << static_cast<int>(state.playerWorld.z)
<< L" DIR " << std::setw(2) << static_cast<int>(state.playerDirection)
<< L" " << (state.playerAnimation == 3 ? L"RUN" : state.playerAnimation == 1 ? L"WALK" : L"IDLE")
<< L" WASD / KEYPAD SHIFT RUN";
HFONT hudFont = CreateFontW(-16, 0, 0, 0, FW_MEDIUM, FALSE, FALSE, FALSE,
DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY,
DEFAULT_PITCH | FF_DONTCARE, L"Consolas");
RECT labelBounds{20, 0, viewWidth - 12, 30};
const int saved = SaveDC(device);
SetBkMode(device, TRANSPARENT);
SetTextColor(device, RGB(224, 229, 214));
SelectObject(device, hudFont);
DrawTextW(device, label.str().c_str(), -1, &labelBounds, DT_LEFT | DT_VCENTER | DT_SINGLELINE);
const remorse::EntityDispatchEntryBase& stand = state.diagnosticStand->base;
const remorse::u32 sleepStart = standSleepStart(*state.diagnosticStand);
const remorse::u32 sleepLength = stand.bytes[0x0e] | (static_cast<remorse::u32>(stand.bytes[0x0f]) << 8);
std::wostringstream diagnostics;
diagnostics << L"HOST 40Hz | KERNEL TICK " << state.diagnosticKernel.systemTimerTick()
<< L" | STAND #" << static_cast<int>(stand.bytes[0x02])
<< L" " << ((stand.bytes[0x19] & 0x10) != 0 ? L"SLEEP " : L"READY ")
<< ((stand.bytes[0x19] & 0x10) != 0
? static_cast<remorse::u32>(sleepStart + sleepLength - state.diagnosticKernel.systemTimerTick() + 1)
: 0)
<< L" | WAKEUPS " << state.standWakeCount
<< L" | KEY EVENTS " << state.diagnosticKeyEvents;
RECT diagnosticsBounds{20, 30, viewWidth - 12, 54};
SetTextColor(device, RGB(74, 207, 184));
DrawTextW(device, diagnostics.str().c_str(), -1, &diagnosticsBounds, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS);
const auto nearbyItem = state.liveItems ? state.liveItems->nearestItem(
state.playerWorld.x, state.playerWorld.y, diagnosticItemRange) : std::nullopt;
if (state.diagnosticItem || nearbyItem) {
const auto& displayItem = state.diagnosticItem ? state.diagnosticItem : nearbyItem;
std::wostringstream itemStatus;
itemStatus << L"MAP ITEM " << displayItem->itemNumber
<< L" | SHAPE " << displayItem->data.shape
<< L" | RELEASE REQUEST " << state.diagnosticReleaseEventItem
<< L" | " << (state.diagnosticReleaseBodyBytes != 0
? widen(state.diagnosticReleaseClass) + L" SCRIPT " + std::to_wstring(state.diagnosticReleaseBodyBytes) + L" BYTES (NOT RUN)"
: L"NO RELEASE SCRIPT")
<< L" | PROCESS " << (state.diagnosticItemCompleted ? L"DONE" :
state.diagnosticItemProcessId != 0 ? L"QUEUED" :
displayItem->itemNumber > remorse::ProcessKernel::maxTrackedItemNumber ? L"ITEM OUT OF RANGE" :
!remorse::itemGrabCanCreateProcess(*displayItem) ? L"ITEM FLAG BLOCKS" : L"F: TEST RELEASE");
RECT itemBounds{20, 54, viewWidth - 12, hud.bottom - 1};
DrawTextW(device, itemStatus.str().c_str(), -1, &itemBounds, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS);
}
RestoreDC(device, saved);
DeleteObject(hudFont);
finishPaint();
}
void updatePlayer(HWND window, AppState& state)
{
LARGE_INTEGER now{};
QueryPerformanceCounter(&now);
const double elapsed = std::clamp(
static_cast<double>(now.QuadPart - state.lastTick.QuadPart) /
static_cast<double>(state.ticksPerSecond.QuadPart),
0.0, 0.25);
state.lastTick = now;
if (GetAsyncKeyState(VK_ESCAPE) & 0x8000) {
DestroyWindow(window);
return;
}
if (GetForegroundWindow() != window) {
return;
}
std::lock_guard<std::mutex> lock(state.sceneMutex);
if (!state.sceneLoaded || !state.scene || !state.loadError.empty()) {
return;
}
state.simulationAccumulator += elapsed;
const auto direction = readMovementDirection();
bool changed = false;
while (state.simulationAccumulator >= simulationTickSeconds) {
state.simulationAccumulator -= simulationTickSeconds;
state.diagnosticKernel.deliverSystemTimerEvent();
const bool wasSleeping = (state.diagnosticStand->base.bytes[0x19] & 0x10) != 0;
const remorse::u32 previousSleepStart = standSleepStart(*state.diagnosticStand);
state.diagnosticKernel.runTimedSchedulerPass(state.diagnosticKernel.activeGroup(), [](remorse::EntityDispatchEntryBase& entry, void* context) {
auto& app = *static_cast<AppState*>(context);
if (&entry == &app.diagnosticStand->base) {
remorse::StandProcess::run(entry,
[](const remorse::EntityDispatchEntryBase&, void*) { return false; },
nullptr, app.diagnosticKernel.systemTimerTick());
} else if (entry.bytes[0] == 0x2f && entry.bytes[1] == 0x10) {
remorse::ItemProcess::run(entry, app.diagnosticKernel, app.diagnosticGroupCounts,
[](remorse::u16 itemNumber, remorse::u32 eventMask, remorse::u16 eventId, void* releaseContext) {
auto& app = *static_cast<AppState*>(releaseContext);
app.diagnosticReleaseEventItem = itemNumber;
if (app.diagnosticItem && app.usecodeArchive &&
app.diagnosticItem->data.shape < app.shapeTypes.size()) {
const auto& item = *app.diagnosticItem;
const remorse::UsecodeItemIdentity identity{item.itemNumber, item.data.shape,
item.data.flags, item.data.quality, app.shapeTypes[item.data.shape].family, false};
const remorse::UsecodeClassBases bases{0, 0x800, 0x900};
const auto eligible = remorse::selectEligibleUsecodeEvent(*app.usecodeArchive,
app.usecodeOwnerRows, identity, bases, eventMask, eventId);
if (eligible) {
app.diagnosticReleaseClass = eligible->className;
app.diagnosticReleaseBodyBytes = eligible->body.bytes.size();
}
}
}, &app);
}
}, &state);
state.diagnosticKernel.refreshActiveGroup(state.diagnosticGroupCounts);
if (state.diagnosticItemProcessId != 0 &&
state.diagnosticKernel.processAt(state.diagnosticItemProcessId) == nullptr) {
state.diagnosticItemCompleted = true;
}
if (wasSleeping && standSleepStart(*state.diagnosticStand) != previousSleepStart) {
++state.standWakeCount;
}
changed = true;
if (!direction) {
changed = changed || state.playerAnimation != 0 || state.playerFrame != 0;
state.playerAnimation = 0;
state.playerFrame = 0;
continue;
}
const remorse::u8 requestedAnimation = isWalkRequested() ? 1 : 3;
const remorse::AnimationClip& clip = requestedAnimation == 1
? *state.walkAnimation : *state.runAnimation;
if (state.playerAnimation != requestedAnimation) {
state.playerAnimation = requestedAnimation;
state.playerFrame = 0;
} else {
state.playerFrame = static_cast<remorse::u8>(
(state.playerFrame + 1) % clip.frameCount);
}
state.playerDirection = *direction;
const auto metadata = remorse::getAnimationFrame(clip, state.playerDirection, state.playerFrame);
if (metadata) {
const auto step = remorse::hostMovementStep(
*metadata, state.playerDirection, (clip.header[2] & 0x10) != 0);
if (step) {
const remorse::WorldPoint destination{
state.playerWorld.x + step->x,
state.playerWorld.y + step->y,
state.playerWorld.z + step->z};
const remorse::ScreenPoint destinationScreen = remorse::projectToScreen(destination);
const remorse::ScreenPoint spawnScreen = remorse::projectToScreen(state.spawn);
const double nextOffsetX = destinationScreen.x - spawnScreen.x;
const double nextOffsetY = destinationScreen.y - spawnScreen.y;
const bool withinMapBounds = destination.x >= state.minWorldX &&
destination.x <= state.maxWorldX && destination.y >= state.minWorldY &&
destination.y <= state.maxWorldY;
const bool withinSceneBounds = std::abs(nextOffsetX) <= backingWidth / 2 - 16 &&
std::abs(nextOffsetY) <= backingHeight / 2 - 16;
if (withinMapBounds && withinSceneBounds && remorse::canMoveCollisionBody(
state.playerCollisionBody, destination, state.collisionBodies)) {
state.playerWorld = destination;
state.playerCollisionBody.location = destination;
state.playerOffsetX = nextOffsetX;
state.playerOffsetY = nextOffsetY;
}
}
}
changed = true;
}
if (changed) {
InvalidateRect(window, nullptr, FALSE);
}
}
LRESULT CALLBACK windowProcedure(HWND window, UINT message, WPARAM wParam, LPARAM lParam)
{
AppState* state = reinterpret_cast<AppState*>(GetWindowLongPtrW(window, GWLP_USERDATA));
if (message == WM_NCCREATE) {
const auto* create = reinterpret_cast<const CREATESTRUCTW*>(lParam);
state = static_cast<AppState*>(create->lpCreateParams);
SetWindowLongPtrW(window, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(state));
}
if (!state) {
return DefWindowProcW(window, message, wParam, lParam);
}
switch (message) {
case WM_CREATE:
QueryPerformanceFrequency(&state->ticksPerSecond);
QueryPerformanceCounter(&state->lastTick);
SetTimer(window, timerId, 16, nullptr);
loadSceneAsync(window, *state);
return 0;
case WM_TIMER:
if (wParam == timerId) {
updatePlayer(window, *state);
}
return 0;
case WM_KEYDOWN:
if (wParam == 'F') {
std::lock_guard<std::mutex> lock(state->sceneMutex);
if (state->sceneLoaded && state->scene && !state->diagnosticItemCompleted &&
state->diagnosticItemProcessId == 0) {
state->diagnosticItem = state->liveItems ? state->liveItems->nearestItem(
state->playerWorld.x, state->playerWorld.y, diagnosticItemRange) : std::nullopt;
}
if (state->diagnosticItem && state->diagnosticItemProcessId == 0 &&
state->diagnosticItem->itemNumber <= remorse::ProcessKernel::maxTrackedItemNumber &&
remorse::itemGrabCanCreateProcess(*state->diagnosticItem)) {
auto* itemProcess = state->diagnosticKernel.createItemProcess(
state->diagnosticKernel.activeGroup(), state->diagnosticItem->itemNumber,
state->diagnosticGroupCounts);
state->diagnosticItemProcessId = static_cast<remorse::u16>(
itemProcess->bytes[2] | (static_cast<remorse::u16>(itemProcess->bytes[3]) << 8));
InvalidateRect(window, nullptr, FALSE);
}
}
return 0;
case WM_CHAR:
if (wParam > 0 && wParam <= 0xff) {
remorse::KeyEvent lastEvent{};
lastEvent.character = static_cast<remorse::u8>(wParam);
lastEvent.scanCode = static_cast<remorse::u8>((lParam >> 16) & 0xff);
lastEvent.field8 = 1;
remorse::KeyEvent event = lastEvent;
if (remorse::KeyboardProcess::handleKeyEvent(*state->diagnosticKeyboard, 0x10, 0, event, lastEvent)) {
++state->diagnosticKeyEvents;
InvalidateRect(window, nullptr, FALSE);
}
}
return 0;
case WM_SIZE:
InvalidateRect(window, nullptr, FALSE);
return 0;
case WM_ERASEBKGND:
return 1;
case WM_PAINT:
paintWindow(window, *state);
return 0;
case sceneReadyMessage: {
InvalidateRect(window, nullptr, FALSE);
return 0;
}
case WM_DESTROY:
KillTimer(window, timerId);
if (state->sceneThread.joinable()) {
state->sceneThread.join();
}
if (state->backBufferDc) {
SelectObject(state->backBufferDc, state->previousBackBufferBitmap);
DeleteObject(state->backBufferBitmap);
DeleteDC(state->backBufferDc);
}
PostQuitMessage(0);
return 0;
default:
return DefWindowProcW(window, message, wParam, lParam);
}
}
} // namespace
int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR commandLine, int showCommand)
{
remorse::installCrashDiagnostics();
remorse::u32 mapIndex = 1;
if (commandLine && *commandLine) {
wchar_t* end = nullptr;
const unsigned long parsed = std::wcstoul(commandLine, &end, 0);
if (end != commandLine && parsed <= 255) {
mapIndex = static_cast<remorse::u32>(parsed);
}
}
wchar_t executablePath[MAX_PATH]{};
GetModuleFileNameW(nullptr, executablePath, MAX_PATH);
auto root = remorse::findGameDataRoot(std::filesystem::path(executablePath).parent_path());
if (!root) {
root = remorse::findGameDataRoot(std::filesystem::current_path());
}
if (!root) {
MessageBoxW(nullptr,
L"Could not locate CRUSADER.EXE, STATIC, and USECODE. Place this application below the game data folder or launch it from that folder.",
L"Crusader Rebuild", MB_OK | MB_ICONERROR);
return 2;
}
AppState state;
state.root = *root;
state.mapIndex = mapIndex;
for (int index = 0; index < 3; ++index) {
state.diagnosticKernel.createProcess(1, state.diagnosticGroupCounts);
}
state.diagnosticKernel.createSystemTimerProcess(1, state.diagnosticGroupCounts);
state.diagnosticKeyboard = state.diagnosticKernel.createKeyboardProcess(1, state.diagnosticGroupCounts);
state.diagnosticKernel.createKeyDaemonProcess(1, state.diagnosticGroupCounts);
state.diagnosticStand = state.diagnosticKernel.createStandProcess(1, 1, state.diagnosticGroupCounts);
WNDCLASSEXW windowClass{};
windowClass.cbSize = sizeof(windowClass);
windowClass.style = CS_HREDRAW | CS_VREDRAW;
windowClass.lpfnWndProc = windowProcedure;
windowClass.hInstance = instance;
windowClass.hCursor = LoadCursorW(nullptr, MAKEINTRESOURCEW(32512));
windowClass.hIcon = LoadIconW(nullptr, MAKEINTRESOURCEW(32512));
windowClass.hbrBackground = reinterpret_cast<HBRUSH>(COLOR_WINDOW + 1);
windowClass.lpszClassName = windowClassName;
if (!RegisterClassExW(&windowClass)) {
MessageBoxW(nullptr, L"Could not register the game window.", L"Crusader Rebuild", MB_OK | MB_ICONERROR);
return 3;
}
RECT bounds{0, 0, initialClientWidth, initialClientHeight};
AdjustWindowRect(&bounds, WS_OVERLAPPEDWINDOW, FALSE);
HWND window = CreateWindowExW(0, windowClassName, L"Crusader: No Remorse | Rebuild", WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, bounds.right - bounds.left, bounds.bottom - bounds.top,
nullptr, nullptr, instance, &state);
if (!window) {
MessageBoxW(nullptr, L"Could not create the game window.", L"Crusader Rebuild", MB_OK | MB_ICONERROR);
return 4;
}
ShowWindow(window, showCommand);
UpdateWindow(window);
MSG message{};
while (GetMessageW(&message, nullptr, 0, 0) > 0) {
TranslateMessage(&message);
DispatchMessageW(&message);
}
return static_cast<int>(message.wParam);
}