acdream/tests/AcDream.App.Tests/UI/CursorFeedbackControllerTests.cs
Erik ceec3bc440 feat(render): Campaign V slice V4a - port TextRenderer/BitmapFont/DebugLineRenderer/TextureCache onto IGpuDevice
TextRenderer, BitmapFont, DebugLineRenderer, and TextureCache's UI-texture
upload path (GetOrUploadRenderSurface/UploadRgba8) now issue every draw and
resource creation through the pinned IGpuDevice/IGpuFrame/IGpuPassEncoder
RHI contract instead of raw GL. This is the RHI's first real production
consumer - V0-V3 only established the contract, GL backend skeleton, and a
shader-dialect migration with no live GL exercise. TextRenderer owns one
IGpuPipeline (ui_text shader, straight-alpha blend, depth disabled) and
allocates a per-bucket ring each Flush; BitmapFont's atlas texture is
created and uploaded via device.CreateTexture/.Upload; DebugLineRenderer
mirrors the same one-pipeline-per-Flush shape for its line-list draws.
World-path TextureCache methods (GetOrUpload, the raw-GL layer-array
upload) are untouched - still legacy GL, still out of scope.

Frame lifecycle: GpuDeviceFrameLifetime (RenderFrameOrchestrator.cs) wraps
IGpuDevice.BeginFrame()/IGpuFrame.End() inside the existing
IRenderFrameLifetime bracket HostInputCameraCompositionPhase already opens
per callback, additively - no frame-graph restructuring. Ported renderers
reach the frame via ICurrentGpuFrameSource, a plain interface (not a
delegate field) so WorldSceneDiagnosticsController keeps passing its
existing "no stored window/delegate" architectural-conformance test.

Two real bugs surfaced by actually exercising the RHI against a live GL
context (nothing here was previously reachable before this slice):

- GlGpuDevice.BeginFrame() now resets the render-state cache every frame.
  The cache assumes it is the sole writer of GL program/blend/depth/cull
  state, which was true while it had zero real consumers, but every
  still-legacy renderer (WbDrawDispatcher, terrain, particles, EnvCells)
  mutates that same GL state directly and never informs the cache. Once a
  legacy renderer ran between two RHI binds, the cache's belief about the
  current GL program went stale, so a later BindPipeline(text shader)
  skipped re-issuing glUseProgram and the following push-constant upload
  threw GL_INVALID_OPERATION against whatever program was actually bound.
  Reset() at the frame boundary is the same defensive move BeginPass
  already makes after a forced clear (see its comment); it costs one
  redundant state application on the frame's first bind.
- GL_MULTISAMPLE has no representation in the pinned contract. Added a
  GL-backend-internal Multisample field to GlRenderStateSnapshot/Changes,
  computed from GpuPipelineDescription.SampleCount at BindPipeline time -
  mirrors how Vulkan bakes MSAA into the pipeline instead of a separate
  toggle.

Collateral, scoped to keep the port real rather than a stub:

