diff --git a/Packages/com.llealloo.audiolink.extras/Runtime/Scripts/AudioLinkZone.cs b/Packages/com.llealloo.audiolink.extras/Runtime/Scripts/AudioLinkZone.cs index 44be29a1..ca4aad97 100644 --- a/Packages/com.llealloo.audiolink.extras/Runtime/Scripts/AudioLinkZone.cs +++ b/Packages/com.llealloo.audiolink.extras/Runtime/Scripts/AudioLinkZone.cs @@ -26,4 +26,4 @@ public override void OnPlayerTriggerEnter(VRCPlayerApi player) } } } -#endif \ No newline at end of file +#endif diff --git a/Packages/com.llealloo.audiolink/Editor/Scripts/AudioLinkAssetManager.cs b/Packages/com.llealloo.audiolink/Editor/Scripts/AudioLinkAssetManager.cs index 2bb88029..d68fd92e 100644 --- a/Packages/com.llealloo.audiolink/Editor/Scripts/AudioLinkAssetManager.cs +++ b/Packages/com.llealloo.audiolink/Editor/Scripts/AudioLinkAssetManager.cs @@ -1,31 +1,24 @@ -using System.IO; +using System.Collections.Generic; +using System.IO; using System.Linq; -using System.Collections.Generic; using UnityEditor; -using UnityEditor.SceneManagement; using UnityEditor.Experimental.SceneManagement; +using UnityEditor.SceneManagement; using UnityEngine; -namespace AudioLink.Editor -{ +namespace AudioLink.Editor { [InitializeOnLoad] - public class AudioLinkAssetManager - { + public class AudioLinkAssetManager { private const string audioLinkReimportedKey = "AUDIOLINK_REIMPORTED"; - static AudioLinkAssetManager() - { + static AudioLinkAssetManager() { // Skip if we've already checked for the canary file during this Editor Session - if (!SessionState.GetBool(audioLinkReimportedKey, false)) - { + if (!SessionState.GetBool(audioLinkReimportedKey, false)) { // Check for canary file in Library - package probably needs a reimport after a Library wipe string canaryFilePath = Path.Combine("Library", audioLinkReimportedKey); - if (File.Exists(canaryFilePath)) - { + if (File.Exists(canaryFilePath)) { SessionState.SetBool(audioLinkReimportedKey, true); - } - else - { + } else { ReimportPackage(); File.WriteAllText(canaryFilePath, audioLinkReimportedKey); AudioLinkShaderCompatabilityUtility.UpgradeShaders(); @@ -33,23 +26,19 @@ static AudioLinkAssetManager() } } - private static void ReimportPackage() - { + private static void ReimportPackage() { AssetDatabase.ImportAsset(Path.Combine("Packages", "com.llealloo.audiolink"), ImportAssetOptions.ImportRecursive); SessionState.SetBool(audioLinkReimportedKey, true); } #if !AUDIOLINK_STANDALONE [MenuItem("Tools/AudioLink/Open AudioLink Example Scene")] - public static void OpenExampleScene() - { - if (EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo()) - { + public static void OpenExampleScene() { + if (EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo()) { string baseAssetsPath = "Samples/AudioLink/1.2.1"; string packagePath = "Packages/com.llealloo.audiolink/Samples~/AudioLinkExampleScene"; string assetsPath = Path.Combine("Assets", baseAssetsPath, "AudioLinkExampleScene"); - if (!Directory.Exists(Path.Combine(Application.dataPath, baseAssetsPath, "AudioLinkExampleScene"))) - { + if (!Directory.Exists(Path.Combine(Application.dataPath, baseAssetsPath, "AudioLinkExampleScene"))) { Directory.CreateDirectory(Path.Combine(Application.dataPath, baseAssetsPath)); FileUtil.CopyFileOrDirectory(packagePath, assetsPath); AssetDatabase.Refresh(); @@ -68,8 +57,7 @@ public static void OpenExampleScene() [MenuItem("Tools/AudioLink/Add AudioLink Prefab to Scene", false)] [MenuItem("GameObject/AudioLink/Add AudioLink Prefab to Scene", false, 49)] - public static void AddAudioLinkToScene() - { + public static void AddAudioLinkToScene() { GameObject audiolink = null; #if UDONSHARP // VRC World @@ -92,19 +80,16 @@ public static void AddAudioLinkToScene() audiolink = alInstance != null ? alInstance.gameObject : AddPrefabInstance(_audioLinkPath); #endif - if (audiolink != null) - { + if (audiolink != null) { AudioLinkEditor.LinkAll(audiolink.GetComponent()); EditorGUIUtility.PingObject(audiolink); } } - private static GameObject AddPrefabInstance(string assetPath) - { + private static GameObject AddPrefabInstance(string assetPath) { var sourceAsset = AssetDatabase.LoadAssetAtPath(assetPath); GameObject instance = null; - if (sourceAsset != null) - { + if (sourceAsset != null) { instance = (GameObject)PrefabUtility.InstantiatePrefab(sourceAsset); Undo.RegisterCreatedObjectUndo(instance, "Undo create prefab instance"); } @@ -112,8 +97,7 @@ private static GameObject AddPrefabInstance(string assetPath) return instance; } - private static T[] GetComponentsInScene(bool includeInactive = true) where T : Component - { + private static T[] GetComponentsInScene(bool includeInactive = true) where T : Component { var stage = PrefabStageUtility.GetCurrentPrefabStage(); GameObject[] roots = stage == null ? UnityEngine.SceneManagement.SceneManager.GetActiveScene().GetRootGameObjects() : new[] { stage.prefabContentsRoot }; List objects = new List(); @@ -121,8 +105,7 @@ private static T[] GetComponentsInScene(bool includeInactive = true) where T return objects.ToArray(); } - private static GameObject[] GetGameObjectsInScene(string name, bool includeInactive = true) - { + private static GameObject[] GetGameObjectsInScene(string name, bool includeInactive = true) { var stage = PrefabStageUtility.GetCurrentPrefabStage(); GameObject[] roots = stage == null ? UnityEngine.SceneManagement.SceneManager.GetActiveScene().GetRootGameObjects() : new[] { stage.prefabContentsRoot }; List objects = new List(); @@ -130,4 +113,4 @@ private static GameObject[] GetGameObjectsInScene(string name, bool includeInact return objects.Where(t => t.gameObject.name == name).Select(t => t.gameObject).ToArray(); } } -} \ No newline at end of file +} diff --git a/Packages/com.llealloo.audiolink/Editor/Scripts/AudioLinkDefineManager.cs b/Packages/com.llealloo.audiolink/Editor/Scripts/AudioLinkDefineManager.cs index 60d0f4b7..b010d266 100644 --- a/Packages/com.llealloo.audiolink/Editor/Scripts/AudioLinkDefineManager.cs +++ b/Packages/com.llealloo.audiolink/Editor/Scripts/AudioLinkDefineManager.cs @@ -4,20 +4,16 @@ using UnityEditor; using UnityEngine; -namespace AudioLink.Editor -{ +namespace AudioLink.Editor { [InitializeOnLoad] - public class AudioLinkDefineManager - { - static AudioLinkDefineManager() - { + public class AudioLinkDefineManager { + static AudioLinkDefineManager() { AddDefineIfMissing(EditorUserBuildSettings.selectedBuildTargetGroup, "AUDIOLINK"); AddDefineIfMissing(EditorUserBuildSettings.selectedBuildTargetGroup, "AUDIOLINK_V1"); Shader.EnableKeyword("AUDIOLINK_IMPORTED"); } - private static void AddDefineIfMissing(BuildTargetGroup buildTarget, string newDefine) - { + private static void AddDefineIfMissing(BuildTargetGroup buildTarget, string newDefine) { bool definesChanged = false; string existingDefines = PlayerSettings.GetScriptingDefineSymbolsForGroup(buildTarget); HashSet defineSet = new HashSet(); @@ -28,8 +24,7 @@ private static void AddDefineIfMissing(BuildTargetGroup buildTarget, string newD if (defineSet.Add(newDefine)) definesChanged = true; - if (definesChanged) - { + if (definesChanged) { string finalDefineString = string.Join(";", defineSet.ToArray()); PlayerSettings.SetScriptingDefineSymbolsForGroup(buildTarget, finalDefineString); Debug.LogFormat("Set Scripting Define Symbols for selected build target ({0}) to: {1}", @@ -38,4 +33,4 @@ private static void AddDefineIfMissing(BuildTargetGroup buildTarget, string newD } } } -#endif \ No newline at end of file +#endif diff --git a/Packages/com.llealloo.audiolink/Editor/Scripts/AudioLinkEditor.cs b/Packages/com.llealloo.audiolink/Editor/Scripts/AudioLinkEditor.cs index 023721e4..9f136e26 100644 --- a/Packages/com.llealloo.audiolink/Editor/Scripts/AudioLinkEditor.cs +++ b/Packages/com.llealloo.audiolink/Editor/Scripts/AudioLinkEditor.cs @@ -9,19 +9,15 @@ using UnityEditor; using UnityEngine; -namespace AudioLink.Editor -{ +namespace AudioLink.Editor { [CustomEditor(typeof(AudioLink))] - public class AudioLinkEditor : UnityEditor.Editor - { + public class AudioLinkEditor : UnityEditor.Editor { private readonly static GUIContent DisableReadbackButtonContent = EditorGUIUtility.TrTextContent("Disable readback", "Disables asynchronous readback, which is required for audio-reactive Udon scripts to function. This feature comes with a slight performance penalty."); private readonly static GUIContent EnableReadbackButtonContent = EditorGUIUtility.TrTextContent("Enable readback", "Enables asynchronous readback, which is required for audio-reactive Udon scripts to function. This feature comes with a slight performance penalty."); - public void OnEnable() - { + public void OnEnable() { AudioLink audioLink = (AudioLink)target; - if (audioLink.audioData2D == null) - { + if (audioLink.audioData2D == null) { audioLink.audioData2D = AssetDatabase.LoadAssetAtPath( AssetDatabase.GUIDToAssetPath("b07c8466531ac5e4e852f3e276e4baca")); @@ -29,27 +25,23 @@ public void OnEnable() } } - public override void OnInspectorGUI() - { + public override void OnInspectorGUI() { AudioLink audioLink = (AudioLink)target; #if UDONSHARP if (UdonSharpGUI.DrawDefaultUdonSharpBehaviourHeader(target)) return; #endif - if (Camera.main == null) - { + if (Camera.main == null) { EditorGUILayout.HelpBox("The current scene might be missing a main camera, this could cause issues with the AudioLink camera.", MessageType.Warning); } - if (audioLink.audioSource == null) - { + if (audioLink.audioSource == null) { EditorGUILayout.HelpBox("No audio source assigned. AudioLink will not work.", MessageType.Warning); } EditorGUILayout.Space(); if (GUILayout.Button(new GUIContent("Link all sound reactive objects to this AudioLink instance", - "Links all scripts with 'audioLink' parameter to this object."))) - { + "Links all scripts with 'audioLink' parameter to this object."))) { LinkAll(); } @@ -57,33 +49,26 @@ public override void OnInspectorGUI() base.OnInspectorGUI(); EditorGUILayout.Space(); - if (audioLink.audioDataToggle) - { + if (audioLink.audioDataToggle) { GUI.backgroundColor = Color.red; - if (GUILayout.Button(DisableReadbackButtonContent)) - { + if (GUILayout.Button(DisableReadbackButtonContent)) { audioLink.DisableReadback(); EditorUtility.SetDirty(audioLink); } - } - else - { + } else { GUI.backgroundColor = Color.green; - if (GUILayout.Button(EnableReadbackButtonContent)) - { + if (GUILayout.Button(EnableReadbackButtonContent)) { audioLink.EnableReadback(); EditorUtility.SetDirty(audioLink); } } } - public void LinkAll() - { + public void LinkAll() { LinkAll(target as AudioLink); } - public static void LinkAll(AudioLink target) - { + public static void LinkAll(AudioLink target) { #if UDONSHARP UdonSharpBehaviour[] allBehaviours = FindObjectsOfType(); #else @@ -91,28 +76,22 @@ public static void LinkAll(AudioLink target) #endif // this handles all reasonable cases of referencing audiolink // (it doesn't handle referencing it multiple times in one monobehaviour, or referencing it as it's Base type) - foreach (var behaviour in allBehaviours) - { + foreach (var behaviour in allBehaviours) { FieldInfo fieldInfo = behaviour.GetType().GetField("audioLink"); // in case the field isn't called "audioLink" - if (fieldInfo == null) - { - foreach (FieldInfo field in behaviour.GetType().GetFields()) - { - if (field.FieldType == typeof(AudioLink)) - { + if (fieldInfo == null) { + foreach (FieldInfo field in behaviour.GetType().GetFields()) { + if (field.FieldType == typeof(AudioLink)) { fieldInfo = field; break; } } } - if (fieldInfo != null && fieldInfo.FieldType == typeof(AudioLink)) - { + if (fieldInfo != null && fieldInfo.FieldType == typeof(AudioLink)) { fieldInfo.SetValue(behaviour, target); EditorUtility.SetDirty(behaviour); - if (PrefabUtility.IsPartOfPrefabInstance(behaviour)) - { + if (PrefabUtility.IsPartOfPrefabInstance(behaviour)) { PrefabUtility.RecordPrefabInstancePropertyModifications(behaviour); } } @@ -120,4 +99,4 @@ public static void LinkAll(AudioLink target) } } } -#endif \ No newline at end of file +#endif diff --git a/Packages/com.llealloo.audiolink/Editor/Scripts/AudioLinkMiniPlayerControllerInspector.cs b/Packages/com.llealloo.audiolink/Editor/Scripts/AudioLinkMiniPlayerControllerInspector.cs index 7383d365..e4f0d503 100644 --- a/Packages/com.llealloo.audiolink/Editor/Scripts/AudioLinkMiniPlayerControllerInspector.cs +++ b/Packages/com.llealloo.audiolink/Editor/Scripts/AudioLinkMiniPlayerControllerInspector.cs @@ -79,4 +79,4 @@ public override void OnInspectorGUI() } } } -#endif \ No newline at end of file +#endif diff --git a/Packages/com.llealloo.audiolink/Editor/Scripts/AudioLinkShaderCompatabilityUtility.cs b/Packages/com.llealloo.audiolink/Editor/Scripts/AudioLinkShaderCompatabilityUtility.cs index 3283cb2c..b84f1344 100644 --- a/Packages/com.llealloo.audiolink/Editor/Scripts/AudioLinkShaderCompatabilityUtility.cs +++ b/Packages/com.llealloo.audiolink/Editor/Scripts/AudioLinkShaderCompatabilityUtility.cs @@ -3,10 +3,8 @@ using UnityEditor; using UnityEngine; -namespace AudioLink.Editor -{ - public class AudioLinkShaderCompatabilityUtility - { +namespace AudioLink.Editor { + public class AudioLinkShaderCompatabilityUtility { private const string OldAbsolutePath = "Assets/AudioLink/Shaders/AudioLink.cginc"; private const string NewAbsolutePath = "Packages/com.llealloo.audiolink/Runtime/Shaders/AudioLink.cginc"; private const string MenuItemPath = "Tools/AudioLink/Update AudioLink Compatible Shaders"; @@ -24,59 +22,48 @@ public class AudioLinkShaderCompatabilityUtility [MenuItem(MenuItemPath)] - public static void UpgradeShaders() - { - if (EditorUtility.DisplayDialog(DialogTitle, DialogText, DialogOkButton, DialogCancelButton)) - { + public static void UpgradeShaders() { + if (EditorUtility.DisplayDialog(DialogTitle, DialogText, DialogOkButton, DialogCancelButton)) { UpgradeShaderFiles(); UpgradeCgincFiles(); AssetDatabase.Refresh(); } } - private static void UpgradeShaderFiles() - { + private static void UpgradeShaderFiles() { ShaderInfo[] shaders = ShaderUtil.GetAllShaderInfo(); - foreach (ShaderInfo shaderinfo in shaders) - { + foreach (ShaderInfo shaderinfo in shaders) { Shader shader = Shader.Find(shaderinfo.name); string path = AssetDatabase.GetAssetPath(shader); // we want to avoid built-in shaders so we check the Path - if (path.StartsWith("Assets") || path.StartsWith("Packages")) - { + if (path.StartsWith("Assets") || path.StartsWith("Packages")) { ReplaceInFile(path); } } } - private static void UpgradeCgincFiles() - { + private static void UpgradeCgincFiles() { List cgincs = FindCgincFiles(Application.dataPath); cgincs.AddRange(FindCgincFiles(Path.GetDirectoryName(Application.dataPath) + "/Packages")); - foreach (string cginc in cgincs) - { + foreach (string cginc in cgincs) { ReplaceInFile(cginc); } } - private static List FindCgincFiles(string path) - { + private static List FindCgincFiles(string path) { List cgincList = new List(); string[] files = Directory.GetFiles(path); - foreach (string file in files) - { - if (file.EndsWith(".cginc") || file.EndsWith(".hlsl")) - { + foreach (string file in files) { + if (file.EndsWith(".cginc") || file.EndsWith(".hlsl")) { cgincList.Add(file); } } string[] folders = Directory.GetDirectories(path); - foreach (string folder in folders) - { + foreach (string folder in folders) { List cgincs = FindCgincFiles(folder); cgincList.AddRange(cgincs); } @@ -84,30 +71,23 @@ private static List FindCgincFiles(string path) return cgincList; } - private static void ReplaceInFile(string path) - { + private static void ReplaceInFile(string path) { string[] shaderSource = File.ReadAllLines(path); bool shouldWrite = false; - for (int i = 0; i < shaderSource.Length; i++) - { + for (int i = 0; i < shaderSource.Length; i++) { string line = shaderSource[i]; - if (line.Contains(OldAbsolutePath)) - { + if (line.Contains(OldAbsolutePath)) { line = line.Replace(OldAbsolutePath, NewAbsolutePath); - while (line.Contains("/Packages")) - { + while (line.Contains("/Packages")) { line = line.Replace("./Packages", "Packages"); line = line.Replace("/Packages", "Packages"); } shaderSource[i] = line; shouldWrite = true; - } - else if (!line.Contains(NewAbsolutePath) && line.Contains("AudioLink.cginc")) - { + } else if (!line.Contains(NewAbsolutePath) && line.Contains("AudioLink.cginc")) { string trimmedLine = line.Replace("#include", "").Trim().Trim('"'); string fullPath = Path.GetFullPath(Path.GetDirectoryName(path) + '/' + trimmedLine.TrimStart('/')).Replace('\\', '/'); - if (fullPath.EndsWith(OldAbsolutePath)) - { + if (fullPath.EndsWith(OldAbsolutePath)) { int index = line.IndexOf("#include"); string whitespace = line.Remove(index, line.Length - index); shaderSource[i] = whitespace + "#include \"" + NewAbsolutePath + "\""; @@ -116,10 +96,9 @@ private static void ReplaceInFile(string path) } } - if (shouldWrite) - { + if (shouldWrite) { File.WriteAllLines(path, shaderSource); } } } -} \ No newline at end of file +} diff --git a/Packages/com.llealloo.audiolink/Runtime/Scripts/AudioLink.DataAPI.cs b/Packages/com.llealloo.audiolink/Runtime/Scripts/AudioLink.DataAPI.cs index 8cce8b23..5dad82af 100644 --- a/Packages/com.llealloo.audiolink/Runtime/Scripts/AudioLink.DataAPI.cs +++ b/Packages/com.llealloo.audiolink/Runtime/Scripts/AudioLink.DataAPI.cs @@ -1,9 +1,7 @@ using UnityEngine; -namespace AudioLink -{ - public partial class AudioLink - { +namespace AudioLink { + public partial class AudioLink { #region Passes /// Corresponds to ALPASS_DFT in AudioLink.cginc. public static Vector2 ALPassDft => new Vector2(0, 4); @@ -121,8 +119,7 @@ public partial class AudioLink /// you may need to enable readbacks on the AudioLink prefab. /// /// Corresponds to AudioLinkIsAvailable() in AudioLink.cginc. - public bool AudioDataIsAvailable() - { + public bool AudioDataIsAvailable() { return audioDataToggle && audioData != null && audioData.Length > 0; } @@ -133,8 +130,7 @@ public bool AudioDataIsAvailable() /// The y coordinate of the pixel to read. /// The value of the pixel at the given coordinates. /// Corresponds to AudioLinkData() in AudioLink.cginc. - public Vector4 GetDataAtPixel(int x, int y) - { + public Vector4 GetDataAtPixel(int x, int y) { return audioData[y * AudioLinkWidth + x]; } @@ -144,8 +140,7 @@ public Vector4 GetDataAtPixel(int x, int y) /// The coordinates of the pixel to read. /// The value of the pixel at the given coordinates. /// Corresponds to AudioLinkData() in AudioLink.cginc. - public Vector4 GetDataAtPixel(Vector2 position) - { + public Vector4 GetDataAtPixel(Vector2 position) { return GetDataAtPixel((int)position.x, (int)position.y); } @@ -156,8 +151,7 @@ public Vector4 GetDataAtPixel(Vector2 position) /// The y coordinate of the pixel to read. /// The value of the pixel at the given coordinates. /// Corresponds to AudioLinkLerp() in AudioLink.cginc. - public Vector4 LerpAudioDataAtPixel(float x, float y) - { + public Vector4 LerpAudioDataAtPixel(float x, float y) { return Vector4.Lerp(GetDataAtPixel((int)x, (int)y), GetDataAtPixel((int)x + 1, (int)y), x % 1.0f); } @@ -167,8 +161,7 @@ public Vector4 LerpAudioDataAtPixel(float x, float y) /// The coordinates of the pixel to read. /// The value of the pixel at the given coordinates. /// Corresponds to AudioLinkLerp() in AudioLink.cginc. - public Vector4 LerpAudioDataAtPixel(Vector2 position) - { + public Vector4 LerpAudioDataAtPixel(Vector2 position) { return LerpAudioDataAtPixel(position.x, position.y); } @@ -179,8 +172,7 @@ public Vector4 LerpAudioDataAtPixel(Vector2 position) /// The y coordinate of the pixel to read. /// The value of the pixel at the given coordinates. /// Corresponds to AudioLinkDataMultiline() in AudioLink.cginc. - public Vector4 GetDataAtPixelMultiline(int x, int y) - { + public Vector4 GetDataAtPixelMultiline(int x, int y) { return GetDataAtPixel(x % AudioLinkWidth, y + x / AudioLinkWidth); } @@ -190,8 +182,7 @@ public Vector4 GetDataAtPixelMultiline(int x, int y) /// The coordinates of the pixel to read. /// The value of the pixel at the given coordinates. /// Corresponds to AudioLinkDataMultiline() in AudioLink.cginc. - public Vector4 GetDataAtPixelMultiline(Vector2 position) - { + public Vector4 GetDataAtPixelMultiline(Vector2 position) { return GetDataAtPixelMultiline((int)position.x, (int)position.y); } @@ -203,8 +194,7 @@ public Vector4 GetDataAtPixelMultiline(Vector2 position) /// The y coordinate of the pixel to read. /// The value of the pixel at the given coordinates. /// Corresponds to AudioLinkLerpMultiline() in AudioLink.cginc. - public Vector4 LerpAudioDataAtPixelMultiline(float x, float y) - { + public Vector4 LerpAudioDataAtPixelMultiline(float x, float y) { return Vector4.Lerp(GetDataAtPixelMultiline((int)x, (int)y), GetDataAtPixelMultiline((int)x + 1, (int)y), x % 1.0f); } @@ -214,8 +204,7 @@ public Vector4 LerpAudioDataAtPixelMultiline(float x, float y) /// /// The coordinates of the pixel to read. /// The value of the pixel at the given coordinates. - public Vector4 LerpAudioDataAtPixelMultiline(Vector2 position) - { + public Vector4 LerpAudioDataAtPixelMultiline(Vector2 position) { return LerpAudioDataAtPixelMultiline(position.x, position.y); } @@ -225,8 +214,7 @@ public Vector4 LerpAudioDataAtPixelMultiline(Vector2 position) /// The coordinates of the pixel to read. /// The value of the pixel at the given coordinates, decoded as an unsigned integer. /// Corresponds to AudioLinkDecodeDataAsUInt() in AudioLink.cginc. - public uint DecodeDataAsUInt(Vector2 position) - { + public uint DecodeDataAsUInt(Vector2 position) { Vector4 rpx = GetDataAtPixel(position); return (uint)rpx.x + (uint)rpx.y * 1024 + (uint)rpx.z * 1048576 + (uint)rpx.w * 1073741824; } @@ -239,8 +227,7 @@ public uint DecodeDataAsUInt(Vector2 position) /// The coordinates of the pixel to read. /// The value of the pixel at the given coordinates, decoded as a float representing seconds. /// Corresponds to AudioLinkDecodeDataAsSeconds() in AudioLink.cginc. - public float DecodeDataAsSeconds(Vector2 position) - { + public float DecodeDataAsSeconds(Vector2 position) { int time = (int)DecodeDataAsUInt(position) & 0x7ffffff; return (float)(time / 1000) + (float)(time % 1000) / 1000.0f; } @@ -251,8 +238,7 @@ public float DecodeDataAsSeconds(Vector2 position) /// The frequency to sample in range [13.75; 14080]. /// The amplitude of the given frequency. /// Corresponds to AudioLinkGetAmplitudeAtFrequency() in AudioLink.cginc. - public Vector4 GetAmplitudeAtFrequency(float hertz) - { + public Vector4 GetAmplitudeAtFrequency(float hertz) { float note = AudioLinkExpBins * Mathf.Log(hertz / AudioLinkBottomFrequency, 2); return LerpAudioDataAtPixelMultiline(ALPassDft + new Vector2(note, 0)); } @@ -264,8 +250,7 @@ public Vector4 GetAmplitudeAtFrequency(float hertz) /// The quartertone to sample in range [0; 23]. /// The amplitude of the given quartertone. /// Corresponds to AudioLinkGetAmplitudeAtQuarterNote() in AudioLink.cginc. - public Vector4 GetAmplitudeAtQuarterNote(float octave, float quarter) - { + public Vector4 GetAmplitudeAtQuarterNote(float octave, float quarter) { return LerpAudioDataAtPixelMultiline(ALPassDft + new Vector2(octave * AudioLinkExpBins + quarter, 0)); } @@ -276,8 +261,7 @@ public Vector4 GetAmplitudeAtQuarterNote(float octave, float quarter) /// The semitone to sample in range [0; 11]. /// The amplitude of the given semitone. /// Corresponds to AudioLinkGetAmplitudeAtNote() in AudioLink.cginc. - public Vector4 GetAmplitudeAtNote(float octave, float note) - { + public Vector4 GetAmplitudeAtNote(float octave, float note) { float quarter = note * 2.0f; return GetAmplitudeAtQuarterNote(octave, quarter); } @@ -288,11 +272,9 @@ public Vector4 GetAmplitudeAtNote(float octave, float note) /// The quartertone to sample in range [0; 23]. /// The amplitude of the given quartertone across all octaves. /// Corresponds to AudioLinkGetAmplitudesAtQuarterNote() in AudioLink.cginc. - public Vector4 GetAmplitudesAtQuarterNote(float quarter) - { + public Vector4 GetAmplitudesAtQuarterNote(float quarter) { Vector4 amplitude = Color.clear; - for (int i = 0; i < AudioLinkExpOct; i++) - { + for (int i = 0; i < AudioLinkExpOct; i++) { amplitude += GetAmplitudeAtQuarterNote(i, quarter); } return amplitude; @@ -304,8 +286,7 @@ public Vector4 GetAmplitudesAtQuarterNote(float quarter) /// The semitone to sample in range [0; 11]. /// The amplitude of the given semitone across all octaves. /// Corresponds to AudioLinkGetAmplitudesAtNote() in AudioLink.cginc. - public Vector4 GetAmplitudesAtNote(float note) - { + public Vector4 GetAmplitudesAtNote(float note) { float quarter = note * 2.0f; return GetAmplitudesAtQuarterNote(quarter); } @@ -318,8 +299,7 @@ public Vector4 GetAmplitudesAtNote(float note) /// The chronotensity index to sample in range [0; 7]. /// A reasonable drop-in replacement time value for _Time.y. /// Corresponds to AudioLinkGetChronoTime() in AudioLink.cginc. - public float GetChronoTime(uint index, uint band) - { + public float GetChronoTime(uint index, uint band) { return (DecodeDataAsUInt(ALPassChronotensity + new Vector2((int)index, (int)band))) / 100000.0f; } @@ -332,8 +312,7 @@ public float GetChronoTime(uint index, uint band) /// The speed to modulate the chronotensity value by. /// A chronotensity value in the interval [0; 1]. /// Corresponds to AudioLinkGetChronoTime() in AudioLink.cginc. - public float GetChronoTimeNormalized(uint index, uint band, float speed) - { + public float GetChronoTimeNormalized(uint index, uint band, float speed) { return (GetChronoTime(index, band) * speed) % 1.0f; } @@ -347,8 +326,7 @@ public float GetChronoTimeNormalized(uint index, uint band, float speed) /// The interval to modulate the chronotensity value by. /// A chronotensity value in the interval [0; interval]. /// Corresponds to AudioLinkGetChronoTimeInterval() in AudioLink.cginc. - public float GetChronoTimeInterval(uint index, uint band, float speed, float interval) - { + public float GetChronoTimeInterval(uint index, uint band, float speed, float interval) { return GetChronoTimeNormalized(index, band, speed) * interval; } @@ -357,8 +335,7 @@ public float GetChronoTimeInterval(uint index, uint band, float speed, float int /// /// The first synced custom string. /// Corresponds to AudioLinkGetCustomString1Char() in AudioLink.cginc. - public string GetCustomString1() - { + public string GetCustomString1() { return customString1; } @@ -367,10 +344,9 @@ public string GetCustomString1() /// /// The second synced custom string. /// Corresponds to AudioLinkGetCustomString1Char() in AudioLink.cginc. - public string GetCustomString2() - { + public string GetCustomString2() { return customString2; } #endregion } -} \ No newline at end of file +} diff --git a/Packages/com.llealloo.audiolink/Runtime/Scripts/AudioLink.PlayerAPI.cs b/Packages/com.llealloo.audiolink/Runtime/Scripts/AudioLink.PlayerAPI.cs index af487b5e..782b5dde 100644 --- a/Packages/com.llealloo.audiolink/Runtime/Scripts/AudioLink.PlayerAPI.cs +++ b/Packages/com.llealloo.audiolink/Runtime/Scripts/AudioLink.PlayerAPI.cs @@ -1,16 +1,13 @@  using UnityEngine; -namespace AudioLink -{ - public partial class AudioLink - { +namespace AudioLink { + public partial class AudioLink { /// /// Set Media Volume display. Volume is in range 0.0f to 1.0f. /// /// The volume to set between 0.0f and 1.0f - public void SetMediaVolume(float volume) - { + public void SetMediaVolume(float volume) { audioMaterial.SetFloat("_MediaVolume", volume); @@ -20,8 +17,7 @@ public void SetMediaVolume(float volume) /// Set Media Time display. Time is in range 0.0f and 1.0f. /// /// The time to set between 0.0f and 1.0f - public void SetMediaTime(float time) - { + public void SetMediaTime(float time) { audioMaterial.SetFloat("_MediaTime", time); @@ -36,8 +32,7 @@ public void SetMediaTime(float time) /// Loading 4 (4.0f). /// /// The playing state to set. - public void SetMediaPlaying(MediaPlaying playingstate) - { + public void SetMediaPlaying(MediaPlaying playingstate) { int state = (int)playingstate; audioMaterial.SetFloat("_MediaPlaying", (float)state); @@ -53,8 +48,7 @@ public void SetMediaPlaying(MediaPlaying playingstate) /// RandomLoop 4 (4.0f). /// /// The loop state to set. - public void SetMediaLoop(MediaLoop loopstate) - { + public void SetMediaLoop(MediaLoop loopstate) { int loop = (int)loopstate; audioMaterial.SetFloat("_MediaLoop", (float)loop); @@ -62,8 +56,7 @@ public void SetMediaLoop(MediaLoop loopstate) } } - public enum MediaPlaying - { + public enum MediaPlaying { None = 0, Playing = 1, Paused = 2, @@ -73,12 +66,11 @@ public enum MediaPlaying Error = 6 } - public enum MediaLoop - { + public enum MediaLoop { None = 0, Loop = 1, LoopOne = 2, Random = 3, RandomLoop = 4 } -} \ No newline at end of file +} diff --git a/Packages/com.llealloo.audiolink/Runtime/Scripts/AudioLink.cs b/Packages/com.llealloo.audiolink/Runtime/Scripts/AudioLink.cs index d2c53955..bcd76976 100644 --- a/Packages/com.llealloo.audiolink/Runtime/Scripts/AudioLink.cs +++ b/Packages/com.llealloo.audiolink/Runtime/Scripts/AudioLink.cs @@ -2,8 +2,7 @@ using UnityEngine; -namespace AudioLink -{ +namespace AudioLink { #if UDONSHARP using static VRC.SDKBase.VRCShader; @@ -15,11 +14,9 @@ namespace AudioLink [UdonBehaviourSyncMode(BehaviourSyncMode.Manual)] public partial class AudioLink : UdonSharpBehaviour #else - using static Shader; - using Unity.Collections; - using UnityEngine.Rendering; + using static Shader; public partial class AudioLink : MonoBehaviour #endif @@ -215,8 +212,7 @@ public partial class AudioLink : MonoBehaviour // ReSharper restore InconsistentNaming private bool _IsInitialized = false; - private void InitIDs() - { + private void InitIDs() { if (_IsInitialized) return; @@ -275,8 +271,7 @@ private void InitIDs() #endregion // TODO(3): try to port this to standalone - void Start() - { + void Start() { #if UDONSHARP { // Handle sync'd time stuff. @@ -319,8 +314,7 @@ void Start() UpdateSettings(); UpdateThemeColors(); UpdateCustomStrings(); - if (audioSource == null) - { + if (audioSource == null) { Debug.LogWarning("[AudioLink] No audioSource provided. AudioLink will not do anything until an audio source has been assigned."); } @@ -329,16 +323,14 @@ void Start() // Disable camera on start if user didn't ask for it - if (!audioDataToggle) - { + if (!audioDataToggle) { DisableReadback(); } } // TODO(3): try to port this to standalone // Only happens once per second. - private void FPSUpdate() - { + private void FPSUpdate() { #if UDONSHARP if (!_hasInitializedTime) { @@ -391,8 +383,7 @@ private void FPSUpdate() // This handles wrapping of the ElapsedTime so we don't lose precision // onthe floating point. const double elapsedTimeMSWBoundary = 1024; - if (_elapsedTime >= elapsedTimeMSWBoundary) - { + if (_elapsedTime >= elapsedTimeMSWBoundary) { //For particularly long running instances, i.e. several days, the first //few frames will be spent federating _elapsedTime into _elapsedTimeMSW. //This is fine. It just means over time, the @@ -408,33 +399,25 @@ private void FPSUpdate() int networkTimeMSNow = (int)(Time.time * 1000.0f); #endif int networkTimeDelta = networkTimeMSNow - _networkTimeMS; - if (networkTimeDelta > 3000) - { + if (networkTimeDelta > 3000) { //Major upset, reset. _networkTimeMS = networkTimeMSNow; - } - else if (networkTimeDelta < -3000) - { + } else if (networkTimeDelta < -3000) { //Major upset, reset. _networkTimeMS = networkTimeMSNow; - } - else - { + } else { //Slowly correct the timebase. _networkTimeMS += networkTimeDelta / 20; } //Debug.Log( $"[AudioLink] Refinement: ${networkTimeDelta}" ); } - private void Update() - { - if (!_audioLinkEnabled) - { + private void Update() { + if (!_audioLinkEnabled) { return; } - if (audioDataToggle) - { + if (audioDataToggle) { #if UDONSHARP VRCAsyncGPUReadback.Request(audioRenderTexture, 0, TextureFormat.RGBAFloat, (VRC.Udon.Common.Interfaces.IUdonEventReceiver)(Component)this); #else @@ -451,8 +434,7 @@ private void Update() double deltaTimeMS = Time.deltaTime * 1000.0; int advanceTimeMS = (int)(deltaTimeMS); _networkTimeMSAccumulatedError += deltaTimeMS - advanceTimeMS; - if (_networkTimeMSAccumulatedError > 1) - { + if (_networkTimeMSAccumulatedError > 1) { _networkTimeMSAccumulatedError--; advanceTimeMS++; } @@ -461,8 +443,7 @@ private void Update() _fpsCount++; - if (_elapsedTime >= _fpsTime) - { + if (_elapsedTime >= _fpsTime) { FPSUpdate(); } @@ -495,8 +476,7 @@ private void Update() // Casting and encoding as UInt32 as 2 floats, to prevent aliasing, twice: 5.1ms / 255 // Casting and encoding as UInt32 as 2 floats, to prevent aliasing, once: 3.2ms / 255 - if (audioSource != null) - { + if (audioSource != null) { SendAudioOutputData(); // Used to correct for the volume of the audio source component @@ -506,32 +486,24 @@ private void Update() audioMaterial.SetVector(_SourcePosition, audioSource.transform.position); - if (autoSetMediaState) - { + if (autoSetMediaState) { SetMediaVolume(audioSource.volume); float time = 0f; - if (audioSource.clip != null) - { + if (audioSource.clip != null) { time = audioSource.time / audioSource.clip.length; } SetMediaTime(time); - if (audioSource.isPlaying) - { + if (audioSource.isPlaying) { SetMediaPlaying(MediaPlaying.Playing); - } - else - { + } else { SetMediaPlaying(MediaPlaying.Stopped); } - if (audioSource.loop) - { + if (audioSource.loop) { SetMediaLoop(MediaLoop.Loop); - } - else - { + } else { SetMediaLoop(MediaLoop.None); } } @@ -566,30 +538,25 @@ public override void OnAsyncGpuReadbackComplete(VRCAsyncGPUReadbackRequest reque request.TryGetData(audioData); } #else - public void OnAsyncGpuReadbackComplete(AsyncGPUReadbackRequest request) - { + public void OnAsyncGpuReadbackComplete(AsyncGPUReadbackRequest request) { if (request.hasError || !request.done) return; - + NativeArray data = request.GetData(); - for (int i = 0; i < data.Length; i++) - { + for (int i = 0; i < data.Length; i++) { audioData[i] = data[i]; } } #endif - private void OnEnable() - { + private void OnEnable() { EnableAudioLink(); } - private void OnDisable() - { + private void OnDisable() { DisableAudioLink(); } - public void UpdateSettings() - { + public void UpdateSettings() { InitIDs(); audioMaterial.SetFloat(_Gain, gain); audioMaterial.SetFloat(_FadeLength, fadeLength); @@ -610,8 +577,7 @@ public void UpdateSettings() // Note: These might be changed frequently so as an optimization, they're in a different function // rather than bundled in with the other things in UpdateSettings(). - public void UpdateThemeColors() - { + public void UpdateThemeColors() { InitIDs(); audioMaterial.SetInt(_ThemeColorMode, themeColorMode); audioMaterial.SetColor(_CustomThemeColor0, customThemeColor0); @@ -620,8 +586,7 @@ public void UpdateThemeColors() audioMaterial.SetColor(_CustomThemeColor3, customThemeColor3); } - private static float IntToFloatBits24Bit(uint value) - { + private static float IntToFloatBits24Bit(uint value) { uint frac = value & 0x007FFFFF; return (frac / 8388608F) * 1.1754944e-38F; } @@ -663,8 +628,7 @@ private void FindAndUpdateMasterName() } #endif - public void UpdateCustomStrings() - { + public void UpdateCustomStrings() { #if UDONSHARP if (!Networking.IsOwner(gameObject)) Networking.SetOwner(_localPlayer, gameObject); @@ -689,8 +653,7 @@ public override void OnDeserialization() } #endif - private void UpdateGlobalString(int nameID, string input) - { + private void UpdateGlobalString(int nameID, string input) { InitIDs(); const int maxLength = 32; if (input.Length > maxLength) @@ -699,11 +662,9 @@ private void UpdateGlobalString(int nameID, string input) // Get unicode codepoints int[] codePoints = new int[input.Length]; int codePointsLength = 0; - for (int i = 0; i < input.Length; i++) - { + for (int i = 0; i < input.Length; i++) { codePoints[codePointsLength++] = Char.ConvertToUtf32(input, i); - if (Char.IsHighSurrogate(input[i])) - { + if (Char.IsHighSurrogate(input[i])) { i += 1; } } @@ -711,8 +672,7 @@ private void UpdateGlobalString(int nameID, string input) // Pack them into vectors Vector4[] vecs = new Vector4[maxLength / 4]; // 4 chars per vector int j = 0; - for (int i = 0; i < vecs.Length; i++) - { + for (int i = 0; i < vecs.Length; i++) { if (j < codePoints.Length) vecs[i].x = IntToFloatBits24Bit((uint)codePoints[j++]); else break; if (j < codePoints.Length) vecs[i].y = IntToFloatBits24Bit((uint)codePoints[j++]); else break; if (j < codePoints.Length) vecs[i].z = IntToFloatBits24Bit((uint)codePoints[j++]); else break; @@ -723,8 +683,7 @@ private void UpdateGlobalString(int nameID, string input) audioMaterial.SetVectorArray(nameID, vecs); } - public void EnableAudioLink() - { + public void EnableAudioLink() { InitIDs(); _audioLinkEnabled = true; audioRenderTexture.updateMode = CustomRenderTextureUpdateMode.Realtime; @@ -735,8 +694,7 @@ public void EnableAudioLink() #endif } - public void DisableAudioLink() - { + public void DisableAudioLink() { _audioLinkEnabled = false; if (audioRenderTexture != null) { audioRenderTexture.updateMode = CustomRenderTextureUpdateMode.OnDemand; } #if UDONSHARP @@ -746,35 +704,26 @@ public void DisableAudioLink() #endif } - public void EnableReadback() - { + public void EnableReadback() { audioDataToggle = true; } - public void DisableReadback() - { + public void DisableReadback() { audioDataToggle = false; } - public void SendAudioOutputData() - { + public void SendAudioOutputData() { InitIDs(); audioSource.GetOutputData(_audioFramesL, 0); // left channel - if (_rightChannelTestCounter > 0) - { - if (_ignoreRightChannel) - { + if (_rightChannelTestCounter > 0) { + if (_ignoreRightChannel) { Array.Copy(_audioFramesL, 0, _audioFramesR, 0, 4092); - } - else - { + } else { audioSource.GetOutputData(_audioFramesR, 1); } _rightChannelTestCounter--; - } - else - { + } else { _rightChannelTestCounter = _rightChannelTestDelay; // reset test countdown _audioFramesR[0] = 0f; // reset tested array element to zero just in case audioSource.GetOutputData(_audioFramesR, 1); // right channel test @@ -800,8 +749,7 @@ public void SendAudioOutputData() audioMaterial.SetFloatArray(_Samples3R, _samples); } - private float Remap(float t, float a, float b, float u, float v) - { + private float Remap(float t, float a, float b, float u, float v) { return ((t - a) / (b - a)) * (v - u) + u; } } diff --git a/Packages/com.llealloo.audiolink/Runtime/Scripts/AudioLinkController.cs b/Packages/com.llealloo.audiolink/Runtime/Scripts/AudioLinkController.cs index 963d8342..49043539 100644 --- a/Packages/com.llealloo.audiolink/Runtime/Scripts/AudioLinkController.cs +++ b/Packages/com.llealloo.audiolink/Runtime/Scripts/AudioLinkController.cs @@ -1,8 +1,7 @@ using UnityEngine; using UnityEngine.UI; -namespace AudioLink -{ +namespace AudioLink { #if UDONSHARP using static VRC.SDKBase.VRCShader; @@ -78,8 +77,7 @@ public class AudioLinkController : MonoBehaviour private int _Power; // ReSharper restore InconsistentNaming - private void InitIDs() - { + private void InitIDs() { _X0 = PropertyToID("_X0"); _X1 = PropertyToID("_X1"); _X2 = PropertyToID("_X2"); @@ -98,44 +96,36 @@ private void InitIDs() #endregion #if UNITY_EDITOR - void Update() - { + void Update() { //UpdateSettings(); } #endif - ThemeColorController FindThemeColorController() - { + ThemeColorController FindThemeColorController() { Transform controllerTransform = transform.Find("ThemeColorController"); if (controllerTransform == null) return null; return controllerTransform.GetComponent(); } - void Start() - { + void Start() { InitIDs(); - if (audioLink == null) - { + if (audioLink == null) { Debug.LogError("[AudioLink] Controller not connected to AudioLink"); return; } - if (themeColorController == null) - { + if (themeColorController == null) { // This is here in case someone upgraded AudioLink, which updates // everything in the prefab, but not the outermost properties of the prefab. // TODO: Double check that this is how upgrading ends up working. Debug.Log("[AudioLink] AudioLinkController using fallback method for finding themeColorController"); themeColorController = FindThemeColorController(); } - if (themeColorController == null) - { + if (themeColorController == null) { // Something really weird has gone on. maybe using updated script // on un-updated prefab? Debug.LogError("[AudioLink] AudioLinkController could not find themeColorController"); - } - else - { + } else { themeColorController.audioLink = audioLink; themeColorController.audioLinkUI = audioLinkUI; themeColorController.InitializeAudioLinkThemeColors(); @@ -165,8 +155,7 @@ void Start() UpdateSettings(); } - private void GetSettings() - { + private void GetSettings() { // General settings gainSlider.value = audioLink.gain; //trebleSlider.value = audioLink.treble; @@ -186,8 +175,7 @@ private void GetSettings() threshold3Slider.value = audioLink.threshold3; } - public void UpdateSettings() - { + public void UpdateSettings() { // Update Sliders Vector2 anchor0 = new Vector2(x0Slider.value, 1f); Vector2 anchor1 = new Vector2(x1Slider.value, 1f); @@ -216,8 +204,7 @@ public void UpdateSettings() audioLinkUI.SetInt(_AutoGain, autoGainToggle.isOn ? 1 : 0); audioLinkUI.SetInt(_Power, powerToggle.isOn ? 1 : 0); - if (audioLink == null) - { + if (audioLink == null) { Debug.LogError("[AudioLink] Controller not connected to AudioLink"); return; } @@ -242,18 +229,14 @@ public void UpdateSettings() audioLink.UpdateSettings(); // Toggle - if (powerToggle.isOn) - { + if (powerToggle.isOn) { audioLink.EnableAudioLink(); - } - else - { + } else { audioLink.DisableAudioLink(); } } - public void ResetSettings() - { + public void ResetSettings() { gainSlider.value = _initGain; //trebleSlider.value = _initTreble; // bassSlider.value = _initBass; @@ -268,15 +251,13 @@ public void ResetSettings() threshold1Slider.value = _initThreshold1; threshold2Slider.value = _initThreshold2; threshold3Slider.value = _initThreshold3; - if (themeColorController != null) - { + if (themeColorController != null) { themeColorController.ResetThemeColors(); } } - private float Remap(float t, float a, float b, float u, float v) - { + private float Remap(float t, float a, float b, float u, float v) { return ((t - a) / (b - a)) * (v - u) + u; } } diff --git a/Packages/com.llealloo.audiolink/Runtime/Scripts/AudioLinkControllerV0.cs b/Packages/com.llealloo.audiolink/Runtime/Scripts/AudioLinkControllerV0.cs index 6e7b06fc..eabe5472 100644 --- a/Packages/com.llealloo.audiolink/Runtime/Scripts/AudioLinkControllerV0.cs +++ b/Packages/com.llealloo.audiolink/Runtime/Scripts/AudioLinkControllerV0.cs @@ -1,8 +1,7 @@ using UnityEngine; using UnityEngine.UI; -namespace AudioLink -{ +namespace AudioLink { #if UDONSHARP using static VRC.SDKBase.VRCShader; @@ -75,8 +74,7 @@ public class AudioLinkControllerV0 : MonoBehaviour private int _Threshold3; // ReSharper restore InconsistentNaming - private void InitIDs() - { + private void InitIDs() { _X0 = PropertyToID("_X0"); _X1 = PropertyToID("_X1"); _X2 = PropertyToID("_X2"); @@ -90,44 +88,36 @@ private void InitIDs() #endregion #if UNITY_EDITOR - void Update() - { + void Update() { //UpdateSettings(); } #endif - ThemeColorControllerV0 FindThemeColorController() - { + ThemeColorControllerV0 FindThemeColorController() { Transform controllerTransform = transform.Find("ThemeColorController"); if (controllerTransform == null) return null; return controllerTransform.GetComponent(); } - void Start() - { + void Start() { InitIDs(); - if (audioLink == null) - { + if (audioLink == null) { Debug.LogError("[AudioLink] Controller not connected to AudioLink"); return; } - if (themeColorController == null) - { + if (themeColorController == null) { // This is here in case someone upgraded AudioLink, which updates // everything in the prefab, but not the outermost properties of the prefab. // TODO: Double check that this is how upgrading ends up working. Debug.Log("[AudioLink] AudioLinkController using fallback method for finding themeColorController"); themeColorController = FindThemeColorController(); } - if (themeColorController == null) - { + if (themeColorController == null) { // Something really weird has gone on. maybe using updated script // on un-updated prefab? Debug.LogError("[AudioLink] AudioLinkController could not find themeColorController"); - } - else - { + } else { themeColorController.audioLink = audioLink; themeColorController.InitializeAudioLinkThemeColors(); } @@ -155,8 +145,7 @@ void Start() UpdateSettings(); } - private void GetSettings() - { + private void GetSettings() { // General settings gainSlider.value = audioLink.gain; trebleSlider.value = audioLink.treble; @@ -176,8 +165,7 @@ private void GetSettings() threshold3Slider.value = audioLink.threshold3; } - public void UpdateSettings() - { + public void UpdateSettings() { // Update labels gainLabel.text = "Gain: " + ((int)Remap(gainSlider.value, 0f, 2f, 0f, 200f)).ToString() + "%"; trebleLabel.text = "Treble: " + ((int)Remap(trebleSlider.value, 0f, 2f, 0f, 200f)).ToString() + "%"; @@ -206,8 +194,7 @@ public void UpdateSettings() audioSpectrumDisplay.SetFloat(_Threshold2, threshold2Slider.value); audioSpectrumDisplay.SetFloat(_Threshold3, threshold3Slider.value); - if (audioLink == null) - { + if (audioLink == null) { Debug.LogError("[AudioLink] Controller not connected to AudioLink"); return; } @@ -232,8 +219,7 @@ public void UpdateSettings() audioLink.UpdateSettings(); } - public void ResetSettings() - { + public void ResetSettings() { gainSlider.value = _initGain; trebleSlider.value = _initTreble; bassSlider.value = _initBass; @@ -247,15 +233,13 @@ public void ResetSettings() threshold1Slider.value = _initThreshold1; threshold2Slider.value = _initThreshold2; threshold3Slider.value = _initThreshold3; - if (themeColorController != null) - { + if (themeColorController != null) { themeColorController.ResetThemeColors(); } } - private float Remap(float t, float a, float b, float u, float v) - { + private float Remap(float t, float a, float b, float u, float v) { return ((t - a) / (b - a)) * (v - u) + u; } } diff --git a/Packages/com.llealloo.audiolink/Runtime/Scripts/AudioLinkMiniPlayerController.cs b/Packages/com.llealloo.audiolink/Runtime/Scripts/AudioLinkMiniPlayerController.cs index 8debf095..ae149467 100644 --- a/Packages/com.llealloo.audiolink/Runtime/Scripts/AudioLinkMiniPlayerController.cs +++ b/Packages/com.llealloo.audiolink/Runtime/Scripts/AudioLinkMiniPlayerController.cs @@ -369,4 +369,4 @@ public override void OnPlayerLeft(VRCPlayerApi player) } } } -#endif \ No newline at end of file +#endif diff --git a/Packages/com.llealloo.audiolink/Runtime/Scripts/AudioReactiveLight.cs b/Packages/com.llealloo.audiolink/Runtime/Scripts/AudioReactiveLight.cs index caa65893..4bf88f92 100644 --- a/Packages/com.llealloo.audiolink/Runtime/Scripts/AudioReactiveLight.cs +++ b/Packages/com.llealloo.audiolink/Runtime/Scripts/AudioReactiveLight.cs @@ -1,7 +1,6 @@ using UnityEngine; -namespace AudioLink -{ +namespace AudioLink { #if UDONSHARP using UdonSharp; @@ -22,18 +21,15 @@ public class AudioReactiveLight : MonoBehaviour private int _dataIndex; private Color _initialColor; - void Start() - { + void Start() { _light = transform.GetComponent(); _initialColor = _light.color; _dataIndex = (band * 128) + delay; } - void Update() - { - if (audioLink.AudioDataIsAvailable()) - { + void Update() { + if (audioLink.AudioDataIsAvailable()) { // Convert to grayscale float amplitude = Vector3.Dot(audioLink.GetDataAtPixel(delay, band), new Vector3(0.299f, 0.587f, 0.114f)); if (affectIntensity) _light.intensity = amplitude * intensityMultiplier; @@ -41,12 +37,11 @@ void Update() } } - private Color HueShift(Color color, float hueShiftAmount) - { + private Color HueShift(Color color, float hueShiftAmount) { float h, s, v; Color.RGBToHSV(color, out h, out s, out v); h += hueShiftAmount; return Color.HSVToRGB(h, s, v); } } -} \ No newline at end of file +} diff --git a/Packages/com.llealloo.audiolink/Runtime/Scripts/AudioReactiveObject.cs b/Packages/com.llealloo.audiolink/Runtime/Scripts/AudioReactiveObject.cs index fa696255..7c0f28a9 100644 --- a/Packages/com.llealloo.audiolink/Runtime/Scripts/AudioReactiveObject.cs +++ b/Packages/com.llealloo.audiolink/Runtime/Scripts/AudioReactiveObject.cs @@ -1,7 +1,6 @@ using UnityEngine; -namespace AudioLink -{ +namespace AudioLink { #if UDONSHARP using UdonSharp; @@ -24,8 +23,7 @@ public class AudioReactiveObject : MonoBehaviour private Vector3 _initialRotation; private Vector3 _initialScale; - void Start() - { + void Start() { UpdateDataIndex(); _initialPosition = transform.localPosition; _initialRotation = transform.localEulerAngles; @@ -33,8 +31,7 @@ void Start() } - void Update() - { + void Update() { Color[] audioData = audioLink.audioData; if (audioData.Length != 0) // check for audioLink initialization { @@ -47,9 +44,8 @@ void Update() } } - public void UpdateDataIndex() - { + public void UpdateDataIndex() { _dataIndex = (band * 128) + delay; } } -} \ No newline at end of file +} diff --git a/Packages/com.llealloo.audiolink/Runtime/Scripts/AudioReactiveSurface.cs b/Packages/com.llealloo.audiolink/Runtime/Scripts/AudioReactiveSurface.cs index cfe6f88c..9abc007b 100644 --- a/Packages/com.llealloo.audiolink/Runtime/Scripts/AudioReactiveSurface.cs +++ b/Packages/com.llealloo.audiolink/Runtime/Scripts/AudioReactiveSurface.cs @@ -1,7 +1,6 @@ using UnityEngine; -namespace AudioLink -{ +namespace AudioLink { #if UDONSHARP using static VRC.SDKBase.VRCShader; @@ -45,8 +44,7 @@ public class AudioReactiveSurface : MonoBehaviour private int _PulseRotation; // ReSharper restore InconsistentNaming - private void InitIDs() - { + private void InitIDs() { _Delay = PropertyToID("_Delay"); _Band = PropertyToID("_Band"); _HueShift = PropertyToID("_HueShift"); @@ -57,14 +55,12 @@ private void InitIDs() } #endregion - void Start() - { + void Start() { InitIDs(); UpdateMaterial(); } - public void UpdateMaterial() - { + public void UpdateMaterial() { MaterialPropertyBlock block = new MaterialPropertyBlock(); MeshRenderer mesh = GetComponent(); block.SetFloat(_Delay, (float)delay / 128f); @@ -77,4 +73,4 @@ public void UpdateMaterial() mesh.SetPropertyBlock(block); } } -} \ No newline at end of file +} diff --git a/Packages/com.llealloo.audiolink/Runtime/Scripts/AudioReactiveSurfaceArray.cs b/Packages/com.llealloo.audiolink/Runtime/Scripts/AudioReactiveSurfaceArray.cs index d819d807..e5cdde3d 100644 --- a/Packages/com.llealloo.audiolink/Runtime/Scripts/AudioReactiveSurfaceArray.cs +++ b/Packages/com.llealloo.audiolink/Runtime/Scripts/AudioReactiveSurfaceArray.cs @@ -1,7 +1,6 @@ using UnityEngine; -namespace AudioLink -{ +namespace AudioLink { #if UDONSHARP using static VRC.SDKBase.VRCShader; @@ -56,8 +55,7 @@ public class AudioReactiveSurfaceArray : MonoBehaviour private int _PulseRotation; // ReSharper restore InconsistentNaming - private void InitIDs() - { + private void InitIDs() { _Delay = PropertyToID("_Delay"); _Band = PropertyToID("_Band"); _HueShift = PropertyToID("_HueShift"); @@ -69,33 +67,26 @@ private void InitIDs() #endregion - void Start() - { + void Start() { InitIDs(); _childRenderers = transform.GetComponentsInChildren(true); UpdateChildren(); } - public void UpdateChildren() - { + public void UpdateChildren() { - foreach (Renderer renderer in _childRenderers) - { + foreach (Renderer renderer in _childRenderers) { Transform child = renderer.transform; int index = child.GetSiblingIndex(); // Recursively apply step to children of children like a tree with branches, otherwise ignore - if (childrenOfChildren) - { + if (childrenOfChildren) { Transform pointer = child.parent; - while (!pointer.Equals(transform)) - { + while (!pointer.Equals(transform)) { index += pointer.GetSiblingIndex() + 1; pointer = pointer.parent; } - } - else - { + } else { if (!child.parent.Equals(transform)) continue; } MaterialPropertyBlock block = new MaterialPropertyBlock(); @@ -110,12 +101,11 @@ public void UpdateChildren() } } - private Color HueShift(Color color, float hueShiftAmount) - { + private Color HueShift(Color color, float hueShiftAmount) { float h, s, v; Color.RGBToHSV(color, out h, out s, out v); h = (h + hueShiftAmount) - Mathf.Floor(h + hueShiftAmount); return Color.HSVToRGB(h, s, v); } } -} \ No newline at end of file +} diff --git a/Packages/com.llealloo.audiolink/Runtime/Scripts/GlobalSlider.cs b/Packages/com.llealloo.audiolink/Runtime/Scripts/GlobalSlider.cs index 7e244cb5..cc663fc5 100644 --- a/Packages/com.llealloo.audiolink/Runtime/Scripts/GlobalSlider.cs +++ b/Packages/com.llealloo.audiolink/Runtime/Scripts/GlobalSlider.cs @@ -48,4 +48,4 @@ public void SlideUpdate() } } } -#endif \ No newline at end of file +#endif diff --git a/Packages/com.llealloo.audiolink/Runtime/Scripts/GlobalToggle.cs b/Packages/com.llealloo.audiolink/Runtime/Scripts/GlobalToggle.cs index 3edffaa0..395ccdbc 100644 --- a/Packages/com.llealloo.audiolink/Runtime/Scripts/GlobalToggle.cs +++ b/Packages/com.llealloo.audiolink/Runtime/Scripts/GlobalToggle.cs @@ -48,4 +48,4 @@ public void ToggleUpdate() } } } -#endif \ No newline at end of file +#endif diff --git a/Packages/com.llealloo.audiolink/Runtime/Scripts/StringInListDrawer.cs b/Packages/com.llealloo.audiolink/Runtime/Scripts/StringInListDrawer.cs index 96278c57..a9fdb804 100644 --- a/Packages/com.llealloo.audiolink/Runtime/Scripts/StringInListDrawer.cs +++ b/Packages/com.llealloo.audiolink/Runtime/Scripts/StringInListDrawer.cs @@ -7,44 +7,33 @@ using UnityEngine; -namespace AudioLink.Editor -{ - public class StringInList : PropertyAttribute - { - public StringInList(params string[] list) - { +namespace AudioLink.Editor { + public class StringInList : PropertyAttribute { + public StringInList(params string[] list) { List = list; } - public string[] List - { + public string[] List { get; } } [CustomPropertyDrawer(typeof(StringInList))] - public class StringInListDrawer : PropertyDrawer - { + public class StringInListDrawer : PropertyDrawer { // Draw the property inside the given rect - public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) - { + public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { string[] list = ((StringInList)attribute).List; - if (property.propertyType == SerializedPropertyType.String) - { + if (property.propertyType == SerializedPropertyType.String) { int index = Mathf.Max(0, Array.IndexOf(list, property.stringValue)); index = EditorGUI.Popup(position, property.displayName, index, list); property.stringValue = list[index]; - } - else if (property.propertyType == SerializedPropertyType.Integer) - { + } else if (property.propertyType == SerializedPropertyType.Integer) { property.intValue = EditorGUI.Popup(position, property.displayName, property.intValue, list); - } - else - { + } else { base.OnGUI(position, property, label); } } } } -#endif \ No newline at end of file +#endif diff --git a/Packages/com.llealloo.audiolink/Runtime/Scripts/ThemeColorController.cs b/Packages/com.llealloo.audiolink/Runtime/Scripts/ThemeColorController.cs index bce48df3..b96375fa 100644 --- a/Packages/com.llealloo.audiolink/Runtime/Scripts/ThemeColorController.cs +++ b/Packages/com.llealloo.audiolink/Runtime/Scripts/ThemeColorController.cs @@ -1,8 +1,7 @@ using UnityEngine; using UnityEngine.UI; -namespace AudioLink -{ +namespace AudioLink { #if UDONSHARP using UdonSharp; @@ -44,8 +43,7 @@ public class ThemeColorController : MonoBehaviour public Toggle themeColorToggle; public int customColorIndex = 0; - private void Start() - { + private void Start() { #if UDONSHARP localPlayer = Networking.LocalPlayer; #endif @@ -70,33 +68,27 @@ public override void OnDeserialization() public void SelectCustomColor1() { SelectCustomColorN(1); } public void SelectCustomColor2() { SelectCustomColorN(2); } public void SelectCustomColor3() { SelectCustomColorN(3); } - public void SelectCustomColorN(int n) - { + public void SelectCustomColorN(int n) { customColorIndex = n; UpdateGUI(); } - public void ToggleThemeColorMode() - { + public void ToggleThemeColorMode() { _themeColorMode = themeColorToggle.isOn ? 0 : 1; UpdateGUI(); UpdateAudioLinkThemeColors(); } - public void ForceThemeColorMode() - { - if (!_processGUIEvents) - { + public void ForceThemeColorMode() { + if (!_processGUIEvents) { return; } - + themeColorToggle.isOn = false; } - public void OnGUIchange() - { - if (!_processGUIEvents) - { + public void OnGUIchange() { + if (!_processGUIEvents) { return; } #if UDONSHARP @@ -116,11 +108,9 @@ public void OnGUIchange() #endif } - public void ResetThemeColors() - { + public void ResetThemeColors() { _themeColorMode = _initThemeColorMode; - for (int i = 0; i < 4; ++i) - { + for (int i = 0; i < 4; ++i) { customThemeColors[i] = _initCustomThemeColors[i]; } UpdateGUI(); @@ -130,8 +120,7 @@ public void ResetThemeColors() #endif } - public void UpdateGUI() - { + public void UpdateGUI() { _processGUIEvents = false; bool isCustom = _themeColorMode == 1; @@ -146,8 +135,7 @@ public void UpdateGUI() // update toggle themeColorToggle.isOn = _themeColorMode == 0; - if (audioLinkUI != null) - { + if (audioLinkUI != null) { audioLinkUI.SetInt("_ThemeColorMode", _themeColorMode); audioLinkUI.SetInt("_SelectedColor", customColorIndex); audioLinkUI.SetFloat("_Hue", h); @@ -163,8 +151,7 @@ public void UpdateGUI() _processGUIEvents = true; } - public void InitializeAudioLinkThemeColors() - { + public void InitializeAudioLinkThemeColors() { if (audioLink == null) return; customThemeColors[0] = audioLink.customThemeColor0; @@ -190,8 +177,7 @@ public void InitializeAudioLinkThemeColors() #endif } - public void UpdateAudioLinkThemeColors() - { + public void UpdateAudioLinkThemeColors() { if (audioLink == null) return; audioLink.themeColorMode = _themeColorMode; audioLink.customThemeColor0 = customThemeColors[0]; diff --git a/Packages/com.llealloo.audiolink/Runtime/Scripts/ThemeColorControllerV0.cs b/Packages/com.llealloo.audiolink/Runtime/Scripts/ThemeColorControllerV0.cs index 3bbf77f9..ab070146 100644 --- a/Packages/com.llealloo.audiolink/Runtime/Scripts/ThemeColorControllerV0.cs +++ b/Packages/com.llealloo.audiolink/Runtime/Scripts/ThemeColorControllerV0.cs @@ -1,8 +1,7 @@ using UnityEngine; using UnityEngine.UI; -namespace AudioLink -{ +namespace AudioLink { #if UDONSHARP using UdonSharp; @@ -45,8 +44,7 @@ public class ThemeColorControllerV0 : MonoBehaviour public Transform[] customColorLassos; public int customColorIndex = 0; - private void Start() - { + private void Start() { #if UDONSHARP localPlayer = Networking.LocalPlayer; #endif @@ -71,16 +69,13 @@ public override void OnDeserialization() public void SelectCustomColor1() { SelectCustomColorN(1); } public void SelectCustomColor2() { SelectCustomColorN(2); } public void SelectCustomColor3() { SelectCustomColorN(3); } - public void SelectCustomColorN(int n) - { + public void SelectCustomColorN(int n) { customColorIndex = n; UpdateGUI(); } - public void OnGUIchange() - { - if (!_processGUIEvents) - { + public void OnGUIchange() { + if (!_processGUIEvents) { return; } #if UDONSHARP @@ -102,11 +97,9 @@ public void OnGUIchange() #endif } - public void ResetThemeColors() - { + public void ResetThemeColors() { _themeColorMode = _initThemeColorMode; - for (int i = 0; i < 4; ++i) - { + for (int i = 0; i < 4; ++i) { customThemeColors[i] = _initCustomThemeColors[i]; } UpdateGUI(); @@ -116,15 +109,13 @@ public void ResetThemeColors() #endif } - public void UpdateGUI() - { + public void UpdateGUI() { _processGUIEvents = false; themeColorDropdown.value = _themeColorMode; bool isCustom = _themeColorMode == 1; extensionCanvas.gameObject.SetActive(isCustom); - for (int i = 0; i < 4; ++i) - { + for (int i = 0; i < 4; ++i) { customColorLassos[i].gameObject.SetActive( i == customColorIndex ); @@ -140,8 +131,7 @@ public void UpdateGUI() _processGUIEvents = true; } - public void InitializeAudioLinkThemeColors() - { + public void InitializeAudioLinkThemeColors() { if (audioLink == null) return; customThemeColors[0] = audioLink.customThemeColor0; @@ -167,8 +157,7 @@ public void InitializeAudioLinkThemeColors() #endif } - public void UpdateAudioLinkThemeColors() - { + public void UpdateAudioLinkThemeColors() { if (audioLink == null) return; audioLink.themeColorMode = _themeColorMode; audioLink.customThemeColor0 = customThemeColors[0]; diff --git a/Packages/com.llealloo.audiolink/Runtime/Scripts/UdonSyncedAttribute.cs b/Packages/com.llealloo.audiolink/Runtime/Scripts/UdonSyncedAttribute.cs index db42d071..ea77f131 100644 --- a/Packages/com.llealloo.audiolink/Runtime/Scripts/UdonSyncedAttribute.cs +++ b/Packages/com.llealloo.audiolink/Runtime/Scripts/UdonSyncedAttribute.cs @@ -1,3 +1,3 @@ #if !UDONSHARP && !COMPILER_UDONSHARP namespace AudioLink { internal class UdonSyncedAttribute : System.Attribute { } } // stub so we don't have to do the #if UDONSHARP song and dance -#endif \ No newline at end of file +#endif diff --git a/Packages/com.llealloo.audiolink/Runtime/Scripts/ytdlpPlayer.cs b/Packages/com.llealloo.audiolink/Runtime/Scripts/ytdlpPlayer.cs index 761f33f4..146c9975 100644 --- a/Packages/com.llealloo.audiolink/Runtime/Scripts/ytdlpPlayer.cs +++ b/Packages/com.llealloo.audiolink/Runtime/Scripts/ytdlpPlayer.cs @@ -12,10 +12,8 @@ // TODO(float3): add this to the AudioLinkMiniPlayer -namespace AudioLink -{ - public class ytdlpPlayer : MonoBehaviour - { +namespace AudioLink { + public class ytdlpPlayer : MonoBehaviour { public string ytdlpURL = "https://www.youtube.com/watch?v=SFTcZ1GXOCQ"; ytdlpRequest _currentRequest = null; @@ -27,8 +25,7 @@ public class ytdlpPlayer : MonoBehaviour [SerializeField] public Resolution resolution = Resolution._720p; - public enum Resolution - { + public enum Resolution { [InspectorName("360p")] _360p = 360, [InspectorName("480p")] _480p = 480, [InspectorName("720p")] _720p = 720, @@ -37,80 +34,64 @@ public enum Resolution [InspectorName("2160p")] _2160p = 2160, } - void OnEnable() - { + void OnEnable() { RequestPlay(); } - public void RequestPlay() - { + public void RequestPlay() { _currentRequest = ytdlpURLResolver.Resolve(ytdlpURL, (int)resolution); } - void Update() - { - if (_currentRequest != null && _currentRequest.isDone) - { + void Update() { + if (_currentRequest != null && _currentRequest.isDone) { UpdateUrl(_currentRequest.resolvedURL); _currentRequest = null; } } - public void UpdateUrl(string resolved) - { + public void UpdateUrl(string resolved) { if (videoPlayer == null) return; videoPlayer.url = resolved; SetPlaybackTime(0.0f); - if (videoPlayer.length > 0) - { + if (videoPlayer.length > 0) { videoPlayer.Play(); } } - public float GetPlaybackTime() - { + public float GetPlaybackTime() { if (videoPlayer != null && videoPlayer.length > 0) return (float)(videoPlayer.length > 0 ? videoPlayer.time / videoPlayer.length : 0); else return 0; } - public void SetPlaybackTime(float time) - { + public void SetPlaybackTime(float time) { if (videoPlayer != null && videoPlayer.length > 0 && videoPlayer.canSetTime) videoPlayer.time = videoPlayer.length * Mathf.Clamp(time, 0.0f, 1.0f); } - public string FormattedTimestamp(double seconds, double maxSeconds = 0) - { + public string FormattedTimestamp(double seconds, double maxSeconds = 0) { double formatValue = maxSeconds > 0 ? maxSeconds : seconds; string formatString = formatValue >= 3600.0 ? @"hh\:mm\:ss" : @"mm\:ss"; return TimeSpan.FromSeconds(seconds).ToString(formatString); } - public string PlaybackTimestampFormatted() - { - if (videoPlayer != null && videoPlayer.length > 0) - { + public string PlaybackTimestampFormatted() { + if (videoPlayer != null && videoPlayer.length > 0) { return $"{FormattedTimestamp(videoPlayer.time, videoPlayer.length)} / {FormattedTimestamp(videoPlayer.length)}"; - } - else - { + } else { return "00:00 / 00:00"; } } - public bool GetAudioSourceVolume(out float volume) - { + public bool GetAudioSourceVolume(out float volume) { volume = 0; - if (videoPlayer != null) - { + if (videoPlayer != null) { AudioSource audioSourceOutput = videoPlayer.GetTargetAudioSource(0); - if (audioSourceOutput != null) - { + if (audioSourceOutput != null) { volume = audioSourceOutput.volume; return true; } @@ -119,10 +100,8 @@ public bool GetAudioSourceVolume(out float volume) return false; } - public void SetAudioSourceVolume(float volume) - { - if (videoPlayer != null) - { + public void SetAudioSourceVolume(float volume) { + if (videoPlayer != null) { AudioSource audioSourceOutput = videoPlayer.GetTargetAudioSource(0); if (audioSourceOutput != null) audioSourceOutput.volume = Mathf.Clamp01(volume); @@ -130,21 +109,18 @@ public void SetAudioSourceVolume(float volume) } } - public class ytdlpRequest - { + public class ytdlpRequest { public bool isDone; public string resolvedURL; } - public static class ytdlpURLResolver - { + public static class ytdlpURLResolver { private static string _localytdlpPath = Application.dataPath + "\\AudioLink\\yt-dlp.exe"; private static string _ytdlpPath = ""; private static bool _ytdlpFound = false; - public static bool IsytdlpAvailable() - { + public static bool IsytdlpAvailable() { if (_ytdlpFound) return true; @@ -152,8 +128,7 @@ public static bool IsytdlpAvailable() return _ytdlpFound; } - public static void Locateytdlp() - { + public static void Locateytdlp() { _ytdlpFound = false; #if UNITY_EDITOR_WIN string[] splitPath = Application.persistentDataPath.Split('/', '\\'); @@ -162,13 +137,11 @@ public static void Locateytdlp() #else _ytdlpPath = "/usr/bin/yt-dlp"; #endif - if (!File.Exists(_ytdlpPath)) - { + if (!File.Exists(_ytdlpPath)) { _ytdlpPath = _localytdlpPath; } - if (!File.Exists(_ytdlpPath)) - { + if (!File.Exists(_ytdlpPath)) { #if UNITY_EDITOR_WIN _ytdlpPath = LocateExecutable("yt-dlp.exe"); #else @@ -176,26 +149,20 @@ public static void Locateytdlp() #endif } - if (!File.Exists(_ytdlpPath)) - { + if (!File.Exists(_ytdlpPath)) { return; - } - else - { + } else { _ytdlpFound = true; Debug.Log($"[AudioLink:ytdlp] Found yt-dlp at path '{_ytdlpPath}'"); } } - public static ytdlpRequest Resolve(string url, int resolution = 720) - { - if (!_ytdlpFound) - { + public static ytdlpRequest Resolve(string url, int resolution = 720) { + if (!_ytdlpFound) { Locateytdlp(); } - if (!_ytdlpFound) - { + if (!_ytdlpFound) { Debug.LogWarning($"[AudioLink:ytdlp] Unable to resolve URL '{url}' : yt-dlp not found"); } @@ -211,43 +178,33 @@ public static ytdlpRequest Resolve(string url, int resolution = 720) proc.StartInfo.FileName = _ytdlpPath; proc.StartInfo.Arguments = $"--no-check-certificate --no-cache-dir --rm-cache-dir -f \"mp4[height<=?{resolution}]/best[height<=?{resolution}]\" --get-url \"{url}\""; - proc.Exited += (sender, args) => - { + proc.Exited += (sender, args) => { proc.Dispose(); }; - proc.OutputDataReceived += (sender, args) => - { - if (args.Data != null) - { + proc.OutputDataReceived += (sender, args) => { + if (args.Data != null) { request.resolvedURL = args.Data; request.isDone = true; } }; - try - { + try { proc.Start(); proc.BeginOutputReadLine(); return request; - } - catch (Exception e) - { + } catch (Exception e) { Debug.LogWarning($"[AudioLink:ytdlp] Unable to resolve URL '{url}' : " + e.Message); return null; } } - private static string LocateExecutable(string name) - { - if (!File.Exists(name)) - { - if (Path.GetDirectoryName(name) == string.Empty) - { + private static string LocateExecutable(string name) { + if (!File.Exists(name)) { + if (Path.GetDirectoryName(name) == string.Empty) { string[] path = (Environment.GetEnvironmentVariable("PATH") ?? "").Split(Path.PathSeparator); - foreach (string dir in path) - { + foreach (string dir in path) { string trimmed = dir.Trim(); if (!string.IsNullOrEmpty(trimmed) && File.Exists(Path.Combine(trimmed, name))) return Path.GetFullPath(Path.Combine(trimmed, name)); @@ -259,28 +216,24 @@ private static string LocateExecutable(string name) } [CustomEditor(typeof(ytdlpPlayer))] - public class ytdlpPlayerEditor : UnityEditor.Editor - { + public class ytdlpPlayerEditor : UnityEditor.Editor { ytdlpPlayer _ytdlpPlayer; - void OnEnable() - { + void OnEnable() { _ytdlpPlayer = (ytdlpPlayer)target; // If video player is on the same gameobject, assign it automatically if (_ytdlpPlayer.gameObject.GetComponent() != null) _ytdlpPlayer.videoPlayer = _ytdlpPlayer.gameObject.GetComponent(); } - public override bool RequiresConstantRepaint() - { + public override bool RequiresConstantRepaint() { if (_ytdlpPlayer.videoPlayer != null) return _ytdlpPlayer.videoPlayer.isPlaying; else return false; } - public override void OnInspectorGUI() - { + public override void OnInspectorGUI() { #if UNITY_EDITOR_LINUX bool available = false; #else @@ -291,24 +244,19 @@ public override void OnInspectorGUI() float playbackTime = hasVideoPlayer ? _ytdlpPlayer.GetPlaybackTime() : 0; double videoLength = hasVideoPlayer ? _ytdlpPlayer.videoPlayer.length : 0; - using (new EditorGUI.DisabledScope(!available)) - { - using (new EditorGUILayout.HorizontalScope()) - { + using (new EditorGUI.DisabledScope(!available)) { + using (new EditorGUILayout.HorizontalScope()) { EditorGUILayout.LabelField(new GUIContent(" Video URL", EditorGUIUtility.IconContent("CloudConnect").image), GUILayout.Width(100)); EditorGUI.BeginChangeCheck(); _ytdlpPlayer.ytdlpURL = EditorGUILayout.TextField(_ytdlpPlayer.ytdlpURL); - if (EditorGUI.EndChangeCheck()) - { + if (EditorGUI.EndChangeCheck()) { EditorUtility.SetDirty(_ytdlpPlayer); }; _ytdlpPlayer.resolution = (ytdlpPlayer.Resolution)EditorGUILayout.EnumPopup(_ytdlpPlayer.resolution, GUILayout.Width(65)); } - using (new EditorGUI.DisabledScope(!hasVideoPlayer || !EditorApplication.isPlaying)) - { - using (new EditorGUILayout.HorizontalScope()) - { + using (new EditorGUI.DisabledScope(!hasVideoPlayer || !EditorApplication.isPlaying)) { + using (new EditorGUILayout.HorizontalScope()) { // Timestamp/Reload button EditorGUILayout.LabelField(new GUIContent(" Seek: " + _ytdlpPlayer.PlaybackTimestampFormatted(), EditorGUIUtility.IconContent("d_Slider Icon").image)); @@ -321,8 +269,7 @@ public override void OnInspectorGUI() // Seekbar/Time input using (new EditorGUI.DisabledScope(!hasVideoPlayer || videoLength == 0)) - using (new EditorGUILayout.HorizontalScope()) - { + using (new EditorGUILayout.HorizontalScope()) { // Seekbar input EditorGUI.BeginChangeCheck(); playbackTime = GUILayout.HorizontalSlider(playbackTime, 0, 1); @@ -334,15 +281,13 @@ public override void OnInspectorGUI() double time = hasVideoPlayer ? _ytdlpPlayer.videoPlayer.time : 0; string currentTimestamp = _ytdlpPlayer.FormattedTimestamp(time, videoLength); string seekTimestamp = EditorGUILayout.DelayedTextField(currentTimestamp, GUILayout.MaxWidth(8 * currentTimestamp.Length)); - if (EditorGUI.EndChangeCheck() && videoLength > 0) - { + if (EditorGUI.EndChangeCheck() && videoLength > 0) { TimeSpan inputTimestamp; // Add extra 00:'s to force TimeSpan.TryParse to interpret times properly // 22 -> 00:00:22, 2:22 -> 00:02:22, 2:22:22 -> 00:2:22:22 if (seekTimestamp.Length < 5) seekTimestamp = "00:" + seekTimestamp; - if (TimeSpan.TryParse($"00:{seekTimestamp}", out inputTimestamp)) - { + if (TimeSpan.TryParse($"00:{seekTimestamp}", out inputTimestamp)) { playbackTime = (float)(inputTimestamp.TotalSeconds / videoLength); _ytdlpPlayer.SetPlaybackTime(playbackTime); } @@ -350,8 +295,7 @@ public override void OnInspectorGUI() } // Media Controls - using (new EditorGUILayout.HorizontalScope()) - { + using (new EditorGUILayout.HorizontalScope()) { bool isPlaying = hasVideoPlayer ? _ytdlpPlayer.videoPlayer.isPlaying : false; bool isPaused = hasVideoPlayer ? _ytdlpPlayer.videoPlayer.isPaused : false; bool isStopped = !isPlaying && !isPaused; @@ -360,8 +304,7 @@ public override void OnInspectorGUI() bool pause = GUILayout.Toggle(isPaused, new GUIContent(" Pause", EditorGUIUtility.IconContent("d_PauseButton On").image), "Button") != isPaused; bool stop = GUILayout.Toggle(isStopped, new GUIContent(" Stop", EditorGUIUtility.IconContent("d_Record Off").image), "Button") != isStopped; - if (hasVideoPlayer) - { + if (hasVideoPlayer) { if (play) _ytdlpPlayer.videoPlayer.Play(); else if (pause) @@ -373,8 +316,7 @@ public override void OnInspectorGUI() } float volume; - using (new EditorGUI.DisabledScope(!_ytdlpPlayer.GetAudioSourceVolume(out volume))) - { + using (new EditorGUI.DisabledScope(!_ytdlpPlayer.GetAudioSourceVolume(out volume))) { EditorGUI.BeginChangeCheck(); volume = EditorGUILayout.Slider(new GUIContent(" AudioSource Volume", EditorGUIUtility.IconContent("d_Profiler.Audio").image), volume, 0.0f, 1.0f); if (EditorGUI.EndChangeCheck()) @@ -384,18 +326,15 @@ public override void OnInspectorGUI() bool videoPlayerOnThisObject = _ytdlpPlayer.gameObject.GetComponent() != null; - using (new EditorGUI.DisabledScope(EditorApplication.isPlaying || videoPlayerOnThisObject)) - { + using (new EditorGUI.DisabledScope(EditorApplication.isPlaying || videoPlayerOnThisObject)) { _ytdlpPlayer.videoPlayer = (VideoPlayer)EditorGUILayout.ObjectField(new GUIContent(" VideoPlayer", EditorGUIUtility.IconContent("d_Profiler.Video").image), _ytdlpPlayer.videoPlayer, typeof(VideoPlayer), allowSceneObjects: true); } // Video preview - using (new EditorGUI.DisabledScope(!available || !hasVideoPlayer)) - { + using (new EditorGUI.DisabledScope(!available || !hasVideoPlayer)) { _ytdlpPlayer.showVideoPreviewInComponent = EditorGUILayout.Toggle(new GUIContent(" Show Video Preview", EditorGUIUtility.IconContent("d_ViewToolOrbit On").image), _ytdlpPlayer.showVideoPreviewInComponent); - if (_ytdlpPlayer.showVideoPreviewInComponent && available && hasVideoPlayer && _ytdlpPlayer.videoPlayer.texture != null) - { + if (_ytdlpPlayer.showVideoPreviewInComponent && available && hasVideoPlayer && _ytdlpPlayer.videoPlayer.texture != null) { // Draw video preview with the same aspect ratio as the video Texture videoPlayerTexture = _ytdlpPlayer.videoPlayer.texture; float aspectRatio = (float)videoPlayerTexture.width / videoPlayerTexture.height; @@ -404,8 +343,7 @@ public override void OnInspectorGUI() } } - if (!available) - { + if (!available) { #if UNITY_EDITOR_LINUX EditorGUILayout.HelpBox("The yt-dlp Player is currently not supported on Linux, as Unity on Linux cannot play the required file formats.", MessageType.Warning); #elif UNITY_EDITOR_WIN @@ -418,4 +356,4 @@ public override void OnInspectorGUI() } } -#endif \ No newline at end of file +#endif