feat(vendor): Slice 6 buy arc — shop items are real objects, vendor selection is THE selection, and Buy works (0x005F)
Some checks are pending
Headless portability / portable-headless (ubuntu-latest) (push) Waiting to run
Headless portability / portable-headless (windows-latest) (push) Waiting to run
Headless portability / linux-graphical (push) Waiting to run
Headless portability / linux-vulkan (push) Waiting to run

Three ordered pieces in one landing (the shared controller/composition
files carry all three; the internal order was 6.1 -> 6.2 -> 6.3):

6.1 VendorShopItemMaterializer diff-merges the shop list into the live
ClientObjectTable on VendorState transitions (so client-local close and
session teardown retire the entries too) and never claims a guid it did
not add — ACE's UniqueItemsForSale can re-list a guid a player once
held (AP-163 files the collision-skip; no retail counterpart traced).
Right-click examine on shop items now routes through the ordinary
appraisal path — the 5.4 F7c blocker dissolves with the table entries.

6.2 SelectionChangeSource.Vendor: row clicks, auto-select, and examine
all flow through the canonical SelectionState; the status bar and the
existing byte-faithful StackSplitQuantityState slider light up
unmodified. VendorSplitPolicy is the single 0xDC41CB0 mask owner; the
slider VALUE seeds to 1 for exempt items while maxSplitSize keeps the
stack (the splitSize/maxSplitSize distinction, research §B.3).
Selection clears at retail's actual site — VendorItemsUI::RemoveFromShop
(pc:202848), not a CloseVendor-level clear that does not exist.

6.3 BuildBuy (0x005F): vendorGuid, count, (i32 amount, u32 guid) pairs,
and the trailing alternateCurrencyId the REAL client sends
(CM_Vendor::Event_Buy pc:689288) though ACE's reader ignores it.
TryBuy rides the EXISTING J5.2 one-request-at-a-time reservation and
completes on UseDone; the Buy button disables while a request is in
flight. The reconciliation round-trip (money property update, inventory
CreateObject, ApproachVendor refresh -> panel rebuild) is proven by a
synthetic-inbound test against existing machinery — no new owner.

Register: AP-161 narrowed (selection + examine residuals close;
staging/Sell remain; double-click-to-buy confirmed ABSENT from retail
with negative evidence cited — we match retail). AP-162 files the
conscious no-client-side-affordability-precheck deferral.

Clean-room complete solution: 11,368 passed / 4 skipped / 0 failed.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
Erik 2026-08-07 20:28:26 +02:00
parent c884a938e0
commit 97cf873870
19 changed files with 1577 additions and 65 deletions

View file

