refactor(runtime): own world reveal generation

This commit is contained in:
Erik 2026-07-26 17:09:54 +02:00
parent 4ab98b080e
commit a6860d5563
26 changed files with 1294 additions and 502 deletions

View file

@ -26,6 +26,7 @@ using AcDream.Core.Selection;
using AcDream.Core.Vfx;
using AcDream.Core.World;
using AcDream.Runtime.Entities;
using AcDream.Runtime.World;
using DatReaderWriter;
using DatReaderWriter.DBObjs;
using Silk.NET.OpenGL;
@ -71,6 +72,7 @@ internal sealed record LivePresentationDependencies(
DeferredCanonicalWorldEntityCountSource? DevWorldEntities,
DeferredRenderFrameDiagnosticsSource? DevFrameDiagnostics,
DeferredRenderFrameDiagnosticsSource UiFrameDiagnostics,
Action<string> Log,
Action<string>? Toast);
internal sealed record LivePresentationResult(
@ -80,6 +82,7 @@ internal sealed record LivePresentationResult(
EntitySpawnAdapter EntitySpawnAdapter,
EntityScriptActivator EntityScriptActivator,
RetailStaticAnimatingObjectScheduler StaticAnimationScheduler,
RuntimeWorldTransitState WorldTransit,
WorldGenerationAvailabilityState WorldAvailability,
GpuWorldState WorldState,
RenderSceneShadowRuntime? RenderSceneShadow,
@ -333,7 +336,9 @@ internal sealed class LivePresentationCompositionPhase
staticAnimationScheduler.Unregister,
(entity, info) => staticAnimationScheduler.Rebind(entity, info));
var worldAvailability = new WorldGenerationAvailabilityState();
var worldTransit = new RuntimeWorldTransitState(d.Log);
var worldAvailability =
new WorldGenerationAvailabilityState(worldTransit);
var worldState = new GpuWorldState(
wbSpawnAdapter,
d.ClassificationCache.InvalidateLandblock,
@ -583,6 +588,7 @@ internal sealed class LivePresentationCompositionPhase
entitySpawnAdapter,
entityScriptActivator,
staticAnimationScheduler,
worldTransit,
worldAvailability,
worldState,
renderSceneShadow,
@ -630,6 +636,7 @@ internal sealed class LivePresentationCompositionPhase
EntitySpawnAdapter entitySpawnAdapter,
EntityScriptActivator entityScriptActivator,
RetailStaticAnimatingObjectScheduler staticAnimationScheduler,
RuntimeWorldTransitState worldTransit,
WorldGenerationAvailabilityState worldAvailability,
GpuWorldState worldState,
RenderSceneShadowRuntime? renderSceneShadow,
@ -1026,6 +1033,7 @@ internal sealed class LivePresentationCompositionPhase
entitySpawnAdapter,
entityScriptActivator,
staticAnimationScheduler,
worldTransit,
worldAvailability,
worldState,
renderSceneShadow,

View file

@ -325,7 +325,6 @@ internal sealed class SessionPlayerCompositionPhase
content.Dats,
d.DatLock);
var worldQuiescence = new WorldGenerationQuiescence(
live.WorldAvailability,
d.Actions.Selection,
live.WorldState,
guid => live.LiveEntities.TryGetProjectionKey(
@ -340,6 +339,7 @@ internal sealed class SessionPlayerCompositionPhase
foundation.MeshAdapter.SetDestinationRevealUploadPriority,
foundation.TextureCache.SetDestinationRevealUploadPriority);
var worldReveal = new WorldRevealCoordinator(
live.WorldTransit,
streaming.IsRenderNeighborhoodResident,
d.PhysicsEngine.IsSpawnCellReady,
d.PhysicsEngine.IsNeighborhoodTerrainResident,
@ -359,7 +359,6 @@ internal sealed class SessionPlayerCompositionPhase
live.DrawDispatcher.InvalidateCompositeWarmupReadiness();
},
spawnClaimClassifier.IsUnhydratable,
d.Log,
worldQuiescence,
streaming,
revealRenderResources);
@ -880,7 +879,7 @@ internal sealed class SessionPlayerCompositionPhase
d.Actions,
d.PlayerController,
d.WorldEnvironment.Runtime,
worldReveal,
live.WorldTransit,
d.UpdateClock,
live.SelectionInteractions);
bindings.Adopt("current game runtime adapter", gameRuntime);

View file

