From 97b839160850ad5dbe423fd21f70b4924d972eaa Mon Sep 17 00:00:00 2001 From: dingo Date: Sat, 21 Mar 2026 09:49:08 -0400 Subject: [PATCH] Live-star skybox: game activity feed + procedural star sky Server: - GameActivityRegistry singleton tracks subscribed clients - game.subscribe_activity handler: registers client, returns active session IDs - game.unsubscribe_activity handler: deregisters client - BroadcastActivityAsync helper in GameHandlerBase (mirrors spectator push pattern) - GamePlaceArchSpiritHandler broadcasts "started" when both players have placed - FinalizeGameAsync broadcasts "ended" to all subscribers Client: - Settings.skybox_mode: "live" | "cdn" | "off" (default: "live"), persisted to cfg - Game.game_activity signal forwarded from game.activity push - game_screen.gd: live mode sets near-black procedural sky; subscribes to activity feed; each active session is an emissive sphere star (280-unit radius, blue-white) that fades in on start, twinkles via sine tween, and flash-explodes on end - CDN and Off modes preserved; hot-swap supported mid-game via Settings.settings_changed - InGameSettings: SkyboxModeOption OptionButton (Live / CDN / Off) Generated with [Claude Code](https://claude.ai/code) via [Happy](https://happy.engineering) Co-Authored-By: Claude Co-Authored-By: Happy --- Client/origin-client/autoloads/Game.gd | 11 ++ Client/origin-client/autoloads/Settings.gd | 13 ++ .../scenes/game/InGameSettings.tscn | 26 ++- .../origin-client/scenes/game/game_screen.gd | 179 +++++++++++++++++- .../scenes/game/in_game_settings.gd | 10 +- Server/src/SOR.Game/GameActivityRegistry.cs | 28 +++ Server/src/SOR.Game/GameMessages.cs | 19 ++ .../src/SOR.Game/Handlers/GameHandlerBase.cs | 20 ++ .../Handlers/GamePlaceArchSpiritHandler.cs | 5 +- .../Handlers/GameSubscribeActivityHandler.cs | 47 +++++ .../GameUnsubscribeActivityHandler.cs | 26 +++ Server/src/SOR.Game/ServiceRegistration.cs | 7 + 12 files changed, 376 insertions(+), 15 deletions(-) create mode 100644 Server/src/SOR.Game/GameActivityRegistry.cs create mode 100644 Server/src/SOR.Game/Handlers/GameSubscribeActivityHandler.cs create mode 100644 Server/src/SOR.Game/Handlers/GameUnsubscribeActivityHandler.cs diff --git a/Client/origin-client/autoloads/Game.gd b/Client/origin-client/autoloads/Game.gd index 6119c7e..582fe2f 100644 --- a/Client/origin-client/autoloads/Game.gd +++ b/Client/origin-client/autoloads/Game.gd @@ -37,6 +37,11 @@ signal inactive_warning(session_id: String) ## Both players must wait — no concede or force-concede is allowed. signal both_idle_warning(session_id: String) +## Emitted when a game session starts or ends (from game.activity pushes). +## Used by game_screen.gd to drive the live-star skybox. +## event_type: "started" | "ended" +signal game_activity(event_type: String, session_id: String) + # ── State ───────────────────────────────────────────────────────────────────── var session_id : String = "" @@ -555,3 +560,9 @@ func _on_server_push(type: String, payload: Variant) -> void: var sid : String = str(d.get("sessionId", "")) print("[Game] PUSH both_idle_warning session=", sid) both_idle_warning.emit(sid) + + "game.activity": + var d := payload as Dictionary + var ev_type : String = str(d.get("eventType", "")) + var ev_sid : String = str(d.get("sessionId", "")) + game_activity.emit(ev_type, ev_sid) diff --git a/Client/origin-client/autoloads/Settings.gd b/Client/origin-client/autoloads/Settings.gd index 422d268..5a75707 100644 --- a/Client/origin-client/autoloads/Settings.gd +++ b/Client/origin-client/autoloads/Settings.gd @@ -12,6 +12,7 @@ extends Node const SAVE_PATH := "user://settings.cfg" const SECTION := "audio" const SECTION_GAMEPLAY := "gameplay" +const SECTION_VISUAL := "visual" ## Audio bus names as configured in the Godot project. const BUS_MUSIC := "Music" @@ -54,6 +55,16 @@ var camera_follow_unit : bool = true : _save() settings_changed.emit() +## Skybox display mode in gameplay scenes. +## "live" — near-black sky with emissive stars; each star = an active game session. +## "cdn" — server-configured panoramic or animated skybox image. +## "off" — default procedural sky (dark blue gradient). +var skybox_mode : String = "live" : + set(v): + skybox_mode = v + _save() + settings_changed.emit() + # ── Lifecycle ───────────────────────────────────────────────────────────────── func _ready() -> void: @@ -88,6 +99,7 @@ func _load() -> void: sfx_volume = float(cfg.get_value(SECTION, "sfx_volume", 1.0)) sfx_muted = bool(cfg.get_value(SECTION, "sfx_muted", false)) camera_follow_unit = bool(cfg.get_value(SECTION_GAMEPLAY, "camera_follow_unit", true)) + skybox_mode = str(cfg.get_value(SECTION_VISUAL, "skybox_mode", "live")) func _save() -> void: @@ -97,4 +109,5 @@ func _save() -> void: cfg.set_value(SECTION, "sfx_volume", sfx_volume) cfg.set_value(SECTION, "sfx_muted", sfx_muted) cfg.set_value(SECTION_GAMEPLAY, "camera_follow_unit", camera_follow_unit) + cfg.set_value(SECTION_VISUAL, "skybox_mode", skybox_mode) cfg.save(SAVE_PATH) diff --git a/Client/origin-client/scenes/game/InGameSettings.tscn b/Client/origin-client/scenes/game/InGameSettings.tscn index a309d8c..22c32bd 100644 --- a/Client/origin-client/scenes/game/InGameSettings.tscn +++ b/Client/origin-client/scenes/game/InGameSettings.tscn @@ -9,9 +9,9 @@ anchor_top = 0.5 anchor_right = 0.5 anchor_bottom = 0.5 offset_left = -220.0 -offset_top = -260.0 +offset_top = -278.0 offset_right = 220.0 -offset_bottom = 260.0 +offset_bottom = 278.0 grow_horizontal = 2 grow_vertical = 2 script = ExtResource("1_script") @@ -108,6 +108,28 @@ unique_name_in_owner = true layout_mode = 2 text = "Center camera on selected unit" +[node name="SkyboxRow" type="HBoxContainer" parent="MarginContainer/VBoxContainer"] +layout_mode = 2 + +[node name="SkyboxLabel" type="Label" parent="MarginContainer/VBoxContainer/SkyboxRow"] +layout_mode = 2 +custom_minimum_size = Vector2(80, 0) +text = "Skybox" +vertical_alignment = 1 + +[node name="SkyboxModeOption" type="OptionButton" parent="MarginContainer/VBoxContainer/SkyboxRow"] +unique_name_in_owner = true +layout_mode = 2 +size_flags_horizontal = 3 +item_count = 3 +popup/item_0/text = "Live (Stars)" +popup/item_0/id = 0 +popup/item_1/text = "CDN" +popup/item_1/id = 1 +popup/item_2/text = "Off" +popup/item_2/id = 2 +selected = 0 + [node name="HSeparator3" type="HSeparator" parent="MarginContainer/VBoxContainer"] layout_mode = 2 diff --git a/Client/origin-client/scenes/game/game_screen.gd b/Client/origin-client/scenes/game/game_screen.gd index e8ac24b..57cb98d 100644 --- a/Client/origin-client/scenes/game/game_screen.gd +++ b/Client/origin-client/scenes/game/game_screen.gd @@ -162,6 +162,7 @@ var _skybox_sky : Sky = null # the Sky object created in _setup_enviro var _skybox_frames : Array = [] # Array[ImageTexture] for animated skybox frames var _skybox_frame_idx : int = 0 var _skybox_timer : Timer = null +var _stars : Dictionary = {} # sessionId (String) → MeshInstance3D (live mode) # ── Animation / facing state ─────────────────────────────────────────────────── var _local_is_p1 : bool = false # true when Auth.user_id == playerOneAccountId @@ -262,6 +263,16 @@ func _exit_tree() -> void: Game.inactive_warning.disconnect(_on_inactive_warning) if Game.both_idle_warning.is_connected(_on_both_idle_warning): Game.both_idle_warning.disconnect(_on_both_idle_warning) + if Game.game_activity.is_connected(_on_game_activity): + Game.game_activity.disconnect(_on_game_activity) + if Settings.settings_changed.is_connected(_on_skybox_setting_changed): + Settings.settings_changed.disconnect(_on_skybox_setting_changed) + # Unsubscribe from activity feed and free star nodes. + if Settings.skybox_mode == "live": + Network.request("game.unsubscribe_activity", {}, + func(_t: String, _r: Variant) -> void: pass, + func(_c: String, _m: String) -> void: pass) + _clear_stars() # Remove chat overlay added to the viewport root. var root := get_tree().get_root() for child in root.get_children(): @@ -299,20 +310,168 @@ func _setup_spectator_ui() -> void: # ── Environment ─────────────────────────────────────────────────────────────── func _setup_environment() -> void: - var env := Environment.new() - _skybox_sky = Sky.new() - var proc := ProceduralSkyMaterial.new() - proc.sky_top_color = Color(0.08, 0.10, 0.20) - proc.sky_horizon_color = Color(0.28, 0.38, 0.55) - proc.ground_bottom_color = Color(0.373, 0.374, 0.484, 1.0) - proc.ground_horizon_color = Color(0.20, 0.28, 0.38) - _skybox_sky.sky_material = proc + var env := Environment.new() + _skybox_sky = Sky.new() env.background_mode = Environment.BG_SKY env.sky = _skybox_sky env.ambient_light_source = Environment.AMBIENT_SOURCE_SKY - env.ambient_light_energy = 0.6 $WorldEnvironment.environment = env - _fetch_skybox() + + match Settings.skybox_mode: + "live": + _setup_live_skybox(env) + "cdn": + _setup_procedural_sky(env) + _fetch_skybox() + _: # "off" or any unknown value + _setup_procedural_sky(env) + + # Re-apply skybox whenever the user changes the setting mid-game. + if not Settings.settings_changed.is_connected(_on_skybox_setting_changed): + Settings.settings_changed.connect(_on_skybox_setting_changed) + +## Dark blue procedural sky — shown for "off" mode and as the CDN loading placeholder. +func _setup_procedural_sky(env: Environment = null) -> void: + if _skybox_timer != null: + _skybox_timer.queue_free() + _skybox_timer = null + _skybox_frames.clear() + var proc := ProceduralSkyMaterial.new() + proc.sky_top_color = Color(0.08, 0.10, 0.20) + proc.sky_horizon_color = Color(0.28, 0.38, 0.55) + proc.ground_bottom_color = Color(0.373, 0.374, 0.484, 1.0) + proc.ground_horizon_color = Color(0.20, 0.28, 0.38) + if is_instance_valid(_skybox_sky): + _skybox_sky.sky_material = proc + var e : Environment = env if env != null else $WorldEnvironment.environment + if e != null: + e.ambient_light_energy = 0.6 + +## Near-black star sky — shown for "live" mode. +## Subscribes to game.activity pushes to add/remove star nodes. +func _setup_live_skybox(env: Environment) -> void: + _clear_stars() + var proc := ProceduralSkyMaterial.new() + proc.sky_top_color = Color(0.0, 0.0, 0.02) + proc.sky_horizon_color = Color(0.01, 0.0, 0.03) + proc.ground_bottom_color = Color(0.0, 0.0, 0.01) + proc.ground_horizon_color = Color(0.01, 0.01, 0.02) + if is_instance_valid(_skybox_sky): + _skybox_sky.sky_material = proc + env.ambient_light_energy = 0.25 + + if not Game.game_activity.is_connected(_on_game_activity): + Game.game_activity.connect(_on_game_activity) + + Network.request("game.subscribe_activity", {}, + func(_type: String, resp: Variant) -> void: + var ids : Array = (resp as Dictionary).get("activeSessionIds", []) + for sid in ids: + _add_star(str(sid), true), + func(code: String, msg: String) -> void: + push_warning("[GameScreen] subscribe_activity failed — %s: %s" % [code, msg])) + +func _on_skybox_setting_changed() -> void: + # Tear down current live subscriptions / stars before switching mode. + if Game.game_activity.is_connected(_on_game_activity): + Game.game_activity.disconnect(_on_game_activity) + _clear_stars() + if _skybox_timer != null: + _skybox_timer.queue_free() + _skybox_timer = null + _skybox_frames.clear() + + var env := $WorldEnvironment.environment as Environment + match Settings.skybox_mode: + "live": + _setup_live_skybox(env) + "cdn": + _setup_procedural_sky() + _fetch_skybox() + _: + _setup_procedural_sky() + +func _on_game_activity(event_type: String, session_id: String) -> void: + match event_type: + "started": _add_star(session_id, false) + "ended": _remove_star(session_id) + +# ── Live-star skybox helpers ─────────────────────────────────────────────────── + +## Returns a deterministic spherical position from a session ID hash. +func _session_star_pos(session_id: String) -> Vector3: + var rng := RandomNumberGenerator.new() + rng.seed = session_id.hash() + var theta := rng.randf() * TAU + var phi := rng.randf_range(0.15, 0.85) * PI # avoid poles + var r := 280.0 + return Vector3(r * sin(phi) * cos(theta), r * cos(phi), r * sin(phi) * sin(theta)) + +## Adds an emissive sphere star for the given session. instant=true skips the fade-in. +func _add_star(session_id: String, instant: bool) -> void: + if _stars.has(session_id): + return + var mesh := MeshInstance3D.new() + var sphere := SphereMesh.new() + sphere.radius = 0.6 + sphere.height = 1.2 + sphere.radial_segments = 6 + sphere.rings = 4 + mesh.mesh = sphere + var mat := StandardMaterial3D.new() + mat.shading_mode = BaseMaterial3D.SHADING_MODE_UNSHADED + mat.emission_enabled = true + mat.emission = Color(0.85, 0.90, 1.0) # blue-white + mat.emission_energy_multiplier = 0.0 + mesh.material_override = mat + mesh.global_position = _session_star_pos(session_id) + add_child(mesh) + _stars[session_id] = mesh + + if instant: + mat.emission_energy_multiplier = 1.0 + _start_star_twinkle(mesh) + else: + var tw := create_tween() + tw.tween_property(mat, "emission_energy_multiplier", 1.0, 2.0) \ + .set_trans(Tween.TRANS_CUBIC) + tw.finished.connect(func() -> void: _start_star_twinkle(mesh)) + +## Starts the looping gentle brightness oscillation on a star. +func _start_star_twinkle(mesh: MeshInstance3D) -> void: + if not is_instance_valid(mesh): + return + var mat := mesh.material_override as StandardMaterial3D + var rng := RandomNumberGenerator.new() + rng.seed = hash(mesh.global_position.x) + var period := rng.randf_range(2.0, 5.5) + var tw := create_tween().set_loops() + tw.tween_property(mat, "emission_energy_multiplier", 1.6, period * 0.5) \ + .set_trans(Tween.TRANS_SINE) + tw.tween_property(mat, "emission_energy_multiplier", 0.6, period * 0.5) \ + .set_trans(Tween.TRANS_SINE) + +## Removes a star with a bright explosion flash then fade. +func _remove_star(session_id: String) -> void: + if not _stars.has(session_id): + return + var mesh : MeshInstance3D = _stars[session_id] + _stars.erase(session_id) + var mat := mesh.material_override as StandardMaterial3D + var tw := create_tween() + tw.tween_property(mat, "emission_energy_multiplier", 12.0, 0.12) + tw.tween_property(mat, "emission_energy_multiplier", 0.0, 1.8) \ + .set_trans(Tween.TRANS_EXPO) + tw.finished.connect(mesh.queue_free) + +## Queue-frees all active star nodes (called on mode switch or scene exit). +func _clear_stars() -> void: + for mesh in _stars.values(): + if is_instance_valid(mesh): + mesh.queue_free() + _stars.clear() + +# ── CDN skybox helpers ───────────────────────────────────────────────────────── func _fetch_skybox() -> void: Network.request("content.get_skybox_config", {}, diff --git a/Client/origin-client/scenes/game/in_game_settings.gd b/Client/origin-client/scenes/game/in_game_settings.gd index 7be5ee4..e761148 100644 --- a/Client/origin-client/scenes/game/in_game_settings.gd +++ b/Client/origin-client/scenes/game/in_game_settings.gd @@ -6,8 +6,9 @@ extends PanelContainer @onready var _music_mute : CheckButton = %MusicMute @onready var _sfx_slider : HSlider = %SfxSlider @onready var _sfx_mute : CheckButton = %SfxMute -@onready var _cam_follow : CheckButton = %CameraFollowUnit -@onready var _sync_btn : Button = %SyncBtn +@onready var _cam_follow : CheckButton = %CameraFollowUnit +@onready var _skybox_opt : OptionButton = %SkyboxModeOption +@onready var _sync_btn : Button = %SyncBtn @onready var _concede_btn : Button = %ConcedeBtn @onready var _confirm_row : HBoxContainer = %ConcedeConfirmRow @onready var _confirm_yes : Button = %ConcedeYes @@ -25,6 +26,7 @@ func _ready() -> void: _sfx_slider.value_changed.connect(_on_sfx_volume_changed) _sfx_mute.toggled.connect(_on_sfx_mute_toggled) _cam_follow.toggled.connect(func(v: bool) -> void: Settings.camera_follow_unit = v) + _skybox_opt.item_selected.connect(_on_skybox_mode_changed) _sync_btn.pressed.connect(_on_sync_pressed) _concede_btn.pressed.connect(_on_concede_pressed) @@ -53,6 +55,7 @@ func _sync_from_settings() -> void: _sfx_slider.set_value_no_signal(Settings.sfx_volume) _sfx_mute.set_pressed_no_signal(Settings.sfx_muted) _cam_follow.set_pressed_no_signal(Settings.camera_follow_unit) + _skybox_opt.selected = ["live", "cdn", "off"].find(Settings.skybox_mode) _music_slider.modulate.a = 0.4 if Settings.music_muted else 1.0 _sfx_slider.modulate.a = 0.4 if Settings.sfx_muted else 1.0 @@ -79,6 +82,9 @@ func _on_sync_pressed() -> void: _sync_btn.text = "Request Sync" _sync_btn.disabled = false) +func _on_skybox_mode_changed(idx: int) -> void: + Settings.skybox_mode = (["live", "cdn", "off"] as Array)[idx] + func _on_concede_pressed() -> void: _concede_btn.visible = false _confirm_row.visible = true diff --git a/Server/src/SOR.Game/GameActivityRegistry.cs b/Server/src/SOR.Game/GameActivityRegistry.cs new file mode 100644 index 0000000..7b1f9d1 --- /dev/null +++ b/Server/src/SOR.Game/GameActivityRegistry.cs @@ -0,0 +1,28 @@ +namespace SOR.Game; + +using System.Collections.Concurrent; +using System.Collections.Generic; + +/// +/// In-memory registry of client connections that have subscribed to game activity +/// events (session started / ended). Used to drive the live-star skybox feature. +/// +/// Access via from static helpers (e.g. GameHandlerBase) +/// that cannot use constructor injection. The singleton is initialised when the +/// DI container constructs the registered singleton instance. +/// +public sealed class GameActivityRegistry +{ + /// The singleton set by the constructor when DI builds this instance. + public static GameActivityRegistry? Instance { get; private set; } + + private readonly ConcurrentDictionary _subscribers = new(); + + public GameActivityRegistry() { Instance = this; } + + public void Subscribe(string userId) => _subscribers.TryAdd(userId, 0); + public void Unsubscribe(string userId) => _subscribers.TryRemove(userId, out _); + + /// Snapshot of current subscriber user IDs (safe to enumerate). + public IReadOnlyList Subscribers => [.. _subscribers.Keys]; +} diff --git a/Server/src/SOR.Game/GameMessages.cs b/Server/src/SOR.Game/GameMessages.cs index c00ef66..878383e 100644 --- a/Server/src/SOR.Game/GameMessages.cs +++ b/Server/src/SOR.Game/GameMessages.cs @@ -461,6 +461,25 @@ public sealed record GameMetaDelta( string? ActivePlayerAccountId, int? TurnNumber); +// ── Skybox activity feed ─────────────────────────────────────────────────────── + +/// +/// Subscribe to game activity events so the client can animate its live star skybox. +/// The response includes IDs of currently active sessions to initialise the star field. +/// +public sealed record GameSubscribeActivityRequest; +public sealed record GameSubscribeActivityResponse(IReadOnlyList ActiveSessionIds); + +/// Unsubscribe from game activity events. +public sealed record GameUnsubscribeActivityRequest; +public sealed record GameUnsubscribeActivityResponse; + +/// +/// Pushed to all subscribed clients when a game session starts or ends. +/// EventType: "started" | "ended" +/// +public sealed record GameActivityPush(string EventType, string SessionId); + // ── DTOs ───────────────────────────────────────────────────────────────────── /// diff --git a/Server/src/SOR.Game/Handlers/GameHandlerBase.cs b/Server/src/SOR.Game/Handlers/GameHandlerBase.cs index 57c9d4b..2250599 100644 --- a/Server/src/SOR.Game/Handlers/GameHandlerBase.cs +++ b/Server/src/SOR.Game/Handlers/GameHandlerBase.cs @@ -89,6 +89,23 @@ internal abstract class GameHandlerBase await gameDb.Database.CommitTransactionAsync(ct); } + /// + /// Broadcast a game activity event (session started / ended) to all subscribed clients. + /// Used by the live-star skybox feature. Best-effort; subscriber list is in-memory only. + /// + internal static async Task BroadcastActivityAsync( + IClientPush clientPush, + string eventType, + Guid sessionId, + CancellationToken ct) + { + var subs = GameActivityRegistry.Instance?.Subscribers; + if (subs is null || subs.Count == 0) return; + var push = ServerMessage.Push("game.activity", + new GameActivityPush(eventType, sessionId.ToString())); + await Task.WhenAll(subs.Select(uid => clientPush.PushAsync(uid, push, ct))); + } + /// /// Push the updated game state to both players and any current spectators. /// When is supplied a structured delta (game.state_delta) @@ -270,6 +287,9 @@ internal abstract class GameHandlerBase await Task.WhenAll(gameOverTasks); + // Notify skybox activity subscribers that this game has ended. + await BroadcastActivityAsync(clientPush, "ended", session.Id, ct); + // Publish inter-service event so ChatLifecycleHostedService archives the match channel. await eventBus.PublishAsync(NatsSubjects.GameEnded, new GameEndedEvent( diff --git a/Server/src/SOR.Game/Handlers/GamePlaceArchSpiritHandler.cs b/Server/src/SOR.Game/Handlers/GamePlaceArchSpiritHandler.cs index 75ec2d7..48fa69a 100644 --- a/Server/src/SOR.Game/Handlers/GamePlaceArchSpiritHandler.cs +++ b/Server/src/SOR.Game/Handlers/GamePlaceArchSpiritHandler.cs @@ -58,10 +58,13 @@ internal sealed class GamePlaceArchSpiritHandler : GameHandlerBase, IMessageHand await PushStateToPlayersAsync(_clientPush, session, newState, ct, state); - // Start the turn timer once both players have placed and turn 1 begins. + // Start the turn timer and notify skybox activity subscribers once both players have placed. if (bothPlaced) + { _timerService.ResetTimer(session.Id, newState.Rules.TurnTimerSeconds, newState.Rules.TimeLimitMinutes, session.CreatedAt); + await BroadcastActivityAsync(_clientPush, "started", session.Id, ct); + } return ServerMessage.Reply("game.place_arch_spirit.ack", message.Seq, new GamePlaceArchSpiritResponse(dto)); diff --git a/Server/src/SOR.Game/Handlers/GameSubscribeActivityHandler.cs b/Server/src/SOR.Game/Handlers/GameSubscribeActivityHandler.cs new file mode 100644 index 0000000..1bbcfc8 --- /dev/null +++ b/Server/src/SOR.Game/Handlers/GameSubscribeActivityHandler.cs @@ -0,0 +1,47 @@ +namespace SOR.Game.Handlers; + +using Microsoft.EntityFrameworkCore; +using SOR.Database.Contexts; +using SOR.Database.Enums; +using SOR.Networking.Abstractions.Messaging; +using SOR.Networking.Abstractions.Transport; +using SOR.Shared.Networking; + +/// +/// game.subscribe_activity — registers this connection to receive game.activity pushes +/// whenever any game session starts or ends on the server. +/// +/// Used by the client to power the live-star skybox: each active session appears as +/// a star that fades in on start and explodes on end. +/// +/// The response includes IDs of all currently active sessions so the client can +/// pre-populate the sky with existing stars on first subscribe. +/// +internal sealed class GameSubscribeActivityHandler : IMessageHandler +{ + private readonly GameDbContext _gameDb; + + public GameSubscribeActivityHandler(GameDbContext gameDb) + { + _gameDb = gameDb; + } + + public string MessageType => "game.subscribe_activity"; + + public async Task HandleAsync( + IClientMessage message, + AuthenticatedConnection connection, + CancellationToken ct) + { + GameActivityRegistry.Instance?.Subscribe(connection.UserId.ToString()); + + var activeIds = await _gameDb.GameSessions + .AsNoTracking() + .Where(s => s.Status == GameSessionStatus.Active) + .Select(s => s.Id.ToString()) + .ToListAsync(ct); + + return ServerMessage.Reply("game.subscribe_activity.ack", message.Seq, + new GameSubscribeActivityResponse(activeIds)); + } +} diff --git a/Server/src/SOR.Game/Handlers/GameUnsubscribeActivityHandler.cs b/Server/src/SOR.Game/Handlers/GameUnsubscribeActivityHandler.cs new file mode 100644 index 0000000..81fd9da --- /dev/null +++ b/Server/src/SOR.Game/Handlers/GameUnsubscribeActivityHandler.cs @@ -0,0 +1,26 @@ +namespace SOR.Game.Handlers; + +using SOR.Networking.Abstractions.Messaging; +using SOR.Networking.Abstractions.Transport; +using SOR.Shared.Networking; + +/// +/// game.unsubscribe_activity — removes this connection from the activity subscriber list. +/// Called by the client when leaving the game screen. +/// +internal sealed class GameUnsubscribeActivityHandler : IMessageHandler +{ + public string MessageType => "game.unsubscribe_activity"; + + public Task HandleAsync( + IClientMessage message, + AuthenticatedConnection connection, + CancellationToken ct) + { + GameActivityRegistry.Instance?.Unsubscribe(connection.UserId.ToString()); + + return Task.FromResult( + ServerMessage.Reply("game.unsubscribe_activity.ack", message.Seq, + new GameUnsubscribeActivityResponse())); + } +} diff --git a/Server/src/SOR.Game/ServiceRegistration.cs b/Server/src/SOR.Game/ServiceRegistration.cs index 8a8b503..12f13dd 100644 --- a/Server/src/SOR.Game/ServiceRegistration.cs +++ b/Server/src/SOR.Game/ServiceRegistration.cs @@ -35,6 +35,9 @@ public static class ServiceRegistration // Tracks spectators per session (in-memory; spectators only, players are not registered here). services.AddSingleton(); + // Tracks clients subscribed to game activity events for the live-star skybox. + services.AddSingleton(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); @@ -69,6 +72,10 @@ public static class ServiceRegistration services.AddTransient(); services.AddTransient(); + // Skybox activity feed handlers + services.AddTransient(); + services.AddTransient(); + // Preset vote service (in-memory, one active vote per lobby at a time). services.AddSingleton();