@ -27,6 +27,7 @@ public sealed class ItemInteractionControllerTests
public readonly List<uint> Drops = new();
public readonly List<(uint Item, uint Amount)> SplitDrops = new();
public readonly List<(uint Target, uint Item, uint Amount)> Gives = new();
public readonly List<(uint VendorGuid, uint ItemGuid, int Amount, uint AlternateCurrencyId)> Buys = new();
public readonly List<string> Toasts = new();
public readonly List<string> SystemMessages = new();
public readonly List<CombatMode> CombatModeRequests = new();
@ -94,7 +95,9 @@ public sealed class ItemInteractionControllerTests
},
combatState: Combat,
sendChangeCombatMode: CombatModeRequests.Add,
requestUse: requestUse);
requestUse: requestUse,
sendBuy: (vendorGuid, itemGuid, amount, alternateCurrencyId) =>
Buys.Add((vendorGuid, itemGuid, amount, alternateCurrencyId)));
}
public ItemInteractionController Controller { get; }
@ -2145,4 +2148,123 @@ public sealed class ItemInteractionControllerTests
Assert.Equal(0, h.Controller.BusyCount);
Assert.Equal(InteractionModeKind.None, h.Controller.InteractionState.Current.Kind);
}
// ── Slice 6.3: TryBuy ───────────────────────────────────────────────
[Fact]
public void TryBuy_Succeeds_SendsBuyAndTakesTheSharedUseReservation()
{
var h = new Harness();
bool result = h.Controller.TryBuy(
vendorGuid: 0x40001000u,
itemGuid: 0x50002000u,
amount: 1,
alternateCurrencyId: 0u);
Assert.True(result);
Assert.Equal(
new[] { (0x40001000u, 0x50002000u, 1, 0u) },
h.Buys);
// BeginUseRequestReservation increments BusyCount synchronously,
// before/independent of any wire response -- this is what makes the
// Buy button disable immediately (research doc §A.4: "no second
// gate", the SAME BusyCount>0 check every other request rides).
Assert.Equal(1, h.Controller.BusyCount);
}
[Fact]
public void TryBuy_StackedQuantity_ForwardsTheExactAmount()
{
var h = new Harness();
Assert.True(h.Controller.TryBuy(0x40001000u, 0x50002001u, 25, 0u));
Assert.Equal(25, h.Buys.Single().Amount);
}
[Fact]
public void TryBuy_AlternateCurrencyVendor_ForwardsTheCurrencyWcid()
{
var h = new Harness();
Assert.True(h.Controller.TryBuy(0x40001000u, 0x50002000u, 1, 0x12345678u));
Assert.Equal(0x12345678u, h.Buys.Single().AlternateCurrencyId);
}
[Fact]
public void TryBuy_WhileAnotherRequestIsBusy_IsRejectedAndSendsNothing()
{
var h = new Harness();
h.Controller.IncrementBusyCount(); // simulates any other in-flight request
bool result = h.Controller.TryBuy(0x40001000u, 0x50002000u, 1, 0u);
Assert.False(result);
Assert.Empty(h.Buys);
Assert.Equal(1, h.Controller.BusyCount); // unchanged -- no second reservation taken
}
[Fact]
public void TryBuy_ASecondBuyWhileTheFirstIsInFlight_IsRejected()
{
var h = new Harness();
Assert.True(h.Controller.TryBuy(0x40001000u, 0x50002000u, 1, 0u));
bool second = h.Controller.TryBuy(0x40001000u, 0x50002001u, 1, 0u);
Assert.False(second);
Assert.Single(h.Buys);
Assert.Equal(1, h.Controller.BusyCount);
}
[Theory]
[InlineData(0u, 0x50002000u, 1)]
[InlineData(0x40001000u, 0u, 1)]
[InlineData(0x40001000u, 0x50002000u, 0)]
[InlineData(0x40001000u, 0x50002000u, -1)]
public void TryBuy_InvalidArguments_IsRejectedWithoutTakingAReservation(
uint vendorGuid, uint itemGuid, int amount)
{
var h = new Harness();
bool result = h.Controller.TryBuy(vendorGuid, itemGuid, amount, 0u);
Assert.False(result);
Assert.Empty(h.Buys);
Assert.Equal(0, h.Controller.BusyCount);
}
[Fact]
public void TryBuy_CompleteUse_ReleasesTheReservationAndReenablesFurtherRequests()
{
// Research doc §A.4: UseDone (0x01C7) is the completion signal for
// Buy, resolved through the SAME RuntimeInteractionTransactionState.
// CompleteUse the existing UseDone handler already calls -- no new
// completion plumbing needed on the receive side.
var h = new Harness();
Assert.True(h.Controller.TryBuy(0x40001000u, 0x50002000u, 1, 0u));
Assert.Equal(1, h.Controller.BusyCount);
h.Controller.CompleteUse(0);
Assert.Equal(0, h.Controller.BusyCount);
// The gate is free again -- a second Buy can now proceed.
Assert.True(h.Controller.TryBuy(0x40001000u, 0x50002001u, 1, 0u));
Assert.Equal(2, h.Buys.Count);
}
[Fact]
public void TryBuy_FailedUseDone_AlsoReleasesTheReservation()
{
// A.2's failure paths all still end in exactly one SendUseDoneEvent
// -- success or failure, the reservation resolves the same way.
var h = new Harness();
Assert.True(h.Controller.TryBuy(0x40001000u, 0x50002000u, 1, 0u));
h.Controller.CompleteUse(0x0009u); // an arbitrary nonzero WeenieError
Assert.Equal(0, h.Controller.BusyCount);
}
}

View file

@ -94,6 +94,9 @@ public class SelectedObjectControllerTests
public readonly Dictionary<uint, bool> HasHealthMap = new();
public readonly Dictionary<uint, float> ManaMap = new();
public readonly Dictionary<uint, uint> StackMap = new();
// Slice 6.2: vendor-owned split-exempt predicate — see
// SelectedObjectController.Bind's isVendorSplitExempt parameter.
public readonly Dictionary<uint, bool> VendorSplitExemptMap = new();
public void FireSelection(uint? g)
{
@ -135,7 +138,8 @@ public class SelectedObjectControllerTests
unsubscribeObjectUpdated: h =>
{
if (ObjectUpdatedHandler == h) ObjectUpdatedHandler = null;
});
},
isVendorSplitExempt: g => VendorSplitExemptMap.TryGetValue(g, out var v) && v);
}
// ── B1: Bind initialisation ──────────────────────────────────────────────

View file

