Skip to content

A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.

Advisors S6a: the media player, the photo fallback and the small disclosure (Refs #1484) (#1598)

Eyal Golan29c7e6f70539
diff --git a/changelog.d/advisors-s6a-draft.md b/changelog.d/advisors-s6a-draft.md
new file mode 100644
index 000000000..a5b401767
--- /dev/null
+++ b/changelog.d/advisors-s6a-draft.md
@@ -0,0 +1,4 @@
+### Added
+- The advisors' popup can play a short clip, a still or the advisor's portrait with its narration and live captions, in the popup on desktop
+ and in a centred overlay on phones; it never plays by itself, and any button or a window opening over it stops it.
+ No clip ships yet (Refs #1484).
diff --git a/unity/Assets/Scripts/UI/AdvisorCatalog.cs b/unity/Assets/Scripts/UI/AdvisorCatalog.cs
index 1c78ac7fc..cb3377a0b 100644
--- a/unity/Assets/Scripts/UI/AdvisorCatalog.cs
+++ b/unity/Assets/Scripts/UI/AdvisorCatalog.cs
@@ -14,6 +14,7 @@ namespace Statecraft.Game.UI
/// pages. A Unity-side file, never part of the hashed game content.</summary>
public sealed class AdvisorCatalog
{
+ public const string MediaFolder = "advisors";
public const string ResourcePath = "Advisors/advisor-messages";
public const string Path = "Assets/Resources/Advisors/advisor-messages.yaml";
public static readonly string[] AdvisorIds = { "ben_gurion", "meyerson", "dayan" };
@@ -34,6 +35,17 @@ namespace Statecraft.Game.UI
public bool OpenCard { get; set; }
}
+ /// <summary>Silent picture and separate narration, with live caption cue starts and disclosure/credit keys. The
+ /// picture is optional: without one the advisor's portrait stays while the narration plays (owner, 24 Oct 2026, #1547).</summary>
+ public sealed class Media
+ {
+ public string? Picture { get; set; }
+ public Dictionary<string, string> Narration { get; set; } = new Dictionary<string, string>();
+ public Dictionary<string, List<double>> Cues { get; set; } = new Dictionary<string, List<double>>();
+ public string Label { get; set; } = "";
+ public string Credit { get; set; } = "";
+ }
+
public sealed class Message
{
public string Id { get; set; } = "";
@@ -49,6 +61,7 @@ namespace Statecraft.Game.UI
public string Quote { get; set; } = "";
public string DisagreesWith { get; set; } = "";
public string HeReview { get; set; } = Pending;
+ public Media? Media { get; set; }
/// <summary>Teaching (help levels new and experienced) as against advice and warnings (spec 7.1's button sets).</summary>
public bool Teaching => Level == "new" || Level == "experienced";
@@ -64,6 +77,7 @@ namespace Statecraft.Game.UI
public string ShowMe { get; set; } = "";
public List<string> Rules { get; set; } = new List<string>();
public string HeReview { get; set; } = Pending;
+ public Media? Media { get; set; }
public bool ApprovedIn(bool hebrew) => !hebrew || HeReview == Approved;
}
@@ -127,6 +141,7 @@ namespace Statecraft.Game.UI
{
Signals = AdvisorSignals.Names.ToList(), Conditions = AdvisorSignals.Measures.Keys.ToList(),
Screens = ScreenNav.Screens, Targets = AdvisorTargets.Names,
+ StreamingFile = f => System.IO.File.Exists(System.IO.Path.Combine(Application.streamingAssetsPath, MediaFolder, f)),
};
/// <summary>Every problem, one line each (spec 4.1).</summary>
@@ -165,6 +180,7 @@ namespace Statecraft.Game.UI
}
if (m.HeReview != Pending && m.HeReview != Approved) p.Add($"{at}: he_review must be pending or approved");
Text(p, en, he, at, "advisor." + m.Id + ".text", MaxWords);
+ CheckMedia(p, at, "advisor." + m.Id, m.Media, m.HeReview, en, he, known);
}
if (Cycle() is string c) p.Add("requires has a cycle: " + c);
foreach (var g in Pages.GroupBy(x => x.Id).Where(g => g.Count() > 1)) p.Add($"page {g.Key}: listed more than once");
@@ -177,10 +193,52 @@ namespace Statecraft.Game.UI
if (page.HeReview != Pending && page.HeReview != Approved) p.Add($"{at}: he_review must be pending or approved");
Text(p, en, he, at, "advisor.page." + page.Id + ".title", 0);
Text(p, en, he, at, "advisor.page." + page.Id + ".text", 0);
+ CheckMedia(p, at, "advisor.page." + page.Id, page.Media, page.HeReview, en, he, known);
}
return p;
}
+ static void CheckMedia(List<string> p, string at, string stem, Media? media, string heReview, UiText en, UiText he, Known known)
+ {
+ if (media == null) return;
+ bool File(string file)
+ {
+ if (string.IsNullOrWhiteSpace(file) || file.Contains("/") || file.Contains("\\") || file == "." || file == ".." || file.Contains(":"))
+ { p.Add($"{at}: media uses a file name within StreamingAssets/{MediaFolder}"); return false; }
+ if (!known.StreamingFile(file)) p.Add($"{at}: no StreamingAssets/{MediaFolder}/{file}");
+ return true;
+ }
+ if (media.Picture is string picture && picture != "") // when supplied; a row without one needs narration (below)
+ {
+ if (!(picture.EndsWith(".mp4", StringComparison.OrdinalIgnoreCase) || picture.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) || picture.EndsWith(".png", StringComparison.OrdinalIgnoreCase)))
+ p.Add($"{at}: picture must be .mp4, .jpg or .png");
+ File(picture);
+ }
+ if (string.IsNullOrWhiteSpace(media.Label)) p.Add($"{at}: media needs a disclosure label key");
+ else Text(p, en, he, at, media.Label, 0);
+ if (!string.IsNullOrWhiteSpace(media.Credit)) Text(p, en, he, at, media.Credit, 0);
+ if (media.Narration == null || media.Cues == null) { p.Add($"{at}: narration and cues must be language maps"); return; }
+ if (media.Narration.Count == 0) p.Add($"{at}: media needs narration");
+ if (heReview != Approved && (media.Narration.ContainsKey("he") || media.Cues.ContainsKey("he"))) p.Add($"{at}: Hebrew narration before its approval");
+ foreach (var lang in media.Cues.Keys)
+ if (!media.Narration.ContainsKey(lang)) p.Add($"{at}: cues for {lang} without narration");
+ int? count = null;
+ foreach (var narration in media.Narration)
+ {
+ var lang = narration.Key; var file = narration.Value ?? "";
+ if (lang != "en" && lang != "he") p.Add($"{at}: unknown narration language '{lang}'");
+ if (!file.EndsWith(".wav", StringComparison.OrdinalIgnoreCase)) p.Add($"{at}: narration must be .wav");
+ File(file);
+ if (!media.Cues.TryGetValue(lang, out var starts) || starts == null || starts.Count == 0 || starts[0] != 0)
+ { p.Add($"{at}: {lang} cues start at 0"); continue; }
+ if (starts.Any(x => double.IsNaN(x) || double.IsInfinity(x)) || starts.Where((x, i) => i > 0 && x <= starts[i - 1]).Any())
+ p.Add($"{at}: {lang} cues must rise and be finite");
+ if (count.HasValue && count.Value != starts.Count) p.Add($"{at}: cue counts must match across languages");
+ count = starts.Count;
+ for (int i = 1; i <= starts.Count; i++) Text(p, en, he, at, stem + ".cue." + i, 0);
+ }
+ }
+
void CheckAct(List<string> p, string at, Act a, Known known)
{
int set = (a.ShowMe != "" ? 1 : 0) + (a.OpenScreen != "" ? 1 : 0) + (a.Encyclopedia != "" ? 1 : 0) + (a.OpenCard ? 1 : 0);
diff --git a/unity/Assets/Scripts/UI/AdvisorMedia.cs b/unity/Assets/Scripts/UI/AdvisorMedia.cs
new file mode 100644
index 000000000..318c14dde
--- /dev/null
+++ b/unity/Assets/Scripts/UI/AdvisorMedia.cs
@@ -0,0 +1,244 @@
+#nullable enable
+using System;
+using System.Collections.Generic;
+using UnityEngine;
+using UnityEngine.Networking;
+using UnityEngine.UIElements;
+
+namespace Statecraft.Game.UI
+{
+ /// <summary>A lazy, user-started silent picture and separate narration. The audio position drives live captions;
+ /// neither stream starts until both are ready. Owns its audio/output, and borrows rather than owns the card player.
+ /// A row with no picture plays its narration alone and uses no picture player: the advisor's portrait stays.</summary>
+ public sealed class AdvisorMedia : IDisposable
+ {
+ public const int TickMs = 50;
+ public const double DriftS = 0.1;
+ public const float InlineMinPx = 460;
+ public static bool Inline(HudTier tier, float slotHeight) => tier != HudTier.ThreeRow && slotHeight >= InlineMinPx;
+
+ public interface IPicture
+ {
+ void Load(string url, VisualElement target, Action<string> failed);
+ bool Ready { get; }
+ void Start();
+ void Stop();
+ double Time { get; }
+ void Seek(double time);
+ }
+
+ readonly UiText text;
+ readonly IPicture? clipPicture, stillPicture;
+ readonly DeclarationRecording.Fetch fetch;
+ readonly DeclarationRecording.IOutput output;
+ IPicture? picture;
+ AudioClip? narration;
+ DeclarationRecording.IRequest? request;
+ IVisualElementScheduledItem? timer;
+ Label? caption;
+ IReadOnlyList<double> cues = Array.Empty<double>();
+ Action? ended;
+ Action<string>? failed;
+ string file = "", stem = "";
+ bool started, heard, moving, disposed;
+ int generation, loadingMs, stalledMs, decodingMs, startingMs, pictureMs, pictureStalledMs;
+ ulong bytes, pictureBytes;
+
+ public AdvisorMedia(UiText text, IPicture? clip, IPicture? still, DeclarationRecording.Fetch fetch, DeclarationRecording.IOutput output)
+ { this.text = text; clipPicture = clip; stillPicture = still; this.fetch = fetch; this.output = output; }
+
+ public bool Playing { get; private set; }
+
+ public static string Url(string file)
+ {
+ var url = Application.streamingAssetsPath + "/" + AdvisorCatalog.MediaFolder + "/" + file;
+ return url.Contains("://") ? Boot.GameInputs.WithBuildId(url, Application.buildGUID) : "file://" + url;
+ }
+
+ public void Play(AdvisorCatalog.Media media, string keyStem, bool hebrew, VisualElement surface, Label caption,
+ Action ended, Action<string> failed)
+ {
+ if (disposed) return;
+ Stop();
+ this.caption = caption; caption.text = ""; this.ended = ended; this.failed = failed; stem = keyStem;
+ var supplied = media.Picture ?? "";
+ file = supplied;
+ moving = supplied.EndsWith(".mp4", StringComparison.OrdinalIgnoreCase);
+ picture = supplied == "" ? null : moving ? clipPicture : stillPicture;
+ Playing = true;
+ var lang = hebrew ? "he" : "en";
+ if (!media.Narration.TryGetValue(lang, out var audio) || !media.Cues.TryGetValue(lang, out var starts) || starts.Count == 0)
+ { Fail("no narration or captions for " + lang); return; }
+ if (supplied == "") file = audio; // the failure log names the voice-only line's file
+ else if (picture == null) { Fail("no player for " + supplied); return; }
+ cues = starts;
+ int mine = generation;
+ timer = caption.schedule.Execute(Tick).Every(TickMs).StartingIn(TickMs);
+ try
+ {
+ picture?.Load(Url(supplied), surface, why => { if (mine == generation && Playing) Fail("picture: " + why); });
+ if (mine != generation || !Playing) return;
+ var pending = fetch(Url(audio), (clip, error) =>
+ {
+ if (mine != generation || !Playing) { Release(clip); return; }
+ request = null;
+ if (clip == null) { Fail("fetch: " + error); return; }
+ narration = clip; decodingMs = 0;
+ });
+ // A synchronous fake/cache callback may have completed (or failed) before Fetch returns.
+ if (mine == generation && Playing && narration == null) request = pending;
+ else if (mine != generation) pending.Abort();
+ }
+ catch (Exception e) { if (mine == generation && Playing) Fail("load: " + e.Message); }
+ }
+
+ internal void Tick()
+ {
+ if (!Playing) return;
+ if (!started)
+ {
+ if (picture != null && !picture.Ready)
+ {
+ pictureMs += TickMs;
+ if (picture is StillPicture still)
+ {
+ ulong progress = still.Bytes;
+ pictureStalledMs = progress > pictureBytes ? 0 : pictureStalledMs + TickMs; pictureBytes = progress;
+ if (pictureStalledMs >= DeclarationRecording.StallTimeoutMs || pictureMs >= DeclarationRecording.LoadCapMs)
+ { Fail("picture fetch timed out"); return; }
+ }
+ else if (pictureMs >= CardVideo.PrepareTimeoutMs) { Fail("picture preparation timed out"); return; }
+ }
+ if (narration == null)
+ {
+ loadingMs += TickMs;
+ var now = request?.Bytes ?? 0;
+ stalledMs = now > bytes ? 0 : stalledMs + TickMs; bytes = now;
+ if (stalledMs >= DeclarationRecording.StallTimeoutMs || loadingMs >= DeclarationRecording.LoadCapMs) Fail("fetch timed out");
+ return;
+ }
+ var ready = output.Ready(narration);
+ if (ready == null) { Fail("narration could not decode"); return; }
+ if (!ready.Value)
+ {
+ if ((decodingMs += TickMs) >= DeclarationRecording.DecodeTimeoutMs) Fail("narration decode timed out");
+ return;
+ }
+ if (picture != null && !picture.Ready) return;
+ try { picture?.Start(); output.Play(narration); started = true; }
+ catch (Exception e) { Fail("start: " + e.Message); return; }
+ }
+ if (output.IsPlaying && output.Position > 0) heard = true;
+ if (!heard && (startingMs += TickMs) >= DeclarationRecording.StartTimeoutMs) { Fail("narration did not start"); return; }
+ if (heard && !output.IsPlaying)
+ {
+ var done = ended; Stop(); done?.Invoke(); return;
+ }
+ int cue = AdvisorCaptions.At(cues, output.Position);
+ if (caption != null) caption.text = cue < 0 ? "" : text[stem + ".cue." + (cue + 1)];
+ if (moving && picture != null && Math.Abs(picture.Time - output.Position) > DriftS) picture.Seek(output.Position);
+ }
+
+ void Fail(string why)
+ {
+ var tell = failed; var name = file;
+ Stop();
+ Debug.LogWarning($"ADVISOR MEDIA failed {name}: {why}");
+ tell?.Invoke(why);
+ }
+
+ public void Stop()
+ {
+ generation++; Playing = false;
+ timer?.Pause(); timer = null;
+ request?.Abort(); request = null;
+ picture?.Stop(); picture = null;
+ output.Stop(); Release(narration); narration = null;
+ if (caption != null) caption.text = "";
+ caption = null; ended = null; failed = null;
+ started = heard = false;
+ loadingMs = stalledMs = decodingMs = startingMs = pictureMs = pictureStalledMs = 0; bytes = pictureBytes = 0;
+ }
+
+ static void Release(AudioClip? clip)
+ {
+ if (clip == null) return;
+ if (Application.isPlaying) UnityEngine.Object.Destroy(clip); else UnityEngine.Object.DestroyImmediate(clip);
+ }
+
+ public void Dispose() { if (disposed) return; Stop(); output.Dispose(); disposed = true; }
+ }
+
+ public static class AdvisorCaptions
+ {
+ public static int At(IReadOnlyList<double> starts, double position)
+ {
+ for (int i = starts.Count - 1; i >= 0; i--) if (position >= starts[i]) return i;
+ return -1;
+ }
+ }
+
+ /// <summary>Only the URL this adapter loaded is its own to release, seek or stop.</summary>
+ public sealed class ClipPicture : AdvisorMedia.IPicture
+ {
+ readonly CardVideo video;
+ string? url;
+ public ClipPicture(CardVideo video) { this.video = video; }
+ bool Owns => url != null && video.Current == url;
+ public void Load(string url, VisualElement target, Action<string> failed)
+ { Stop(); this.url = url; video.Play(url, target, failed, loop: false, held: true); }
+ public bool Ready => Owns && video.Prepared;
+ public double Time => Owns ? video.Time : 0;
+ public void Start() { if (Owns) video.Release(); }
+ public void Seek(double time) { if (Owns) video.Seek(time); }
+ public void Stop() { if (Owns) video.Stop(); url = null; }
+ }
+
+ /// <summary>A fetched texture held until Start. Stop aborts it and invalidates late callbacks.</summary>
+ public sealed class StillPicture : AdvisorMedia.IPicture
+ {
+ UnityWebRequest? request;
+ Texture2D? image;
+ VisualElement? target;
+ int generation;
+ internal ulong Bytes => request?.downloadedBytes ?? 0;
+ public bool Ready => image != null;
+ public double Time => 0;
+ public void Seek(double time) { }
+ public void Load(string url, VisualElement target, Action<string> failed)
+ {
+ Stop(); this.target = target; int mine = generation;
+ var pending = UnityWebRequestTexture.GetTexture(url);
+ request = pending;
+ UnityWebRequestAsyncOperation operation;
+ try { operation = pending.SendWebRequest(); }
+ catch { request = null; pending.Dispose(); throw; }
+ operation.completed += _ =>
+ {
+ if (mine != generation) { pending.Dispose(); return; }
+ request = null;
+ string? error = null;
+ try
+ {
+ if (pending.result != UnityWebRequest.Result.Success) error = pending.error ?? "texture fetch failed";
+ else image = DownloadHandlerTexture.GetContent(pending);
+ if (image == null && error == null) error = "no texture";
+ }
+ catch (Exception e) { error = e.Message; }
+ finally { pending.Dispose(); }
+ if (error != null) failed(error);
+ };
+ }
+ public void Start() { if (target != null && image != null) target.style.backgroundImage = new StyleBackground(image); }
+ public void Stop()
+ {
+ generation++; request?.Abort(); request = null;
+ if (image != null)
+ {
+ if (target != null && target.style.backgroundImage.value.texture == image) target.style.backgroundImage = StyleKeyword.Null;
+ if (Application.isPlaying) UnityEngine.Object.Destroy(image); else UnityEngine.Object.DestroyImmediate(image);
+ }
+ image = null; target = null;
+ }
+ }
+}
diff --git a/unity/Assets/Scripts/UI/AdvisorMedia.cs.meta b/unity/Assets/Scripts/UI/AdvisorMedia.cs.meta
new file mode 100644
index 000000000..4f5aa36da
--- /dev/null
+++ b/unity/Assets/Scripts/UI/AdvisorMedia.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: bbf6b5375cfd48f5a2c0ef8c4b9a7e5b
diff --git a/unity/Assets/Scripts/UI/AdvisorPresenter.cs b/unity/Assets/Scripts/UI/AdvisorPresenter.cs
index 250419466..0a6345a91 100644
--- a/unity/Assets/Scripts/UI/AdvisorPresenter.cs
+++ b/unity/Assets/Scripts/UI/AdvisorPresenter.cs
@@ -36,6 +36,31 @@ namespace Statecraft.Game.UI
public const long HideMs = 150;
public const string RingClass = "advisor-ring-open";
public const long RingOnlyMs = 4000;
+ public const string WatchingClass = "advisor-watching", OverlayOpenClass = "advisor-overlay-open";
+ /// <summary>On the popup while a line with no picture plays its narration: the portrait row stays (owner, 24 Oct 2026, #1547).</summary>
+ public const string NarratingClass = "advisor-narrating";
+ AdvisorMedia? media;
+ public AdvisorMedia? Media
+ {
+ get => media;
+ set { if (ReferenceEquals(media, value)) return; StopWatching(); media?.Dispose(); media = value; UpdateWatch(); }
+ }
+ internal bool? ForceInline { get; set; }
+ readonly VisualElement mediaPicture, overlay, overlayPicture, mediaHead;
+ readonly Label mediaLabel, mediaCredit, overlayCaption, overlayLabel, overlayCredit;
+ readonly Button watch, overlayClose;
+ readonly Action onWatch, onOverlayClose;
+ readonly EventCallback<GeometryChangedEvent> onMediaGeometry;
+ string watchScreens = "";
+ VisualElement? mediaOpener;
+ bool watchStoppedOnPress;
+ int overlayClosedAt = -1;
+ internal bool OverlayClosedThisFrame => overlayClosedAt == Time.frameCount;
+ readonly List<(VisualElement element, bool enabled)> overlayCoveredScreens = new List<(VisualElement, bool)>();
+ readonly EventCallback<PointerDownEvent> onMediaPointer;
+ readonly EventCallback<NavigationSubmitEvent> onMediaSubmit;
+ readonly EventCallback<NavigationCancelEvent> onMediaCancel;
+
readonly VisualElement ring;
string? target;
Action? putBack;
@@ -77,6 +102,28 @@ namespace Statecraft.Game.UI
layer = root.Q<VisualElement>(LayerName);
popup = layer.Q<VisualElement>("advisor-popup");
ring = layer.Q("advisor-ring");
+ mediaHead = popup.Q(className: "advisor-head");
+ mediaPicture = popup.Q("advisor-media"); mediaLabel = popup.Q<Label>("advisor-media-label"); mediaCredit = popup.Q<Label>("advisor-media-credit");
+ overlay = hudRoot.Q("advisor-overlay"); overlayPicture = overlay.Q("advisor-overlay-media");
+ overlayCaption = overlay.Q<Label>("advisor-overlay-caption"); overlayLabel = overlay.Q<Label>("advisor-overlay-label"); overlayCredit = overlay.Q<Label>("advisor-overlay-credit");
+ watch = popup.Q<Button>("advisor-watch"); overlayClose = overlay.Q<Button>("advisor-overlay-close");
+ watch.text = text["advisor.watch"]; overlayClose.text = text["advisor.close"];
+ onWatch = () => { if (watchStoppedOnPress) { watchStoppedOnPress = false; return; } if (Media?.Playing == true) StopWatching(); else if (Shown?.Media is AdvisorCatalog.Media row) Watch(row, "advisor." + Shown.Id); };
+ onOverlayClose = () => CloseOverlay();
+ watch.clicked += onWatch; overlayClose.clicked += onOverlayClose;
+ onMediaPointer = e => StopBeforeButton(e); onMediaSubmit = e => StopBeforeButton(e);
+ onMediaCancel = e => { if (CloseOverlay()) e.StopPropagation(); };
+ hudRoot.RegisterCallback(onMediaPointer, TrickleDown.TrickleDown); hudRoot.RegisterCallback(onMediaSubmit, TrickleDown.TrickleDown);
+ overlay.RegisterCallback(onMediaCancel);
+
+ onMediaGeometry = _ =>
+ {
+ SizeMedia(); ApplyTextFloor();
+ if (Media?.Playing == true && ForceInline == null && popup.ClassListContains(WatchingClass) && layer.layout.width > 0
+ && !AdvisorMedia.Inline(AdvisorLayout.Tier(hudRoot), Slot().height)) StopWatching();
+ };
+ hudRoot.RegisterCallback(onMediaGeometry); mediaPicture.RegisterCallback(onMediaGeometry); overlayPicture.RegisterCallback(onMediaGeometry);
+
portrait = popup.Q<VisualElement>("advisor-portrait");
name = popup.Q<Label>("advisor-name"); role = popup.Q<Label>("advisor-role");
words = popup.Q<Label>("advisor-text"); count = popup.Q<Label>("advisor-count");
@@ -84,7 +131,7 @@ namespace Statecraft.Game.UI
notNow = popup.Q<Button>("advisor-not-now"); gotIt = popup.Q<Button>("advisor-got-it"); close = popup.Q<Button>("advisor-close");
showMe.text = text["advisor.show_me"]; more.text = text["advisor.more"]; notNow.text = text["advisor.not_now"];
gotIt.text = text["advisor.got_it"]; close.text = text["advisor.close"];
- floored = new (VisualElement, float)[] { (name, NamePx), (role, RolePx), (words, TextPx), (showMe, ButtonPx), (more, ButtonPx), (notNow, ButtonPx), (gotIt, ButtonPx), (close, ButtonPx), (count, CountPx) };
+ floored = new (VisualElement, float)[] { (name, NamePx), (role, RolePx), (words, TextPx), (showMe, ButtonPx), (more, ButtonPx), (notNow, ButtonPx), (gotIt, ButtonPx), (close, ButtonPx), (count, CountPx), (mediaLabel, 15f), (mediaCredit, 15f), (overlayCaption, TextPx), (overlayLabel, 15f), (overlayCredit, 15f), (watch, 15f), (overlayClose, ButtonPx) };
onShowMe = ShowMe; onGotIt = GotIt; onNotNow = NotNow;
onClose = () => { if (session.Chain.Step >= 0) CloseChain(); else GotIt(); };
reopen = root.Q<Button>("how-to-play-guide");
@@ -185,11 +232,13 @@ namespace Statecraft.Game.UI
void Fill(AdvisorCatalog.Message m)
{
+ if (Shown?.Id != m.Id) StopWatching();
Shown = m;
gotIt.text = text["advisor.got_it"];
name.text = text[m.Advisor == "meyerson" && !session.Introduced(m.Advisor) ? "advisor.meyerson.name_first" : "advisor." + m.Advisor + ".name"];
role.text = text["advisor." + m.Advisor + ".role"];
- words.text = text["advisor." + m.Id + ".text"];
+ if (!Captioning) words.text = text["advisor." + m.Id + ".text"];
+ UpdateWatch();
var picture = portraits?.Get(session.Catalog.AdvisorOf(m.Advisor).Person);
popup.EnableInClassList(NoPortraitClass, picture == null);
portrait.style.backgroundImage = picture == null ? new StyleBackground(StyleKeyword.Null) : new StyleBackground(picture);
@@ -239,6 +288,7 @@ namespace Statecraft.Game.UI
void Hide()
{
+ StopWatching();
if (hidden) return;
hidden = true;
ring.style.display = DisplayStyle.None;
@@ -262,6 +312,8 @@ namespace Statecraft.Game.UI
void CoverChanged()
{
if (disposed) return;
+ if (Media?.Playing == true && (HardMediaCover() || CurrentScreens() != watchScreens)) StopWatching();
+ if (hudRoot.ClassListContains(OverlayOpenClass)) return;
if (session.Chain.Step >= 0) { RenderChain(); return; }
if (Covered(hudRoot)) { if (Shown != null) covered = Shown; Hide(); return; }
if (covered is AdvisorCatalog.Message m)
@@ -438,6 +490,7 @@ namespace Statecraft.Game.UI
void ShowMe()
{
+ StopWatching();
if (Shown == null) return;
foreach (var a in Shown.Actions)
if (a.ShowMe != "") ShowTarget(a.ShowMe);
@@ -448,7 +501,8 @@ namespace Statecraft.Game.UI
/// <summary>Got it, the X, or Escape from inside: seen, and the next message (if any) shows.</summary>
public void GotIt()
{
- if (Shown == null || !IsOpen) return; // not while it fades out under a new layer
+ if (Shown == null || !IsOpen) return; // final S1: no action during fade
+ StopWatching();
if (session.Chain.Step >= 0) { NextStep(); return; }
ClearTarget();
session.Queue.Done(Shown, Turn, bridge.State.Date);
@@ -460,12 +514,116 @@ namespace Statecraft.Game.UI
public void NotNow()
{
if (Shown == null || !IsOpen || Shown.Teaching || Shown.Critical) return;
+ StopWatching();
ClearTarget();
session.Queue.PutOff(Shown, Turn, bridge.State.Date);
Shown = null;
Render();
}
+ bool HardMediaCover() => hudRoot.ClassListContains(StartScreenPresenter.OpenClass) || hudRoot.ClassListContains(EventCardPresenter.OpenClass)
+ || hudRoot.ClassListContains(CaptureDialogPresenter.OpenClass) || hudRoot.ClassListContains(TurnReportPresenter.OpenClass)
+ || hudRoot.ClassListContains(OutcomePresenter.OpenClass) || hudRoot.ClassListContains(EndScreenPresenter.OpenClass)
+ || hudRoot.ClassListContains(FeedbackPresenter.OpenClass) || hudRoot.ClassListContains(SharePresenter.OpenClass);
+
+ void StopBeforeButton(EventBase e)
+ {
+ var element = e.target as VisualElement;
+ var button = element as Button ?? element?.GetFirstAncestorOfType<Button>();
+ if (button == null) return;
+ if (button == watch) watchStoppedOnPress = Media?.Playing == true;
+ if (Media?.Playing == true) StopWatching(); // before another window snapshots the covered UI states
+ }
+
+ string CurrentScreens() => string.Join("|", ScreenNav.Screens.Where(n => hudRoot.Q("screen-" + n) is VisualElement screen && ScreenNav.IsOpen(screen)));
+
+ /// <summary>Spec 12, per line: a clip or a supplied still with its narration, or the narration alone with the portrait.
+ /// Either needs the current language's narration; with none there is no Watch control.</summary>
+ bool Watchable(AdvisorCatalog.Media? row) => Media != null && row != null && row.Narration.ContainsKey(hebrew ? "he" : "en")
+ && !session.MediaFailed.Contains(FailureKey(row));
+ /// <summary>The file a failure is remembered by: the picture, or a voice-only line's own narration (never an empty name,
+ /// which every voice-only line would share).</summary>
+ string FailureKey(AdvisorCatalog.Media row) =>
+ string.IsNullOrEmpty(row.Picture) ? row.Narration.TryGetValue(hebrew ? "he" : "en", out var voice) ? voice : "" : row.Picture!;
+ bool Captioning => popup.ClassListContains(WatchingClass) || popup.ClassListContains(NarratingClass);
+ void UpdateWatch()
+ {
+ bool canWatch = Watchable(Shown?.Media) && Shown!.ApprovedIn(hebrew);
+ Display(watch, canWatch); popup.EnableInClassList("advisor-has-media", canWatch);
+ }
+
+ internal void Watch(AdvisorCatalog.Media row, string keyStem) => PlayMedia(row, keyStem, overlayOnly: false);
+ /// <summary>For the encyclopedia and Counsel adapters once their owners land; their source row must be approved. Supplied
+ /// pictures only: a voice-only item keeps its own screen's portrait (spec 12), which those screens' owners draw.</summary>
+ internal void WatchOverlay(AdvisorCatalog.Media row, string keyStem) => PlayMedia(row, keyStem, overlayOnly: true);
+
+ void PlayMedia(AdvisorCatalog.Media row, string keyStem, bool overlayOnly)
+ {
+ bool hasPicture = !string.IsNullOrEmpty(row.Picture);
+ if (disposed || !Watchable(row) || HardMediaCover() || (overlayOnly && !hasPicture)) return;
+ StopWatching(); watchScreens = CurrentScreens(); mediaOpener = hudRoot.focusController?.focusedElement as VisualElement;
+ // Without a picture the portrait row stays and the caption takes the text's place, never the overlay (spec 12).
+ bool inline = !hasPicture || (!overlayOnly && (ForceInline ?? AdvisorMedia.Inline(AdvisorLayout.Tier(hudRoot), Slot().height)));
+ var picture = inline ? mediaPicture : overlayPicture;
+ var caption = inline ? words : overlayCaption;
+ var label = inline ? mediaLabel : overlayLabel;
+ var credit = inline ? mediaCredit : overlayCredit;
+ label.text = text[row.Label]; credit.text = row.Credit == "" ? "" : text[row.Credit];
+ popup.EnableInClassList(WatchingClass, inline && hasPicture);
+ popup.EnableInClassList(NarratingClass, !hasPicture);
+ if (inline && hasPicture) mediaHead.BringToFront();
+ hudRoot.EnableInClassList(OverlayOpenClass, !inline);
+ if (!inline)
+ {
+ foreach (var name in ScreenNav.Screens)
+ if (hudRoot.Q("screen-" + name) is VisualElement screen) { overlayCoveredScreens.Add((screen, screen.enabledSelf)); screen.SetEnabled(false); }
+ ScreenNav.DisableCovered(hudRoot); FocusReturn.To(overlayClose);
+ }
+ SizeMedia(); ApplyTextFloor();
+ Media!.Play(row, keyStem, hebrew, picture, caption, StopWatching, _ =>
+ {
+ session.MediaFailed.Add(FailureKey(row)); StopWatching(); UpdateWatch();
+ });
+ }
+
+ void SizeMedia()
+ {
+ void Fit(VisualElement e, float ceiling)
+ {
+ float width = e.layout.width;
+ float height = Mathf.Min(width / EventCardPresenter.MediaAspect, ceiling);
+ if (width > 0 && Mathf.Abs(e.layout.height - height) > 0.5f) e.style.height = height;
+ }
+ Fit(mediaPicture, float.MaxValue);
+ float availableHeight = Mathf.Max(0, hudRoot.layout.height - 220);
+ overlay.Q("advisor-overlay-frame").style.width = Mathf.Min(1000, Mathf.Max(0, hudRoot.layout.width - 32), availableHeight * EventCardPresenter.MediaAspect + 40);
+ Fit(overlayPicture, float.MaxValue);
+ }
+
+ void StopWatching()
+ {
+ bool overlayWasOpen = hudRoot.ClassListContains(OverlayOpenClass);
+ Media?.Stop();
+ if (popup.ClassListContains(WatchingClass)) mediaHead.SendToBack();
+ popup.RemoveFromClassList(WatchingClass); popup.RemoveFromClassList(NarratingClass); hudRoot.RemoveFromClassList(OverlayOpenClass);
+ if (Shown != null) words.text = text["advisor." + Shown.Id + ".text"];
+ if (overlayWasOpen)
+ {
+ overlayClosedAt = Time.frameCount;
+ foreach (var (element, enabled) in overlayCoveredScreens) element.SetEnabled(enabled);
+ overlayCoveredScreens.Clear();
+ ScreenNav.DisableCovered(hudRoot);
+ if (!disposed) FocusReturn.To(mediaOpener ?? gotIt);
+ mediaOpener = null;
+ }
+ }
+
+ public bool CloseOverlay()
+ {
+ if (!hudRoot.ClassListContains(OverlayOpenClass)) return false;
+ StopWatching(); return true;
+ }
+
/// <summary>Escape: closes it as the X does, only while the focus is inside it (spec 16). True when it did, and
/// also in the frame ScreenNav's Cancel already closed it, so GameRoot's poll does not close the screen under it too.
/// That frame check comes first: Got it can bring the next message up at once, and one Escape dismisses one message.</summary>
@@ -542,6 +700,11 @@ namespace Statecraft.Game.UI
if (session.Chain.Step >= 0) { session.Chain.PutBack = putBack ?? adopted; putBack = null; }
ClearTarget();
disposed = true;
+ StopWatching(); Media?.Dispose();
+ watch.clicked -= onWatch; overlayClose.clicked -= onOverlayClose;
+ hudRoot.UnregisterCallback(onMediaGeometry); mediaPicture.UnregisterCallback(onMediaGeometry); overlayPicture.UnregisterCallback(onMediaGeometry);
+ hudRoot.UnregisterCallback(onMediaPointer, TrickleDown.TrickleDown); hudRoot.UnregisterCallback(onMediaSubmit, TrickleDown.TrickleDown);
+ overlay.UnregisterCallback(onMediaCancel);
follow.Pause();
fading?.Pause();
layer.UnregisterCallback(onLaidOut);
diff --git a/unity/Assets/Scripts/UI/AdvisorSession.cs b/unity/Assets/Scripts/UI/AdvisorSession.cs
index 6107d9b7e..9dd2913dc 100644
--- a/unity/Assets/Scripts/UI/AdvisorSession.cs
+++ b/unity/Assets/Scripts/UI/AdvisorSession.cs
@@ -35,6 +35,8 @@ namespace Statecraft.Game.UI
public AdvisorQueue Queue { get; }
/// <summary>The event signals fired on <see cref="FiredTurn"/>; they hold for that turn only.</summary>
public HashSet<string> Fired { get; } = new HashSet<string>(StringComparer.Ordinal);
+ /// <summary>Failed media files stay hidden through language rebuilds in this session; never saved.</summary>
+ public HashSet<string> MediaFailed { get; } = new HashSet<string>(StringComparer.Ordinal);
public int FiredTurn { get; set; } = -1;
/// <summary>Whether Meyerson has been named in full once this profile (her first appearance, spec 3.1), by her seen marks.</summary>
public bool Introduced(string advisor) =>
diff --git a/unity/Assets/Scripts/UI/CardVideo.cs b/unity/Assets/Scripts/UI/CardVideo.cs
index 4e39f1190..310697ec2 100644
--- a/unity/Assets/Scripts/UI/CardVideo.cs
+++ b/unity/Assets/Scripts/UI/CardVideo.cs
@@ -19,6 +19,15 @@ namespace Statecraft.Game.UI
/// <summary>How long a clip may take to be ready before the card gives up on it.</summary>
public const long PrepareTimeoutMs = 8000;
+ bool held;
+ internal bool Prepared { get; private set; }
+ public double Time => player?.time ?? 0;
+ public void Seek(double time)
+ {
+ if (player == null || !Prepared || double.IsNaN(time) || double.IsInfinity(time)) return;
+ player.time = Math.Max(0, player.length > 0 ? Math.Min(player.length, time) : time);
+ }
+
GameObject? go; VideoPlayer? player; RenderTexture? rt;
VisualElement? target; Action<string>? onFail; Action? onEnded; IVisualElementScheduledItem? timeout;
@@ -51,16 +60,17 @@ namespace Statecraft.Game.UI
/// <paramref name="ended"/>.</summary>
/// <param name="prepareTimeoutMs">How long it may take to be ready (default PrepareTimeoutMs).</param>
public void Play(string url, VisualElement header, Action<string> failed, bool loop = true, Action? ended = null,
- long prepareTimeoutMs = PrepareTimeoutMs)
+ long prepareTimeoutMs = PrepareTimeoutMs, bool held = false)
{
Stop();
Ensure();
var was = RenderTexture.active; RenderTexture.active = rt; GL.Clear(false, true, Color.black); RenderTexture.active = was;
+ this.held = held;
target = header; onFail = failed; onEnded = loop ? null : ended; Current = url;
player!.isLooping = loop;
player.url = url;
player.Prepare();
- timeout = header.schedule.Execute(() => { if (Current == url && !Showing) Fail("not ready after " + prepareTimeoutMs + " ms"); }).StartingIn(prepareTimeoutMs);
+ timeout = header.schedule.Execute(() => { if (Current == url && !Prepared) Fail("not ready after " + prepareTimeoutMs + " ms"); }).StartingIn(prepareTimeoutMs);
}
/// <summary>Puts the playing clip back on <paramref name="header"/>'s background (after the card reset it to the
@@ -76,7 +86,7 @@ namespace Statecraft.Game.UI
{
timeout?.Pause(); timeout = null;
if (player != null) { player.Stop(); player.url = ""; }
- target = null; onFail = null; onEnded = null; Current = null; Showing = false;
+ target = null; onFail = null; onEnded = null; Current = null; Showing = false; Prepared = false; held = false;
}
public void Dispose()
@@ -111,9 +121,18 @@ namespace Statecraft.Game.UI
void OnPrepared(VideoPlayer p)
{
if (target == null) return;
+ Prepared = true;
+ if (!held) Release();
+ }
+
+ /// <summary>Shows and starts a held, prepared picture only when its separate narration is ready.</summary>
+ public void Release()
+ {
+ held = false;
+ if (!Prepared || player == null || target == null) return;
target.style.backgroundImage = new StyleBackground(Background.FromRenderTexture(rt));
Showing = true;
- p.Play();
+ player.Play();
Debug.Log("VIDEO playing " + Current);
}
diff --git a/unity/Assets/Scripts/UI/DeclarationRecording.cs b/unity/Assets/Scripts/UI/DeclarationRecording.cs
index 69b21529b..83d8d2b8b 100644
--- a/unity/Assets/Scripts/UI/DeclarationRecording.cs
+++ b/unity/Assets/Scripts/UI/DeclarationRecording.cs
@@ -201,7 +201,7 @@ namespace Statecraft.Game.UI
}
/// <summary>The game's fetch: UnityWebRequestMultimedia from StreamingAssets, as WAV.</summary>
- static IRequest WebFetch(string url, Action<AudioClip?, string?> done) => new WebRequest(url, done);
+ internal static IRequest WebFetch(string url, Action<AudioClip?, string?> done) => new WebRequest(url, done);
sealed class WebRequest : IRequest
{
diff --git a/unity/Assets/Scripts/UI/GameRoot.cs b/unity/Assets/Scripts/UI/GameRoot.cs
index ed153e952..d062049fd 100644
--- a/unity/Assets/Scripts/UI/GameRoot.cs
+++ b/unity/Assets/Scripts/UI/GameRoot.cs
@@ -300,7 +300,7 @@ namespace Statecraft.Game.UI
// Star, Report and Share as round icons at the map screen's bottom left (#1236): the same actions as Settings' buttons.
Own(new CommunityIconsPresenter(root, text, feedbackPanel, sharePanel));
// Both panels in one hook: the same Escape never closes the screen under the panel too.
- nav!.TakesEscape = () => feedbackPanel.Escape() || sharePanel.Escape() || advisor?.Escape() == true;
+ nav!.TakesEscape = () => feedbackPanel.Escape() || sharePanel.Escape() || advisor?.CloseOverlay() == true || advisor?.OverlayClosedThisFrame == true || advisor?.Escape() == true;
var names = map.SettlementsFor(inputs.Map.SettlementsYaml).ToDictionary(s => s.Id, s => s.Name); // the map's parse (issue #321)
// The capture dialog (GDD Phase 6 PR 10, #802): in the decision layer, after the card, which goes first; the
// places' Hebrew names from the same parse.
@@ -551,6 +551,8 @@ namespace Statecraft.Game.UI
return new Rect(at, Vector2.one);
},
}));
+ if (video != null)
+ advisor.Media = new AdvisorMedia(text, new ClipPicture(video), new StillPicture(), DeclarationRecording.WebFetch, new DeclarationRecording.SourceOutput());
if (newGame != null) newGame.Started += advisor.NewGame;
if (hebrew) Own(new UiDirection(root, bridge));
root.Q("root")?.RemoveFromClassList("loading"); // ready: the bar, panels and screens may show (P2-1)
@@ -811,7 +813,7 @@ namespace Statecraft.Game.UI
// which shows only while the card does not.
// The report panel (#1169) and the share panel (#1170) are over everything: their Escape goes no further.
// Nor does the advisors' popup's, with the focus inside it (AdvisorPresenter.Escape, also in the frame its Cancel closed it).
- if (UnityEngine.InputSystem.Keyboard.current?.escapeKey.wasPressedThisFrame == true && feedback?.Escape() != true && share?.Escape() != true && advisor?.Escape() != true) { bool done = outcomes?.SkipAll() == true || outcomes?.ClosedThisFrame == true; if (!done) done = end?.Close() == true || end?.ClosedThisFrame == true; if (!done) done = report?.Close() == true || report?.ClosedThisFrame == true; done |= start?.Escape() == true; done |= nav?.Close() == true; if (!done && document.rootVisualElement.focusController?.focusedElement == null && capture?.Escape() != true) card?.Escape(); }
+ if (UnityEngine.InputSystem.Keyboard.current?.escapeKey.wasPressedThisFrame == true && feedback?.Escape() != true && share?.Escape() != true && advisor?.Escape() != true) { bool done = outcomes?.SkipAll() == true || outcomes?.ClosedThisFrame == true; if (!done) done = advisor?.CloseOverlay() == true || advisor?.OverlayClosedThisFrame == true; if (!done) done = end?.Close() == true || end?.ClosedThisFrame == true; if (!done) done = report?.Close() == true || report?.ClosedThisFrame == true; done |= start?.Escape() == true; done |= nav?.Close() == true; if (!done && document.rootVisualElement.focusController?.focusedElement == null && capture?.Escape() != true) card?.Escape(); }
// PageUp, PageDown, Home and End, with no modifier, scroll the open screen or the open card's text, with or without
// focus (KeyScroll; accessibility audit H3), but not under an End Turn outcome clip, which covers them. The arrows
// stay with the camera (NavigationGuard, B6).
diff --git a/unity/Assets/Scripts/UI/ScreenNav.cs b/unity/Assets/Scripts/UI/ScreenNav.cs
index ee98513f8..951d3d83b 100644
--- a/unity/Assets/Scripts/UI/ScreenNav.cs
+++ b/unity/Assets/Scripts/UI/ScreenNav.cs
@@ -44,7 +44,7 @@ namespace Statecraft.Game.UI
bool start = r.ClassListContains(StartScreenPresenter.OpenClass);
bool screen = r.ClassListContains(ScreenOpenClass);
bool full = screen && r.ClassListContains(HudPresenter.TwoRowClass);
- bool outcome = r.ClassListContains(OutcomePresenter.OpenClass); // an End Turn outcome clip covers all but itself
+ bool outcome = r.ClassListContains(OutcomePresenter.OpenClass) || r.ClassListContains(AdvisorPresenter.OverlayOpenClass); // an End Turn outcome clip covers all but itself
bool end = r.ClassListContains(EndScreenPresenter.OpenClass); // the end screen (#812) covers the HUD and the report
bool report = r.ClassListContains(TurnReportPresenter.OpenClass) || end; // the turn report covers the HUD under it
bool modal = (r.ClassListContains(EventCardPresenter.OpenClass) || r.ClassListContains(CaptureDialogPresenter.OpenClass)) && !start && !screen && !outcome;
diff --git a/unity/Assets/Tests/EditMode/AdvisorCatalogTests.cs b/unity/Assets/Tests/EditMode/AdvisorCatalogTests.cs
index e4cdbedcc..4dd831fc4 100644
--- a/unity/Assets/Tests/EditMode/AdvisorCatalogTests.cs
+++ b/unity/Assets/Tests/EditMode/AdvisorCatalogTests.cs
@@ -27,6 +27,48 @@ public class AdvisorCatalogTests
static List<string> ProblemsOf(string messages, params string[] keys) =>
AdvisorCatalog.Parse(Head + messages).Problems(Strings(keys), Strings(keys), Fixture);
+ [TestCase("{ picture: ../x.mp4, narration: { en: x.en.wav }, cues: { en: [0] }, label: lab }", "file name") ]
+ [TestCase("{ picture: x.gif, narration: { en: x.en.wav }, cues: { en: [0.0] }, label: lab }", "picture must be .mp4, .jpg or .png")]
+ [TestCase("{ picture: missing.mp4, narration: { en: x.en.wav }, cues: { en: [0.0] }, label: lab }", "no StreamingAssets/advisors/missing.mp4")]
+ [TestCase("{ picture: x.mp4, narration: { en: x.en.mp3 }, cues: { en: [0.0] }, label: lab }", "narration must be .wav")]
+ [TestCase("{ picture: x.mp4, narration: { en: x.en.wav }, cues: { en: [0.5] }, label: lab }", "cues start at 0")]
+ [TestCase("{ picture: x.mp4, narration: { en: x.en.wav }, cues: { en: [0.0, 3.0, 2.0] }, label: lab }", "cues must rise")]
+ [TestCase("{ picture: x.mp4, narration: { en: x.en.wav, he: x.he.wav }, cues: { en: [0.0], he: [0.0] }, label: lab }", "Hebrew narration before its approval")]
+ [TestCase("{ picture: x.mp4, narration: { en: x.en.wav }, cues: { en: [0.0, 2.0] }, label: lab }", "no advisor.x.cue.2")]
+ [TestCase("{ picture: x.mp4, narration: { en: x.en.wav }, cues: { en: [0.0] }, label: nolabel }", "no nolabel")]
+ [TestCase("{ label: lab }", "media needs narration")] // no picture and no narration: nothing to play (spec 12)
+ public void EachBrokenMediaRowIsNamed(string media, string expected)
+ {
+ var known = new AdvisorCatalog.Known { Signals = new[] { "new_game" }, StreamingFile = f => f.StartsWith("x.", System.StringComparison.Ordinal) };
+ var c = AdvisorCatalog.Parse(Head + "messages:\n - { id: x, advisor: dayan, signal: new_game, level: new, media: " + media + " }\n");
+ var t = Strings("advisor.x.text", "advisor.x.cue.1", "lab");
+ var problems = c.Problems(t, t, known);
+ Assert.IsTrue(problems.Any(p => p.Contains(expected)), $"expected '{expected}' in:\n{string.Join("\n", problems)}");
+ }
+
+ [Test]
+ public void AGoodMediaRowHasNoProblems()
+ {
+ var known = new AdvisorCatalog.Known { Signals = new[] { "new_game" }, StreamingFile = _ => true };
+ var c = AdvisorCatalog.Parse(Head + "messages:\n - { id: x, advisor: dayan, signal: new_game, level: new, he_review: approved, " +
+ "media: { picture: x.jpg, narration: { en: x.en.wav, he: x.he.wav }, cues: { en: [0.0, 2.5], he: [0.0, 2.8] }, label: lab } }\n");
+ var t = Strings("advisor.x.text", "advisor.x.cue.1", "advisor.x.cue.2", "lab");
+ Assert.IsNotNull(c.Messages.Single().Media);
+ Assert.AreEqual("x.jpg", c.Messages.Single().Media!.Picture);
+ Assert.IsEmpty(c.Problems(t, t, known));
+ }
+
+ /// <summary>The owner's ruling of 24 October 2026 (#1547): a line without a clip keeps the advisor's portrait, so the
+ /// picture is optional when the row has narration.</summary>
+ [Test]
+ public void AGoodNarrationOnlyRowHasNoProblems()
+ {
+ var known = new AdvisorCatalog.Known { Signals = new[] { "new_game" }, StreamingFile = _ => true };
+ var c = AdvisorCatalog.Parse(Head + "messages:\n - { id: x, advisor: dayan, signal: new_game, level: new, media: { narration: { en: x.en.wav }, cues: { en: [0.0] }, label: lab } }\n");
+ Assert.IsNull(c.Messages.Single().Media!.Picture, "no picture: the portrait stays");
+ Assert.IsEmpty(c.Problems(Strings("advisor.x.text", "advisor.x.cue.1", "lab"), Strings("advisor.x.text", "advisor.x.cue.1", "lab"), known));
+ }
+
[Test]
public void ParsesAMessageWithEveryField()
{
diff --git a/unity/Assets/Tests/EditMode/AdvisorMediaTests.cs b/unity/Assets/Tests/EditMode/AdvisorMediaTests.cs
new file mode 100644
index 000000000..9f5b30a70
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/AdvisorMediaTests.cs
@@ -0,0 +1,457 @@
+#nullable enable
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using NUnit.Framework;
+using Statecraft.Game.UI;
+using Statecraft.Game;
+using Statecraft.Sim;
+using UnityEditor;
+using UnityEngine;
+using UnityEngine.TestTools;
+using UnityEngine.UIElements;
+
+/// <summary>Spec 12 and Review Focus 1 and 2: the picture is silent and the narration a separate file; they start in the
+/// same tick only once both are ready; a drift past 0.1 s is corrected to the narration; live captions follow the
+/// narration's position; one press or a covering layer stops both; the card's own loop is never stopped by the advisor.</summary>
+public class AdvisorMediaTests
+{
+ sealed class FakePicture : AdvisorMedia.IPicture
+ {
+ public bool Ready { get; set; }
+ public double Time { get; set; }
+ public bool Started, Stopped; public int Loads; public readonly List<double> Seeks = new List<double>();
+ public void Load(string url, VisualElement target, Action<string> failed) { Loads++; }
+ public void Start() { Started = true; Stopped = false; }
+ public void Stop() => Stopped = true;
+ public void Seek(double t) { Seeks.Add(t); Time = t; }
+ }
+
+ sealed class FakeOutput : DeclarationRecording.IOutput
+ {
+ public bool Decoded = true; public bool IsPlaying { get; set; } public float Position { get; set; }
+ public bool Played, Stopped;
+ public bool? Ready(AudioClip clip) => Decoded;
+ public void Play(AudioClip clip) { Played = true; Stopped = false; IsPlaying = true; }
+ public void Stop() { Stopped = true; IsPlaying = false; }
+ public void Dispose() { }
+ }
+
+ sealed class Done : DeclarationRecording.IRequest { public ulong Bytes => 0; public void Abort() { } }
+ static DeclarationRecording.Fetch Immediate => (url, done) => { done(AudioClip.Create("n", 4410, 1, 44100, false), null); return new Done(); };
+
+ static readonly AdvisorCatalog.Media Row = new AdvisorCatalog.Media
+ {
+ Picture = "x.mp4", Narration = new Dictionary<string, string> { ["en"] = "x.en.wav" },
+ Cues = new Dictionary<string, List<double>> { ["en"] = new List<double> { 0.0, 2.5 } }, Label = "lab",
+ };
+ static UiText Text => UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.Strings).text +
+ "\nadvisor.t.teach.text: \"Teach.\"\nadvisor.t.warn.text: \"Warn.\"\nadvisor.t.crit.text: \"Critical.\"\nadvisor.x.cue.1: \"First.\"\nadvisor.x.cue.2: \"Second.\"\nlab: \"Label.\"\n" +
+ "advisor.t.teach.cue.1: \"Teach one.\"\nadvisor.t.teach.cue.2: \"Teach two.\"\n");
+
+ readonly List<AdvisorMedia> owned = new List<AdvisorMedia>();
+ [TearDown] public void Clean() { foreach (var media in owned) media.Dispose(); owned.Clear(); }
+
+ (AdvisorMedia media, FakePicture pic, FakeOutput output, Label caption) Make()
+ {
+ var pic = new FakePicture(); var output = new FakeOutput(); var caption = new Label();
+ var media = new AdvisorMedia(Text, pic, null, Immediate, output);
+ owned.Add(media);
+ media.Play(Row, "advisor.x", false, new VisualElement(), caption, () => { }, _ => { });
+ return (media, pic, output, caption);
+ }
+
+ [Test]
+ public void PictureAndNarrationStartTogether()
+ {
+ var (media, pic, output, _) = Make();
+ media.Tick();
+ Assert.IsFalse(pic.Started || output.Played, "the picture is not ready: neither starts");
+ pic.Ready = true;
+ media.Tick();
+ Assert.IsTrue(pic.Started && output.Played, "both in the same tick");
+ }
+
+ [Test]
+ public void ADriftIsCorrectedToTheNarration()
+ {
+ var (media, pic, output, _) = Make();
+ pic.Ready = true; media.Tick();
+ output.Position = 3.0f; pic.Time = 2.8; media.Tick();
+ CollectionAssert.AreEqual(new[] { 3.0 }, pic.Seeks);
+ output.Position = 3.5f; pic.Time = 3.45; media.Tick();
+ Assert.AreEqual(1, pic.Seeks.Count, "within 0.1 s: left alone");
+ }
+
+ [Test]
+ public void CaptionsFollowTheNarrationsPosition()
+ {
+ var (media, pic, output, caption) = Make();
+ pic.Ready = true; media.Tick();
+ output.Position = 0.1f; media.Tick();
+ Assert.AreEqual("First.", caption.text);
+ output.Position = 2.6f; media.Tick();
+ Assert.AreEqual("Second.", caption.text);
+ Assert.AreEqual(-1, AdvisorCaptions.At(new[] { 0.5 }, 0.2));
+ }
+
+ [Test]
+ public void OnePressStopsBoth()
+ {
+ var (media, pic, output, caption) = Make();
+ pic.Ready = true; media.Tick(); output.Position = 0.1f; media.Tick();
+ media.Stop();
+ Assert.IsTrue(pic.Stopped && output.Stopped);
+ Assert.AreEqual("", caption.text);
+ Assert.IsFalse(media.Playing);
+ }
+
+ /// <summary>Review Focus 1: the advisor borrows the card's player only while no card is open; whatever stops the advisor's
+ /// clip never stops the card's own illustration loop on the same player.</summary>
+ [Test]
+ public void ALayerOverAPlayingClipStopsBothAndLeavesTheCardsLoopAlone()
+ {
+ bool previous = LogAssert.ignoreFailingMessages;
+ try
+ {
+ LogAssert.ignoreFailingMessages = true; // only the deliberately nonexistent URL ownership probe
+ using var video = new CardVideo();
+ var header = new VisualElement(); var clip = new ClipPicture(video);
+ clip.Load("advisor-clip.mp4", header, _ => { });
+ video.Play("card-loop.mp4", header, _ => { });
+ clip.Stop();
+ Assert.AreEqual("card-loop.mp4", video.Current, "the card's loop is not the advisor's to stop");
+ }
+ finally { LogAssert.ignoreFailingMessages = previous; }
+
+ using var rig = new AdvisorPopupTests.Rig(text: Text);
+ var pic = new FakePicture { Ready = true }; var output = new FakeOutput();
+ rig.Advisor.Media = new AdvisorMedia(Text, pic, null, Immediate, output);
+ rig.Advisor.NewGame();
+ rig.Advisor.Watch(Row, "advisor.x");
+ rig.Advisor.Media.Tick();
+ Assert.IsTrue(rig.Advisor.Media.Playing, "precondition");
+ rig.HudRoot.AddToClassList(EventCardPresenter.OpenClass); ScreenNav.DisableCovered(rig.Ui.Root);
+ Assert.IsTrue(pic.Stopped && output.Stopped, "a layer over it stops picture and narration at once");
+ }
+ [TestCase(HudTier.OneRow, 506f, true)] // 1920x1080
+ [TestCase(HudTier.OneRow, 400f, false)] // 844x390: a phone held sideways
+ [TestCase(HudTier.TwoRow, 746f, true)] // 960x1080
+ [TestCase(HudTier.ThreeRow, 1164f, false)] // an upright phone: always the overlay
+ public void InlineWhereTheSlotHasRoom(HudTier tier, float slot, bool inline) => Assert.AreEqual(inline, AdvisorMedia.Inline(tier, slot));
+
+ [Test]
+ public void WatchPlaysInThePopupWithCaptionsInTheTextsPlace()
+ {
+ using var rig = new AdvisorPopupTests.Rig(text: Text);
+ var pic = new FakePicture { Ready = true }; var output = new FakeOutput();
+ rig.Advisor.Media = new AdvisorMedia(Text, pic, null, Immediate, output);
+ rig.Advisor.ForceInline = true; // EditMode's panel has no real slot height
+ rig.Advisor.NewGame();
+ rig.Advisor.Watch(Row, "advisor.x");
+ Assert.IsTrue(rig.Ui.Q<VisualElement>("advisor-popup").ClassListContains("advisor-watching"));
+ rig.Ui.Press("advisor-got-it");
+ Assert.IsTrue(output.Stopped, "any button stops it");
+ Assert.IsFalse(rig.Ui.Q<VisualElement>("advisor-popup").ClassListContains("advisor-watching"));
+ }
+
+ [Test]
+ public void TheOverlayClosesWithItsXOrEscapeAndStopsBoth()
+ {
+ using var rig = new AdvisorPopupTests.Rig(text: Text);
+ var pic = new FakePicture { Ready = true }; var output = new FakeOutput();
+ rig.Advisor.Media = new AdvisorMedia(Text, pic, null, Immediate, output);
+ rig.Advisor.ForceInline = false;
+ rig.Advisor.NewGame();
+ // ScreenNav's Cancel trickles down from the root and closes the open screen unless a layer takes it first: GameRoot
+ // gives the overlay that turn through TakesEscape (GameRoot.cs, nav!.TakesEscape), wired here the same way.
+ rig.Nav.TakesEscape = () => rig.Advisor.CloseOverlay() || rig.Advisor.OverlayClosedThisFrame || rig.Advisor.Escape();
+ rig.Ui.Press("nav-budget"); // a screen under the overlay
+ Assert.AreEqual("budget", rig.Nav.Current, "precondition");
+ var close = rig.Ui.Q<Button>("advisor-overlay-close");
+
+ rig.Advisor.Watch(Row, "advisor.x");
+ Assert.IsTrue(rig.HudRoot.ClassListContains("advisor-overlay-open"));
+ rig.Ui.Press("advisor-overlay-close");
+ Assert.IsTrue(pic.Stopped && output.Stopped, "the X stops picture and narration");
+ Assert.IsFalse(rig.HudRoot.ClassListContains("advisor-overlay-open"));
+ Assert.AreEqual("budget", rig.Nav.Current, "the X closes only the overlay");
+
+ pic.Stopped = output.Stopped = false;
+ rig.Advisor.Watch(Row, "advisor.x");
+ Assert.IsTrue(rig.HudRoot.ClassListContains("advisor-overlay-open"));
+ using (var esc = NavigationCancelEvent.GetPooled()) { esc.target = close; close.SendEvent(esc); }
+ Assert.IsTrue(pic.Stopped && output.Stopped, "Escape stops picture and narration");
+ Assert.IsFalse(rig.HudRoot.ClassListContains("advisor-overlay-open"));
+ Assert.AreEqual("budget", rig.Nav.Current, "Escape closes only the overlay, not the screen under it");
+ Assert.IsFalse(rig.Advisor.CloseOverlay(), "nothing to close");
+ }
+ [Test]
+ public void ConstructionDoesNotFetchOrPlay()
+ {
+ int fetched = 0;
+ var pic = new FakePicture(); var output = new FakeOutput();
+ using var media = new AdvisorMedia(Text, pic, null, (url, done) => { fetched++; return new Done(); }, output);
+ Assert.AreEqual(0, fetched); Assert.AreEqual(0, pic.Loads);
+ Assert.IsFalse(output.Played || pic.Started || media.Playing);
+ }
+
+ [Test]
+ public void AReadyPictureWaitsForTheAudioToDecode()
+ {
+ var (media, pic, output, _) = Make();
+ pic.Ready = true; output.Decoded = false; media.Tick();
+ Assert.IsFalse(pic.Started || output.Played);
+ output.Decoded = true; media.Tick();
+ Assert.IsTrue(pic.Started && output.Played);
+ }
+
+ [Test]
+ public void AStoppedFetchCannotRestartPlayback()
+ {
+ Action<AudioClip?, string?>? done = null;
+ var pic = new FakePicture { Ready = true }; var output = new FakeOutput(); var caption = new Label();
+ using var media = new AdvisorMedia(Text, pic, null, (url, callback) => { done = callback; return new Done(); }, output);
+ media.Play(Row, "advisor.x", false, new VisualElement(), caption, () => Assert.Fail("stopped"), _ => Assert.Fail("stopped"));
+ media.Stop();
+ done!(AudioClip.Create("late", 4410, 1, 44100, false), null);
+ media.Tick();
+ Assert.IsFalse(media.Playing || output.Played || pic.Started); Assert.AreEqual("", caption.text);
+ }
+
+ [Test]
+ public void AnUnmovingFetchFailsOnceWithinTheExistingStallBudget()
+ {
+ var pic = new FakePicture { Ready = true }; var output = new FakeOutput(); int failed = 0;
+ using var media = new AdvisorMedia(Text, pic, null, (url, done) => new Done(), output);
+ LogAssert.Expect(LogType.Warning, new System.Text.RegularExpressions.Regex("ADVISOR MEDIA failed.*fetch.*"));
+ media.Play(Row, "advisor.x", false, new VisualElement(), new Label(), () => Assert.Fail("not loaded"), _ => failed++);
+ for (int i = 0; i <= DeclarationRecording.StallTimeoutMs / AdvisorMedia.TickMs; i++) media.Tick();
+ Assert.AreEqual(1, failed); Assert.IsFalse(media.Playing); Assert.IsTrue(pic.Stopped && output.Stopped);
+ }
+ [Test]
+ public void AButtonStopsMediaBeforeItOpensAnotherWindow()
+ {
+ using var rig = new AdvisorPopupTests.Rig(text: Text);
+ var pic = new FakePicture { Ready = true }; var output = new FakeOutput();
+ rig.Advisor.Media = new AdvisorMedia(Text, pic, null, Immediate, output);
+ rig.Advisor.ForceInline = true; rig.Advisor.NewGame(); rig.Advisor.Watch(Row, "advisor.x"); rig.Advisor.Media.Tick();
+ Assert.IsTrue(rig.Advisor.Media.Playing);
+ rig.Ui.Press("nav-budget");
+ Assert.IsTrue(pic.Stopped && output.Stopped); Assert.AreEqual("budget", rig.Nav.Current);
+ }
+
+ [Test]
+ public void ASecondWatchPressStopsWithoutRestarting()
+ {
+ var catalog = AdvisorPopupTests.Fixture.Replace("level: new, actions: [{ open_screen: budget }]",
+ "level: new, media: { picture: x.mp4, narration: { en: x.en.wav }, cues: { en: [0, 2.5] }, label: lab }");
+ using var rig = new AdvisorPopupTests.Rig(catalog: catalog, text: Text);
+ var pic = new FakePicture { Ready = true }; var output = new FakeOutput();
+ rig.Advisor.Media = new AdvisorMedia(Text, pic, null, Immediate, output);
+ rig.Advisor.ForceInline = true; rig.Advisor.NewGame();
+ rig.Ui.Press("advisor-watch"); rig.Advisor.Media.Tick();
+ Assert.IsTrue(rig.Advisor.Media.Playing);
+ rig.Ui.Press("advisor-watch");
+ Assert.IsFalse(rig.Advisor.Media.Playing); Assert.AreEqual(1, pic.Loads);
+ }
+
+ [UnityTest]
+ public System.Collections.IEnumerator InlineKeepsItsXAndAPhoneStopsItBeforeUsingTheOverlay()
+ {
+ var wide = new RenderTexture(1280, 720, 0);
+ var panel = UnityEngine.Object.Instantiate(AssetDatabase.LoadAssetAtPath<PanelSettings>(UiPaths.Panel)); panel.targetTexture = wide;
+ var go = new GameObject("AdvisorMediaGeometry"); go.SetActive(false);
+ var doc = go.AddComponent<UIDocument>(); doc.panelSettings = panel;
+ doc.visualTreeAsset = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(UiPaths.GameUxml); go.SetActive(true);
+ var root = doc.rootVisualElement; var hudRoot = root.Q("root"); hudRoot.RemoveFromClassList("loading");
+ var bridge = new SimBridge(GameSession.New(ContentLoader.Load(Paths.Content), GoldenRun.Seed, Mode.Historical), Text);
+ var hud = new HudPresenter(root, bridge, Text); var nav = new ScreenNav(root);
+ var card = new EventCardPresenter(root, bridge, Text, null); card.Collapse(takeFocus: false);
+ var session = new AdvisorSession(AdvisorCatalog.Parse(AdvisorPopupTests.Fixture), new AdvisorSettings(null), true);
+ var advisor = new AdvisorPresenter(root, bridge, Text, session, hooks: new AdvisorHooks { Card = card });
+ var pic = new FakePicture { Ready = true }; var output = new FakeOutput();
+ advisor.Media = new AdvisorMedia(Text, pic, null, Immediate, output);
+ try
+ {
+ advisor.NewGame(); for (int i = 0; i < 6; i++) yield return null;
+ advisor.ForceInline = true; advisor.Watch(Row, "advisor.x"); advisor.Media.Tick(); output.Position = 0.1f;
+ for (int i = 0; i < 4; i++) yield return null;
+ Assert.IsTrue(AdvisorTargets.Shown(root.Q("advisor-close")), "inline keeps X usable");
+ // A runtime targetTexture swap does not resize an EditMode panel (it stayed 1920x1080 panel px for 30 frames), so the
+ // HUD root takes an upright phone's size in panel px (390x844 at the 1280x720 panel's 1.5 panel px per pixel).
+ advisor.ForceInline = null; hudRoot.style.width = 585; hudRoot.style.height = 1266;
+ for (int i = 0; i < 6; i++) yield return null;
+ Assert.IsTrue(hudRoot.ClassListContains(HudPresenter.ThreeRowClass));
+ Assert.IsFalse(advisor.Media.Playing, "inline stops when the new tier has no room; no automatic replay");
+ advisor.ForceInline = false; advisor.Watch(Row, "advisor.x"); advisor.Media.Tick(); output.Position = 0.1f;
+ for (int i = 0; i < 6; i++) yield return null;
+ var picture = root.Q("advisor-overlay-media").worldBound;
+ Assert.Greater(picture.height, 0); Assert.AreEqual(EventCardPresenter.MediaAspect, picture.width / picture.height, 0.02f);
+ Assert.GreaterOrEqual(root.Q("advisor-overlay-caption").resolvedStyle.fontSize * root.panel.scaledPixelsPerPoint, HudPresenter.TextFloorPx - 0.01f);
+ }
+ finally
+ {
+ advisor.Dispose(); card.Dispose(); nav.Dispose(); hud.Dispose();
+ UnityEngine.Object.DestroyImmediate(go); UnityEngine.Object.DestroyImmediate(panel);
+ wide.Release(); UnityEngine.Object.DestroyImmediate(wide);
+ }
+ }
+
+ // The owner's ruling of 24 October 2026 (#1547; spec 12; plan Task 25), per line: play the clip, or a supplied still,
+ // when present; otherwise keep the advisor's portrait and play the narration with live captions when the current
+ // language has it; otherwise the portrait and the text, with no Watch. The disclosure (#1530, OQ-16) is one small line
+ // under the live caption.
+
+ const string Disclosure = "AI animation and voice. Fictional dialogue.";
+ const string VoiceOnly = "{ narration: { en: t.en.wav }, cues: { en: [0, 2.5] }, label: advisor.media_label }";
+ static string TeachWith(string media) =>
+ AdvisorPopupTests.Fixture.Replace("level: new, actions: [{ open_screen: budget }]", "level: new, media: " + media);
+ static AdvisorCatalog.Media Voice(string label = "lab") => new AdvisorCatalog.Media
+ {
+ Narration = new Dictionary<string, string> { ["en"] = "x.en.wav" },
+ Cues = new Dictionary<string, List<double>> { ["en"] = new List<double> { 0.0, 2.5 } }, Label = label,
+ };
+ static AdvisorCatalog.Media Picture(string file, string label = "lab") => new AdvisorCatalog.Media
+ {
+ Picture = file, Narration = new Dictionary<string, string> { ["en"] = "x.en.wav" },
+ Cues = new Dictionary<string, List<double>> { ["en"] = new List<double> { 0.0, 2.5 } }, Label = label,
+ };
+
+ [Test]
+ public void ANarrationOnlyRowPlaysTheVoiceWithNoPicturePlayer()
+ {
+ var clip = new FakePicture(); var still = new FakePicture(); var output = new FakeOutput(); var caption = new Label();
+ var media = new AdvisorMedia(Text, clip, still, Immediate, output); owned.Add(media);
+ media.Play(Voice(), "advisor.x", false, new VisualElement(), caption, () => { }, why => Assert.Fail("a voice-only line plays: " + why));
+ media.Tick();
+ Assert.IsTrue(output.Played && media.Playing, "the voice starts with no picture to wait for");
+ Assert.AreEqual(0, clip.Loads + still.Loads, "no picture player is used");
+ output.Position = 0.1f; media.Tick();
+ Assert.AreEqual("First.", caption.text);
+ output.Position = 2.6f; media.Tick();
+ Assert.AreEqual("Second.", caption.text);
+ media.Stop();
+ Assert.IsTrue(output.Stopped); Assert.AreEqual("", caption.text); Assert.IsFalse(media.Playing);
+ }
+
+ [Test]
+ public void ASuppliedStillIsAPictureAndPlaysAsOne()
+ {
+ using var rig = new AdvisorPopupTests.Rig(text: Text);
+ var clip = new FakePicture { Ready = true }; var still = new FakePicture { Ready = true }; var output = new FakeOutput();
+ rig.Advisor.Media = new AdvisorMedia(Text, clip, still, Immediate, output);
+ rig.Advisor.ForceInline = true; rig.Advisor.NewGame();
+ rig.Advisor.Watch(Picture("x.jpg"), "advisor.x"); rig.Advisor.Media.Tick();
+ Assert.AreEqual(1, still.Loads); Assert.AreEqual(0, clip.Loads);
+ Assert.IsTrue(still.Started && output.Played);
+ Assert.IsTrue(rig.Ui.Q<VisualElement>("advisor-popup").ClassListContains("advisor-watching"), "the still takes the portrait row's place");
+ }
+
+ [Test]
+ public void ANarrationOnlyLineKeepsThePortraitAndSpeaksWithLiveCaptions()
+ {
+ using var rig = new AdvisorPopupTests.Rig(catalog: TeachWith(VoiceOnly), text: Text);
+ var clip = new FakePicture(); var still = new FakePicture(); var output = new FakeOutput();
+ rig.Advisor.Media = new AdvisorMedia(Text, clip, still, Immediate, output);
+ rig.Advisor.ForceInline = false; // where a picture would take the overlay
+ rig.Advisor.NewGame();
+ Assert.AreNotEqual(DisplayStyle.None, rig.Ui.Q<Button>("advisor-watch").style.display.value, "a voice is playable: Watch shows");
+ rig.Ui.Press("advisor-watch"); rig.Advisor.Media!.Tick();
+ Assert.IsTrue(output.Played && rig.Advisor.Media.Playing);
+ var popup = rig.Ui.Q<VisualElement>("advisor-popup");
+ Assert.IsFalse(popup.ClassListContains("advisor-watching"), "the portrait row stays");
+ Assert.IsFalse(rig.HudRoot.ClassListContains("advisor-overlay-open"), "no overlay without a picture");
+ Assert.AreEqual(0, clip.Loads + still.Loads, "the card's player is not borrowed");
+ output.Position = 0.1f; rig.Advisor.Media.Tick();
+ Assert.AreEqual("Teach one.", rig.Ui.Q<Label>("advisor-text").text, "the live caption takes the text's place");
+ Assert.AreEqual(Disclosure, rig.Ui.Q<Label>("advisor-media-label").text);
+ rig.Ui.Press("advisor-got-it");
+ Assert.IsTrue(output.Stopped, "any popup button stops the voice");
+ Assert.IsFalse(rig.Advisor.Media.Playing);
+ }
+
+ [TestCase("")] // no media row
+ [TestCase("{ picture: x.mp4, narration: { he: x.he.wav }, cues: { he: [0] }, label: advisor.media_label }")] // nothing in English
+ public void ALineWithNothingToPlayHasNoWatchAndKeepsThePortraitAndText(string media)
+ {
+ using var rig = new AdvisorPopupTests.Rig(catalog: media == "" ? AdvisorPopupTests.Fixture : TeachWith(media), text: Text);
+ var clip = new FakePicture { Ready = true }; var still = new FakePicture { Ready = true }; var output = new FakeOutput();
+ rig.Advisor.Media = new AdvisorMedia(Text, clip, still, Immediate, output);
+ rig.Advisor.ForceInline = true; rig.Advisor.NewGame();
+ Assert.AreEqual(DisplayStyle.None, rig.Ui.Q<Button>("advisor-watch").style.display.value, "no Watch control");
+ if (rig.Session.Catalog.Messages.First(m => m.Id == "t.teach").Media is AdvisorCatalog.Media row) rig.Advisor.Watch(row, "advisor.t.teach");
+ Assert.IsFalse(rig.Advisor.Media!.Playing || output.Played); Assert.AreEqual(0, clip.Loads + still.Loads);
+ Assert.AreEqual("Teach.", rig.Ui.Q<Label>("advisor-text").text);
+ Assert.IsFalse(rig.Ui.Q<VisualElement>("advisor-popup").ClassListContains("advisor-watching"));
+ Assert.IsFalse(rig.HudRoot.ClassListContains("advisor-overlay-open"));
+ }
+
+ [Test]
+ public void AVoiceOnlyFailureHidesThatLinesWatchByItsOwnFile()
+ {
+ using var rig = new AdvisorPopupTests.Rig(catalog: TeachWith(VoiceOnly), text: Text);
+ var output = new FakeOutput();
+ rig.Advisor.Media = new AdvisorMedia(Text, new FakePicture(), new FakePicture(), (url, done) => { done(null, "404"); return new Done(); }, output);
+ rig.Advisor.NewGame();
+ LogAssert.Expect(LogType.Warning, new System.Text.RegularExpressions.Regex("ADVISOR MEDIA failed t\\.en\\.wav: fetch"));
+ rig.Ui.Press("advisor-watch");
+ CollectionAssert.AreEquivalent(new[] { "t.en.wav" }, rig.Session.MediaFailed, "never an empty picture name that would hide every voice-only line");
+ Assert.AreEqual(DisplayStyle.None, rig.Ui.Q<Button>("advisor-watch").style.display.value);
+ }
+
+ /// <summary>OQ-16 (#1530): the disclosure is the exact text, one small muted line at the bar's small text size, under
+ /// the live caption, never over the picture: under the voice's caption, the inline picture's and the overlay's.</summary>
+ [UnityTest]
+ public System.Collections.IEnumerator TheDisclosureIsSmallAndUnderTheCaptionWhereverItPlays()
+ {
+ Assert.AreEqual(Disclosure, Text["advisor.media_label"]);
+ var wide = new RenderTexture(1280, 720, 0);
+ var panel = UnityEngine.Object.Instantiate(AssetDatabase.LoadAssetAtPath<PanelSettings>(UiPaths.Panel)); panel.targetTexture = wide;
+ var go = new GameObject("AdvisorDisclosure"); go.SetActive(false);
+ var doc = go.AddComponent<UIDocument>(); doc.panelSettings = panel;
+ doc.visualTreeAsset = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(UiPaths.GameUxml); go.SetActive(true);
+ var root = doc.rootVisualElement; var hudRoot = root.Q("root"); hudRoot.RemoveFromClassList("loading");
+ var bridge = new SimBridge(GameSession.New(ContentLoader.Load(Paths.Content), GoldenRun.Seed, Mode.Historical), Text);
+ var hud = new HudPresenter(root, bridge, Text); var nav = new ScreenNav(root);
+ var card = new EventCardPresenter(root, bridge, Text, null); card.Collapse(takeFocus: false);
+ var session = new AdvisorSession(AdvisorCatalog.Parse(TeachWith(VoiceOnly)), new AdvisorSettings(null), true);
+ var advisor = new AdvisorPresenter(root, bridge, Text, session, hooks: new AdvisorHooks { Card = card });
+ var output = new FakeOutput();
+ advisor.Media = new AdvisorMedia(Text, new FakePicture { Ready = true }, new FakePicture { Ready = true }, Immediate, output);
+ void Small(string where, string label, string caption, string? picture)
+ {
+ var l = root.Q<Label>(label); var c = root.Q<Label>(caption);
+ Assert.AreEqual(Disclosure, l.text, where);
+ Assert.IsTrue(AdvisorTargets.Shown(l), where + ": the disclosure shows");
+ Assert.GreaterOrEqual(l.worldBound.yMin, c.worldBound.yMax - 0.5f, where + ": under the live caption");
+ if (picture != null) Assert.GreaterOrEqual(l.worldBound.yMin, root.Q(picture).worldBound.yMax - 0.5f, where + ": never over the picture");
+ Assert.AreEqual(HudPresenter.SmallTextSize(HudPresenter.ScreenPxPerPanelPx(root.panel)), l.resolvedStyle.fontSize, 0.01f, where + ": the bar's small text size");
+ Assert.Less(l.resolvedStyle.fontSize, c.resolvedStyle.fontSize, where + ": smaller than the caption");
+ }
+ try
+ {
+ advisor.NewGame(); for (int i = 0; i < 6; i++) yield return null;
+ advisor.Watch(session.Catalog.Messages.First(m => m.Id == "t.teach").Media!, "advisor.t.teach"); advisor.Media.Tick(); output.Position = 0.1f; advisor.Media.Tick();
+ for (int i = 0; i < 4; i++) yield return null;
+ Assert.IsTrue(AdvisorTargets.Shown(root.Q("advisor-portrait")), "a voice-only line keeps the portrait");
+ Small("voice only", "advisor-media-label", "advisor-text", null);
+
+ advisor.ForceInline = true; advisor.Watch(Picture("x.mp4", "advisor.media_label"), "advisor.x"); advisor.Media.Tick(); output.Position = 0.1f; advisor.Media.Tick();
+ for (int i = 0; i < 4; i++) yield return null;
+ Small("inline picture", "advisor-media-label", "advisor-text", "advisor-media");
+
+ advisor.ForceInline = false; advisor.Watch(Picture("x.mp4", "advisor.media_label"), "advisor.x"); advisor.Media.Tick(); output.Position = 0.1f; advisor.Media.Tick();
+ for (int i = 0; i < 4; i++) yield return null;
+ Small("overlay", "advisor-overlay-label", "advisor-overlay-caption", "advisor-overlay-media");
+ Assert.IsFalse(AdvisorTargets.Shown(root.Q("advisor-popup")), "the popup hides under its overlay");
+ Assert.Less(root.Q("advisor-overlay-close").worldBound.width, 100f, "the overlay's X is a button, not a bar");
+ }
+ finally
+ {
+ advisor.Dispose(); card.Dispose(); nav.Dispose(); hud.Dispose();
+ UnityEngine.Object.DestroyImmediate(go); UnityEngine.Object.DestroyImmediate(panel);
+ wide.Release(); UnityEngine.Object.DestroyImmediate(wide);
+ }
+ }
+}
diff --git a/unity/Assets/Tests/EditMode/AdvisorMediaTests.cs.meta b/unity/Assets/Tests/EditMode/AdvisorMediaTests.cs.meta
new file mode 100644
index 000000000..01124f3e3
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/AdvisorMediaTests.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: c33ad0dd5e25477ba1297afb1e68f327
diff --git a/unity/Assets/UI/Game.uxml b/unity/Assets/UI/Game.uxml
index 91304f522..ffeb9bebe 100644
--- a/unity/Assets/UI/Game.uxml
+++ b/unity/Assets/UI/Game.uxml
@@ -459,16 +459,20 @@
<ui:VisualElement name="advisor-ring" class="advisor-ring" picking-mode="Ignore" />
<ui:VisualElement name="advisor-popup" class="panel advisor-popup">
<ui:VisualElement class="row advisor-head">
- <ui:VisualElement name="advisor-portrait" class="advisor-portrait" />
+ <ui:VisualElement name="advisor-portrait" class="advisor-portrait"><ui:Button name="advisor-watch" class="advisor-watch" /></ui:VisualElement>
<ui:VisualElement class="advisor-names">
<ui:Label name="advisor-name" class="title advisor-name" />
<ui:Label name="advisor-role" class="muted advisor-role" />
</ui:VisualElement>
<ui:Button name="advisor-close" class="advisor-close" />
</ui:VisualElement>
+ <ui:VisualElement name="advisor-media" class="advisor-media" />
<ui:ScrollView name="advisor-body" class="advisor-body">
<ui:Label name="advisor-text" class="advisor-text" />
</ui:ScrollView>
+ <!-- The disclosure and credit: under the live caption, never over the picture (spec 12, OQ-16). -->
+ <ui:Label name="advisor-media-label" class="muted advisor-media-label" />
+ <ui:Label name="advisor-media-credit" class="muted advisor-media-label" />
<ui:VisualElement class="row advisor-actions">
<ui:Button name="advisor-show-me" />
<ui:Button name="advisor-more" />
@@ -518,6 +522,19 @@
<Statecraft.Game.UI.UiFrame filigree="true" />
</ui:VisualElement>
</ui:VisualElement>
+ <!-- User-started advisor media, after outcome clips; the start screen/feedback still cover it. -->
+ <ui:VisualElement name="advisor-overlay" class="advisor-overlay">
+ <ui:VisualElement name="advisor-overlay-frame" class="panel advisor-overlay-frame">
+ <ui:Button name="advisor-overlay-close" class="advisor-close" />
+ <ui:VisualElement name="advisor-overlay-media" class="advisor-overlay-media" />
+ <ui:ScrollView class="advisor-overlay-words">
+ <ui:Label name="advisor-overlay-caption" class="advisor-text" />
+ <ui:Label name="advisor-overlay-label" class="muted advisor-media-label" />
+ <ui:Label name="advisor-overlay-credit" class="muted advisor-media-label" />
+ </ui:ScrollView>
+ <Statecraft.Game.UI.UiFrame filigree="true" />
+ </ui:VisualElement>
+ </ui:VisualElement>
<!-- The start screen (StartScreenPresenter): shown over the started game before its first turn (never in automated
runs). The painting is AI-generated concept art (ASSETS.yaml), with no identifiable person. The two quotations
are the Declaration of the Establishment of the State of Israel, word for word: the official Hebrew (Iton
diff --git a/unity/Assets/UI/Statecraft.uss b/unity/Assets/UI/Statecraft.uss
index 8fb07b933..124a38ea3 100644
--- a/unity/Assets/UI/Statecraft.uss
+++ b/unity/Assets/UI/Statecraft.uss
@@ -1026,3 +1026,26 @@ Button.settings-choice-selected { -unity-font-definition: url("project://databas
one-row bar, 8 in the narrow one. */
.advisor-ring-open #attention { margin-bottom: 5px; }
.advisor-ring-open.hud-narrow #attention { margin-bottom: 8px; }
+
+/* User-started advisor media: live caption replaces the prose; no shipped media row means no Watch badge. */
+.advisor-watch { display: none; position: absolute; bottom: 0; left: 0; right: 0; min-width: 0; font-size: 15px; padding: 1px 2px; }
+.advisor-media, .advisor-media-label { display: none; }
+.advisor-media { width: 100%; height: 205px; flex-shrink: 0; background-size: contain; background-color: var(--navy-deep); }
+.advisor-watching .advisor-media, .advisor-watching .advisor-media-label { display: flex; }
+.advisor-narrating .advisor-media-label { display: flex; } /* a voice-only line: portrait and caption stay, the disclosure under it */
+.advisor-watching .advisor-portrait { display: none; }
+.advisor-media-label { white-space: normal; font-size: 15px; flex-shrink: 0; }
+.advisor-overlay { display: none; position: absolute; left: 0; top: 0; right: 0; bottom: 0; justify-content: center; align-items: center; background-color: rgba(5, 9, 18, 0.72); padding: 16px; }
+.advisor-overlay-open .advisor-overlay { display: flex; }
+.advisor-overlay-open .advisor-layer { display: none; }
+.advisor-overlay-frame { width: 1000px; max-width: 100%; max-height: 100%; padding: 16px 20px; }
+.advisor-overlay-frame > .advisor-close { align-self: flex-end; } /* the X at the top corner, not a full-width bar */
+.lang-he .advisor-overlay-frame > .advisor-close { align-self: flex-start; }
+.advisor-overlay-media { width: 100%; height: 540px; flex-shrink: 0; background-size: contain; background-color: var(--navy-deep); }
+.advisor-overlay .advisor-media-label { display: flex; }
+.advisor-overlay-words { flex-shrink: 1; min-height: 0; }
+
+.advisor-watching .advisor-head { position: absolute; right: 8px; top: 8px; margin: 0; }
+.advisor-no-portrait.advisor-has-media .advisor-portrait { display: flex; }
+
+.advisor-watching .advisor-head > .advisor-portrait, .advisor-watching .advisor-head > .advisor-names { display: none; }
diff --git a/unity/Assets/UI/strings.en.yaml b/unity/Assets/UI/strings.en.yaml
index 5eb8bfd0f..886c5f4ed 100644
--- a/unity/Assets/UI/strings.en.yaml
+++ b/unity/Assets/UI/strings.en.yaml
@@ -640,3 +640,18 @@ advisor.next: "Next"
advisor.done: "Done"
# {0} the step, {1} the steps in the chain now.
advisor.step: "Step {0} of {1}"
+
+# Advisor media control (spec12). Hebrew UI draft for the native reviewer (#564).
+advisor.watch: "Watch"
+# The media row's disclosure (owner, 24 Oct 2026, OQ-16 option 2; spec 11.3, 12): exactly this text, shown small.
+advisor.media_label: "AI animation and voice. Fictional dialogue."
+
+# S6a caption keys: same text as the C68 recorded opening lines; no media row/files assigned.
+# Hebrew cues remain agent drafts and require the parent opening row’s native approval.
+advisor.opening.greeting.cue.1: "The country has urgent needs and limited means. The decisions are theirs, and the advisers will explain what each choice changes."
+advisor.opening.attention.cue.1: "Attention is the capacity for decisions this month. It refills next month, and any amount left now does not carry over."
+advisor.opening.city.cue.1: "A city shows its housing, housing condition, jobs, and people. Employment brings in Money, while overcrowding can weaken Social cohesion."
+advisor.opening.training.cue.1: "Training uses civilians without work, Money, and time. Halutz and craftsman training supports development; military training also requires Arms."
+advisor.opening.move.cue.1: "A unit moves at once, and terrain sets the cost of each hex. A farther destination creates a route that continues on later turns."
+advisor.opening.event.cue.1: "An event card presents a decision and shows its effects. A card left unanswered when the month ends goes to the responsible minister."
+advisor.opening.objectives.cue.1: "Objectives define the campaign's goals and compare each completion date with its historical date. Completion awards points and opens the objective's event card."
diff --git a/unity/Assets/UI/strings.he.yaml b/unity/Assets/UI/strings.he.yaml
index 14c37cca5..1b8264f99 100644
--- a/unity/Assets/UI/strings.he.yaml
+++ b/unity/Assets/UI/strings.he.yaml
@@ -681,3 +681,18 @@ advisor.opening.objectives.text: "היעדים מגדירים את מטרות ה
advisor.next: "הבא"
advisor.done: "סיום"
advisor.step: "שלב {0} מתוך {1}"
+
+# Advisor media control (spec12). Hebrew UI draft for the native reviewer (#564).
+advisor.watch: "צפייה"
+# The media row's disclosure (OQ-16). Hebrew draft for the native reviewer (#564).
+advisor.media_label: "הנפשה וקול בבינה מלאכותית. דיאלוג בדיוני."
+
+# S6a caption keys: same text as the C68 recorded opening lines; no media row/files assigned.
+# Hebrew cues remain agent drafts and require the parent opening row’s native approval.
+advisor.opening.greeting.cue.1: "למדינה צרכים דחופים ואמצעים מוגבלים. ההחלטות בידיכם, והיועצים יסבירו מה כל בחירה משנה."
+advisor.opening.attention.cue.1: "תשומת לב היא היכולת לקבל החלטות בחודש הזה. היא מתמלאת מחדש בחודש הבא, ומה שנשאר עכשיו אינו עובר הלאה."
+advisor.opening.city.cue.1: "בעיר מוצגים הדיור, מצב הדיור, המשרות והאנשים. תעסוקה מכניסה כסף, ואילו צפיפות יתר עלולה להחליש את הלכידות החברתית."
+advisor.opening.training.cue.1: "אימון והכשרה דורשים אזרחים ללא עבודה, כסף וזמן. הכשרת חלוצים ובעלי מלאכה תומכת בפיתוח; אימון צבאי דורש גם נשק."
+advisor.opening.move.cue.1: "יחידה נעה מיד, והשטח קובע את העלות של כל משושה. יעד רחוק יותר יוצר מסלול שממשיך בתורות הבאים."
+advisor.opening.event.cue.1: "כרטיס אירוע מציג החלטה ואת השפעותיה. כרטיס שלא נענה בסיום החודש עובר לשר האחראי."
+advisor.opening.objectives.cue.1: "היעדים מגדירים את מטרות המערכה ומשווים כל תאריך השלמה לתאריך ההיסטורי שלו. השלמה מעניקה נקודות ופותחת את כרטיס האירוע של היעד."