From e295d30ba879f9c9b5354a257c0bb1c46311da35 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Mon, 13 Jul 2026 18:31:16 +0100 Subject: [PATCH] Publish Aetheria SoA bodies through CultMesh --- Aetheria.State.Daemon/Program.cs | 31 +- Aetheria.State.Verify/Program.cs | 53 +++- .../AetheriaRuntimeDaemonSoaDocuments.cs | 1 + .../AetheriaRuntimeDaemonSoaFramePublisher.cs | 271 ++++++++++-------- .../AetheriaRuntimeDaemonTickRunner.cs | 14 +- .../AetheriaRuntimeEveEntitySoaProjection.cs | 62 +--- .../Runtime/AetheriaRuntimeVerseClient.cs | 4 + 7 files changed, 244 insertions(+), 192 deletions(-) diff --git a/Aetheria.State.Daemon/Program.cs b/Aetheria.State.Daemon/Program.cs index 76bd3ac8a..28660dd14 100644 --- a/Aetheria.State.Daemon/Program.cs +++ b/Aetheria.State.Daemon/Program.cs @@ -33,6 +33,9 @@ await using var node = await AetheriaStateNode.OpenAsync( runtimeId: options.DaemonId, startServer: true, enableDurableShardLogs: false).ConfigureAwait(false); +using var soaPublisher = new AetheriaRuntimeDaemonSoaFramePublisher( + node.Cache, + DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()); using var discoveryHost = new AetheriaVerseDiscoveryHost(node); await EnsureWorldDocumentAsync(node).ConfigureAwait(false); @@ -52,7 +55,7 @@ using var clientPumpCancellation = new CancellationTokenSource(); var clientPump = RunClientCultMeshPumpAsync(cultMeshRudpHost, clientPumpCancellation.Token); var nextApiPublicationUtc = DateTimeOffset.UtcNow; var ingressState = new AetheriaDaemonIngressState(); -var firstTick = await TickAsync(node, options, physicalPayloadPhysics, worldPhysics, latestFrame, ingressState, buildPublications: true).ConfigureAwait(false); +var firstTick = await TickAsync(node, options, physicalPayloadPhysics, worldPhysics, soaPublisher, latestFrame, ingressState, buildPublications: true).ConfigureAwait(false); ThrowIfClientPumpFaulted(clientPump); latestFrame = firstTick.Frame; nextApiPublicationUtc = DateTimeOffset.UtcNow.Add(options.ApiPublicationInterval); @@ -90,7 +93,7 @@ while (!stopped.Task.IsCompleted) } var buildPublications = DateTimeOffset.UtcNow >= nextApiPublicationUtc; - var tick = await TickAsync(node, options, physicalPayloadPhysics, worldPhysics, latestFrame, ingressState, buildPublications: false).ConfigureAwait(false); + var tick = await TickAsync(node, options, physicalPayloadPhysics, worldPhysics, soaPublisher, latestFrame, ingressState, buildPublications: false).ConfigureAwait(false); ThrowIfClientPumpFaulted(clientPump); latestFrame = tick.Frame; nextTickUtc += options.TickInterval; @@ -100,8 +103,8 @@ while (!stopped.Task.IsCompleted) { if (publicationTask.IsFaulted) await publicationTask.ConfigureAwait(false); - var publication = PreparePublication(node.StatePath, options, tick, ingressState); - publicationTask = PublishPreparedDocumentsAsync(node, options, publication); + var publication = PreparePublication(node.StatePath, options, soaPublisher, tick, ingressState); + publicationTask = PublishPreparedDocumentsAsync(node, options, soaPublisher, publication); nextApiPublicationUtc = DateTimeOffset.UtcNow.Add(options.ApiPublicationInterval); } if (tick.Frame.FrameId % (traceClientRudp ? 10 : 120) == 0) @@ -135,6 +138,7 @@ static async Task TickAsync( AetheriaDaemonHostOptions options, IAetheriaRuntimePhysicalPayloadPhysics physicalPayloadPhysics, IAetheriaRuntimeWorldPhysics worldPhysics, + AetheriaRuntimeDaemonSoaFramePublisher soaPublisher, AetheriaRuntimeDaemonFrameDocument? currentFrame, AetheriaDaemonIngressState ingressState, bool buildPublications) @@ -253,6 +257,7 @@ static async Task TickAsync( StarbridgeScenario = starbridgeScenario, StarbridgeSession = starbridgeSession, BuildPublications = buildPublications, + SoaFramePublisher = soaPublisher, OperationContext = new AetheriaRuntimeDaemonOperationContext { LoadoutTemplates = loadoutTemplates @@ -287,7 +292,7 @@ static async Task TickAsync( if (buildPublications) { - await PublishDaemonApiDocumentsAsync(node, options, result, publishTopology: true).ConfigureAwait(false); + await PublishDaemonApiDocumentsAsync(node, options, soaPublisher, result, publishTopology: true).ConfigureAwait(false); TracePhase("api-publication"); await PublishStateSurfacesAsync(node, options, result.Frame.PublishedAtUtc).ConfigureAwait(false); TracePhase("state-surfaces"); @@ -301,6 +306,7 @@ static async Task TickAsync( static AetheriaRuntimeDaemonTickResult PreparePublication( string statePath, AetheriaDaemonHostOptions options, + AetheriaRuntimeDaemonSoaFramePublisher soaPublisher, AetheriaRuntimeDaemonTickResult tick, AetheriaDaemonIngressState ingressState) { @@ -323,7 +329,8 @@ static AetheriaRuntimeDaemonTickResult PreparePublication( StarbridgeScenario = ingressState.StarbridgeScenario, StarbridgeSession = ingressState.StarbridgeSession, RenderSettings = options.RenderSettings, - SimulationSettings = options.SimulationSettings + SimulationSettings = options.SimulationSettings, + SoaFramePublisher = soaPublisher }, frame.AccountedCommandIds?.Count ?? 0); } @@ -331,9 +338,10 @@ static AetheriaRuntimeDaemonTickResult PreparePublication( static async Task PublishPreparedDocumentsAsync( AetheriaStateNode node, AetheriaDaemonHostOptions options, + AetheriaRuntimeDaemonSoaFramePublisher soaPublisher, AetheriaRuntimeDaemonTickResult publication) { - await PublishDaemonApiDocumentsAsync(node, options, publication, publishTopology: false).ConfigureAwait(false); + await PublishDaemonApiDocumentsAsync(node, options, soaPublisher, publication, publishTopology: false).ConfigureAwait(false); } static async Task RefreshControlPlaneInputsAsync( @@ -1482,6 +1490,7 @@ static bool TryGetDouble( static async Task PublishDaemonApiDocumentsAsync( AetheriaStateNode node, AetheriaDaemonHostOptions options, + AetheriaRuntimeDaemonSoaFramePublisher soaPublisher, AetheriaRuntimeDaemonTickResult result, bool publishTopology) { @@ -1491,14 +1500,18 @@ static async Task PublishDaemonApiDocumentsAsync( await node.MutableDocument(AetheriaRuntimeVerseRecordKeys.ZoneRenderLatest) .ReplaceAsync(AetheriaRuntimeGameDocuments.ZoneRender(result.Frame)) .ConfigureAwait(false); - if (result.SoaView != null && + if (result.SoaFrame != null && result.SoaView != null && string.Equals(result.SoaView.Schema, AetheriaRuntimeDaemonSchemas.SoaView, StringComparison.Ordinal)) { await node.MutableDocument(AetheriaRuntimeVerseRecordKeys.DaemonSoaViewLatest) .ReplaceAsync(result.SoaView) .ConfigureAwait(false); + var soaPublication = await soaPublisher.PublishAsync(result.SoaFrame).ConfigureAwait(false); + await node.MutableDocument(soaPublication.Body.RecordKey) + .ReplaceAsync(soaPublication.Body) + .ConfigureAwait(false); await node.MutableDocument(AetheriaRuntimeVerseRecordKeys.EveEntitySoaViewLatest) - .ReplaceAsync(AetheriaRuntimeEveEntitySoaProjection.Project(result.SoaView)) + .ReplaceAsync(soaPublication.View) .ConfigureAwait(false); } diff --git a/Aetheria.State.Verify/Program.cs b/Aetheria.State.Verify/Program.cs index b7320476b..2cb14bfc6 100644 --- a/Aetheria.State.Verify/Program.cs +++ b/Aetheria.State.Verify/Program.cs @@ -11495,6 +11495,7 @@ static void RequireDaemonVersePublication(string root) var daemonTickRunnerPath = Path.Combine(root, "Packages", "org.gamecult.aetheria.state", "Runtime", "AetheriaRuntimeDaemonTickRunner.cs"); var daemonSoaDocumentsPath = Path.Combine(root, "Packages", "org.gamecult.aetheria.state", "Runtime", "AetheriaRuntimeDaemonSoaDocuments.cs"); var daemonSoaFramePublisherPath = Path.Combine(root, "Packages", "org.gamecult.aetheria.state", "Runtime", "AetheriaRuntimeDaemonSoaFramePublisher.cs"); + var eveSoaProjectionPath = Path.Combine(root, "Packages", "org.gamecult.aetheria.state", "Runtime", "AetheriaRuntimeEveEntitySoaProjection.cs"); var assetDocumentsPath = Path.Combine(root, "Packages", "org.gamecult.aetheria.state", "Runtime", "AetheriaRuntimeAssetDocuments.cs"); var runtimeAssetsPath = Path.Combine(root, "Packages", "org.gamecult.aetheria.state", "Runtime", "AetheriaRuntimeAssets.cs"); var runtimeGameDocumentsPath = Path.Combine(root, "Packages", "org.gamecult.aetheria.state", "Runtime", "AetheriaRuntimeGameDocuments.cs"); @@ -11528,6 +11529,7 @@ static void RequireDaemonVersePublication(string root) daemonTickRunnerPath, daemonSoaDocumentsPath, daemonSoaFramePublisherPath, + eveSoaProjectionPath, assetDocumentsPath, runtimeAssetsPath, runtimeGameDocumentsPath, @@ -11569,6 +11571,7 @@ static void RequireDaemonVersePublication(string root) var daemonTickRunner = File.ReadAllText(daemonTickRunnerPath); var daemonSoaDocuments = File.ReadAllText(daemonSoaDocumentsPath); var daemonSoaFramePublisher = File.ReadAllText(daemonSoaFramePublisherPath); + var eveSoaProjection = File.ReadAllText(eveSoaProjectionPath); var assetDocuments = File.ReadAllText(assetDocumentsPath); var runtimeAssets = File.ReadAllText(runtimeAssetsPath); var runtimeGameDocuments = File.ReadAllText(runtimeGameDocumentsPath); @@ -11661,10 +11664,13 @@ static void RequireDaemonVersePublication(string root) var requiredSoaFramePublisherSymbols = new[] { - "public static class AetheriaRuntimeDaemonSoaFramePublisher", + "public sealed class AetheriaRuntimeDaemonSoaFramePublisher : IDisposable", "BuildCurrentZoneEntities(", - "AetheriaRuntimeDaemonSoaBackends.MemoryMappedFile", - "MemoryMappedFile.CreateOrOpen(", + "new CultMeshFrameBodyPublisher(", + "new CultMeshNetworkBodyPublisher(", + "CultMeshBodyPublicationValidator.Validate(publication, BodyId)", + "view.Buffers[0].BufferId, publication.BodyId", + "view.Columns.Any(column => !string.Equals(column.BufferId, publication.BodyId", "ObserverWritable = false", "AetheriaRuntimeDaemonSoaColumnKinds.EntityIndex", "AetheriaRuntimeDaemonSoaColumnKinds.Position", @@ -11682,6 +11688,45 @@ static void RequireDaemonVersePublication(string root) "Daemon SoA frame publisher no longer turns authoritative frames into observer-readable direct-memory slabs: " + string.Join(", ", missingSoaFramePublisherSymbols)); } + var forbiddenSoaPublisherSymbols = new[] + { + "MemoryMappedFile", + "RetainedMappedBuffer", + "CreateLocation(" + }; + var forbiddenSoaPublisherHits = forbiddenSoaPublisherSymbols + .Where(symbol => daemonSoaFramePublisher.Contains(symbol, StringComparison.Ordinal)) + .ToArray(); + if (forbiddenSoaPublisherHits.Length > 0) + { + throw new InvalidOperationException( + "Aetheria still owns SoA mapping location or retention instead of CultMesh: " + + string.Join(", ", forbiddenSoaPublisherHits)); + } + var forbiddenProjectionSymbols = new[] + { + "CultMeshBodyDescriptor", + "TransportKind", + "CapabilityToken", + "Backend =", + "Location =", + "StableEpoch(" + }; + var forbiddenProjectionHits = forbiddenProjectionSymbols + .Where(symbol => eveSoaProjection.Contains(symbol, StringComparison.Ordinal)) + .ToArray(); + if (forbiddenProjectionHits.Length > 0) + { + throw new InvalidOperationException( + "Eve SoA layout projection still owns transport material or producer epoch: " + + string.Join(", ", forbiddenProjectionHits)); + } + if (!daemonHostProgram.Contains("MutableDocument(soaPublication.Body.RecordKey)", StringComparison.Ordinal) || + daemonHostProgram.IndexOf("MutableDocument(soaPublication.Body.RecordKey)", StringComparison.Ordinal) > + daemonHostProgram.IndexOf("MutableDocument(AetheriaRuntimeVerseRecordKeys.EveEntitySoaViewLatest)", StringComparison.Ordinal)) + { + throw new InvalidOperationException("CultMesh body publication must precede the Eve entity SoA layout record."); + } if (File.Exists(legacyProviderAdvertisementPath)) { throw new InvalidOperationException( @@ -12027,7 +12072,7 @@ static void RequireDaemonVersePublication(string root) "CultMeshAddress", "BuildPublications", "AetheriaRuntimeDaemonCommandBoundaryDocument.Create", - "AetheriaRuntimeDaemonSoaFramePublisher.BuildCurrentZoneEntities(stateFilePath, frame)", + "soaPublisher.BuildCurrentZoneEntities(frame)", "AetheriaRuntimeDaemonProviderAdvertisementDocument.Create", "AetheriaRuntimeStarbridgeDocuments.SessionSummary(", "StarbridgeScenario", diff --git a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonSoaDocuments.cs b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonSoaDocuments.cs index ec160fa5a..c159bc45d 100644 --- a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonSoaDocuments.cs +++ b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonSoaDocuments.cs @@ -10,6 +10,7 @@ namespace GameCult.Aetheria.State.Verse public static class AetheriaRuntimeDaemonSoaBackends { public const string CultCache = "cultcache"; + public const string CultMesh = "cultmesh"; public const string MemoryMappedFile = "memory_mapped_file"; public const string SharedNativeMemory = "shared_native_memory"; } diff --git a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonSoaFramePublisher.cs b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonSoaFramePublisher.cs index bb9326dcf..df66d8ea2 100644 --- a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonSoaFramePublisher.cs +++ b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonSoaFramePublisher.cs @@ -1,39 +1,75 @@ using System; using System.Collections.Generic; -using System.IO.MemoryMappedFiles; using System.Linq; -using System.Security.Cryptography; -using System.Text; +using System.Threading.Tasks; +using GameCult.Caching; +using GameCult.Eve.Surface; +using GameCult.Mesh; #nullable enable namespace GameCult.Aetheria.State.Verse { - public static class AetheriaRuntimeDaemonSoaFramePublisher + public sealed class AetheriaRuntimeDaemonSoaFrame { - private const string BufferId = "current-zone-entities-hot"; + public AetheriaRuntimeDaemonSoaFrame(AetheriaRuntimeDaemonSoaViewDocument view, byte[] bytes) + { + View = view ?? throw new ArgumentNullException(nameof(view)); + Bytes = bytes ?? throw new ArgumentNullException(nameof(bytes)); + } + + public AetheriaRuntimeDaemonSoaViewDocument View { get; } + public byte[] Bytes { get; } + } + + public sealed class AetheriaRuntimeDaemonSoaPublication + { + public AetheriaRuntimeDaemonSoaPublication( + CultMeshBodyPublicationDocument body, + EveEntitySoaViewDocument view) + { + Body = body ?? throw new ArgumentNullException(nameof(body)); + View = view ?? throw new ArgumentNullException(nameof(view)); + } + + public CultMeshBodyPublicationDocument Body { get; } + public EveEntitySoaViewDocument View { get; } + } + + public sealed class AetheriaRuntimeDaemonSoaFramePublisher : IDisposable + { + public const string BodyId = "eve:entity-soa:aetheria.daemon:pilot"; + public const string ProducerId = "aetheria.daemon"; + public const string BodySchemaId = "gamecult.eve.entity_soa.body.v2"; + public const int LayoutVersion = 2; + private const int Capacity = 4096; private const int EntityRenderGroupId = 1; private const int FloatStride = 4; private const int Float3Stride = 12; private const int IntStride = 4; private const int ByteStride = 1; - private const int RetainedBufferCount = 4; private const string EntityProxyMeshAssetKey = "daemon.entity_proxy.mesh"; private const string EntityProxyMaterialAssetKey = "daemon.entity_proxy.material"; private const string EntityProxyMeshUri = "cultmesh://aetheria/assets/daemon/entity_proxy/mesh"; private const string EntityProxyMaterialUri = "cultmesh://aetheria/assets/daemon/entity_proxy/material"; - private static readonly object Sync = new object(); - private static readonly Dictionary RetainedBuffers = - new Dictionary(StringComparer.Ordinal); - private static long RetainedBufferUseSequence; + private readonly CultMeshFrameBodyPublisher _localPublisher; + private readonly CultMeshNetworkBodyPublisher _networkPublisher; - public static AetheriaRuntimeDaemonSoaViewDocument BuildCurrentZoneEntities( - string stateFilePath, + public AetheriaRuntimeDaemonSoaFramePublisher(CultCache cache, long producerEpoch) + { + if (cache == null) throw new ArgumentNullException(nameof(cache)); + _localPublisher = new CultMeshFrameBodyPublisher( + BodyId, BodySchemaId, LayoutVersion, Capacity, producerEpoch, + checked((int)EntityHotSlabLayout.Create(Capacity).TotalByteLength)); + _networkPublisher = new CultMeshNetworkBodyPublisher( + cache, + generation => string.Equals(generation.ProducerId, ProducerId, StringComparison.Ordinal)); + } + + public AetheriaRuntimeDaemonSoaFrame BuildCurrentZoneEntities( AetheriaRuntimeDaemonFrameDocument frame) { - if (string.IsNullOrWhiteSpace(stateFilePath)) - throw new ArgumentException("State file path must be non-empty.", nameof(stateFilePath)); if (frame == null) throw new ArgumentNullException(nameof(frame)); @@ -69,13 +105,13 @@ namespace GameCult.Aetheria.State.Verse .ToArray(); var firstPickupEntityIndex = entities.Length == 0 ? 0 : entities.Max(entity => entity.EntityIndex) + 1; var count = entities.Length + pickups.Length; + if (count > Capacity) + throw new InvalidOperationException($"Aetheria entity SoA capacity {Capacity} was exceeded by {count} rows."); var generation = Math.Max(frame.FrameId, 0); var layout = EntityHotSlabLayout.Create(count); - var location = CreateLocation(stateFilePath, frame.SessionId, generation); - - var buffer = RetainBuffer(location, layout.TotalByteLength); - WriteEntities(buffer.Accessor, layout, entities); - WritePickups(buffer.Accessor, layout, pickups, entities.Length, firstPickupEntityIndex); + var bytes = new byte[layout.TotalByteLength]; + WriteEntities(bytes, layout, entities); + WritePickups(bytes, layout, pickups, entities.Length, firstPickupEntityIndex); var view = AetheriaRuntimeDaemonSoaViewDocument.Create( string.IsNullOrWhiteSpace(frame.DaemonId) ? "aetheria-daemon" : frame.DaemonId, @@ -86,10 +122,8 @@ namespace GameCult.Aetheria.State.Verse { new AetheriaRuntimeDaemonSoaBufferDocument { - BufferId = BufferId, + BufferId = BodyId, DisplayName = "Current zone daemon entity hot slab", - Backend = AetheriaRuntimeDaemonSoaBackends.MemoryMappedFile, - Location = location, ByteOffset = 0, ByteLength = layout.TotalByteLength, Generation = generation, @@ -99,7 +133,7 @@ namespace GameCult.Aetheria.State.Verse }, layout.CreateColumns(count), layout.CreateDirtyRanges(count, generation), - backend: AetheriaRuntimeDaemonSoaBackends.MemoryMappedFile, + backend: AetheriaRuntimeDaemonSoaBackends.CultMesh, synchronizationMode: AetheriaRuntimeDaemonSoaSynchronizationModes.ImmutableFrame, renderGroups: CreateRenderGroups(entities, pickups), identities: entities.Select(entity => new AetheriaRuntimeDaemonSoaIdentityDocument @@ -126,9 +160,53 @@ namespace GameCult.Aetheria.State.Verse })) .ToArray()); - return view; + return new AetheriaRuntimeDaemonSoaFrame(view, bytes); } + public async Task PublishAsync(AetheriaRuntimeDaemonSoaFrame frame) + { + if (frame == null) throw new ArgumentNullException(nameof(frame)); + var now = DateTimeOffset.UtcNow; + if (!_localPublisher.TryPublish(frame.Bytes, now, out var local)) + throw new InvalidOperationException("CultMesh has no unleased frame slot for the Aetheria SoA generation."); + var generation = new CultMeshBodyGeneration + { + BodyId = BodyId, + ProducerId = ProducerId, + SchemaId = BodySchemaId, + LayoutVersion = LayoutVersion, + Capacity = Capacity, + ProducerEpoch = local.ProducerEpoch, + Sequence = local.Sequence, + Synchronization = local.Synchronization, + LeaseExpiresAtUnixMs = local.LeaseExpiresAtUnixMs + }; + var network = await _networkPublisher.PublishAsync(generation, frame.Bytes).ConfigureAwait(false); + var publication = new CultMeshBodyPublicationDocument + { + BodyId = BodyId, + ProducerId = ProducerId, + SchemaId = BodySchemaId, + LayoutVersion = LayoutVersion, + ByteSize = local.ByteSize, + Capacity = Capacity, + ProducerEpoch = local.ProducerEpoch, + Sequence = local.Sequence, + Synchronization = local.Synchronization, + LivenessExpiresAtUnixMs = local.LeaseExpiresAtUnixMs, + PreferredLocal = local, + NetworkFallback = network + }; + CultMeshBodyPublicationValidator.Validate(publication, BodyId); + var view = AetheriaRuntimeEveEntitySoaProjection.Project(frame.View, generation); + if (view.Buffers.Length != 1 || !string.Equals(view.Buffers[0].BufferId, publication.BodyId, StringComparison.Ordinal) || + view.Columns.Any(column => !string.Equals(column.BufferId, publication.BodyId, StringComparison.Ordinal))) + throw new InvalidOperationException("Aetheria Eve SoA layout does not reference its published logical body identity."); + return new AetheriaRuntimeDaemonSoaPublication(publication, view); + } + + public void Dispose() => _localPublisher.Dispose(); + private static IReadOnlyList CreateRenderGroups( IReadOnlyList entities, IReadOnlyList pickups) @@ -184,30 +262,30 @@ namespace GameCult.Aetheria.State.Verse } private static void WriteEntities( - MemoryMappedViewAccessor accessor, + byte[] bytes, EntityHotSlabLayout layout, IReadOnlyList entities) { for (var index = 0; index < entities.Count; index++) { var entity = entities[index]; - accessor.Write(layout.EntityIndex + index * IntStride, entity.EntityIndex); - accessor.Write(layout.CargoQuantity + index * IntStride, CountCargoUnits(entity)); - WriteFloat3(accessor, layout.Position, index, entity.PositionX, entity.PositionY, entity.PositionZ); - WriteFloat(accessor, layout.RotationRadians, index, Math.Atan2(entity.DirectionX, entity.DirectionY)); - WriteFloat3(accessor, layout.Velocity, index, entity.VelocityX, 0.0, entity.VelocityY); - WriteFloat(accessor, layout.PhysicsBodyRadius, index, 1.0); - WriteFloat(accessor, layout.PhysicsBodyMass, index, 1.0); - WriteFloat(accessor, layout.PhysicsBodyInverseMass, index, 1.0); - WriteFloat(accessor, layout.RenderScale, index, 1.0); - accessor.Write(layout.RenderVisibility + index * ByteStride, (byte)(entity.IsActive ? 1 : 0)); - accessor.Write(layout.RenderLod + index * IntStride, 0); - accessor.Write(layout.RenderGroupId + index * IntStride, (uint)EntityRenderGroupId); + WriteInt32(bytes, layout.EntityIndex + index * IntStride, entity.EntityIndex); + WriteInt32(bytes, layout.CargoQuantity + index * IntStride, CountCargoUnits(entity)); + WriteFloat3(bytes, layout.Position, index, entity.PositionX, entity.PositionY, entity.PositionZ); + WriteFloat(bytes, layout.RotationRadians, index, Math.Atan2(entity.DirectionX, entity.DirectionY)); + WriteFloat3(bytes, layout.Velocity, index, entity.VelocityX, 0.0, entity.VelocityY); + WriteFloat(bytes, layout.PhysicsBodyRadius, index, 1.0); + WriteFloat(bytes, layout.PhysicsBodyMass, index, 1.0); + WriteFloat(bytes, layout.PhysicsBodyInverseMass, index, 1.0); + WriteFloat(bytes, layout.RenderScale, index, 1.0); + bytes[checked((int)(layout.RenderVisibility + index * ByteStride))] = (byte)(entity.IsActive ? 1 : 0); + WriteInt32(bytes, layout.RenderLod + index * IntStride, 0); + WriteUInt32(bytes, layout.RenderGroupId + index * IntStride, EntityRenderGroupId); } } private static void WritePickups( - MemoryMappedViewAccessor accessor, + byte[] bytes, EntityHotSlabLayout layout, IReadOnlyList pickups, int rowOffset, @@ -217,28 +295,28 @@ namespace GameCult.Aetheria.State.Verse { var pickup = pickups[pickupRow]; var row = rowOffset + pickupRow; - accessor.Write(layout.EntityIndex + row * IntStride, firstPickupEntityIndex + pickup.PickupIndex); - accessor.Write(layout.CargoQuantity + row * IntStride, 0); - WriteFloat3(accessor, layout.Position, row, pickup.PositionX, pickup.PositionY, pickup.PositionZ); - WriteFloat(accessor, layout.RotationRadians, row, 0.0); - WriteFloat3(accessor, layout.Velocity, row, pickup.VelocityX, pickup.VelocityY, pickup.VelocityZ); - WriteFloat(accessor, layout.PhysicsBodyRadius, row, 0.5); - WriteFloat(accessor, layout.PhysicsBodyMass, row, 0.25); - WriteFloat(accessor, layout.PhysicsBodyInverseMass, row, 4.0); - WriteFloat(accessor, layout.RenderScale, row, 1.0); - accessor.Write(layout.RenderVisibility + row * ByteStride, (byte)1); - accessor.Write(layout.RenderLod + row * IntStride, 0); - accessor.Write(layout.RenderGroupId + row * IntStride, (uint)EntityRenderGroupId); + WriteInt32(bytes, layout.EntityIndex + row * IntStride, firstPickupEntityIndex + pickup.PickupIndex); + WriteInt32(bytes, layout.CargoQuantity + row * IntStride, 0); + WriteFloat3(bytes, layout.Position, row, pickup.PositionX, pickup.PositionY, pickup.PositionZ); + WriteFloat(bytes, layout.RotationRadians, row, 0.0); + WriteFloat3(bytes, layout.Velocity, row, pickup.VelocityX, pickup.VelocityY, pickup.VelocityZ); + WriteFloat(bytes, layout.PhysicsBodyRadius, row, 0.5); + WriteFloat(bytes, layout.PhysicsBodyMass, row, 0.25); + WriteFloat(bytes, layout.PhysicsBodyInverseMass, row, 4.0); + WriteFloat(bytes, layout.RenderScale, row, 1.0); + bytes[checked((int)(layout.RenderVisibility + row * ByteStride))] = 1; + WriteInt32(bytes, layout.RenderLod + row * IntStride, 0); + WriteUInt32(bytes, layout.RenderGroupId + row * IntStride, EntityRenderGroupId); } } - private static void WriteFloat(MemoryMappedViewAccessor accessor, long byteOffset, int index, double value) + private static void WriteFloat(byte[] bytes, long byteOffset, int index, double value) { - accessor.Write(byteOffset + index * FloatStride, IsFinite(value) ? (float)value : 0.0f); + WriteBytes(bytes, byteOffset + index * FloatStride, BitConverter.GetBytes(IsFinite(value) ? (float)value : 0.0f)); } private static void WriteFloat3( - MemoryMappedViewAccessor accessor, + byte[] bytes, long byteOffset, int index, double x, @@ -246,11 +324,20 @@ namespace GameCult.Aetheria.State.Verse double z) { var elementOffset = byteOffset + index * Float3Stride; - accessor.Write(elementOffset, IsFinite(x) ? (float)x : 0.0f); - accessor.Write(elementOffset + FloatStride, IsFinite(y) ? (float)y : 0.0f); - accessor.Write(elementOffset + FloatStride * 2, IsFinite(z) ? (float)z : 0.0f); + WriteFloat(bytes, elementOffset, 0, x); + WriteFloat(bytes, elementOffset + FloatStride, 0, y); + WriteFloat(bytes, elementOffset + FloatStride * 2, 0, z); } + private static void WriteInt32(byte[] bytes, long offset, int value) => + WriteBytes(bytes, offset, BitConverter.GetBytes(value)); + + private static void WriteUInt32(byte[] bytes, long offset, int value) => + WriteBytes(bytes, offset, BitConverter.GetBytes((uint)value)); + + private static void WriteBytes(byte[] destination, long offset, byte[] source) => + Buffer.BlockCopy(source, 0, destination, checked((int)offset), source.Length); + private static bool IsFinite(double value) { return !double.IsNaN(value) && !double.IsInfinity(value); @@ -265,76 +352,6 @@ namespace GameCult.Aetheria.State.Verse .Sum(slot => Math.Max(0, slot.Item.Quantity)); } - private static RetainedMappedBuffer RetainBuffer(string location, long byteLength) - { - lock (Sync) - { - if (RetainedBuffers.TryGetValue(location, out var existing)) - { - existing.MarkUsed(++RetainedBufferUseSequence); - return existing; - } - - var memory = MemoryMappedFile.CreateOrOpen(location, byteLength, MemoryMappedFileAccess.ReadWrite); - var accessor = memory.CreateViewAccessor(0, byteLength, MemoryMappedFileAccess.ReadWrite); - var buffer = new RetainedMappedBuffer(memory, accessor, ++RetainedBufferUseSequence); - RetainedBuffers[location] = buffer; - TrimRetainedBuffers(location); - return buffer; - } - } - - private static void TrimRetainedBuffers(string retainedLocation) - { - if (RetainedBuffers.Count <= RetainedBufferCount) - return; - - foreach (var key in RetainedBuffers - .Where(pair => !string.Equals(pair.Key, retainedLocation, StringComparison.Ordinal)) - .OrderBy(pair => pair.Value.LastUsedSequence) - .Select(pair => pair.Key) - .Take(RetainedBuffers.Count - RetainedBufferCount) - .ToArray()) - { - RetainedBuffers[key].Dispose(); - RetainedBuffers.Remove(key); - } - } - - private static string CreateLocation(string stateFilePath, string sessionId, long generation) - { - using var sha = SHA256.Create(); - var identity = $"{stateFilePath}|{sessionId}|{generation}"; - var hash = sha.ComputeHash(Encoding.UTF8.GetBytes(identity)); - return "Aetheria.Daemon.Soa." + BitConverter.ToString(hash, 0, 12).Replace("-", ""); - } - - private sealed class RetainedMappedBuffer : IDisposable - { - private readonly MemoryMappedFile _memory; - public RetainedMappedBuffer(MemoryMappedFile memory, MemoryMappedViewAccessor accessor, long lastUsedSequence) - { - _memory = memory; - Accessor = accessor; - LastUsedSequence = lastUsedSequence; - } - - public MemoryMappedViewAccessor Accessor { get; } - - public long LastUsedSequence { get; private set; } - - public void MarkUsed(long sequence) - { - LastUsedSequence = sequence; - } - - public void Dispose() - { - Accessor.Dispose(); - _memory.Dispose(); - } - } - private readonly struct EntityHotSlabLayout { private EntityHotSlabLayout( @@ -460,7 +477,7 @@ namespace GameCult.Aetheria.State.Verse { ColumnId = columnId, Kind = kind, - BufferId = BufferId, + BufferId = BodyId, ScalarType = scalarType, ByteOffset = byteOffset, ElementStride = stride, diff --git a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonTickRunner.cs b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonTickRunner.cs index 231390b42..ed3e61eb5 100644 --- a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonTickRunner.cs +++ b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeDaemonTickRunner.cs @@ -41,6 +41,7 @@ namespace GameCult.Aetheria.State.Verse public bool AdvanceSimulation { get; set; } = true; public int SimulationStepCount { get; set; } = 1; public bool BuildPublications { get; set; } = true; + public AetheriaRuntimeDaemonSoaFramePublisher? SoaFramePublisher { get; set; } } public sealed class AetheriaRuntimeDaemonTickResult @@ -49,7 +50,7 @@ namespace GameCult.Aetheria.State.Verse AetheriaRuntimeRunCheckpointCommit run, AetheriaRuntimeDaemonOperationResult operationResult, AetheriaRuntimeDaemonFrameDocument frame, - AetheriaRuntimeDaemonSoaViewDocument? soaView = null, + AetheriaRuntimeDaemonSoaFrame? soaFrame = null, AetheriaRuntimeDaemonProviderAdvertisementDocument? providerAdvertisement = null, AetheriaRuntimeDaemonHealthDocument? health = null, AetheriaRuntimeDaemonCommandBoundaryDocument? commandBoundary = null, @@ -66,7 +67,7 @@ namespace GameCult.Aetheria.State.Verse Array.Empty(), Array.Empty()); Frame = frame ?? new AetheriaRuntimeDaemonFrameDocument(); - SoaView = soaView; + SoaFrame = soaFrame; ProviderAdvertisement = providerAdvertisement; Health = health; CommandBoundary = commandBoundary; @@ -81,7 +82,8 @@ namespace GameCult.Aetheria.State.Verse public AetheriaRuntimeRunCheckpointCommit Run { get; } public AetheriaRuntimeDaemonOperationResult OperationResult { get; } public AetheriaRuntimeDaemonFrameDocument Frame { get; } - public AetheriaRuntimeDaemonSoaViewDocument? SoaView { get; } + public AetheriaRuntimeDaemonSoaFrame? SoaFrame { get; } + public AetheriaRuntimeDaemonSoaViewDocument? SoaView => SoaFrame?.View; public AetheriaRuntimeDaemonProviderAdvertisementDocument? ProviderAdvertisement { get; } public AetheriaRuntimeDaemonHealthDocument? Health { get; } public AetheriaRuntimeDaemonCommandBoundaryDocument? CommandBoundary { get; } @@ -252,7 +254,9 @@ namespace GameCult.Aetheria.State.Verse AetheriaRuntimeDaemonTickOptions options, int observedCommandCount) { - var soaView = AetheriaRuntimeDaemonSoaFramePublisher.BuildCurrentZoneEntities(stateFilePath, frame); + var soaPublisher = options.SoaFramePublisher ?? + throw new InvalidOperationException("The daemon-lifetime Aetheria SoA publisher is required."); + var soaFrame = soaPublisher.BuildCurrentZoneEntities(frame); var commandBoundary = AetheriaRuntimeDaemonCommandBoundaryDocument.Create(options.DaemonId); var providerAdvertisement = AetheriaRuntimeDaemonProviderAdvertisementDocument.Create( stateFilePath, @@ -305,7 +309,7 @@ namespace GameCult.Aetheria.State.Verse operationResult.Run, operationResult, frame, - soaView, + soaFrame, providerAdvertisement, health, commandBoundary, diff --git a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeEveEntitySoaProjection.cs b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeEveEntitySoaProjection.cs index 589855180..aa8e650c7 100644 --- a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeEveEntitySoaProjection.cs +++ b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeEveEntitySoaProjection.cs @@ -9,46 +9,29 @@ namespace GameCult.Aetheria.State.Verse { public static class AetheriaRuntimeEveEntitySoaProjection { - public static EveEntitySoaViewDocument Project(AetheriaRuntimeDaemonSoaViewDocument source) + public static EveEntitySoaViewDocument Project( + AetheriaRuntimeDaemonSoaViewDocument source, + CultMeshBodyGeneration generation) { if (source == null) throw new ArgumentNullException(nameof(source)); - var primaryBuffer = (source.Buffers ?? Array.Empty()).FirstOrDefault(); + if (generation == null) throw new ArgumentNullException(nameof(generation)); return new EveEntitySoaViewDocument { - ProviderId = "aetheria.daemon", + ProviderId = generation.ProducerId, ViewId = "pilot", FrameId = source.FrameId, - Generation = source.Generation, PublishedAtUtc = source.PublishedAtUtc, - Backend = source.Backend, - SynchronizationMode = source.SynchronizationMode, - Body = primaryBuffer == null ? null : new CultMeshBodyDescriptor - { - BodyId = $"eve:entity-soa:{source.DaemonId}:{source.SessionId}:pilot", - SchemaId = EveEntitySoaViewDocument.SchemaId + ".body.v1", - LayoutVersion = 1, - ByteSize = primaryBuffer.ByteLength, - Capacity = (source.Columns ?? Array.Empty()) - .Select(column => column.ElementCount) - .DefaultIfEmpty(0) - .Max(), - ProducerEpoch = StableEpoch(source.SessionId), - Sequence = source.Generation, - AccessMode = CultMeshBodyAccessMode.ReadOnly, - Synchronization = CultMeshBodySynchronization.ImmutableSequence, - LeaseExpiresAtUnixMs = DateTimeOffset.UtcNow.AddSeconds(5).ToUnixTimeMilliseconds(), - TransportKind = CultMeshBodyTransportKind.SharedMemory, - CapabilityToken = primaryBuffer.Location - }, + BodySchemaId = generation.SchemaId, + LayoutVersion = generation.LayoutVersion, + ProducerEpoch = generation.ProducerEpoch, + Sequence = generation.Sequence, + Capacity = generation.Capacity, Buffers = (source.Buffers ?? Array.Empty()) .Select(buffer => new EveEntitySoaBuffer { BufferId = buffer.BufferId, - Backend = buffer.Backend, - Location = buffer.Location, ByteOffset = buffer.ByteOffset, - ByteLength = buffer.ByteLength, - Generation = buffer.Generation + ByteLength = buffer.ByteLength }).ToArray(), Columns = (source.Columns ?? Array.Empty()) .Select(column => new EveEntitySoaColumn @@ -69,7 +52,7 @@ namespace GameCult.Aetheria.State.Verse ColumnId = range.ColumnId, StartIndex = range.StartIndex, Count = range.Count, - Generation = range.Generation + Sequence = generation.Sequence }).ToArray(), RenderGroups = (source.RenderGroups ?? Array.Empty()) .Select(group => new EveEntityRenderGroup @@ -92,11 +75,11 @@ namespace GameCult.Aetheria.State.Verse Lod = group.Lod }).ToArray(), Identities = (source.Identities ?? Array.Empty()) - .Select(identity => new EveEntitySoaIdentity + .Select(identity => new EveEntityIdentity { - EntityIndex = identity.EntityIndex, + Index = identity.EntityIndex, EntityId = identity.EntityId, - Kind = identity.Kind, + EntityKind = identity.Kind, Label = identity.Label, Faction = identity.Faction, Selectable = identity.Selectable, @@ -106,20 +89,5 @@ namespace GameCult.Aetheria.State.Verse }; } - private static long StableEpoch(string value) - { - unchecked - { - const long offset = 1469598103934665603; - const long prime = 1099511628211; - var hash = offset; - foreach (var character in value ?? string.Empty) - { - hash ^= character; - hash *= prime; - } - return hash & long.MaxValue; - } - } } } diff --git a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeVerseClient.cs b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeVerseClient.cs index 2343b6379..36f9d7ca0 100644 --- a/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeVerseClient.cs +++ b/Packages/org.gamecult.aetheria.state/Runtime/AetheriaRuntimeVerseClient.cs @@ -185,6 +185,10 @@ namespace GameCult.Aetheria.State.Verse typeof(EveCommandReceiptDocument), typeof(EveAssetCatalogDocument), typeof(EveEntitySoaViewDocument), + typeof(CultMeshBodyPublicationDocument), + typeof(CultMeshNetworkBodyDocument), + typeof(CultMeshCdnArtifactManifest), + typeof(CultMeshCdnArtifactChunk), typeof(AetheriaRuntimeDaemonCommandDocument), typeof(AetheriaRuntimeEveCommandDocument), typeof(AetheriaRuntimeCommittedCommandFactDocument)