@ -4,6 +4,8 @@ using AcDream.App.UI;
using AcDream.App.UI.Layout;
using AcDream.Core.Items;
using AcDream.Core.Properties;
using AcDream.Core.Selection;
using AcDream.Runtime.Gameplay;
namespace AcDream.App.Tests.UI.Layout;
@ -41,13 +43,26 @@ public sealed class VendorUiControllerTests
Visible = false,
});
var objects = new ClientObjectTable();
using var itemInteraction = new ItemInteractionController(
objects,
new RuntimeInteractionTransactionState(new InventoryTransactionState(objects)),
new InteractionState(),
playerGuid: static () => 0u,
sendUse: null,
sendUseWithTarget: null,
sendWield: null,
sendDrop: null);
VendorUiController? controller = VendorUiController.Bind(
layout,
new VendorState(),
window,
static (_, _, _, _, _) => 0u,
new ClientObjectTable(),
objects,
static () => 0u,
itemInteraction,
new SelectionState(),
new StackSplitQuantityState(),
datFont: null,
debugFont: null,
static _ => (0u, 0, 0));
@ -60,9 +75,11 @@ public sealed class VendorUiControllerTests
// F2/F3: a deterministic non-zero player coin total so the cost-text
// "(you have ...)" tail is assertable.
public const int DefaultPlayerCoinValue = 1500;
private const uint PlayerGuid = 0x50000001u;
public const uint PlayerGuid = 0x50000001u;
public readonly VendorState State = new();
public readonly SelectionState Selection = new();
public readonly StackSplitQuantityState SplitQuantity = new();
public readonly UiRoot Screen = new() { Width = 800f, Height = 600f };
public readonly ClientObjectTable Objects = new();
public readonly UiItemList ItemList = new();
@ -81,6 +98,9 @@ public sealed class VendorUiControllerTests
public readonly UiButton AddButton;
public readonly RetailWindowHandle Window;
public readonly VendorUiController Controller;
public readonly List<uint> Examines = new();
public readonly List<(uint VendorGuid, uint ItemGuid, int Amount, uint AlternateCurrencyId)> Buys = new();
public readonly ItemInteractionController ItemInteraction;
public Harness()
{
@ -145,6 +165,19 @@ public sealed class VendorUiControllerTests
Resizable = false,
});
ItemInteraction = new ItemInteractionController(
Objects,
new RuntimeInteractionTransactionState(new InventoryTransactionState(Objects)),
new InteractionState(),
playerGuid: static () => PlayerGuid,
sendUse: null,
sendUseWithTarget: null,
sendWield: null,
sendDrop: null,
sendExamine: Examines.Add,
sendBuy: (vendorGuid, itemGuid, amount, alternateCurrencyId) =>
Buys.Add((vendorGuid, itemGuid, amount, alternateCurrencyId)));
Controller = VendorUiController.Bind(
layout,
State,
@ -155,6 +188,9 @@ public sealed class VendorUiControllerTests
static (_, iconId, underlay, overlay, effects) => iconId + underlay + overlay + effects,
Objects,
static () => PlayerGuid,
ItemInteraction,
Selection,
SplitQuantity,
datFont: null,
debugFont: null,
static _ => (0u, 0, 0))!;
@ -611,4 +647,204 @@ public sealed class VendorUiControllerTests
Assert.False(h.SellingPage.Visible);
Assert.Equal(1, h.ItemList.GetNumUIItems());
}
[Fact]
public void RightClickShopRow_SelectsAndRoutesThroughItemInteractionExamine()
{
// Slice 6.1: mirrors ExternalContainerControllerTests'
// RightClickLoot_selectsAndExaminesWithoutPickingUp — the shop list
// wires ExamineItemRequested the same way the container lists do,
// now that shop items are materialized into ClientObjectTable
// (AP-161 finding #2's examine gap closes here).
var h = new Harness();
h.State.Apply(VendorGuid, Profile(), new[]
{
new VendorShopItem(ArmorItemGuid, -1, 2u, "Chainmail", (uint)ItemType.Armor, 200u, 500),
new VendorShopItem(FoodItemGuid, -1, 1u, "Bread", (uint)ItemType.Food, 100u, 5),
});
// Food, not the auto-selected Armor default, so the assertion below
// proves the right click itself drove the selection.
UiItemSlot? foodCell = null;
object? foodPayload = h.TypeMenu.Items.First(i => i.Label == "Food").Payload;
h.TypeMenu.OnSelect!.Invoke(foodPayload);
foodCell = h.ItemList.GetItem(0);
Assert.Equal(FoodItemGuid, foodCell!.ItemId);
foodCell.OnEvent(new UiEvent(0u, foodCell, UiEventType.RightClick));
Assert.Equal(new[] { FoodItemGuid }, h.Examines);
Assert.Equal("Bread", GetText(h.ItemNameText));
Assert.True(foodCell.Selected);
}
// ── Slice 6.3: Buy button ────────────────────────────────────────────
[Fact]
public void BuyButton_Press_NonStackedItem_BuysQuantityOne()
{
var h = new Harness();
h.State.Apply(VendorGuid, Profile(), new[]
{
new VendorShopItem(ArmorItemGuid, -1, 2u, "Chainmail", (uint)ItemType.Armor, 200u, 500),
});
// F4 auto-selected the sole item; its own stack size (default/absent)
// is <=1, so StackSplitQuantityState was never seeded above 1 either
// (this harness doesn't mount SelectedObjectController, so the split
// state starts at its class default Value=1/Maximum=1 — exactly what
// production would also show for a non-stacked item).
h.BuyButton.OnClick!.Invoke();
Assert.Equal(
new[] { (VendorGuid, ArmorItemGuid, 1, 0u) },
h.Buys);
}
[Fact]
public void BuyButton_Press_StackedItem_UsesTheLiveSplitSliderQuantity()
{
// Slice 6.3: BuySingleItem (pc:201674-201681) reads the CURRENT
// slider value, not the full stack. This harness doesn't mount
// SelectedObjectController (the toolbar owns that seeding in
// production), so the test seeds SplitQuantity directly to stand in
// for "the player selected this item, then dragged the slider to
// 25" before pressing Buy.
var h = new Harness();
h.State.Apply(VendorGuid, Profile(), new[]
{
new VendorShopItem(
StackedItemGuid, -1, 3u, "Arrows", (uint)ItemType.MissileWeapon, 300u, 1000,
DescStackSize: 100),
});
h.SplitQuantity.Reset(100u, initialValue: 25u);
h.BuyButton.OnClick!.Invoke();
Assert.Equal(25, h.Buys.Single().Amount);
}
[Fact]
public void BuyButton_Press_AlternateCurrencyVendor_ForwardsTheVendorsTradeWcid()
{
var h = new Harness();
h.State.Apply(
VendorGuid,
Profile(altCurrency: 0x12345678u, altName: "Trade Notes", altAmount: 500u),
new[]
{
new VendorShopItem(ArmorItemGuid, -1, 2u, "Chainmail", (uint)ItemType.Armor, 200u, 500),
});
h.BuyButton.OnClick!.Invoke();
Assert.Equal(0x12345678u, h.Buys.Single().AlternateCurrencyId);
}
[Fact]
public void BuyButton_DisablesTheInstantAPurchaseIsInFlight_AndReenablesOnCompletion()
{
var h = new Harness();
h.State.Apply(VendorGuid, Profile(), new[]
{
new VendorShopItem(ArmorItemGuid, -1, 2u, "Chainmail", (uint)ItemType.Armor, 200u, 500),
});
Assert.True(h.BuyButton.Enabled);
h.BuyButton.OnClick!.Invoke();
// TryBuy's reservation increments BusyCount synchronously, before
// any wire response — the button must reflect that immediately,
// with no per-frame polling (ItemInteractionController.StateChanged
// drives RecomputeBuyButtonEnabled).
Assert.False(h.BuyButton.Enabled);
h.ItemInteraction.CompleteUse(0);
Assert.True(h.BuyButton.Enabled);
}
[Fact]
public void BuyButton_NoSelection_PressDoesNothing()
{
var h = new Harness();
h.BuyButton.OnClick!.Invoke();
Assert.Empty(h.Buys);
}
[Fact]
public void ReconciliationRoundTrip_MoneyCreateObjectAndApproachVendorRefresh_FlowThroughExistingMachinery()
{
// Slice 6.3: verifies the loop end-to-end with synthetic inbound
// messages, adding no new owner (research doc §C.4/§A.2 point 4):
// (1) a money property update applies to the SAME ClientObjectTable
// the vendor panel reads live for its cost text,
// (2) the purchase lands in the player's inventory via the ordinary
// CreateObject merge-upsert (ClientObjectTable.Ingest),
// (3) the vendor's post-buy ApproachVendor refresh
// (VendorStateTransitionKind.Refreshed) rebuilds the panel —
// here the bought-out item leaves the vendor's stock entirely
// (the common single-item-purchase case), so the rebuild is
// externally observable: the item leaves the list and the
// selection/buttons clear.
var h = new Harness();
const uint PurchasedItemGuid = 0x60000900u;
h.State.Apply(VendorGuid, Profile(sellRate: 1.0f), new[]
{
new VendorShopItem(ArmorItemGuid, -1, 2u, "Chainmail", (uint)ItemType.Armor, 200u, 500),
});
Assert.Equal(1, h.ItemList.GetNumUIItems());
Assert.True(h.BuyButton.Enabled);
h.BuyButton.OnClick!.Invoke();
Assert.Single(h.Buys);
Assert.False(h.BuyButton.Enabled);
// (1) Money: PrivateUpdatePropertyInt(CoinValue) — the exact path
// ObjectTableWiring's PlayerIntPropertyUpdated handler calls.
int newCoinValue = Harness.DefaultPlayerCoinValue - 500;
h.Objects.UpdateIntProperty(Harness.PlayerGuid, (uint)PropertyInt.CoinValue, newCoinValue);
// (2) CreateObject: the purchased item lands in the player's own
// inventory — the ordinary Ingest merge-upsert every CreateObject
// uses (ObjectTableWiring.ApplyEntitySpawn), landing here with the
// player as its container.
h.Objects.Ingest(new WeenieData(
Guid: PurchasedItemGuid,
Name: "Chainmail",
Type: ItemType.Armor,
WeenieClassId: 2u,
IconId: 200u,
IconOverlayId: 0u,
IconUnderlayId: 0u,
Effects: 0u,
Value: 500,
StackSize: null,
StackSizeMax: null,
Burden: null,
ContainerId: Harness.PlayerGuid,
WielderId: 0u,
ValidLocations: null,
CurrentWieldedLocation: null,
Priority: null,
ItemsCapacity: null,
ContainersCapacity: null,
Structure: null,
MaxStructure: null,
Workmanship: null));
// (3) ApproachVendor refresh: sold out of the ONLY armor stack, so
// the SAME vendor's next snapshot no longer lists it.
h.State.Apply(VendorGuid, Profile(sellRate: 1.0f), System.Array.Empty<VendorShopItem>());
// (4) UseDone completes the reservation.
h.ItemInteraction.CompleteUse(0);
Assert.Equal(newCoinValue, h.Objects.Get(Harness.PlayerGuid)?.Properties.GetInt((uint)PropertyInt.CoinValue));
Assert.Equal(Harness.PlayerGuid, h.Objects.Get(PurchasedItemGuid)?.ContainerId);
Assert.Equal(0, h.ItemList.GetNumUIItems());
Assert.Equal(string.Empty, GetText(h.ItemNameText));
Assert.False(h.BuyButton.Enabled);
}
}

