Enhance teleporter and map rendering tests

- Added initialization of startup processes in flex_archive_tests to ensure proper setup before teleporter operations.
- Updated assertions to verify the correct allocation and state of processes during teleporter execution.
- Introduced new tests in map_renderer_tests to validate shape rendering, including isolated shape rendering and player sprite integration.
- Enhanced map_sorter_tests with additional checks for occlusion handling and boundary conditions in render order resolution.
This commit is contained in:
Maddo 2026-10-06 21:07:35 +02:00
commit e00f9f3186
16 changed files with 954 additions and 398 deletions

View file

@ -36,7 +36,6 @@ struct RenderSortItem {
bool translucent = false;
bool animated = false;
bool land = false;
bool sprite = false;
bool inventoryItem = false;
};

View file

@ -224,6 +224,10 @@ private:
bool markNewProcesses_ = false;
};
bool runFreshGameTeleporterStartup(ProcessKernel& kernel, LiveFixedMapItems& items,
u16 mapNumber, u16 teleportId, const std::vector<ShapeTypeInfo>& shapes,
u16 (&groupCounts)[32]);
class EntityDispatchEntry {
public:
static constexpr u16 initBaseSegment = 0x11e0;

View file

@ -81,6 +81,9 @@ std::optional<FixedMap> loadFixedMap(const FixedMapArchive& archive, u32 mapInde
std::optional<std::vector<StagedFixedMapItem>> stageFixedMapItems(const FixedMap& map);
std::optional<StagedFixedMapItem> findTeleportEgg(
const std::vector<StagedFixedMapItem>& items, const std::vector<ShapeTypeInfo>& shapes, u8 eggId);
std::optional<StagedFixedMapItem> findNearbyActiveTeleportEgg(const StagedFixedMapItem& origin,
const std::vector<StagedFixedMapItem>& items, const std::vector<ShapeTypeInfo>& shapes,
u8 currentMapNumber);
std::optional<std::vector<StagedContainedFixedMapItem>> stageContainedFixedMapItems(
const FixedMap& map, const std::vector<ShapeTypeInfo>& shapes);
std::optional<StagedFixedMapItem> nearestStagedFixedMapItem(

View file

@ -31,6 +31,15 @@ struct WorldPoint {
s32 z = 0;
};
struct MapRenderSprite {
WorldPoint position;
u16 shape = 0;
u8 frame = 0;
bool flipped = false;
const DecodedShapeFrame* decoded = nullptr;
const Palette256* palette = nullptr;
};
struct ScreenPoint {
s32 x = 0;
s32 y = 0;
@ -59,6 +68,7 @@ struct RenderedMapImage {
s32 fullWidth = 0;
s32 fullHeight = 0;
std::vector<RgbColor> pixels;
std::vector<u8> coverage;
};
struct MapSceneRenderer {
@ -70,7 +80,7 @@ struct MapSceneRenderer {
std::map<std::pair<u32, u32>, DecodedShapeFrame> decodedFrames;
std::optional<RenderedMapImage> render(const MapRenderOptions& options,
const LiveFixedMapItems* liveItems = nullptr);
const LiveFixedMapItems* liveItems = nullptr, const MapRenderSprite* sprite = nullptr);
};
std::optional<MapSceneRenderer> loadMapSceneRenderer(const GameDataRoot& root, u32 mapIndex);

View file

@ -270,6 +270,48 @@ bool ProcessKernel::runClearAvatarInStasisProcess(u16 processId, bool& avatarInS
return true;
}
bool runFreshGameTeleporterStartup(ProcessKernel& kernel, LiveFixedMapItems& items,
u16 mapNumber, u16 teleportId, const std::vector<ShapeTypeInfo>& shapes,
u16 (&groupCounts)[32])
{
const u8 activeGroup = kernel.activeGroup();
bool avatarInStasis = false;
auto* teleporter = kernel.createTeleporterProcess(activeGroup, mapNumber, teleportId,
groupCounts, true, false, avatarInStasis);
const u16 teleporterId = readLe16(teleporter->base, 0x02);
struct StartupContext {
ProcessKernel& kernel;
LiveFixedMapItems& items;
const std::vector<ShapeTypeInfo>& shapes;
u16 (&groupCounts)[32];
bool& avatarInStasis;
u16 mapNumber;
bool teleported = false;
} startup{kernel, items, shapes, groupCounts, avatarInStasis, mapNumber};
const auto runStartupProcess = [](EntityDispatchEntryBase& entry, void* opaque) {
auto& context = *static_cast<StartupContext*>(opaque);
const u16 processId = readLe16(entry, 0x02);
if (processId < 3) {
return;
}
const u16 vtable = readLe16(entry, 0x00);
if (vtable == ClearAvatarInStasisProcess::vtableOffset) {
context.kernel.runClearAvatarInStasisProcess(processId,
context.avatarInStasis, context.groupCounts);
} else if (vtable == TeleporterProcess::vtableOffset) {
const auto& process = *reinterpret_cast<TeleporterProcessEntry*>(&entry);
context.teleported = TeleporterProcess::run(process, context.items,
context.mapNumber, context.shapes);
entry.bytes[0x18] |= 4;
context.kernel.terminateProcess(processId, context.groupCounts);
}
};
for (unsigned pass = 0; pass < 2 && kernel.processAt(teleporterId) != nullptr; ++pass) {
kernel.scanRunnableProcesses(activeGroup, runStartupProcess, &startup);
}
return startup.teleported && !avatarInStasis && kernel.processAt(teleporterId) == nullptr;
}
EntityVmContextProcessEntry* ProcessKernel::createUsecodeProcess(u8 activeGroup,
u16 (&groupCounts)[32])
{

View file

@ -171,6 +171,28 @@ std::optional<StagedFixedMapItem> findTeleportEgg(
return match;
}
std::optional<StagedFixedMapItem> findNearbyActiveTeleportEgg(const StagedFixedMapItem& origin,
const std::vector<StagedFixedMapItem>& items, const std::vector<ShapeTypeInfo>& shapes,
u8 currentMapNumber)
{
for (const auto& item : items) {
if (item.data.shape >= shapes.size() || shapes[item.data.shape].family != 8 ||
item.data.frame == 1 || item.data.mapNumber != currentMapNumber) {
continue;
}
const s32 xRange = static_cast<s32>((item.data.npcNumber >> 4) & 0x0f) * 64;
const s32 yRange = static_cast<s32>(item.data.npcNumber & 0x0f) * 64;
const s32 deltaX = static_cast<s32>(origin.data.x) - item.data.x;
const s32 deltaY = static_cast<s32>(origin.data.y) - item.data.y;
const s32 deltaZ = static_cast<s32>(origin.data.z) - item.data.z;
if (deltaX >= -xRange && deltaX <= xRange && deltaY >= -yRange && deltaY <= yRange &&
deltaZ >= -48 && deltaZ <= 48) {
return item;
}
}
return std::nullopt;
}
std::optional<std::vector<StagedContainedFixedMapItem>> stageContainedFixedMapItems(
const FixedMap& map, const std::vector<ShapeTypeInfo>& shapes)
{

View file

@ -35,11 +35,14 @@ struct SceneItem {
u16 quality = 0;
u8 mapNumber = 0;
bool fromFixed = true;
const DecodedShapeFrame* decodedOverride = nullptr;
const Palette256* paletteOverride = nullptr;
};
struct RenderNode {
SceneItem item;
const DecodedShapeFrame* decoded = nullptr;
const Palette256* paletteOverride = nullptr;
s32 left = 0;
s32 top = 0;
s32 right = 0;
@ -208,7 +211,8 @@ std::vector<RenderNode> prepareRenderNodes(
nodes.reserve(items.size());
sortItems.reserve(items.size());
for (const SceneItem& item : items) {
const auto* decoded = cachedDecode(shapeArchive, cache, item.shape, item.frame);
const auto* decoded = item.decodedOverride != nullptr
? item.decodedOverride : cachedDecode(shapeArchive, cache, item.shape, item.frame);
if (!decoded) {
continue;
}
@ -219,6 +223,7 @@ std::vector<RenderNode> prepareRenderNodes(
RenderNode node;
node.item = item;
node.decoded = decoded;
node.paletteOverride = item.paletteOverride;
node.left = flipped
? bottomX + decoded->frame.xOffset - static_cast<s32>(decoded->frame.width)
: bottomX - decoded->frame.xOffset;
@ -275,6 +280,7 @@ std::vector<RenderNode> prepareRenderNodes(
void paintNode(RenderedMapImage& image, const RenderNode& node, const Palette256& palette)
{
const Palette256& nodePalette = node.paletteOverride != nullptr ? *node.paletteOverride : palette;
const bool flipped = (node.item.flags & flagFlipped) != 0;
for (u32 sourceY = 0; sourceY < node.decoded->frame.height; ++sourceY) {
const s32 destY = node.top - image.sourceTop + static_cast<s32>(sourceY);
@ -292,7 +298,9 @@ void paintNode(RenderedMapImage& image, const RenderNode& node, const Palette256
if (destX < 0 || destX >= static_cast<s32>(image.width)) {
continue;
}
image.pixels[static_cast<std::size_t>(destY) * image.width + destX] = scalePaletteColor(palette.colors[colorIndex]);
const std::size_t pixelIndex = static_cast<std::size_t>(destY) * image.width + destX;
image.pixels[pixelIndex] = scalePaletteColor(nodePalette.colors[colorIndex]);
image.coverage[pixelIndex] = 1;
}
}
}
@ -343,9 +351,26 @@ std::optional<MapSceneRenderer> loadMapSceneRenderer(const GameDataRoot& root, u
}
std::optional<RenderedMapImage> MapSceneRenderer::render(const MapRenderOptions& options,
const LiveFixedMapItems* liveItems)
const LiveFixedMapItems* liveItems, const MapRenderSprite* sprite)
{
const auto items = collectSceneItems(map, typeFlags, globs, options, liveItems);
auto items = collectSceneItems(map, typeFlags, globs, options, liveItems);
if (sprite != nullptr && sprite->decoded != nullptr && sprite->palette != nullptr &&
sprite->shape < typeFlags.size()) {
SceneItem sceneSprite;
sceneSprite.x = sprite->position.x;
sceneSprite.y = sprite->position.y;
sceneSprite.z = sprite->position.z;
sceneSprite.shape = sprite->shape;
sceneSprite.frame = sprite->frame;
sceneSprite.flags = sprite->flipped ? flagFlipped : 0;
sceneSprite.mapNumber = static_cast<u8>(options.mapIndex);
sceneSprite.fromFixed = false;
sceneSprite.decodedOverride = sprite->decoded;
sceneSprite.paletteOverride = sprite->palette;
if (inWorldRect(sceneSprite, options.worldRect)) {
items.push_back(sceneSprite);
}
}
auto nodes = prepareRenderNodes(items, shapes, typeFlags, decodedFrames);
if (nodes.empty()) {
return std::nullopt;
@ -385,6 +410,7 @@ std::optional<RenderedMapImage> MapSceneRenderer::render(const MapRenderOptions&
image.pixels.assign(
static_cast<std::size_t>(image.width) * image.height,
RgbColor{static_cast<u8>(10), static_cast<u8>(12), static_cast<u8>(18)});
image.coverage.assign(image.pixels.size(), 0);
for (const RenderNode& node : nodes) {
if (node.right < image.sourceLeft || node.bottom < image.sourceTop ||

View file

@ -1,6 +1,9 @@
#include "remorse/detail/map_sorter.h"
#include <algorithm>
#include <cstdint>
#include <set>
#include <unordered_map>
namespace remorse {
namespace detail {
@ -13,11 +16,22 @@ struct SortNode {
s32 order = -1;
};
constexpr s32 spatialCellSize = 128;
s32 spatialCell(s32 coordinate)
{
const s32 quotient = coordinate / spatialCellSize;
return coordinate % spatialCellSize < 0 ? quotient - 1 : quotient;
}
std::uint64_t spatialKey(s32 x, s32 y)
{
return (static_cast<std::uint64_t>(static_cast<std::uint32_t>(x)) << 32) |
static_cast<std::uint32_t>(y);
}
bool listLessThan(const RenderSortItem& left, const RenderSortItem& right)
{
if (left.sprite != right.sprite) {
return left.sprite < right.sprite;
}
if (left.z != right.z) {
return left.z < right.z;
}
@ -77,10 +91,6 @@ bool occludes(const RenderSortItem& outer, const RenderSortItem& inner)
bool below(const RenderSortItem& left, const RenderSortItem& right)
{
if (left.sprite != right.sprite) {
return left.sprite < right.sprite;
}
if (left.flat && right.flat) {
if (left.z != right.z) {
return left.z < right.z;
@ -256,15 +266,49 @@ std::vector<std::size_t> resolveRenderOrder(const std::vector<RenderSortItem>& i
nodes.push_back(SortNode{item, {}, false, -1});
}
std::vector<std::size_t> ordered;
ordered.reserve(nodes.size());
const auto indexLessThan = [&nodes](std::size_t left, std::size_t right) {
if (listLessThan(nodes[left].item, nodes[right].item)) {
return true;
}
if (listLessThan(nodes[right].item, nodes[left].item)) {
return false;
}
return left < right;
};
std::set<std::size_t, decltype(indexLessThan)> ordered(indexLessThan);
std::unordered_map<std::uint64_t, std::vector<std::size_t>> spatialBuckets;
spatialBuckets.reserve(nodes.size() * 2);
std::vector<std::size_t> visited(nodes.size(), 0);
std::vector<std::size_t> candidates;
for (std::size_t index = 0; index < nodes.size(); ++index) {
std::size_t insertAt = ordered.size();
for (std::size_t otherIndex = 0; otherIndex < ordered.size(); ++otherIndex) {
const std::size_t other = ordered[otherIndex];
if (insertAt == ordered.size() && listLessThan(nodes[index].item, nodes[other].item)) {
insertAt = otherIndex;
candidates.clear();
const RenderSortItem& current = nodes[index].item;
if (current.right > current.left && current.bottom > current.top) {
const s32 minCellX = spatialCell(current.left);
const s32 maxCellX = spatialCell(current.right - 1);
const s32 minCellY = spatialCell(current.top);
const s32 maxCellY = spatialCell(current.bottom - 1);
for (s32 cellY = minCellY; cellY <= maxCellY; ++cellY) {
for (s32 cellX = minCellX; cellX <= maxCellX; ++cellX) {
const auto bucket = spatialBuckets.find(spatialKey(cellX, cellY));
if (bucket == spatialBuckets.end()) {
continue;
}
for (const std::size_t other : bucket->second) {
if (visited[other] == index + 1) {
continue;
}
visited[other] = index + 1;
if (rectIntersects(current, nodes[other].item)) {
candidates.push_back(other);
}
}
}
}
std::sort(candidates.begin(), candidates.end(), indexLessThan);
}
for (const std::size_t other : candidates) {
if (nodes[other].occluded || !overlaps(nodes[index].item, nodes[other].item)) {
continue;
}
@ -281,7 +325,19 @@ std::vector<std::size_t> resolveRenderOrder(const std::vector<RenderSortItem>& i
insertDependencySorted(nodes, index, other);
}
}
ordered.insert(ordered.begin() + static_cast<std::ptrdiff_t>(insertAt), index);
ordered.insert(index);
if (current.right > current.left && current.bottom > current.top) {
const s32 minCellX = spatialCell(current.left);
const s32 maxCellX = spatialCell(current.right - 1);
const s32 minCellY = spatialCell(current.top);
const s32 maxCellY = spatialCell(current.bottom - 1);
for (s32 cellY = minCellY; cellY <= maxCellY; ++cellY) {
for (s32 cellX = minCellX; cellX <= maxCellX; ++cellX) {
spatialBuckets[spatialKey(cellX, cellY)].push_back(index);
}
}
}
}
std::vector<std::size_t> painted;

View file

@ -18,10 +18,12 @@
#include "remorse/usecode_vm.h"
#include <algorithm>
#include <array>
#include <cmath>
#include <condition_variable>
#include <cstdint>
#include <cstring>
#include <cwchar>
#include <iomanip>
#include <mutex>
#include <optional>
@ -37,15 +39,24 @@ 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> warpStart;
remorse::ProcessKernel diagnosticKernel;
remorse::u16 diagnosticGroupCounts[32]{};
remorse::UsecodeTaskRegistry usecodeTasks;
@ -66,11 +77,15 @@ struct AppState {
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;
std::uint64_t renderGeneration = 0;
bool renderStop = false;
std::optional<remorse::RenderedMapImage> scene;
std::optional<remorse::RenderedMapImage> playerPatch;
std::optional<remorse::MapSceneRenderer> renderer;
std::optional<remorse::AnimationClip> standAnimation;
std::optional<remorse::AnimationClip> walkAnimation;
@ -145,6 +160,50 @@ remorse::WorldPoint avatarWorld(const AppState& state)
: 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<remorse::s32>(
playerPatchWidth + playerPatchHeight * 2 + 1280);
options.worldRect = remorse::WorldRect{
center.x - radius, center.y - radius, center.x + radius, center.y + radius};
return options;
}
std::optional<remorse::MapRenderSprite> playerRenderSprite(const AppState& state)
{
const remorse::AnimationClip* clip = nullptr;
if (state.playerAnimation == 1 && state.walkAnimation) {
clip = &*state.walkAnimation;
} else if (state.playerAnimation == 3 && state.runAnimation) {
clip = &*state.runAnimation;
} else if (state.standAnimation) {
clip = &*state.standAnimation;
}
if (!clip) {
return std::nullopt;
}
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<remorse::u8>(shapeFrame),
remorse::isAnimationFrameFlipped(*metadata), &*state.playerFrames[shapeFrame],
&state.playerPalette};
}
bool hatchGlobsInFastArea(remorse::LiveFixedMapItems& items,
const remorse::MapSceneRenderer& renderer, const remorse::FastAreaRange& range);
@ -507,99 +566,98 @@ void loadSceneAsync(HWND window, AppState& state)
maxY = std::max(maxY, static_cast<remorse::s32>(entry.y));
}
const auto startingEgg = remorse::findTeleportEgg(*stagedItems, *shapeTypes, 0x1e);
if (state.mapIndex == 1 && !startingEgg) {
const auto startingEgg = state.warpStart
? std::optional<remorse::StagedFixedMapItem>{}
: 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.mapIndex != 1 && !state.diagnostics) {
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;
}
const remorse::WorldPoint spawn = startingEgg
? remorse::WorldPoint{startingEgg->data.x * 2, startingEgg->data.y * 2, startingEgg->data.z}
: remorse::WorldPoint{(minX + maxX) / 2, (minY + maxY) / 2, 0};
remorse::WorldPoint spawn = state.warpStart
? remorse::WorldPoint{static_cast<remorse::s32>(state.warpStart->x) * 2,
static_cast<remorse::s32>(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;
options.mapIndex = state.mapIndex;
options.maxWidth = backingWidth;
options.maxHeight = backingHeight;
options.includeRoofs = true;
options.viewCenter = spawn;
remorse::LiveFixedMapItems liveItems(std::move(*stagedItems), std::move(containedItems));
liveItems.initializeAvatar();
if (startingEgg) {
remorse::ProcessKernel teleporterKernel;
remorse::u16 teleporterGroupCounts[32]{};
for (int reservedSlot = 0; reservedSlot < 3; ++reservedSlot) {
teleporterKernel.createProcess(1, teleporterGroupCounts);
}
bool avatarInStasis = false;
auto* teleporter = teleporterKernel.createTeleporterProcess(1,
static_cast<remorse::u16>(state.mapIndex), 0x1e, teleporterGroupCounts,
true, false, avatarInStasis);
const remorse::u16 processId = static_cast<remorse::u16>(teleporter->base.bytes[2] |
(static_cast<remorse::u16>(teleporter->base.bytes[3]) << 8));
struct StartupContext {
remorse::ProcessKernel& kernel;
remorse::LiveFixedMapItems& items;
const std::vector<remorse::ShapeTypeInfo>& shapes;
remorse::u16 (&groupCounts)[32];
bool& avatarInStasis;
remorse::u16 mapNumber;
bool teleported = false;
bool valid = true;
} startup{teleporterKernel, liveItems, *shapeTypes, teleporterGroupCounts,
avatarInStasis, static_cast<remorse::u16>(state.mapIndex)};
const auto runStartupProcess = [](remorse::EntityDispatchEntryBase& entry,
void* opaque) {
auto& context = *static_cast<StartupContext*>(opaque);
const remorse::u16 processId = static_cast<remorse::u16>(entry.bytes[2] |
(static_cast<remorse::u16>(entry.bytes[3]) << 8));
if (processId < 3) return;
const remorse::u16 vtable = static_cast<remorse::u16>(entry.bytes[0] |
(static_cast<remorse::u16>(entry.bytes[1]) << 8));
if (vtable == remorse::ClearAvatarInStasisProcess::vtableOffset) {
context.valid = context.kernel.runClearAvatarInStasisProcess(processId,
context.avatarInStasis, context.groupCounts);
} else if (vtable == remorse::TeleporterProcess::vtableOffset) {
const auto& teleporterProcess =
*reinterpret_cast<remorse::TeleporterProcessEntry*>(&entry);
context.teleported = remorse::TeleporterProcess::run(teleporterProcess,
context.items, context.mapNumber, context.shapes);
entry.bytes[0x18] |= 4;
context.kernel.terminateProcess(processId, context.groupCounts);
} else {
context.valid = false;
}
};
for (unsigned pass = 0; pass < 2 && teleporterKernel.processAt(processId) != nullptr;
++pass) {
teleporterKernel.scanRunnableProcesses(1, runStartupProcess, &startup);
}
if (!startup.valid || !startup.teleported || avatarInStasis ||
teleporterKernel.processAt(processId) != nullptr) {
std::lock_guard<std::mutex> kernelLock(state.kernelMutex);
if (!remorse::runFreshGameTeleporterStartup(state.diagnosticKernel, liveItems,
static_cast<remorse::u16>(state.mapIndex), 0x1e, *shapeTypes,
state.diagnosticGroupCounts)) {
setLoadFailure(state, L"The teleporter process could not resolve its map and egg destination.");
PostMessageW(window, sceneReadyMessage, 0, 0);
return;
}
const auto* avatar = liveItems.findItem(1);
const auto stagingTeleporter = avatar ? remorse::findNearbyActiveTeleportEgg(
*avatar, liveItems.mapItems(), *shapeTypes, static_cast<remorse::u8>(state.mapIndex))
: std::nullopt;
if (!stagingTeleporter || !remorse::runFreshGameTeleporterStartup(
state.diagnosticKernel, liveItems, stagingTeleporter->data.mapNumber,
static_cast<remorse::u8>(stagingTeleporter->data.quality & 0xff), *shapeTypes,
state.diagnosticGroupCounts)) {
setLoadFailure(state, L"The staging teleporter could not resolve its level destination.");
PostMessageW(window, sceneReadyMessage, 0, 0);
return;
}
avatar = liveItems.findItem(1);
spawn = remorse::WorldPoint{avatar->data.x * 2, avatar->data.y * 2, avatar->data.z};
options.viewCenter = spawn;
} else {
remorse::StagedFixedMapItem diagnosticStart;
diagnosticStart.data.x = static_cast<remorse::u16>(spawn.x / 2);
diagnosticStart.data.y = static_cast<remorse::u16>(spawn.y / 2);
diagnosticStart.data.z = static_cast<remorse::u8>(spawn.z);
liveItems.teleportAvatar(diagnosticStart, static_cast<remorse::u8>(state.mapIndex));
remorse::StagedFixedMapItem directStart;
directStart.data.x = static_cast<remorse::u16>(spawn.x / 2);
directStart.data.y = static_cast<remorse::u16>(spawn.y / 2);
directStart.data.z = static_cast<remorse::u8>(spawn.z);
liveItems.teleportAvatar(directStart, static_cast<remorse::u8>(state.mapIndex));
}
auto renderer = remorse::loadMapSceneRenderer(state.root, state.mapIndex);
if (renderer) {
hatchGlobsInFastArea(liveItems, *renderer, remorse::calculateFastAreaRange(spawn));
}
const auto initialMetadata = remorse::getAnimationFrame(*standAnimation, 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<remorse::u8>(initialShapeFrame),
remorse::isAnimationFrameFlipped(*initialMetadata), &*playerFrames[initialShapeFrame],
&*palette};
auto scene = renderer ? renderer->render(options, &liveItems) : std::nullopt;
if (!scene) {
setLoadFailure(state, L"Map graphics or palette data could not be loaded.");
PostMessageW(window, sceneReadyMessage, 0, 0);
return;
}
auto playerPatch = renderer ? renderer->render(
playerPatchOptions(state.mapIndex, spawn), &liveItems, &initialPlayer) : std::nullopt;
if (!playerPatch) {
setLoadFailure(state, L"The initial player render patch could not be built.");
PostMessageW(window, sceneReadyMessage, 0, 0);
return;
}
std::vector<std::uint8_t> dibPixels(scene->pixels.size() * 3);
for (std::size_t index = 0; index < scene->pixels.size(); ++index) {
@ -624,6 +682,7 @@ void loadSceneAsync(HWND window, AppState& state)
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.standAnimation = *standAnimation;
@ -672,7 +731,10 @@ void startLiveRenderer(HWND window, AppState& state)
state.renderThread = std::thread([window, &state]() {
for (;;) {
std::optional<remorse::LiveFixedMapItems> snapshot;
std::optional<remorse::MapRenderSprite> playerSprite;
remorse::WorldPoint center{};
bool fullRender = false;
std::uint64_t generation = 0;
{
std::unique_lock<std::mutex> lock(state.sceneMutex);
state.renderWake.wait(lock, [&state]() { return state.renderStop || state.renderRequested; });
@ -680,41 +742,70 @@ void startLiveRenderer(HWND window, AppState& state)
return;
}
state.renderRequested = false;
fullRender = state.renderFullRequested;
state.renderFullRequested = false;
generation = state.renderGeneration;
snapshot.emplace(*state.liveItems);
center = avatarWorld(state);
playerSprite = playerRenderSprite(state);
}
remorse::MapRenderOptions options;
options.mapIndex = state.mapIndex;
options.maxWidth = backingWidth;
options.maxHeight = backingHeight;
options.viewCenter = center;
const remorse::s32 radius = static_cast<remorse::s32>(
backingWidth + backingHeight * 2 + 512);
options.worldRect = remorse::WorldRect{
center.x - radius, center.y - radius, center.x + radius, center.y + radius};
auto scene = state.renderer->render(options, &*snapshot);
if (!scene) {
std::optional<remorse::RenderedMapImage> scene;
std::vector<std::uint8_t> pixels;
if (fullRender) {
remorse::MapRenderOptions options;
options.mapIndex = state.mapIndex;
options.maxWidth = backingWidth;
options.maxHeight = backingHeight;
options.includeRoofs = true;
options.viewCenter = center;
const remorse::s32 radius = static_cast<remorse::s32>(
backingWidth + backingHeight * 2 + 512);
options.worldRect = remorse::WorldRect{
center.x - radius, center.y - radius, center.x + radius, center.y + radius};
scene = state.renderer->render(options, &*snapshot);
if (!scene) {
continue;
}
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;
}
}
auto playerPatch = state.renderer->render(playerPatchOptions(state.mapIndex, center),
&*snapshot, playerSprite ? &*playerSprite : nullptr);
if (!playerPatch) {
continue;
}
std::vector<std::uint8_t> pixels(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<std::mutex> lock(state.sceneMutex);
if (state.renderStop) {
return;
}
state.scene = std::move(scene);
state.dibPixels = std::move(pixels);
if (state.renderGeneration != generation && state.renderFullRequested) {
state.renderRequested = true;
continue;
}
if (fullRender) {
state.scene = std::move(scene);
state.dibPixels = std::move(pixels);
}
state.playerPatch = std::move(playerPatch);
}
PostMessageW(window, sceneReadyMessage, 0, 0);
}
});
}
void requestLiveRender(AppState& state, bool fullRender)
{
state.renderRequested = true;
state.renderFullRequested = state.renderFullRequested || fullRender;
++state.renderGeneration;
state.renderWake.notify_one();
}
void drawCenteredText(HDC device, const RECT& bounds, const wchar_t* text, COLORREF color, HFONT font)
{
const int saved = SaveDC(device);
@ -725,76 +816,6 @@ void drawCenteredText(HDC device, const RECT& bounds, const wchar_t* text, COLOR
RestoreDC(device, saved);
}
void compositePlayer(HDC device, AppState& state, int viewWidth, int viewHeight,
int sourceLeft, int sourceTop, std::size_t viewStride)
{
const remorse::AnimationClip* clip = nullptr;
if (state.playerAnimation == 1 && state.walkAnimation) {
clip = &*state.walkAnimation;
} else if (state.playerAnimation == 3 && state.runAnimation) {
clip = &*state.runAnimation;
} else if (state.standAnimation) {
clip = &*state.standAnimation;
}
if (!clip || state.playerFrames.empty()) {
return;
}
const remorse::u8 frameIndex = state.playerAnimation == 0 ? 0 : state.playerFrame;
const auto metadata = remorse::getAnimationFrame(*clip, state.playerDirection, frameIndex);
if (!metadata) {
return;
}
const remorse::u16 shapeFrame = remorse::getAnimationShapeFrame(*metadata);
if (shapeFrame >= state.playerFrames.size() || !state.playerFrames[shapeFrame]) {
return;
}
const remorse::DecodedShapeFrame& sprite = *state.playerFrames[shapeFrame];
const auto avatarScreen = remorse::projectToScreen(avatarWorld(state));
const int actorX = avatarScreen.x - state.scene->sourceLeft - sourceLeft;
const int actorY = avatarScreen.y - state.scene->sourceTop - sourceTop;
const int spriteLeft = actorX + sprite.frame.xOffset;
const int spriteTop = actorY + sprite.frame.yOffset;
const bool flipped = remorse::isAnimationFrameFlipped(*metadata);
for (remorse::u32 y = 0; y < sprite.frame.height; ++y) {
const int destinationY = spriteTop + static_cast<int>(y);
if (destinationY < 0 || destinationY >= viewHeight) {
continue;
}
for (remorse::u32 x = 0; x < sprite.frame.width; ++x) {
const int destinationX = spriteLeft + static_cast<int>(x);
if (destinationX < 0 || destinationX >= viewWidth) {
continue;
}
const remorse::u32 sourceX = flipped ? sprite.frame.width - 1 - x : x;
const remorse::s16 paletteIndex = sprite.pixels[
static_cast<std::size_t>(y) * sprite.frame.width + sourceX];
if (paletteIndex < 0) {
continue;
}
const remorse::RgbColor& color = state.playerPalette.colors[
static_cast<remorse::u8>(paletteIndex)];
const std::size_t pixelOffset = static_cast<std::size_t>(destinationY) * viewStride +
static_cast<std::size_t>(destinationX) * 3;
state.viewPixels[pixelOffset] = static_cast<std::uint8_t>(color.blue * 255 / 63);
state.viewPixels[pixelOffset + 1] = static_cast<std::uint8_t>(color.green * 255 / 63);
state.viewPixels[pixelOffset + 2] = static_cast<std::uint8_t>(color.red * 255 / 63);
}
}
BITMAPINFO bitmap{};
bitmap.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bitmap.bmiHeader.biWidth = viewWidth;
bitmap.bmiHeader.biHeight = -viewHeight;
bitmap.bmiHeader.biPlanes = 1;
bitmap.bmiHeader.biBitCount = 24;
bitmap.bmiHeader.biCompression = BI_RGB;
StretchDIBits(device, 0, 0, viewWidth, viewHeight, 0, 0, viewWidth, viewHeight,
state.viewPixels.data(), &bitmap, DIB_RGB_COLORS, SRCCOPY);
}
void drawLoadingScreen(HDC device, const RECT& client, const AppState& state)
{
HBRUSH background = CreateSolidBrush(RGB(13, 23, 28));
@ -885,6 +906,9 @@ void paintWindow(HWND window, AppState& state)
const int centeredTop = avatarScreen.y - state.scene->sourceTop - viewHeight / 2;
const int sourceLeft = std::clamp(centeredLeft, 0, static_cast<int>(state.scene->width) - viewWidth);
const int sourceTop = std::clamp(centeredTop, 0, static_cast<int>(state.scene->height) - viewHeight);
if ((sourceLeft != centeredLeft || sourceTop != centeredTop) && state.renderThread.joinable()) {
requestLiveRender(state, true);
}
const std::size_t viewStride = (static_cast<std::size_t>(viewWidth) * 3 + 3) & ~std::size_t(3);
state.viewPixels.resize(viewStride * static_cast<std::size_t>(viewHeight));
@ -896,7 +920,43 @@ void paintWindow(HWND window, AppState& state)
std::memcpy(state.viewPixels.data() + viewOffset, state.dibPixels.data() + sceneOffset,
static_cast<std::size_t>(viewWidth) * 3);
}
compositePlayer(device, state, viewWidth, viewHeight, sourceLeft, sourceTop, viewStride);
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<int>(patch.height); ++patchY) {
const int destY = patchTop + patchY;
if (destY < 0 || destY >= viewHeight) {
continue;
}
for (int patchX = 0; patchX < static_cast<int>(patch.width); ++patchX) {
const int destX = patchLeft + patchX;
if (destX < 0 || destX >= viewWidth) {
continue;
}
const std::size_t sourceIndex = static_cast<std::size_t>(patchY) * patch.width + patchX;
if (patch.coverage[sourceIndex] == 0) {
continue;
}
const remorse::RgbColor& color = patch.pixels[sourceIndex];
const std::size_t destIndex = static_cast<std::size_t>(destY) * viewStride +
static_cast<std::size_t>(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<DWORD>(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;
@ -1069,6 +1129,7 @@ void updatePlayer(HWND window, AppState& state)
}
changed = changed || state.diagnostics || gravityMoved;
if (movement.animation == 0) {
const bool playerSpriteChanged = state.playerAnimation != 0 || state.playerFrame != 0;
if (state.animationProcessId != 0) {
auto* process = state.diagnosticKernel.processAt(state.animationProcessId);
process->bytes[0x18] |= 4;
@ -1081,13 +1142,16 @@ void updatePlayer(HWND window, AppState& state)
const bool usecodeMutation = state.usecodeWorldMutationPending;
state.usecodeWorldMutationPending = false;
changed = changed || usecodeMutation;
if (state.renderThread.joinable() && (gravityMoved || usecodeMutation)) {
state.renderRequested = true;
state.renderWake.notify_one();
if (state.renderThread.joinable() &&
(gravityMoved || usecodeMutation || playerSpriteChanged)) {
requestLiveRender(state, gravityMoved || usecodeMutation);
}
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 = requestedAnimation == 1
? *state.walkAnimation : *state.runAnimation;
@ -1135,9 +1199,11 @@ void updatePlayer(HWND window, AppState& state)
*state.liveItems, *state.renderer, remorse::calculateFastAreaRange(avatarWorld(state)));
const bool usecodeMutation = state.usecodeWorldMutationPending;
state.usecodeWorldMutationPending = false;
if (state.renderThread.joinable() && (moved || hatched || usecodeMutation || gravityMoved)) {
state.renderRequested = true;
state.renderWake.notify_one();
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);
}
changed = true;
}
@ -1172,7 +1238,10 @@ LRESULT CALLBACK windowProcedure(HWND window, UINT message, WPARAM wParam, LPARA
return 0;
case WM_KILLFOCUS:
state->controllerMovement.clear();
while (state->diagnosticKernel.popPendingKeyEvent()) {}
{
std::lock_guard<std::mutex> lock(state->kernelMutex);
while (state->diagnosticKernel.popPendingKeyEvent()) {}
}
return 0;
case WM_KEYDOWN:
case WM_KEYUP:
@ -1204,6 +1273,7 @@ LRESULT CALLBACK windowProcedure(HWND window, UINT message, WPARAM wParam, LPARA
if (GetKeyState(VK_LSHIFT) & 0x8000) event.modifiers |= 1;
if (GetKeyState(VK_RSHIFT) & 0x8000) event.modifiers |= 2;
event.field8 = message == WM_KEYDOWN ? 1 : 0;
std::lock_guard<std::mutex> lock(state->kernelMutex);
state->diagnosticKernel.queuePendingKeyEvent(event);
}
if (message == WM_KEYUP) return 0;
@ -1290,19 +1360,78 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR commandLine, int showCo
remorse::installCrashDiagnostics();
remorse::u32 mapIndex = 1;
bool diagnostics = false;
std::wistringstream arguments(commandLine ? commandLine : L"");
std::optional<WarpStart> warpStart;
constexpr std::array<remorse::u16, 17> 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<std::wstring> arguments;
std::wstring argument;
while (arguments >> argument) {
if (argument == L"--diagnostics") {
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<long>(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<remorse::u16>(x),
static_cast<remorse::u16>(y), static_cast<remorse::u8>(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 {
wchar_t* end = nullptr;
const unsigned long parsed = std::wcstoul(argument.c_str(), &end, 0);
if (end != argument.c_str() && *end == L'\0' && parsed <= 255) {
long parsed = 0;
if (parseInteger(current, 0, 255, parsed)) {
mapIndex = static_cast<remorse::u32>(parsed);
}
}
}
if (warpRequested) {
const long targetMap = missionBaseMaps[static_cast<std::size_t>(warpMission)] + mapOffset;
if (targetMap < 0 || targetMap > 255) {
invalidArguments = true;
} else {
mapIndex = static_cast<remorse::u32>(targetMap);
}
}
if (invalidArguments) {
MessageBoxW(nullptr,
L"Usage: remorse_game.exe -warp <mission> <x> <y> <z> [-mapoff <delta>]\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);
@ -1321,6 +1450,7 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR commandLine, int showCo
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);
}
@ -1348,8 +1478,16 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR commandLine, int showCo
RECT bounds{0, 0, initialClientWidth, initialClientHeight};
AdjustWindowRect(&bounds, WS_OVERLAPPEDWINDOW, FALSE);
HWND window = CreateWindowExW(0, windowClassName,
diagnostics ? L"Crusader: No Remorse | Diagnostics" : L"Crusader: No Remorse | Traversal Test",
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<unsigned>(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);

View file

@ -250,14 +250,27 @@ int main()
for (int reservedSlot = 0; reservedSlot < 3; ++reservedSlot) {
teleporterKernel.createProcess(1, teleporterGroups);
}
auto* startupTimer = teleporterKernel.createSystemTimerProcess(1, teleporterGroups);
auto* startupKeyboard = teleporterKernel.createKeyboardProcess(1, teleporterGroups);
auto* startupController = teleporterKernel.createControllerProcess(1, teleporterGroups);
assert(startupTimer && startupKeyboard && startupController);
const auto processIdOf = [](const auto& process) {
return static_cast<remorse::u16>(process->base.bytes[2] |
(static_cast<remorse::u16>(process->base.bytes[3]) << 8));
};
const remorse::u16 startupTimerId = processIdOf(startupTimer);
const remorse::u16 startupKeyboardId = processIdOf(startupKeyboard);
const remorse::u16 startupControllerId = processIdOf(startupController);
bool avatarInStasis = false;
auto* teleporterProcess = teleporterKernel.createTeleporterProcess(1, 1, 0x1e,
teleporterGroups, true, false, avatarInStasis);
const remorse::u16 teleporterProcessId = static_cast<remorse::u16>(
teleporterProcess->base.bytes[2] | (static_cast<remorse::u16>(teleporterProcess->base.bytes[3]) << 8));
assert(avatarInStasis && teleporterKernel.allocationSizeAt(4) == 0x33 &&
teleporterKernel.processAt(4)->bytes[0] == 0x5e &&
teleporterKernel.processAt(4)->bytes[1] == 0x0f);
const remorse::u16 clearStasisProcessId = static_cast<remorse::u16>(teleporterProcessId + 1);
assert(avatarInStasis && clearStasisProcessId > startupControllerId &&
teleporterKernel.allocationSizeAt(clearStasisProcessId) == 0x33 &&
teleporterKernel.processAt(clearStasisProcessId)->bytes[0] == 0x5e &&
teleporterKernel.processAt(clearStasisProcessId)->bytes[1] == 0x0f);
assert(!remorse::TeleporterProcess::run(*teleporterProcess, spawnSearchWorld, 2, *typeFlags));
assert(spawnSearchWorld.findItem(1)->data.x == 0 && spawnSearchWorld.findItem(1)->data.y == 0);
struct TeleporterPassContext {
@ -288,12 +301,19 @@ int main()
};
teleporterKernel.scanRunnableProcesses(1, runTeleporterPass, &teleporterPass);
assert(!avatarInStasis && !teleporterPass.teleported &&
teleporterKernel.processAt(startupTimerId) == &startupTimer->base &&
teleporterKernel.processAt(startupKeyboardId) == &startupKeyboard->base &&
teleporterKernel.processAt(startupControllerId) == &startupController->base &&
teleporterKernel.processAt(clearStasisProcessId) == nullptr &&
teleporterKernel.processAt(teleporterProcessId) == &teleporterProcess->base &&
spawnSearchWorld.findItem(1)->data.x == 0 && spawnSearchWorld.findItem(1)->data.y == 0);
teleporterKernel.scanRunnableProcesses(1, runTeleporterPass, &teleporterPass);
assert(teleporterPass.teleported);
assert(teleporterKernel.processAt(teleporterProcessId) == nullptr &&
teleporterKernel.allocationSizeAt(teleporterProcessId) == 0 && teleporterGroups[1] == 3);
teleporterKernel.allocationSizeAt(teleporterProcessId) == 0 && teleporterGroups[1] == 6 &&
teleporterKernel.processAt(startupTimerId) == &startupTimer->base &&
teleporterKernel.processAt(startupKeyboardId) == &startupKeyboard->base &&
teleporterKernel.processAt(startupControllerId) == &startupController->base);
assert(spawnEgg->recordIndex < fixedMap->entries.size());
const auto& startingEggRecord = fixedMap->entries[spawnEgg->recordIndex];
const auto* spawnedAvatar = spawnSearchWorld.findItem(1);
@ -302,6 +322,44 @@ int main()
assert(spawnedAvatar && spawnedAvatar->itemNumber == 1 &&
spawnedAvatar->data.x == spawnEgg->data.x && spawnedAvatar->data.y == spawnEgg->data.y &&
spawnedAvatar->data.z == spawnEgg->data.z && spawnedAvatar->data.mapNumber == 1);
remorse::LiveFixedMapItems integratedStartupWorld(*stagedItems);
assert(integratedStartupWorld.initializeAvatar());
remorse::ProcessKernel integratedStartupKernel;
remorse::u16 integratedStartupGroups[32]{};
for (int reservedSlot = 0; reservedSlot < 3; ++reservedSlot) {
integratedStartupKernel.createProcess(1, integratedStartupGroups);
}
auto* integratedTimer = integratedStartupKernel.createSystemTimerProcess(1, integratedStartupGroups);
auto* integratedKeyboard = integratedStartupKernel.createKeyboardProcess(1, integratedStartupGroups);
auto* integratedController = integratedStartupKernel.createControllerProcess(1, integratedStartupGroups);
assert(remorse::runFreshGameTeleporterStartup(integratedStartupKernel, integratedStartupWorld,
1, 0x1e, *typeFlags, integratedStartupGroups));
const auto* integratedAvatar = integratedStartupWorld.findItem(1);
assert(integratedTimer && integratedKeyboard && integratedController && integratedAvatar &&
integratedAvatar->data.x == spawnEgg->data.x && integratedAvatar->data.y == spawnEgg->data.y &&
integratedAvatar->data.mapNumber == 1 && integratedStartupGroups[1] == 6 &&
integratedStartupKernel.processAt(processIdOf(integratedTimer)) == &integratedTimer->base &&
integratedStartupKernel.processAt(processIdOf(integratedKeyboard)) == &integratedKeyboard->base &&
integratedStartupKernel.processAt(processIdOf(integratedController)) == &integratedController->base);
const auto stagingTeleporter = remorse::findNearbyActiveTeleportEgg(*integratedAvatar,
integratedStartupWorld.mapItems(), *typeFlags, 1);
const auto levelStartEgg = remorse::findTeleportEgg(*stagedItems, *typeFlags, 0x63);
assert(stagingTeleporter && stagingTeleporter->itemNumber == 1598 &&
stagingTeleporter->data.shape == 0x0194 && stagingTeleporter->data.frame == 0 &&
stagingTeleporter->data.quality == 0x0063 && stagingTeleporter->data.mapNumber == 1 &&
levelStartEgg && levelStartEgg->itemNumber == 6812 && levelStartEgg->data.x == 30328 &&
levelStartEgg->data.y == 29656 && levelStartEgg->data.z == 16);
assert(remorse::runFreshGameTeleporterStartup(integratedStartupKernel, integratedStartupWorld,
stagingTeleporter->data.mapNumber,
static_cast<remorse::u8>(stagingTeleporter->data.quality & 0xff), *typeFlags,
integratedStartupGroups));
integratedAvatar = integratedStartupWorld.findItem(1);
assert(integratedAvatar && integratedAvatar->data.x == levelStartEgg->data.x &&
integratedAvatar->data.y == levelStartEgg->data.y && integratedAvatar->data.z == levelStartEgg->data.z &&
integratedAvatar->data.mapNumber == 1 && integratedStartupGroups[1] == 6 &&
integratedStartupKernel.processAt(processIdOf(integratedTimer)) == &integratedTimer->base &&
integratedStartupKernel.processAt(processIdOf(integratedKeyboard)) == &integratedKeyboard->base &&
integratedStartupKernel.processAt(processIdOf(integratedController)) == &integratedController->base);
const auto spawnUseCandidates = remorse::itemGrabSearchCandidates(
*spawnedAvatar, spawnSearchWorld.mapItems(), *typeFlags);
assert(spawnUseCandidates);

View file

@ -3,6 +3,7 @@
#include "remorse/fixed_map.h"
#include "remorse/glob_archive.h"
#include "remorse/map_renderer.h"
#include "remorse/shape_archive.h"
#include "remorse/type_flags.h"
#include <algorithm>
@ -80,6 +81,31 @@ int main()
remorse::LiveFixedMapItems liveSceneItems(*stagedItems);
auto cachedRenderer = remorse::loadMapSceneRenderer(*root, 1);
assert(cachedRenderer);
const auto shape60Item = std::find_if(stagedItems->begin(), stagedItems->end(), [](const auto& item) {
return item.data.shape == 0x003c;
});
assert(shape60Item != stagedItems->end());
const auto shape60Frame = remorse::decodeShapeFrame(cachedRenderer->shapes, 0x003c,
shape60Item->data.frame);
assert(shape60Frame && std::any_of(shape60Frame->pixels.begin(), shape60Frame->pixels.end(),
[](remorse::s16 color) { return color >= 0; }));
assert(((*shapeTypes)[0x003c].flags & 0x400) != 0);
remorse::MapSceneRenderer isolatedShape60 = *cachedRenderer;
isolatedShape60.map.entries = {fixedMap->entries[shape60Item->recordIndex]};
remorse::MapRenderOptions shape60Options;
shape60Options.mapIndex = 1;
shape60Options.maxWidth = 320;
shape60Options.maxHeight = 200;
shape60Options.includeHiddenMarkers = true;
shape60Options.viewCenter = remorse::WorldPoint{
static_cast<remorse::s32>(fixedMap->entries[shape60Item->recordIndex].x),
static_cast<remorse::s32>(fixedMap->entries[shape60Item->recordIndex].y),
fixedMap->entries[shape60Item->recordIndex].z};
assert(!isolatedShape60.render(shape60Options));
shape60Options.includeRoofs = true;
const auto isolatedShape60Image = isolatedShape60.render(shape60Options);
assert(isolatedShape60Image && isolatedShape60Image->renderItemCount == 1 &&
isolatedShape60Image->decodedItemCount == 1 && isolatedShape60Image->paintedItemCount == 1);
const auto liveBefore = cachedRenderer->render(options, &liveSceneItems);
const auto samePixels = [](const auto& left, const auto& right) {
return left.size() == right.size() && std::equal(left.begin(), left.end(), right.begin(),
@ -88,6 +114,57 @@ int main()
});
};
assert(liveBefore && samePixels(liveBefore->pixels, startingScene->pixels));
const auto playerFrame = remorse::decodeShapeFrame(cachedRenderer->shapes, 1, 0);
assert(playerFrame);
const remorse::MapRenderSprite playerSprite{spawn, 1, 0, false,
&*playerFrame, &cachedRenderer->palette};
const auto sceneWithPlayer = cachedRenderer->render(options, &liveSceneItems, &playerSprite);
assert(sceneWithPlayer && sceneWithPlayer->renderItemCount == liveBefore->renderItemCount + 1 &&
!samePixels(sceneWithPlayer->pixels, liveBefore->pixels));
assert(sceneWithPlayer->coverage.size() == sceneWithPlayer->pixels.size() &&
std::any_of(sceneWithPlayer->coverage.begin(), sceneWithPlayer->coverage.end(),
[](remorse::u8 covered) { return covered != 0; }));
remorse::MapRenderOptions fullPlayerReferenceOptions = options;
fullPlayerReferenceOptions.maxWidth = 512;
fullPlayerReferenceOptions.maxHeight = 384;
const auto fullPlayerReference = cachedRenderer->render(
fullPlayerReferenceOptions, &liveSceneItems, &playerSprite);
assert(fullPlayerReference);
remorse::MapRenderOptions playerPatchOptions = fullPlayerReferenceOptions;
playerPatchOptions.worldRect = remorse::WorldRect{
spawn.x - 2048, spawn.y - 2048, spawn.x + 2048, spawn.y + 2048};
const auto playerPatch = cachedRenderer->render(playerPatchOptions, &liveSceneItems, &playerSprite);
assert(playerPatch && playerPatch->sourceLeft == fullPlayerReference->sourceLeft &&
playerPatch->sourceTop == fullPlayerReference->sourceTop);
for (std::size_t index = 0; index < playerPatch->coverage.size(); ++index) {
if (playerPatch->coverage[index] != 0) {
assert(playerPatch->pixels[index].red == fullPlayerReference->pixels[index].red &&
playerPatch->pixels[index].green == fullPlayerReference->pixels[index].green &&
playerPatch->pixels[index].blue == fullPlayerReference->pixels[index].blue);
}
}
const remorse::WorldPoint warpPosition{30463 * 2, 29951 * 2, 0};
const remorse::MapRenderSprite warpPlayer{warpPosition, 1, 0, false,
&*playerFrame, &cachedRenderer->palette};
remorse::MapRenderOptions warpReferenceOptions = fullPlayerReferenceOptions;
warpReferenceOptions.includeRoofs = true;
warpReferenceOptions.viewCenter = warpPosition;
const auto warpReference = cachedRenderer->render(warpReferenceOptions, nullptr, &warpPlayer);
assert(warpReference);
remorse::MapRenderOptions warpPatchOptions = warpReferenceOptions;
warpPatchOptions.worldRect = remorse::WorldRect{
warpPosition.x - 2560, warpPosition.y - 2560,
warpPosition.x + 2560, warpPosition.y + 2560};
const auto warpPatch = cachedRenderer->render(warpPatchOptions, nullptr, &warpPlayer);
assert(warpPatch && warpPatch->sourceLeft == warpReference->sourceLeft &&
warpPatch->sourceTop == warpReference->sourceTop);
for (std::size_t index = 0; index < warpPatch->coverage.size(); ++index) {
if (warpPatch->coverage[index] != 0) {
assert(warpPatch->pixels[index].red == warpReference->pixels[index].red &&
warpPatch->pixels[index].green == warpReference->pixels[index].green &&
warpPatch->pixels[index].blue == warpReference->pixels[index].blue);
}
}
const remorse::s32 redrawRadius = static_cast<remorse::s32>(
options.maxWidth + options.maxHeight * 2 + 512);
options.worldRect = remorse::WorldRect{spawn.x - redrawRadius, spawn.y - redrawRadius,

View file

@ -49,6 +49,28 @@ int main()
assert(order[0] == 1);
assert(order[1] == 0);
remorse::detail::RenderSortItem occluder = elevated;
occluder.occludes = true;
const std::vector<remorse::detail::RenderSortItem> occludedPlayerItems{occluder, ground};
const std::vector<std::size_t> occludedPlayerOrder =
remorse::detail::resolveRenderOrder(occludedPlayerItems);
assert(occludedPlayerOrder.size() == 1 && occludedPlayerOrder[0] == 0);
remorse::detail::RenderSortItem boundaryOccluder = occluder;
boundaryOccluder.left = 120;
boundaryOccluder.top = 120;
boundaryOccluder.right = 184;
boundaryOccluder.bottom = 184;
remorse::detail::RenderSortItem boundaryPlayer = ground;
boundaryPlayer.left = 128;
boundaryPlayer.top = 128;
boundaryPlayer.right = 160;
boundaryPlayer.bottom = 160;
const std::vector<remorse::detail::RenderSortItem> boundaryItems{
boundaryOccluder, boundaryPlayer};
const std::vector<std::size_t> boundaryOrder = remorse::detail::resolveRenderOrder(boundaryItems);
assert(boundaryOrder.size() == 1 && boundaryOrder[0] == 0);
remorse::detail::RenderSortItem animatedFlat = elevated;
animatedFlat.x = 64;
animatedFlat.xLeft = 64;