using System.IO;
using UnityEngine;
using UnityEngine.Video;
namespace GrassCutter
{
///
/// A character's talking loops (Assets/StreamingAssets/Talk/<who>_<mood>.webm, VP8 with alpha, made by
/// Tools/director/talk_videos.py): one player per mood, each looping into its own texture. The picture shows the one for
/// the mood of the moment; the others wait where they left off, so a change of mood is a cut, not a stall.
///
public class TalkVideo
{
readonly VideoPlayer[] _players;
readonly RenderTexture[] _rts;
int _on = -1;
/// The picture now; says when it changes.
public RenderTexture Rt => _rts[Mathf.Max(0, _on)];
public System.Action Switched;
public TalkVideo(string who, string[] moods, int w, int h)
{
var go = new GameObject("Talk " + who);
Object.DontDestroyOnLoad(go);
_players = new VideoPlayer[moods.Length];
_rts = new RenderTexture[moods.Length];
for (int i = 0; i < moods.Length; i++)
{
var rt = new RenderTexture(w, h, 0, RenderTextureFormat.ARGB32) { name = $"Talk {who} {moods[i]}" };
rt.Create();
// see-through until the first frame is in
var was = RenderTexture.active;
RenderTexture.active = rt;
GL.Clear(true, true, Color.clear);
RenderTexture.active = was;
var vp = go.AddComponent();
vp.playOnAwake = false;
vp.source = VideoSource.Url;
vp.url = Path.Combine(Application.streamingAssetsPath, "Talk", who + "_" + moods[i] + ".webm");
vp.isLooping = true;
vp.skipOnDrop = true;
vp.audioOutputMode = VideoAudioOutputMode.None;
vp.renderMode = VideoRenderMode.RenderTexture;
vp.targetTexture = rt;
vp.Prepare();
_players[i] = vp;
_rts[i] = rt;
}
}
/// Plays the loop for this mood (and only it).
public void Play(int mood)
{
mood = Mathf.Clamp(mood, 0, _players.Length - 1);
if (mood != _on)
{
if (_on >= 0) _players[_on].Pause();
_on = mood;
Switched?.Invoke(_rts[mood]);
}
if (!_players[mood].isPlaying) _players[mood].Play();
}
public void Stop()
{
if (_on >= 0) _players[_on].Pause();
}
/// The Director: calm (and pleased), stern (and worried), furious.
public static int BossMood(Mood m) => m == Mood.Angry ? 2 : m == Mood.Stern || m == Mood.Scared || m == Mood.Sad ? 1 : 0;
/// The assistant: cheerful, matter-of-fact, fed up.
public static int AssistantMood(Mood m) => m == Mood.Stern ? 1 : m == Mood.Angry || m == Mood.Scared || m == Mood.Sad ? 2 : 0;
/// The strongest of the eased moods.
public static Mood Strongest(float[] mood)
{
int best = 0;
for (int i = 1; i < mood.Length; i++) if (mood[i] > mood[best]) best = i;
return (Mood)best;
}
}
}