forked from nikita/muzika-gromche
591 lines
22 KiB
C#
591 lines
22 KiB
C#
using BepInEx.Configuration;
|
|
using BepInEx;
|
|
using CSync.Extensions;
|
|
using CSync.Lib;
|
|
using HarmonyLib;
|
|
using LethalConfig.ConfigItems.Options;
|
|
using LethalConfig.ConfigItems;
|
|
using LethalConfig;
|
|
using System.Collections.Generic;
|
|
using System.Collections;
|
|
using System.Linq;
|
|
using System.Security.Cryptography;
|
|
using System;
|
|
using UnityEngine.Networking;
|
|
using UnityEngine;
|
|
|
|
namespace MuzikaGromche
|
|
{
|
|
[BepInPlugin(PluginInfo.PLUGIN_GUID, PluginInfo.PLUGIN_NAME, PluginInfo.PLUGIN_VERSION)]
|
|
[BepInDependency("com.sigurd.csync", "5.0.1")]
|
|
[BepInDependency("ainavt.lc.lethalconfig", "1.4.6")]
|
|
public class Plugin : BaseUnityPlugin
|
|
{
|
|
internal new static Config Config { get; private set; } = null;
|
|
|
|
public static Track[] Tracks = [
|
|
new Track
|
|
{
|
|
Name = "MuzikaGromche",
|
|
Language = Language.RUSSIAN,
|
|
WindUpTimer = 46.3f,
|
|
Bars = 8,
|
|
},
|
|
new Track
|
|
{
|
|
Name = "VseVZale",
|
|
Language = Language.RUSSIAN,
|
|
WindUpTimer = 39f,
|
|
Bars = 8,
|
|
},
|
|
new Track
|
|
{
|
|
Name = "DeployDestroy",
|
|
Language = Language.RUSSIAN,
|
|
WindUpTimer = 40.7f,
|
|
Bars = 8,
|
|
},
|
|
new Track
|
|
{
|
|
Name = "MoyaZhittya",
|
|
Language = Language.ENGLISH,
|
|
WindUpTimer = 34.5f,
|
|
Bars = 8,
|
|
},
|
|
new Track
|
|
{
|
|
Name = "Gorgorod",
|
|
Language = Language.RUSSIAN,
|
|
WindUpTimer = 43.2f,
|
|
Bars = 6,
|
|
},
|
|
new Track
|
|
{
|
|
Name = "Durochka",
|
|
Language = Language.RUSSIAN,
|
|
WindUpTimer = 37f,
|
|
Bars = 10,
|
|
}
|
|
];
|
|
|
|
public static Track ChooseTrack()
|
|
{
|
|
var seed = RoundManager.Instance.dungeonGenerator.Generator.ChosenSeed;
|
|
int[] weights = [.. Tracks.Select(track => track.Weight.Value)];
|
|
var rwi = new RandomWeightedIndex(weights);
|
|
var trackId = rwi.GetRandomWeightedIndex(seed);
|
|
var track = Tracks[trackId];
|
|
Debug.Log($"Seed is {seed}, chosen track is \"{track.Name}\", #{trackId} of {rwi}");
|
|
return Tracks[trackId];
|
|
}
|
|
|
|
public static Track CurrentTrack;
|
|
|
|
public static void SetLightColor(Color color)
|
|
{
|
|
foreach (var light in RoundManager.Instance.allPoweredLights)
|
|
{
|
|
light.color = color;
|
|
}
|
|
}
|
|
|
|
public static void ResetLightColor()
|
|
{
|
|
SetLightColor(Color.white);
|
|
}
|
|
|
|
private void Awake()
|
|
{
|
|
string text = Info.Location.TrimEnd((PluginInfo.PLUGIN_NAME + ".dll").ToCharArray());
|
|
UnityWebRequest[] requests = new UnityWebRequest[Tracks.Length * 2];
|
|
for (int i = 0; i < Tracks.Length; i++)
|
|
{
|
|
Track track = Tracks[i];
|
|
requests[i * 2] = UnityWebRequestMultimedia.GetAudioClip($"File://{text}{track.FileNameStart}", track.AudioType);
|
|
requests[i * 2 + 1] = UnityWebRequestMultimedia.GetAudioClip($"File://{text}{track.FileNameLoop}", track.AudioType);
|
|
requests[i * 2].SendWebRequest();
|
|
requests[i * 2 + 1].SendWebRequest();
|
|
}
|
|
|
|
while (!requests.All(request => request.isDone)) { }
|
|
|
|
if (requests.All(request => request.result == UnityWebRequest.Result.Success))
|
|
{
|
|
for (int i = 0; i < Tracks.Length; i++)
|
|
{
|
|
Track track = Tracks[i];
|
|
track.LoadedStart = DownloadHandlerAudioClip.GetContent(requests[i * 2]);
|
|
track.LoadedLoop = DownloadHandlerAudioClip.GetContent(requests[i * 2 + 1]);
|
|
}
|
|
Config = new Config(base.Config);
|
|
new Harmony(PluginInfo.PLUGIN_NAME).PatchAll(typeof(JesterPatch));
|
|
}
|
|
else
|
|
{
|
|
Logger.LogError("Could not load audio file");
|
|
}
|
|
}
|
|
};
|
|
|
|
public record Language(string Short, string Full)
|
|
{
|
|
public static readonly Language ENGLISH = new("EN", "English");
|
|
public static readonly Language RUSSIAN = new("RU", "Russian");
|
|
}
|
|
|
|
public class Track
|
|
{
|
|
public string Name;
|
|
// Language of the track's lyrics.
|
|
public Language Language;
|
|
// Wind-up time can and should be shorter than the Start audio track,
|
|
// so that the "pop" effect can be baked into the Start audio and kept away
|
|
// from the looped part. This also means that the light show starts before
|
|
// the looped track does, so we need to sync them up as soon as we enter the Loop.
|
|
public float WindUpTimer;
|
|
|
|
// Estimated number of beats per minute. Not used for light show, but might come in handy.
|
|
public float Bpm => 60f / (LoadedLoop.length / Beats);
|
|
|
|
// How many beats the loop segment has. The default strategy is to switch color of lights on each beat.
|
|
public int Beats;
|
|
|
|
// Shorthand for four beats
|
|
public int Bars
|
|
{
|
|
set => Beats = value * 4;
|
|
}
|
|
|
|
// MPEG is basically mp3, and it can produce gaps at the start.
|
|
// WAV is OK, but takes a lot of space. Try OGGVORBIS instead.
|
|
public AudioType AudioType = AudioType.MPEG;
|
|
|
|
public AudioClip LoadedStart;
|
|
public AudioClip LoadedLoop;
|
|
|
|
// This does not account for the timestamp when Jester has actually popped
|
|
public float FixedLoopDelay => LoadedStart.length - WindUpTimer;
|
|
|
|
// How often this track should be chosen, relative to the sum of weights of all tracks.
|
|
public SyncedEntry<int> Weight;
|
|
|
|
public string FileNameStart => $"{Name}Start.{Ext}";
|
|
public string FileNameLoop => $"{Name}Loop.{Ext}";
|
|
private string Ext => AudioType switch
|
|
{
|
|
AudioType.MPEG => "mp3",
|
|
AudioType.WAV => "wav",
|
|
AudioType.OGGVORBIS => "ogg",
|
|
_ => "",
|
|
};
|
|
|
|
public float CalculateBeat(AudioSource start, AudioSource loop)
|
|
{
|
|
// If popped, calculate which beat the music is currently at.
|
|
// In order to do that we should choose one of two strategies:
|
|
//
|
|
// 1. If start source is still playing, use its position since WindUpTimer.
|
|
// 2. Otherwise use loop source, adding the delay after WindUpTimer,
|
|
// which is the remaining of the start, i.e. (LoadedStart.length - WindUpTimer).
|
|
//
|
|
// NOTE 1: PlayDelayed also counts as isPlaying, so loop.isPlaying is always true and as such it's useful.
|
|
// NOTE 2: There is a weird state when Jester has popped and chases a player:
|
|
// Start/farAudio isPlaying is true but stays exactly at zero time, so we need to ignore that.
|
|
|
|
var elapsed = start.isPlaying && start.time != 0f
|
|
// [1] Start source is still playing
|
|
? start.time - WindUpTimer
|
|
// [2] Start source has finished
|
|
: loop.time + FixedLoopDelay;
|
|
|
|
elapsed -= Config.AudioOffset.Value;
|
|
|
|
var normalized = Mod.Positive(elapsed / LoadedLoop.length, 1f);
|
|
|
|
var beat = normalized * (float)Beats;
|
|
#if DEBUG
|
|
var color = ColorAtBeat(beat);
|
|
Debug.LogFormat("MuzikaGromche t={0,10:N4} d={1,7:N4} Start[{2}{3,8:N4} ==0f? {4}] Loop[{5}{6,8:N4}] norm={7,6:N4} beat={8,7:N4} color={9}",
|
|
Time.realtimeSinceStartup, Time.deltaTime,
|
|
(start.isPlaying ? '+' : ' '), start.time, (start.time == 0f ? 'Y' : 'n'),
|
|
(loop.isPlaying ? '+' : ' '), loop.time,
|
|
normalized, beat, color);
|
|
#endif
|
|
return beat;
|
|
}
|
|
|
|
static readonly List<Color> Colors = [Color.magenta, Color.cyan, Color.green, Color.yellow];
|
|
|
|
public Color ColorAtBeat(float beat)
|
|
{
|
|
int beatIndex = Mod.Positive(Mathf.FloorToInt(beat), Beats);
|
|
|
|
return Mod.Index(Colors, beatIndex);
|
|
}
|
|
}
|
|
|
|
// Default C#/.NET remainder operator % returns negative result for negative input
|
|
// which is unsuitable as an index for an array.
|
|
public static class Mod
|
|
{
|
|
public static int Positive(int x, int m)
|
|
{
|
|
int r = x % m;
|
|
return r < 0 ? r + m : r;
|
|
}
|
|
|
|
public static float Positive(float x, float m)
|
|
{
|
|
float r = x % m;
|
|
return r < 0f ? r + m : r;
|
|
}
|
|
|
|
public static T Index<T>(IList<T> array, int index)
|
|
{
|
|
return array[Mod.Positive(index, array.Count)];
|
|
}
|
|
}
|
|
|
|
public readonly struct RandomWeightedIndex
|
|
{
|
|
public RandomWeightedIndex(int[] weights)
|
|
{
|
|
Weights = weights;
|
|
TotalWeights = Weights.Sum();
|
|
if (TotalWeights == 0)
|
|
{
|
|
// If everything is set to zero, everything is equally possible
|
|
Weights = [.. Weights.Select(_ => 1)];
|
|
TotalWeights = Weights.Length;
|
|
}
|
|
}
|
|
|
|
private byte[] GetHash(int seed)
|
|
{
|
|
var buffer = new byte[4 * (1 + Weights.Length)];
|
|
var offset = 0;
|
|
Buffer.BlockCopy(BitConverter.GetBytes(seed), 0, buffer, offset, sizeof(int));
|
|
// Make sure that tweaking weights even a little drastically changes the outcome
|
|
foreach (var weight in Weights)
|
|
{
|
|
offset += 4;
|
|
Buffer.BlockCopy(BitConverter.GetBytes(weight), 0, buffer, offset, sizeof(int));
|
|
}
|
|
var sha = SHA256.Create();
|
|
var hash = sha.ComputeHash(buffer);
|
|
return hash;
|
|
}
|
|
|
|
private int GetRawIndex(byte[] hash)
|
|
{
|
|
if (TotalWeights == 0)
|
|
{
|
|
// Should not happen, but what if Weights array is empty?
|
|
return -1;
|
|
}
|
|
|
|
var index = 0;
|
|
foreach (var t in hash)
|
|
{
|
|
// modulus division on byte array
|
|
index *= 256 % TotalWeights;
|
|
index %= TotalWeights;
|
|
index += t % TotalWeights;
|
|
index %= TotalWeights;
|
|
}
|
|
return index;
|
|
}
|
|
|
|
private int GetWeightedIndex(int rawIndex)
|
|
{
|
|
if (rawIndex < 0 || rawIndex >= TotalWeights)
|
|
{
|
|
return -1;
|
|
}
|
|
|
|
int sum = 0;
|
|
foreach (var (weight, index) in Weights.Select((x, i) => (x, i)))
|
|
{
|
|
sum += weight;
|
|
if (rawIndex < sum)
|
|
{
|
|
// Found
|
|
return index;
|
|
}
|
|
}
|
|
|
|
return -1;
|
|
}
|
|
|
|
public int GetRandomWeightedIndex(int seed)
|
|
{
|
|
var hash = GetHash(seed);
|
|
var index = GetRawIndex(hash);
|
|
return GetWeightedIndex(index);
|
|
}
|
|
|
|
public override string ToString()
|
|
{
|
|
return $"Weighted(Total={TotalWeights}, Weights=[{string.Join(',', Weights)}])";
|
|
}
|
|
|
|
readonly private int[] Weights;
|
|
readonly public int TotalWeights { get; }
|
|
}
|
|
|
|
public static class SyncedEntryExtensions
|
|
{
|
|
// Update local values on clients. Even though the clients couldn't
|
|
// edit them, they could at least see the new values.
|
|
public static void SyncHostToLocal<T>(this SyncedEntry<T> entry)
|
|
{
|
|
entry.Changed += (sender, args) =>
|
|
{
|
|
args.ChangedEntry.LocalValue = args.NewValue;
|
|
};
|
|
}
|
|
}
|
|
|
|
public class Config : SyncedConfig2<Config>
|
|
{
|
|
public static ConfigEntry<float> AudioOffset { get; private set; }
|
|
|
|
public static bool ShouldSkipWindingPhase { get; private set; } = false;
|
|
|
|
public Config(ConfigFile configFile) : base(PluginInfo.PLUGIN_GUID)
|
|
{
|
|
AudioOffset = configFile.Bind("General", "Audio Offset", 0f, new ConfigDescription(
|
|
"Adjust audio offset (in seconds).\n\nIf you are playing with Bluetooth headphones and experiencing a visual desync, try setting this to about negative 0.2.\n\nIf your video output has high latency (like a long HDMI cable etc.), try positive values instead.",
|
|
new AcceptableValueRange<float>(-0.5f, 0.5f)));
|
|
LethalConfigManager.AddConfigItem(new FloatSliderConfigItem(AudioOffset, requiresRestart: false));
|
|
|
|
#if DEBUG
|
|
SetupEntriesToSkipWinding(configFile);
|
|
#endif
|
|
|
|
var chanceRange = new AcceptableValueRange<int>(0, 100);
|
|
var languageSectionButtonExists = new HashSet<Language>();
|
|
|
|
foreach (var track in Plugin.Tracks)
|
|
{
|
|
var language = track.Language;
|
|
string section = $"Tracks.{language.Short}";
|
|
|
|
// Create section toggle
|
|
if (!languageSectionButtonExists.Contains(language))
|
|
{
|
|
languageSectionButtonExists.Add(language);
|
|
string buttonOptionName = $"Toggle all {language.Full} tracks";
|
|
string buttonDescription = "Toggle all tracks in this section ON or OFF. Effective immediately.";
|
|
string buttonText = "Toggle";
|
|
var button = new GenericButtonConfigItem(section, buttonOptionName, buttonDescription, buttonText, () =>
|
|
{
|
|
if (CanModifyWeightsNow())
|
|
{
|
|
var tracks = Plugin.Tracks.Where(t => t.Language.Equals(language)).ToList();
|
|
var isOff = tracks.All(t => t.Weight.LocalValue == 0);
|
|
var newWeight = isOff ? 50 : 0;
|
|
foreach (var t in tracks)
|
|
{
|
|
t.Weight.LocalValue = newWeight;
|
|
}
|
|
}
|
|
});
|
|
button.ButtonOptions.CanModifyCallback = CanModifyWeightsNow;
|
|
LethalConfigManager.AddConfigItem(button);
|
|
}
|
|
|
|
// Create slider entry for track
|
|
string name = $"[{language.Short}] {track.Name}";
|
|
string description = $"Language: {language.Full}\n\nRandom (relative) chance of selecting this track.\n\nSet to zero to effectively disable the track.";
|
|
track.Weight = configFile.BindSyncedEntry(
|
|
new ConfigDefinition(section, track.Name),
|
|
50,
|
|
new ConfigDescription(description, chanceRange, track));
|
|
|
|
var slider = new IntSliderConfigItem(track.Weight.Entry, new IntSliderOptions
|
|
{
|
|
RequiresRestart = false,
|
|
CanModifyCallback = CanModifyWeightsNow,
|
|
});
|
|
LethalConfigManager.AddConfigItem(slider);
|
|
CSyncHackAddSyncedEntry(track.Weight);
|
|
}
|
|
|
|
ConfigManager.Register(this);
|
|
}
|
|
|
|
// HACK because CSync doesn't provide an API to register a list of config entries
|
|
// See https://github.com/lc-sigurd/CSync/issues/11
|
|
private void CSyncHackAddSyncedEntry(SyncedEntryBase entryBase)
|
|
{
|
|
// This is basically what ConfigFile.PopulateEntryContainer does
|
|
EntryContainer.Add(entryBase.BoxedEntry.ToSyncedEntryIdentifier(), entryBase);
|
|
}
|
|
|
|
public static CanModifyResult CanModifyIfHost()
|
|
{
|
|
var startOfRound = StartOfRound.Instance;
|
|
if (!startOfRound)
|
|
{
|
|
return CanModifyResult.True(); // Main menu
|
|
}
|
|
if (!startOfRound.IsHost)
|
|
{
|
|
return CanModifyResult.False("Only for host");
|
|
}
|
|
return CanModifyResult.True();
|
|
}
|
|
|
|
public static CanModifyResult CanModifyWeightsNow()
|
|
{
|
|
var startOfRound = StartOfRound.Instance;
|
|
if (!startOfRound)
|
|
{
|
|
return CanModifyResult.True(); // Main menu
|
|
}
|
|
if (!startOfRound.IsHost)
|
|
{
|
|
return CanModifyResult.False("Only for host");
|
|
}
|
|
#if !DEBUG // Changing tracks on the fly might lead to a desync. But it may speed up development process
|
|
if (!startOfRound.inShipPhase)
|
|
{
|
|
return CanModifyResult.False("Only while orbiting");
|
|
}
|
|
#endif
|
|
return CanModifyResult.True();
|
|
}
|
|
|
|
private void SetupEntriesToSkipWinding(ConfigFile configFile)
|
|
{
|
|
var syncedEntry = configFile.BindSyncedEntry("General", "Skip Winding Phase", false,
|
|
new ConfigDescription("Skip most of the wind-up/intro/start music.\n\nUse this option to test your Loop audio segment."));
|
|
LethalConfigManager.AddConfigItem(new BoolCheckBoxConfigItem(syncedEntry.Entry, new BoolCheckBoxOptions
|
|
{
|
|
RequiresRestart = false,
|
|
CanModifyCallback = CanModifyIfHost,
|
|
}));
|
|
CSyncHackAddSyncedEntry(syncedEntry);
|
|
syncedEntry.Changed += (sender, args) => apply();
|
|
syncedEntry.SyncHostToLocal();
|
|
apply();
|
|
|
|
void apply()
|
|
{
|
|
ShouldSkipWindingPhase = syncedEntry.Value;
|
|
}
|
|
}
|
|
}
|
|
|
|
// farAudio is during windup, Start overrides popGoesTheWeaselTheme
|
|
// creatureVoice is when popped, Loop overrides screamingSFX
|
|
[HarmonyPatch(typeof(JesterAI))]
|
|
internal class JesterPatch
|
|
{
|
|
#if DEBUG
|
|
[HarmonyPatch("SetJesterInitialValues")]
|
|
[HarmonyPostfix]
|
|
public static void AlmostInstantFollowTimerPostfix(JesterAI __instance)
|
|
{
|
|
__instance.beginCrankingTimer = 1f;
|
|
}
|
|
#endif
|
|
[HarmonyPatch("Update")]
|
|
[HarmonyPrefix]
|
|
public static void DoNotStopTheMusicPrefix(JesterAI __instance, out State __state)
|
|
{
|
|
__state = new State
|
|
{
|
|
farAudio = __instance.farAudio,
|
|
previousState = __instance.previousState,
|
|
};
|
|
if (__instance.currentBehaviourStateIndex == 2 && __instance.previousState != 2)
|
|
{
|
|
// If just popped out, then override farAudio so that vanilla logic does not stop the modded Start music.
|
|
// The game will stop farAudio it during its Update, so we temporarily set it to any other AudioSource
|
|
// which we don't care about stopping for now.
|
|
//
|
|
// Why creatureVoice though? We gonna need creatureVoice later in Postfix to schedule the Loop,
|
|
// but right now we still don't care if it's stopped, so it shouldn't matter.
|
|
// And it's cheaper and simpler than figuring out how to instantiate an AudioSource behaviour.
|
|
__instance.farAudio = __instance.creatureVoice;
|
|
}
|
|
}
|
|
|
|
[HarmonyPatch("Update")]
|
|
[HarmonyPostfix]
|
|
public static void DoNotStopTheMusic(JesterAI __instance, State __state)
|
|
{
|
|
if (__instance.previousState == 1 && __state.previousState != 1)
|
|
{
|
|
// if just started winding up
|
|
// then stop the default music...
|
|
__instance.farAudio.Stop();
|
|
__instance.creatureVoice.Stop();
|
|
|
|
// ...and start modded music
|
|
Plugin.CurrentTrack = Plugin.ChooseTrack();
|
|
// Set up custom popup timer, which is shorter than Start audio
|
|
__instance.popUpTimer = Plugin.CurrentTrack.WindUpTimer;
|
|
|
|
// Override popGoesTheWeaselTheme with Start audio
|
|
__instance.farAudio.maxDistance = 150;
|
|
__instance.farAudio.clip = Plugin.CurrentTrack.LoadedStart;
|
|
__instance.farAudio.loop = false;
|
|
if (Config.ShouldSkipWindingPhase)
|
|
{
|
|
var rewind = 5f;
|
|
__instance.popUpTimer = rewind;
|
|
__instance.farAudio.time = Plugin.CurrentTrack.WindUpTimer - rewind;
|
|
}
|
|
else
|
|
{
|
|
// reset if previously skipped winding by assigning different starting time.
|
|
__instance.farAudio.time = 0;
|
|
}
|
|
__instance.farAudio.Play();
|
|
|
|
Debug.Log($"Playing start music: maxDistance: {__instance.farAudio.maxDistance}, minDistance: {__instance.farAudio.minDistance}, volume: {__instance.farAudio.volume}, spread: {__instance.farAudio.spread}");
|
|
}
|
|
|
|
if (__instance.previousState != 2 && __state.previousState == 2)
|
|
{
|
|
Plugin.ResetLightColor();
|
|
}
|
|
|
|
if (__instance.previousState == 2 && __state.previousState != 2)
|
|
{
|
|
// Restore stashed AudioSource. See the comment in Prefix
|
|
__instance.farAudio = __state.farAudio;
|
|
|
|
var time = __instance.farAudio.time;
|
|
var delay = Plugin.CurrentTrack.LoadedStart.length - time;
|
|
|
|
// Override screamingSFX with Loop, delayed by the remaining time of the Start audio
|
|
__instance.creatureVoice.Stop();
|
|
__instance.creatureVoice.maxDistance = 150;
|
|
__instance.creatureVoice.clip = Plugin.CurrentTrack.LoadedLoop;
|
|
__instance.creatureVoice.PlayDelayed(delay);
|
|
|
|
Debug.Log($"Start length: {Plugin.CurrentTrack.LoadedStart.length}; played time: {time}");
|
|
Debug.Log($"Playing loop music: maxDistance: {__instance.creatureVoice.maxDistance}, minDistance: {__instance.creatureVoice.minDistance}, volume: {__instance.creatureVoice.volume}, spread: {__instance.creatureVoice.spread}, in seconds: {delay}");
|
|
}
|
|
|
|
// Manage the timeline: switch color of the lights according to the current playback/beat position.
|
|
if (__instance.previousState == 2)
|
|
{
|
|
var beat = Plugin.CurrentTrack.CalculateBeat(start: __instance.farAudio, loop: __instance.creatureVoice);
|
|
var color = Plugin.CurrentTrack.ColorAtBeat(beat);
|
|
Plugin.SetLightColor(color);
|
|
}
|
|
}
|
|
}
|
|
|
|
internal class State
|
|
{
|
|
public AudioSource farAudio;
|
|
public int previousState;
|
|
}
|
|
}
|