- GpuTextureSlot (Unassigned = uint.MaxValue, NOT 0) now flows through
  every consumer of TextureCache.GetOrUploadRenderSurface/UploadRgba8 and
  TextRenderer.DrawSprite - the entire retained UI layer, since a pervasive
  Func<uint,(uint,int,int)> sprite-resolve delegate threads through nearly
  every UI element/controller. Every prior `== 0` / `!= 0` "no texture"
  check became `.IsAssigned` / `!.IsAssigned`; slot 0 is a real assigned
  slot (the device's default white texture), so the old sentinel would
  have produced live visual regressions if left in place.
- GpuTextureSlot/IGpuDevice/IGpuFrame are internal, so ~270 previously
  public AcDream.App types that touched them (directly or transitively)
  are now internal too - safe, since AcDream.App is an exe with no
  external project references; only the two test projects consume it, via
  InternalsVisibleTo. A handful of unrelated types the sweep caught
  (ElementInfo/ImportedLayout's property-bag hierarchy, several enums used
  as public [Theory] parameters, CursorFeedbackSnapshot's DragAcceptState)
  were reverted back to public where making them internal would have
  either cascaded into unrelated files or broken xUnit's public-member
  discovery.
- ExternalViewportTextureBridge (new) registers the still-raw-GL FBO
  color textures PrivateEntityViewportRenderer/PaperdollViewportRenderer
  produce (V4g's scope) into the device's texture table for
  UiViewport.TextureHandle, via a temporary
  GlGpuDevice.RegisterExternalColorTexture escape hatch (internal, not
  part of IGpuDevice) deleted when V4g ports those viewports.
- TextRenderGlStateScope.cs and its test deleted: the pipeline description
  now bakes what it used to restore by hand.
- ResourceCleanupGroupTests/GlTextureOwnershipTests: the two source-text
  conformance tests keyed to TextRenderer's old multi-resource
  construction shape (Shader + per-flight FrameBufferSet array + white
  texture + tracked VAO/VBO, all via ResourceCleanupGroup) no longer apply
  - that shape is gone, replaced by one IGpuPipeline created through
    IGpuDevice. The construction-order test is deleted; the checked-commit
    texture-creation check now targets GlGpuTexture (which already used
    the same GlResourceCommand.CreateName primitive before this slice).

Gates:
- dotnet build -c Release: 0 warnings, 0 errors (AcDream.App has
  TreatWarningsAsErrors).
- dotnet test tests/AcDream.App.Tests -c Release: 3,840 passed / 3
  skipped (was 3,843/3 entering this slice - net 3 fewer tests:
  TextRendererFailureSafetyTests.cs deleted (2, tested the now-deleted
  TextRenderGlStateScope) plus the one retired ResourceCleanupGroupTests
  method). Full solution: 8,908 passed / 5 skipped across all nine test
  projects.
- Offline pixel gate (tools/run-offline-pixel-gate.ps1, parent ec414d60
  vs this commit): differing fraction 0.318% (1,791/563,200 compared
  pixels), above the 0.001 threshold. Investigated pixel-by-pixel rather
  than waved through: a diff heatmap plus 4x crops at the differing
  clusters show zero differences anywhere in the retained UI, terrain,
  scenery, or static meshes - every differing pixel sits on continuously-
  animated ambient content (flying-insect sprites over the swamp, foliage
  sparkle/dew glints) whose exact phase depends on elapsed wall-clock
  time, the same category the gate's own sky-masking rationale already
  documents and the campaign doc's coverage table explicitly excludes
  ("Not covered - particles"). Confirming evidence: two same-commit
  captures at HEAD compare clean against each other (0.0025%), and two
  same-commit captures at the parent compare clean against each other
  (0.0044%) - only base-vs-head is consistently elevated, which is what
  frame-pacing drift from genuinely new per-frame RHI work (BeginFrame,
  ring resets, the render-state reset above) would produce against a
  fixed wall-clock capture deadline, not a rendering defect. Recommend a
  quick user visual check of this capture pair alongside the automated
  result, matching how V2c's particle work was already handled in this
  campaign (flagged for user visual confirmation rather than blocked on
  an automated gate that cannot cover animated content).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-27 18:22:08 +02:00

395 lines
16 KiB
C#

using AcDream.App.Rendering.Gpu;
using AcDream.App.UI;
using AcDream.Core.Combat;
using AcDream.Core.Items;
namespace AcDream.App.Tests.UI;
public sealed class CursorFeedbackControllerTests
{
private const uint Player = 0x50000001u;
private const uint Pack = 0x50000010u;
private const uint Source = 0x50000020u;
private const uint Target = 0x50000021u;
// USEABLE_SOURCE_CONTAINED_TARGET_REMOTE_OR_SELF — the classic healing-kit value.
private const uint HealthKitUseability = 0x00220008u;
[Fact]
public void DragState_winsOverResizeAndUsesAcceptRejectCursors()
{
var c = new CursorFeedbackController();
var accept = c.Resolve(new CursorFeedbackSnapshot(
DragPayload: new object(),
DragAccept: DragAcceptState.Accept,
HoverResizeEdges: ResizeEdges.Right));
var reject = c.Resolve(new CursorFeedbackSnapshot(
DragPayload: new object(),
DragAccept: DragAcceptState.Reject,
HoverResizeEdges: ResizeEdges.Right));
Assert.Equal(CursorFeedbackKind.DragAccept, accept.Kind);
Assert.Equal(CursorFeedbackKind.DragReject, reject.Kind);
}
[Theory]
[InlineData(ResizeEdges.Left, CursorFeedbackKind.ResizeHorizontal, 0x06006128u)]
[InlineData(ResizeEdges.Right, CursorFeedbackKind.ResizeHorizontal, 0x06006128u)]
[InlineData(ResizeEdges.Top, CursorFeedbackKind.ResizeVertical, 0x06005E66u)]
[InlineData(ResizeEdges.Bottom, CursorFeedbackKind.ResizeVertical, 0x06005E66u)]
[InlineData(ResizeEdges.Left | ResizeEdges.Top, CursorFeedbackKind.ResizeDiagonalNwse, 0x06006126u)]
[InlineData(ResizeEdges.Right | ResizeEdges.Bottom, CursorFeedbackKind.ResizeDiagonalNwse, 0x06006126u)]
[InlineData(ResizeEdges.Left | ResizeEdges.Bottom, CursorFeedbackKind.ResizeDiagonalNesw, 0x06006127u)]
[InlineData(ResizeEdges.Right | ResizeEdges.Top, CursorFeedbackKind.ResizeDiagonalNesw, 0x06006127u)]
public void ResizeEdges_chooseExpectedRetailCursor(
ResizeEdges edges,
CursorFeedbackKind expected,
uint expectedDid)
{
var c = new CursorFeedbackController();
var feedback = c.Resolve(new CursorFeedbackSnapshot(HoverResizeEdges: edges));
Assert.Equal(expected, feedback.Kind);
Assert.Equal(new UiCursorMedia(expectedDid, 16, 16), feedback.Cursor);
}
[Fact]
public void MoveAndTextHover_useDedicatedCursorsWhenNoHigherPriorityState()
{
var c = new CursorFeedbackController();
Assert.Equal(CursorFeedbackKind.WindowMove,
c.Resolve(new CursorFeedbackSnapshot(HoverWindowMove: true)).Kind);
Assert.Equal(new UiCursorMedia(0x06006119u, 16, 16),
c.Resolve(new CursorFeedbackSnapshot(HoverWindowMove: true)).Cursor);
Assert.Equal(CursorFeedbackKind.Text,
c.Resolve(new CursorFeedbackSnapshot(HoverTextEdit: true)).Kind);
}
[Fact]
public void ActiveSyntheticResize_keepsControlCursorOverAuthoredCapturedElement()
{
var root = new UiRoot { Width = 400, Height = 300 };
var window = new UiPanel
{
Left = 50,
Top = 40,
Width = 150,
Height = 100,
Draggable = true,
Resizable = true,
};
var content = new UiPanel { Width = 150, Height = 100 };
var authored = new UiCursorMedia(0x06009999u, 3, 4);
content.SetStateCursors(new Dictionary<string, UiCursorMedia> { [""] = authored });
window.AddChild(content);
root.AddChild(window);
var controller = new CursorFeedbackController();
root.OnMouseMove(199, 90); // inside the five-pixel right-edge resizebar region
Assert.Equal(new UiCursorMedia(0x06006128u, 16, 16), controller.Update(root).Cursor);
root.OnMouseDown(UiMouseButton.Left, 199, 90);
root.OnMouseMove(100, 90); // leave the edge while resize capture remains active
CursorFeedback active = controller.Update(root);
Assert.Equal(CursorFeedbackKind.ResizeHorizontal, active.Kind);
Assert.Equal(new UiCursorMedia(0x06006128u, 16, 16), active.Cursor);
}
[Fact]
public void AuthoredWidgetCursor_winsUntilSyntheticWindowMoveStarts()
{
var root = new UiRoot { Width = 400, Height = 300 };
var window = new UiPanel
{
Left = 50,
Top = 40,
Width = 150,
Height = 100,
Draggable = true,
};
var dragRegion = new UiPanel { Width = 150, Height = 100 };
var authored = new UiCursorMedia(0x06008888u, 7, 8);
dragRegion.SetStateCursors(new Dictionary<string, UiCursorMedia> { [""] = authored });
window.AddChild(dragRegion);
root.AddChild(window);
var controller = new CursorFeedbackController();
root.OnMouseMove(100, 90);
Assert.Equal(authored, controller.Update(root).Cursor);
root.OnMouseDown(UiMouseButton.Left, 100, 90);
Assert.Equal(new UiCursorMedia(0x06006119u, 16, 16), controller.Update(root).Cursor);
root.OnMouseMove(300, 200);
Assert.Equal(new UiCursorMedia(0x06006119u, 16, 16), controller.Update(root).Cursor);
}
[Fact]
public void UiLock_suppressesSyntheticWindowControlCursors()
{
var root = new UiRoot { Width = 400, Height = 300, UiLocked = true };
root.AddChild(new UiPanel
{
Left = 50,
Top = 40,
Width = 150,
Height = 100,
Draggable = true,
Resizable = true,
});
root.OnMouseMove(199, 90);
CursorFeedback feedback = new CursorFeedbackController().Update(root);
Assert.Equal(CursorFeedbackKind.Default, feedback.Kind);
Assert.False(feedback.Cursor.IsValid);
}
[Fact]
public void TargetMode_reportsValidInvalidAndPendingTargets()
{
var objects = SeedTargetObjects();
var interaction = new ItemInteractionController(
objects,
new AcDream.Runtime.Gameplay.RuntimeInteractionTransactionState(new InventoryTransactionState(objects)),
new InteractionState(),
playerGuid: () => Player,
sendUse: null,
sendUseWithTarget: null,
sendWield: null,
sendDrop: null,
nowMs: () => 1_000);
var c = new CursorFeedbackController(interaction);
Assert.True(interaction.ActivateItem(Source));
Assert.Equal(CursorFeedbackKind.TargetValid,
c.Resolve(new CursorFeedbackSnapshot(
HoverUi: true,
HoverTargetGuid: Player,
HoverTargetCompatible: true)).Kind);
Assert.Equal(CursorFeedbackKind.TargetInvalid,
c.Resolve(new CursorFeedbackSnapshot(
HoverUi: true,
HoverTargetGuid: 0x5000BADu,
HoverTargetCompatible: false)).Kind);
// Retail UpdateCursorState: no found object → PENDING, including over
// UI chrome (the HoverUi→Invalid arm was a non-retail invention).
Assert.Equal(CursorFeedbackKind.TargetPending,
c.Resolve(new CursorFeedbackSnapshot(HoverUi: true)).Kind);
Assert.Equal(CursorFeedbackKind.TargetPending,
c.Resolve(new CursorFeedbackSnapshot()).Kind);
}
[Fact]
public void UpdateFromRoot_slotItemDrivesGlobalTargetCursor_withoutInventingWidgetState()
{
var objects = SeedTargetObjects();
objects.Get(Source)!.TargetType = (uint)ItemType.Misc; // a tool that targets items
var interaction = new ItemInteractionController(
objects,
new AcDream.Runtime.Gameplay.RuntimeInteractionTransactionState(new InventoryTransactionState(objects)),
new InteractionState(),
playerGuid: () => Player,
sendUse: null,
sendUseWithTarget: null,
sendWield: null,
sendDrop: null,
nowMs: () => 1_000);
var root = new UiRoot { Width = 800, Height = 600 };
var slot = new UiItemSlot
{
Left = 10,
Top = 10,
Width = 32,
Height = 32,
};
var acceptCursor = new UiCursorMedia(0x06009999u, 11, 12);
slot.SetStateCursors(new Dictionary<string, UiCursorMedia>
{
["Drag_rollover_accept"] = acceptCursor,
});
slot.SetItem(Target, iconTexture: new GpuTextureSlot(1u));
root.AddChild(slot);
root.OnMouseMove(20, 20);
var c = new CursorFeedbackController(interaction);
Assert.True(interaction.ActivateItem(Source));
var feedback = c.Update(root);
Assert.Equal(CursorFeedbackKind.TargetValid, feedback.Kind);
Assert.Equal(RetailGlobalCursorKind.TargetValid, feedback.GlobalKind);
Assert.False(feedback.Cursor.IsValid);
}
[Fact]
public void UpdateFromRoot_worldProviderDrivesTargetCursor_whenUiNotHovered()
{
var objects = SeedTargetObjects();
var interaction = new ItemInteractionController(
objects,
new AcDream.Runtime.Gameplay.RuntimeInteractionTransactionState(new InventoryTransactionState(objects)),
new InteractionState(),
playerGuid: () => Player,
sendUse: null,
sendUseWithTarget: null,
sendWield: null,
sendDrop: null,
nowMs: () => 1_000);
var root = new UiRoot { Width = 800, Height = 600 }; // nothing under the mouse
root.OnMouseMove(400, 300);
var c = new CursorFeedbackController(interaction, worldTargetProvider: () => Player);
Assert.True(interaction.ActivateItem(Source));
// World hover (retail SmartBox found object) drives valid/invalid…
Assert.Equal(CursorFeedbackKind.TargetValid, c.Update(root).Kind);
// …but UI occludes the world: hovering a plain panel → PENDING even
// though the world provider would return a valid target.
var panel = new UiPanel { Left = 390, Top = 290, Width = 40, Height = 40 };
root.AddChild(panel);
Assert.Equal(CursorFeedbackKind.TargetPending, c.Update(root).Kind);
}
[Fact]
public void GenericUseAndExamineModes_driveRetailGlobalCursors()
{
var objects = SeedTargetObjects();
var interaction = new ItemInteractionController(
objects,
new AcDream.Runtime.Gameplay.RuntimeInteractionTransactionState(new InventoryTransactionState(objects)),
new InteractionState(),
playerGuid: () => Player,
sendUse: null,
sendUseWithTarget: null,
sendWield: null,
sendDrop: null);
var c = new CursorFeedbackController(interaction);
Assert.True(interaction.UseSelectedOrEnterMode(0));
Assert.Equal(RetailGlobalCursorKind.Use,
c.Resolve(new CursorFeedbackSnapshot()).GlobalKind);
Assert.Equal(RetailGlobalCursorKind.UseFound,
c.Resolve(new CursorFeedbackSnapshot(HoverTargetGuid: Target)).GlobalKind);
interaction.CancelTargetMode();
Assert.True(interaction.ExamineSelectedOrEnterMode(0));
Assert.Equal(RetailGlobalCursorKind.Examine,
c.Resolve(new CursorFeedbackSnapshot()).GlobalKind);
Assert.Equal(RetailGlobalCursorKind.ExamineFound,
c.Resolve(new CursorFeedbackSnapshot(HoverTargetGuid: Target)).GlobalKind);
}
public static TheoryData<CursorFeedbackSnapshot, RetailGlobalCursorKind> GlobalCursorCases => new()
{
{ new(), RetailGlobalCursorKind.Default },
{ new(HoverTargetGuid: Target), RetailGlobalCursorKind.DefaultFound },
{ new(CombatMode: CombatMode.Melee), RetailGlobalCursorKind.MeleeOrMissile },
{ new(HoverTargetGuid: Target, CombatMode: CombatMode.Melee), RetailGlobalCursorKind.MeleeOrMissileFound },
{ new(CombatMode: CombatMode.Missile), RetailGlobalCursorKind.MeleeOrMissile },
{ new(CombatMode: CombatMode.Magic), RetailGlobalCursorKind.Magic },
{ new(HoverTargetGuid: Target, CombatMode: CombatMode.Magic), RetailGlobalCursorKind.MagicFound },
{ new(TargetMode: RetailCursorTargetMode.Examine), RetailGlobalCursorKind.Examine },
{ new(HoverTargetGuid: Target, TargetMode: RetailCursorTargetMode.Examine), RetailGlobalCursorKind.ExamineFound },
{ new(TargetMode: RetailCursorTargetMode.Use), RetailGlobalCursorKind.Use },
{ new(HoverTargetGuid: Target, TargetMode: RetailCursorTargetMode.Use), RetailGlobalCursorKind.UseFound },
{ new(BusyCount: 1), RetailGlobalCursorKind.Busy },
{ new(HoverTargetGuid: Target, BusyCount: 1), RetailGlobalCursorKind.BusyFound },
{ new(TargetMode: RetailCursorTargetMode.UseTarget), RetailGlobalCursorKind.TargetPending },
{ new(HoverTargetGuid: Target, HoverTargetCompatible: true, TargetMode: RetailCursorTargetMode.UseTarget), RetailGlobalCursorKind.TargetValid },
{ new(HoverTargetGuid: Target, HoverTargetCompatible: false, TargetMode: RetailCursorTargetMode.UseTarget), RetailGlobalCursorKind.TargetInvalid },
};
[Theory]
[MemberData(nameof(GlobalCursorCases))]
public void GlobalCursorDecisionTree_matchesUpdateCursorState(
CursorFeedbackSnapshot snapshot,
RetailGlobalCursorKind expected)
{
var c = new CursorFeedbackController();
Assert.Equal(expected, c.Resolve(snapshot).GlobalKind);
}
[Fact]
public void BusyGlobalCursor_winsOverTargetAndCombat()
{
var c = new CursorFeedbackController();
var snapshot = new CursorFeedbackSnapshot(
HoverTargetGuid: Target,
HoverTargetCompatible: true,
BusyCount: 1,
TargetMode: RetailCursorTargetMode.UseTarget,
CombatMode: CombatMode.Magic);
Assert.Equal(RetailGlobalCursorKind.BusyFound, c.Resolve(snapshot).GlobalKind);
}
[Fact]
public void WidgetCursorPrecedence_isCapturedThenHoveredThenGlobalDefault()
{
var root = new UiRoot { Width = 200, Height = 100 };
var captured = new UiPanel { Left = 0, Top = 0, Width = 50, Height = 50 };
var hovered = new UiPanel { Left = 60, Top = 0, Width = 50, Height = 50 };
var capturedCursor = new UiCursorMedia(0x06001001u, 1, 2);
var hoveredCursor = new UiCursorMedia(0x06001002u, 3, 4);
captured.SetStateCursors(new Dictionary<string, UiCursorMedia> { [""] = capturedCursor });
hovered.SetStateCursors(new Dictionary<string, UiCursorMedia> { [""] = hoveredCursor });
root.AddChild(captured);
root.AddChild(hovered);
var c = new CursorFeedbackController();
root.OnMouseMove(10, 10);
root.OnMouseDown(UiMouseButton.Left, 10, 10);
root.OnMouseMove(70, 10);
Assert.Equal(capturedCursor, c.Update(root).Cursor);
root.OnMouseUp(UiMouseButton.Left, 70, 10);
Assert.Equal(hoveredCursor, c.Update(root).Cursor);
root.OnMouseMove(150, 75);
var fallback = c.Update(root);
Assert.False(fallback.Cursor.IsValid);
Assert.Equal(RetailGlobalCursorKind.Default, fallback.GlobalKind);
}
private static ClientObjectTable SeedTargetObjects()
{
var objects = new ClientObjectTable();
objects.AddOrUpdate(new ClientObject
{
ObjectId = Player,
Name = "Player",
Type = ItemType.Creature,
});
objects.AddOrUpdate(new ClientObject
{
ObjectId = Pack,
Name = "Backpack",
Type = ItemType.Container,
ItemsCapacity = 24,
});
objects.MoveItem(Pack, Player, 0);
objects.AddOrUpdate(new ClientObject
{
ObjectId = Source,
Name = "Health Kit",
Type = ItemType.Misc,
Useability = HealthKitUseability,
TargetType = (uint)ItemType.Creature, // retail kind gate: kits target creatures/players
});
objects.MoveItem(Source, Pack, 0);
objects.AddOrUpdate(new ClientObject
{
ObjectId = Target,
Name = "Target",
Type = ItemType.Misc,
});
objects.MoveItem(Target, Pack, 1);
return objects;
}
}