Add comprehensive tests for ProcessKernel and Usecode VM functionality

- Implemented tests for ProcessKernel in entity_dispatch_entry_tests.cpp, covering process creation, termination, and scanning of runnable processes.
- Enhanced fixed_map_tests.cpp with tests for item allocation and release, including recycling of items and process ownership.
- Expanded flex_archive_tests.cpp to validate the interaction between usecode events and item processes, ensuring correct behavior of spawned tasks and rendering.
- Introduced usecode_vm_tests.cpp to thoroughly test the UsecodeInterpreterState and UsecodeProcessTask functionalities, including stack operations and opcode services.
This commit is contained in:
Maddo 2026-10-04 18:11:16 +02:00
commit 08a907f322
14 changed files with 1784 additions and 34 deletions

View file

@ -15,6 +15,7 @@
#include "remorse/shape_archive.h"
#include "remorse/type_flags.h"
#include "remorse/usecode_archive.h"
#include "remorse/usecode_vm.h"
#include <algorithm>
#include <cmath>
@ -47,6 +48,10 @@ struct AppState {
bool diagnostics = false;
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;
@ -55,6 +60,7 @@ struct AppState {
std::optional<remorse::StagedFixedMapItem> diagnosticItem;
remorse::u16 diagnosticItemProcessId = 0;
remorse::u16 diagnosticReleaseEventItem = 0;
remorse::u16 diagnosticReleaseProcessId = 0;
std::string diagnosticReleaseClass;
std::size_t diagnosticReleaseBodyBytes = 0;
bool diagnosticItemCompleted = false;
@ -142,6 +148,208 @@ remorse::WorldPoint avatarWorld(const AppState& state)
bool hatchGlobsInFastArea(remorse::LiveFixedMapItems& items,
const remorse::MapSceneRenderer& renderer, const remorse::FastAreaRange& range);
std::optional<remorse::u16> queueUsecodeTask(AppState& state, remorse::u16 classId,
remorse::u16 eventSlot, remorse::u16 sourceItem, std::vector<remorse::u8> code,
remorse::u8 itemArgumentSize = 2, std::vector<remorse::u8> extraArguments = {})
{
auto* process = state.diagnosticKernel.createUsecodeProcess(
state.diagnosticKernel.activeGroup(), state.diagnosticGroupCounts);
const remorse::u16 processId = static_cast<remorse::u16>(process->base.bytes[2] |
(static_cast<remorse::u16>(process->base.bytes[3]) << 8));
auto task = remorse::UsecodeProcessTask::create(processId, classId, eventSlot,
sourceItem, std::move(code), itemArgumentSize, std::move(extraArguments));
if (!task) {
state.diagnosticKernel.terminateProcess(processId, state.diagnosticGroupCounts);
state.diagnosticKernel.clearTerminatedProcesses();
return std::nullopt;
}
const remorse::UsecodeContextFactoryFields factoryFields{{0, 0}, itemArgumentSize,
classId, eventSlot, task->interpreter.contextParameterOffset.value_or(0)};
if (!remorse::writeUsecodeContextFactoryFields(reinterpret_cast<remorse::u8*>(process),
sizeof(*process), factoryFields) || !state.usecodeTasks.add(std::move(*task))) {
state.diagnosticKernel.terminateProcess(processId, state.diagnosticGroupCounts);
state.diagnosticKernel.clearTerminatedProcesses();
return std::nullopt;
}
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<AppState*>(context);
const remorse::u16 processId = static_cast<remorse::u16>(process.bytes[2] |
(static_cast<remorse::u16>(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<remorse::u16> {
return task->readMappedItemWord(remorse::FarPtr16{offset, segment});
};
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<remorse::u16> {
if (ordinal == 0x00 && argumentBytes == 0) {
return remorse::u16{0};
}
if (ordinal == 0xfd && argumentBytes == 2) {
const remorse::u16 keycard = static_cast<remorse::u16>(arguments[0] |
(static_cast<remorse::u16>(arguments[1]) << 8));
return static_cast<remorse::u16>(keycard < 64 &&
(app.heldKeycards & (std::uint64_t{1} << keycard)) != 0);
}
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<remorse::u16>(arguments[0] |
(static_cast<remorse::u16>(arguments[1]) << 8));
const remorse::u16 segment = static_cast<remorse::u16>(arguments[2] |
(static_cast<remorse::u16>(arguments[3]) << 8));
const auto itemNumber = task->readMappedItemWord(remorse::FarPtr16{offset, segment});
if (!itemNumber) {
return std::nullopt;
}
if (ordinal == 0xea && argumentBytes == 4) {
const auto* item = app.liveItems ? app.liveItems->findItem(*itemNumber) : nullptr;
return item ? std::optional<remorse::u16>{static_cast<remorse::u16>(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<remorse::u16>{item->data.frame} : std::nullopt;
}
if (ordinal == 0x03 && argumentBytes == 4) {
const auto* item = app.liveItems ? app.liveItems->findItem(*itemNumber) : nullptr;
return item ? std::optional<remorse::u16>{item->data.mapNumber} : std::nullopt;
}
if (ordinal == 0x59 && argumentBytes == 6) {
std::lock_guard<std::mutex> lock(app.sceneMutex);
const remorse::u8 frame = static_cast<remorse::u8>(arguments[4] |
(static_cast<remorse::u16>(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<remorse::u16> {
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<remorse::u8> 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<remorse::u16>(arguments[0] |
(static_cast<remorse::u16>(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<remorse::u16>(processId);
if (state.usecodeTasks.find(id) && state.diagnosticKernel.processAt(id) == nullptr) {
state.usecodeTasks.remove(id);
}
}
}
void loadSceneAsync(HWND window, AppState& state)
{
state.sceneThread = std::thread([window, &state]() {
@ -659,12 +867,18 @@ void paintWindow(HWND window, AppState& state)
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 (NOT RUN)"
? 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" :
@ -708,6 +922,11 @@ void updatePlayer(HWND window, AppState& state)
app.controllerMovement.handleDirectionalKey(event.scanCode, event.modifiers, event.field8 != 0);
}
}, &state);
if (state.useRequested) {
state.useRequested = false;
changed = startNearbyUsecode(state) || changed;
}
runUsecodeTasks(state);
const auto movement = state.controllerMovement.request();
state.diagnosticKernel.deliverSystemTimerEvent();
if (state.diagnostics) {
@ -724,17 +943,21 @@ void updatePlayer(HWND window, AppState& state)
[](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};
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);
@ -814,7 +1037,9 @@ void updatePlayer(HWND window, AppState& state)
avatar->data.z != beforeMove.z;
const bool hatched = moved && hatchGlobsInFastArea(
*state.liveItems, *state.renderer, remorse::calculateFastAreaRange(avatarWorld(state)));
if (state.renderThread.joinable() && (moved || hatched)) {
const bool usecodeMutation = state.usecodeWorldMutationPending;
state.usecodeWorldMutationPending = false;
if (state.renderThread.joinable() && (moved || hatched || usecodeMutation)) {
state.renderRequested = true;
state.renderWake.notify_one();
}
@ -859,6 +1084,9 @@ LRESULT CALLBACK windowProcedure(HWND window, UINT message, WPARAM wParam, LPARA
DestroyWindow(window);
return 0;
}
if (wParam == 'E' && message == WM_KEYDOWN) {
state->useRequested = true;
}
{
remorse::KeyEvent event{};
event.scanCode = static_cast<remorse::u8>((lParam >> 16) & 0xff);