@ -5,6 +5,7 @@ using AcDream.App.Rendering.Scene;
using AcDream.App.Streaming;
using AcDream.App.UI.Testing;
using AcDream.Core.Physics;
using AcDream.Runtime;
namespace AcDream.App.Diagnostics;
@ -101,7 +102,7 @@ internal sealed record WorldLifecycleCheckpoint(
string Name,
DateTime TimestampUtc,
int ProcessId,
WorldRevealLifecycleSnapshot Reveal,
RuntimePortalSnapshot Reveal,
RenderFrameOutcome Render,
WorldLifecycleResourceSnapshot Resources);
@ -175,7 +176,7 @@ internal sealed class WorldLifecycleAutomationController :
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
};
private readonly Func<WorldRevealLifecycleSnapshot> _getReveal;
private readonly Func<RuntimePortalSnapshot> _getReveal;
private readonly Func<int> _getPortalMaterializationCount;
private readonly Func<RenderFrameOutcome, WorldLifecycleResourceSnapshot>
_captureResources;
@ -189,7 +190,7 @@ internal sealed class WorldLifecycleAutomationController :
private bool _disposed;
public WorldLifecycleAutomationController(
Func<WorldRevealLifecycleSnapshot> getReveal,
Func<RuntimePortalSnapshot> getReveal,
Func<int> getPortalMaterializationCount,
Func<RenderFrameOutcome, WorldLifecycleResourceSnapshot> captureResources,
FrameScreenshotController screenshots,

View file

@ -1350,6 +1350,7 @@ public sealed class GameWindow :
settingsDevTools.DevTools?.LateBindings.WorldEntities,
settingsDevTools.DevTools?.LateBindings.FrameDiagnostics,
_uiFrameDiagnostics,
Console.WriteLine,
compositionToast),
this).Compose(
platformResult,

View file

@ -1,7 +1,6 @@
using AcDream.App.Input;
using AcDream.App.Interaction;
using AcDream.App.Net;
using AcDream.App.Streaming;
using AcDream.App.World;
using AcDream.Runtime;
using AcDream.Runtime.Entities;
@ -40,7 +39,7 @@ internal sealed class CurrentGameRuntimeAdapter
RuntimeActionState actions,
RuntimeLocalPlayerMovementState movement,
RuntimeWorldEnvironmentState environment,
WorldRevealCoordinator worldReveal,
RuntimeWorldTransitState worldTransit,
IGameRuntimeClock clock,
SelectionInteractionController selection)
{
@ -54,7 +53,7 @@ internal sealed class CurrentGameRuntimeAdapter
actions,
movement,
environment,
worldReveal,
worldTransit,
clock);
entityObjects.BindEventContext(
() => _view.Generation,

View file

@ -1,6 +1,5 @@
using AcDream.App.Input;
using AcDream.App.Net;
using AcDream.App.Streaming;
using AcDream.Core.Chat;
using AcDream.Core.Items;
using AcDream.Runtime;
@ -29,7 +28,7 @@ internal sealed class CurrentGameRuntimeViewAdapter : IGameRuntimeView
private readonly IRuntimeActionView _actionView;
private readonly IRuntimeMovementView _movementView;
private readonly IRuntimeWorldEnvironmentView _environmentView;
private readonly PortalView _portalView;
private readonly IRuntimePortalView _portalView;
private bool _active = true;
public CurrentGameRuntimeViewAdapter(
@ -42,7 +41,7 @@ internal sealed class CurrentGameRuntimeViewAdapter : IGameRuntimeView
RuntimeActionState actions,
RuntimeLocalPlayerMovementState movement,
RuntimeWorldEnvironmentState environment,
WorldRevealCoordinator worldReveal,
RuntimeWorldTransitState worldTransit,
IGameRuntimeClock clock)
{
_session = session ?? throw new ArgumentNullException(nameof(session));
@ -66,8 +65,8 @@ internal sealed class CurrentGameRuntimeViewAdapter : IGameRuntimeView
movement ?? throw new ArgumentNullException(nameof(movement))).View;
_environmentView = environment
?? throw new ArgumentNullException(nameof(environment));
_portalView = new PortalView(
worldReveal ?? throw new ArgumentNullException(nameof(worldReveal)));
_portalView = worldTransit
?? throw new ArgumentNullException(nameof(worldTransit));
}
internal bool IsActive => _active && !_session.IsDisposalComplete;
@ -130,33 +129,4 @@ internal sealed class CurrentGameRuntimeViewAdapter : IGameRuntimeView
_portalView.Snapshot);
internal void Deactivate() => _active = false;
private sealed class PortalView(WorldRevealCoordinator owner)
: IRuntimePortalView
{
public RuntimePortalSnapshot Snapshot
{
get
{
WorldRevealLifecycleSnapshot snapshot = owner.Snapshot;
RuntimePortalKind kind = snapshot.Generation == 0
? RuntimePortalKind.None
: snapshot.Kind switch
{
WorldRevealKind.Login => RuntimePortalKind.Login,
WorldRevealKind.Portal => RuntimePortalKind.Portal,
_ => RuntimePortalKind.None,
};
return new RuntimePortalSnapshot(
snapshot.Generation,
kind,
snapshot.Readiness.DestinationCell,
snapshot.IsReady,
snapshot.Materialized,
snapshot.Completed,
snapshot.Cancelled,
snapshot.WorldViewportObserved);
}
}
}
}

View file

@ -10,6 +10,7 @@ using AcDream.Core.Net.Messages;
using AcDream.Core.Physics;
using AcDream.Core.Rendering;
using AcDream.Core.World;
using AcDream.Runtime;
namespace AcDream.App.Streaming;
@ -668,7 +669,7 @@ internal sealed class LocalPlayerTeleportController
// Retail SmartBox enters blocking_for_cells before old-world object,
// physics, landscape, and ambient owners may advance again. Begin the
// reveal generation before a recenter can start detaching that world.
_worldReveal.Begin(WorldRevealKind.Portal, position.LandblockId);
_worldReveal.Begin(RuntimePortalKind.Portal, position.LandblockId);
if (!IsCurrentLifetime(generation, sequence))
return false;
@ -737,7 +738,10 @@ internal sealed class LocalPlayerTeleportController
if (_lifetimeGeneration != generation)
return generation;
_worldReveal.Cancel();
if (clearSession)
_worldReveal.ResetSession();
else
_worldReveal.Cancel();
if (_lifetimeGeneration != generation)
return generation;

