Refactor collision handling and item management in the Remorse project

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

View file

@ -324,13 +324,13 @@ A separate diagnostic applies the exported Z/footprint classifier in chain order
Contained placement has a separate source-derived diagnostic: for nonzero maps, nonempty contained records consume free IDs, encode nesting depth in the fixed-record X field, ascend the parent link when depth falls, and append children only to container/monster-egg families (`10a8:05e3`, `10a8:2533`, `10a0:0e32`). Synthetic nested/sibling and invalid-parent tests pass; retail map 1 contains no nonzero-shape contained records, so it cannot verify those links. The stage is not a live container cache or a runtime ID-order trace. The shape loader exposes TYPEFLAG row byte 7 as weight, and the `Item_Fall` (`1038:1334`) gate requires a drawable, nonzero-weight shape. The action planner preserves `Item_Grab`'s type-1 fall versus type-2 flag-checked process decision in source order; the first retail origin produces zero actions.
The bounded staged dispatcher can now issue those actions against the host process kernel. `Process_GetProcessForItemAndType` (`11d0:13a4`) scans live slots from 3, ignores terminated entries, and supports item/type wildcards; the host mirrors those rules. `Item_Hurl` (`1038:12a6`) reuses an existing type-`0x203` gravity process and adds velocity, or creates a `0x42`-byte process (`1038:0395`) with zero velocity, gravity 2, and a 20-tick sleep for a fall request. Tests cover both branches, duplicate item-process requests, strict wake, ownership and ID-limit rejection, and teardown/reuse. Staged dispatch rejects any out-of-range action before starting; the Windows `F` key is still a separate release fixture. A host-owned `LiveFixedMapItems` copy now supports ID lookup, bounded position changes, and `Item_Grab` dispatch against current item positions; the window owns this copy for nearby-item lookup. `Item_LegalMoveToPointWithCollisionInfo` (`10a0:1841`) calls `Item_Grab` before `AreaSearch_CollideMove` on its successful path; `moveApprovedItem` preserves that ordering once a caller has approved the move, and tests distinguish old-position requests from post-move search. Synthetic move/dispatch and retail-map ownership tests pass. This is not the original item cache, does not yet provide a legal-move collision event or update rendered sprites, and does not include contained items. `runUnobstructedGravity` now moves an owned item and advances/sleeps its owned process in the nonzero-vertical-speed branch after explicit caller-supplied approval of the full pre-sweep target. A refused or missing sweep makes no mutation; tests cover both paths. This does not execute the zero-speed fall/`Item_Grab` branch, process collision responses, map fast-area gate, or an automatic scheduler tick. The original `AreaSearch_SweepTestItem` (`10e0:1151`) forwards into `AreaSearch_SweepTestPt` (`10e0:0b39`), which requires fast-area map blocks, item iteration, and resolved collision points absent from the host's boolean-only sweep. DOSBox-X is now installed at `C:\DOSBox-X`, but its interactive debugger has not produced a retail map-load or ItemFind trace; runtime IDs, parents, and first/next search behavior still lack original-execution trace parity.
The bounded staged dispatcher can now issue those actions against the host process kernel. `Process_GetProcessForItemAndType` (`11d0:13a4`) scans live slots from 3, ignores terminated entries, and supports item/type wildcards; the host mirrors those rules. `Item_Hurl` (`1038:12a6`) reuses an existing type-`0x203` gravity process and adds velocity, or creates a `0x42`-byte process (`1038:0395`) with zero velocity, gravity 2, and a 20-tick sleep for a fall request. Tests cover both branches, duplicate item-process requests, strict wake, ownership and ID-limit rejection, and teardown/reuse. Staged dispatch rejects any out-of-range action before starting; the Windows `F` key is still a separate release fixture. A host-owned `LiveFixedMapItems` copy now supports ID lookup, bounded position changes, and `Item_Grab` dispatch against current item positions; the window owns this copy for nearby-item lookup. `Item_LegalMoveToPointWithCollisionInfo` (`10a0:1841`) calls `Item_Grab` before `AreaSearch_CollideMove` on its successful path; `moveApprovedItem` preserves that ordering once a caller has approved the move, and tests distinguish old-position requests from post-move search. Synthetic move/dispatch and retail-map ownership tests pass. This is not the original item cache, does not yet provide a legal-move collision event or update rendered sprites, and does not include live contained items. `runUnobstructedGravity` moves an owned item and advances/sleeps its owned process in the nonzero-vertical-speed branch after explicit caller-supplied approval of the full pre-sweep target. A refused or missing sweep makes no mutation on that path. On the zero-Z horizontal path, it requests `Item_Grab` before sweep approval, so a refused sweep may still leave a process request. The stationary zero-speed fall search, collision responses, live fast-area state, and automatic scheduler tick remain unported. The original `AreaSearch_SweepTestItem` (`10e0:1151`) forwards into `AreaSearch_SweepTestPt` (`10e0:0b39`); the host has bounded fast-area and item-iterator gates but not resolved collision points. Runtime ID and search-order parity remain unverified and are not a current gate.
The host-owned item move now follows `Item_MoveToPoint` (`10a0:1945`) through `ItemCache_Push`/`ItemCache_Poptocoords` (`10a8:1ced/1df5`) for two bounded cache effects: a moved item becomes the destination block's newest head, even when staying in the same block, and Z above `0xfa` is clamped. Caller-supplied, newly allocated item IDs can also be inserted at a block head with duplicate and placement guards. Focused tests verify process request order for moved and inserted items and the Z value; the host still lacks free-ID allocation, fast-area, viewport, and contained-item side effects.
The host-owned item move now follows `Item_MoveToPoint` (`10a0:1945`) through `ItemCache_Push`/`ItemCache_Poptocoords` (`10a8:1ced/1df5`) for two bounded cache effects: a moved item becomes the destination block's newest head, even when staying in the same block, and Z above `0xfa` is clamped. Caller-supplied item IDs can also be inserted at a block head. The host free-ID allocator uses the source `0x100..0x27ff` range, skips staged direct and contained records, and fails without mutation when exhausted. The window reserves staged contained IDs and retains their parent links; placing one in the world clears its parent while its children remain linked. Synthetic nested/exhaustion and retail-map tests pass. This does not yet implement returning freed IDs to the list, live inventory/container transfers, fast-area status, or viewport side effects.
The supported horizontal `GravityProcess_Run` path now issues `Item_Grab` at the old item position when Z speed is zero and X/Y speed is nonzero, then asks the injected sweep to approve movement. As in the source order, a refused sweep can leave a newly requested item process behind while the item stays put. The earlier no-mutation guarantee for a refused sweep applies only to the nonzero-Z path, which does not issue that request. The stationary zero-speed fall search, collision response, and automatic scheduler dispatch are still unported; a caller must provide shapes, group counts, and the sweep decision for this host-only branch.
The standalone `AreaSearch_SweepTestPt` bounds stage (`10e0:0b39`) clamps X/Y to `0..0x7fff` and Z to `0..0xfa`, reports failed-direction bits `1/2/4`, and distinguishes a horizontal hard failure from Z clamping. Tests cover combined and Z-only out-of-range targets. It is not yet the sweep's fast-area, item-iteration, or collision-resolution stage, and the gravity runner still requires an explicit approved sweep callback.
The standalone `AreaSearch_SweepTestPt` bounds stage (`10e0:0b39`) clamps X/Y to `0..0x7fff` and Z to `0..0xfa`, reports failed-direction bits `1/2/4`, and distinguishes a horizontal hard failure from Z clamping. The source's `World_MapBlockInFastArea` (`10a8:0000`) rotated block predicate and eight-corner start/destination footprint gate are now testable with an explicit fast-area range. The sweep's item-iterator rectangle and live candidate query follow inclusive X/Y filtering and Y-then-X block order. The per-item sweep uses 16-unit X/Y extents, 8-unit Z extents with the source zero-height fallback, and six axis-face tests that report one-unit-before-contact points and failed-direction bits. A read-only live collector combines those tests with candidate order, shape solidity and flip flags, and an explicit fast-area range. The host now selects a solid hit in source order when any axis is strictly closer, retains the earlier hit on a tie, and accumulates direction bits across contacts; a live entry point returns the resulting point and first colliding item. Synthetic tests cover both directions on all axes, self-exclusion, non-solid items, chain order, flipped shapes, and candidate selection. It does not handle damaging-only or floor contacts, maintain live fast-area state, or drive gravity movement. The gravity runner still requires an explicit approved sweep callback.
Original DOS debugging and runtime verification are postponed indefinitely until requested again. The DOSBox-X debugger session has been stopped; do not treat a live trace as a prerequisite for the source-port work below. Keep unverified parity claims labeled as such.
@ -338,8 +338,8 @@ Next source-port checks, in call-chain order:
1. Keep the `0x23ff/0x2400` process item boundary until source-derived allocation limits support changing it; do not infer a wider live table from staged map IDs.
2. Port the remaining scheduler interval/group transitions behind host timing boundaries using static code evidence, with runtime parity explicitly deferred.
3. Port original free-ID allocation and contained-item ownership, and connect the caller-supplied live insert path to those allocation events.
4. Port the area sweep's fast-area and item-collision resolution, including failed directions and resolved points, before enabling collision-driven movement.
3. Port free-ID return/reuse and live container transfers while preserving contained parent/child links and process ownership.
4. Add damaging-only and mode-dependent floor contacts, then combine the solid-hit result with bounds and fast-area failures before enabling collision-driven movement.
5. Port the `GravityProcess_Run` area sweep, collision responses, and item-cache position/status writes to make created gravity entries move real items after their sleep.
6. Connect the approved-move `Item_Grab` path to a ported `Item_LegalMoveToPointWithCollisionInfo` sweep and item-cache lifecycle, without changing the separate Windows `F` release fixture.
7. Lift `EntityVmContext::CreateFromSlotIndex` (`1420:0eec`) and its interpreter initialization; keep release event-body lookup diagnostic until the VM executes it.