View file

@ -0,0 +1,127 @@
using System;
using System.Buffers.Binary;
using AcDream.Core.Net.Messages;
using Xunit;
namespace AcDream.Core.Net.Tests.Messages;
/// <summary>
/// Slice 6.3 golden-byte coverage for the outbound Buy (<c>0x005F</c>)
/// builder — research doc §A.1's four-way-confirmed wire layout, including
/// the trailing <c>alternateCurrencyId</c> field the real retail client
/// sends but ACE's reader currently ignores.
/// </summary>
public sealed class VendorRequestsTests
{
[Fact]
public void BuildBuy_SingleItem_WritesEnvelopeSequenceOpcodeVendorCountAndItem()
{
byte[] body = VendorRequests.BuildBuy(
gameActionSequence: 9,
vendorGuid: 0x40001000u,
amount: 1,
itemGuid: 0x50002000u,
alternateCurrencyId: 0u);
// envelope(4) + seq(4) + opcode(4) + vendorGuid(4) + itemCount(4)
// + 1*(amount(4)+guid(4)) + trailing currency(4) = 32.
Assert.Equal(32, body.Length);
Assert.Equal(VendorRequests.GameActionEnvelope,
BinaryPrimitives.ReadUInt32LittleEndian(body.AsSpan(0)));
Assert.Equal(9u,
BinaryPrimitives.ReadUInt32LittleEndian(body.AsSpan(4)));
Assert.Equal(VendorRequests.BuyOpcode,
BinaryPrimitives.ReadUInt32LittleEndian(body.AsSpan(8)));
Assert.Equal(0x005Fu, VendorRequests.BuyOpcode);
Assert.Equal(0x40001000u,
BinaryPrimitives.ReadUInt32LittleEndian(body.AsSpan(12)));
Assert.Equal(1u,
BinaryPrimitives.ReadUInt32LittleEndian(body.AsSpan(16)));
Assert.Equal(1,
BinaryPrimitives.ReadInt32LittleEndian(body.AsSpan(20)));
Assert.Equal(0x50002000u,
BinaryPrimitives.ReadUInt32LittleEndian(body.AsSpan(24)));
// Trailing alternateCurrencyId — present even for a pyreal (0) vendor,
// matching retail's CM_Vendor::Event_Buy which writes it unconditionally.
Assert.Equal(0u,
BinaryPrimitives.ReadUInt32LittleEndian(body.AsSpan(28)));
}
[Fact]
public void BuildBuy_StackedItem_WritesTheSplitSliderQuantityAsAPlainPositiveAmount()
{
// amount is NOT ItemProfile's packed sign-extended supply-count
// field -- it's a plain positive int32 (research doc §A.1).
byte[] body = VendorRequests.BuildBuy(
gameActionSequence: 1,
vendorGuid: 0x40001000u,
amount: 25,
itemGuid: 0x50002001u,
alternateCurrencyId: 0u);
Assert.Equal(25,
BinaryPrimitives.ReadInt32LittleEndian(body.AsSpan(20)));
}
[Fact]
public void BuildBuy_AlternateCurrencyVendor_WritesTheVendorsTradeWcidTrailing()
{
byte[] body = VendorRequests.BuildBuy(
gameActionSequence: 1,
vendorGuid: 0x40001000u,
amount: 1,
itemGuid: 0x50002000u,
alternateCurrencyId: 0x12345678u);
Assert.Equal(0x12345678u,
BinaryPrimitives.ReadUInt32LittleEndian(body.AsSpan(28)));
}
[Fact]
public void BuildBuy_ListOverload_MultipleItems_WritesEachAmountGuidPairInOrder()
{
byte[] body = VendorRequests.BuildBuy(
gameActionSequence: 4,
vendorGuid: 0x40001000u,
items: new (int Amount, uint ItemGuid)[]
{
(1, 0x50002000u),
(10, 0x50002001u),
},
alternateCurrencyId: 0u);
// 24 + 2*8 = 40.
Assert.Equal(40, body.Length);
Assert.Equal(2u,
BinaryPrimitives.ReadUInt32LittleEndian(body.AsSpan(16)));
Assert.Equal(1,
BinaryPrimitives.ReadInt32LittleEndian(body.AsSpan(20)));
Assert.Equal(0x50002000u,
BinaryPrimitives.ReadUInt32LittleEndian(body.AsSpan(24)));
Assert.Equal(10,
BinaryPrimitives.ReadInt32LittleEndian(body.AsSpan(28)));
Assert.Equal(0x50002001u,
BinaryPrimitives.ReadUInt32LittleEndian(body.AsSpan(32)));
// Trailing currency still lands after every item pair.
Assert.Equal(0u,
BinaryPrimitives.ReadUInt32LittleEndian(body.AsSpan(36)));
}
[Fact]
public void BuildBuy_SingleItemOverload_MatchesTheGeneralListOverload()
{
byte[] viaSingle = VendorRequests.BuildBuy(
gameActionSequence: 3,
vendorGuid: 0x40001000u,
amount: 5,
itemGuid: 0x50002000u,
alternateCurrencyId: 7u);
byte[] viaList = VendorRequests.BuildBuy(
gameActionSequence: 3,
vendorGuid: 0x40001000u,
items: new (int Amount, uint ItemGuid)[] { (5, 0x50002000u) },
alternateCurrencyId: 7u);
Assert.Equal(viaList, viaSingle);
}
}

