Add tests for controller fire attempt suppression and usecode interpreter functionality

- Enhanced isometric_controls_tests.cpp to include assertions for controller fire attempt suppression under various conditions.
- Added tests for the Usecode interpreter in usecode_vm_tests.cpp, verifying script execution and stack manipulation.
- Introduced a new PowerShell script, clean-old-build-artifacts.ps1, to facilitate the cleanup of old build artifacts in specified directories.
This commit is contained in:
Maddo 2026-10-08 09:01:31 +02:00
commit ffb1918f35
41 changed files with 3611 additions and 349 deletions

View file

@ -1,9 +1,12 @@
#include "remorse/collision.h"
#include "remorse/animation_archive.h"
#include "remorse/entity_dispatch_entry.h"
#include "remorse/game_start.h"
#include "remorse/file_system.h"
#include "remorse/flex_archive.h"
#include "remorse/fixed_map.h"
#include "remorse/glob_archive.h"
#include "remorse/isometric_controls.h"
#include "remorse/map_renderer.h"
#include "remorse/type_flags.h"
#include "remorse/usecode_archive.h"
@ -14,6 +17,11 @@
#include <cassert>
#include <cstdint>
#include <filesystem>
#include <iostream>
#include <limits>
#include <queue>
#include <string>
#include <vector>
int main()
{
@ -360,6 +368,80 @@ int main()
integratedStartupKernel.processAt(processIdOf(integratedTimer)) == &integratedTimer->base &&
integratedStartupKernel.processAt(processIdOf(integratedKeyboard)) == &integratedKeyboard->base &&
integratedStartupKernel.processAt(processIdOf(integratedController)) == &integratedController->base);
remorse::LiveFixedMapItems freshGameWorld(*stagedItems);
remorse::ProcessKernel freshGameKernel;
remorse::u16 freshGameGroups[32]{};
for (int reservedSlot = 0; reservedSlot < 3; ++reservedSlot) {
freshGameKernel.createProcess(1, freshGameGroups);
}
auto* freshGameTimer = freshGameKernel.createSystemTimerProcess(1, freshGameGroups);
auto* freshGameKeyboard = freshGameKernel.createKeyboardProcess(1, freshGameGroups);
auto* freshGameController = freshGameKernel.createControllerProcess(1, freshGameGroups);
assert(remorse::startFreshGameMapOne(freshGameKernel, freshGameWorld, *typeFlags, freshGameGroups));
const auto* freshGameAvatar = freshGameWorld.findItem(1);
const auto* expectedLevelStart = freshGameWorld.findItem(6812);
assert(freshGameAvatar && expectedLevelStart && freshGameAvatar->data.x == expectedLevelStart->data.x &&
freshGameAvatar->data.y == expectedLevelStart->data.y && freshGameAvatar->data.z == expectedLevelStart->data.z &&
freshGameAvatar->data.mapNumber == 1 && freshGameGroups[1] == 6 && freshGameTimer &&
freshGameKeyboard && freshGameController &&
freshGameKernel.processAt(processIdOf(freshGameTimer)) == &freshGameTimer->base &&
freshGameKernel.processAt(processIdOf(freshGameKeyboard)) == &freshGameKeyboard->base &&
freshGameKernel.processAt(processIdOf(freshGameController)) == &freshGameController->base);
remorse::ControllerActorState bootTickActor;
bootTickActor.mapNumber = 1;
bootTickActor.direction = 14;
remorse::ControllerMovementState bootTickController;
bootTickController.setActorState(bootTickActor);
remorse::KeyEvent bootInput{};
bootInput.scanCode = 0x48;
bootInput.field8 = 1;
bootInput.field9 = 1;
bootInput.fieldA = 1;
assert(freshGameKernel.queuePendingKeyEvent(bootInput));
freshGameKernel.dispatchPendingKeyEvents([](remorse::EntityDispatchEntryBase& process,
remorse::u16 selector, remorse::u16 filter, remorse::KeyEvent& event, void* context) {
if (process.bytes[0] == 0xa6 && process.bytes[1] == 0x3a && selector == 0x10 && filter == 0) {
static_cast<remorse::ControllerMovementState*>(context)->handleKeyEvent(
event.scanCode, event.modifiers, event.field8, event.field9,
event.fieldA, event.field6);
}
}, &bootTickController);
const auto bootMovement = bootTickController.request();
assert(bootMovement.animation == 1 && bootMovement.direction == 14);
remorse::AnimationClip bootTickAnimation{};
bootTickAnimation.header = {17, 4, 0, 0};
bootTickAnimation.frameCount = 17;
bootTickAnimation.frames.resize(17 * 8);
auto* bootTickProcess = freshGameKernel.createAnimPrimitiveProcess(1, 1,
bootMovement.animation, bootMovement.direction,
bootTickAnimation, freshGameGroups);
const remorse::u16 bootTickProcessId = static_cast<remorse::u16>(bootTickProcess->base.bytes[2] |
(static_cast<remorse::u16>(bootTickProcess->base.bytes[3]) << 8));
assert(freshGameKernel.startAnimPrimitiveProcess(bootTickProcessId, freshGameWorld, bootTickAnimation));
struct FreshGameTickContext {
remorse::ProcessKernel& kernel;
remorse::LiveFixedMapItems& items;
const remorse::AnimationClip& clip;
const std::vector<remorse::ShapeTypeInfo>& shapes;
remorse::u16 processId;
std::optional<bool> advanced;
} freshGameTick{freshGameKernel, freshGameWorld, bootTickAnimation, *typeFlags, bootTickProcessId};
freshGameKernel.deliverSystemTimerEvent();
freshGameKernel.runTimedSchedulerPass(freshGameKernel.activeGroup(),
[](remorse::EntityDispatchEntryBase& process, void* opaque) {
auto& tick = *static_cast<FreshGameTickContext*>(opaque);
if (&process == tick.kernel.processAt(tick.processId)) {
const auto* avatar = tick.items.findItem(1);
assert(avatar);
tick.advanced = tick.kernel.advanceGroundedAnimPrimitive(tick.processId,
tick.items, tick.clip, tick.shapes,
remorse::calculateFastAreaRange({avatar->data.x * 2, avatar->data.y * 2,
avatar->data.z}));
}
}, &freshGameTick);
assert(freshGameKernel.systemTimerTick() == 1 && freshGameTick.advanced == true &&
freshGameWorld.findNpcAnimation(1)->frame == 1 &&
freshGameWorld.findItem(1)->itemNumber == 1);
const auto destinationUseCandidates = remorse::itemGrabSearchCandidates(
*integratedAvatar, integratedStartupWorld.mapItems(), *typeFlags);
assert(destinationUseCandidates);
@ -417,6 +499,530 @@ int main()
}
}
assert(eligibleMapUseItems == 218 && keycardUseItems == 10 && boxItem);
struct RankedUseTarget {
remorse::u32 distance = 0;
remorse::u16 itemNumber = 0;
remorse::u16 classId = 0;
std::string className;
};
std::vector<RankedUseTarget> rankedUseTargets;
for (const auto& item : *stagedItems) {
if (item.data.shape >= typeFlags->size()) continue;
const auto& shape = (*typeFlags)[item.data.shape];
const remorse::UsecodeItemIdentity targetIdentity{item.itemNumber, item.data.shape,
item.data.flags, item.data.quality, shape.family, false};
const auto eligible = remorse::selectEligibleUsecodeEvent(*usecode, *retailOwnerRows,
targetIdentity, remorse::UsecodeClassBases{0, 0x800, 0x900}, 0x02, 1);
if (!eligible) continue;
const remorse::s32 targetX = item.data.x;
const remorse::s32 targetY = item.data.y;
const remorse::s32 startX = integratedAvatar->data.x;
const remorse::s32 startY = integratedAvatar->data.y;
const auto absDelta = [](remorse::s32 left, remorse::s32 right) {
return left < right ? right - left : left - right;
};
rankedUseTargets.push_back({static_cast<remorse::u32>(
absDelta(targetX, startX) + absDelta(targetY, startY)), item.itemNumber,
eligible->classId, eligible->className});
}
std::sort(rankedUseTargets.begin(), rankedUseTargets.end(), [](const auto& left, const auto& right) {
return left.distance < right.distance;
});
std::cout << "Nearest map-1 use targets from destination pad:\n";
for (std::size_t index = 0; index < std::min<std::size_t>(12, rankedUseTargets.size()); ++index) {
const auto& target = rankedUseTargets[index];
const auto* item = integratedStartupWorld.findItem(target.itemNumber);
assert(item);
std::cout << " item " << target.itemNumber << " distance " << target.distance << " xy "
<< item->data.x << ',' << item->data.y << ',' << static_cast<unsigned>(item->data.z)
<< " shape/frame/quality/flags " << item->data.shape << '/' << static_cast<unsigned>(item->data.frame)
<< '/' << item->data.quality << '/' << item->data.flags << " class " << target.className
<< " (" << target.classId << ")\n";
}
constexpr remorse::s32 routeStep = 16;
constexpr remorse::s32 routeRadius = 8192;
constexpr remorse::s32 routeSide = routeRadius * 2 / routeStep + 1;
constexpr remorse::s32 routeCenter = routeRadius / routeStep;
constexpr std::size_t maximumExpandedNodes = 30000;
remorse::LiveFixedMapItems approachWorld(*stagedItems);
assert(approachWorld.initializeAvatar() && approachWorld.teleportAvatar(*levelStartEgg, 1));
const auto* approachAvatar = approachWorld.findItem(1);
assert(approachAvatar);
const remorse::StagedFixedMapItem searchOrigin = *approachAvatar;
const remorse::WorldPoint routeStart{searchOrigin.data.x, searchOrigin.data.y, searchOrigin.data.z};
std::vector<const remorse::StagedFixedMapItem*> elevationCompatibleTargets;
for (const auto& target : rankedUseTargets) {
const auto* item = approachWorld.findItem(target.itemNumber);
assert(item);
if (remorse::classifyItemFindZMatch(searchOrigin, (*typeFlags)[searchOrigin.data.shape],
*item, (*typeFlags)[item->data.shape], 3) != 0) {
elevationCompatibleTargets.push_back(item);
}
}
std::cout << "Use targets matching spawn elevation: " << elevationCompatibleTargets.size() << '\n';
for (std::size_t index = 0; index < std::min<std::size_t>(12, elevationCompatibleTargets.size()); ++index) {
const auto* item = elevationCompatibleTargets[index];
std::cout << " item " << item->itemNumber << " at " << item->data.x << ',' << item->data.y
<< ',' << static_cast<unsigned>(item->data.z) << '\n';
}
struct RouteGoalArea {
remorse::s32 minX;
remorse::s32 maxX;
remorse::s32 minY;
remorse::s32 maxY;
};
const auto& avatarShape = (*typeFlags)[searchOrigin.data.shape];
std::vector<RouteGoalArea> routeGoalAreas;
for (const auto* target : elevationCompatibleTargets) {
const auto& targetShape = (*typeFlags)[target->data.shape];
const remorse::s32 minX = std::max({static_cast<remorse::s32>(target->data.x) - 0x100,
static_cast<remorse::s32>(target->data.x) - static_cast<remorse::s32>(targetShape.x) * 16 + 1, 0});
const remorse::s32 maxX = std::min(static_cast<remorse::s32>(target->data.x) +
static_cast<remorse::s32>(avatarShape.x) * 16 - 1, 0x7fff);
const remorse::s32 minY = std::max({static_cast<remorse::s32>(target->data.y) - 0x100,
static_cast<remorse::s32>(target->data.y) - static_cast<remorse::s32>(targetShape.y) * 16 + 1, 0});
const remorse::s32 maxY = std::min(static_cast<remorse::s32>(target->data.y) +
static_cast<remorse::s32>(avatarShape.y) * 16 - 1, 0x7fff);
if (minX <= maxX && minY <= maxY) {
routeGoalAreas.push_back({minX, maxX, minY, maxY});
}
}
const auto routeCell = [&](const remorse::WorldPoint& point) {
const remorse::s32 gridX = (point.x - routeStart.x) / routeStep + routeCenter;
const remorse::s32 gridY = (point.y - routeStart.y) / routeStep + routeCenter;
assert(gridX >= 0 && gridX < routeSide && gridY >= 0 && gridY < routeSide);
return static_cast<std::size_t>(gridY * routeSide + gridX);
};
const auto pointForRouteCell = [&](int cell) {
const auto index = static_cast<std::size_t>(cell);
const remorse::s32 gridX = static_cast<remorse::s32>(index % routeSide) - routeCenter;
const remorse::s32 gridY = static_cast<remorse::s32>(index / routeSide) - routeCenter;
return remorse::WorldPoint{routeStart.x + gridX * routeStep,
routeStart.y + gridY * routeStep, routeStart.z};
};
const auto distanceToRange = [](remorse::s32 value, remorse::s32 minimum, remorse::s32 maximum) {
return value < minimum ? minimum - value : value > maximum ? value - maximum : 0;
};
const auto routeHeuristic = [&](const remorse::WorldPoint& point) {
remorse::s32 bestDistance = std::numeric_limits<remorse::s32>::max();
for (const auto& area : routeGoalAreas) {
const remorse::s32 distance = distanceToRange(point.x, area.minX, area.maxX) +
distanceToRange(point.y, area.minY, area.maxY);
bestDistance = std::min(bestDistance, (distance + routeStep - 1) / routeStep);
}
return bestDistance == std::numeric_limits<remorse::s32>::max() ? 0 : bestDistance;
};
struct RouteOpenEntry {
remorse::s32 estimate;
remorse::s32 distance;
int cell;
};
struct RouteOpenOrder {
bool operator()(const RouteOpenEntry& left, const RouteOpenEntry& right) const
{
if (left.estimate != right.estimate) return left.estimate > right.estimate;
return left.distance < right.distance;
}
};
const std::size_t routeCellCount = static_cast<std::size_t>(routeSide * routeSide);
std::vector<int> routeDistances(routeCellCount, std::numeric_limits<int>::max());
std::vector<int> routeParents(routeCellCount, -2);
const int startCell = static_cast<int>(routeCell(routeStart));
routeDistances[static_cast<std::size_t>(startCell)] = 0;
routeParents[static_cast<std::size_t>(startCell)] = -1;
std::priority_queue<RouteOpenEntry, std::vector<RouteOpenEntry>, RouteOpenOrder> openRoutes;
openRoutes.push({routeHeuristic(routeStart), 0, startCell});
int targetCell = -1;
remorse::u16 approachTargetItem = 0;
std::size_t expandedNodes = 0;
constexpr std::array<std::pair<remorse::s32, remorse::s32>, 4> routeDirections{{
{routeStep, 0}, {-routeStep, 0}, {0, routeStep}, {0, -routeStep}}};
while (!openRoutes.empty() && targetCell < 0 && expandedNodes < maximumExpandedNodes) {
const RouteOpenEntry entry = openRoutes.top();
openRoutes.pop();
const std::size_t currentCellIndex = static_cast<std::size_t>(entry.cell);
if (entry.distance != routeDistances[currentCellIndex]) continue;
++expandedNodes;
const remorse::WorldPoint current = pointForRouteCell(entry.cell);
remorse::StagedFixedMapItem currentOrigin = searchOrigin;
currentOrigin.data.x = static_cast<remorse::u16>(current.x);
currentOrigin.data.y = static_cast<remorse::u16>(current.y);
const auto& originShape = (*typeFlags)[currentOrigin.data.shape];
const auto interactionArea = remorse::itemFindAreaAroundItem(currentOrigin, originShape);
const auto targetCandidate = std::find_if(elevationCompatibleTargets.begin(),
elevationCompatibleTargets.end(), [&](const auto* candidate) {
return candidate->data.x >= interactionArea.minX && candidate->data.x <= interactionArea.maxX &&
candidate->data.y >= interactionArea.minY && candidate->data.y <= interactionArea.maxY &&
remorse::classifyItemFindZMatch(currentOrigin, originShape, *candidate,
(*typeFlags)[candidate->data.shape], 3) != 0;
});
if (targetCandidate != elevationCompatibleTargets.end()) {
approachTargetItem = (*targetCandidate)->itemNumber;
targetCell = entry.cell;
break;
}
assert(approachWorld.moveItem(1, static_cast<remorse::u16>(current.x),
static_cast<remorse::u16>(current.y), static_cast<remorse::u8>(current.z)));
for (const auto [deltaX, deltaY] : routeDirections) {
const remorse::WorldPoint destination{current.x + deltaX, current.y + deltaY, current.z};
if (destination.x < 0 || destination.x > 0x7fff || destination.y < 0 || destination.y > 0x7fff ||
destination.x < routeStart.x - routeRadius || destination.x > routeStart.x + routeRadius ||
destination.y < routeStart.y - routeRadius || destination.y > routeStart.y + routeRadius) {
continue;
}
const std::size_t cell = routeCell(destination);
const int nextDistance = entry.distance + 1;
if (nextDistance >= routeDistances[cell]) continue;
const auto sweep = remorse::resolveSolidLiveSweep(approachWorld, 1, destination,
*typeFlags, remorse::calculateFastAreaRange(current));
if (!sweep || sweep->failed || sweep->failedDirections != 0 ||
sweep->destination.x != destination.x || sweep->destination.y != destination.y ||
sweep->destination.z != destination.z) {
continue;
}
routeDistances[cell] = nextDistance;
routeParents[cell] = entry.cell;
openRoutes.push({nextDistance + routeHeuristic(destination), nextDistance,
static_cast<int>(cell)});
}
}
std::cout << "Route search expanded " << expandedNodes << " nodes\n";
assert(targetCell >= 0);
std::vector<remorse::WorldPoint> approachRoute;
for (int cell = targetCell; cell >= 0;) {
approachRoute.push_back(pointForRouteCell(cell));
cell = routeParents[static_cast<std::size_t>(cell)];
}
std::reverse(approachRoute.begin(), approachRoute.end());
const remorse::u16 routeGoalItem = approachTargetItem;
assert(approachWorld.teleportAvatar(*levelStartEgg, 1));
for (std::size_t index = 1; index < approachRoute.size(); ++index) {
const auto& current = approachRoute[index - 1];
const auto& destination = approachRoute[index];
const auto sweep = remorse::resolveSolidLiveSweep(approachWorld, 1, destination,
*typeFlags, remorse::calculateFastAreaRange(current));
assert(sweep && !sweep->failed && sweep->failedDirections == 0 &&
sweep->destination.x == destination.x && sweep->destination.y == destination.y &&
sweep->destination.z == destination.z);
assert(approachWorld.moveItem(1, static_cast<remorse::u16>(destination.x),
static_cast<remorse::u16>(destination.y), static_cast<remorse::u8>(destination.z)));
}
const auto* endpointAvatar = approachWorld.findItem(1);
assert(endpointAvatar);
const auto endpointCandidates = remorse::itemGrabSearchCandidates(*endpointAvatar,
approachWorld.mapItems(), *typeFlags);
assert(endpointCandidates && std::any_of(endpointCandidates->begin(), endpointCandidates->end(),
[&](const auto& candidate) { return candidate.itemNumber == routeGoalItem; }));
std::optional<remorse::EligibleUsecodeEvent> approachEvent;
approachTargetItem = 0;
for (const auto& candidate : *endpointCandidates) {
const auto* item = approachWorld.findItem(candidate.itemNumber);
if (item == nullptr || item->data.shape >= typeFlags->size()) continue;
const auto& shape = (*typeFlags)[item->data.shape];
const remorse::UsecodeItemIdentity interactionIdentity{item->itemNumber, item->data.shape,
item->data.flags, item->data.quality, shape.family, false};
auto eligible = remorse::selectEligibleUsecodeEvent(*usecode, *retailOwnerRows,
interactionIdentity, remorse::UsecodeClassBases{0, 0x800, 0x900}, 0x02, 1);
if (eligible) {
approachTargetItem = item->itemNumber;
approachEvent = std::move(*eligible);
break;
}
}
assert(approachEvent);
const auto* approachTarget = approachWorld.findItem(approachTargetItem);
assert(approachTarget);
auto targetRenderer = remorse::loadMapSceneRenderer(*root, 1);
assert(targetRenderer);
remorse::MapRenderOptions targetRenderOptions;
targetRenderOptions.mapIndex = 1;
targetRenderOptions.maxWidth = 320;
targetRenderOptions.maxHeight = 200;
const remorse::WorldPoint targetWorldLocation{approachTarget->data.x * 2,
approachTarget->data.y * 2, approachTarget->data.z};
targetRenderOptions.viewCenter = targetWorldLocation;
targetRenderOptions.worldRect = remorse::WorldRect{targetWorldLocation.x - 1,
targetWorldLocation.y - 1, targetWorldLocation.x + 1, targetWorldLocation.y + 1};
const auto targetBefore = targetRenderer->render(targetRenderOptions, &approachWorld);
assert(targetBefore);
const remorse::u16 originalTargetShape = approachTarget->data.shape;
const remorse::u8 originalTargetFrame = approachTarget->data.frame;
constexpr remorse::u16 interactionProcessId = 0x0340;
remorse::UsecodeTaskRegistry interactionTasks;
auto interactionContext = remorse::createUsecodeEventContext(interactionTasks.runtimeMemory(),
*retailOwnerRows, approachEvent->classId, 1, approachTargetItem, approachEvent->body.bytes, 2);
auto interactionTaskValue = remorse::UsecodeProcessTask::create(interactionProcessId,
approachEvent->classId, 1, approachTargetItem, approachEvent->body.bytes, 2);
assert(interactionContext && interactionTaskValue);
const std::vector<remorse::u8> interactionProcessIdBytes{0x40, 0x03};
assert(interactionTasks.runtimeMemory().write(interactionContext->processIdOutput,
interactionProcessIdBytes));
assert(interactionTasks.addWithContext(std::move(*interactionTaskValue), std::move(*interactionContext)));
auto* interactionTask = interactionTasks.find(interactionProcessId);
assert(interactionTask);
remorse::UsecodeOpcodeServices interactionServices;
interactionServices.readFarWord = [interactionTask](remorse::u16 offset, remorse::u16 segment)
-> std::optional<remorse::u16> {
return interactionTask->readMappedFarWord(remorse::FarPtr16{offset, segment});
};
interactionServices.setInfo = [](remorse::u16, remorse::u16) { return true; };
interactionServices.processCount = []() { return remorse::u16{2}; };
interactionServices.currentProcessId = []() { return interactionProcessId; };
std::optional<std::pair<remorse::u16, remorse::u16>> rejectedEvent;
interactionServices.callEvent = [&usecode, interactionTask, &rejectedEvent](
remorse::u16 classId, remorse::u16 eventSlot)
-> std::optional<remorse::UsecodeEventBody> {
std::cout << "Nested event call from " << interactionTask->classId << '/'
<< interactionTask->eventSlot << " pc " << interactionTask->programCounter
<< " BP " << interactionTask->frameBaseOffset << " stack "
<< interactionTask->interpreter.stackTop << ':';
for (std::size_t index = interactionTask->interpreter.stackTop;
index < std::min(interactionTask->interpreter.valueStack.size(),
interactionTask->interpreter.stackTop + 12); ++index) {
std::cout << ' ' << static_cast<unsigned>(interactionTask->interpreter.valueStack[index]);
}
std::cout << " frame:";
for (std::size_t index = 0x30; index < 0x50; ++index) {
std::cout << ' ' << static_cast<unsigned>(interactionTask->frame[index]);
}
std::cout << '\n';
const auto usecodeClass = remorse::loadUsecodeClass(*usecode, classId);
auto body = usecodeClass
? remorse::readUsecodeEventBody(*usecodeClass, eventSlot) : std::nullopt;
if (!body) rejectedEvent = std::pair{classId, eventSlot};
return body;
};
remorse::u16 nextInteractionChildId = 0x0350;
std::vector<std::pair<remorse::u16, remorse::u16>> spawnedInteractionEvents;
std::optional<std::pair<remorse::u16, remorse::u16>> rejectedSpawn;
interactionServices.spawn = [&usecode, &nextInteractionChildId, &spawnedInteractionEvents,
&rejectedSpawn](remorse::u16 classId,
remorse::u16 eventSlot, remorse::u8, remorse::u8, remorse::u16, const remorse::u8*)
-> std::optional<remorse::u16> {
const auto usecodeClass = remorse::loadUsecodeClass(*usecode, classId);
const auto body = usecodeClass
? remorse::readUsecodeEventBody(*usecodeClass, eventSlot) : std::nullopt;
if (!body) {
rejectedSpawn = std::pair{classId, eventSlot};
return std::nullopt;
}
spawnedInteractionEvents.emplace_back(classId, eventSlot);
return nextInteractionChildId++;
};
std::optional<remorse::u16> rejectedIntrinsic;
std::vector<std::pair<remorse::u16, remorse::u8>> interactionIntrinsics;
std::vector<std::pair<remorse::u16, remorse::u16>> queriedShapeFamilies;
std::vector<std::pair<remorse::u16, remorse::u16>> queriedItemFamilies;
interactionServices.callIntrinsic = [interactionTask, &approachWorld, &typeFlags,
&rejectedIntrinsic, &interactionIntrinsics, &queriedShapeFamilies,
&queriedItemFamilies](
remorse::u16 ordinal, remorse::u8 argumentBytes, const remorse::u8* arguments)
-> std::optional<remorse::u16> {
interactionIntrinsics.emplace_back(ordinal, argumentBytes);
if (ordinal == 0x00 && argumentBytes == 0) return remorse::u16{0};
if (ordinal == 0xfd && argumentBytes == 2) return remorse::u16{0};
if (ordinal == 0xac && argumentBytes == 2) {
const remorse::u16 shape = static_cast<remorse::u16>(arguments[0] |
(static_cast<remorse::u16>(arguments[1]) << 8));
if (shape >= typeFlags->size()) return std::nullopt;
const remorse::u16 family = (*typeFlags)[shape].family;
queriedShapeFamilies.emplace_back(shape, family);
return family;
}
if ((ordinal == 0x15 || ordinal == 0x3a) && argumentBytes == 6) return remorse::u16{0};
if (argumentBytes < 4) {
rejectedIntrinsic = ordinal;
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));
if (ordinal == 0x0a && argumentBytes == 4) {
const auto itemNumber = interactionTask->readMappedFarWord(remorse::FarPtr16{offset, segment});
if (itemNumber) approachWorld.destroyItem(*itemNumber);
return remorse::u16{0};
}
if (ordinal == 0x30 && argumentBytes == 4) {
return approachWorld.popItemFromEtherealVoid().value_or(0);
}
if (ordinal == 0x20 && argumentBytes == 10) {
const remorse::u16 x = static_cast<remorse::u16>(arguments[4] |
(static_cast<remorse::u16>(arguments[5]) << 8));
const remorse::u16 y = static_cast<remorse::u16>(arguments[6] |
(static_cast<remorse::u16>(arguments[7]) << 8));
return approachWorld.popItemToCoords(x, y, arguments[8]).value_or(0);
}
if (ordinal == 0x19 && argumentBytes == 14) {
const remorse::u16 shape = static_cast<remorse::u16>(arguments[4] |
(static_cast<remorse::u16>(arguments[5]) << 8));
const remorse::u16 frame = static_cast<remorse::u16>(arguments[6] |
(static_cast<remorse::u16>(arguments[7]) << 8));
const remorse::u16 x = static_cast<remorse::u16>(arguments[8] |
(static_cast<remorse::u16>(arguments[9]) << 8));
const remorse::u16 y = static_cast<remorse::u16>(arguments[10] |
(static_cast<remorse::u16>(arguments[11]) << 8));
const remorse::u8 z = arguments[12];
const bool legalPosition = frame <= 0xff &&
approachWorld.canCreateItemAt(shape, x, y, z, *typeFlags);
if (!legalPosition) {
return remorse::u16{0};
}
remorse::StagedFixedMapItem createdItem;
createdItem.recordIndex = static_cast<std::size_t>(-1);
createdItem.data.x = x;
createdItem.data.y = y;
createdItem.data.z = z;
createdItem.data.shape = shape;
createdItem.data.frame = static_cast<remorse::u8>(frame);
const auto itemNumber = approachWorld.allocateItem(createdItem);
if (!itemNumber || !interactionTask->writeMappedFarWord(
remorse::FarPtr16{offset, segment}, *itemNumber)) {
return remorse::u16{0};
}
return remorse::u16{1};
}
const auto itemNumber = interactionTask->readMappedFarWord(remorse::FarPtr16{offset, segment});
if (ordinal == 0x10 && argumentBytes == 4) {
const auto* item = itemNumber ? approachWorld.findItem(*itemNumber) : nullptr;
return item ? static_cast<remorse::u16>(item->data.quality & 0xff) : remorse::u16{0};
}
if (!itemNumber) return std::nullopt;
const auto* item = approachWorld.findItem(*itemNumber);
if (ordinal == 0x3c && argumentBytes == 4 && item && item->data.shape < typeFlags->size()) {
const remorse::u16 family = (*typeFlags)[item->data.shape].family;
queriedItemFamilies.emplace_back(*itemNumber, family);
return family;
}
if (ordinal == 0x22 && argumentBytes == 4 && item) {
return approachWorld.pushItemToEtherealVoid(*itemNumber)
? std::optional<remorse::u16>{remorse::u16{0}} : std::nullopt;
}
if (ordinal == 0x25) return remorse::u16{0};
if (ordinal == 0xea && argumentBytes == 4 && item) {
return static_cast<remorse::u16>(item->data.quality & 0xff);
}
if (ordinal == 0x01 && argumentBytes == 4 && item) return item->data.frame;
if (ordinal == 0x03 && argumentBytes == 4 && item) return item->data.mapNumber;
if (ordinal == 0x09 && argumentBytes == 4 && item) return item->data.z;
if (ordinal == 0x13 && argumentBytes == 4 && item) return item->data.x;
if (ordinal == 0x14 && argumentBytes == 4 && item) return item->data.y;
if (ordinal == 0x24 && argumentBytes == 6) {
const remorse::u16 shape = static_cast<remorse::u16>(arguments[4] |
(static_cast<remorse::u16>(arguments[5]) << 8));
return approachWorld.setItemShape(*itemNumber, shape)
? std::optional<remorse::u16>{remorse::u16{0}} : std::nullopt;
}
if ((ordinal == 0x02 || ordinal == 0x59) && argumentBytes == 6) {
const remorse::u8 frame = static_cast<remorse::u8>(arguments[4] |
(static_cast<remorse::u16>(arguments[5]) << 8));
return approachWorld.setItemFrame(*itemNumber, frame)
? std::optional<remorse::u16>{remorse::u16{0}} : std::nullopt;
}
rejectedIntrinsic = ordinal;
return std::nullopt;
};
remorse::UsecodeStepResult lastInteractionResult = remorse::UsecodeStepResult::Advanced;
bool interactionStoppedOnError = false;
bool reachedInteractionMilestone = false;
bool targetVisualChanged = false;
const remorse::u16 originalTargetFlags = approachTarget->data.flags;
const std::size_t originalWorldItemCount = approachWorld.mapItems().size();
const auto targetRenderHasChanged = [&]() {
const auto image = targetRenderer->render(targetRenderOptions, &approachWorld);
return image && image->pixels.size() == targetBefore->pixels.size() &&
!std::equal(targetBefore->pixels.begin(), targetBefore->pixels.end(), image->pixels.begin(),
image->pixels.end(), [](const auto& left, const auto& right) {
return left.red == right.red && left.green == right.green && left.blue == right.blue;
});
};
for (unsigned tick = 0; tick < 8 && !reachedInteractionMilestone && !interactionTask->halted &&
!interactionStoppedOnError; ++tick) {
interactionTask->interpreter.impliedProcessId = 0;
for (unsigned instruction = 0; instruction < 256; ++instruction) {
lastInteractionResult = interactionTask->step(interactionServices);
const auto* item = approachWorld.findItem(approachTargetItem);
targetVisualChanged = !item || item->data.shape != originalTargetShape ||
item->data.frame != originalTargetFrame;
if (lastInteractionResult == remorse::UsecodeStepResult::Advanced ||
lastInteractionResult == remorse::UsecodeStepResult::SetInfo ||
lastInteractionResult == remorse::UsecodeStepResult::Spawned) {
if (!spawnedInteractionEvents.empty() && targetRenderHasChanged()) {
targetVisualChanged = true;
reachedInteractionMilestone = true;
break;
}
continue;
}
if (lastInteractionResult != remorse::UsecodeStepResult::Yielded &&
lastInteractionResult != remorse::UsecodeStepResult::Returned) {
interactionStoppedOnError = true;
}
break;
}
}
const auto* finalInteractionTarget = approachWorld.findItem(approachTargetItem);
targetVisualChanged = targetVisualChanged || finalInteractionTarget == nullptr ||
finalInteractionTarget->data.shape != originalTargetShape ||
finalInteractionTarget->data.frame != originalTargetFrame ||
finalInteractionTarget->data.flags != originalTargetFlags ||
approachWorld.mapItems().size() != originalWorldItemCount;
std::cout << "Reachable target use event: class " << approachEvent->className << " ("
<< approachEvent->classId << ") shape/frame " << originalTargetShape << '/'
<< static_cast<unsigned>(originalTargetFrame) << " body bytes " << approachEvent->body.bytes.size()
<< " VM result " << static_cast<unsigned>(lastInteractionResult) << " PC "
<< interactionTask->programCounter << " class/event " << interactionTask->classId << '/'
<< interactionTask->eventSlot << " call depth " << interactionTask->routineFrames.size()
<< " rejected intrinsic " << rejectedIntrinsic.value_or(0xffff) << " rejected event "
<< (rejectedEvent ? rejectedEvent->first : 0xffff) << '/'
<< (rejectedEvent ? rejectedEvent->second : 0xffff) << " rejected spawn "
<< (rejectedSpawn ? rejectedSpawn->first : 0xffff) << '/'
<< (rejectedSpawn ? rejectedSpawn->second : 0xffff) << " spawned "
<< spawnedInteractionEvents.size() << " changed " << targetVisualChanged << '\n';
std::cout << "Selected target item " << approachTargetItem << " quality/flags "
<< (finalInteractionTarget ? finalInteractionTarget->data.quality : 0) << '/'
<< (finalInteractionTarget ? finalInteractionTarget->data.flags : 0) << '\n';
for (const auto& [classId, eventSlot] : spawnedInteractionEvents) {
std::cout << " spawned usecode " << classId << '/' << eventSlot << '\n';
}
std::cout << "Executed intrinsics:";
for (const auto& [ordinal, argumentBytes] : interactionIntrinsics) {
std::cout << ' ' << ordinal << '/' << static_cast<unsigned>(argumentBytes);
}
std::cout << '\n';
for (const auto& [shape, family] : queriedShapeFamilies) {
std::cout << " shape family " << shape << '=' << family << '\n';
}
for (const auto& [itemNumber, family] : queriedItemFamilies) {
std::cout << " item family " << itemNumber << '=' << family << '\n';
}
if (lastInteractionResult == remorse::UsecodeStepResult::UnsupportedOpcode) {
const std::size_t windowStart = interactionTask->programCounter > 4
? interactionTask->programCounter - 4 : remorse::usecodeEventBytecodeOffset;
const std::size_t windowEnd = std::min(interactionTask->code.size(),
interactionTask->programCounter + 8);
std::cout << "Unsupported usecode bytes:";
for (std::size_t index = windowStart; index < windowEnd; ++index) {
std::cout << ' ' << index << ':' << static_cast<unsigned>(interactionTask->code[index]);
}
std::cout << '\n';
}
assert(reachedInteractionMilestone && targetVisualChanged && !interactionStoppedOnError);
const auto targetAfter = targetRenderer->render(targetRenderOptions, &approachWorld);
assert(targetAfter && targetBefore->pixels.size() == targetAfter->pixels.size());
const bool targetPixelsChanged = !std::equal(targetBefore->pixels.begin(), targetBefore->pixels.end(),
targetAfter->pixels.begin(), targetAfter->pixels.end(), [](const auto& left, const auto& right) {
return left.red == right.red && left.green == right.green && left.blue == right.blue;
});
assert(targetPixelsChanged);
std::cout << "Visible target mutation: shape/frame "
<< (finalInteractionTarget ? finalInteractionTarget->data.shape : 0xffff) << '/'
<< (finalInteractionTarget ? static_cast<unsigned>(finalInteractionTarget->data.frame) : 0xff)
<< " pixels changed " << targetPixelsChanged << '\n';
std::cout << "Reachable target Item_Grab route: item " << approachTargetItem
<< " steps " << approachRoute.size() - 1 << " expanded " << expandedNodes << " endpoint "
<< approachRoute.back().x
<< ',' << approachRoute.back().y << ',' << approachRoute.back().z << '\n';
const auto globPath = remorse::resolveGameDataPath(*root, std::filesystem::path("STATIC") / "GLOB.FLX");
const auto globs = globPath ? remorse::loadGlobObjects(*globPath) : std::nullopt;
assert(globs);