View file

@ -1,6 +1,7 @@
using AcDream.App.Audio;
using AcDream.Core.Selection;
using AcDream.Runtime.Entities;
using AcDream.Runtime.World;
namespace AcDream.App.Streaming;
@ -24,57 +25,51 @@ internal sealed class AlwaysAvailableWorldGeneration
}
/// <summary>
/// Single-writer state behind <see cref="IWorldGenerationAvailability"/>.
/// Superseding reveal generations stay continuously quiesced; only the exact
/// active generation may reopen the world.
/// Read-only graphical-host projection of the canonical Runtime transit
/// lifetime. It stores no availability or generation state.
/// </summary>
internal sealed class WorldGenerationAvailabilityState
: IWorldGenerationAvailability
{
public bool IsWorldAvailable => QuiescedGeneration == 0;
public long QuiescedGeneration { get; private set; }
private readonly RuntimeWorldTransitState _transit;
public void Begin(long generation)
public WorldGenerationAvailabilityState(
RuntimeWorldTransitState transit)
{
if (generation <= 0)
throw new ArgumentOutOfRangeException(nameof(generation));
QuiescedGeneration = generation;
_transit = transit ?? throw new ArgumentNullException(nameof(transit));
}
public bool End(long generation)
{
if (generation <= 0 || QuiescedGeneration != generation)
return false;
public bool IsWorldAvailable =>
_transit.IsWorldSimulationAvailable;
QuiescedGeneration = 0;
return true;
}
public long QuiescedGeneration =>
IsWorldAvailable ? 0 : _transit.Snapshot.Generation;
}
internal readonly record struct WorldGenerationQuiescenceEdge(
bool ShouldApply,
bool ClearWorldSelection);
/// <summary>
/// Owns the immediate observable edge of retail
/// Projects the immediate graphical/audio edge of retail
/// <c>SmartBox::UseTime @ 0x00455410</c>'s <c>blocking_for_cells</c>
/// branch. Deferred teardown may retain memory, but the old generation cannot
/// keep rendering, targeting, ticking, or producing world audio.
/// branch. Runtime owns whether the world is available; this class only
/// applies selection and audio side effects at the accepted Runtime edge.
/// </summary>
internal sealed class WorldGenerationQuiescence
{
private readonly WorldGenerationAvailabilityState _availability;
private readonly SelectionState _selection;
private readonly GpuWorldState _world;
private readonly Func<uint, RuntimeEntityKey?> _resolveProjectionKey;
private readonly IWorldAudioQuiescence? _audio;
private bool _effectsQuiesced;
public WorldGenerationQuiescence(
WorldGenerationAvailabilityState availability,
SelectionState selection,
GpuWorldState world,
Func<uint, RuntimeEntityKey?> resolveProjectionKey,
IWorldAudioQuiescence? audio)
{
_availability = availability
?? throw new ArgumentNullException(nameof(availability));
_selection = selection ?? throw new ArgumentNullException(nameof(selection));
_world = world ?? throw new ArgumentNullException(nameof(world));
_resolveProjectionKey = resolveProjectionKey
@ -82,22 +77,33 @@ internal sealed class WorldGenerationQuiescence
_audio = audio;
}
public IWorldGenerationAvailability Availability => _availability;
public void Begin(long generation)
/// <summary>
/// Captures the pre-quiescence graphical selection fact before Runtime
/// closes world availability. The returned edge contains no authority and
/// is committed only after Runtime accepts the new generation.
/// </summary>
public WorldGenerationQuiescenceEdge CaptureBegin()
{
bool firstEdge = _availability.IsWorldAvailable;
uint? selected = firstEdge ? _selection.SelectedObjectId : null;
if (_effectsQuiesced)
return default;
uint? selected = _selection.SelectedObjectId;
bool clearWorldSelection =
selected is uint selectedGuid
&& _resolveProjectionKey(selectedGuid) is RuntimeEntityKey key
&& _world.IsLiveEntityVisible(key);
return new WorldGenerationQuiescenceEdge(
ShouldApply: true,
clearWorldSelection);
}
_availability.Begin(generation);
if (!firstEdge)
public void CommitBegin(in WorldGenerationQuiescenceEdge edge)
{
if (!edge.ShouldApply || _effectsQuiesced)
return;
if (clearWorldSelection)
_effectsQuiesced = true;
if (edge.ClearWorldSelection)
{
_selection.Clear(
SelectionChangeSource.System,
@ -107,9 +113,12 @@ internal sealed class WorldGenerationQuiescence
_audio?.SuspendWorldAudio();
}
public void End(long generation)
public void ObserveReleased()
{
if (_availability.End(generation))
_audio?.ResumeWorldAudio();
if (!_effectsQuiesced)
return;
_effectsQuiesced = false;
_audio?.ResumeWorldAudio();
}
}

View file

@ -1,9 +1,13 @@
using AcDream.Runtime;
using AcDream.Runtime.World;
namespace AcDream.App.Streaming;
/// <summary>
/// Generation-scoped destination-work seam. The reveal coordinator is the
/// canonical owner of login/portal lifetime; the streaming scheduler only
/// reserves capacity for the exact generation and destination it is given.
/// graphical host for Runtime's canonical login/portal lifetime; the
/// streaming scheduler only reserves capacity for the exact generation and
/// destination it is given.
/// </summary>
internal interface IWorldRevealStreamingScheduler
{
@ -26,23 +30,23 @@ internal interface IWorldRevealRenderResourceScheduler
}
/// <summary>
/// Owns one login/portal reveal lifetime across readiness and lifecycle
/// diagnostics. This keeps the destination barrier and its observations on a
/// single seam so callers cannot begin, prepare, or evaluate one owner while
/// forgetting the other.
/// Graphical-host adapter for one canonical Runtime login/portal reveal
/// lifetime. App owns render/collision readiness and destination resource
/// reservations; Runtime owns generation, destination, materialization,
/// simulation availability, completion, and cancellation.
/// </summary>
internal sealed class WorldRevealCoordinator
{
private readonly RuntimeWorldTransitState _transit;
private readonly WorldRevealReadinessBarrier _readiness;
private readonly WorldRevealLifecycleTelemetry _lifecycle;
private readonly WorldGenerationQuiescence? _quiescence;
private readonly IWorldRevealStreamingScheduler? _streaming;
private readonly IWorldRevealRenderResourceScheduler? _renderResources;
private long _activeGeneration;
private bool _worldSimulationReleased;
private long _reservationGeneration;
private bool _worldViewportReleased;
public WorldRevealCoordinator(
RuntimeWorldTransitState transit,
Func<uint, int, bool> isRenderNeighborhoodReady,
Func<uint, bool> isSpawnCellReady,
Func<uint, int, bool> isTerrainNeighborhoodReady,
@ -50,11 +54,11 @@ internal sealed class WorldRevealCoordinator
Action<uint, int> prepareCompositeTextures,
Action invalidateCompositeTextures,
Func<uint, bool> isSpawnClaimUnhydratable,
Action<string>? log = null,
WorldGenerationQuiescence? quiescence = null,
IWorldRevealStreamingScheduler? streaming = null,
IWorldRevealRenderResourceScheduler? renderResources = null)
{
_transit = transit ?? throw new ArgumentNullException(nameof(transit));
_readiness = new WorldRevealReadinessBarrier(
isRenderNeighborhoodReady,
isSpawnCellReady,
@ -63,27 +67,28 @@ internal sealed class WorldRevealCoordinator
prepareCompositeTextures,
invalidateCompositeTextures,
isSpawnClaimUnhydratable);
_lifecycle = new WorldRevealLifecycleTelemetry(log);
_quiescence = quiescence;
_streaming = streaming;
_renderResources = renderResources;
}
public WorldRevealLifecycleSnapshot Snapshot => _lifecycle.Snapshot;
public int PortalMaterializationCount => _lifecycle.PortalMaterializationCount;
public bool WaitCueShown => _lifecycle.WaitCueShown;
public RuntimePortalSnapshot Snapshot => _transit.Snapshot;
public int PortalMaterializationCount =>
_transit.Snapshot.PortalMaterializationCount;
public bool WaitCueShown => _transit.Snapshot.WaitCueShown;
public long Begin(WorldRevealKind kind, uint destinationCell)
public long Begin(RuntimePortalKind kind, uint destinationCell)
{
if (destinationCell == 0u)
throw new ArgumentOutOfRangeException(nameof(destinationCell));
WorldGenerationQuiescenceEdge quiescenceEdge =
_quiescence?.CaptureBegin() ?? default;
_readiness.Begin();
long generation = _lifecycle.Begin(kind);
_activeGeneration = generation;
_worldSimulationReleased = false;
long generation = _transit.BeginReveal(kind, destinationCell);
_quiescence?.CommitBegin(quiescenceEdge);
_reservationGeneration = generation;
_worldViewportReleased = false;
_quiescence?.Begin(generation);
_streaming?.BeginDestinationReservation(
generation,
destinationCell,
@ -105,7 +110,20 @@ internal sealed class WorldRevealCoordinator
public WorldRevealReadinessSnapshot Evaluate(uint destinationCell)
{
WorldRevealReadinessSnapshot snapshot = _readiness.Evaluate(destinationCell);
_lifecycle.ObserveReadiness(snapshot);
RuntimePortalSnapshot portal = _transit.Snapshot;
if (portal.Generation != 0)
{
_transit.AcknowledgeDestinationReadiness(
new RuntimeDestinationReadiness(
portal.Generation,
snapshot.DestinationCell,
snapshot.IsIndoor,
snapshot.IsUnhydratable,
snapshot.RequiredRenderRadius,
snapshot.IsRenderNeighborhoodReady,
snapshot.AreCompositeTexturesReady,
snapshot.IsCollisionReady));
}
return snapshot;
}
@ -122,15 +140,30 @@ internal sealed class WorldRevealCoordinator
/// </remarks>
public void ObserveMaterialized()
{
_lifecycle.ObserveMaterialized();
ReleaseWorldSimulation();
RuntimePortalSnapshot snapshot = _transit.Snapshot;
if (snapshot.Generation == 0)
return;
bool wasAvailable = _transit.IsWorldSimulationAvailable;
_transit.AcknowledgeMaterialized(
snapshot.Generation,
snapshot.DestinationCell);
ObserveSimulationRelease(wasAvailable);
}
public void ObserveWorldViewportVisible() =>
_lifecycle.ObserveWorldViewportVisible();
public void ObserveWorldViewportVisible()
{
long generation = _transit.Snapshot.Generation;
if (generation != 0)
_transit.AcknowledgeWorldViewportVisible(generation);
}
public bool ObserveWait(TimeSpan elapsed) =>
_lifecycle.ObserveWait(elapsed);
public bool ObserveWait(TimeSpan elapsed)
{
long generation = _transit.Snapshot.Generation;
return generation != 0
&& _transit.ObserveWait(generation, elapsed);
}
/// <summary>
/// Releases the destination streaming/resource reservation at retail's
@ -140,7 +173,7 @@ internal sealed class WorldRevealCoordinator
/// </summary>
public void RevealWorldViewport()
{
long generation = _activeGeneration;
long generation = _reservationGeneration;
if (generation == 0 || _worldViewportReleased)
return;
@ -151,36 +184,53 @@ internal sealed class WorldRevealCoordinator
public void Complete()
{
_lifecycle.Complete();
EndLifetime();
long generation = _transit.Snapshot.Generation;
if (generation == 0)
return;
bool wasAvailable = _transit.IsWorldSimulationAvailable;
_transit.Complete(generation);
ObserveSimulationRelease(wasAvailable);
EndHostLifetime();
}
public void Cancel()
{
_lifecycle.Cancel();
EndLifetime();
}
private void EndLifetime()
{
long generation = _activeGeneration;
long generation = _transit.Snapshot.Generation;
if (generation == 0)
return;
bool wasAvailable = _transit.IsWorldSimulationAvailable;
_transit.Cancel(generation);
ObserveSimulationRelease(wasAvailable);
EndHostLifetime();
}
public void ResetSession()
{
bool wasAvailable = _transit.IsWorldSimulationAvailable;
long generation = _transit.Snapshot.Generation;
if (generation != 0)
_transit.Cancel(generation);
ObserveSimulationRelease(wasAvailable);
EndHostLifetime();
_transit.ResetSession();
}
private void EndHostLifetime()
{
long generation = _reservationGeneration;
if (generation == 0)
return;
ReleaseWorldSimulation();
RevealWorldViewport();
_activeGeneration = 0;
_worldSimulationReleased = false;
_reservationGeneration = 0;
_worldViewportReleased = false;
}
private void ReleaseWorldSimulation()
private void ObserveSimulationRelease(bool wasAvailable)
{
long generation = _activeGeneration;
if (generation == 0 || _worldSimulationReleased)
return;
_quiescence?.End(generation);
_worldSimulationReleased = true;
if (!wasAvailable && _transit.IsWorldSimulationAvailable)
_quiescence?.ObserveReleased();
}
}

View file

@ -1,187 +0,0 @@
using System.Globalization;
namespace AcDream.App.Streaming;
internal enum WorldRevealKind
{
Login,
Portal,
}
internal readonly record struct WorldRevealLifecycleSnapshot(
long Generation,
WorldRevealKind Kind,
WorldRevealReadinessSnapshot Readiness,
bool Materialized,
bool Completed,
bool Cancelled,
bool WorldViewportObserved,
int InvariantFailureCount)
{
public bool IsActive => Generation != 0 && !Cancelled;
public bool IsReady => Readiness.IsReady;
}
/// <summary>
/// Observes logical login/portal reveal generations without owning rendering or
/// changing gameplay state. The owner turns the canonical readiness decision
/// into deterministic lifecycle markers for connected automation and records a
/// hard diagnostic failure if normal world geometry becomes visible early.
/// </summary>
internal sealed class WorldRevealLifecycleTelemetry
{
internal static readonly TimeSpan RetailWaitCueDelay =
TimeSpan.FromSeconds(5);
private readonly Action<string> _log;
private WorldRevealLifecycleSnapshot _snapshot;
private long _nextGeneration;
private int _portalMaterializationCount;
private bool _waitCueShown;
public WorldRevealLifecycleTelemetry(Action<string>? log = null)
{
_log = log ?? (_ => { });
}
public WorldRevealLifecycleSnapshot Snapshot => _snapshot;
public int PortalMaterializationCount => _portalMaterializationCount;
public bool WaitCueShown => _waitCueShown;
public long Begin(WorldRevealKind kind)
{
if (_snapshot.Generation != 0
&& !_snapshot.Cancelled
&& !_snapshot.WorldViewportObserved)
{
Log("superseded", _snapshot);
}
long generation = checked(++_nextGeneration);
_waitCueShown = false;
_snapshot = new WorldRevealLifecycleSnapshot(
generation,
kind,
default,
Materialized: false,
Completed: false,
Cancelled: false,
WorldViewportObserved: false,
InvariantFailureCount: _snapshot.InvariantFailureCount);
Log("begin", _snapshot);
return generation;
}
public bool ObserveWait(TimeSpan elapsed)
{
if (_snapshot.Generation == 0
|| _snapshot.Cancelled
|| _snapshot.Completed
|| elapsed < RetailWaitCueDelay)
{
return false;
}
if (!_waitCueShown)
{
_waitCueShown = true;
_log(
$"[world-reveal] event=wait-cue elapsedMs={elapsed.TotalMilliseconds:F0} "
+ Describe(_snapshot));
}
return true;
}
public void ObserveReadiness(WorldRevealReadinessSnapshot readiness)
{
if (_snapshot.Generation == 0 || _snapshot.Cancelled)
return;
if (_snapshot.Readiness == readiness)
return;
if (_snapshot.Readiness.DestinationCell != 0u
&& readiness.DestinationCell != 0u
&& _snapshot.Readiness.DestinationCell != readiness.DestinationCell)
{
FailInvariant(
"destination-changed",
$"from=0x{_snapshot.Readiness.DestinationCell:X8} to=0x{readiness.DestinationCell:X8}");
}
_snapshot = _snapshot with { Readiness = readiness };
Log("readiness", _snapshot);
}
public void ObserveMaterialized()
{
if (_snapshot.Generation == 0 || _snapshot.Cancelled || _snapshot.Materialized)
return;
_snapshot = _snapshot with { Materialized = true };
if (_snapshot.Kind == WorldRevealKind.Portal)
_portalMaterializationCount++;
Log("materialized", _snapshot);
}
public void ObserveWorldViewportVisible()
{
if (_snapshot.Generation == 0 || _snapshot.Cancelled || _snapshot.WorldViewportObserved)
return;
if (!_snapshot.Readiness.IsReady)
FailInvariant("viewport-before-ready", null);
_snapshot = _snapshot with { WorldViewportObserved = true };
Log("world-visible", _snapshot);
}
public void Complete()
{
if (_snapshot.Generation == 0 || _snapshot.Cancelled || _snapshot.Completed)
return;
_snapshot = _snapshot with { Completed = true };
Log("complete", _snapshot);
}
public void Cancel()
{
if (_snapshot.Generation == 0
|| _snapshot.Cancelled
|| _snapshot.Completed)
return;
_snapshot = _snapshot with { Cancelled = true };
Log("cancel", _snapshot);
}
private void FailInvariant(string reason, string? detail)
{
_snapshot = _snapshot with
{
InvariantFailureCount = checked(_snapshot.InvariantFailureCount + 1),
};
string suffix = string.IsNullOrWhiteSpace(detail) ? string.Empty : $" {detail}";
_log($"[world-reveal] event=invariant-failure reason={reason}{suffix} {Describe(_snapshot)}");
}
private void Log(string eventName, WorldRevealLifecycleSnapshot snapshot) =>
_log($"[world-reveal] event={eventName} {Describe(snapshot)}");
private static string Describe(WorldRevealLifecycleSnapshot snapshot)
{
WorldRevealReadinessSnapshot ready = snapshot.Readiness;
return string.Create(
CultureInfo.InvariantCulture,
$"generation={snapshot.Generation} kind={snapshot.Kind} " +
$"cell=0x{ready.DestinationCell:X8} indoor={ready.IsIndoor} " +
$"radius={ready.RequiredRenderRadius} unhydratable={ready.IsUnhydratable} " +
$"render={ready.IsRenderNeighborhoodReady} composites={ready.AreCompositeTexturesReady} " +
$"collision={ready.IsCollisionReady} ready={ready.IsReady} " +
$"materialized={snapshot.Materialized} completed={snapshot.Completed} " +
$"cancelled={snapshot.Cancelled} visible={snapshot.WorldViewportObserved} " +
$"failures={snapshot.InvariantFailureCount}");
}
}

View file

@ -5,6 +5,7 @@ using AcDream.App.Rendering.Vfx;
using AcDream.App.Streaming;
using AcDream.Core.Net;
using AcDream.Core.Net.Messages;
using AcDream.Runtime;
using AcDream.Runtime.Entities;
namespace AcDream.App.World;
@ -237,7 +238,7 @@ internal sealed class LiveEntityWorldOriginCoordinator : ILiveEntityWorldOriginC
lbY,
isSealedDungeon: _sealedDungeonCells.IsSealedDungeon(
position.LandblockId));
_worldReveal.Begin(WorldRevealKind.Login, position.LandblockId);
_worldReveal.Begin(RuntimePortalKind.Login, position.LandblockId);
return new(
true,

View file

@ -92,15 +92,59 @@ public enum RuntimePortalKind
Portal,
}
public readonly record struct RuntimeDestinationReadiness(
long Generation,
uint DestinationCell,
bool IsIndoor,
bool IsUnhydratable,
int RequiredRenderRadius,
bool IsRenderNeighborhoodReady,
bool AreCompositeTexturesReady,
bool IsCollisionReady)
{
public bool HasDestination => DestinationCell != 0u;
public bool IsReady => HasDestination
&& (IsUnhydratable
|| (IsRenderNeighborhoodReady
&& AreCompositeTexturesReady
&& IsCollisionReady));
}
public readonly record struct RuntimePortalSnapshot(
long Generation,
RuntimePortalKind Kind,
uint DestinationCell,
bool IsReady,
bool IsMaterialized,
bool IsCompleted,
bool IsCancelled,
bool IsWorldVisible);
RuntimeDestinationReadiness Readiness,
bool Materialized,
bool Completed,
bool Cancelled,
bool WorldViewportObserved,
bool WorldSimulationAvailable,
int InvariantFailureCount,
bool WaitCueShown,
int PortalMaterializationCount)
{
public static RuntimePortalSnapshot Idle { get; } = new(
Generation: 0,
RuntimePortalKind.None,
Readiness: default,
Materialized: false,
Completed: false,
Cancelled: false,
WorldViewportObserved: false,
WorldSimulationAvailable: true,
InvariantFailureCount: 0,
WaitCueShown: false,
PortalMaterializationCount: 0);
public uint DestinationCell => Readiness.DestinationCell;
public bool IsReady => Readiness.IsReady;
public bool IsMaterialized => Materialized;
public bool IsCompleted => Completed;
public bool IsCancelled => Cancelled;
public bool IsWorldVisible => WorldViewportObserved;
public bool IsActive => Generation != 0 && !Cancelled;
}
public interface IRuntimePortalView
{

View file

@ -0,0 +1,385 @@
using System.Globalization;
namespace AcDream.Runtime.World;
/// <summary>
/// Canonical presentation-independent owner of one login/portal reveal
/// generation. The graphical or headless host supplies typed destination
/// readiness acknowledgements; Runtime owns which generation and destination
/// those acknowledgements are allowed to advance.
/// </summary>
/// <remarks>
/// Retail ordering follows <c>SmartBox::TeleportPlayer @ 0x00453910</c>,
/// <c>SmartBox::UseTime @ 0x00455410</c>, and
/// <c>gmSmartBoxUI::EndTeleportAnimation @ 0x004D65A0</c>. Destination
/// materialization resumes simulation before the later normal-world viewport
/// edge.
/// </remarks>
public sealed class RuntimeWorldTransitState
: IRuntimePortalView
{
public static readonly TimeSpan RetailWaitCueDelay =
TimeSpan.FromSeconds(5);
private readonly Action<string> _log;
private RuntimePortalSnapshot _snapshot = RuntimePortalSnapshot.Idle;
private long _nextGeneration;
public RuntimeWorldTransitState(Action<string>? log = null)
{
_log = log ?? (_ => { });
}
public RuntimePortalSnapshot Snapshot => _snapshot;
public bool IsWorldSimulationAvailable =>
_snapshot.WorldSimulationAvailable;
public int DiagnosticFailureCount { get; private set; }
public Exception? LastDiagnosticFailure { get; private set; }
public long BeginReveal(
RuntimePortalKind kind,
uint destinationCell)
{
if (kind is RuntimePortalKind.None)
throw new ArgumentOutOfRangeException(nameof(kind));
if (destinationCell == 0u)
throw new ArgumentOutOfRangeException(nameof(destinationCell));
if (_snapshot.Generation != 0
&& !_snapshot.Cancelled
&& !_snapshot.WorldViewportObserved)
{
Log("superseded", _snapshot);
}
long generation = checked(++_nextGeneration);
int failures = _snapshot.InvariantFailureCount;
int materializations = _snapshot.PortalMaterializationCount;
_snapshot = new RuntimePortalSnapshot(
generation,
kind,
new RuntimeDestinationReadiness(
generation,
destinationCell,
IsIndoor: IsIndoor(destinationCell),
IsUnhydratable: false,
RequiredRenderRadius: 0,
IsRenderNeighborhoodReady: false,
AreCompositeTexturesReady: false,
IsCollisionReady: false),
Materialized: false,
Completed: false,
Cancelled: false,
WorldViewportObserved: false,
WorldSimulationAvailable: false,
InvariantFailureCount: failures,
WaitCueShown: false,
PortalMaterializationCount: materializations);
Log("begin", _snapshot);
return generation;
}
public bool AcknowledgeDestinationReadiness(
in RuntimeDestinationReadiness acknowledgement)
{
if (!ValidateActive(
acknowledgement.Generation,
acknowledgement.DestinationCell,
"readiness"))
{
return false;
}
if (_snapshot.Readiness.IsReady)
{
if (_snapshot.Readiness == acknowledgement)
return false;
FailInvariant(
"readiness-changed-after-ready",
$"accepted={DescribeReadiness(_snapshot.Readiness)} "
+ $"actual={DescribeReadiness(acknowledgement)}");
return false;
}
bool isIndoor = IsIndoor(acknowledgement.DestinationCell);
int requiredRenderRadius = isIndoor ? 0 : 1;
if (acknowledgement.IsIndoor != isIndoor
|| acknowledgement.RequiredRenderRadius
!= requiredRenderRadius)
{
FailInvariant(
"invalid-readiness-shape",
$"indoor={acknowledgement.IsIndoor} "
+ $"expectedIndoor={isIndoor} "
+ $"radius={acknowledgement.RequiredRenderRadius} "
+ $"expectedRadius={requiredRenderRadius}");
return false;
}
if (_snapshot.Readiness == acknowledgement)
return false;
_snapshot = _snapshot with { Readiness = acknowledgement };
Log("readiness", _snapshot);
return true;
}
public bool AcknowledgeMaterialized(
long generation,
uint destinationCell)
{
if (!ValidateActive(generation, destinationCell, "materialized"))
return false;
if (_snapshot.Materialized)
return false;
if (!_snapshot.Readiness.IsReady)
{
FailInvariant("materialized-before-ready", null);
return false;
}
int count = _snapshot.PortalMaterializationCount;
if (_snapshot.Kind == RuntimePortalKind.Portal)
count = checked(count + 1);
_snapshot = _snapshot with
{
Materialized = true,
WorldSimulationAvailable = true,
PortalMaterializationCount = count,
};
Log("materialized", _snapshot);
return true;
}
public bool AcknowledgeWorldViewportVisible(long generation)
{
if (!ValidateGeneration(
generation,
"world-visible",
allowCompleted: true))
{
return false;
}
if (_snapshot.WorldViewportObserved)
return false;
if (!_snapshot.Readiness.IsReady)
{
FailInvariant("viewport-before-ready", null);
return false;
}
_snapshot = _snapshot with { WorldViewportObserved = true };
Log("world-visible", _snapshot);
return true;
}
public bool ObserveWait(long generation, TimeSpan elapsed)
{
if (generation == 0
|| generation != _snapshot.Generation
|| _snapshot.Cancelled
|| _snapshot.Completed
|| elapsed < RetailWaitCueDelay)
{
return false;
}
if (!_snapshot.WaitCueShown)
{
_snapshot = _snapshot with { WaitCueShown = true };
SafeLog(
$"[world-reveal] event=wait-cue "
+ $"elapsedMs={elapsed.TotalMilliseconds:F0} "
+ Describe(_snapshot));
}
return true;
}
public bool Complete(long generation)
{
if (!ValidateGeneration(
generation,
"complete",
allowCompleted: true))
{
return false;
}
if (_snapshot.Completed)
return false;
if (!_snapshot.Readiness.IsReady)
{
FailInvariant("complete-before-ready", null);
return false;
}
if (_snapshot.Kind == RuntimePortalKind.Portal
&& !_snapshot.Materialized)
{
FailInvariant("portal-complete-before-materialized", null);
return false;
}
_snapshot = _snapshot with
{
Completed = true,
WorldSimulationAvailable = true,
};
Log("complete", _snapshot);
return true;
}
public bool Cancel(long generation)
{
if (generation == 0
|| generation != _snapshot.Generation
|| _snapshot.Cancelled
|| _snapshot.Completed)
{
return false;
}
_snapshot = _snapshot with
{
Cancelled = true,
WorldSimulationAvailable = true,
};
Log("cancel", _snapshot);
return true;
}
/// <summary>
/// Clears session-visible state while retaining the monotonically
/// increasing generation counter so a delayed prior-session host
/// acknowledgement cannot match a future generation.
/// </summary>
public void ResetSession()
{
_snapshot = RuntimePortalSnapshot.Idle;
}
private bool ValidateActive(
long generation,
uint destinationCell,
string eventName)
{
if (!ValidateGeneration(
generation,
eventName,
allowCompleted: false))
{
return false;
}
if (destinationCell == 0u
|| destinationCell != _snapshot.DestinationCell)
{
FailInvariant(
$"{eventName}-destination-mismatch",
$"expected=0x{_snapshot.DestinationCell:X8} "
+ $"actual=0x{destinationCell:X8}");
return false;
}
return true;
}
private bool ValidateGeneration(
long generation,
string eventName,
bool allowCompleted)
{
if (generation == 0 || generation != _snapshot.Generation)
{
LogRejected(
$"{eventName}-generation-mismatch",
$"expected={_snapshot.Generation} actual={generation}");
return false;
}
if (_snapshot.Cancelled
|| (!allowCompleted && _snapshot.Completed))
{
LogRejected(
$"{eventName}-after-terminal",
$"completed={_snapshot.Completed} "
+ $"cancelled={_snapshot.Cancelled}");
return false;
}
return true;
}
private void FailInvariant(string reason, string? detail)
{
_snapshot = _snapshot with
{
InvariantFailureCount =
checked(_snapshot.InvariantFailureCount + 1),
};
string suffix =
string.IsNullOrWhiteSpace(detail) ? string.Empty : $" {detail}";
SafeLog(
$"[world-reveal] event=invariant-failure "
+ $"reason={reason}{suffix} {Describe(_snapshot)}");
}
private void LogRejected(string reason, string? detail)
{
string suffix =
string.IsNullOrWhiteSpace(detail) ? string.Empty : $" {detail}";
SafeLog(
$"[world-reveal] event=rejected "
+ $"reason={reason}{suffix} {Describe(_snapshot)}");
}
private void Log(string eventName, RuntimePortalSnapshot snapshot) =>
SafeLog($"[world-reveal] event={eventName} {Describe(snapshot)}");
private void SafeLog(string message)
{
try
{
_log(message);
}
catch (Exception error)
{
DiagnosticFailureCount =
checked(DiagnosticFailureCount + 1);
LastDiagnosticFailure = error;
}
}
private static string Describe(RuntimePortalSnapshot snapshot)
{
RuntimeDestinationReadiness ready = snapshot.Readiness;
return string.Create(
CultureInfo.InvariantCulture,
$"generation={snapshot.Generation} kind={snapshot.Kind} "
+ $"cell=0x{ready.DestinationCell:X8} "
+ $"indoor={ready.IsIndoor} "
+ $"radius={ready.RequiredRenderRadius} "
+ $"unhydratable={ready.IsUnhydratable} "
+ $"render={ready.IsRenderNeighborhoodReady} "
+ $"composites={ready.AreCompositeTexturesReady} "
+ $"collision={ready.IsCollisionReady} ready={ready.IsReady} "
+ $"materialized={snapshot.Materialized} "
+ $"completed={snapshot.Completed} "
+ $"cancelled={snapshot.Cancelled} "
+ $"visible={snapshot.WorldViewportObserved} "
+ $"simulation={snapshot.WorldSimulationAvailable} "
+ $"failures={snapshot.InvariantFailureCount}");
}
private static string DescribeReadiness(
in RuntimeDestinationReadiness readiness) =>
string.Create(
CultureInfo.InvariantCulture,
$"indoor={readiness.IsIndoor},"
+ $"unhydratable={readiness.IsUnhydratable},"
+ $"radius={readiness.RequiredRenderRadius},"
+ $"render={readiness.IsRenderNeighborhoodReady},"
+ $"composites={readiness.AreCompositeTexturesReady},"
+ $"collision={readiness.IsCollisionReady}");
private static bool IsIndoor(uint cellId) =>
(cellId & 0xFFFFu) >= 0x0100u;
}