View file

@ -1,5 +1,6 @@
#pragma once
#include <optional>
#include <vector>
#include "remorse\fixed_map.h"
@ -27,10 +28,48 @@ struct SweepBoundsResult {
bool failed = false;
};
struct SweepItemImpact {
WorldPoint resolved{};
u8 failedDirections = 0;
};
struct SweepCandidateImpact {
u16 itemNumber = 0;
SweepItemImpact impact{};
};
struct SweepCollisionResult {
WorldPoint destination{};
u16 firstCollision = 0;
u8 failedDirections = 0;
};
struct FastAreaRange {
s32 minSum = 0;
s32 maxSum = 0;
s32 minDifference = 0;
s32 maxDifference = 0;
};
bool isWorldPointInFastArea(s32 x, s32 y, const FastAreaRange& range);
bool isSweepFootprintInFastArea(WorldPoint from, WorldPoint destination,
s32 extentX, s32 extentY, const FastAreaRange& range);
WorldRect areaSweepCandidateBounds(WorldPoint from, WorldPoint destination, s32 extentX, s32 extentY);
SweepBoundsResult clampAreaSweepBounds(WorldPoint from, WorldPoint destination);
GravitySweepPlan planGravitySweep(WorldPoint location, s16 xSpeed, s16 ySpeed, s16 zSpeed,
s16 gravity, u32 timeScale);
CollisionBody makeCollisionBody(WorldPoint location, const ShapeTypeInfo& shapeInfo, bool flipped = false);
CollisionBody makeSweepItemBody(WorldPoint location, const ShapeTypeInfo& shapeInfo, bool flipped = false);
std::optional<SweepItemImpact> sweepSolidItemImpact(
const CollisionBody& moving, WorldPoint destination, const CollisionBody& obstacle);
std::optional<std::vector<SweepCandidateImpact>> collectSolidSweepImpacts(
const LiveFixedMapItems& items, u16 movingItemNumber, WorldPoint destination,
const std::vector<ShapeTypeInfo>& shapes, const FastAreaRange& fastArea);
SweepCollisionResult selectSolidSweepImpact(WorldPoint from, WorldPoint destination,
const std::vector<SweepCandidateImpact>& impacts);
std::optional<SweepCollisionResult> resolveSolidLiveSweep(
const LiveFixedMapItems& items, u16 movingItemNumber, WorldPoint destination,
const std::vector<ShapeTypeInfo>& shapes, const FastAreaRange& fastArea);
bool collisionBodiesOverlap(const CollisionBody& left, const CollisionBody& right);
bool canMoveCollisionBody(
const CollisionBody& body,

View file

@ -9,6 +9,7 @@
namespace remorse {
struct ShapeTypeInfo;
struct WorldRect;
class ProcessKernel;
struct FixedMapEntry {
@ -100,9 +101,13 @@ std::optional<std::vector<u16>> dispatchStagedItemGrab(const StagedFixedMapItem&
class LiveFixedMapItems {
public:
explicit LiveFixedMapItems(std::vector<StagedFixedMapItem> items);
explicit LiveFixedMapItems(std::vector<StagedFixedMapItem> items,
std::vector<StagedContainedFixedMapItem> containedItems = {});
const StagedFixedMapItem* findItem(u16 itemNumber) const;
u16 containedParent(u16 itemNumber) const;
std::optional<StagedFixedMapItem> nearestItem(s32 worldX, s32 worldY, s32 maxDistance) const;
std::optional<std::vector<u16>> sweepCandidateIds(const WorldRect& area, u16 excludedItemNumber) const;
std::optional<u16> allocateItem(StagedFixedMapItem item);
bool insertItem(StagedFixedMapItem item);
bool moveItem(u16 itemNumber, u16 x, u16 y, u8 z);
std::optional<std::vector<u16>> grabItem(u16 itemNumber, const std::vector<ShapeTypeInfo>& shapes,
@ -113,6 +118,9 @@ public:
private:
std::vector<StagedFixedMapItem> items_;
std::vector<bool> allocatedIds_;
std::vector<u16> parentById_;
u16 nextFreeItemNumber_ = 0x100;
};
} // namespace remorse

View file

@ -1,6 +1,7 @@
#include "remorse/collision.h"
#include <algorithm>
#include <array>
#include <cstdint>
namespace remorse {
@ -77,6 +78,40 @@ void appendSolidBody(std::vector<CollisionBody>& bodies, const std::vector<Shape
} // namespace
bool isWorldPointInFastArea(s32 x, s32 y, const FastAreaRange& range)
{
if (x < 0 || x > 0x7fff || y < 0 || y > 0x7fff) {
return false;
}
const s32 blockX = x >> 9;
const s32 blockY = y >> 9;
return range.minSum <= blockX + blockY && blockX + blockY <= range.maxSum &&
range.minDifference <= blockX - blockY && blockX - blockY <= range.maxDifference;
}
bool isSweepFootprintInFastArea(WorldPoint from, WorldPoint destination,
s32 extentX, s32 extentY, const FastAreaRange& range)
{
for (const WorldPoint point : {from, destination}) {
for (const s32 x : {point.x - extentX + 1, point.x}) {
for (const s32 y : {point.y - extentY + 1, point.y}) {
if (!isWorldPointInFastArea(x, y, range)) {
return false;
}
}
}
}
return true;
}
WorldRect areaSweepCandidateBounds(WorldPoint from, WorldPoint destination, s32 extentX, s32 extentY)
{
return {std::max(0, std::min(from.x, destination.x) - extentX),
std::max(0, std::min(from.y, destination.y) - extentY),
std::min(0x7fff, std::max(from.x, destination.x) + 0x100),
std::min(0x7fff, std::max(from.y, destination.y) + 0x100)};
}
SweepBoundsResult clampAreaSweepBounds(WorldPoint from, WorldPoint destination)
{
SweepBoundsResult result{destination};
@ -117,6 +152,152 @@ CollisionBody makeCollisionBody(WorldPoint location, const ShapeTypeInfo& shapeI
static_cast<s32>(shapeInfo.z) * shapeHeightScale};
}
CollisionBody makeSweepItemBody(WorldPoint location, const ShapeTypeInfo& shapeInfo, bool flipped)
{
const s32 extentX = static_cast<s32>(flipped ? shapeInfo.y : shapeInfo.x) * 16;
const s32 extentY = static_cast<s32>(flipped ? shapeInfo.x : shapeInfo.y) * 16;
const s32 extentZ = shapeInfo.z == 0 && (shapeInfo.flags & 1) == 0 ? 1 :
static_cast<s32>(shapeInfo.z) * shapeHeightScale;
return {location, extentX, extentY, extentZ};
}
std::optional<SweepItemImpact> sweepSolidItemImpact(
const CollisionBody& moving, WorldPoint destination, const CollisionBody& obstacle)
{
if (moving.extentX <= 0 || moving.extentY <= 0 || moving.extentZ <= 0 ||
obstacle.extentX <= 0 || obstacle.extentY <= 0 || obstacle.extentZ <= 0) {
return std::nullopt;
}
const std::array<std::int64_t, 3> origin{moving.location.x, moving.location.y, moving.location.z};
const std::array<std::int64_t, 3> delta{
static_cast<std::int64_t>(destination.x) - origin[0],
static_cast<std::int64_t>(destination.y) - origin[1],
static_cast<std::int64_t>(destination.z) - origin[2]};
const std::array<std::int64_t, 3> obstaclePosition{
obstacle.location.x, obstacle.location.y, obstacle.location.z};
const std::array<std::int64_t, 3> movingExtent{moving.extentX, moving.extentY, moving.extentZ};
const std::array<std::int64_t, 3> obstacleExtent{obstacle.extentX, obstacle.extentY, obstacle.extentZ};
std::array<std::int64_t, 3> lower{};
std::array<std::int64_t, 3> upper{};
for (std::size_t axis = 0; axis < 3; ++axis) {
lower[axis] = obstaclePosition[axis] - obstacleExtent[axis] + 1 - origin[axis];
upper[axis] = obstaclePosition[axis] + movingExtent[axis] - 1 - origin[axis];
}
lower[2] = obstaclePosition[2] - movingExtent[2] + 1 - origin[2];
upper[2] = obstaclePosition[2] + obstacleExtent[2] - 1 - origin[2];
for (const int direction : {1, -1}) {
for (std::size_t axis = 0; axis < 3; ++axis) {
const std::int64_t distance = direction > 0 ? lower[axis] : -upper[axis];
const std::int64_t extent = delta[axis] * direction;
if (distance <= 0 || distance > extent) {
continue;
}
bool withinOtherAxes = true;
for (std::size_t other = 0; other < 3; ++other) {
if (other == axis) {
continue;
}
const std::int64_t progress = delta[other] * distance;
if (progress < lower[other] * extent || progress > upper[other] * extent) {
withinOtherAxes = false;
break;
}
}
if (withinOtherAxes) {
const std::int64_t beforeContact = distance - 1;
std::array<s32, 3> resolved{};
for (std::size_t coordinate = 0; coordinate < 3; ++coordinate) {
resolved[coordinate] = static_cast<s32>(origin[coordinate] +
delta[coordinate] * beforeContact / extent);
}
return SweepItemImpact{{resolved[0], resolved[1], resolved[2]},
static_cast<u8>(1u << axis)};
}
}
}
return std::nullopt;
}
std::optional<std::vector<SweepCandidateImpact>> collectSolidSweepImpacts(
const LiveFixedMapItems& items, u16 movingItemNumber, WorldPoint destination,
const std::vector<ShapeTypeInfo>& shapes, const FastAreaRange& fastArea)
{
const auto* movingItem = items.findItem(movingItemNumber);
if (movingItem == nullptr || movingItem->data.shape >= shapes.size() ||
destination.x < 0 || destination.x > 0x7fff || destination.y < 0 ||
destination.y > 0x7fff || destination.z < 0 || destination.z > 0xfa) {
return std::nullopt;
}
const WorldPoint from{movingItem->data.x, movingItem->data.y, movingItem->data.z};
const auto movingBody = makeSweepItemBody(from, shapes[movingItem->data.shape],
(movingItem->data.flags & flippedFlag) != 0);
if (!isSweepFootprintInFastArea(from, destination, movingBody.extentX,
movingBody.extentY, fastArea)) {
return std::nullopt;
}
const auto candidates = items.sweepCandidateIds(areaSweepCandidateBounds(from, destination,
movingBody.extentX, movingBody.extentY), movingItemNumber);
if (!candidates) {
return std::nullopt;
}
std::vector<SweepCandidateImpact> impacts;
for (const u16 itemNumber : *candidates) {
const auto* item = items.findItem(itemNumber);
if (item == nullptr || item->data.shape >= shapes.size()) {
return std::nullopt;
}
const auto& shape = shapes[item->data.shape];
if ((shape.flags & solidFlag) == 0) {
continue;
}
const auto obstacle = makeSweepItemBody({item->data.x, item->data.y, item->data.z},
shape, (item->data.flags & flippedFlag) != 0);
if (const auto impact = sweepSolidItemImpact(movingBody, destination, obstacle)) {
impacts.push_back({itemNumber, *impact});
}
}
return impacts;
}
SweepCollisionResult selectSolidSweepImpact(WorldPoint from, WorldPoint destination,
const std::vector<SweepCandidateImpact>& impacts)
{
SweepCollisionResult result{destination};
for (const auto& candidate : impacts) {
result.failedDirections |= candidate.impact.failedDirections;
const auto& point = candidate.impact.resolved;
if (candidate.itemNumber != 0 &&
(std::abs(static_cast<std::int64_t>(point.x) - from.x) <
std::abs(static_cast<std::int64_t>(result.destination.x) - from.x) ||
std::abs(static_cast<std::int64_t>(point.y) - from.y) <
std::abs(static_cast<std::int64_t>(result.destination.y) - from.y) ||
std::abs(static_cast<std::int64_t>(point.z) - from.z) <
std::abs(static_cast<std::int64_t>(result.destination.z) - from.z))) {
result.destination = point;
result.firstCollision = candidate.itemNumber;
}
}
return result;
}
std::optional<SweepCollisionResult> resolveSolidLiveSweep(
const LiveFixedMapItems& items, u16 movingItemNumber, WorldPoint destination,
const std::vector<ShapeTypeInfo>& shapes, const FastAreaRange& fastArea)
{
const auto* movingItem = items.findItem(movingItemNumber);
if (movingItem == nullptr) {
return std::nullopt;
}
const auto impacts = collectSolidSweepImpacts(items, movingItemNumber, destination,
shapes, fastArea);
if (!impacts) {
return std::nullopt;
}
return selectSolidSweepImpact({movingItem->data.x, movingItem->data.y, movingItem->data.z},
destination, *impacts);
}
bool collisionBodiesOverlap(const CollisionBody& left, const CollisionBody& right)
{
return overlapsAt(left, left.location, right);

View file

@ -2,6 +2,7 @@
#include "remorse/entity_dispatch_entry.h"
#include "remorse/file_system.h"
#include "remorse/map_renderer.h"
#include "remorse/type_flags.h"
#include <algorithm>
@ -412,11 +413,30 @@ std::optional<std::vector<u16>> dispatchStagedItemGrab(const StagedFixedMapItem&
return processIds;
}
LiveFixedMapItems::LiveFixedMapItems(std::vector<StagedFixedMapItem> items) : items_(std::move(items))
LiveFixedMapItems::LiveFixedMapItems(std::vector<StagedFixedMapItem> items,
std::vector<StagedContainedFixedMapItem> containedItems)
: items_(std::move(items)), allocatedIds_(0x2800), parentById_(0x2800)
{
if (!buildStagedItemBlockChains(items_)) {
throw std::invalid_argument("invalid live item IDs or coordinates");
}
for (const auto& item : items_) {
allocatedIds_[item.itemNumber] = true;
}
for (const auto& contained : containedItems) {
const u16 itemNumber = contained.itemNumber;
if (itemNumber < 0x100 || itemNumber >= allocatedIds_.size() || allocatedIds_[itemNumber]) {
throw std::invalid_argument("invalid contained item ID");
}
allocatedIds_[itemNumber] = true;
}
for (const auto& contained : containedItems) {
if (contained.parentItemNumber < 0x100 || contained.parentItemNumber >= contained.itemNumber ||
!allocatedIds_[contained.parentItemNumber]) {
throw std::invalid_argument("invalid contained parent ID");
}
parentById_[contained.itemNumber] = contained.parentItemNumber;
}
}
const StagedFixedMapItem* LiveFixedMapItems::findItem(u16 itemNumber) const
@ -429,12 +449,61 @@ const StagedFixedMapItem* LiveFixedMapItems::findItem(u16 itemNumber) const
return nullptr;
}
u16 LiveFixedMapItems::containedParent(u16 itemNumber) const
{
return itemNumber < parentById_.size() ? parentById_[itemNumber] : 0;
}
std::optional<StagedFixedMapItem> LiveFixedMapItems::nearestItem(s32 worldX, s32 worldY,
s32 maxDistance) const
{
return nearestStagedFixedMapItem(items_, worldX, worldY, maxDistance);
}
std::optional<std::vector<u16>> LiveFixedMapItems::sweepCandidateIds(const WorldRect& area,
u16 excludedItemNumber) const
{
if (area.minX < 0 || area.minY < 0 || area.maxX > 0x7fff || area.maxY > 0x7fff ||
area.minX > area.maxX || area.minY > area.maxY) {
return std::nullopt;
}
const auto chains = buildStagedItemBlockChains(items_);
if (!chains) {
return std::nullopt;
}
std::vector<const StagedFixedMapItem*> byId(chains->next.size());
for (const auto& item : items_) {
byId[item.itemNumber] = &item;
}
const ItemFindArea itemArea{static_cast<u16>(area.minX), static_cast<u16>(area.minY),
static_cast<u16>(area.maxX), static_cast<u16>(area.maxY)};
std::vector<u16> candidates;
for (const u16 itemNumber : itemFindCandidateOrder(itemArea, *chains)) {
const auto& item = *byId[itemNumber];
if (itemNumber != excludedItemNumber && item.data.x >= area.minX && item.data.x <= area.maxX &&
item.data.y >= area.minY && item.data.y <= area.maxY) {
candidates.push_back(itemNumber);
}
}
return candidates;
}
std::optional<u16> LiveFixedMapItems::allocateItem(StagedFixedMapItem item)
{
if (item.data.x > 0x7fff || item.data.y > 0x7fff) {
return std::nullopt;
}
while (nextFreeItemNumber_ < allocatedIds_.size() && allocatedIds_[nextFreeItemNumber_]) {
++nextFreeItemNumber_;
}
if (nextFreeItemNumber_ == allocatedIds_.size()) {
return std::nullopt;
}
item.itemNumber = nextFreeItemNumber_;
insertItem(item);
return item.itemNumber;
}
bool LiveFixedMapItems::insertItem(StagedFixedMapItem item)
{
if (item.itemNumber < 0x100 || item.itemNumber >= 0x2800 || item.data.x > 0x7fff ||
@ -443,6 +512,8 @@ bool LiveFixedMapItems::insertItem(StagedFixedMapItem item)
}
item.data.z = std::min<u8>(item.data.z, 0xfa);
items_.push_back(item);
allocatedIds_[item.itemNumber] = true;
parentById_[item.itemNumber] = 0;
return true;
}

View file

@ -160,6 +160,16 @@ void loadSceneAsync(HWND window, AppState& state)
PostMessageW(window, sceneReadyMessage, 0, 0);
return;
}
std::vector<remorse::StagedContainedFixedMapItem> containedItems;
if (map->index != 0) {
const auto contained = remorse::stageContainedFixedMapItems(*map, *shapeTypes);
if (!contained) {
setLoadFailure(state, L"Contained map items could not be staged.");
PostMessageW(window, sceneReadyMessage, 0, 0);
return;
}
containedItems = std::move(*contained);
}
auto collisionBodies = remorse::collectMapCollisionBodies(*map, *shapeTypes, *globObjects);
const auto usecodePath = remorse::resolveGameDataPath(
state.root, std::filesystem::path("USECODE") / "EUSECODE.FLX");
@ -281,7 +291,7 @@ void loadSceneAsync(HWND window, AppState& state)
state.playerFrames = std::move(playerFrames);
state.playerPalette = *palette;
if (stagedItems) {
state.liveItems.emplace(std::move(*stagedItems));
state.liveItems.emplace(std::move(*stagedItems), std::move(containedItems));
}
state.sceneLoaded = true;
}

View file

@ -4,6 +4,24 @@
int main()
{
const remorse::FastAreaRange fastArea{2, 4, 0, 2};
assert(remorse::isWorldPointInFastArea(512, 512, fastArea));
assert(!remorse::isWorldPointInFastArea(-1, 512, fastArea));
assert(!remorse::isWorldPointInFastArea(0x8000, 512, fastArea));
assert(remorse::isSweepFootprintInFastArea({1000, 1000, 0}, {2000, 1000, 0},
32, 32, fastArea));
assert(!remorse::isSweepFootprintInFastArea({1000, 1000, 0}, {2000, 1000, 0},
32, 32, {2, 3, 0, 2}));
assert(!remorse::isSweepFootprintInFastArea({1000, 1000, 0}, {2000, 1000, 0},
32, 32, {2, 4, 1, 2}));
const auto sweepArea = remorse::areaSweepCandidateBounds({511, 512, 0}, {1024, 1536, 0}, 32, 64);
assert(sweepArea.minX == 479 && sweepArea.minY == 448 &&
sweepArea.maxX == 1280 && sweepArea.maxY == 1792);
const auto reverseArea = remorse::areaSweepCandidateBounds({1024, 1536, 0}, {511, 512, 0}, 32, 64);
assert(reverseArea.minX == sweepArea.minX && reverseArea.maxY == sweepArea.maxY);
const auto edgeSweepArea = remorse::areaSweepCandidateBounds({10, 10, 0}, {0x7fff, 0x7fff, 0}, 32, 64);
assert(edgeSweepArea.minX == 0 && edgeSweepArea.minY == 0 &&
edgeSweepArea.maxX == 0x7fff && edgeSweepArea.maxY == 0x7fff);
const auto outsideBounds = remorse::clampAreaSweepBounds({10, 20, 10}, {-3, 0x8000, 252});
assert(outsideBounds.destination.x == 0 && outsideBounds.destination.y == 0x7fff &&
outsideBounds.destination.z == 250 && outsideBounds.failedDirections == 7 &&
@ -56,6 +74,105 @@ int main()
assert(flipped.extentX == 128);
assert(flipped.extentY == 64);
const auto sweepItem = remorse::makeSweepItemBody({300, 300, 0}, obstacleInfo, true);
assert(sweepItem.extentX == 64 && sweepItem.extentY == 32 && sweepItem.extentZ == 64);
obstacleInfo.z = 0;
const auto zeroHeightItem = remorse::makeSweepItemBody({300, 300, 0}, obstacleInfo);
assert(zeroHeightItem.extentZ == 1);
obstacleInfo.flags = 1;
assert(remorse::makeSweepItemBody({300, 300, 0}, obstacleInfo).extentZ == 0);
obstacleInfo.z = 8;
obstacleInfo.flags = 0;
const remorse::CollisionBody sweepActor{{100, 100, 0}, 32, 32, 16};
const remorse::CollisionBody sweepWall{{200, 100, 0}, 32, 32, 16};
const auto rightHit = remorse::sweepSolidItemImpact(sweepActor, {250, 100, 0}, sweepWall);
assert(rightHit && rightHit->failedDirections == 1 && rightHit->resolved.x == 168);
const auto leftHit = remorse::sweepSolidItemImpact({{300, 100, 0}, 32, 32, 16},
{150, 100, 0}, sweepWall);
assert(leftHit && leftHit->failedDirections == 1 && leftHit->resolved.x == 232);
const auto upHit = remorse::sweepSolidItemImpact(sweepActor, {100, 250, 0},
{{100, 200, 0}, 32, 32, 16});
assert(upHit && upHit->failedDirections == 2 && upHit->resolved.y == 168);
const auto downHit = remorse::sweepSolidItemImpact({{100, 300, 0}, 32, 32, 16},
{100, 150, 0}, {{100, 200, 0}, 32, 32, 16});
assert(downHit && downHit->failedDirections == 2 && downHit->resolved.y == 232);
const auto ascendingHit = remorse::sweepSolidItemImpact(sweepActor, {100, 100, 30},
{{100, 100, 20}, 32, 32, 16});
assert(ascendingHit && ascendingHit->failedDirections == 4 && ascendingHit->resolved.z == 4);
const auto descendingHit = remorse::sweepSolidItemImpact({{100, 100, 40}, 32, 32, 16},
{100, 100, 0}, {{100, 100, 20}, 32, 32, 16});
assert(descendingHit && descendingHit->failedDirections == 4 && descendingHit->resolved.z == 36);
assert(!remorse::sweepSolidItemImpact(sweepActor, {250, 100, 0},
{{200, 200, 0}, 32, 32, 16}));
remorse::StagedFixedMapItem movingItem;
movingItem.itemNumber = 0x100;
movingItem.data.x = 512;
movingItem.data.y = 512;
movingItem.data.shape = 1;
auto wallItem = movingItem;
wallItem.itemNumber = 0x101;
wallItem.data.x = 640;
wallItem.data.shape = 2;
auto harmlessItem = wallItem;
harmlessItem.itemNumber = 0x102;
harmlessItem.data.x = 600;
harmlessItem.data.shape = 3;
remorse::LiveFixedMapItems liveSweepItems({movingItem, wallItem, harmlessItem});
std::vector<remorse::ShapeTypeInfo> sweepShapes(4);
sweepShapes[1].x = sweepShapes[1].y = sweepShapes[1].z = 2;
sweepShapes[2] = sweepShapes[1];
sweepShapes[2].flags = 2;
sweepShapes[3] = sweepShapes[1];
const remorse::FastAreaRange allBlocks{-128, 128, -128, 128};
const auto liveImpacts = remorse::collectSolidSweepImpacts(liveSweepItems, 0x100,
{700, 512, 0}, sweepShapes, allBlocks);
assert(liveImpacts && liveImpacts->size() == 1);
assert((*liveImpacts)[0].itemNumber == 0x101 &&
(*liveImpacts)[0].impact.failedDirections == 1 &&
(*liveImpacts)[0].impact.resolved.x == 608);
auto nextWall = wallItem;
nextWall.itemNumber = 0x103;
nextWall.data.x = 670;
sweepShapes[2].x = 1;
sweepShapes[2].y = 4;
wallItem.data.flags = 0x20;
remorse::LiveFixedMapItems flippedSweepItems({movingItem, wallItem, nextWall, harmlessItem});
const auto flippedImpacts = remorse::collectSolidSweepImpacts(flippedSweepItems, 0x100,
{700, 512, 0}, sweepShapes, allBlocks);
assert(flippedImpacts && flippedImpacts->size() == 2);
assert((*flippedImpacts)[0].itemNumber == 0x103 && (*flippedImpacts)[0].impact.resolved.x == 654);
assert((*flippedImpacts)[1].itemNumber == 0x101 && (*flippedImpacts)[1].impact.resolved.x == 576);
const auto nearestImpact = remorse::selectSolidSweepImpact({512, 512, 0},
{700, 512, 0}, *flippedImpacts);
assert(nearestImpact.firstCollision == 0x101 && nearestImpact.destination.x == 576 &&
nearestImpact.failedDirections == 1);
const auto resolvedLive = remorse::resolveSolidLiveSweep(flippedSweepItems, 0x100,
{700, 512, 0}, sweepShapes, allBlocks);
assert(resolvedLive && resolvedLive->firstCollision == 0x101 &&
resolvedLive->destination.x == 576 && resolvedLive->failedDirections == 1);
assert(!remorse::resolveSolidLiveSweep(flippedSweepItems, 0x100,
{700, 512, 0}, sweepShapes, {2, 2, 0, 0}));
const auto noImpact = remorse::selectSolidSweepImpact({512, 512, 0}, {700, 512, 0}, {});
assert(noImpact.firstCollision == 0 && noImpact.destination.x == 700 &&
noImpact.failedDirections == 0);
const std::vector<remorse::SweepCandidateImpact> tiedImpacts{
{0x101, {{576, 512, 0}, 1}}, {0x103, {{576, 512, 0}, 2}}};
const auto tiedImpact = remorse::selectSolidSweepImpact({512, 512, 0},
{700, 512, 0}, tiedImpacts);
assert(tiedImpact.firstCollision == 0x101 && tiedImpact.failedDirections == 3);
const std::vector<remorse::SweepCandidateImpact> mixedAxisImpacts{
{0x101, {{540, 590, 0}, 1}}, {0x103, {{550, 550, 0}, 2}}};
const auto mixedAxis = remorse::selectSolidSweepImpact({512, 512, 0},
{700, 700, 0}, mixedAxisImpacts);
assert(mixedAxis.firstCollision == 0x103 && mixedAxis.destination.x == 550 &&
mixedAxis.destination.y == 550 && mixedAxis.failedDirections == 3);
assert(!remorse::collectSolidSweepImpacts(liveSweepItems, 0x100,
{700, 512, 0}, sweepShapes, {2, 2, 0, 0}));
assert(!remorse::collectSolidSweepImpacts(liveSweepItems, 0x105,
{700, 512, 0}, sweepShapes, allBlocks));
remorse::FixedMap map;
remorse::FixedMapEntry solid;
solid.x = 500;

View file

@ -1,6 +1,7 @@
#include "remorse/entity_dispatch_entry.h"
#include "remorse/file_system.h"
#include "remorse/fixed_map.h"
#include "remorse/map_renderer.h"
#include "remorse/type_flags.h"
#include <cassert>
@ -181,6 +182,9 @@ int main()
assert(!liveItems.moveItem(0x100, 0x8000, 0, 0));
assert(liveItems.moveItem(0x100, 768, 511, 81));
assert(liveItems.findItem(0x100)->data.x == 768 && blockItems[0].data.x == 511);
const auto sweepBefore = liveItems.sweepCandidateIds({511, 511, 512, 512}, 0x105);
assert(sweepBefore && (*sweepBefore == std::vector<remorse::u16>{0x103, 0x102}));
assert(!liveItems.sweepCandidateIds({-1, 0, 512, 512}, 0x105));
assert(liveItems.nearestItem(768 * 2, 511 * 2, 0)->itemNumber == 0x100);
assert(!liveItems.nearestItem(511 * 2, 511 * 2, -1));
assert(!liveItems.grabItem(0x106, searchShapes, liveKernel, liveGroups, 14));
@ -197,6 +201,8 @@ int main()
reorderedKernel.createProcess(1, reorderedGroups);
}
assert(reorderedItems.moveItem(0x100, 511, 511, 81));
const auto sweepAfter = reorderedItems.sweepCandidateIds({511, 511, 512, 512}, 0x105);
assert(sweepAfter && (*sweepAfter == std::vector<remorse::u16>{0x100, 0x103, 0x102}));
const auto reorderedGrab = reorderedItems.grabItem(0x105, searchShapes,
reorderedKernel, reorderedGroups, 14);
assert(reorderedGrab && reorderedGrab->size() == 2 && (*reorderedGrab)[0] == 3 &&
@ -221,6 +227,14 @@ int main()
insertedKernel, insertedGroups, 14);
assert(insertedGrab && insertedGrab->size() == 3 && (*insertedGrab)[0] == 3);
assert(insertedKernel.findProcessForItemAndType(0x106, 0xf1) == insertedKernel.processAt(3));
remorse::LiveFixedMapItems allocatedItems(blockItems, {{0x101, 0x100, 0}});
newItem.itemNumber = 0;
assert(!allocatedItems.findItem(0x101));
assert(allocatedItems.allocateItem(newItem) == 0x106);
assert(allocatedItems.findItem(0x106)->data.x == 511);
assert(allocatedItems.allocateItem(newItem) == 0x107);
newItem.data.x = 0x8000;
assert(!allocatedItems.allocateItem(newItem) && !allocatedItems.findItem(0x108));
remorse::LiveFixedMapItems movingItems(blockItems);
remorse::ProcessKernel movingKernel;
remorse::u16 movingGroups[32]{};
@ -326,6 +340,25 @@ int main()
assert((*contained)[0].itemNumber == 0x101 && (*contained)[0].parentItemNumber == 0x100);
assert((*contained)[1].itemNumber == 0x102 && (*contained)[1].parentItemNumber == 0x101);
assert((*contained)[2].itemNumber == 0x103 && (*contained)[2].parentItemNumber == 0x100);
const auto directContainerItems = remorse::stageFixedMapItems(containedMap);
assert(directContainerItems && directContainerItems->size() == 2);
remorse::LiveFixedMapItems nestedItems(*directContainerItems, *contained);
assert(nestedItems.containedParent(0x101) == 0x100 &&
nestedItems.containedParent(0x102) == 0x101 && nestedItems.containedParent(0x103) == 0x100);
remorse::StagedFixedMapItem nestedNewItem = directContainerItems->front();
assert(nestedItems.allocateItem(nestedNewItem) == 0x105);
assert(!nestedItems.findItem(0x101) && !nestedItems.findItem(0x102) &&
!nestedItems.findItem(0x103) && nestedItems.findItem(0x105));
nestedNewItem.itemNumber = 0x101;
assert(nestedItems.insertItem(nestedNewItem));
assert(nestedItems.containedParent(0x101) == 0 && nestedItems.containedParent(0x102) == 0x101);
std::vector<remorse::StagedContainedFixedMapItem> fullItemRange;
for (remorse::u16 itemNumber = 0x101; itemNumber < 0x2800; ++itemNumber) {
fullItemRange.push_back({itemNumber, 0x100, 0});
}
remorse::LiveFixedMapItems exhaustedItems({directContainerItems->front()}, fullItemRange);
assert(!exhaustedItems.allocateItem(nestedNewItem));
assert(!exhaustedItems.findItem(0x101) && exhaustedItems.containedParent(0x101) == 0x100);
containerShapes[1].family = 0;
assert(!remorse::stageContainedFixedMapItems(containedMap, containerShapes));
assert(remorse::itemGrabCanCreateProcess((*stagedItems)[0]));