View file

@ -0,0 +1,64 @@
using System.Net;
using AcDream.Core.Net;
using AcDream.Core.Net.Messages;
namespace AcDream.Core.Net.Tests;
/// <summary>
/// Slice 6.3 — verifies <see cref="WorldSession.SendBuy"/> produces the same
/// wire bytes <see cref="VendorRequests.BuildBuy"/> does directly, using a
/// sequence number drawn from <see cref="WorldSession.NextGameActionSequence"/>.
/// Mirrors <c>WorldSessionChatTests</c>'s <c>GameActionCapture</c> test seam.
/// </summary>
public sealed class WorldSessionVendorTests
{
private static WorldSession NewSession()
{
var ep = new IPEndPoint(IPAddress.Loopback, 65001);
return new WorldSession(ep);
}
[Fact]
public void SendBuy_EmitsBytesIdenticalToVendorRequestsBuildBuy()
{
using var session = NewSession();
byte[]? captured = null;
session.GameActionCapture = body => captured = body;
session.SendBuy(
vendorGuid: 0x40001000u,
itemGuid: 0x50002000u,
amount: 3,
alternateCurrencyId: 0u);
byte[] expected = VendorRequests.BuildBuy(
gameActionSequence: 1,
vendorGuid: 0x40001000u,
amount: 3,
itemGuid: 0x50002000u,
alternateCurrencyId: 0u);
Assert.NotNull(captured);
Assert.Equal(expected, captured);
}
[Fact]
public void SendBuy_IncrementsTheSharedGameActionSequenceLikeEveryOtherSend()
{
using var session = NewSession();
byte[]? captured = null;
session.GameActionCapture = body => captured = body;
session.SendTalk("first"); // consumes sequence 1
session.SendBuy(0x40001000u, 0x50002000u, 1, 0u); // should be sequence 2
byte[] expected = VendorRequests.BuildBuy(
gameActionSequence: 2,
vendorGuid: 0x40001000u,
amount: 1,
itemGuid: 0x50002000u,
alternateCurrencyId: 0u);
Assert.Equal(expected, captured);
}
}

