2026-07-10 04:39:16 +01:00
using System ;
using System.Collections.Generic ;
using System.IO ;
using System.Linq ;
2026-07-12 13:10:43 +01:00
using System.Collections.Concurrent ;
2026-07-20 00:04:45 +01:00
using System.Net.Sockets ;
2026-07-19 22:56:18 +01:00
using System.Threading ;
2026-07-18 19:22:35 +01:00
using System.Threading.Tasks ;
2026-07-10 04:39:16 +01:00
using GameCult.Caching ;
2026-07-15 17:12:11 +01:00
using GameCult.Eve.PluginFields ;
2026-07-10 04:39:16 +01:00
using GameCult.Eve.Surface ;
2026-07-15 17:12:11 +01:00
using GameCult.Eve.UnityScene.Fields ;
2026-07-10 04:39:16 +01:00
using GameCult.Mesh ;
2026-07-19 22:56:18 +01:00
using GameCult.Mesh.Quic.Native ;
2026-07-10 06:00:36 +01:00
using UnityEngine ;
2026-07-19 20:34:03 +01:00
using Stopwatch = System . Diagnostics . Stopwatch ;
2026-07-10 04:39:16 +01:00
#nullable enable
namespace GameCult.Eve.UnityScene
{
public sealed class EveUnityCultMeshLiveProviderTransport :
IEveUnitySceneLiveProviderTransport ,
2026-07-10 06:00:36 +01:00
IEveUnityGameObjectAssetProvider ,
2026-07-10 04:39:16 +01:00
IDisposable
{
2026-08-19 10:04:30 +02:00
private const int AssetPresentationAttemptLimit = 3 ;
2026-08-17 21:02:01 +02:00
private readonly string _cachePath ;
private readonly string _rendezvousEndpoint ;
2026-08-18 07:27:13 +02:00
private readonly CultMeshSessionTarget _target ;
2026-07-10 04:39:16 +01:00
private readonly string _providerId ;
private readonly string _surfaceId ;
private readonly string _runtimeId ;
2026-08-18 19:41:25 +02:00
private readonly CultMeshAuthorityTrustPolicy _authorityTrust ;
2026-08-19 08:09:59 +02:00
private readonly CultMeshAuthorityTrustPolicy _crossTargetAuthorityTrust ;
2026-08-19 04:03:00 +02:00
private readonly Dictionary < string , EveSurfaceCommandRequest > _pendingCommands =
new Dictionary < string , EveSurfaceCommandRequest > ( StringComparer . Ordinal ) ;
2026-08-18 19:03:06 +02:00
private readonly Dictionary < string , Task < ReceiptSubscription > > _receiptSubscriptions =
new Dictionary < string , Task < ReceiptSubscription > > ( StringComparer . Ordinal ) ;
2026-08-19 09:10:37 +02:00
private readonly object _presentationFinalityGate = new object ( ) ;
private readonly Dictionary < string , EveCommandReceiptDocument > _deferredTerminalReceipts =
new Dictionary < string , EveCommandReceiptDocument > ( StringComparer . Ordinal ) ;
2026-08-18 10:08:03 +02:00
private readonly HashSet < string > _continuousCommandIds = new HashSet < string > ( StringComparer . Ordinal ) ;
2026-07-12 13:10:43 +01:00
private readonly ConcurrentQueue < object > _liveDocuments = new ConcurrentQueue < object > ( ) ;
2026-07-19 22:56:18 +01:00
private readonly object _realtimeFrameGate = new object ( ) ;
private readonly Dictionary < string , CultMeshRealtimeFrame > _latestRealtimeFrames =
new Dictionary < string , CultMeshRealtimeFrame > ( StringComparer . Ordinal ) ;
private readonly HashSet < string > _queuedRealtimeFrameBodies =
new HashSet < string > ( StringComparer . Ordinal ) ;
2026-07-19 07:35:16 +01:00
private readonly Dictionary < string , EveSurfaceDocument > _embeddedSurfaces =
new Dictionary < string , EveSurfaceDocument > ( StringComparer . Ordinal ) ;
2026-08-17 21:02:01 +02:00
private readonly List < IDisposable > _documentLeases = new List < IDisposable > ( ) ;
private readonly List < IDisposable > _documentWatches = new List < IDisposable > ( ) ;
2026-08-18 10:08:03 +02:00
private readonly CancellationTokenSource _lifetime = new CancellationTokenSource ( ) ;
2026-08-19 07:57:33 +02:00
private readonly SemaphoreSlim _assetGenerationGate = new SemaphoreSlim ( 1 , 1 ) ;
2026-07-14 01:26:47 +01:00
private CultMeshClient ? _meshClient ;
2026-08-17 21:02:01 +02:00
private bool _liveDocumentsReady ;
private CultCache ? _contentState ;
2026-08-19 07:57:33 +02:00
private AssetGeneration _assetGeneration ;
2026-07-10 04:39:16 +01:00
private EveProviderAdvertisementDocument ? _advertisement ;
private EveAdvertisedSurface ? _advertisedSurface ;
2026-07-19 07:35:16 +01:00
private EveSurfaceDocument ? _baseSurface ;
2026-07-13 22:21:47 +01:00
private CultMeshBodyPublicationResolver ? _bodyResolver ;
2026-07-19 04:07:02 +01:00
private EveEntitySoaViewDocument ? _latestEntityLayout ;
2026-07-19 05:56:09 +01:00
private CultMeshBodyPublicationDocument ? _latestEntityPublication ;
2026-07-19 04:39:33 +01:00
private CultMeshMappedFrameBodyCursor ? _mappedEntityFrameCursor ;
private CultMeshBodyDescriptor ? _mappedEntityFrameContract ;
2026-07-19 22:56:18 +01:00
private CancellationTokenSource ? _realtimeLifetime ;
2026-08-19 09:36:55 +02:00
private CancellationTokenSource ? _surfaceAssetCandidateLifetime ;
2026-07-19 22:56:18 +01:00
private Task ? _realtimePump ;
private CultMeshRealtimeSession ? _realtimeSession ;
2026-08-18 10:08:03 +02:00
private EveUnityCultMeshCommandOutbox ? _commandOutbox ;
2026-08-19 07:31:25 +02:00
private PendingAssetCatalogUpdate ? _pendingAssetCatalog ;
2026-08-18 10:08:03 +02:00
private bool _assetCatalogUpdateRunning ;
2026-08-19 07:31:25 +02:00
private long _surfaceAssetGeneration ;
2026-08-19 09:36:55 +02:00
private long _highestObservedBaseSurfaceVersion = - 1 ;
2026-08-19 09:56:36 +02:00
private long _activeBaseSurfaceCandidateVersion = - 1 ;
private long _activeBaseSurfaceCandidateGeneration = - 1 ;
2026-08-19 10:04:30 +02:00
private int _lastAssetPresentationAttemptCount ;
2026-08-19 09:19:04 +02:00
private long _mountedBaseSurfaceVersion ;
2026-08-19 09:10:37 +02:00
private long _presentationBarrierVersion = - 1 ;
2026-07-14 00:45:39 +01:00
private long _lastQueuedEntityViewEpoch = - 1 ;
private long _lastQueuedEntityViewSequence = - 1 ;
2026-07-19 05:56:09 +01:00
private long _lastPresentedEntityViewEpoch = - 1 ;
private long _lastPresentedEntityViewSequence = - 1 ;
2026-07-19 06:30:37 +01:00
private bool _bootstrapped ;
2026-07-18 19:22:35 +01:00
private bool _disposed ;
2026-07-10 04:39:16 +01:00
public EveUnityCultMeshLiveProviderTransport (
2026-08-17 21:02:01 +02:00
string cachePath ,
string rendezvousEndpoint ,
2026-08-18 07:27:13 +02:00
string verseId ,
string authorityRuntimeId ,
2026-07-10 04:39:16 +01:00
string providerId ,
string surfaceId ,
2026-07-13 18:01:12 +01:00
string runtimeId = "eve-unity" ,
2026-08-18 19:41:25 +02:00
CultMeshBodyPublicationResolver ? bodyResolver = null ,
2026-08-19 08:09:59 +02:00
CultMeshAuthorityTrustPolicy ? authorityTrust = null ,
CultMeshAuthorityTrustPolicy ? crossTargetAuthorityTrust = null )
2026-07-10 04:39:16 +01:00
{
2026-08-17 21:02:01 +02:00
_cachePath = string . IsNullOrWhiteSpace ( cachePath )
? throw new ArgumentException ( "Cache path must be non-empty." , nameof ( cachePath ) )
: Path . GetFullPath ( cachePath ) ;
_rendezvousEndpoint = string . IsNullOrWhiteSpace ( rendezvousEndpoint )
? throw new ArgumentException ( "CultMesh rendezvous endpoint must be non-empty." , nameof ( rendezvousEndpoint ) )
: rendezvousEndpoint . Trim ( ) ;
2026-08-18 07:27:13 +02:00
_target = new CultMeshSessionTarget ( verseId , authorityRuntimeId ) ;
2026-07-10 04:39:16 +01:00
_providerId = string . IsNullOrWhiteSpace ( providerId )
? throw new ArgumentException ( "Provider id must be non-empty." , nameof ( providerId ) )
: providerId . Trim ( ) ;
2026-08-19 07:57:33 +02:00
_assetGeneration = new AssetGeneration (
new AssetSource ( _target , _providerId , "" , Array . Empty < string > ( ) ) ,
sourceIdentity : "" ,
catalogVersion : - 1 ,
meshClient : null ) ;
2026-07-10 04:39:16 +01:00
_surfaceId = string . IsNullOrWhiteSpace ( surfaceId )
? throw new ArgumentException ( "Surface id must be non-empty." , nameof ( surfaceId ) )
: surfaceId . Trim ( ) ;
_runtimeId = string . IsNullOrWhiteSpace ( runtimeId ) ? "eve-unity" : runtimeId . Trim ( ) ;
2026-07-13 22:26:04 +01:00
_bodyResolver = bodyResolver ;
2026-08-18 19:41:25 +02:00
_authorityTrust = authorityTrust ? ? new CultMeshAuthorityTrustPolicy (
CultMeshAuthorityTrustMode . AuthenticatedRemote ) ;
2026-08-19 08:09:59 +02:00
_crossTargetAuthorityTrust = crossTargetAuthorityTrust ? ? _authorityTrust ;
2026-07-10 04:39:16 +01:00
CurrentSurfaceDocument = EmptySurfaceDocument ( ) ;
CurrentAssetManifestDocument = EmptyAssetManifest ( ) ;
2026-07-15 03:21:28 +01:00
CurrentInputCapability = new EveInputCapabilityDocument ( ) ;
2026-07-10 04:39:16 +01:00
}
2026-08-17 21:02:01 +02:00
public string TransportKind = > "eve-cultmesh-identity-session" ;
2026-07-10 04:39:16 +01:00
public string SurfacePointer = > CurrentSurfaceDocument . SourcePointer ;
public string AssetManifestPointer = > CurrentAssetManifestDocument . ManifestRef ;
public EveUnitySceneProviderSurfaceDocument CurrentSurfaceDocument { get ; private set ; }
public EveUnityPlayableWorldAssetManifestDocument CurrentAssetManifestDocument { get ; private set ; }
2026-07-15 03:21:28 +01:00
public EveInputCapabilityDocument CurrentInputCapability { get ; private set ; }
2026-08-19 07:57:33 +02:00
public CultMeshBodyTransportKind ? CurrentAssetBodyTransportKind = > _assetGeneration . BodyTransportKind ;
2026-07-16 14:17:37 +01:00
2026-07-10 04:39:16 +01:00
public event Action < EveUnitySceneProviderSurfaceDocument > ? SurfaceDocumentAvailable ;
public event Action < EveUnityPlayableWorldAssetManifestDocument > ? AssetManifestDocumentAvailable ;
public event Action < EveUnitySceneCommandReceipt > ? CommandReceiptAvailable ;
2026-07-13 18:01:12 +01:00
public event Action < EveEntitySoaViewDocument , ICultMeshBodyReadLease > ? EntityViewAvailable ;
2026-07-12 12:33:36 +01:00
2026-07-15 17:12:11 +01:00
public event Action < EveFieldsSplatsDocument > ? FieldsSplatsAvailable ;
2026-07-13 19:47:19 +01:00
private static CultMeshBodyPublicationHandle BodyPublicationHandle ( EveEntitySoaViewDocument document )
{
if ( document = = null ) throw new ArgumentNullException ( nameof ( document ) ) ;
if ( document . Buffers = = null | | document . Buffers . Length = = 0 )
throw new InvalidOperationException ( "Entity layout does not name a primary logical buffer." ) ;
return new CultMeshBodyPublicationHandle (
document . Buffers [ 0 ] . BufferId ,
document . ProducerEpoch ,
document . Sequence ) ;
}
2026-07-10 04:39:16 +01:00
public void Connect ( )
{
2026-08-18 10:08:03 +02:00
EnsurePrepared ( ) ;
2026-07-10 04:39:16 +01:00
}
public void Disconnect ( )
{
}
public void Refresh ( )
{
2026-08-18 10:08:03 +02:00
EnsurePrepared ( ) ;
PumpLiveEvents ( ) ;
2026-07-19 06:30:37 +01:00
}
2026-08-18 10:08:03 +02:00
public async Task PrepareAsync ( CancellationToken cancellationToken = default )
2026-07-19 06:30:37 +01:00
{
if ( _bootstrapped )
return ;
2026-07-20 00:04:45 +01:00
try
{
2026-08-18 10:08:03 +02:00
EnsureOpen ( ) ;
2026-07-20 00:04:45 +01:00
var elapsed = Stopwatch . StartNew ( ) ;
2026-08-18 10:08:03 +02:00
await ResolveAdvertisementAsync ( forceRefresh : true , cancellationToken ) ;
2026-07-20 00:04:45 +01:00
TraceStartup ( "advertisement" , elapsed ) ;
2026-08-18 10:08:03 +02:00
await RefreshSurfaceAsync ( cancellationToken ) ;
2026-07-20 00:04:45 +01:00
TraceStartup ( "surface" , elapsed ) ;
2026-08-18 10:08:03 +02:00
await RefreshAssetCatalogAsync ( cancellationToken ) ;
2026-07-20 00:04:45 +01:00
TraceStartup ( "asset-catalog-and-bundles" , elapsed ) ;
2026-08-18 10:08:03 +02:00
await EnsureLiveDocumentsAsync ( cancellationToken ) ;
2026-07-20 00:04:45 +01:00
TraceStartup ( "subscriptions" , elapsed ) ;
2026-08-18 10:08:03 +02:00
_commandOutbox = new EveUnityCultMeshCommandOutbox (
SendCommandAsync ,
ContinuousCommandKey ,
ForgetPendingCommand ) ;
2026-07-20 00:04:45 +01:00
_bootstrapped = true ;
}
catch ( Exception error ) when ( error is IOException | | error is SocketException | | error is TimeoutException )
{
throw new InvalidOperationException (
2026-08-18 07:27:13 +02:00
$"CultMesh provider '{_providerId}' bootstrap through target '{_target}' failed." ,
2026-07-20 00:04:45 +01:00
error ) ;
}
2026-07-12 13:10:43 +01:00
}
2026-08-18 10:08:03 +02:00
private void EnsurePrepared ( )
{
if ( ! _bootstrapped )
throw new InvalidOperationException (
"The EveUnity CultMesh transport is not prepared. Await PrepareAsync before mounting or connecting it." ) ;
}
2026-07-19 20:34:03 +01:00
private static void TraceStartup ( string phase , Stopwatch elapsed )
{
if ( string . Equals ( Environment . GetEnvironmentVariable ( "EVEUNITY_TRACE_STARTUP_PHASES" ) , "1" , StringComparison . Ordinal ) )
Debug . Log ( $"EveUnity startup phase {phase} took {elapsed.Elapsed.TotalMilliseconds:0.###}ms." ) ;
elapsed . Restart ( ) ;
}
2026-07-15 03:21:28 +01:00
private static string FindComponentProp ( EveSurfaceComponent component , string key )
{
var value = component . GetProp ( key ) ;
if ( ! string . IsNullOrWhiteSpace ( value ) )
return value ;
foreach ( var child in component . Children )
{
value = FindComponentProp ( child , key ) ;
if ( ! string . IsNullOrWhiteSpace ( value ) )
return value ;
}
return "" ;
}
2026-07-12 13:10:43 +01:00
public void PumpLiveEvents ( )
{
while ( _liveDocuments . TryDequeue ( out var document ) )
{
2026-07-19 05:56:09 +01:00
if ( document is PendingEntityGeneration entityGeneration )
PublishEntityView ( entityGeneration . View , entityGeneration . Publication ) ;
2026-07-19 22:56:18 +01:00
else if ( document is PendingRealtimeEntityFrame realtimeFrame )
PublishPendingRealtimeEntityFrame ( realtimeFrame . BodyId ) ;
2026-07-15 17:12:11 +01:00
else if ( document is EveFieldsSplatsDocument fields )
FieldsSplatsAvailable ? . Invoke ( fields ) ;
2026-07-19 07:35:16 +01:00
else if ( document is PendingSurfaceDocument surface )
{
if ( string . Equals ( surface . RecordKey , _advertisedSurface ? . RecordRef , StringComparison . Ordinal ) )
PublishBaseSurface ( surface . Document ) ;
else
PublishEmbeddedSurface ( surface . RecordKey , surface . Document ) ;
}
2026-07-19 06:30:37 +01:00
else if ( document is EveInputCapabilityDocument inputCapability )
CurrentInputCapability = inputCapability ;
else if ( document is EveAssetCatalogDocument assetCatalog )
2026-08-19 07:31:25 +02:00
QueueAssetCatalogUpdate ( CurrentAssetSourceIdentity , assetCatalog ) ;
2026-07-12 13:10:43 +01:00
else if ( document is EveCommandReceiptDocument receipt )
PublishReceipt ( receipt ) ;
2026-07-19 09:33:59 +01:00
else if ( document is Exception error )
throw error ;
2026-07-12 13:10:43 +01:00
}
2026-07-19 04:39:33 +01:00
PumpMappedEntityFrame ( ) ;
}
2026-07-14 00:45:39 +01:00
private void QueueEntityView ( EveEntitySoaViewDocument document )
{
2026-07-19 04:39:33 +01:00
TraceHotState ( $"layout epoch={document.ProducerEpoch} sequence={document.Sequence} identities={document.Identities?.Length ?? 0}" ) ;
2026-07-19 04:07:02 +01:00
_latestEntityLayout = document ;
2026-07-19 05:56:09 +01:00
var publication = _latestEntityPublication ;
if ( publication ! = null & & PublicationMatchesLayout ( publication , document ) )
QueueEntityGeneration ( document , publication ) ;
2026-07-14 00:45:39 +01:00
}
2026-07-19 04:07:02 +01:00
private void QueueBodyPublication ( CultMeshBodyPublicationDocument publication )
{
2026-07-19 05:56:09 +01:00
_latestEntityPublication = publication ;
2026-07-19 04:07:02 +01:00
var layout = _latestEntityLayout ;
if ( layout = = null | | layout . Buffers = = null | | layout . Buffers . Length = = 0 | |
! string . Equals ( layout . Buffers [ 0 ] . BufferId , publication . BodyId , StringComparison . Ordinal ) )
2026-07-19 04:39:33 +01:00
{
TraceHotState ( $"publication skipped body={publication.BodyId} sequence={publication.Sequence} layout={(layout == null ? " missing " : " incompatible ")}" ) ;
2026-07-19 04:07:02 +01:00
return ;
2026-07-19 04:39:33 +01:00
}
TraceHotState ( $"publication body={publication.BodyId} epoch={publication.ProducerEpoch} sequence={publication.Sequence} plane={string.Join(" , ", publication.Representations.Select(value => value.TransportKind))}" ) ;
2026-07-19 04:07:02 +01:00
2026-07-19 05:56:09 +01:00
var generation = PublicationMatchesLayout ( publication , layout )
? layout
: MaterializeEntityGeneration ( layout , publication . ProducerEpoch , publication . Sequence ) ;
QueueEntityGeneration ( generation , publication ) ;
}
private void QueueEntityGeneration (
EveEntitySoaViewDocument document ,
CultMeshBodyPublicationDocument publication )
{
if ( document . ProducerEpoch < _lastQueuedEntityViewEpoch | |
( document . ProducerEpoch = = _lastQueuedEntityViewEpoch & &
document . Sequence < = _lastQueuedEntityViewSequence ) )
return ;
_lastQueuedEntityViewEpoch = document . ProducerEpoch ;
_lastQueuedEntityViewSequence = document . Sequence ;
_liveDocuments . Enqueue ( new PendingEntityGeneration ( document , publication ) ) ;
}
private static bool PublicationMatchesLayout (
CultMeshBodyPublicationDocument publication ,
EveEntitySoaViewDocument layout ) = >
publication . ProducerEpoch = = layout . ProducerEpoch & &
publication . Sequence = = layout . Sequence ;
private sealed class PendingEntityGeneration
{
public PendingEntityGeneration (
EveEntitySoaViewDocument view ,
CultMeshBodyPublicationDocument publication )
{
View = view ;
Publication = publication ;
}
public EveEntitySoaViewDocument View { get ; }
public CultMeshBodyPublicationDocument Publication { get ; }
2026-07-19 04:39:33 +01:00
}
private static EveEntitySoaViewDocument MaterializeEntityGeneration (
EveEntitySoaViewDocument layout ,
long producerEpoch ,
long sequence )
{
return new EveEntitySoaViewDocument
2026-07-19 04:07:02 +01:00
{
Schema = layout . Schema ,
ProviderId = layout . ProviderId ,
ViewId = layout . ViewId ,
PublishedAtUtc = DateTimeOffset . UtcNow . ToString ( "O" ) ,
BodySchemaId = layout . BodySchemaId ,
LayoutVersion = layout . LayoutVersion ,
2026-07-19 04:39:33 +01:00
ProducerEpoch = producerEpoch ,
Sequence = sequence ,
2026-07-19 04:07:02 +01:00
Capacity = layout . Capacity ,
Buffers = layout . Buffers ,
Columns = layout . Columns ,
DirtyRanges = ( layout . DirtyRanges ? ? Array . Empty < EveEntitySoaDirtyRange > ( ) )
. Select ( range = > new EveEntitySoaDirtyRange
{
ColumnId = range . ColumnId ,
StartIndex = range . StartIndex ,
Count = range . Count ,
2026-07-19 04:39:33 +01:00
Sequence = sequence
2026-07-19 04:07:02 +01:00
} )
. ToArray ( ) ,
RenderGroups = layout . RenderGroups ,
Identities = layout . Identities ,
2026-07-19 04:39:33 +01:00
FrameId = sequence
} ;
2026-07-19 04:07:02 +01:00
}
2026-07-10 04:39:16 +01:00
public void SubmitCommand ( EveSurfaceCommandRequest request )
{
if ( request = = null ) throw new ArgumentNullException ( nameof ( request ) ) ;
2026-08-18 10:08:03 +02:00
EnsurePrepared ( ) ;
2026-08-19 09:10:37 +02:00
EnsurePresentationWritable ( ) ;
2026-07-10 04:39:16 +01:00
var interaction = RequireWorldInteraction ( ) ;
if ( string . IsNullOrWhiteSpace ( interaction . CommandRecordRef ) )
throw new InvalidOperationException ( "The provider advertisement does not publish a command record reference." ) ;
if ( ! string . Equals ( request . ProviderId , _providerId , StringComparison . Ordinal ) | |
! string . Equals ( request . SurfaceId , _surfaceId , StringComparison . Ordinal ) )
{
throw new InvalidOperationException ( "The command does not target the connected provider surface." ) ;
}
var commandId = request . CommandId ;
if ( string . IsNullOrWhiteSpace ( commandId ) )
throw new InvalidOperationException ( "Eve command invocations require an idempotency key." ) ;
2026-08-19 04:03:00 +02:00
lock ( _pendingCommands )
{
if ( _pendingCommands . ContainsKey ( commandId ) )
throw new InvalidOperationException ( $"Eve command '{commandId}' is already pending." ) ;
_pendingCommands . Add ( commandId , request ) ;
}
2026-08-18 10:08:03 +02:00
try { _commandOutbox ! . Enqueue ( request ) ; }
2026-07-20 03:58:03 +01:00
catch
{
2026-08-18 10:08:03 +02:00
ForgetPendingCommand ( commandId ) ;
2026-07-20 03:58:03 +01:00
throw ;
}
2026-07-10 04:39:16 +01:00
}
2026-08-18 10:08:03 +02:00
private Task SendCommandAsync ( EveSurfaceCommandRequest request , CancellationToken cancellationToken )
{
2026-08-18 19:03:06 +02:00
return SendCommandWithReceiptLeaseAsync ( request , cancellationToken ) ;
}
private async Task SendCommandWithReceiptLeaseAsync (
EveSurfaceCommandRequest request ,
CancellationToken cancellationToken )
{
await EnsureReceiptSubscriptionAsync ( request . CommandId , cancellationToken ) . ConfigureAwait ( false ) ;
2026-08-18 10:08:03 +02:00
var interaction = RequireWorldInteraction ( ) ;
var recordKey = ChildRecordKey ( interaction . CommandRecordRef , request . CommandId ) ;
2026-08-18 19:03:06 +02:00
await _meshClient ! . SubmitDocumentAsync (
_target ,
recordKey ,
request ,
_runtimeId ,
"eve-unity" ,
cancellationToken )
. ConfigureAwait ( false ) ;
2026-08-18 10:08:03 +02:00
}
private string? ContinuousCommandKey ( EveSurfaceCommandRequest request )
{
if ( ! request . PayloadFields . TryGetValue ( "commandId" , out var commandId ) | |
! _continuousCommandIds . Contains ( commandId ) )
return null ;
request . PayloadFields . TryGetValue ( "entityId" , out var entityId ) ;
return commandId + "\u001f" + ( entityId ? ? "" ) ;
}
private void ForgetPendingCommand ( string commandId )
{
2026-08-18 19:03:06 +02:00
Task < ReceiptSubscription > ? subscription = null ;
2026-08-19 04:03:00 +02:00
lock ( _pendingCommands )
2026-08-18 19:03:06 +02:00
{
2026-08-19 04:03:00 +02:00
_pendingCommands . Remove ( commandId ) ;
2026-08-18 19:03:06 +02:00
if ( _receiptSubscriptions . TryGetValue ( commandId , out subscription ) )
_receiptSubscriptions . Remove ( commandId ) ;
}
if ( subscription ! = null ) DisposeReceiptSubscription ( subscription ) ;
2026-08-18 10:08:03 +02:00
}
2026-07-10 04:39:16 +01:00
public void Dispose ( )
{
2026-07-18 19:22:35 +01:00
_disposed = true ;
2026-08-18 10:08:03 +02:00
_lifetime . Cancel ( ) ;
_commandOutbox ? . Dispose ( ) ;
_commandOutbox = null ;
2026-08-19 07:57:33 +02:00
_assetGeneration . Dispose ( ) ;
2026-07-19 04:39:33 +01:00
_mappedEntityFrameCursor ? . Dispose ( ) ;
_mappedEntityFrameCursor = null ;
_mappedEntityFrameContract = null ;
2026-07-19 22:56:18 +01:00
_realtimeLifetime ? . Cancel ( ) ;
2026-08-19 09:36:55 +02:00
_surfaceAssetCandidateLifetime ? . Cancel ( ) ;
_surfaceAssetCandidateLifetime ? . Dispose ( ) ;
_surfaceAssetCandidateLifetime = null ;
2026-07-19 22:56:18 +01:00
_realtimeSession ? . Dispose ( ) ;
_realtimeSession = null ;
_realtimePump = null ;
_realtimeLifetime ? . Dispose ( ) ;
_realtimeLifetime = null ;
2026-08-17 21:02:01 +02:00
DisposeLiveDocuments ( ) ;
_contentState ? . Dispose ( ) ;
_contentState = null ;
2026-07-14 01:26:47 +01:00
_meshClient ? . Dispose ( ) ;
_meshClient = null ;
2026-07-19 07:35:16 +01:00
_baseSurface = null ;
_embeddedSurfaces . Clear ( ) ;
2026-08-19 04:03:00 +02:00
lock ( _pendingCommands )
2026-08-18 10:08:03 +02:00
{
2026-08-19 04:03:00 +02:00
_pendingCommands . Clear ( ) ;
2026-08-18 19:03:06 +02:00
foreach ( var subscription in _receiptSubscriptions . Values )
DisposeReceiptSubscription ( subscription ) ;
_receiptSubscriptions . Clear ( ) ;
2026-08-18 10:08:03 +02:00
}
2026-08-19 09:10:37 +02:00
lock ( _presentationFinalityGate )
{
_deferredTerminalReceipts . Clear ( ) ;
_presentationBarrierVersion = - 1 ;
}
2026-08-18 10:08:03 +02:00
_lifetime . Dispose ( ) ;
2026-07-18 19:22:35 +01:00
}
2026-07-10 06:00:36 +01:00
public GameObject ? ResolvePrefab ( EveUnityPlayableWorldAssetBinding asset )
{
if ( asset = = null ) throw new ArgumentNullException ( nameof ( asset ) ) ;
2026-08-18 10:08:03 +02:00
EnsureAssetPrepared ( asset . AssetRef ) ;
2026-08-19 07:57:33 +02:00
return _assetGeneration . Prefabs . TryGetValue ( asset . AssetRef , out var prefab ) ? prefab : null ;
2026-07-10 06:00:36 +01:00
}
2026-07-12 06:25:10 +01:00
public UnityEngine . Object ? ResolveAsset ( EveUnityPlayableWorldAssetBinding asset , Type assetType )
{
if ( asset = = null ) throw new ArgumentNullException ( nameof ( asset ) ) ;
if ( assetType = = null ) throw new ArgumentNullException ( nameof ( assetType ) ) ;
2026-08-18 10:08:03 +02:00
EnsureAssetPrepared ( asset . AssetRef ) ;
2026-08-19 07:57:33 +02:00
return _assetGeneration . NativeAssets . TryGetValue ( asset . AssetRef , out var value ) & & assetType . IsInstanceOfType ( value )
2026-07-12 06:25:10 +01:00
? value : null ;
}
2026-08-18 10:08:03 +02:00
private void EnsureAssetPrepared ( string assetRef )
{
EnsurePrepared ( ) ;
2026-08-19 07:57:33 +02:00
if ( _assetGeneration . AssetSelections . ContainsKey ( assetRef ) & &
! _assetGeneration . NativeAssets . ContainsKey ( assetRef ) )
2026-08-18 10:08:03 +02:00
throw new InvalidOperationException (
$"Provider asset '{assetRef}' was not materialized during asynchronous preparation." ) ;
}
2026-07-15 19:59:37 +01:00
public bool TryResolveAssetMetadata (
EveUnityPlayableWorldAssetBinding asset ,
out IReadOnlyDictionary < string , string > metadata )
{
if ( asset = = null ) throw new ArgumentNullException ( nameof ( asset ) ) ;
2026-08-19 07:57:33 +02:00
return _assetGeneration . NativeAssetMetadata . TryGetValue ( asset . AssetRef , out metadata ! ) ;
2026-07-15 19:59:37 +01:00
}
2026-07-13 21:35:11 +01:00
public bool TryGetRenderChannelLayer ( string channel , out int layer )
2026-07-12 06:25:10 +01:00
{
2026-08-19 07:57:33 +02:00
return _assetGeneration . RenderChannelLayers . TryGetValue ( channel ? ? "" , out layer ) ;
2026-07-12 06:25:10 +01:00
}
2026-07-10 04:39:16 +01:00
private void EnsureOpen ( )
{
2026-08-17 21:02:01 +02:00
if ( _meshClient ! = null )
2026-07-10 04:39:16 +01:00
return ;
2026-08-19 08:09:59 +02:00
_meshClient = CreateMeshClient ( new [ ] { _rendezvousEndpoint } , _authorityTrust ) ;
2026-08-19 07:31:25 +02:00
}
2026-08-19 08:09:59 +02:00
private CultMeshClient CreateMeshClient (
IReadOnlyList < string > rendezvousEndpoints ,
CultMeshAuthorityTrustPolicy authorityTrust )
2026-08-19 07:31:25 +02:00
{
return new CultMeshClient ( new CultMeshClientOptions
2026-07-20 00:04:45 +01:00
{
2026-08-19 07:31:25 +02:00
RendezvousEndpoints = rendezvousEndpoints ,
2026-08-18 20:14:02 +02:00
Discovery = EveUnityCultMeshConnectivity . Discovery ( ) ,
2026-08-19 08:09:59 +02:00
Sessions = new CultMeshSessionManagerOptions
{
Trust = authorityTrust ? ? throw new ArgumentNullException ( nameof ( authorityTrust ) )
} ,
2026-08-18 20:14:02 +02:00
Connectors = EveUnityCultMeshConnectivity . SchemaConnectors ( ) ,
ContentConnectors = EveUnityCultMeshConnectivity . ContentConnectors ( ) ,
2026-07-20 00:04:45 +01:00
RealtimeConnectors = new ICultMeshRealtimeTransportConnector [ ]
{
new CultMeshNativeQuicRealtimeTransportConnector ( )
}
} ) ;
}
2026-08-19 07:57:33 +02:00
private CultMeshClient AssetMeshClient ( AssetGeneration ? generation = null ) = >
( generation ? ? _assetGeneration ) . MeshClient ? ?
2026-08-19 07:31:25 +02:00
_meshClient ? ? throw new InvalidOperationException ( "The CultMesh client is not open." ) ;
2026-08-18 10:08:03 +02:00
private async Task ResolveAdvertisementAsync (
bool forceRefresh = false ,
CancellationToken cancellationToken = default )
2026-07-10 04:39:16 +01:00
{
2026-07-13 23:12:03 +01:00
if ( ! forceRefresh & & _advertisement ! = null & & _advertisedSurface ! = null )
return ;
2026-08-18 10:08:03 +02:00
using var lease = await _meshClient !
. LeaseCollectionAsync < EveProviderAdvertisementDocument > ( _target , cancellationToken ) ;
var documents = await lease . Handle . LatestAsync ( ) ;
_advertisement = documents . FirstOrDefault ( document = >
2026-07-10 04:39:16 +01:00
string . Equals ( document . ProviderId , _providerId , StringComparison . Ordinal ) )
? ? throw new InvalidOperationException ( $"Provider '{_providerId}' did not publish an Eve advertisement." ) ;
_advertisedSurface = _advertisement . Surfaces . FirstOrDefault ( surface = >
string . Equals ( surface . SurfaceId , _surfaceId , StringComparison . Ordinal ) )
? ? throw new InvalidOperationException ( $"Provider '{_providerId}' did not advertise surface '{_surfaceId}'." ) ;
if ( ! string . Equals ( _advertisedSurface . Transport , "cultmesh-record" , StringComparison . Ordinal ) )
throw new InvalidOperationException ( "EveUnity CultMesh transport requires a cultmesh-record surface advertisement." ) ;
if ( string . IsNullOrWhiteSpace ( _advertisedSurface . RecordRef ) )
throw new InvalidOperationException ( "The provider surface advertisement does not publish a record reference." ) ;
}
2026-07-13 18:01:12 +01:00
private CultMeshBodyPublicationResolver CreateBodyResolver ( )
{
2026-07-13 22:31:56 +01:00
var producerIds = RequireAdvertisedBodyProducerIds ( _advertisement ) ;
2026-07-19 13:57:56 +01:00
if ( string . IsNullOrWhiteSpace ( _advertisement ! . ServiceId ) )
throw new InvalidOperationException (
$"Eve provider '{_advertisement.ProviderId}' has no service-instance identity for body transport." ) ;
2026-08-17 21:02:01 +02:00
var mappedRoot = _cachePath ;
2026-07-19 13:57:56 +01:00
var networkBodies = _meshClient ! . BodyProvider (
_advertisement . ProviderId ,
2026-08-18 07:27:13 +02:00
_target ,
2026-07-19 13:57:56 +01:00
new CultMeshSessionBodyProviderOptions { ResponseTimeout = TimeSpan . FromSeconds ( 2 ) } ) ;
2026-07-13 18:01:12 +01:00
return new CultMeshBodyPublicationResolver ( new CultMeshBodyTransportService (
new ICultMeshBodyTransportAdapter [ ]
{
new CultMeshSharedMemoryBodyAdapter ( ) ,
new CultMeshMappedBodyAdapter ( mappedRoot ) ,
2026-07-19 13:57:56 +01:00
new CultMeshNetworkBodyAdapter ( networkBodies )
2026-07-13 18:01:12 +01:00
} ,
2026-07-13 22:31:56 +01:00
( candidateProducerId , _ ) = > IsAdvertisedBodyProducer ( producerIds , candidateProducerId ) ) ) ;
2026-07-13 22:21:47 +01:00
}
2026-07-13 22:31:56 +01:00
private static bool IsAdvertisedBodyProducer (
IReadOnlyList < string > advertisedProducerIds ,
string candidateProducerId ) = >
advertisedProducerIds . Any ( producerId = >
string . Equals ( candidateProducerId , producerId , StringComparison . Ordinal ) ) ;
2026-07-13 22:21:47 +01:00
2026-07-13 22:31:56 +01:00
private static IReadOnlyList < string > RequireAdvertisedBodyProducerIds ( EveProviderAdvertisementDocument ? advertisement )
2026-07-13 22:21:47 +01:00
{
if ( advertisement = = null )
throw new InvalidOperationException ( "The Eve provider advertisement must be resolved before body transport authorization." ) ;
2026-07-13 22:31:56 +01:00
var producerIds = advertisement . AuthorizedBodyProducerIds
. Where ( producerId = > ! string . IsNullOrWhiteSpace ( producerId ) )
. Distinct ( StringComparer . Ordinal )
. ToArray ( ) ;
if ( producerIds . Length = = 0 )
2026-07-13 22:21:47 +01:00
throw new InvalidOperationException (
2026-07-13 22:31:56 +01:00
$"Eve provider '{advertisement.ProviderId}' does not advertise an authorized body producer." ) ;
return producerIds ;
2026-07-13 18:01:12 +01:00
}
2026-07-14 01:26:47 +01:00
private static string NormalizeContentHash ( string value )
{
if ( string . IsNullOrWhiteSpace ( value ) )
throw new InvalidDataException ( "CultMesh content hash is missing." ) ;
var normalized = value . StartsWith ( "sha256:" , StringComparison . OrdinalIgnoreCase )
? value . Substring ( "sha256:" . Length )
: value ;
return normalized . ToLowerInvariant ( ) ;
2026-07-13 20:27:00 +01:00
}
2026-07-19 05:56:09 +01:00
private void PublishEntityView (
EveEntitySoaViewDocument document ,
CultMeshBodyPublicationDocument publication )
2026-07-13 18:01:12 +01:00
{
2026-08-18 10:08:03 +02:00
EnsurePrepared ( ) ;
2026-07-13 18:01:12 +01:00
if ( ! string . Equals ( document . ProviderId , _advertisement ! . ProviderId , StringComparison . Ordinal ) )
2026-07-13 22:06:27 +01:00
throw new UnauthorizedAccessException (
$"Entity layout provider '{document.ProviderId}' does not match advertised Eve provider '{_advertisement.ProviderId}'." ) ;
2026-07-13 18:01:12 +01:00
if ( document . Buffers = = null | | document . Buffers . Length = = 0 )
throw new InvalidOperationException ( "Entity layout does not name a primary logical buffer." ) ;
2026-07-13 19:47:19 +01:00
var handle = BodyPublicationHandle ( document ) ;
handle . Validate ( publication ) ;
2026-07-13 20:14:53 +01:00
var now = DateTimeOffset . UtcNow ;
if ( ! IsPublicationLive ( publication , now ) )
return ;
2026-07-19 04:39:33 +01:00
EnsureMappedEntityFrameCursor ( publication ) ;
2026-07-19 05:56:09 +01:00
if ( _mappedEntityFrameCursor ! = null )
return ;
2026-07-19 22:56:18 +01:00
EnsureRealtimeEntityState ( ) ;
2026-07-13 18:01:12 +01:00
}
2026-07-19 04:39:33 +01:00
private void EnsureMappedEntityFrameCursor ( CultMeshBodyPublicationDocument publication )
{
var descriptor = ( publication . Representations ? ? Array . Empty < CultMeshBodyDescriptor > ( ) )
. FirstOrDefault ( CultMeshMappedFrameBodyCursor . CanOpen ) ;
if ( descriptor = = null )
{
_mappedEntityFrameCursor ? . Dispose ( ) ;
_mappedEntityFrameCursor = null ;
_mappedEntityFrameContract = null ;
return ;
}
var current = _mappedEntityFrameContract ;
if ( current ! = null & &
string . Equals ( FrameCapabilityIdentity ( current . CapabilityToken ) ,
FrameCapabilityIdentity ( descriptor . CapabilityToken ) , StringComparison . Ordinal ) & &
string . Equals ( current . BodyId , descriptor . BodyId , StringComparison . Ordinal ) & &
string . Equals ( current . SchemaId , descriptor . SchemaId , StringComparison . Ordinal ) & &
current . LayoutVersion = = descriptor . LayoutVersion & &
current . Capacity = = descriptor . Capacity & &
current . ProducerEpoch = = descriptor . ProducerEpoch & &
current . ByteSize = = descriptor . ByteSize )
return ;
_mappedEntityFrameCursor ? . Dispose ( ) ;
2026-07-19 22:56:18 +01:00
try
{
_mappedEntityFrameCursor = new CultMeshMappedFrameBodyCursor ( descriptor ) ;
_mappedEntityFrameContract = descriptor ;
TraceHotState (
$"mapped frame cursor body={descriptor.BodyId} epoch={descriptor.ProducerEpoch} sequence={descriptor.Sequence}" ) ;
}
catch ( Exception error ) when (
error is IOException | |
error is UnauthorizedAccessException | |
error is InvalidOperationException )
{
_mappedEntityFrameCursor = null ;
_mappedEntityFrameContract = null ;
TraceHotState ( $"mapped frame unavailable; selecting remote realtime plane: {error.Message}" ) ;
}
}
private void EnsureRealtimeEntityState ( )
{
if ( _realtimePump ! = null )
return ;
if ( _advertisement = = null | | string . IsNullOrWhiteSpace ( _advertisement . VerseId ) )
throw new InvalidOperationException (
$"Eve provider '{_providerId}' does not advertise the Verse identity required for realtime state." ) ;
_realtimeLifetime = new CancellationTokenSource ( ) ;
2026-08-18 07:27:13 +02:00
if ( ! string . Equals ( _advertisement . VerseId , _target . VerseId , StringComparison . Ordinal ) )
throw new InvalidOperationException (
$"Eve provider '{_providerId}' advertisement Verse '{_advertisement.VerseId}' does not match selected Verse '{_target.VerseId}'." ) ;
_realtimePump = Task . Run ( ( ) = > PumpRealtimeEntityStateAsync ( _realtimeLifetime . Token ) ) ;
2026-07-19 22:56:18 +01:00
}
2026-08-18 07:27:13 +02:00
private async Task PumpRealtimeEntityStateAsync ( CancellationToken cancellationToken )
2026-07-19 22:56:18 +01:00
{
try
{
_realtimeSession = await _meshClient !
2026-08-18 07:27:13 +02:00
. ConnectRealtimeAsync ( _target , cancellationToken )
2026-07-19 22:56:18 +01:00
. ConfigureAwait ( false ) ;
2026-08-18 07:27:13 +02:00
TraceHotState ( $"realtime state connected transport={_realtimeSession.TransportId} target={_target}" ) ;
2026-07-19 22:56:18 +01:00
while ( ! cancellationToken . IsCancellationRequested )
{
var frame = await _realtimeSession . ReceiveAsync ( cancellationToken ) . ConfigureAwait ( false ) ;
EnqueueRealtimeEntityFrame ( frame ) ;
}
}
catch ( OperationCanceledException ) when ( cancellationToken . IsCancellationRequested )
{
}
catch ( ObjectDisposedException ) when ( _disposed )
{
}
catch ( Exception error )
{
_liveDocuments . Enqueue ( error ) ;
}
}
private void EnqueueRealtimeEntityFrame ( CultMeshRealtimeFrame frame )
{
if ( frame = = null )
throw new ArgumentNullException ( nameof ( frame ) ) ;
lock ( _realtimeFrameGate )
{
if ( _latestRealtimeFrames . TryGetValue ( frame . BodyId , out var current ) & &
( frame . ProducerEpoch < current . ProducerEpoch | |
( frame . ProducerEpoch = = current . ProducerEpoch & & frame . Sequence < = current . Sequence ) ) )
return ;
_latestRealtimeFrames [ frame . BodyId ] = frame ;
if ( _queuedRealtimeFrameBodies . Add ( frame . BodyId ) )
_liveDocuments . Enqueue ( new PendingRealtimeEntityFrame ( frame . BodyId ) ) ;
}
}
private void PublishPendingRealtimeEntityFrame ( string bodyId )
{
CultMeshRealtimeFrame ? frame ;
lock ( _realtimeFrameGate )
{
_queuedRealtimeFrameBodies . Remove ( bodyId ) ;
if ( ! _latestRealtimeFrames . TryGetValue ( bodyId , out frame ) )
return ;
_latestRealtimeFrames . Remove ( bodyId ) ;
}
PublishRealtimeEntityFrame ( frame ) ;
}
private void PublishRealtimeEntityFrame ( CultMeshRealtimeFrame frame )
{
var layout = _latestEntityLayout
? ? throw new InvalidOperationException ( "Realtime entity state arrived before its Eve SoA layout." ) ;
var publication = _latestEntityPublication
? ? throw new InvalidOperationException ( "Realtime entity state arrived before its body publication." ) ;
if ( ! string . Equals ( frame . BodyId , publication . BodyId , StringComparison . Ordinal ) | |
! string . Equals ( frame . SchemaId , layout . BodySchemaId , StringComparison . Ordinal ) )
throw new UnauthorizedAccessException ( "Realtime entity state does not match the advertised Eve body contract." ) ;
if ( frame . Delivery ! = CultMeshRealtimeDelivery . LatestOnly )
throw new InvalidDataException ( "Playable entity state requires latest-only QUIC delivery." ) ;
if ( frame . ProducerEpoch < _lastPresentedEntityViewEpoch | |
( frame . ProducerEpoch = = _lastPresentedEntityViewEpoch & &
frame . Sequence < = _lastPresentedEntityViewSequence ) )
return ;
var representation = ( publication . Representations ? ? Array . Empty < CultMeshBodyDescriptor > ( ) )
. FirstOrDefault ( value = >
string . Equals ( value . BodyId , frame . BodyId , StringComparison . Ordinal ) & &
string . Equals ( value . SchemaId , frame . SchemaId , StringComparison . Ordinal ) )
? ? throw new InvalidDataException ( "Realtime entity state has no advertised body representation." ) ;
if ( frame . Payload . Length ! = representation . ByteSize )
throw new InvalidDataException (
$"Realtime entity body size {frame.Payload.Length} does not match advertised size {representation.ByteSize}." ) ;
var generation = MaterializeEntityGeneration ( layout , frame . ProducerEpoch , frame . Sequence ) ;
var lease = new RealtimeEntityBodyLease (
new CultMeshBodyDescriptor
{
BodyId = frame . BodyId ,
SchemaId = frame . SchemaId ,
LayoutVersion = layout . LayoutVersion ,
ByteSize = frame . Payload . Length ,
Capacity = layout . Capacity ,
ProducerEpoch = frame . ProducerEpoch ,
Sequence = frame . Sequence ,
AccessMode = CultMeshBodyAccessMode . ReadOnly ,
Synchronization = CultMeshBodySynchronization . EpochSequence ,
LeaseExpiresAtUnixMs = DateTimeOffset . UtcNow . AddSeconds ( 2 ) . ToUnixTimeMilliseconds ( ) ,
TransportKind = CultMeshBodyTransportKind . Network ,
CapabilityToken = "authenticated-quic" ,
SemanticHash = ""
} ,
frame . Payload . ToArray ( ) ) ;
var handler = EntityViewAvailable ;
if ( handler = = null )
{
lease . Dispose ( ) ;
return ;
}
try
{
handler ( generation , lease ) ;
_lastPresentedEntityViewEpoch = frame . ProducerEpoch ;
_lastPresentedEntityViewSequence = frame . Sequence ;
}
catch
{
lease . Dispose ( ) ;
throw ;
}
}
private sealed class PendingRealtimeEntityFrame
{
public PendingRealtimeEntityFrame ( string bodyId ) = >
BodyId = string . IsNullOrWhiteSpace ( bodyId )
? throw new ArgumentException ( "Body id must be non-empty." , nameof ( bodyId ) )
: bodyId ;
public string BodyId { get ; }
}
private sealed class RealtimeEntityBodyLease : ICultMeshBodyReadLease
{
private byte [ ] _bytes ;
public RealtimeEntityBodyLease ( CultMeshBodyDescriptor descriptor , byte [ ] bytes )
{
Descriptor = descriptor ;
_bytes = bytes ;
}
public CultMeshBodyDescriptor Descriptor { get ; }
public CultMeshBodyTransportKind TransportKind = > CultMeshBodyTransportKind . Network ;
public byte ReadByte ( long offset ) { Validate ( offset , 1 ) ; return _bytes [ ( int ) offset ] ; }
public int ReadInt32 ( long offset ) { Validate ( offset , 4 ) ; return BitConverter . ToInt32 ( _bytes , ( int ) offset ) ; }
public long ReadInt64 ( long offset ) { Validate ( offset , 8 ) ; return BitConverter . ToInt64 ( _bytes , ( int ) offset ) ; }
public float ReadSingle ( long offset ) { Validate ( offset , 4 ) ; return BitConverter . ToSingle ( _bytes , ( int ) offset ) ; }
public double ReadDouble ( long offset ) { Validate ( offset , 8 ) ; return BitConverter . ToDouble ( _bytes , ( int ) offset ) ; }
public int CopyTo ( long offset , byte [ ] destination , int destinationOffset , int count )
{
Validate ( offset , count ) ;
Buffer . BlockCopy ( _bytes , ( int ) offset , destination , destinationOffset , count ) ;
return count ;
}
public void Dispose ( ) = > _bytes = Array . Empty < byte > ( ) ;
private void Validate ( long offset , int count )
{
if ( offset < 0 | | count < 0 | | offset > _bytes . LongLength - count )
throw new ArgumentOutOfRangeException ( nameof ( offset ) ) ;
}
2026-07-19 04:39:33 +01:00
}
private void PumpMappedEntityFrame ( )
{
var cursor = _mappedEntityFrameCursor ;
var layout = _latestEntityLayout ;
if ( cursor = = null | | layout = = null | | ! cursor . TryAcquireLatest ( out var lease ) )
return ;
var descriptor = lease . Descriptor ;
2026-07-19 05:56:09 +01:00
if ( descriptor . ProducerEpoch < _lastPresentedEntityViewEpoch | |
( descriptor . ProducerEpoch = = _lastPresentedEntityViewEpoch & &
descriptor . Sequence < = _lastPresentedEntityViewSequence ) )
2026-07-19 04:39:33 +01:00
{
lease . Dispose ( ) ;
return ;
}
var generation = MaterializeEntityGeneration (
layout ,
descriptor . ProducerEpoch ,
descriptor . Sequence ) ;
var handler = EntityViewAvailable ;
if ( handler = = null )
{
lease . Dispose ( ) ;
return ;
}
try
{
handler ( generation , lease ) ;
2026-07-19 05:56:09 +01:00
_lastPresentedEntityViewEpoch = descriptor . ProducerEpoch ;
_lastPresentedEntityViewSequence = descriptor . Sequence ;
2026-07-19 04:39:33 +01:00
}
catch
{
lease . Dispose ( ) ;
throw ;
}
}
private static string FrameCapabilityIdentity ( string capabilityToken )
{
var separator = capabilityToken . LastIndexOf ( '.' ) ;
return separator > 0 ? capabilityToken . Substring ( 0 , separator ) : capabilityToken ;
}
2026-07-13 20:14:53 +01:00
private static bool IsPublicationLive (
CultMeshBodyPublicationDocument publication ,
DateTimeOffset now ) = >
publication . LivenessExpiresAtUnixMs > now . ToUnixTimeMilliseconds ( ) ;
2026-08-18 10:08:03 +02:00
private async Task RefreshSurfaceAsync ( CancellationToken cancellationToken )
2026-07-10 04:39:16 +01:00
{
2026-08-18 10:08:03 +02:00
var surface = await _meshClient !
. ReadAsync < EveSurfaceDocument > ( _target , _advertisedSurface ! . RecordRef , cancellationToken ) ;
2026-07-19 07:35:16 +01:00
PublishBaseSurface ( surface ) ;
2026-07-12 13:10:43 +01:00
}
2026-07-19 07:35:16 +01:00
private void PublishBaseSurface ( EveSurfaceDocument surface )
2026-07-12 13:10:43 +01:00
{
2026-08-19 07:31:25 +02:00
if ( surface = = null ) throw new ArgumentNullException ( nameof ( surface ) ) ;
2026-08-19 09:56:36 +02:00
if ( ! TryBeginBaseSurfaceCandidate ( surface . Version , out var generation ) )
2026-08-19 09:19:04 +02:00
return ;
2026-08-19 09:36:55 +02:00
CancellationToken candidateToken ;
lock ( _presentationFinalityGate )
{
_surfaceAssetCandidateLifetime ? . Cancel ( ) ;
_surfaceAssetCandidateLifetime ? . Dispose ( ) ;
_surfaceAssetCandidateLifetime = CancellationTokenSource . CreateLinkedTokenSource ( _lifetime . Token ) ;
candidateToken = _surfaceAssetCandidateLifetime . Token ;
}
2026-08-19 07:31:25 +02:00
if ( ! _bootstrapped )
{
_baseSurface = surface ;
2026-08-19 09:19:04 +02:00
PublishComposedSurface ( surface . Version ) ;
2026-08-19 07:31:25 +02:00
return ;
}
var source = ResolveAssetSource ( surface ) ;
2026-08-19 09:36:55 +02:00
if ( string . Equals ( source . Identity , CurrentAssetSourceIdentity , StringComparison . Ordinal ) & &
( source . RequiredCatalogVersion < = 0 | | source . RequiredCatalogVersion = = CurrentAssetCatalogVersion ) )
2026-08-19 07:31:25 +02:00
{
_baseSurface = surface ;
2026-08-19 09:19:04 +02:00
PublishComposedSurface ( surface . Version ) ;
2026-08-19 07:31:25 +02:00
return ;
}
// A surface and its provider-qualified asset catalog are one presentation
// candidate. Keep the previous surface mounted until the candidate assets
// have resolved and preloaded; never lower a remote Verse surface against
// the previous Verse's catalog merely because the surface record arrived first.
2026-08-19 09:10:37 +02:00
BeginPresentationTransition ( surface . Version ) ;
2026-08-19 09:36:55 +02:00
_ = RefreshAssetsForSurfaceAsync ( surface , source , generation , candidateToken ) ;
}
2026-08-19 09:56:36 +02:00
private bool TryBeginBaseSurfaceCandidate ( long version , out long generation )
2026-08-19 09:36:55 +02:00
{
lock ( _presentationFinalityGate )
{
2026-08-19 09:56:36 +02:00
generation = - 1 ;
if ( version < _highestObservedBaseSurfaceVersion | |
version < = _mountedBaseSurfaceVersion | |
( version = = _highestObservedBaseSurfaceVersion & &
_activeBaseSurfaceCandidateVersion = = version ) )
2026-08-19 09:36:55 +02:00
return false ;
2026-08-19 09:56:36 +02:00
_highestObservedBaseSurfaceVersion = Math . Max ( _highestObservedBaseSurfaceVersion , version ) ;
generation = Interlocked . Increment ( ref _surfaceAssetGeneration ) ;
_activeBaseSurfaceCandidateVersion = version ;
_activeBaseSurfaceCandidateGeneration = generation ;
2026-08-19 09:36:55 +02:00
return true ;
}
2026-07-19 07:35:16 +01:00
}
2026-08-19 09:56:36 +02:00
private void RetireFailedBaseSurfaceCandidate ( long version , long generation )
{
lock ( _presentationFinalityGate )
{
if ( _activeBaseSurfaceCandidateVersion ! = version | |
_activeBaseSurfaceCandidateGeneration ! = generation )
return ;
_activeBaseSurfaceCandidateVersion = - 1 ;
_activeBaseSurfaceCandidateGeneration = - 1 ;
}
}
2026-07-19 07:35:16 +01:00
private void PublishEmbeddedSurface ( string recordKey , EveSurfaceDocument surface )
{
if ( string . IsNullOrWhiteSpace ( recordKey ) )
throw new InvalidOperationException ( "An embedded Eve surface update has no record identity." ) ;
_embeddedSurfaces [ recordKey ] = surface ? ? throw new ArgumentNullException ( nameof ( surface ) ) ;
PublishComposedSurface ( ) ;
}
2026-08-19 09:19:04 +02:00
private void PublishComposedSurface ( long? committedBaseVersion = null )
2026-07-19 07:35:16 +01:00
{
2026-08-19 07:57:33 +02:00
ApplyPreparedSurface ( PrepareComposedSurface (
2026-08-19 09:19:04 +02:00
_baseSurface ? ? throw new InvalidOperationException ( "The base Eve surface is unavailable." ) ) ,
committedBaseVersion ) ;
2026-08-19 07:57:33 +02:00
}
private PreparedSurface PrepareComposedSurface ( EveSurfaceDocument baseSurface )
{
var surface = ComposeSurface ( baseSurface , _embeddedSurfaces ) ;
2026-07-10 04:39:16 +01:00
var interaction = RequireWorldInteraction ( ) ;
2026-08-19 07:57:33 +02:00
var document = new EveUnitySceneProviderSurfaceDocument (
2026-07-10 04:39:16 +01:00
surface ,
new EveUnitySceneProviderSurfaceAdvertisement (
_advertisedSurface . SurfaceId ,
_advertisedSurface . SurfaceKind ,
new EveUnitySceneWorldInteraction (
interaction . ProjectionKind ,
interaction . CommandBoundary ,
interaction . ReceiptSchema ,
interaction . Ownership ) ) ,
_advertisedSurface . RecordRef ,
surface . Version ) ;
2026-08-18 10:08:03 +02:00
var lowered = new EveUnitySceneSurfaceLowerer ( )
2026-08-19 07:57:33 +02:00
. Lower ( document . SurfaceDocument , document . AdvertisedSurface ) ;
var continuousCommands = new HashSet < string > ( StringComparer . Ordinal ) ;
2026-08-18 10:08:03 +02:00
if ( ! string . IsNullOrWhiteSpace ( lowered . PlayableWorld ? . MovementCommand ) )
2026-08-19 07:57:33 +02:00
continuousCommands . Add ( lowered . PlayableWorld . MovementCommand ) ;
2026-08-18 10:08:03 +02:00
if ( ! string . IsNullOrWhiteSpace ( lowered . PlayableWorld ? . LookCommand ) )
2026-08-19 07:57:33 +02:00
continuousCommands . Add ( lowered . PlayableWorld . LookCommand ) ;
return new PreparedSurface ( document , continuousCommands ) ;
}
2026-08-19 09:19:04 +02:00
private void ApplyPreparedSurface ( PreparedSurface prepared , long? committedBaseVersion = null )
2026-08-19 07:57:33 +02:00
{
CurrentSurfaceDocument = prepared . Document ;
_continuousCommandIds . Clear ( ) ;
foreach ( var command in prepared . ContinuousCommands )
_continuousCommandIds . Add ( command ) ;
2026-07-10 04:39:16 +01:00
SurfaceDocumentAvailable ? . Invoke ( CurrentSurfaceDocument ) ;
2026-08-19 09:19:04 +02:00
if ( committedBaseVersion . HasValue )
CompletePresentationTransition ( committedBaseVersion . Value ) ;
2026-07-19 07:35:16 +01:00
}
internal static EveSurfaceDocument ComposeSurface (
EveSurfaceDocument surface ,
IReadOnlyDictionary < string , EveSurfaceDocument > embeddedSurfaces )
{
var root = ComposeComponent ( surface . Surface . Root , embeddedSurfaces ) ;
var version = embeddedSurfaces . Values . Select ( value = > value . Version )
. DefaultIfEmpty ( surface . Version )
. Append ( surface . Version )
. Max ( ) ;
return new EveSurfaceDocument (
surface . Type ,
surface . Schema ,
surface . ProviderId ,
surface . ProviderKind ,
surface . Title ,
version ,
surface . UpdatedAtUtc ,
new EveSurfaceTree ( surface . Surface . Id , root , surface . Surface . Styles ) ,
surface . Commands ) ;
}
private static EveSurfaceComponent ComposeComponent (
EveSurfaceComponent component ,
IReadOnlyDictionary < string , EveSurfaceDocument > embeddedSurfaces )
{
var children = component . Children . Select ( child = > ComposeComponent ( child , embeddedSurfaces ) ) . ToList ( ) ;
foreach ( var slot in component . EmbeddedDocuments ? ? Array . Empty < EveEmbeddedDocumentSlot > ( ) )
{
if ( ! string . Equals ( slot . SchemaId , EveSurfaceDocument . SchemaId , StringComparison . Ordinal ) | |
! embeddedSurfaces . TryGetValue ( slot . DocumentId , out var embedded ) )
continue ;
children . Add ( ComposeComponent ( embedded . Surface . Root , embeddedSurfaces ) ) ;
}
return new EveSurfaceComponent (
component . Id ,
component . Kind ,
component . Props ,
children ,
component . StateBindingRecords ,
component . EmbeddedDocuments ,
component . Layout ,
component . Style ) ;
2026-07-12 12:33:36 +01:00
}
2026-08-18 10:08:03 +02:00
private async Task EnsureLiveDocumentsAsync ( CancellationToken cancellationToken )
2026-07-12 12:33:36 +01:00
{
2026-08-17 21:02:01 +02:00
if ( _liveDocumentsReady ) return ;
DisposeLiveDocuments ( ) ;
2026-07-19 00:02:51 +01:00
try
2026-07-12 12:33:36 +01:00
{
2026-08-18 10:08:03 +02:00
await OpenLiveDocumentsAsync ( cancellationToken ) ;
2026-08-17 21:02:01 +02:00
_liveDocumentsReady = true ;
2026-07-19 00:02:51 +01:00
}
catch
{
2026-08-17 21:02:01 +02:00
DisposeLiveDocuments ( ) ;
2026-07-19 00:02:51 +01:00
throw ;
2026-07-12 12:33:36 +01:00
}
2026-08-17 21:02:01 +02:00
}
2026-07-19 00:02:51 +01:00
2026-08-18 10:08:03 +02:00
private async Task OpenLiveDocumentsAsync ( CancellationToken cancellationToken )
2026-08-17 21:02:01 +02:00
{
2026-07-12 12:33:36 +01:00
var lowered = new EveUnitySceneSurfaceLowerer ( )
. Lower ( CurrentSurfaceDocument . SurfaceDocument , CurrentSurfaceDocument . AdvertisedSurface ) ;
string entityViewPointer = lowered . PlayableWorld = = null
? ""
: lowered . PlayableWorld . EntityViewPointerId ;
2026-07-19 03:18:35 +01:00
string entityBodyId = lowered . PlayableWorld = = null
? ""
: lowered . PlayableWorld . EntityBodyId ;
2026-07-19 03:28:22 +01:00
var fieldRefs = lowered . PlayableWorld = = null
? Array . Empty < string > ( )
: lowered . PlayableWorld . FieldVolumes
. Select ( field = > field . DocumentRef )
. Where ( value = > ! string . IsNullOrWhiteSpace ( value ) )
. Distinct ( StringComparer . Ordinal )
. ToArray ( ) ;
2026-07-12 12:33:36 +01:00
if ( ! string . IsNullOrWhiteSpace ( entityViewPointer ) )
{
2026-07-19 03:18:35 +01:00
if ( string . IsNullOrWhiteSpace ( entityBodyId ) )
throw new InvalidOperationException (
"The playable world advertises an entity-view pointer without its logical body id." ) ;
2026-07-19 06:09:15 +01:00
_bodyResolver ? ? = CreateBodyResolver ( ) ;
2026-08-18 10:08:03 +02:00
await LeaseDocumentAsync < EveEntitySoaViewDocument > ( entityViewPointer , QueueEntityView , cancellationToken ) ;
await LeaseCollectionAsync < CultMeshBodyPublicationDocument > ( publication = >
2026-07-19 03:28:22 +01:00
{
2026-08-17 21:02:01 +02:00
if ( string . Equals ( publication . BodyId , entityBodyId , StringComparison . Ordinal ) )
QueueBodyPublication ( publication ) ;
2026-08-18 10:08:03 +02:00
} , cancellationToken ) ;
2026-07-19 05:56:09 +01:00
}
2026-08-17 21:02:01 +02:00
foreach ( var fieldRef in fieldRefs )
2026-08-18 10:08:03 +02:00
await LeaseDocumentAsync < EveFieldsSplatsDocument > (
fieldRef ,
fields = > _liveDocuments . Enqueue ( fields ) ,
cancellationToken ) ;
2026-08-17 21:02:01 +02:00
2026-08-18 10:08:03 +02:00
await LeaseDocumentAsync < EveSurfaceDocument > (
2026-08-17 21:02:01 +02:00
_advertisedSurface ! . RecordRef ,
surface = > _liveDocuments . Enqueue ( new PendingSurfaceDocument ( _advertisedSurface . RecordRef , surface ) ) ,
2026-08-18 10:08:03 +02:00
cancellationToken ,
2026-08-17 21:02:01 +02:00
publishInitial : false ) ;
2026-07-19 07:35:16 +01:00
var embeddedSlots = EnumerateEmbeddedDocuments ( CurrentSurfaceDocument . SurfaceDocument . Surface . Root )
. Where ( slot = > string . Equals ( slot . SchemaId , EveSurfaceDocument . SchemaId , StringComparison . Ordinal ) )
. Where ( slot = > ! string . IsNullOrWhiteSpace ( slot . DocumentId ) )
. GroupBy ( slot = > slot . DocumentId , StringComparer . Ordinal )
. Select ( group = > group . First ( ) )
. ToArray ( ) ;
2026-08-17 21:02:01 +02:00
foreach ( var slot in embeddedSlots )
2026-07-19 07:35:16 +01:00
{
2026-08-18 10:08:03 +02:00
await LeaseDocumentAsync < EveSurfaceDocument > (
2026-08-17 21:02:01 +02:00
slot . DocumentId ,
2026-08-18 10:08:03 +02:00
surface = > _liveDocuments . Enqueue ( new PendingSurfaceDocument ( slot . DocumentId , surface ) ) ,
cancellationToken ) ;
2026-07-19 07:35:16 +01:00
}
2026-07-19 06:30:37 +01:00
var inputCapabilityRef = FindComponentProp (
CurrentSurfaceDocument . SurfaceDocument . Surface . Root ,
"inputCapability" ) ;
if ( ! string . IsNullOrWhiteSpace ( inputCapabilityRef ) )
{
2026-08-18 10:08:03 +02:00
await LeaseDocumentAsync < EveInputCapabilityDocument > (
2026-08-17 21:02:01 +02:00
inputCapabilityRef ,
2026-08-18 10:08:03 +02:00
document = > _liveDocuments . Enqueue ( document ) ,
cancellationToken ) ;
2026-07-19 06:30:37 +01:00
}
2026-08-18 19:03:06 +02:00
var interaction = RequireWorldInteraction ( ) ;
if ( ! string . Equals ( interaction . ReceiptSchema , EveCommandReceiptDocument . SchemaId , StringComparison . Ordinal ) )
throw new InvalidOperationException (
$"The provider advertises receipt schema '{interaction.ReceiptSchema}', expected '{EveCommandReceiptDocument.SchemaId}'." ) ;
if ( string . IsNullOrWhiteSpace ( interaction . ReceiptRecordRef ) )
throw new InvalidOperationException ( "The provider advertisement does not publish a receipt record reference." ) ;
}
private Task < ReceiptSubscription > EnsureReceiptSubscriptionAsync (
string commandId ,
CancellationToken cancellationToken )
{
Task < ReceiptSubscription > subscription ;
2026-08-19 04:03:00 +02:00
lock ( _pendingCommands )
2026-08-18 19:03:06 +02:00
{
if ( _receiptSubscriptions . TryGetValue ( commandId , out subscription ! ) ) return subscription ;
subscription = OpenReceiptSubscriptionAsync ( commandId , cancellationToken ) ;
_receiptSubscriptions . Add ( commandId , subscription ) ;
}
return RemoveFailedReceiptSubscriptionAsync ( commandId , subscription ) ;
}
private async Task < ReceiptSubscription > RemoveFailedReceiptSubscriptionAsync (
string commandId ,
Task < ReceiptSubscription > subscription )
{
try { return await subscription . ConfigureAwait ( false ) ; }
catch
{
2026-08-19 04:03:00 +02:00
lock ( _pendingCommands )
2026-08-18 19:03:06 +02:00
{
if ( _receiptSubscriptions . TryGetValue ( commandId , out var current ) & &
ReferenceEquals ( current , subscription ) )
_receiptSubscriptions . Remove ( commandId ) ;
}
throw ;
}
}
private async Task < ReceiptSubscription > OpenReceiptSubscriptionAsync (
string commandId ,
CancellationToken cancellationToken )
{
var recordKey = ChildRecordKey ( RequireWorldInteraction ( ) . ReceiptRecordRef , commandId ) ;
var lease = await _meshClient ! . LeaseDocumentAsync < EveCommandReceiptDocument > (
_target ,
recordKey ,
cancellationToken )
. ConfigureAwait ( false ) ;
IDisposable ? watch = null ;
try
{
watch = lease . Handle . Watch ( receipt = > QueueReceipt ( commandId , receipt ) ) ;
try { QueueReceipt ( commandId , await lease . Handle . LatestAsync ( ) . ConfigureAwait ( false ) ) ; }
catch ( KeyNotFoundException ) { }
return new ReceiptSubscription ( lease , watch ) ;
}
catch
{
watch ? . Dispose ( ) ;
lease . Dispose ( ) ;
throw ;
}
}
private void QueueReceipt ( string expectedCommandId , EveCommandReceiptDocument receipt )
{
2026-08-19 04:03:00 +02:00
if ( receipt = = null ) return ;
lock ( _pendingCommands )
{
if ( ! _pendingCommands . TryGetValue ( expectedCommandId , out var request ) | |
! ReceiptMatches ( request , receipt ) )
return ;
}
2026-08-18 19:03:06 +02:00
_liveDocuments . Enqueue ( receipt ) ;
}
private static void DisposeReceiptSubscription ( Task < ReceiptSubscription > subscription )
{
if ( subscription . Status = = TaskStatus . RanToCompletion )
subscription . Result . Dispose ( ) ;
else
_ = subscription . ContinueWith (
completed = > { if ( completed . Status = = TaskStatus . RanToCompletion ) completed . Result . Dispose ( ) ; } ,
CancellationToken . None ,
TaskContinuationOptions . ExecuteSynchronously ,
TaskScheduler . Default ) ;
2026-07-12 12:33:36 +01:00
}
2026-08-17 21:02:01 +02:00
private void DisposeLiveDocuments ( )
2026-07-19 00:02:51 +01:00
{
2026-08-17 21:02:01 +02:00
foreach ( var watch in _documentWatches ) watch . Dispose ( ) ;
_documentWatches . Clear ( ) ;
foreach ( var lease in _documentLeases ) lease . Dispose ( ) ;
_documentLeases . Clear ( ) ;
_liveDocumentsReady = false ;
2026-07-19 00:02:51 +01:00
}
2026-08-18 10:08:03 +02:00
private async Task LeaseDocumentAsync < TDocument > (
2026-08-17 21:02:01 +02:00
string recordKey ,
Action < TDocument > publish ,
2026-08-18 10:08:03 +02:00
CancellationToken cancellationToken ,
2026-08-17 21:02:01 +02:00
bool publishInitial = true )
where TDocument : class
2026-07-12 12:33:36 +01:00
{
2026-08-18 10:08:03 +02:00
var lease = await _meshClient ! . LeaseDocumentAsync < TDocument > ( _target , recordKey , cancellationToken ) ;
2026-08-17 21:02:01 +02:00
_documentLeases . Add ( lease ) ;
2026-08-18 10:08:03 +02:00
if ( publishInitial ) publish ( await lease . Handle . LatestAsync ( ) ) ;
2026-08-17 21:02:01 +02:00
_documentWatches . Add ( lease . Handle . Watch ( publish ) ) ;
}
2026-08-18 10:08:03 +02:00
private async Task LeaseCollectionAsync < TDocument > (
2026-08-17 21:02:01 +02:00
Action < TDocument > publish ,
2026-08-18 10:08:03 +02:00
CancellationToken cancellationToken ,
2026-08-17 21:02:01 +02:00
bool includeInitialSnapshot = true )
where TDocument : class
{
2026-08-18 10:08:03 +02:00
var lease = await _meshClient ! . LeaseCollectionAsync < TDocument > (
_target ,
includeInitialSnapshot ,
cancellationToken ) ;
2026-08-17 21:02:01 +02:00
_documentLeases . Add ( lease ) ;
if ( includeInitialSnapshot )
2026-08-18 10:08:03 +02:00
foreach ( var document in await lease . Handle . LatestAsync ( ) )
2026-08-17 21:02:01 +02:00
publish ( document ) ;
_documentWatches . Add ( lease . Handle . WatchChanges ( change = >
{
if ( change . Document ! = null ) publish ( change . Document ) ;
} ) ) ;
2026-07-10 04:39:16 +01:00
}
2026-07-19 07:35:16 +01:00
private static IEnumerable < EveEmbeddedDocumentSlot > EnumerateEmbeddedDocuments ( EveSurfaceComponent component )
{
foreach ( var slot in component . EmbeddedDocuments ? ? Array . Empty < EveEmbeddedDocumentSlot > ( ) )
yield return slot ;
foreach ( var child in component . Children ? ? Array . Empty < EveSurfaceComponent > ( ) )
foreach ( var slot in EnumerateEmbeddedDocuments ( child ) )
yield return slot ;
}
private sealed class PendingSurfaceDocument
{
public PendingSurfaceDocument ( string recordKey , EveSurfaceDocument document )
{
RecordKey = recordKey ? ? "" ;
Document = document ? ? throw new ArgumentNullException ( nameof ( document ) ) ;
}
public string RecordKey { get ; }
public EveSurfaceDocument Document { get ; }
}
2026-08-19 07:57:33 +02:00
private sealed class PreparedSurface
{
public PreparedSurface (
EveUnitySceneProviderSurfaceDocument document ,
IReadOnlyCollection < string > continuousCommands )
{
Document = document ;
ContinuousCommands = continuousCommands ;
}
public EveUnitySceneProviderSurfaceDocument Document { get ; }
public IReadOnlyCollection < string > ContinuousCommands { get ; }
}
2026-07-19 04:39:33 +01:00
private static void TraceHotState ( string message )
{
if ( string . Equals ( Environment . GetEnvironmentVariable ( "AETHERIA_TRACE_CLIENT_RUDP" ) , "1" , StringComparison . Ordinal ) )
Debug . Log ( $"EveUnity CultMesh hot state: {message}" ) ;
}
2026-08-18 10:08:03 +02:00
private async Task RefreshAssetCatalogAsync ( CancellationToken cancellationToken )
2026-07-10 06:00:36 +01:00
{
2026-08-19 07:31:25 +02:00
var source = ResolveAssetSource (
_baseSurface ? ? throw new InvalidOperationException ( "The provider surface must be available before its assets are resolved." ) ) ;
if ( string . IsNullOrWhiteSpace ( source . ManifestRecordRef ) )
2026-07-10 06:00:36 +01:00
return ;
2026-08-19 08:18:57 +02:00
var candidate = await BuildAssetGenerationAsync ( source , cancellationToken ) ;
2026-08-19 07:57:33 +02:00
CommitAssetGeneration ( candidate ) ;
2026-08-19 07:31:25 +02:00
}
private async Task RefreshAssetsForSurfaceAsync (
EveSurfaceDocument surface ,
AssetSource source ,
long generation ,
CancellationToken cancellationToken )
{
2026-08-19 10:04:30 +02:00
Exception ? finalError = null ;
Interlocked . Exchange ( ref _lastAssetPresentationAttemptCount , 0 ) ;
for ( var attempt = 1 ; attempt < = AssetPresentationAttemptLimit ; attempt + + )
2026-08-19 07:31:25 +02:00
{
2026-08-19 10:04:30 +02:00
Interlocked . Exchange ( ref _lastAssetPresentationAttemptCount , attempt ) ;
2026-08-19 07:57:33 +02:00
try
{
if ( generation ! = Interlocked . Read ( ref _surfaceAssetGeneration ) )
return ;
2026-08-19 10:04:30 +02:00
await _assetGenerationGate . WaitAsync ( cancellationToken ) ;
try
2026-08-19 07:57:33 +02:00
{
2026-08-19 10:04:30 +02:00
if ( generation ! = Interlocked . Read ( ref _surfaceAssetGeneration ) )
return ;
var candidate = await BuildAssetGenerationAsync ( source , cancellationToken ) ;
if ( generation ! = Interlocked . Read ( ref _surfaceAssetGeneration ) )
{
candidate . Dispose ( ) ;
return ;
}
CommitAssetGeneration ( candidate , surface ) ;
2026-08-19 07:57:33 +02:00
return ;
}
2026-08-19 10:04:30 +02:00
finally
{
_assetGenerationGate . Release ( ) ;
}
2026-08-19 07:57:33 +02:00
}
2026-08-19 10:04:30 +02:00
catch ( OperationCanceledException ) when ( cancellationToken . IsCancellationRequested )
2026-08-19 07:57:33 +02:00
{
2026-08-19 10:04:30 +02:00
return ;
}
catch ( Exception error )
{
finalError = error ;
if ( generation ! = Interlocked . Read ( ref _surfaceAssetGeneration ) )
return ;
if ( attempt < AssetPresentationAttemptLimit )
{
try
{
await Task . Delay ( TimeSpan . FromMilliseconds ( 100 * attempt ) , cancellationToken ) ;
}
catch ( OperationCanceledException ) when ( cancellationToken . IsCancellationRequested )
{
return ;
}
}
2026-08-19 07:57:33 +02:00
}
2026-08-19 07:31:25 +02:00
}
2026-08-19 10:04:30 +02:00
RetireFailedBaseSurfaceCandidate ( surface . Version , generation ) ;
_liveDocuments . Enqueue ( finalError ? ? new InvalidOperationException (
$"Eve surface {surface.Version} asset preparation exhausted its retry policy." ) ) ;
2026-08-19 07:31:25 +02:00
}
private AssetSource ResolveAssetSource ( EveSurfaceDocument surface )
{
var world = FindWorldScene ( surface . Surface . Root ) ;
var manifestRecordRef = world ? . GetProp ( "assetManifest" ) ? ? "" ;
if ( string . IsNullOrWhiteSpace ( manifestRecordRef ) )
manifestRecordRef = RequireWorldInteraction ( ) . AssetManifestRecordRef ;
var providerId = world ? . GetProp ( "assetProviderId" ) ? ? "" ;
var verseId = world ? . GetProp ( "assetVerseId" ) ? ? "" ;
var authorityRuntimeId = world ? . GetProp ( "assetAuthorityRuntimeId" ) ? ? "" ;
2026-08-19 09:36:55 +02:00
var requiredCatalogVersion = long . TryParse (
world ? . GetProp ( "assetCatalogVersion" ) ,
out var parsedCatalogVersion )
? Math . Max ( 0 , parsedCatalogVersion )
: 0 ;
2026-08-19 07:31:25 +02:00
var rendezvousEndpoints = ParseEndpointList ( world ? . GetProp ( "assetRendezvousEndpoints" ) ? ? "" ) ;
var hasQualifiedSource = ! string . IsNullOrWhiteSpace ( providerId ) | |
! string . IsNullOrWhiteSpace ( verseId ) | |
! string . IsNullOrWhiteSpace ( authorityRuntimeId ) ;
if ( ! hasQualifiedSource )
2026-08-19 09:36:55 +02:00
return new AssetSource (
_target ,
_providerId ,
manifestRecordRef ,
Array . Empty < string > ( ) ,
requiredCatalogVersion ) ;
2026-08-19 07:31:25 +02:00
if ( string . IsNullOrWhiteSpace ( providerId ) | | string . IsNullOrWhiteSpace ( verseId ) | |
string . IsNullOrWhiteSpace ( authorityRuntimeId ) )
throw new InvalidOperationException (
"A provider-qualified Eve asset source requires assetProviderId, assetVerseId, and assetAuthorityRuntimeId." ) ;
return new AssetSource (
new CultMeshSessionTarget ( verseId , authorityRuntimeId ) ,
providerId ,
manifestRecordRef ,
2026-08-19 09:36:55 +02:00
rendezvousEndpoints ,
requiredCatalogVersion ) ;
2026-08-19 07:31:25 +02:00
}
2026-08-19 07:57:33 +02:00
private async Task < AssetGeneration > BuildAssetGenerationAsync (
2026-08-19 07:31:25 +02:00
AssetSource source ,
2026-08-19 07:57:33 +02:00
CancellationToken cancellationToken )
{
2026-08-19 08:18:57 +02:00
while ( true )
{
cancellationToken . ThrowIfCancellationRequested ( ) ;
var crossTarget = IsCrossTarget ( source ) ;
var endpoints = AssetRendezvousEndpoints ( source , crossTarget ) ;
var candidate = new AssetGeneration (
source ,
source . Identity ,
catalogVersion : - 1 ,
crossTarget | | source . RendezvousEndpoints . Count > 0
? CreateMeshClient (
endpoints ,
AssetAuthorityTrust ( source ) )
: null ) ;
try
{
2026-08-19 09:36:55 +02:00
var catalog = await AttachAssetCatalogSubscriptionAsync (
candidate ,
source . RequiredCatalogVersion ,
cancellationToken ) ;
2026-08-19 08:18:57 +02:00
ConfigureAssetCatalog ( candidate , catalog ) ;
ReuseCompatibleBundles ( _assetGeneration , candidate ) ;
await PreloadAssetsAsync ( candidate , cancellationToken ) ;
2026-08-19 10:14:37 +02:00
if ( source . RequiredCatalogVersion > 0 )
return candidate ;
2026-08-19 08:18:57 +02:00
var latest = await candidate . CatalogLease ! . Handle . LatestAsync ( ) ;
candidate . ObserveCatalog ( latest ) ;
if ( latest . Version ! = candidate . CatalogVersion )
{
candidate . Dispose ( ) ;
continue ;
}
return candidate ;
}
catch
{
candidate . Dispose ( ) ;
throw ;
}
2026-08-19 07:57:33 +02:00
}
}
2026-08-19 08:09:59 +02:00
private bool IsCrossTarget ( AssetSource source ) = >
! string . Equals ( source . Target . VerseId , _target . VerseId , StringComparison . Ordinal ) | |
! string . Equals ( source . Target . AuthorityRuntimeId , _target . AuthorityRuntimeId , StringComparison . Ordinal ) ;
private CultMeshAuthorityTrustPolicy AssetAuthorityTrust ( AssetSource source ) = >
IsCrossTarget ( source ) ? _crossTargetAuthorityTrust : _authorityTrust ;
private IReadOnlyList < string > AssetRendezvousEndpoints ( AssetSource source , bool crossTarget )
{
if ( source . RendezvousEndpoints . Count > 0 )
return source . RendezvousEndpoints ;
if ( crossTarget )
throw new InvalidOperationException (
$"Cross-target asset source '{source.Target.VerseId}/{source.Target.AuthorityRuntimeId}' " +
"must advertise at least one Odin rendezvous endpoint." ) ;
return new [ ] { _rendezvousEndpoint } ;
}
2026-08-19 08:18:57 +02:00
private async Task < EveAssetCatalogDocument > AttachAssetCatalogSubscriptionAsync (
2026-08-19 07:57:33 +02:00
AssetGeneration candidate ,
2026-08-19 09:36:55 +02:00
long requiredCatalogVersion ,
2026-08-19 07:31:25 +02:00
CancellationToken cancellationToken )
{
2026-08-19 07:57:33 +02:00
var lease = await AssetMeshClient ( candidate )
. LeaseDocumentAsync < EveAssetCatalogDocument > (
candidate . Source . Target ,
candidate . Source . ManifestRecordRef ,
cancellationToken ) ;
2026-08-19 07:31:25 +02:00
IDisposable ? watch = null ;
try
{
2026-08-19 10:14:37 +02:00
var catalog = await lease . Handle . LatestAsync ( ) ;
candidate . ObserveCatalog ( catalog ) ;
if ( requiredCatalogVersion > 0 )
2026-08-19 08:18:57 +02:00
{
2026-08-19 10:14:37 +02:00
RequireCatalogVersion ( catalog , requiredCatalogVersion , candidate . Source . ManifestRecordRef ) ;
candidate . CatalogLease = lease ;
return catalog ;
}
watch = lease . Handle . Watch ( observedCatalog = >
{
var pending = candidate . ObserveCatalog ( observedCatalog ) ;
if ( pending ! = null )
2026-08-19 08:18:57 +02:00
QueueAssetCatalogUpdate ( candidate . SourceIdentity , pending ) ;
} ) ;
2026-08-19 07:57:33 +02:00
candidate . CatalogWatch = watch ;
candidate . CatalogLease = lease ;
2026-08-19 10:14:37 +02:00
return catalog ;
2026-08-19 07:31:25 +02:00
}
catch
{
watch ? . Dispose ( ) ;
lease . Dispose ( ) ;
throw ;
}
}
2026-08-19 10:14:37 +02:00
private static void RequireCatalogVersion (
EveAssetCatalogDocument catalog ,
long requiredCatalogVersion ,
string manifestRecordRef )
{
if ( catalog = = null ) throw new ArgumentNullException ( nameof ( catalog ) ) ;
if ( requiredCatalogVersion < = 0 | | catalog . Version = = requiredCatalogVersion )
return ;
throw new InvalidDataException (
$"Asset catalog record '{manifestRecordRef}' contains version {catalog.Version}, " +
$"but the Eve surface requires immutable version {requiredCatalogVersion}." ) ;
}
2026-08-19 07:57:33 +02:00
private void CommitAssetGeneration ( AssetGeneration candidate , EveSurfaceDocument ? surface = null )
{
PreparedSurface prepared ;
try
{
prepared = PrepareComposedSurface ( surface ? ? _baseSurface ? ?
throw new InvalidOperationException ( "The base Eve surface is unavailable." ) ) ;
}
catch
{
candidate . Dispose ( ) ;
throw ;
}
var previous = _assetGeneration ;
previous . TransferSharedBundlesTo ( candidate ) ;
_assetGeneration = candidate ;
2026-08-19 08:18:57 +02:00
var pendingCatalog = candidate . ActivateCatalogObservation ( ) ;
2026-08-19 09:50:50 +02:00
if ( pendingCatalog ! = null & & candidate . Source . RequiredCatalogVersion < = 0 )
2026-08-19 08:18:57 +02:00
QueueAssetCatalogUpdate ( candidate . SourceIdentity , pendingCatalog ) ;
2026-08-19 07:57:33 +02:00
if ( surface ! = null )
_baseSurface = surface ;
try
{
2026-08-19 09:19:04 +02:00
ApplyPreparedSurface ( prepared , surface ? . Version ) ;
2026-08-19 07:57:33 +02:00
}
finally
{
previous . Dispose ( ) ;
}
}
private static void ReuseCompatibleBundles ( AssetGeneration current , AssetGeneration candidate )
{
foreach ( var pair in candidate . BundleVariants )
{
if ( ! current . LoadedBundlesByUri . TryGetValue ( pair . Key , out var bundle ) | |
! current . BundleVariants . TryGetValue ( pair . Key , out var existing ) | |
! string . Equals ( existing . ContentHash , pair . Value . ContentHash , StringComparison . Ordinal ) | |
existing . SizeBytes ! = pair . Value . SizeBytes )
continue ;
var selections = candidate . BundleSelections [ pair . Key ] ;
if ( selections . Any ( selection = >
! current . NativeAssets . ContainsKey ( selection . Asset . AssetRef ) ) )
continue ;
candidate . AssetBundles . Add ( bundle ) ;
candidate . BorrowedAssetBundles . Add ( bundle ) ;
candidate . LoadedBundlesByUri [ pair . Key ] = bundle ;
candidate . LoadedBundleUris . Add ( pair . Key ) ;
foreach ( var selection in selections )
{
var value = current . NativeAssets [ selection . Asset . AssetRef ] ;
candidate . NativeAssets [ selection . Asset . AssetRef ] = value ;
if ( value is GameObject prefab )
candidate . Prefabs [ selection . Asset . AssetRef ] = prefab ;
if ( selection . Asset . Metadata . TryGetValue ( "presentationRole" , out var role ) & &
! string . IsNullOrWhiteSpace ( role ) )
{
candidate . NativeAssets [ role ] = value ;
if ( value is GameObject rolePrefab )
candidate . Prefabs [ role ] = rolePrefab ;
}
}
}
}
2026-08-19 07:31:25 +02:00
private static EveSurfaceComponent ? FindWorldScene ( EveSurfaceComponent component )
{
if ( string . Equals ( component . Kind , "world.scene3d" , StringComparison . Ordinal ) | |
string . Equals ( component . Kind , "world" , StringComparison . Ordinal ) )
return component ;
foreach ( var child in component . Children ? ? Array . Empty < EveSurfaceComponent > ( ) )
{
var found = FindWorldScene ( child ) ;
if ( found ! = null ) return found ;
}
return null ;
2026-07-19 06:30:37 +01:00
}
2026-08-19 07:31:25 +02:00
private static IReadOnlyList < string > ParseEndpointList ( string value ) = >
( value ? ? "" )
. Split ( new [ ] { ';' } , StringSplitOptions . RemoveEmptyEntries )
. Select ( endpoint = > endpoint . Trim ( ) )
. Where ( endpoint = > endpoint . Length > 0 )
. Distinct ( StringComparer . Ordinal )
. ToArray ( ) ;
2026-08-19 07:57:33 +02:00
private static void ConfigureAssetCatalog ( AssetGeneration candidate , EveAssetCatalogDocument catalog )
2026-07-19 06:30:37 +01:00
{
2026-07-10 06:00:36 +01:00
var selected = catalog . Assets
2026-07-19 21:21:52 +01:00
. Select ( asset = > new SelectedAsset (
asset ,
asset . Variants . FirstOrDefault ( variant = >
2026-07-10 06:00:36 +01:00
string . Equals ( variant . RuntimeId , "unity-scene" , StringComparison . Ordinal ) & &
2026-07-19 21:21:52 +01:00
string . Equals ( variant . Platform , CurrentBundlePlatform ( ) , StringComparison . Ordinal ) ) ) )
2026-07-10 06:00:36 +01:00
. Where ( selection = > selection . Variant ! = null )
. ToArray ( ) ;
2026-07-13 22:58:01 +01:00
if ( selected . Length = = 0 )
{
var advertisedVariants = catalog . Assets
. SelectMany ( asset = > asset . Variants . Select ( variant = >
$"{asset.AssetRef}:{variant.RuntimeId}/{variant.Platform}" ) )
. ToArray ( ) ;
throw new InvalidOperationException (
$"Provider asset catalog '{catalog.CatalogId}' has no unity-scene/{CurrentBundlePlatform()} variant. " +
$"Advertised variants: {string.Join(" , ", advertisedVariants)}" ) ;
}
2026-08-19 08:18:57 +02:00
candidate . SetCatalogVersion ( catalog . Version ) ;
2026-08-19 07:57:33 +02:00
ReadCameraPolicies ( candidate , selected . Select ( selection = > selection . Variant ! ) ) ;
2026-07-19 21:21:52 +01:00
foreach ( var selection in selected )
{
var variant = selection . Variant ! ;
2026-08-19 07:57:33 +02:00
candidate . AssetSelections [ selection . Asset . AssetRef ] = selection ;
candidate . BundleVariants [ variant . Uri ] = variant ;
if ( ! candidate . BundleSelections . TryGetValue ( variant . Uri , out var group ) )
2026-07-19 21:21:52 +01:00
{
group = new List < SelectedAsset > ( ) ;
2026-08-19 07:57:33 +02:00
candidate . BundleSelections [ variant . Uri ] = group ;
2026-07-19 21:21:52 +01:00
}
group . Add ( selection ) ;
var metadata = MergeAssetMetadata ( selection . Asset . Metadata , variant . Metadata ) ;
2026-08-19 07:57:33 +02:00
candidate . NativeAssetMetadata [ selection . Asset . AssetRef ] = metadata ;
2026-07-19 21:21:52 +01:00
if ( selection . Asset . Metadata . TryGetValue ( "presentationRole" , out var role ) & &
! string . IsNullOrWhiteSpace ( role ) )
{
2026-08-19 07:57:33 +02:00
candidate . AssetSelections [ role ] = selection ;
candidate . NativeAssetMetadata [ role ] = metadata ;
2026-07-19 21:21:52 +01:00
}
}
}
2026-08-19 07:31:25 +02:00
private void QueueAssetCatalogUpdate ( string sourceIdentity , EveAssetCatalogDocument catalog )
2026-07-19 21:21:52 +01:00
{
2026-08-19 09:50:50 +02:00
if ( catalog = = null ) throw new ArgumentNullException ( nameof ( catalog ) ) ;
if ( _assetGeneration . Source . RequiredCatalogVersion > 0 )
{
_pendingAssetCatalog = null ;
return ;
}
2026-08-19 07:31:25 +02:00
_pendingAssetCatalog = new PendingAssetCatalogUpdate (
sourceIdentity ,
2026-08-19 09:50:50 +02:00
catalog ) ;
2026-08-18 10:08:03 +02:00
if ( _assetCatalogUpdateRunning ) return ;
_assetCatalogUpdateRunning = true ;
_ = DrainAssetCatalogUpdatesAsync ( ) ;
}
private async Task DrainAssetCatalogUpdatesAsync ( )
{
try
{
while ( ! _lifetime . IsCancellationRequested )
{
2026-08-19 07:31:25 +02:00
var update = _pendingAssetCatalog ;
2026-08-18 10:08:03 +02:00
_pendingAssetCatalog = null ;
2026-08-19 07:31:25 +02:00
if ( update = = null ) break ;
2026-08-19 09:50:50 +02:00
if ( _assetGeneration . Source . RequiredCatalogVersion > 0 )
continue ;
2026-08-19 07:31:25 +02:00
if ( ! string . Equals ( update . SourceIdentity , CurrentAssetSourceIdentity , StringComparison . Ordinal ) )
continue ;
2026-08-19 07:57:33 +02:00
if ( update . Catalog . Version = = CurrentAssetCatalogVersion )
continue ;
await _assetGenerationGate . WaitAsync ( _lifetime . Token ) ;
try
{
if ( ! string . Equals ( update . SourceIdentity , CurrentAssetSourceIdentity , StringComparison . Ordinal ) | |
2026-08-19 09:50:50 +02:00
update . Catalog . Version = = CurrentAssetCatalogVersion | |
_assetGeneration . Source . RequiredCatalogVersion > 0 )
2026-08-19 07:57:33 +02:00
continue ;
2026-08-19 09:36:55 +02:00
var currentSource = _assetGeneration . Source ;
var source = new AssetSource (
currentSource . Target ,
currentSource . ProviderId ,
currentSource . ManifestRecordRef ,
currentSource . RendezvousEndpoints ,
2026-08-19 09:50:50 +02:00
0 ) ;
2026-08-19 08:18:57 +02:00
var candidate = await BuildAssetGenerationAsync ( source , _lifetime . Token ) ;
2026-08-19 09:50:50 +02:00
if ( ! string . Equals ( update . SourceIdentity , CurrentAssetSourceIdentity , StringComparison . Ordinal ) | |
_assetGeneration . Source . RequiredCatalogVersion > 0 )
2026-08-19 07:57:33 +02:00
{
candidate . Dispose ( ) ;
continue ;
}
CommitAssetGeneration ( candidate ) ;
}
finally
{
_assetGenerationGate . Release ( ) ;
}
2026-08-18 10:08:03 +02:00
}
}
catch ( OperationCanceledException ) when ( _lifetime . IsCancellationRequested )
{
}
catch ( Exception error )
{
_liveDocuments . Enqueue ( error ) ;
}
finally
{
_assetCatalogUpdateRunning = false ;
if ( _pendingAssetCatalog ! = null & & ! _lifetime . IsCancellationRequested )
2026-08-19 07:31:25 +02:00
QueueAssetCatalogUpdate ( _pendingAssetCatalog . SourceIdentity , _pendingAssetCatalog . Catalog ) ;
2026-08-18 10:08:03 +02:00
}
}
2026-08-19 07:57:33 +02:00
private async Task PreloadAssetsAsync ( AssetGeneration candidate , CancellationToken cancellationToken )
2026-08-18 10:08:03 +02:00
{
2026-08-19 07:57:33 +02:00
foreach ( var uri in candidate . BundleVariants . Keys . OrderBy ( value = > value , StringComparer . Ordinal ) . ToArray ( ) )
await EnsureBundleLoadedAsync ( candidate , uri , cancellationToken ) ;
2026-07-19 21:21:52 +01:00
}
2026-08-19 07:57:33 +02:00
private async Task EnsureBundleLoadedAsync (
AssetGeneration candidate ,
string uri ,
CancellationToken cancellationToken )
2026-07-19 21:21:52 +01:00
{
2026-08-19 07:57:33 +02:00
if ( candidate . LoadedBundleUris . Contains ( uri ) ) return ;
if ( ! candidate . BundleVariants . TryGetValue ( uri , out var variant ) )
2026-07-19 21:21:52 +01:00
throw new InvalidOperationException ( $"Provider asset bundle '{uri}' is not present in the selected runtime catalog." ) ;
2026-08-19 07:57:33 +02:00
if ( ! candidate . LoadingBundleUris . Add ( uri ) )
2026-07-19 21:21:52 +01:00
throw new InvalidOperationException ( $"Provider asset bundle dependency cycle includes '{uri}'." ) ;
try
2026-07-10 06:00:36 +01:00
{
2026-07-19 21:21:52 +01:00
if ( variant . Metadata . TryGetValue ( "unity.bundleDependencyUris" , out var dependencies ) )
foreach ( var dependency in dependencies . Split ( new [ ] { ';' } , StringSplitOptions . RemoveEmptyEntries ) )
2026-08-19 07:57:33 +02:00
await EnsureBundleLoadedAsync ( candidate , dependency , cancellationToken ) ;
2026-07-19 21:21:52 +01:00
2026-07-19 20:34:03 +01:00
var groupElapsed = Stopwatch . StartNew ( ) ;
2026-08-19 07:57:33 +02:00
var descriptor = await AssetMeshClient ( candidate )
. ReadAsync < CultMeshCdnArtifactManifest > ( candidate . Source . Target , uri , cancellationToken ) ;
2026-07-19 20:34:03 +01:00
TraceStartup ( "asset-manifest" , groupElapsed ) ;
2026-08-19 07:57:33 +02:00
var bundle = await LoadVerifiedBundleAsync ( candidate , descriptor , variant , cancellationToken ) ;
2026-07-19 20:34:03 +01:00
TraceStartup ( "asset-transfer-and-bundle-load" , groupElapsed ) ;
2026-07-10 06:00:36 +01:00
if ( bundle = = null )
2026-07-19 21:21:52 +01:00
throw new InvalidOperationException ( $"Unity could not load provider asset bundle '{uri}'." ) ;
2026-08-19 07:57:33 +02:00
candidate . AssetBundles . Add ( bundle ) ;
candidate . LoadedBundlesByUri [ uri ] = bundle ;
2026-07-13 23:44:55 +01:00
var bundleAssetNames = bundle . GetAllAssetNames ( ) ;
2026-08-19 07:57:33 +02:00
foreach ( var selection in candidate . BundleSelections [ uri ] )
2026-07-10 06:00:36 +01:00
{
2026-07-13 23:44:55 +01:00
var bundleAssetName = ResolveBundleAssetName ( bundleAssetNames , selection . Variant ! . AssetKey ) ;
2026-07-19 21:21:52 +01:00
var value = bundleAssetName = = null
? null
2026-08-18 10:08:03 +02:00
: await LoadBundleAssetAsync ( bundle , bundleAssetName , selection . Asset . AssetKind , cancellationToken ) ;
2026-07-13 22:44:15 +01:00
if ( value = = null )
throw new InvalidOperationException (
$"Provider asset '{selection.Asset.AssetRef}' advertises missing Unity bundle asset " +
2026-07-19 21:21:52 +01:00
$"'{selection.Variant.AssetKey}'. Available assets: " + string . Join ( ", " , bundleAssetNames ) ) ;
2026-08-19 07:57:33 +02:00
candidate . NativeAssets [ selection . Asset . AssetRef ] = value ;
2026-07-12 06:25:10 +01:00
if ( selection . Asset . Metadata . TryGetValue ( "presentationRole" , out var role ) & &
! string . IsNullOrWhiteSpace ( role ) )
2026-08-19 07:57:33 +02:00
candidate . NativeAssets [ role ] = value ;
2026-07-12 06:25:10 +01:00
if ( value is GameObject prefab )
{
2026-08-19 07:57:33 +02:00
candidate . Prefabs [ selection . Asset . AssetRef ] = prefab ;
if ( ! string . IsNullOrWhiteSpace ( role ) ) candidate . Prefabs [ role ] = prefab ;
2026-07-12 06:25:10 +01:00
}
2026-07-10 06:00:36 +01:00
}
2026-08-19 07:57:33 +02:00
candidate . LoadedBundleUris . Add ( uri ) ;
2026-07-19 20:34:03 +01:00
TraceStartup ( "bundle-assets" , groupElapsed ) ;
2026-07-10 06:00:36 +01:00
}
2026-07-19 21:21:52 +01:00
finally
{
2026-08-19 07:57:33 +02:00
candidate . LoadingBundleUris . Remove ( uri ) ;
2026-07-19 21:21:52 +01:00
}
}
2026-08-18 10:08:03 +02:00
private static async Task < UnityEngine . Object ? > LoadBundleAssetAsync (
AssetBundle bundle ,
string assetName ,
string assetKind ,
CancellationToken cancellationToken )
2026-07-19 21:21:52 +01:00
{
2026-08-18 10:08:03 +02:00
var request = string . Equals ( assetKind , "sprite" , StringComparison . Ordinal )
? bundle . LoadAssetAsync < Sprite > ( assetName )
: bundle . LoadAssetAsync ( assetName ) ;
await AwaitUnityAsync ( request , cancellationToken ) ;
return request . asset ;
2026-07-19 21:21:52 +01:00
}
private sealed class SelectedAsset
{
public SelectedAsset ( EveAssetCatalogEntry asset , EveAssetVariant ? variant )
{
Asset = asset ;
Variant = variant ;
}
2026-07-10 06:00:36 +01:00
2026-07-19 21:21:52 +01:00
public EveAssetCatalogEntry Asset { get ; }
public EveAssetVariant ? Variant { get ; }
2026-07-10 06:00:36 +01:00
}
2026-08-19 07:57:33 +02:00
private sealed class AssetGeneration : IDisposable
{
2026-08-19 08:18:57 +02:00
private readonly object _catalogObservationGate = new object ( ) ;
private EveAssetCatalogDocument ? _latestObservedCatalog ;
private bool _catalogObservationActive ;
2026-08-19 07:57:33 +02:00
public AssetGeneration (
AssetSource source ,
string sourceIdentity ,
long catalogVersion ,
CultMeshClient ? meshClient )
{
Source = source ;
SourceIdentity = sourceIdentity ? ? "" ;
CatalogVersion = catalogVersion ;
MeshClient = meshClient ;
}
public AssetSource Source { get ; }
public string SourceIdentity { get ; }
2026-08-19 08:18:57 +02:00
public long CatalogVersion { get ; private set ; }
2026-08-19 07:57:33 +02:00
public CultMeshClient ? MeshClient { get ; }
2026-08-19 08:18:57 +02:00
public CultMeshDocumentLease < EveAssetCatalogDocument > ? CatalogLease { get ; set ; }
2026-08-19 07:57:33 +02:00
public IDisposable ? CatalogWatch { get ; set ; }
public CultMeshContentTransferService ? ContentTransfer { get ; set ; }
public CultMeshVerifiedBodyMappingBroker ? BodyMappings { get ; set ; }
public CultMeshBodyTransportKind ? BodyTransportKind { get ; set ; }
public Dictionary < string , GameObject > Prefabs { get ; } = new Dictionary < string , GameObject > ( StringComparer . Ordinal ) ;
public Dictionary < string , UnityEngine . Object > NativeAssets { get ; } = new Dictionary < string , UnityEngine . Object > ( StringComparer . Ordinal ) ;
public Dictionary < string , IReadOnlyDictionary < string , string > > NativeAssetMetadata { get ; } =
new Dictionary < string , IReadOnlyDictionary < string , string > > ( StringComparer . Ordinal ) ;
public List < AssetBundle > AssetBundles { get ; } = new List < AssetBundle > ( ) ;
public HashSet < AssetBundle > BorrowedAssetBundles { get ; } = new HashSet < AssetBundle > ( ) ;
public Dictionary < string , AssetBundle > LoadedBundlesByUri { get ; } =
new Dictionary < string , AssetBundle > ( StringComparer . Ordinal ) ;
public Dictionary < string , SelectedAsset > AssetSelections { get ; } =
new Dictionary < string , SelectedAsset > ( StringComparer . Ordinal ) ;
public Dictionary < string , List < SelectedAsset > > BundleSelections { get ; } =
new Dictionary < string , List < SelectedAsset > > ( StringComparer . Ordinal ) ;
public Dictionary < string , EveAssetVariant > BundleVariants { get ; } =
new Dictionary < string , EveAssetVariant > ( StringComparer . Ordinal ) ;
public HashSet < string > LoadedBundleUris { get ; } = new HashSet < string > ( StringComparer . Ordinal ) ;
public HashSet < string > LoadingBundleUris { get ; } = new HashSet < string > ( StringComparer . Ordinal ) ;
public List < ICultMeshBodyReadLease > BodyLeases { get ; } = new List < ICultMeshBodyReadLease > ( ) ;
public Dictionary < string , int > RenderChannelLayers { get ; } =
new Dictionary < string , int > ( StringComparer . Ordinal ) ;
public void TransferSharedBundlesTo ( AssetGeneration next )
{
foreach ( var bundle in next . BorrowedAssetBundles )
AssetBundles . Remove ( bundle ) ;
next . BorrowedAssetBundles . Clear ( ) ;
}
2026-08-19 08:18:57 +02:00
public void SetCatalogVersion ( long catalogVersion )
{
if ( CatalogVersion > = 0 & & CatalogVersion ! = catalogVersion )
throw new InvalidOperationException ( "An asset generation cannot change its catalog version after configuration." ) ;
CatalogVersion = catalogVersion ;
}
public EveAssetCatalogDocument ? ObserveCatalog ( EveAssetCatalogDocument catalog )
{
lock ( _catalogObservationGate )
{
_latestObservedCatalog = catalog ? ? throw new ArgumentNullException ( nameof ( catalog ) ) ;
return _catalogObservationActive & & catalog . Version ! = CatalogVersion ? catalog : null ;
}
}
public EveAssetCatalogDocument ? ActivateCatalogObservation ( )
{
lock ( _catalogObservationGate )
{
_catalogObservationActive = true ;
return _latestObservedCatalog ! = null & & _latestObservedCatalog . Version ! = CatalogVersion
? _latestObservedCatalog
: null ;
}
}
2026-08-19 07:57:33 +02:00
public void Dispose ( )
{
CatalogWatch ? . Dispose ( ) ;
CatalogWatch = null ;
CatalogLease ? . Dispose ( ) ;
CatalogLease = null ;
MeshClient ? . Dispose ( ) ;
foreach ( var bundle in AssetBundles )
if ( ! BorrowedAssetBundles . Contains ( bundle ) )
bundle . Unload ( unloadAllLoadedObjects : false ) ;
AssetBundles . Clear ( ) ;
BorrowedAssetBundles . Clear ( ) ;
foreach ( var lease in BodyLeases )
lease . Dispose ( ) ;
BodyLeases . Clear ( ) ;
Prefabs . Clear ( ) ;
NativeAssets . Clear ( ) ;
NativeAssetMetadata . Clear ( ) ;
AssetSelections . Clear ( ) ;
BundleSelections . Clear ( ) ;
BundleVariants . Clear ( ) ;
LoadedBundleUris . Clear ( ) ;
LoadingBundleUris . Clear ( ) ;
LoadedBundlesByUri . Clear ( ) ;
RenderChannelLayers . Clear ( ) ;
}
}
2026-07-13 23:44:55 +01:00
private static string? ResolveBundleAssetName ( IEnumerable < string > bundleAssetNames , string advertisedAssetKey )
{
return bundleAssetNames . FirstOrDefault ( assetName = >
string . Equals ( assetName , advertisedAssetKey , StringComparison . OrdinalIgnoreCase ) ) ;
}
2026-07-15 19:59:37 +01:00
private static IReadOnlyDictionary < string , string > MergeAssetMetadata (
IReadOnlyDictionary < string , string > assetMetadata ,
IReadOnlyDictionary < string , string > variantMetadata )
{
var merged = new Dictionary < string , string > ( StringComparer . Ordinal ) ;
foreach ( var pair in assetMetadata ) merged [ pair . Key ] = pair . Value ;
foreach ( var pair in variantMetadata ) merged [ pair . Key ] = pair . Value ;
return merged ;
}
2026-07-13 23:44:55 +01:00
2026-08-19 07:57:33 +02:00
private static void ReadCameraPolicies ( AssetGeneration candidate , IEnumerable < EveAssetVariant > variants )
2026-07-12 06:25:10 +01:00
{
foreach ( var variant in variants )
{
foreach ( var pair in variant . Metadata )
{
2026-07-13 21:35:11 +01:00
const string prefix = "renderChannel." ;
const string suffix = ".unityLayer" ;
2026-07-12 06:25:10 +01:00
if ( ! pair . Key . StartsWith ( prefix , StringComparison . Ordinal ) | |
! pair . Key . EndsWith ( suffix , StringComparison . Ordinal ) )
continue ;
2026-07-13 21:35:11 +01:00
var channel = pair . Key . Substring ( prefix . Length , pair . Key . Length - prefix . Length - suffix . Length ) ;
if ( ! string . IsNullOrWhiteSpace ( channel ) & &
int . TryParse ( pair . Value , out var layer ) & & layer > = 0 & & layer < 32 )
2026-08-19 07:57:33 +02:00
candidate . RenderChannelLayers [ channel ] = layer ;
2026-07-12 06:25:10 +01:00
}
}
}
2026-08-19 07:57:33 +02:00
private long CurrentAssetCatalogVersion = > _assetGeneration . CatalogVersion ;
2026-07-10 06:00:36 +01:00
2026-08-19 07:57:33 +02:00
private string CurrentAssetSourceIdentity = > _assetGeneration . SourceIdentity ;
2026-08-19 07:31:25 +02:00
2026-07-10 06:00:36 +01:00
private static string CurrentBundlePlatform ( )
{
return Application . platform = = RuntimePlatform . WindowsEditor | |
Application . platform = = RuntimePlatform . WindowsPlayer
? "StandaloneWindows64"
: Application . platform . ToString ( ) ;
}
2026-08-19 07:57:33 +02:00
private CultMeshContentTransferService ContentTransfer ( AssetGeneration candidate )
2026-07-10 06:00:36 +01:00
{
2026-08-19 07:57:33 +02:00
if ( candidate . ContentTransfer ! = null )
return candidate . ContentTransfer ;
2026-08-18 10:08:03 +02:00
if ( _advertisement = = null )
throw new InvalidOperationException ( "The Eve provider advertisement must be prepared before content transfer." ) ;
2026-07-14 01:26:47 +01:00
if ( string . IsNullOrWhiteSpace ( _advertisement ! . ServiceId ) )
throw new InvalidOperationException ( $"Eve provider '{_advertisement.ProviderId}' has no service-instance identity for content transport." ) ;
2026-07-10 06:00:36 +01:00
var cacheRoot = Environment . GetEnvironmentVariable ( "EVEUNITY_ASSET_CACHE_PATH" ) ;
if ( string . IsNullOrWhiteSpace ( cacheRoot ) )
cacheRoot = Path . Combine ( Application . persistentDataPath , "EveUnity" , "assets" ) ;
2026-08-19 07:57:33 +02:00
candidate . BodyMappings = new CultMeshVerifiedBodyMappingBroker ( cacheRoot ) ;
2026-08-17 21:02:01 +02:00
_contentState ? ? = new CultCache (
CultMesh . CreateCultCacheDocumentRegistry ( typeof ( CultMeshContentTransferStateDocument ) ) ) ;
2026-08-19 07:57:33 +02:00
candidate . ContentTransfer = new CultMeshContentTransferService (
2026-08-17 21:02:01 +02:00
_contentState ,
2026-07-14 01:26:47 +01:00
new [ ]
{
2026-08-19 07:57:33 +02:00
AssetMeshClient ( candidate ) . ContentProvider (
candidate . Source . ProviderId ,
candidate . Source . Target )
2026-07-14 01:26:47 +01:00
} ,
2026-07-16 14:17:37 +01:00
new CultMeshContentTransferOptions ( cacheRoot ) ,
2026-08-19 07:57:33 +02:00
candidate . BodyMappings ) ;
return candidate . ContentTransfer ;
2026-07-10 06:00:36 +01:00
}
2026-08-18 10:08:03 +02:00
private async Task < AssetBundle ? > LoadVerifiedBundleAsync (
2026-08-19 07:57:33 +02:00
AssetGeneration candidate ,
2026-08-18 10:08:03 +02:00
CultMeshCdnArtifactManifest manifest ,
EveAssetVariant variant ,
CancellationToken cancellationToken )
2026-07-10 06:00:36 +01:00
{
2026-07-14 01:26:47 +01:00
var hash = NormalizeContentHash ( variant . ContentHash ) ;
if ( manifest . SizeBytes ! = variant . SizeBytes )
2026-07-10 06:00:36 +01:00
throw new InvalidOperationException ( $"Provider asset bundle '{variant.Uri}' size did not match its catalog." ) ;
2026-07-14 01:26:47 +01:00
if ( ! string . Equals ( NormalizeContentHash ( manifest . ContentHash ) ,
hash , StringComparison . Ordinal ) )
2026-07-10 06:00:36 +01:00
throw new InvalidOperationException ( $"Provider asset bundle '{variant.Uri}' hash did not match its catalog." ) ;
2026-07-16 14:17:37 +01:00
var now = DateTimeOffset . UtcNow ;
var network = NetworkArtifactDescriptor ( manifest , now , TimeSpan . FromMinutes ( 5 ) ) ;
2026-07-19 20:34:03 +01:00
var elapsed = Stopwatch . StartNew ( ) ;
2026-08-19 07:57:33 +02:00
var mapped = await ContentTransfer ( candidate )
2026-08-18 10:08:03 +02:00
. FetchMappedContentAsync ( manifest , network , now , TimeSpan . FromMinutes ( 5 ) , cancellationToken ) ;
2026-07-19 20:34:03 +01:00
TraceStartup ( "content-materialization" , elapsed ) ;
2026-08-18 10:08:03 +02:00
var validationRequest = new CultMeshBodyValidationRequest
2026-07-16 14:17:37 +01:00
{
BodyId = network . BodyId ,
SchemaId = network . SchemaId ,
LayoutVersion = network . LayoutVersion ,
ProducerEpoch = network . ProducerEpoch ,
Sequence = network . Sequence ,
Capacity = network . Capacity ,
AccessMode = CultMeshBodyAccessMode . ReadOnly ,
NowUtc = now
} ;
var transport = new CultMeshBodyTransportService (
new ICultMeshBodyTransportAdapter [ ]
{
2026-08-19 07:57:33 +02:00
new CultMeshMappedBodyAdapter ( candidate . BodyMappings ! ) ,
2026-08-18 10:08:03 +02:00
new CultMeshNetworkBodyAdapter ( _ = > File . ReadAllBytes ( mapped . VerifiedPath ) )
2026-07-16 14:17:37 +01:00
} ,
descriptor = > string . Equals ( descriptor . BodyId , manifest . ArtifactId , StringComparison . Ordinal ) & &
string . Equals ( descriptor . SemanticHash , hash , StringComparison . Ordinal ) ) ;
2026-08-18 10:08:03 +02:00
var negotiated = transport . NegotiateReadOnly ( mapped . Descriptor , network , validationRequest ) ;
2026-08-19 07:57:33 +02:00
candidate . BodyTransportKind = negotiated . SelectedTransport ;
candidate . BodyLeases . Add ( negotiated . Lease ) ;
2026-08-18 10:08:03 +02:00
var bundleRequest = AssetBundle . LoadFromFileAsync ( mapped . VerifiedPath ) ;
await AwaitUnityAsync ( bundleRequest , cancellationToken ) ;
TraceStartup ( "asset-bundle-load-from-file" , elapsed ) ;
return bundleRequest . assetBundle ;
2026-07-16 14:17:37 +01:00
}
2026-08-18 10:08:03 +02:00
private static async Task AwaitUnityAsync ( AsyncOperation operation , CancellationToken cancellationToken )
2026-07-16 14:17:37 +01:00
{
2026-08-18 10:08:03 +02:00
while ( ! operation . isDone )
{
cancellationToken . ThrowIfCancellationRequested ( ) ;
await Task . Yield ( ) ;
}
cancellationToken . ThrowIfCancellationRequested ( ) ;
2026-07-16 14:17:37 +01:00
}
private static CultMeshBodyDescriptor NetworkArtifactDescriptor (
CultMeshCdnArtifactManifest manifest ,
DateTimeOffset now ,
TimeSpan leaseDuration )
{
if ( manifest . SizeBytes > int . MaxValue )
throw new InvalidOperationException ( "CultMesh artifact capacity exceeds the current body descriptor bound." ) ;
return new CultMeshBodyDescriptor
{
BodyId = manifest . ArtifactId ,
SchemaId = "gamecult.mesh.cdn-artifact.v1" ,
LayoutVersion = 1 ,
ByteSize = manifest . SizeBytes ,
Capacity = checked ( ( int ) manifest . SizeBytes ) ,
ProducerEpoch = 1 ,
Sequence = 0 ,
AccessMode = CultMeshBodyAccessMode . ReadOnly ,
Synchronization = CultMeshBodySynchronization . ImmutableSequence ,
LeaseExpiresAtUnixMs = now . Add ( leaseDuration ) . ToUnixTimeMilliseconds ( ) ,
TransportKind = CultMeshBodyTransportKind . Network ,
CapabilityToken = CultMeshCdnArtifactManifest . CreateRecordKey ( manifest ) . Value ,
SemanticHash = NormalizeContentHash ( manifest . ContentHash )
} ;
2026-07-10 06:00:36 +01:00
}
2026-07-12 13:10:43 +01:00
private void PublishReceipt ( EveCommandReceiptDocument receipt )
2026-07-10 04:39:16 +01:00
{
2026-08-19 04:03:00 +02:00
var terminal = IsTerminalReceiptState ( receipt . State ) ;
lock ( _pendingCommands )
2026-08-18 10:08:03 +02:00
{
2026-08-19 04:03:00 +02:00
if ( ! _pendingCommands . TryGetValue ( receipt . CommandId , out var request ) | |
! ReceiptMatches ( request , receipt ) )
2026-08-18 10:08:03 +02:00
return ;
2026-08-19 04:03:00 +02:00
}
2026-08-19 09:36:55 +02:00
if ( terminal )
{
_commandOutbox ? . Acknowledge ( receipt . CommandId ) ;
if ( DeferTerminalReceiptUntilPresentation ( receipt ) )
return ;
}
2026-08-19 09:10:37 +02:00
FinalizeReceipt ( receipt , terminal ) ;
}
private void EnsurePresentationWritable ( )
{
lock ( _presentationFinalityGate )
{
2026-08-19 09:19:04 +02:00
if ( _presentationBarrierVersion > _mountedBaseSurfaceVersion )
2026-08-19 09:10:37 +02:00
throw new InvalidOperationException (
$"The Eve presentation is awaiting provider surface version {_presentationBarrierVersion}; " +
2026-08-19 09:19:04 +02:00
$"mounted base version {_mountedBaseSurfaceVersion} is read-only until that generation commits." ) ;
2026-08-19 09:10:37 +02:00
}
}
private void BeginPresentationTransition ( long sourceVersion )
{
lock ( _presentationFinalityGate )
2026-08-19 09:19:04 +02:00
{
if ( sourceVersion < = _mountedBaseSurfaceVersion )
return ;
2026-08-19 09:10:37 +02:00
_presentationBarrierVersion = Math . Max ( _presentationBarrierVersion , sourceVersion ) ;
2026-08-19 09:19:04 +02:00
}
2026-08-19 09:10:37 +02:00
}
private bool DeferTerminalReceiptUntilPresentation ( EveCommandReceiptDocument receipt )
{
2026-08-19 09:36:55 +02:00
if ( receipt . PresentationSurfaceVersion < = 0 )
return false ;
2026-08-19 09:10:37 +02:00
lock ( _presentationFinalityGate )
{
2026-08-19 09:36:55 +02:00
if ( receipt . PresentationSurfaceVersion < = _mountedBaseSurfaceVersion )
2026-08-19 09:10:37 +02:00
return false ;
2026-08-19 09:36:55 +02:00
_presentationBarrierVersion = Math . Max (
_presentationBarrierVersion ,
receipt . PresentationSurfaceVersion ) ;
2026-08-19 09:10:37 +02:00
_deferredTerminalReceipts [ receipt . CommandId ] = receipt ;
return true ;
}
}
private void CompletePresentationTransition ( long committedVersion )
{
EveCommandReceiptDocument [ ] ready ;
lock ( _presentationFinalityGate )
{
2026-08-19 09:19:04 +02:00
_mountedBaseSurfaceVersion = Math . Max ( _mountedBaseSurfaceVersion , committedVersion ) ;
2026-08-19 09:56:36 +02:00
if ( _activeBaseSurfaceCandidateVersion = = committedVersion )
{
_activeBaseSurfaceCandidateVersion = - 1 ;
_activeBaseSurfaceCandidateGeneration = - 1 ;
}
2026-08-19 09:10:37 +02:00
ready = _deferredTerminalReceipts . Values
2026-08-19 09:36:55 +02:00
. Where ( receipt = > receipt . PresentationSurfaceVersion < = _mountedBaseSurfaceVersion )
2026-08-19 09:10:37 +02:00
. ToArray ( ) ;
foreach ( var receipt in ready )
_deferredTerminalReceipts . Remove ( receipt . CommandId ) ;
2026-08-19 09:36:55 +02:00
if ( _presentationBarrierVersion < = _mountedBaseSurfaceVersion )
_presentationBarrierVersion = - 1 ;
2026-08-19 09:10:37 +02:00
}
foreach ( var receipt in ready )
FinalizeReceipt ( receipt , terminal : true ) ;
}
2026-08-19 09:19:04 +02:00
private long MountedBaseSurfaceVersion
{
get
{
lock ( _presentationFinalityGate )
return _mountedBaseSurfaceVersion ;
}
}
2026-08-19 09:10:37 +02:00
private void FinalizeReceipt ( EveCommandReceiptDocument receipt , bool terminal )
{
2026-08-19 04:03:00 +02:00
if ( terminal )
{
2026-08-19 09:10:37 +02:00
lock ( _pendingCommands )
{
if ( ! _pendingCommands . ContainsKey ( receipt . CommandId ) )
return ;
_pendingCommands . Remove ( receipt . CommandId ) ;
}
2026-08-19 04:03:00 +02:00
ForgetPendingCommand ( receipt . CommandId ) ;
2026-08-18 10:08:03 +02:00
}
2026-07-12 13:10:43 +01:00
CommandReceiptAvailable ? . Invoke ( new EveUnitySceneCommandReceipt (
receipt . ReceiptId ,
receipt . Command ,
receipt . CommandId ,
receipt . State ,
receipt . OwnerRepo ,
receipt . Authority ,
receipt . Schema ,
receipt . ProviderId ,
receipt . SurfaceId ,
receipt . Message ,
DateTimeOffset . TryParse ( receipt . IssuedAtUtc , out var issuedAt ) ? issuedAt : null ,
2026-08-17 22:43:10 +02:00
receipt . SourceVersion ,
receipt . Navigation = = null
? null
: new EveUnitySceneNavigationTarget (
receipt . Navigation . VerseId ,
receipt . Navigation . ProviderId ,
receipt . Navigation . SurfaceId ,
receipt . Navigation . SurfaceKind ,
2026-08-19 03:31:16 +02:00
receipt . Navigation . RendezvousEndpoints ,
receipt . Navigation . AuthorityRuntimeId ) ) ) ;
2026-07-10 04:39:16 +01:00
}
2026-08-19 07:31:25 +02:00
private sealed class AssetSource
{
public AssetSource (
CultMeshSessionTarget target ,
string providerId ,
string manifestRecordRef ,
IReadOnlyList < string > rendezvousEndpoints )
2026-08-19 09:36:55 +02:00
: this ( target , providerId , manifestRecordRef , rendezvousEndpoints , 0 )
{
}
public AssetSource (
CultMeshSessionTarget target ,
string providerId ,
string manifestRecordRef ,
IReadOnlyList < string > rendezvousEndpoints ,
long requiredCatalogVersion )
2026-08-19 07:31:25 +02:00
{
Target = target ;
ProviderId = providerId ? ? "" ;
ManifestRecordRef = manifestRecordRef ? ? "" ;
RendezvousEndpoints = rendezvousEndpoints ? ? Array . Empty < string > ( ) ;
2026-08-19 09:36:55 +02:00
RequiredCatalogVersion = Math . Max ( 0 , requiredCatalogVersion ) ;
2026-08-19 07:31:25 +02:00
Identity = Target . VerseId + "\u001f" + Target . AuthorityRuntimeId + "\u001f" +
ProviderId + "\u001f" + ManifestRecordRef + "\u001f" +
string . Join ( "\u001e" , RendezvousEndpoints ) ;
}
public CultMeshSessionTarget Target { get ; }
public string ProviderId { get ; }
public string ManifestRecordRef { get ; }
public IReadOnlyList < string > RendezvousEndpoints { get ; }
2026-08-19 09:36:55 +02:00
public long RequiredCatalogVersion { get ; }
2026-08-19 07:31:25 +02:00
public string Identity { get ; }
}
private sealed class PendingAssetCatalogUpdate
{
public PendingAssetCatalogUpdate ( string sourceIdentity , EveAssetCatalogDocument catalog )
{
SourceIdentity = sourceIdentity ? ? "" ;
Catalog = catalog ;
}
public string SourceIdentity { get ; }
public EveAssetCatalogDocument Catalog { get ; }
}
2026-08-19 04:03:00 +02:00
private bool ReceiptMatches ( EveSurfaceCommandRequest request , EveCommandReceiptDocument receipt ) = >
string . Equals ( receipt . Schema , EveCommandReceiptDocument . SchemaId , StringComparison . Ordinal ) & &
string . Equals ( receipt . CommandId , request . CommandId , StringComparison . Ordinal ) & &
string . Equals ( receipt . Command , request . Command , StringComparison . Ordinal ) & &
string . Equals ( receipt . ProviderId , request . ProviderId , StringComparison . Ordinal ) & &
string . Equals ( receipt . SurfaceId , request . SurfaceId , StringComparison . Ordinal ) & &
string . Equals ( receipt . Authority , _target . AuthorityRuntimeId , StringComparison . Ordinal ) & &
2026-08-19 04:25:32 +02:00
string . Equals ( receipt . InvocationHash , EveCommandInvocationHash . Compute ( request ) , StringComparison . Ordinal ) & &
2026-08-19 04:03:00 +02:00
IsKnownReceiptState ( receipt . State ) ;
private static bool IsKnownReceiptState ( string state ) = >
string . Equals ( state , "pending" , StringComparison . OrdinalIgnoreCase ) | |
IsTerminalReceiptState ( state ) ;
private static bool IsTerminalReceiptState ( string state ) = >
string . Equals ( state , "accepted" , StringComparison . OrdinalIgnoreCase ) | |
string . Equals ( state , "denied" , StringComparison . OrdinalIgnoreCase ) | |
string . Equals ( state , "reconciled" , StringComparison . OrdinalIgnoreCase ) ;
2026-08-18 19:03:06 +02:00
private sealed class ReceiptSubscription : IDisposable
{
private IDisposable ? _lease ;
private IDisposable ? _watch ;
public ReceiptSubscription ( IDisposable lease , IDisposable watch )
{
_lease = lease ;
_watch = watch ;
}
public void Dispose ( )
{
Interlocked . Exchange ( ref _watch , null ) ? . Dispose ( ) ;
Interlocked . Exchange ( ref _lease , null ) ? . Dispose ( ) ;
}
}
2026-07-10 04:39:16 +01:00
private EveWorldInteractionAdvertisement RequireWorldInteraction ( )
{
return _advertisedSurface ? . WorldInteraction
? ? throw new InvalidOperationException ( "The advertised surface has no interactive-world contract." ) ;
}
private EveUnitySceneProviderSurfaceDocument EmptySurfaceDocument ( )
{
var surface = new EveSurfaceDocument (
_providerId ,
"" ,
"" ,
0 ,
"" ,
new EveSurfaceTree (
_surfaceId ,
new EveSurfaceComponent (
"root" ,
"surface" ,
new Dictionary < string , string > ( ) ,
Array . Empty < EveSurfaceComponent > ( ) ) ,
Array . Empty < EveStyleToken > ( ) ) ,
Array . Empty < EveCommandTemplate > ( ) ) ;
return new EveUnitySceneProviderSurfaceDocument (
surface ,
new EveUnitySceneProviderSurfaceAdvertisement (
_surfaceId ,
"interactive-world" ,
new EveUnitySceneWorldInteraction ( "" , "" , EveCommandReceiptDocument . SchemaId , "" ) ) ,
"" ,
0 ) ;
}
private EveUnityPlayableWorldAssetManifestDocument EmptyAssetManifest ( )
{
return new EveUnityPlayableWorldAssetManifestDocument (
"" ,
Array . Empty < EveUnityPlayableWorldAssetManifestDocumentEntry > ( ) ,
_providerId ) ;
}
private static string ChildRecordKey ( string parent , string child )
{
return $"{parent.TrimEnd(':', '/')}:{child}" ;
}
}
}