#define NOMINMAX #define WIN32_LEAN_AND_MEAN #include #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/game_start.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 "remorse/usecode_vm.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include 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 remorse::u32 playerPatchWidth = 512; constexpr remorse::u32 playerPatchHeight = 384; constexpr int initialClientWidth = 1280; constexpr int initialClientHeight = 760; constexpr double simulationTickSeconds = 0.025; constexpr remorse::s32 diagnosticItemRange = 48; struct WarpStart { remorse::u16 x = 0; remorse::u16 y = 0; remorse::u8 z = 0; }; struct AppState { remorse::GameDataRoot root; remorse::u32 mapIndex = 1; bool diagnostics = false; std::optional warpStart; remorse::ProcessKernel diagnosticKernel; remorse::u16 diagnosticGroupCounts[32]{}; remorse::UsecodeTaskRegistry usecodeTasks; bool useRequested = false; bool usecodeWorldMutationPending = false; std::uint64_t heldKeycards = 0; remorse::StandProcessEntry* diagnosticStand = nullptr; remorse::KeyboardProcessEntry* diagnosticKeyboard = nullptr; remorse::ControllerMovementState controllerMovement; std::optional lastControllerCommand; std::optional activeOneShotMovement; remorse::u16 animationProcessId = 0; std::optional liveItems; std::optional diagnosticItem; remorse::u16 diagnosticItemProcessId = 0; remorse::u16 diagnosticReleaseEventItem = 0; remorse::u16 diagnosticReleaseProcessId = 0; std::string diagnosticReleaseClass; std::size_t diagnosticReleaseBodyBytes = 0; bool diagnosticItemCompleted = false; remorse::u32 standWakeCount = 0; remorse::u32 diagnosticKeyEvents = 0; std::mutex kernelMutex; std::mutex sceneMutex; std::condition_variable renderWake; bool renderRequested = false; bool renderFullRequested = false; bool renderFullInFlight = false; bool renderStop = false; std::optional scene; std::optional playerPatch; std::optional renderer; std::array, 0x40> playerAnimations; std::vector> playerFrames; remorse::CollisionBody playerCollisionBody{}; std::vector collisionBodies; std::vector shapeTypes; std::optional usecodeArchive; std::vector usecodeOwnerRows; remorse::Palette256 playerPalette{}; std::vector dibPixels; std::vector viewPixels; remorse::WorldPoint spawn{}; remorse::FastAreaRange fastArea{}; 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; bool playerKneeling = false; bool playerHasActiveWeapon = false; std::wstring loadError; bool loadErrorShown = false; bool sceneLoaded = false; std::thread sceneThread; std::thread renderThread; 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(bytes[0x0b]) << 8) | (static_cast(bytes[0x0c]) << 16) | (static_cast(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(value.size()), nullptr, 0); if (length <= 0) { return L"Map loading failed."; } std::wstring result(static_cast(length), L'\0'); MultiByteToWideChar(CP_UTF8, 0, value.data(), static_cast(value.size()), result.data(), length); return result; } void setLoadFailure(AppState& state, const std::wstring& message) { std::lock_guard lock(state.sceneMutex); state.loadError = message; state.sceneLoaded = true; } void reportLoadFailure(HWND window, AppState& state, const std::wstring& message) { setLoadFailure(state, message); if (!PostMessageW(window, sceneReadyMessage, 0, 0)) { InvalidateRect(window, nullptr, FALSE); } } void displayLoadFailure(HWND window, AppState& state) { std::wstring message; { std::lock_guard lock(state.sceneMutex); if (state.loadError.empty() || state.loadErrorShown) { return; } state.loadErrorShown = true; message = state.loadError; } InvalidateRect(window, nullptr, FALSE); MessageBoxW(window, message.c_str(), L"Crusader map loading failed", MB_OK | MB_ICONERROR); } remorse::WorldPoint avatarWorld(const AppState& state) { const auto* avatar = state.liveItems ? state.liveItems->findItem(1) : nullptr; return avatar ? remorse::WorldPoint{avatar->data.x * 2, avatar->data.y * 2, avatar->data.z} : state.spawn; } remorse::MapRenderOptions playerPatchOptions(remorse::u32 mapIndex, const remorse::WorldPoint& center) { remorse::MapRenderOptions options; options.mapIndex = mapIndex; options.maxWidth = playerPatchWidth; options.maxHeight = playerPatchHeight; options.includeRoofs = true; options.viewCenter = center; const remorse::s32 radius = static_cast( playerPatchWidth + playerPatchHeight * 2 + 1280); options.worldRect = remorse::WorldRect{ center.x - radius, center.y - radius, center.x + radius, center.y + radius}; return options; } remorse::MapRenderOptions fullSceneOptions(remorse::u32 mapIndex, const remorse::WorldPoint& center) { remorse::MapRenderOptions options; options.mapIndex = mapIndex; options.maxWidth = backingWidth; options.maxHeight = backingHeight; options.includeRoofs = true; options.viewCenter = center; return options; } std::optional playerRenderSprite(const AppState& state) { if (state.playerAnimation >= state.playerAnimations.size() || !state.playerAnimations[state.playerAnimation]) { return std::nullopt; } const remorse::AnimationClip* clip = &*state.playerAnimations[state.playerAnimation]; const remorse::u8 frameIndex = state.playerAnimation == 0 ? 0 : state.playerFrame; const auto metadata = remorse::getAnimationFrame(*clip, state.playerDirection, frameIndex); if (!metadata) { return std::nullopt; } const remorse::u16 shapeFrame = remorse::getAnimationShapeFrame(*metadata); if (shapeFrame >= state.playerFrames.size() || !state.playerFrames[shapeFrame]) { return std::nullopt; } return remorse::MapRenderSprite{avatarWorld(state), 1, static_cast(shapeFrame), remorse::isAnimationFrameFlipped(*metadata), &*state.playerFrames[shapeFrame], &state.playerPalette}; } bool hatchGlobsInFastArea(remorse::LiveFixedMapItems& items, const remorse::MapSceneRenderer& renderer, const remorse::FastAreaRange& range); std::optional queueUsecodeTask(AppState& state, remorse::u16 classId, remorse::u16 eventSlot, remorse::u16 sourceItem, std::vector code, remorse::u8 itemArgumentSize = 2, std::vector extraArguments = {}) { auto* process = state.diagnosticKernel.createUsecodeProcess( state.diagnosticKernel.activeGroup(), state.diagnosticGroupCounts); const remorse::u16 processId = static_cast(process->base.bytes[2] | (static_cast(process->base.bytes[3]) << 8)); const auto terminateProcess = [&state, processId]() { state.diagnosticKernel.terminateProcess(processId, state.diagnosticGroupCounts); state.diagnosticKernel.clearTerminatedProcesses(); }; auto eventContext = remorse::createUsecodeEventContext(state.usecodeTasks.runtimeMemory(), state.usecodeOwnerRows, classId, eventSlot, sourceItem, code, itemArgumentSize); if (!eventContext) { terminateProcess(); return std::nullopt; } const std::vector processIdBytes{ static_cast(processId), static_cast(processId >> 8)}; if (!state.usecodeTasks.runtimeMemory().write(eventContext->processIdOutput, processIdBytes)) { remorse::destroyUsecodeEventContext(state.usecodeTasks.runtimeMemory(), *eventContext); terminateProcess(); return std::nullopt; } auto task = remorse::UsecodeProcessTask::create(processId, classId, eventSlot, sourceItem, std::move(code), itemArgumentSize, std::move(extraArguments)); if (!task || !state.usecodeTasks.addWithContext(std::move(*task), std::move(*eventContext))) { terminateProcess(); return std::nullopt; } const auto* registeredContext = state.usecodeTasks.context(processId); if (registeredContext == nullptr) { state.usecodeTasks.remove(processId); terminateProcess(); return std::nullopt; } std::copy(registeredContext->context.processBytes.begin() + remorse::usecodeContextSlotIndexOffset, registeredContext->context.processBytes.end(), reinterpret_cast(process) + remorse::usecodeContextSlotIndexOffset); return processId; } bool startNearbyUsecode(AppState& state) { if (!state.liveItems || !state.usecodeArchive || state.usecodeOwnerRows.empty()) { return false; } const auto* origin = state.liveItems->findItem(1); if (origin == nullptr || origin->data.shape >= state.shapeTypes.size()) { return false; } const auto candidates = remorse::itemGrabSearchCandidates(*origin, state.liveItems->mapItems(), state.shapeTypes); if (!candidates) { return false; } for (const auto& candidate : *candidates) { const auto* item = state.liveItems->findItem(candidate.itemNumber); if (item == nullptr || item->data.shape >= state.shapeTypes.size()) { continue; } const auto& shape = state.shapeTypes[item->data.shape]; const remorse::UsecodeItemIdentity identity{item->itemNumber, item->data.shape, item->data.flags, item->data.quality, shape.family, false}; const auto eligible = remorse::selectEligibleUsecodeEvent(*state.usecodeArchive, state.usecodeOwnerRows, identity, remorse::UsecodeClassBases{0, 0x800, 0x900}, 0x02, 1); if (eligible) { return queueUsecodeTask(state, eligible->classId, 1, item->itemNumber, eligible->body.bytes).has_value(); } } return false; } void runUsecodeTasks(AppState& state) { state.diagnosticKernel.scanRunnableProcesses(state.diagnosticKernel.activeGroup(), [](remorse::EntityDispatchEntryBase& process, void* context) { auto& app = *static_cast(context); const remorse::u16 processId = static_cast(process.bytes[2] | (static_cast(process.bytes[3]) << 8)); auto* task = app.usecodeTasks.find(processId); if (!task || task->halted) { return; } if (task->timerDelayProcess) { if (app.diagnosticKernel.systemTimerTick() >= task->wakeTick) { app.diagnosticKernel.terminateProcess(processId, app.diagnosticGroupCounts); } return; } if (task->interpreter.impliedProcessId != 0) { if (app.diagnosticKernel.processAt(task->interpreter.impliedProcessId) != nullptr) { return; } task->interpreter.impliedProcessId = 0; } remorse::UsecodeOpcodeServices services; services.readFarWord = [task](remorse::u16 offset, remorse::u16 segment) -> std::optional { return task->readMappedFarWord(remorse::FarPtr16{offset, segment}); }; services.callEvent = [&app](remorse::u16 classId, remorse::u16 eventSlot) -> std::optional { if (!app.usecodeArchive) { return std::nullopt; } const auto usecodeClass = remorse::loadUsecodeClass(*app.usecodeArchive, classId); return usecodeClass ? remorse::readUsecodeEventBody(*usecodeClass, eventSlot) : std::nullopt; }; services.setInfo = [&app, processId](remorse::u16 eventType, remorse::u16 sourceItem) { return app.diagnosticKernel.setProcessInfo(processId, eventType, sourceItem); }; services.processCount = [&app]() { return app.diagnosticKernel.processCount(); }; services.currentProcessId = [processId]() { return processId; }; services.callIntrinsic = [&app, task](remorse::u16 ordinal, remorse::u8 argumentBytes, const remorse::u8* arguments) -> std::optional { if (ordinal == 0x00 && argumentBytes == 0) { return remorse::u16{0}; } if (ordinal == 0xfd && argumentBytes == 2) { const remorse::u16 keycard = static_cast(arguments[0] | (static_cast(arguments[1]) << 8)); return static_cast(keycard < 64 && (app.heldKeycards & (std::uint64_t{1} << keycard)) != 0); } if (ordinal == 0xac && argumentBytes == 2) { const remorse::u16 shape = static_cast(arguments[0] | (static_cast(arguments[1]) << 8)); return shape < app.shapeTypes.size() ? std::optional{app.shapeTypes[shape].family} : std::nullopt; } if (ordinal == 0x15 && argumentBytes == 6) { return remorse::u16{0}; } if (ordinal == 0x3a && argumentBytes == 6) { return remorse::u16{0}; } if (argumentBytes < 4) { return std::nullopt; } const remorse::u16 offset = static_cast(arguments[0] | (static_cast(arguments[1]) << 8)); const remorse::u16 segment = static_cast(arguments[2] | (static_cast(arguments[3]) << 8)); if (ordinal == 0x0a && argumentBytes == 4) { const auto itemNumber = task->readMappedFarWord(remorse::FarPtr16{offset, segment}); if (itemNumber && app.liveItems && app.liveItems->destroyItem(*itemNumber)) { app.usecodeWorldMutationPending = true; } return remorse::u16{0}; } if (ordinal == 0x30 && argumentBytes == 4) { const auto poppedItem = app.liveItems ? app.liveItems->popItemFromEtherealVoid() : std::nullopt; if (poppedItem) { app.usecodeWorldMutationPending = true; } return poppedItem.value_or(0); } if (ordinal == 0x20 && argumentBytes == 10) { const remorse::u16 x = static_cast(arguments[4] | (static_cast(arguments[5]) << 8)); const remorse::u16 y = static_cast(arguments[6] | (static_cast(arguments[7]) << 8)); const auto poppedItem = app.liveItems ? app.liveItems->popItemToCoords(x, y, arguments[8]) : std::nullopt; if (poppedItem) { app.usecodeWorldMutationPending = true; } return poppedItem.value_or(0); } if (ordinal == 0x19 && argumentBytes == 14) { const remorse::u16 shape = static_cast(arguments[4] | (static_cast(arguments[5]) << 8)); const remorse::u16 frame = static_cast(arguments[6] | (static_cast(arguments[7]) << 8)); const remorse::u16 x = static_cast(arguments[8] | (static_cast(arguments[9]) << 8)); const remorse::u16 y = static_cast(arguments[10] | (static_cast(arguments[11]) << 8)); const remorse::u8 z = arguments[12]; if (!app.liveItems || frame > 0xff || !app.liveItems->canCreateItemAt(shape, x, y, z, app.shapeTypes)) { return remorse::u16{0}; } remorse::StagedFixedMapItem createdItem; createdItem.recordIndex = static_cast(-1); createdItem.data.x = x; createdItem.data.y = y; createdItem.data.z = z; createdItem.data.shape = shape; createdItem.data.frame = static_cast(frame); const auto itemNumber = app.liveItems->allocateItem(createdItem); if (!itemNumber || !task->writeMappedFarWord( remorse::FarPtr16{offset, segment}, *itemNumber)) { return remorse::u16{0}; } app.usecodeWorldMutationPending = true; return remorse::u16{1}; } const auto itemNumber = task->readMappedFarWord(remorse::FarPtr16{offset, segment}); if (ordinal == 0x10 && argumentBytes == 4) { const auto* item = itemNumber && app.liveItems ? app.liveItems->findItem(*itemNumber) : nullptr; return item ? static_cast(item->data.quality & 0xff) : remorse::u16{0}; } if (!itemNumber) { return std::nullopt; } if (ordinal == 0x3c && argumentBytes == 4) { const auto* item = app.liveItems ? app.liveItems->findItem(*itemNumber) : nullptr; return item && item->data.shape < app.shapeTypes.size() ? std::optional{app.shapeTypes[item->data.shape].family} : std::nullopt; } if (ordinal == 0x22 && argumentBytes == 4) { if (!app.liveItems || !app.liveItems->pushItemToEtherealVoid(*itemNumber)) { return std::nullopt; } app.usecodeWorldMutationPending = true; return remorse::u16{0}; } if (ordinal == 0x25) { return remorse::u16{0}; } if (ordinal == 0xea && argumentBytes == 4) { const auto* item = app.liveItems ? app.liveItems->findItem(*itemNumber) : nullptr; return item ? std::optional{static_cast(item->data.quality & 0xff)} : std::nullopt; } if (ordinal == 0x01 && argumentBytes == 4) { const auto* item = app.liveItems ? app.liveItems->findItem(*itemNumber) : nullptr; return item ? std::optional{item->data.frame} : std::nullopt; } if (ordinal == 0x03 && argumentBytes == 4) { const auto* item = app.liveItems ? app.liveItems->findItem(*itemNumber) : nullptr; return item ? std::optional{item->data.mapNumber} : std::nullopt; } if (ordinal == 0x09 && argumentBytes == 4) { const auto* item = app.liveItems ? app.liveItems->findItem(*itemNumber) : nullptr; return item ? std::optional{item->data.z} : std::nullopt; } if (ordinal == 0x13 && argumentBytes == 4) { const auto* item = app.liveItems ? app.liveItems->findItem(*itemNumber) : nullptr; return item ? std::optional{item->data.x} : std::nullopt; } if (ordinal == 0x14 && argumentBytes == 4) { const auto* item = app.liveItems ? app.liveItems->findItem(*itemNumber) : nullptr; return item ? std::optional{item->data.y} : std::nullopt; } if (ordinal == 0x24 && argumentBytes == 6) { const remorse::u16 shape = static_cast(arguments[4] | (static_cast(arguments[5]) << 8)); if (!app.liveItems || !app.liveItems->setItemShape(*itemNumber, shape)) { return std::nullopt; } app.usecodeWorldMutationPending = true; return remorse::u16{0}; } if ((ordinal == 0x02 || ordinal == 0x59) && argumentBytes == 6) { const remorse::u8 frame = static_cast(arguments[4] | (static_cast(arguments[5]) << 8)); if (!app.liveItems || !app.liveItems->setItemFrame(*itemNumber, frame)) { return std::nullopt; } app.usecodeWorldMutationPending = true; return remorse::u16{0}; } return std::nullopt; }; services.spawn = [&app](remorse::u16 classId, remorse::u16 eventSlot, remorse::u8 extraArgumentBytes, remorse::u8 itemArgumentSize, remorse::u16 itemArgument, const remorse::u8* extraArguments) -> std::optional { if (!app.usecodeArchive) { return std::nullopt; } const auto usecodeClass = remorse::loadUsecodeClass(*app.usecodeArchive, classId); const auto body = usecodeClass ? remorse::readUsecodeEventBody(*usecodeClass, eventSlot) : std::nullopt; if (!body) { return std::nullopt; } std::vector arguments; if (extraArgumentBytes != 0) { arguments.assign(extraArguments, extraArguments + extraArgumentBytes); } const auto childId = queueUsecodeTask(app, classId, eventSlot, itemArgument, body->bytes, itemArgumentSize, std::move(arguments)); if (!childId) { return std::nullopt; } auto* registeredChild = app.usecodeTasks.find(*childId); if (registeredChild && classId == 0x0a0c && eventSlot == 0x32 && itemArgumentSize == 0 && extraArgumentBytes == 2) { const remorse::u16 delay = static_cast(arguments[0] | (static_cast(arguments[1]) << 8)); registeredChild->timerDelayProcess = true; registeredChild->wakeTick = app.diagnosticKernel.systemTimerTick() + delay; } return childId; }; for (std::size_t instructionCount = 0; instructionCount < 256; ++instructionCount) { const auto result = task->step(services); if (result == remorse::UsecodeStepResult::Returned) { app.diagnosticKernel.terminateProcess(processId, app.diagnosticGroupCounts); break; } if (result == remorse::UsecodeStepResult::Yielded) { break; } if (result != remorse::UsecodeStepResult::Advanced && result != remorse::UsecodeStepResult::SetInfo && result != remorse::UsecodeStepResult::Spawned) { task->halted = true; break; } } }, &state, state.diagnosticKernel.systemTimerTick()); state.diagnosticKernel.clearTerminatedProcesses(); for (std::size_t processId = 3; processId < 1020; ++processId) { const auto id = static_cast(processId); if (state.usecodeTasks.find(id) && state.diagnosticKernel.processAt(id) == nullptr) { state.usecodeTasks.remove(id); } } } void loadSceneAsync(HWND window, AppState& state) { try { 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); 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); if (!stagedItems) { setLoadFailure(state, L"The fixed-map item cache could not be initialized."); PostMessageW(window, sceneReadyMessage, 0, 0); return; } const auto shapeTypes = remorse::loadTypeFlags(*typeFlagsPath); 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 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); auto shapeArchive = remorse::loadShapeArchive(*shapesPath); const auto palette = remorse::loadPalette256(*palettePath); std::array, 0x40> playerAnimations; if (animationArchive) { for (const remorse::u8 index : remorse::controllerAnimationIndices) { playerAnimations[index] = remorse::loadAnimationClip( *animationArchive, 1, index); } } const auto shapeFrames = shapeArchive ? remorse::loadShapeFrames(*shapeArchive, 1) : std::nullopt; if (!shapeArchive || !palette || !playerAnimations[0] || !playerAnimations[1] || !playerAnimations[3] || !shapeFrames) { setLoadFailure(state, L"The player stand, walk, or run animation could not be loaded."); PostMessageW(window, sceneReadyMessage, 0, 0); return; } std::vector> 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(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((*shapeFrames)[shapeFrame]); if (!decoded) { return false; } playerFrames[shapeFrame] = std::move(*decoded); } } } return true; }; for (const auto& clip : playerAnimations) { if (clip && !cacheAnimationFrames(*clip)) { 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(entry.x)); minY = std::min(minY, static_cast(entry.y)); maxX = std::max(maxX, static_cast(entry.x)); maxY = std::max(maxY, static_cast(entry.y)); } const auto startingEgg = state.warpStart ? std::optional{} : remorse::findTeleportEgg(*stagedItems, *shapeTypes, 0x1e); if (!state.warpStart && state.mapIndex == 1 && !startingEgg) { setLoadFailure(state, L"The original map 1 starting teleporter could not be found uniquely."); PostMessageW(window, sceneReadyMessage, 0, 0); return; } if (!state.warpStart && state.mapIndex != 1 && !state.diagnostics) { setLoadFailure(state, L"Only map 1 has a source-backed start. Use --diagnostics for other maps."); PostMessageW(window, sceneReadyMessage, 0, 0); return; } remorse::WorldPoint spawn = state.warpStart ? remorse::WorldPoint{static_cast(state.warpStart->x) * 2, static_cast(state.warpStart->y) * 2, state.warpStart->z} : startingEgg ? remorse::WorldPoint{startingEgg->data.x * 2, startingEgg->data.y * 2, startingEgg->data.z} : remorse::WorldPoint{(minX + maxX) / 2, (minY + maxY) / 2, 0}; remorse::MapRenderOptions options = fullSceneOptions(state.mapIndex, spawn); remorse::LiveFixedMapItems liveItems(std::move(*stagedItems), std::move(containedItems)); if (startingEgg) { std::lock_guard kernelLock(state.kernelMutex); if (state.mapIndex != 1 || !remorse::startFreshGameMapOne(state.diagnosticKernel, liveItems, *shapeTypes, state.diagnosticGroupCounts)) { setLoadFailure(state, L"The source-derived fresh-game start could not resolve map 1's level destination."); PostMessageW(window, sceneReadyMessage, 0, 0); return; } const auto* avatar = liveItems.findItem(1); avatar = liveItems.findItem(1); spawn = remorse::WorldPoint{avatar->data.x * 2, avatar->data.y * 2, avatar->data.z}; options.viewCenter = spawn; } else { if (!liveItems.initializeAvatar()) { setLoadFailure(state, L"The player item could not be initialized."); PostMessageW(window, sceneReadyMessage, 0, 0); return; } remorse::StagedFixedMapItem directStart; directStart.data.x = static_cast(spawn.x / 2); directStart.data.y = static_cast(spawn.y / 2); directStart.data.z = static_cast(spawn.z); liveItems.teleportAvatar(directStart, static_cast(state.mapIndex)); } remorse::MapSceneRenderer renderer{ std::move(*map), std::move(*globObjects), std::move(*shapeArchive), *palette, *shapeTypes, {}}; hatchGlobsInFastArea(liveItems, renderer, remorse::calculateFastAreaRange(spawn)); const auto initialMetadata = remorse::getAnimationFrame(*playerAnimations[0], 14, 0); if (!initialMetadata) { setLoadFailure(state, L"The player stand frame could not be resolved."); PostMessageW(window, sceneReadyMessage, 0, 0); return; } const remorse::u16 initialShapeFrame = remorse::getAnimationShapeFrame(*initialMetadata); if (initialShapeFrame >= playerFrames.size() || !playerFrames[initialShapeFrame]) { setLoadFailure(state, L"The player stand frame could not be decoded."); PostMessageW(window, sceneReadyMessage, 0, 0); return; } const remorse::MapRenderSprite initialPlayer{spawn, 1, static_cast(initialShapeFrame), remorse::isAnimationFrameFlipped(*initialMetadata), &*playerFrames[initialShapeFrame], &*palette}; auto scene = renderer.render(options, &liveItems); if (!scene) { setLoadFailure(state, L"Map graphics or palette data could not be loaded."); PostMessageW(window, sceneReadyMessage, 0, 0); return; } auto playerPatch = renderer.render( playerPatchOptions(state.mapIndex, spawn), &liveItems, &initialPlayer); if (!playerPatch) { setLoadFailure(state, L"The initial player render patch could not be built."); PostMessageW(window, sceneReadyMessage, 0, 0); return; } std::vector 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 lock(state.sceneMutex); state.spawn = spawn; state.fastArea = remorse::calculateFastAreaRange(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.playerPatch = std::move(playerPatch); state.renderer = std::move(renderer); state.dibPixels = std::move(dibPixels); state.playerAnimations = std::move(playerAnimations); state.controllerMovement.setTurnStep( state.playerAnimations[1]->directionCount == 8 ? 2 : 1); state.playerFrames = std::move(playerFrames); state.playerPalette = *palette; state.liveItems.emplace(std::move(liveItems)); 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); }); } catch (const std::exception& error) { reportLoadFailure(window, state, widen(error.what())); } catch (...) { reportLoadFailure(window, state, L"Could not start the map-loading worker thread."); } } bool hatchGlobsInFastArea(remorse::LiveFixedMapItems& items, const remorse::MapSceneRenderer& renderer, const remorse::FastAreaRange& range) { std::vector eggIds; for (const auto& item : items.mapItems()) { if (item.data.shape < renderer.typeFlags.size() && renderer.typeFlags[item.data.shape].family == 3 && !items.isGlobHatched(item.itemNumber) && remorse::isWorldPointInFastArea( item.data.x * 2, item.data.y * 2, range)) { eggIds.push_back(item.itemNumber); } } bool changed = false; for (const remorse::u16 eggId : eggIds) { const auto* egg = items.findItem(eggId); const auto glob = std::find_if(renderer.globs.begin(), renderer.globs.end(), [egg](const auto& object) { return object.index == egg->data.quality; }); if (glob != renderer.globs.end()) { changed = items.hatchGlobEgg(eggId, *glob, renderer.typeFlags).has_value() || changed; } } return changed; } void startLiveRenderer(HWND window, AppState& state) { try { state.renderThread = std::thread([window, &state]() { try { for (;;) { std::optional snapshot; std::optional playerSprite; remorse::WorldPoint center{}; bool fullRender = false; { std::unique_lock lock(state.sceneMutex); state.renderWake.wait(lock, [&state]() { return state.renderStop || state.renderRequested; }); if (state.renderStop) { return; } state.renderRequested = false; fullRender = state.renderFullRequested; state.renderFullRequested = false; state.renderFullInFlight = fullRender; snapshot.emplace(*state.liveItems); center = avatarWorld(state); playerSprite = playerRenderSprite(state); } auto playerPatch = state.renderer->render(playerPatchOptions(state.mapIndex, center), &*snapshot, playerSprite ? &*playerSprite : nullptr); if (!playerPatch) { reportLoadFailure(window, state, L"The live player-patch renderer returned no image."); return; } { std::lock_guard lock(state.sceneMutex); if (state.renderStop) { return; } state.playerPatch = std::move(playerPatch); } PostMessageW(window, sceneReadyMessage, 0, 0); std::optional scene; std::vector pixels; if (fullRender) { remorse::MapRenderOptions options = fullSceneOptions(state.mapIndex, center); scene = state.renderer->render(options, &*snapshot); if (!scene) { reportLoadFailure(window, state, L"The live full-map renderer returned no image."); return; } pixels.resize(scene->pixels.size() * 3); for (std::size_t index = 0; index < scene->pixels.size(); ++index) { pixels[index * 3] = scene->pixels[index].blue; pixels[index * 3 + 1] = scene->pixels[index].green; pixels[index * 3 + 2] = scene->pixels[index].red; } { std::lock_guard lock(state.sceneMutex); if (state.renderStop) { return; } state.scene = std::move(scene); state.dibPixels = std::move(pixels); state.renderFullInFlight = false; } PostMessageW(window, sceneReadyMessage, 0, 0); } } } catch (const std::exception& error) { reportLoadFailure(window, state, widen(error.what())); } catch (...) { reportLoadFailure(window, state, L"An unexpected error occurred in the live map renderer."); } }); } catch (const std::exception& error) { reportLoadFailure(window, state, widen(error.what())); } catch (...) { reportLoadFailure(window, state, L"Could not start the live map-rendering worker thread."); } } void requestLiveRender(AppState& state, bool fullRender, bool forceFullRender = false) { state.renderRequested = true; state.renderFullRequested = state.renderFullRequested || (fullRender && (!state.renderFullInFlight || forceFullRender)); state.renderWake.notify_one(); } 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(&bounds), DT_CENTER | DT_VCENTER | DT_SINGLELINE); RestoreDC(device, saved); } 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(std::max(1L, client.right - client.left)); const int clientHeight = static_cast(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( 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 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(state.scene->width)); const int viewHeight = std::min(clientHeight, static_cast(state.scene->height)); const auto avatarScreen = remorse::projectToScreen(avatarWorld(state)); const int centeredLeft = avatarScreen.x - state.scene->sourceLeft - viewWidth / 2; const int centeredTop = avatarScreen.y - state.scene->sourceTop - viewHeight / 2; const int maxSourceLeft = static_cast(state.scene->width) - viewWidth; const int maxSourceTop = static_cast(state.scene->height) - viewHeight; const int sourceLeft = std::clamp(centeredLeft, 0, maxSourceLeft); const int sourceTop = std::clamp(centeredTop, 0, maxSourceTop); const int prefetchMarginX = std::max(1, viewWidth / 4); const int prefetchMarginY = std::max(1, viewHeight / 4); const bool nearingSceneEdge = centeredLeft < prefetchMarginX || centeredLeft > maxSourceLeft - prefetchMarginX || centeredTop < prefetchMarginY || centeredTop > maxSourceTop - prefetchMarginY; if (nearingSceneEdge && state.renderThread.joinable()) { requestLiveRender(state, true); } const std::size_t viewStride = (static_cast(viewWidth) * 3 + 3) & ~std::size_t(3); state.viewPixels.resize(viewStride * static_cast(viewHeight)); const std::size_t sceneStride = static_cast(state.scene->width) * 3; for (int row = 0; row < viewHeight; ++row) { const std::size_t sceneOffset = static_cast(sourceTop + row) * sceneStride + static_cast(sourceLeft) * 3; const std::size_t viewOffset = static_cast(row) * viewStride; std::memcpy(state.viewPixels.data() + viewOffset, state.dibPixels.data() + sceneOffset, static_cast(viewWidth) * 3); } if (state.playerPatch) { const remorse::RenderedMapImage& patch = *state.playerPatch; const int patchLeft = patch.sourceLeft - (state.scene->sourceLeft + sourceLeft); const int patchTop = patch.sourceTop - (state.scene->sourceTop + sourceTop); for (int patchY = 0; patchY < static_cast(patch.height); ++patchY) { const int destY = patchTop + patchY; if (destY < 0 || destY >= viewHeight) { continue; } for (int patchX = 0; patchX < static_cast(patch.width); ++patchX) { const int destX = patchLeft + patchX; if (destX < 0 || destX >= viewWidth) { continue; } const std::size_t sourceIndex = static_cast(patchY) * patch.width + patchX; if (patch.coverage[sourceIndex] == 0) { continue; } const remorse::RgbColor& color = patch.pixels[sourceIndex]; const std::size_t destIndex = static_cast(destY) * viewStride + static_cast(destX) * 3; state.viewPixels[destIndex] = color.blue; state.viewPixels[destIndex + 1] = color.green; state.viewPixels[destIndex + 2] = color.red; } } } BITMAPINFO bitmapInfo{}; bitmapInfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); bitmapInfo.bmiHeader.biWidth = viewWidth; bitmapInfo.bmiHeader.biHeight = -viewHeight; bitmapInfo.bmiHeader.biPlanes = 1; bitmapInfo.bmiHeader.biBitCount = 24; bitmapInfo.bmiHeader.biCompression = BI_RGB; bitmapInfo.bmiHeader.biSizeImage = static_cast(state.viewPixels.size()); StretchDIBits(device, 0, 0, viewWidth, viewHeight, 0, 0, viewWidth, viewHeight, state.viewPixels.data(), &bitmapInfo, DIB_RGB_COLORS, SRCCOPY); if (!state.diagnostics) { finishPaint(); return; } 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; const remorse::WorldPoint playerWorld = avatarWorld(state); label << L"MAP " << std::setw(3) << std::setfill(L'0') << state.mapIndex << L" X " << playerWorld.x << L" Y " << playerWorld.y << L" Z " << static_cast(playerWorld.z) << L" DIR " << std::setw(2) << static_cast(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(stand.bytes[0x0f]) << 8); std::wostringstream diagnostics; diagnostics << L"HOST 40Hz | KERNEL TICK " << state.diagnosticKernel.systemTimerTick() << L" | STAND #" << static_cast(stand.bytes[0x02]) << L" " << ((stand.bytes[0x19] & 0x10) != 0 ? L"SLEEP " : L"READY ") << ((stand.bytes[0x19] & 0x10) != 0 ? static_cast(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( playerWorld.x, playerWorld.y, diagnosticItemRange) : std::nullopt; if (state.diagnosticItem || nearbyItem) { const auto& displayItem = state.diagnosticItem ? state.diagnosticItem : nearbyItem; const auto* releaseTask = state.diagnosticReleaseProcessId != 0 ? state.usecodeTasks.find(state.diagnosticReleaseProcessId) : nullptr; const std::wstring releaseStatus = state.diagnosticReleaseProcessId == 0 ? L"NOT QUEUED" : releaseTask == nullptr ? L"COMPLETE" : releaseTask->halted ? L"HALTED" : releaseTask->programCounter == remorse::usecodeEventBytecodeOffset ? L"QUEUED" : L"RUNNING"; 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 (" + releaseStatus + L")" : 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(now.QuadPart - state.lastTick.QuadPart) / static_cast(state.ticksPerSecond.QuadPart), 0.0, 0.25); state.lastTick = now; if (GetForegroundWindow() != window) { return; } std::lock_guard lock(state.sceneMutex); if (!state.sceneLoaded || !state.scene || !state.loadError.empty()) { return; } state.simulationAccumulator += elapsed; bool changed = false; while (state.simulationAccumulator >= simulationTickSeconds) { state.simulationAccumulator -= simulationTickSeconds; remorse::ControllerActorState controllerActor; controllerActor.mapNumber = static_cast(state.mapIndex); controllerActor.direction = state.playerDirection; controllerActor.lastAnimation = state.playerAnimation; controllerActor.lastAnimationNotCombat = remorse::controllerLastAnimationIsNotCombat( state.playerAnimation); controllerActor.kneeling = state.playerKneeling; controllerActor.activeWeapon = state.playerHasActiveWeapon; controllerActor.busy = state.animationProcessId != 0 && state.diagnosticKernel.processAt(state.animationProcessId) != nullptr; state.controllerMovement.setActorState(controllerActor); state.diagnosticKernel.dispatchPendingKeyEvents([](remorse::EntityDispatchEntryBase& entry, remorse::u16 selector, remorse::u16 filter, remorse::KeyEvent& event, void* context) { auto& app = *static_cast(context); if (entry.bytes[0] == 0xa6 && entry.bytes[1] == 0x3a && selector == 0x10 && filter == 0) { app.controllerMovement.handleKeyEvent( event.scanCode, event.modifiers, event.field8, event.field9, event.fieldA, event.field6); } }, &state); if (auto command = state.controllerMovement.takeCommandRequest()) { state.lastControllerCommand = command; if (command->command == remorse::ControllerCommand::CycleWeaponForward) { state.playerHasActiveWeapon = !state.playerHasActiveWeapon; controllerActor.activeWeapon = state.playerHasActiveWeapon; state.controllerMovement.setActorState(controllerActor); } } if (state.useRequested) { state.useRequested = false; changed = startNearbyUsecode(state) || changed; } runUsecodeTasks(state); if (state.activeOneShotMovement && (state.animationProcessId == 0 || state.diagnosticKernel.processAt(state.animationProcessId) == nullptr)) { state.activeOneShotMovement.reset(); state.animationProcessId = 0; state.playerAnimation = 0; state.playerFrame = 0; } if (const auto action = state.controllerMovement.takeActionRequest()) { state.activeOneShotMovement = action; if (action->animation == 0x28) { state.playerKneeling = true; } else if (action->animation == 0x29) { state.playerKneeling = false; } } auto movement = state.activeOneShotMovement ? *state.activeOneShotMovement : state.controllerMovement.request(); bool directionUpdatedInPlace = false; if (movement.updateDirectionInPlace) { const auto requestedDirection = state.controllerMovement.takeInPlaceDirectionUpdate(); if (requestedDirection && state.liveItems && state.animationProcessId != 0) { const auto updatedDirection = state.diagnosticKernel.updateAnimPrimitiveDirection( state.animationProcessId, *state.liveItems, *requestedDirection); if (updatedDirection) { movement.animation = state.playerAnimation; movement.direction = *updatedDirection; directionUpdatedInPlace = true; } } if (!directionUpdatedInPlace) { movement = state.activeOneShotMovement ? *state.activeOneShotMovement : state.controllerMovement.request(); } } if (movement.animation >= state.playerAnimations.size() || !state.playerAnimations[movement.animation]) { state.activeOneShotMovement.reset(); movement = state.controllerMovement.request(); } state.diagnosticKernel.deliverSystemTimerEvent(); bool gravityMoved = false; if (state.diagnostics) { 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(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(releaseContext); app.diagnosticReleaseEventItem = itemNumber; app.diagnosticReleaseProcessId = 0; app.diagnosticReleaseClass.clear(); app.diagnosticReleaseBodyBytes = 0; const auto* item = app.liveItems ? app.liveItems->findItem(itemNumber) : nullptr; if (item && app.usecodeArchive && item->data.shape < app.shapeTypes.size()) { 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.diagnosticReleaseProcessId = queueUsecodeTask(app, eligible->classId, eventId, itemNumber, eligible->body.bytes).value_or(0); } } }, &app); } else if (entry.bytes[0] == 0x10 && entry.bytes[1] == 0x06 && app.liveItems) { const remorse::u16 processId = static_cast(entry.bytes[2] | (static_cast(entry.bytes[3]) << 8)); app.diagnosticKernel.runResolvedGravity(processId, *app.liveItems, app.shapeTypes, app.fastArea, 1, app.diagnosticKernel.systemTimerTick(), app.diagnosticGroupCounts); } }, &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; } } else if (state.liveItems) { gravityMoved = state.diagnosticKernel.scanResolvedGravity( state.diagnosticKernel.activeGroup(), *state.liveItems, state.shapeTypes, remorse::calculateFastAreaRange(avatarWorld(state)), 1, state.diagnosticKernel.systemTimerTick(), state.diagnosticGroupCounts) != 0; } changed = changed || state.diagnostics || gravityMoved; if (movement.animation == 0) { const bool facingChanged = state.playerDirection != movement.direction; state.playerDirection = movement.direction; const bool playerSpriteChanged = state.playerAnimation != 0 || state.playerFrame != 0; if (state.animationProcessId != 0) { auto* process = state.diagnosticKernel.processAt(state.animationProcessId); if (process != nullptr) { process->bytes[0x18] |= 4; state.diagnosticKernel.terminateProcess(state.animationProcessId, state.diagnosticGroupCounts); } state.animationProcessId = 0; } changed = changed || state.playerAnimation != 0 || state.playerFrame != 0; state.playerAnimation = 0; state.playerFrame = 0; changed = changed || facingChanged; const bool usecodeMutation = state.usecodeWorldMutationPending; state.usecodeWorldMutationPending = false; changed = changed || usecodeMutation; if (state.renderThread.joinable() && (gravityMoved || usecodeMutation || playerSpriteChanged || facingChanged)) { requestLiveRender(state, gravityMoved || usecodeMutation, true); } continue; } const remorse::u8 previousPlayerAnimation = state.playerAnimation; const remorse::u8 previousPlayerDirection = state.playerDirection; const remorse::u8 previousPlayerFrame = state.playerFrame; const remorse::u8 requestedAnimation = movement.animation; const remorse::AnimationClip& clip = *state.playerAnimations[requestedAnimation]; if (!directionUpdatedInPlace && (state.animationProcessId == 0 || state.playerAnimation != requestedAnimation || state.playerDirection != movement.direction)) { if (state.animationProcessId != 0) { auto* process = state.diagnosticKernel.processAt(state.animationProcessId); process->bytes[0x18] |= 4; state.diagnosticKernel.terminateProcess(state.animationProcessId, state.diagnosticGroupCounts); } auto* process = state.diagnosticKernel.createAnimPrimitiveProcess( state.diagnosticKernel.activeGroup(), 1, requestedAnimation, movement.direction, clip, state.diagnosticGroupCounts); state.animationProcessId = static_cast(process->base.bytes[2] | (static_cast(process->base.bytes[3]) << 8)); state.diagnosticKernel.startAnimPrimitiveProcess(state.animationProcessId, *state.liveItems, clip); state.playerAnimation = requestedAnimation; } state.playerDirection = movement.direction; const auto* avatar = state.liveItems->findItem(1); const remorse::WorldPoint beforeMove{avatar->data.x, avatar->data.y, avatar->data.z}; const auto fastArea = remorse::calculateFastAreaRange( {avatar->data.x, avatar->data.y, avatar->data.z}); state.diagnosticKernel.runTimedSchedulerPass(state.diagnosticKernel.activeGroup(), [](remorse::EntityDispatchEntryBase& entry, void* context) { auto& app = *static_cast(context); if (&entry == app.diagnosticKernel.processAt(app.animationProcessId)) { const remorse::AnimationClip& activeClip = *app.playerAnimations[app.playerAnimation]; const auto* item = app.liveItems->findItem(1); const auto advanced = app.diagnosticKernel.advanceGroundedAnimPrimitive(app.animationProcessId, *app.liveItems, activeClip, app.shapeTypes, remorse::calculateFastAreaRange({item->data.x, item->data.y, item->data.z})); if (app.activeOneShotMovement && (!advanced || !*advanced)) { auto* finished = app.diagnosticKernel.processAt(app.animationProcessId); if (finished != nullptr) { finished->bytes[0x18] |= 4; app.diagnosticKernel.terminateProcess( app.animationProcessId, app.diagnosticGroupCounts); } app.animationProcessId = 0; app.playerAnimation = 0; app.playerFrame = 0; } } }, &state); state.fastArea = fastArea; state.playerFrame = state.liveItems->findNpcAnimation(1)->frame; const remorse::ScreenPoint destinationScreen = remorse::projectToScreen(avatarWorld(state)); const remorse::ScreenPoint spawnScreen = remorse::projectToScreen(state.spawn); state.playerOffsetX = destinationScreen.x - spawnScreen.x; state.playerOffsetY = destinationScreen.y - spawnScreen.y; const bool moved = avatar->data.x != beforeMove.x || avatar->data.y != beforeMove.y || avatar->data.z != beforeMove.z; const bool hatched = moved && hatchGlobsInFastArea( *state.liveItems, *state.renderer, remorse::calculateFastAreaRange(avatarWorld(state))); const bool usecodeMutation = state.usecodeWorldMutationPending; state.usecodeWorldMutationPending = false; const bool playerSpriteChanged = state.playerAnimation != previousPlayerAnimation || state.playerDirection != previousPlayerDirection || state.playerFrame != previousPlayerFrame; if (state.renderThread.joinable() && (moved || hatched || usecodeMutation || gravityMoved || playerSpriteChanged)) { requestLiveRender(state, hatched || usecodeMutation || gravityMoved, true); } changed = true; } if (changed) { InvalidateRect(window, nullptr, FALSE); } } LRESULT CALLBACK windowProcedure(HWND window, UINT message, WPARAM wParam, LPARAM lParam) { AppState* state = reinterpret_cast(GetWindowLongPtrW(window, GWLP_USERDATA)); if (message == WM_NCCREATE) { const auto* create = reinterpret_cast(lParam); state = static_cast(create->lpCreateParams); SetWindowLongPtrW(window, GWLP_USERDATA, reinterpret_cast(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) { displayLoadFailure(window, *state); updatePlayer(window, *state); } return 0; case WM_KILLFOCUS: state->controllerMovement.clear(); { std::lock_guard lock(state->kernelMutex); while (state->diagnosticKernel.popPendingKeyEvent()) {} } return 0; case WM_KEYDOWN: case WM_KEYUP: if (wParam == VK_ESCAPE && message == WM_KEYDOWN) { DestroyWindow(window); return 0; } if (wParam == 'E' && message == WM_KEYDOWN) { state->useRequested = true; } { remorse::KeyEvent event{}; event.scanCode = static_cast((lParam >> 16) & 0xff); switch (wParam) { case 'W': event.scanCode = 0x48; break; case 'A': event.scanCode = 0x4b; break; case 'S': event.scanCode = 0x50; break; case 'D': event.scanCode = 0x4d; break; case 'Q': event.scanCode = 0x47; break; case 'E': event.scanCode = 0x49; break; case 'Z': event.scanCode = 0x4f; break; case 'C': event.scanCode = 0x51; break; } event.modifiers = (GetKeyState(VK_CAPITAL) & 1) != 0 ? 0x40 : 0; if (GetKeyState(VK_NUMLOCK) & 1) event.modifiers |= 0x20; if ((lParam & (1L << 24)) != 0 || wParam == 'W' || wParam == 'A' || wParam == 'S' || wParam == 'D' || wParam == 'Q' || wParam == 'E' || wParam == 'Z' || wParam == 'C') event.modifiers &= ~0x20; if (GetKeyState(VK_LSHIFT) & 0x8000) event.modifiers |= 1; if (GetKeyState(VK_RSHIFT) & 0x8000) event.modifiers |= 2; if (GetKeyState(VK_LMENU) & 0x8000 || GetKeyState(VK_RMENU) & 0x8000) { event.modifiers |= 0x0a00; } if (GetKeyState(VK_LCONTROL) & 0x8000 || GetKeyState(VK_RCONTROL) & 0x8000) { event.modifiers |= 0x0500; } event.field8 = 1; event.field9 = message == WM_KEYDOWN ? 1 : 0; event.fieldA = message == WM_KEYDOWN ? 1 : 0; std::lock_guard lock(state->kernelMutex); state->diagnosticKernel.queuePendingKeyEvent(event); } if (message == WM_KEYUP) return 0; if (state->diagnostics && wParam == 'F') { std::lock_guard lock(state->sceneMutex); if (state->sceneLoaded && state->scene && !state->diagnosticItemCompleted && state->diagnosticItemProcessId == 0) { const remorse::WorldPoint playerWorld = avatarWorld(*state); state->diagnosticItem = state->liveItems ? state->liveItems->nearestItem( playerWorld.x, 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( itemProcess->bytes[2] | (static_cast(itemProcess->bytes[3]) << 8)); InvalidateRect(window, nullptr, FALSE); } } return 0; case WM_CHAR: if (state->diagnostics && wParam > 0 && wParam <= 0xff) { remorse::KeyEvent lastEvent{}; lastEvent.character = static_cast(wParam); lastEvent.scanCode = static_cast((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: { bool shouldStartRenderer = false; { std::lock_guard lock(state->sceneMutex); shouldStartRenderer = state->sceneLoaded && state->renderer.has_value() && !state->renderThread.joinable(); } if (shouldStartRenderer) { startLiveRenderer(window, *state); } displayLoadFailure(window, *state); InvalidateRect(window, nullptr, FALSE); return 0; } case WM_DESTROY: KillTimer(window, timerId); if (state->sceneThread.joinable()) { state->sceneThread.join(); } { std::lock_guard lock(state->sceneMutex); state->renderStop = true; } state->renderWake.notify_one(); if (state->renderThread.joinable()) { state->renderThread.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; bool diagnostics = false; std::optional warpStart; constexpr std::array missionBaseMaps{ 0, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 40}; std::wistringstream argumentStream(commandLine ? commandLine : L""); std::vector arguments; std::wstring argument; while (argumentStream >> argument) { arguments.push_back(argument); } const auto parseInteger = [](const std::wstring& text, long minimum, long maximum, long& value) { wchar_t* end = nullptr; const long parsed = std::wcstol(text.c_str(), &end, 0); if (end == text.c_str() || *end != L'\0' || parsed < minimum || parsed > maximum) { return false; } value = parsed; return true; }; long warpMission = 0; long mapOffset = 0; bool warpRequested = false; bool invalidArguments = false; for (std::size_t index = 0; index < arguments.size(); ++index) { const std::wstring& current = arguments[index]; if (current == L"--diagnostics") { diagnostics = true; } else if (current == L"-warp") { long x = 0; long y = 0; long z = 0; if (warpRequested || index + 4 >= arguments.size() || !parseInteger(arguments[index + 1], 0, static_cast(missionBaseMaps.size() - 1), warpMission) || !parseInteger(arguments[index + 2], 0, 0x7fff, x) || !parseInteger(arguments[index + 3], 0, 0x7fff, y) || !parseInteger(arguments[index + 4], 0, 0xff, z)) { invalidArguments = true; break; } warpStart = WarpStart{static_cast(x), static_cast(y), static_cast(z)}; warpRequested = true; index += 4; } else if (current == L"-mapoff") { if (index + 1 >= arguments.size() || !parseInteger(arguments[index + 1], -255, 255, mapOffset)) { invalidArguments = true; break; } ++index; } else { long parsed = 0; if (parseInteger(current, 0, 255, parsed)) { mapIndex = static_cast(parsed); } } } if (warpRequested) { const long targetMap = missionBaseMaps[static_cast(warpMission)] + mapOffset; if (targetMap < 0 || targetMap > 255) { invalidArguments = true; } else { mapIndex = static_cast(targetMap); } } if (invalidArguments) { MessageBoxW(nullptr, L"Usage: remorse_game.exe -warp [-mapoff ]\n" L"Mission must be 0..16, map 0..255, X/Y 0..32767, and Z 0..255.", L"Invalid warp arguments", MB_OK | MB_ICONERROR); return 2; } 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; state.diagnostics = diagnostics; state.warpStart = warpStart; 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.createControllerProcess(1, state.diagnosticGroupCounts); if (diagnostics) { 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(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); std::wstring windowTitle = diagnostics ? L"Crusader: No Remorse | Diagnostics" : L"Crusader: No Remorse | Traversal Test"; if (state.warpStart) { std::wostringstream title; title << L"Crusader: No Remorse | Warp map " << state.mapIndex << L" (" << state.warpStart->x << L", " << state.warpStart->y << L", " << static_cast(state.warpStart->z) << L")"; windowTitle = title.str(); } HWND window = CreateWindowExW(0, windowClassName, windowTitle.c_str(), 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(message.wParam); }