View file

@ -198,6 +198,56 @@ public sealed class RuntimeVendorLifecycleTests
Assert.Equal(0u, runtime.InventoryOwner.Vendor.VendorId);
}
[Fact]
public void ApproachVendorEvent_MaterializesShopItemsIntoTheOwnedObjectTable()
{
// Slice 6.1: unlike Wire()'s throwaway ClientObjectTable (used by
// the tests above, which only assert on VendorState itself), this
// wires the dispatcher against the SAME table
// RuntimeInventoryState.Objects exposes, so the
// VendorShopItemMaterializer subscription RuntimeInventoryState's
// constructor installs is exercised end-to-end from the real wire
// parse through to ClientObjectTable.
using GameRuntime runtime = Create();
using IDisposable wiring = GameEventWiring.WireAll(
_dispatcher,
runtime.InventoryOwner.Objects,
new CombatState(),
new Spellbook(),
new ChatLog(),
vendor: runtime.InventoryOwner.Vendor);
Dispatch(BuildApproachVendorPayload(
vendorGuid: 0x40001000u,
categories: 0u, minValue: 0u, maxValue: 0u, dealsMagic: false,
buyPrice: 1f, sellPrice: 1f, currencyWcid: 0u, currencyAmount: 0u,
currencyName: "",
items:
[
new VendorItemFixture(
0x50002000u, 1, "Iron Sword", 42u, 0x1234u,
(uint)ItemType.Weapon, 250),
]));
ClientObject? shopItem = runtime.InventoryOwner.Objects.Get(0x50002000u);
Assert.NotNull(shopItem);
Assert.Equal(0x40001000u, shopItem!.ContainerId);
Assert.Equal("Iron Sword", shopItem.Name);
Assert.Equal(1, runtime.InventoryOwner.VendorItems.OwnedCount);
runtime.InventoryOwner.Vendor.Close();
Assert.Null(runtime.InventoryOwner.Objects.Get(0x50002000u));
Assert.Equal(0, runtime.InventoryOwner.VendorItems.OwnedCount);
// Close() is a client-local session end, not full disposal, so only
// the vendor-specific ownership dimensions are asserted here — the
// full IsConverged gate is exercised by DisposingInventoryOwner_
// ClearsTheOpenVendorSession below.
RuntimeInventoryOwnershipSnapshot snapshot = runtime.InventoryOwner.CaptureOwnership();
Assert.Equal(0u, snapshot.VendorId);
Assert.Equal(0, snapshot.MaterializedVendorItemCount);
}
[Fact]
public void VendorId_IsTheLiveActiveVendorIdSeamSource()
{

View file

@ -0,0 +1,191 @@
using AcDream.Core.Items;
using AcDream.Runtime.Gameplay;
namespace AcDream.Runtime.Tests.Gameplay;
/// <summary>
/// Slice 6.1 — <see cref="VendorShopItemMaterializer"/> in isolation: the
/// diff/materialize/retire logic against a bare <see cref="VendorState"/> +
/// <see cref="ClientObjectTable"/> pair, independent of the wire parse
/// (<see cref="RuntimeVendorLifecycleTests"/> covers the end-to-end
/// ApproachVendor path).
/// </summary>
public sealed class VendorShopItemMaterializerTests
{
private const uint VendorGuid = 0x40001000u;
private const uint OtherVendorGuid = 0x40002000u;
private const uint ItemA = 0x50002000u;
private const uint ItemB = 0x50002001u;
private static VendorShopItem Item(uint guid, string name = "Item", int? descStackSize = null) =>
new(guid, StackSize: -1, WeenieClassId: 1u, Name: name, ItemType: (uint)ItemType.Misc,
IconId: 0x1234u, Value: 10, DescStackSize: descStackSize);
[Fact]
public void Apply_MaterializesEachShopItemWithVendorAsContainer()
{
var vendor = new VendorState();
var objects = new ClientObjectTable();
using var materializer = new VendorShopItemMaterializer(vendor, objects);
vendor.Apply(VendorGuid, default, new[] { Item(ItemA, "Iron Sword"), Item(ItemB, "Bread") });
ClientObject? a = objects.Get(ItemA);
ClientObject? b = objects.Get(ItemB);
Assert.NotNull(a);
Assert.NotNull(b);
Assert.Equal(VendorGuid, a!.ContainerId);
Assert.Equal(VendorGuid, b!.ContainerId);
Assert.Equal("Iron Sword", a.Name);
Assert.Equal(2, materializer.OwnedCount);
Assert.True(materializer.Owns(ItemA));
Assert.True(materializer.Owns(ItemB));
}
[Fact]
public void Close_RemovesEveryMaterializedItem()
{
var vendor = new VendorState();
var objects = new ClientObjectTable();
using var materializer = new VendorShopItemMaterializer(vendor, objects);
vendor.Apply(VendorGuid, default, new[] { Item(ItemA), Item(ItemB) });
vendor.Close();
Assert.Null(objects.Get(ItemA));
Assert.Null(objects.Get(ItemB));
Assert.Equal(0, materializer.OwnedCount);
}
[Fact]
public void Reset_RemovesEveryMaterializedItem()
{
var vendor = new VendorState();
var objects = new ClientObjectTable();
using var materializer = new VendorShopItemMaterializer(vendor, objects);
vendor.Apply(VendorGuid, default, new[] { Item(ItemA) });
vendor.Reset();
Assert.Null(objects.Get(ItemA));
Assert.Equal(0, materializer.OwnedCount);
}
[Fact]
public void DifferentVendorSupersedes_RemovesPriorVendorsItemsBeforeMaterializingTheNewOnes()
{
var vendor = new VendorState();
var objects = new ClientObjectTable();
using var materializer = new VendorShopItemMaterializer(vendor, objects);
vendor.Apply(VendorGuid, default, new[] { Item(ItemA, "First Vendor Item") });
Assert.NotNull(objects.Get(ItemA));
const uint NewItem = 0x50003000u;
vendor.Apply(OtherVendorGuid, default, new[] { Item(NewItem, "Second Vendor Item") });
Assert.Null(objects.Get(ItemA));
ClientObject? replacement = objects.Get(NewItem);
Assert.NotNull(replacement);
Assert.Equal(OtherVendorGuid, replacement!.ContainerId);
Assert.Equal(1, materializer.OwnedCount);
}
[Fact]
public void Refreshed_SameVendor_DoesNotFireObjectRemovedForStillListedItems()
{
// A same-vendor re-approach (post-buy refresh) must not remove+
// re-add a guid that's still in stock -- see the class doc's "diff,
// not blanket remove-then-reinsert" rationale. A UI panel holding
// the guid (an open appraisal window) would see a false "it's gone"
// notice if this regressed to blanket removal.
var vendor = new VendorState();
var objects = new ClientObjectTable();
using var materializer = new VendorShopItemMaterializer(vendor, objects);
vendor.Apply(VendorGuid, default, new[] { Item(ItemA, "Chainmail") });
var removed = new List<uint>();
objects.ObjectRemoved += o => removed.Add(o.ObjectId);
// Same vendor id re-approaches with the SAME item guid still listed
// (e.g. a post-buy refresh where this item wasn't the one bought)
// but with a refreshed field value.
vendor.Apply(VendorGuid, default, new[] { Item(ItemA, "Chainmail", descStackSize: 5) });
Assert.Empty(removed);
Assert.Equal(1, materializer.OwnedCount);
Assert.Equal(5, objects.Get(ItemA)!.StackSize);
}
[Fact]
public void Refreshed_ItemNoLongerListed_IsRemoved()
{
// A unique item sold out (bought up / delisted) between one
// ApproachVendor and the next same-vendor refresh.
var vendor = new VendorState();
var objects = new ClientObjectTable();
using var materializer = new VendorShopItemMaterializer(vendor, objects);
vendor.Apply(VendorGuid, default, new[] { Item(ItemA), Item(ItemB) });
vendor.Apply(VendorGuid, default, new[] { Item(ItemB) });
Assert.Null(objects.Get(ItemA));
Assert.NotNull(objects.Get(ItemB));
Assert.Equal(1, materializer.OwnedCount);
}
[Fact]
public void CollidingGuid_AlreadyOwnedBySomethingElse_IsNeverClobbered()
{
// The Slice 6.1 collision policy: ACE's UniqueItemsForSale can list
// the EXACT guid a player last held (e.g. a sold-off item, or --
// worst case -- any other collision). If that guid is already in
// ClientObjectTable for a reason this materializer did not itself
// create, it must be left completely untouched, not silently
// reparented into the vendor's container.
var vendor = new VendorState();
var objects = new ClientObjectTable();
// Simulate a pre-existing, non-vendor-owned object at this guid --
// e.g. a live entity, or an item still sitting in someone's
// inventory/equipment.
const uint LiveOwner = 0x60000001u;
objects.AddOrUpdate(new ClientObject
{
ObjectId = ItemA,
Name = "Definitely Not A Shop Item",
ContainerId = LiveOwner,
});
using var materializer = new VendorShopItemMaterializer(vendor, objects);
vendor.Apply(VendorGuid, default, new[] { Item(ItemA, "Shop Listing With A Colliding Guid") });
ClientObject? survivor = objects.Get(ItemA);
Assert.NotNull(survivor);
Assert.Equal("Definitely Not A Shop Item", survivor!.Name);
Assert.Equal(LiveOwner, survivor.ContainerId);
Assert.False(materializer.Owns(ItemA));
Assert.Equal(0, materializer.OwnedCount);
// The collision guid must also survive session close -- since this
// materializer never claimed it, it must never remove it either.
vendor.Close();
Assert.NotNull(objects.Get(ItemA));
}
[Fact]
public void Dispose_UnsubscribesFromVendorChanged()
{
var vendor = new VendorState();
var objects = new ClientObjectTable();
var materializer = new VendorShopItemMaterializer(vendor, objects);
vendor.Apply(VendorGuid, default, new[] { Item(ItemA) });
Assert.NotNull(objects.Get(ItemA));
materializer.Dispose();
// No further reaction once disposed -- a Close() after disposal
// must not throw and must not touch the table (nothing left
// subscribed to react).
vendor.Close();
Assert.NotNull(objects.Get(ItemA));
}
}