Beispiel #1
0
 // --------   Bank Platform ----------------------
 public string GetBankPlatform(FMODPlatform platform)
 {
     if (!HasPlatforms)
     {
         return("");
     }
     #if UNITY_EDITOR
     if (platform == FMODPlatform.PlayInEditor)
     {
         return(GetSetting(BankDirectorySettings, platform, GetSetting(BankDirectorySettings, RuntimeUtils.GetEditorFMODPlatform(), "Desktop")));
     }
     else
     #endif
     {
         return(GetSetting(BankDirectorySettings, platform, "Desktop"));
     }
 }
Beispiel #2
0
        public static void CopyToStreamingAssets()
        {
            if (string.IsNullOrEmpty(Settings.Instance.SourceBankPath))
            {
                return;
            }

            FMODPlatform platform = RuntimeUtils.GetEditorFMODPlatform();

            if (platform == FMODPlatform.None)
            {
                UnityEngine.Debug.LogWarning(string.Format("FMOD Studio: copy banks for platform {0} : Unsupported platform", EditorUserBuildSettings.activeBuildTarget.ToString()));
                return;
            }

            string bankTargetFolder =
                Settings.Instance.ImportType == ImportType.StreamingAssets
                ? Application.dataPath + "/StreamingAssets"
                : Application.dataPath + (string.IsNullOrEmpty(Settings.Instance.TargetAssetPath) ? "" : '/' + Settings.Instance.TargetAssetPath);

            bankTargetFolder = RuntimeUtils.GetCommonPlatformPath(bankTargetFolder);
            Directory.CreateDirectory(bankTargetFolder);

            string bankTargetExension =
                Settings.Instance.ImportType == ImportType.StreamingAssets
                ? "bank"
                : "bytes";

            string bankSourceFolder =
                Settings.Instance.HasPlatforms
                ? Settings.Instance.SourceBankPath + '/' + Settings.Instance.GetBankPlatform(platform)
                : Settings.Instance.SourceBankPath;

            bankSourceFolder = RuntimeUtils.GetCommonPlatformPath(bankSourceFolder);

            if (Path.GetFullPath(bankTargetFolder).TrimEnd('/').ToUpperInvariant() ==
                Path.GetFullPath(bankSourceFolder).TrimEnd('/').ToUpperInvariant())
            {
                return;
            }

            bool madeChanges = false;

            try
            {
                // Clean out any stale .bank files
                string[] currentBankFiles = Directory.GetFiles(bankTargetFolder, "*." + bankTargetExension);
                foreach (var bankFileName in currentBankFiles)
                {
                    string bankName = Path.GetFileNameWithoutExtension(bankFileName);
                    if (!eventCache.EditorBanks.Exists((x) => bankName == x.Name))
                    {
                        string assetString = bankFileName.Replace(Application.dataPath, "Assets");
                        AssetDatabase.ImportAsset(assetString);
                        UnityEngine.Object obj    = AssetDatabase.LoadAssetAtPath <UnityEngine.Object>(assetString);
                        string[]           labels = AssetDatabase.GetLabels(obj);
                        bool containsLabel        = false;
                        foreach (string label in labels)
                        {
                            if (label.Equals("FMOD"))
                            {
                                containsLabel = true;
                                break;
                            }
                        }
                        if (containsLabel)
                        {
                            File.Delete(bankFileName);
                            madeChanges = true;
                        }
                    }
                }

                // Copy over any files that don't match timestamp or size or don't exist
                foreach (var bankRef in eventCache.EditorBanks)
                {
                    string sourcePath = bankSourceFolder + "/" + bankRef.Name + ".bank";
                    string targetPath = bankTargetFolder + "/" + bankRef.Name + "." + bankTargetExension;

                    FileInfo sourceInfo = new FileInfo(sourcePath);
                    FileInfo targetInfo = new FileInfo(targetPath);

                    if (!targetInfo.Exists ||
                        sourceInfo.Length != targetInfo.Length ||
                        sourceInfo.LastWriteTime != targetInfo.LastWriteTime)
                    {
                        if (targetInfo.Exists)
                        {
                            targetInfo.IsReadOnly = false;
                        }
                        File.Copy(sourcePath, targetPath, true);
                        targetInfo               = new FileInfo(targetPath);
                        targetInfo.IsReadOnly    = false;
                        targetInfo.LastWriteTime = sourceInfo.LastWriteTime;

                        madeChanges = true;

                        string assetString = targetPath.Replace(Application.dataPath, "Assets");
                        AssetDatabase.ImportAsset(assetString);
                        UnityEngine.Object obj = AssetDatabase.LoadAssetAtPath <UnityEngine.Object>(assetString);
                        AssetDatabase.SetLabels(obj, new string[] { "FMOD" });
                    }
                }
            }
            catch (Exception exception)
            {
                UnityEngine.Debug.LogError(string.Format("FMOD Studio: copy banks for platform {0} : copying banks from {1} to {2}", platform.ToString(), bankSourceFolder, bankTargetFolder));
                UnityEngine.Debug.LogException(exception);
                return;
            }

            if (madeChanges)
            {
                AssetDatabase.SaveAssets();
                AssetDatabase.Refresh();
                UnityEngine.Debug.Log(string.Format("FMOD Studio: copy banks for platform {0} : copying banks from {1} to {2} succeeded", platform.ToString(), bankSourceFolder, bankTargetFolder));
            }
        }
Beispiel #3
0
        public override void OnInspectorGUI()
        {
            Settings settings = target as Settings;

            DrawLinks();

            EditorGUI.BeginChangeCheck();

            hasBankSourceChanged = false;
            bool hasBankTargetChanged = false;

            GUIStyle style = new GUIStyle(GUI.skin.label);

            style.richText = true;

            GUI.skin.FindStyle("HelpBox").richText = true;

            SourceType sourceType = settings.HasSourceProject ? SourceType.Project : (settings.HasPlatforms ? SourceType.Multi : SourceType.Single);

            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.BeginVertical();
            sourceType = GUILayout.Toggle(sourceType == SourceType.Project, "Project", "Button") ? 0 : sourceType;
            sourceType = GUILayout.Toggle(sourceType == SourceType.Single, "Single Platform Build", "Button") ? SourceType.Single : sourceType;
            sourceType = GUILayout.Toggle(sourceType == SourceType.Multi, "Multiple Platform Build", "Button") ? SourceType.Multi : sourceType;
            EditorGUILayout.EndVertical();
            EditorGUILayout.BeginVertical();

            EditorGUILayout.HelpBox(
                "<size=11>Select the way you wish to connect Unity to the FMOD Studio content:\n" +
                "<b>• Project</b>\t\tIf you have the complete FMOD Studio project avaliable\n" +
                "<b>• Single Platform</b>\tIf you have only the contents of the <i>Build</i> folder for a single platform\n" +
                "<b>• Multiple Platforms</b>\tIf you have only the contents of the <i>Build</i> folder for multiple platforms, each platform in it's own sub directory\n" +
                "</size>"
                , MessageType.Info, true);
            EditorGUILayout.EndVertical();
            EditorGUILayout.EndHorizontal();
            EditorGUILayout.Space();

            if (sourceType == SourceType.Project)
            {
                EditorGUILayout.BeginHorizontal();
                string oldPath = settings.SourceProjectPath;
                EditorGUILayout.PrefixLabel("Studio Project Path", GUI.skin.textField, style);

                EditorGUI.BeginChangeCheck();
                string newPath = EditorGUILayout.TextField(GUIContent.none, settings.SourceProjectPath);
                if (EditorGUI.EndChangeCheck())
                {
                    if (newPath.EndsWith(".fspro"))
                    {
                        settings.SourceProjectPath = newPath;
                    }
                }

                if (GUILayout.Button("Browse", GUILayout.ExpandWidth(false)))
                {
                    GUI.FocusControl(null);
                    EditorApplication.update += BrowseForSourceProjectPath;
                }
                EditorGUILayout.EndHorizontal();

                // Cache in settings for runtime access in play-in-editor mode
                string bankPath = EditorUtils.GetBankDirectory();
                settings.SourceBankPath   = bankPath;
                settings.HasPlatforms     = true;
                settings.HasSourceProject = true;

                // First time project path is set or changes, copy to streaming assets
                if (settings.SourceProjectPath != oldPath)
                {
                    hasBankSourceChanged = true;
                }
            }
            else if (sourceType == SourceType.Single || sourceType == SourceType.Multi)
            {
                EditorGUILayout.BeginHorizontal();
                string oldPath = settings.SourceBankPath;
                EditorGUILayout.PrefixLabel("Build Path", GUI.skin.textField, style);

                EditorGUI.BeginChangeCheck();
                string tempPath = EditorGUILayout.TextField(GUIContent.none, settings.SourceBankPath);
                if (EditorGUI.EndChangeCheck())
                {
                    settings.SourceBankPath = tempPath;
                }

                if (GUILayout.Button("Browse", GUILayout.ExpandWidth(false)))
                {
                    GUI.FocusControl(null);
                    EditorApplication.update += BrowseForSourceBankPath;
                }
                EditorGUILayout.EndHorizontal();

                settings.HasPlatforms     = (sourceType == SourceType.Multi);
                settings.HasSourceProject = false;

                // First time project path is set or changes, copy to streaming assets
                if (settings.SourceBankPath != oldPath)
                {
                    hasBankSourceChanged = true;
                }
            }

            bool   validBanks;
            string failReason;

            EditorUtils.ValidateSource(out validBanks, out failReason);
            if (!validBanks)
            {
                failReason += "\n\nFor detailed setup instructions, please see the getting started guide linked above.";
                EditorGUILayout.HelpBox(failReason, MessageType.Error, true);
                if (EditorGUI.EndChangeCheck())
                {
                    EditorUtility.SetDirty(settings);
                }
                return;
            }

            if (!RuntimeUtils.VerifyPlatformLibsExist())
            {
                string errMsg = "Unable to find the FMOD '" + RuntimeUtils.GetEditorFMODPlatform() + "' libs. See console for details.";
                EditorGUILayout.HelpBox(errMsg, MessageType.Error, true);
                if (EditorGUI.EndChangeCheck())
                {
                    EditorUtility.SetDirty(settings);
                }
                return;
            }

            ImportType importType = (ImportType)EditorGUILayout.EnumPopup("Import Type", settings.ImportType);

            if (importType != settings.ImportType)
            {
                hasBankTargetChanged = true;
                settings.ImportType  = importType;

                bool deleteBanks = EditorUtility.DisplayDialog(
                    "FMOD Bank Import Type Changed", "Do you want to delete the " + (importType == ImportType.AssetBundle ? "StreamingAssets" : "AssetBundle") + " banks in " + (importType == ImportType.AssetBundle ? Application.streamingAssetsPath : Application.dataPath + '/' + settings.TargetAssetPath)
                    , "Yes", "No");
                if (deleteBanks)
                {
                    // Delete the old banks
                    EventManager.removeBanks = true;
                    EventManager.RefreshBanks();
                }
            }

            // ----- Text Assets -------------
            if (settings.ImportType == ImportType.AssetBundle)
            {
                GUI.SetNextControlName("targetAssetPath");
                targetAssetPath = EditorGUILayout.TextField("FMOD Asset Folder", string.IsNullOrEmpty(targetAssetPath) ? settings.TargetAssetPath : targetAssetPath);
                if (GUI.GetNameOfFocusedControl() == "targetAssetPath")
                {
                    focused = true;
                    if (Event.current.isKey)
                    {
                        switch (Event.current.keyCode)
                        {
                        case KeyCode.Return:
                        case KeyCode.KeypadEnter:
                            if (settings.TargetAssetPath != targetAssetPath)
                            {
                                EventManager.RemoveBanks(Application.dataPath + '/' + settings.TargetAssetPath);
                                settings.TargetAssetPath = targetAssetPath;
                                hasBankTargetChanged     = true;
                            }
                            break;
                        }
                    }
                }
                else if (focused)
                {
                    if (settings.TargetAssetPath != targetAssetPath)
                    {
                        EventManager.RemoveBanks(Application.dataPath + '/' + settings.TargetAssetPath);
                        settings.TargetAssetPath = targetAssetPath;
                        hasBankTargetChanged     = true;
                    }
                }
            }

            // ----- Logging -----------------
            EditorGUILayout.Separator();
            EditorGUILayout.LabelField("<b>Logging</b>", style);
            EditorGUI.indentLevel++;
            settings.LoggingLevel = (FMOD.DEBUG_FLAGS)EditorGUILayout.EnumPopup("Logging Level", settings.LoggingLevel);
            EditorGUI.indentLevel--;

            // ----- Loading -----------------
            EditorGUI.BeginDisabledGroup(settings.ImportType == ImportType.AssetBundle);
            EditorGUILayout.Separator();
            EditorGUILayout.LabelField("<b>Initialization</b>", style);
            EditorGUI.indentLevel++;

            settings.BankLoadType = (BankLoadType)EditorGUILayout.EnumPopup("Load Banks", settings.BankLoadType);
            switch (settings.BankLoadType)
            {
            case BankLoadType.All:
                break;

            case BankLoadType.Specified:
                settings.AutomaticEventLoading = false;
                Texture upArrowTexture   = EditorGUIUtility.Load("FMOD/ArrowUp.png") as Texture;
                Texture downArrowTexture = EditorGUIUtility.Load("FMOD/ArrowDown.png") as Texture;
                bankFoldOutState = EditorGUILayout.Foldout(bankFoldOutState, "Specified Banks", true);
                if (bankFoldOutState)
                {
                    for (int i = 0; i < settings.BanksToLoad.Count; i++)
                    {
                        EditorGUILayout.BeginHorizontal();
                        EditorGUI.indentLevel++;

                        var bankName = settings.BanksToLoad[i];
                        EditorGUILayout.TextField(bankName.Replace(".bank", ""));

                        if (GUILayout.Button(upArrowTexture, GUILayout.ExpandWidth(false)))
                        {
                            if (i > 0)
                            {
                                var temp = settings.BanksToLoad[i];
                                settings.BanksToLoad[i]     = settings.BanksToLoad[i - 1];
                                settings.BanksToLoad[i - 1] = temp;
                            }
                            continue;
                        }
                        if (GUILayout.Button(downArrowTexture, GUILayout.ExpandWidth(false)))
                        {
                            if (i < settings.BanksToLoad.Count - 1)
                            {
                                var temp = settings.BanksToLoad[i];
                                settings.BanksToLoad[i]     = settings.BanksToLoad[i + 1];
                                settings.BanksToLoad[i + 1] = temp;
                            }
                            continue;
                        }

                        if (GUILayout.Button("Browse", GUILayout.ExpandWidth(false)))
                        {
                            GUI.FocusControl(null);
                            string path = EditorUtility.OpenFilePanel("Locate Bank", Application.streamingAssetsPath, "bank");
                            if (!string.IsNullOrEmpty(path))
                            {
                                settings.BanksToLoad[i] = path.Replace(Application.streamingAssetsPath + Path.AltDirectorySeparatorChar, "");
                                Repaint();
                            }
                        }
                        if (GUILayout.Button("Remove", GUILayout.ExpandWidth(false)))
                        {
                            Settings.Instance.BanksToLoad.RemoveAt(i);
                            continue;
                        }
                        EditorGUILayout.EndHorizontal();
                        EditorGUI.indentLevel--;
                    }

                    GUILayout.BeginHorizontal();
                    GUILayout.Space(30);
                    if (GUILayout.Button("Add Bank", GUILayout.ExpandWidth(false)))
                    {
                        settings.BanksToLoad.Add("");
                    }
                    if (GUILayout.Button("Add All Banks", GUILayout.ExpandWidth(false)))
                    {
                        FMODPlatform platform = RuntimeUtils.GetEditorFMODPlatform();
                        if (platform == FMODPlatform.None)
                        {
                            platform = FMODPlatform.PlayInEditor;
                        }
                        string sourceDir = RuntimeUtils.GetCommonPlatformPath(settings.SourceBankPath + '/' + (settings.HasPlatforms ? settings.GetBankPlatform(platform) + '/' : ""));
                        sourceDir = RuntimeUtils.GetCommonPlatformPath(Path.GetFullPath(sourceDir));
                        var banksFound = new List <string>(Directory.GetFiles(sourceDir, "*.bank", SearchOption.AllDirectories));
                        for (int i = 0; i < banksFound.Count; i++)
                        {
                            string bankLongName  = RuntimeUtils.GetCommonPlatformPath(Path.GetFullPath(banksFound[i]));
                            string bankShortName = bankLongName.Replace(sourceDir, "");
                            if (!settings.BanksToLoad.Contains(bankShortName))
                            {
                                settings.BanksToLoad.Add(bankShortName);
                            }
                        }
                        Repaint();
                    }
                    if (GUILayout.Button("Clear", GUILayout.ExpandWidth(false)))
                    {
                        settings.BanksToLoad.Clear();
                    }
                    GUILayout.EndHorizontal();
                }
                break;

            case BankLoadType.None:
                settings.AutomaticEventLoading = false;
                break;

            default:
                break;
            }

            EditorGUI.BeginDisabledGroup(settings.BankLoadType == BankLoadType.None);
            settings.AutomaticSampleLoading = EditorGUILayout.Toggle("Load Bank Sample Data", settings.AutomaticSampleLoading);
            EditorGUI.EndDisabledGroup();

            settings.EncryptionKey = EditorGUILayout.TextField("Bank Encryption Key", settings.EncryptionKey);

            EditorGUI.indentLevel--;
            EditorGUI.EndDisabledGroup();

            // ----- PIE ----------------------------------------------
            EditorGUILayout.Separator();
            EditorGUILayout.LabelField("<b>Play In Editor Settings</b>", style);
            EditorGUI.indentLevel++;
            DisplayEditorBool("Live Update", settings.LiveUpdateSettings, FMODPlatform.PlayInEditor);
            if (settings.IsLiveUpdateEnabled(FMODPlatform.PlayInEditor))
            {
                EditorGUILayout.BeginHorizontal();
                settings.LiveUpdatePort = ushort.Parse(EditorGUILayout.TextField("Live Update Port:", settings.LiveUpdatePort.ToString()));
                if (GUILayout.Button("Reset", GUILayout.ExpandWidth(false)))
                {
                    settings.LiveUpdatePort = 9264;
                }
                EditorGUILayout.EndHorizontal();
            }
            DisplayEditorBool("Debug Overlay", settings.OverlaySettings, FMODPlatform.PlayInEditor);
            DisplayChildFreq("Sample Rate", settings.SampleRateSettings, FMODPlatform.PlayInEditor);
            if (settings.HasPlatforms)
            {
                DisplayPIEBuildDirectory("Bank Platform", settings.BankDirectorySettings, FMODPlatform.PlayInEditor);
            }

            DisplayPIESpeakerMode("Speaker Mode", settings.SpeakerModeSettings, FMODPlatform.PlayInEditor);
            if (settings.HasPlatforms)
            {
                EditorGUILayout.HelpBox(string.Format("Match the speaker mode to the setting of the platform <b>{0}</b> inside FMOD Studio", settings.GetBankPlatform(FMODPlatform.PlayInEditor)), MessageType.Info, false);
            }
            else
            {
                EditorGUILayout.HelpBox("Match the speaker mode to the setting inside FMOD Studio", MessageType.Info, false);
            }

            EditorGUI.indentLevel--;

            // ----- Default ----------------------------------------------
            EditorGUILayout.Separator();
            EditorGUILayout.LabelField("<b>Default Settings</b>", style);
            EditorGUI.indentLevel++;
            DisplayParentBool("Live Update", settings.LiveUpdateSettings, FMODPlatform.Default);
            if (settings.IsLiveUpdateEnabled(FMODPlatform.Default))
            {
                EditorGUILayout.BeginHorizontal();
                settings.LiveUpdatePort = ushort.Parse(EditorGUILayout.TextField("Live Update Port:", settings.LiveUpdatePort.ToString()));
                if (GUILayout.Button("Reset", GUILayout.ExpandWidth(false)))
                {
                    settings.LiveUpdatePort = 9264;
                }
                EditorGUILayout.EndHorizontal();
            }
            DisplayParentBool("Debug Overlay", settings.OverlaySettings, FMODPlatform.Default);
            DisplayParentFreq("Sample Rate", settings.SampleRateSettings, FMODPlatform.Default);
            if (settings.HasPlatforms)
            {
                bool prevChanged = GUI.changed;
                DisplayParentBuildDirectory("Bank Platform", settings.BankDirectorySettings, FMODPlatform.Default);
                hasBankSourceChanged |= !prevChanged && GUI.changed;
            }

            DisplayParentSpeakerMode("Speaker Mode", settings.SpeakerModeSettings, FMODPlatform.Default);
            if (settings.HasPlatforms)
            {
                EditorGUILayout.HelpBox(string.Format("Match the speaker mode to the setting of the platform <b>{0}</b> inside FMOD Studio", settings.GetBankPlatform(FMODPlatform.Default)), MessageType.Info, false);
            }
            else
            {
                EditorGUILayout.HelpBox("Match the speaker mode to the setting inside FMOD Studio", MessageType.Info, false);
            }
            DisplayParentInt("Virtual Channel Count", settings.VirtualChannelSettings, FMODPlatform.Default, 1, 2048);
            DisplayParentInt("Real Channel Count", settings.RealChannelSettings, FMODPlatform.Default, 1, 256);
            EditorGUI.indentLevel--;

            // ----- Plugins ----------------------------------------------
            EditorGUILayout.Separator();
            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.PrefixLabel("<b>Plugins</b>", GUI.skin.button, style);
            if (GUILayout.Button("Add Plugin", GUILayout.ExpandWidth(false)))
            {
                settings.Plugins.Add("");
            }
            EditorGUILayout.EndHorizontal();

            EditorGUI.indentLevel++;
            for (int count = 0; count < settings.Plugins.Count; count++)
            {
                EditorGUILayout.BeginHorizontal();
                settings.Plugins[count] = EditorGUILayout.TextField("Plugin " + (count + 1).ToString() + ":", settings.Plugins[count]);

                if (GUILayout.Button("Delete Plugin", GUILayout.ExpandWidth(false)))
                {
                    settings.Plugins.RemoveAt(count);
                }
                EditorGUILayout.EndHorizontal();
            }
            EditorGUI.indentLevel--;

            // ----- Windows ----------------------------------------------
            DisplayPlatform(FMODPlatform.Desktop, new FMODPlatform[] { FMODPlatform.WebGL });
            DisplayPlatform(FMODPlatform.Mobile, new FMODPlatform[] { FMODPlatform.MobileHigh, FMODPlatform.MobileLow, FMODPlatform.AppleTV });
            DisplayPlatform(FMODPlatform.Console, new FMODPlatform[] { FMODPlatform.XboxOne, FMODPlatform.PS4, FMODPlatform.Switch, FMODPlatform.Stadia });

            if (EditorGUI.EndChangeCheck())
            {
                EditorUtility.SetDirty(settings);
            }

            if (hasBankSourceChanged)
            {
                EventManager.RefreshBanks();
            }
            if (hasBankTargetChanged)
            {
                EventManager.RefreshBanks();
            }
        }
        public void Play()
        {
            if (TriggerOnce && hasTriggered)
            {
                return;
            }

            if (String.IsNullOrEmpty(Event))
            {
                return;
            }

            if (eventDescription == null)
            {
                Lookup();
            }

            bool isOneshot = false;

            if (!Event.StartsWith("snapshot", StringComparison.CurrentCultureIgnoreCase))
            {
                eventDescription.isOneshot(out isOneshot);
            }
            bool is3D;

            eventDescription.is3D(out is3D);

            if (instance != null && !instance.isValid())
            {
                instance = null;
            }

            // Let previous oneshot instances play out
            if (isOneshot && instance != null)
            {
                instance.release();
                instance = null;
            }

            if (instance == null)
            {
                eventDescription.createInstance(out instance);

                // Only want to update if we need to set 3D attributes
                if (is3D)
                {
                    var rigidBody = GetComponent <Rigidbody>();
                    var transform = GetComponent <Transform>();
                    instance.set3DAttributes(RuntimeUtils.To3DAttributes(gameObject, rigidBody));
                    RuntimeManager.AttachInstanceToGameObject(instance, transform, rigidBody);
                }
            }

            foreach (var param in Params)
            {
                instance.setParameterValue(param.Name, param.Value);
            }

            instance.start();

            hasTriggered = true;
        }
        public static void LoadBank(string bankName, bool loadSamples = false)
        {
            if (Instance.loadedBanks.ContainsKey(bankName))
            {
                LoadedBank loadedBank = Instance.loadedBanks[bankName];
                loadedBank.RefCount++;

                if (loadSamples)
                {
                    loadedBank.Bank.loadSampleData();
                }
                Instance.loadedBanks[bankName] = loadedBank;
            }
            else
            {
                LoadedBank  loadedBank = new LoadedBank();
                string      bankPath   = RuntimeUtils.GetBankPath(bankName);
                FMOD.RESULT loadResult;
                #if UNITY_ANDROID && !UNITY_EDITOR
                if (!bankPath.StartsWith("file:///android_asset"))
                {
                    using (var www = new WWW(bankPath))
                    {
                        while (!www.isDone)
                        {
                        }
                        if (!String.IsNullOrEmpty(www.error))
                        {
                            throw new BankLoadException(bankPath, www.error);
                        }
                        else
                        {
                            loadResult = Instance.studioSystem.loadBankMemory(www.bytes, FMOD.Studio.LOAD_BANK_FLAGS.NORMAL, out loadedBank.Bank);
                        }
                    }
                }
                else
                #endif
                {
                    loadResult = Instance.studioSystem.loadBankFile(bankPath, FMOD.Studio.LOAD_BANK_FLAGS.NORMAL, out loadedBank.Bank);
                }

                if (loadResult == FMOD.RESULT.OK)
                {
                    loadedBank.RefCount = 1;
                    Instance.loadedBanks.Add(bankName, loadedBank);

                    if (loadSamples)
                    {
                        loadedBank.Bank.loadSampleData();
                    }
                }
                else if (loadResult == FMOD.RESULT.ERR_EVENT_ALREADY_LOADED)
                {
                    // someone loaded this bank directly using the studio API
                    // TODO: will the null bank handle be an issue
                    loadedBank.RefCount = 2;
                    Instance.loadedBanks.Add(bankName, loadedBank);
                }
                else
                {
                    throw new BankLoadException(bankPath, loadResult);
                }
            }
        }
 public static void SetListenerLocation(int listenerIndex, GameObject gameObject, Rigidbody2D rigidBody2D)
 {
     Instance.studioSystem.setListenerAttributes(listenerIndex, RuntimeUtils.To3DAttributes(gameObject, rigidBody2D));
 }
Beispiel #7
0
        public static void CopyToStreamingAssets()
        {
            if (string.IsNullOrEmpty(Settings.Instance.SourceBankPath))
            {
                return;
            }

            FMODPlatform platform = RuntimeUtils.GetEditorFMODPlatform();

            if (platform == FMODPlatform.None)
            {
                UnityEngine.Debug.LogWarning(string.Format("FMOD Studio: copy banks for platform {0} : Unsupported platform", EditorUserBuildSettings.activeBuildTarget.ToString()));
                return;
            }

            string bankTargetFolder =
                Settings.Instance.ImportType == ImportType.StreamingAssets
                ? Application.dataPath + "/StreamingAssets"
                : Application.dataPath + (string.IsNullOrEmpty(Settings.Instance.TargetAssetPath) ? "" : '/' + Settings.Instance.TargetAssetPath);

            bankTargetFolder = RuntimeUtils.GetCommonPlatformPath(bankTargetFolder);
            Directory.CreateDirectory(bankTargetFolder);

            string bankTargetExtension =
                Settings.Instance.ImportType == ImportType.StreamingAssets
                ? ".bank"
                : ".bytes";

            string bankSourceFolder =
                Settings.Instance.HasPlatforms
                ? Settings.Instance.SourceBankPath + '/' + Settings.Instance.GetBankPlatform(platform)
                : Settings.Instance.SourceBankPath;

            bankSourceFolder = RuntimeUtils.GetCommonPlatformPath(bankSourceFolder);

            if (Path.GetFullPath(bankTargetFolder).TrimEnd('/').ToUpperInvariant() ==
                Path.GetFullPath(bankSourceFolder).TrimEnd('/').ToUpperInvariant())
            {
                return;
            }

            bool madeChanges = false;

            if (removeBanks)
            {
                string oldBankTargetFolder =
                    Settings.Instance.ImportType == ImportType.AssetBundle
                ? Application.dataPath + "/StreamingAssets"
                : Application.dataPath + "/" + Settings.Instance.TargetAssetPath;

                RemoveBanks(oldBankTargetFolder);
                madeChanges = true;
            }

            try
            {
                // Clean out any stale .bank files
                string[] existingBankFiles =
                    Directory.GetFiles(bankTargetFolder, "*" + bankTargetExtension, SearchOption.AllDirectories);

                foreach (string bankFilePath in existingBankFiles)
                {
                    string bankName = EditorBankRef.CalculateName(bankFilePath, bankTargetFolder);

                    if (!eventCache.EditorBanks.Exists(x => x.Name == bankName))
                    {
                        string assetPath = bankFilePath.Replace(Application.dataPath, AssetsFolderName);

                        if (AssetHasLabel(assetPath, FMODLabel))
                        {
                            AssetDatabase.MoveAssetToTrash(assetPath);
                            madeChanges = true;
                        }
                    }
                }

                // Copy over any files that don't match timestamp or size or don't exist
                foreach (var bankRef in eventCache.EditorBanks)
                {
                    string sourcePath         = bankSourceFolder + "/" + bankRef.Name + ".bank";
                    string targetPathRelative = bankRef.Name + bankTargetExtension;
                    string targetPathFull     = bankTargetFolder + "/" + targetPathRelative;

                    FileInfo sourceInfo = new FileInfo(sourcePath);
                    FileInfo targetInfo = new FileInfo(targetPathFull);

                    if (!targetInfo.Exists ||
                        sourceInfo.Length != targetInfo.Length ||
                        sourceInfo.LastWriteTime != targetInfo.LastWriteTime)
                    {
                        if (targetInfo.Exists)
                        {
                            targetInfo.IsReadOnly = false;
                        }
                        else
                        {
                            EnsureFoldersExist(targetPathRelative, bankTargetFolder);
                        }

                        File.Copy(sourcePath, targetPathFull, true);
                        targetInfo               = new FileInfo(targetPathFull);
                        targetInfo.IsReadOnly    = false;
                        targetInfo.LastWriteTime = sourceInfo.LastWriteTime;

                        madeChanges = true;

                        string assetString = targetPathFull.Replace(Application.dataPath, "Assets");
                        AssetDatabase.ImportAsset(assetString);
                        UnityEngine.Object obj = AssetDatabase.LoadAssetAtPath <UnityEngine.Object>(assetString);
                        AssetDatabase.SetLabels(obj, new string[] { FMODLabel });
                    }
                }

                RemoveEmptyFMODFolders(bankTargetFolder);
            }
            catch (Exception exception)
            {
                UnityEngine.Debug.LogError(string.Format("FMOD Studio: copy banks for platform {0} : copying banks from {1} to {2}", platform.ToString(), bankSourceFolder, bankTargetFolder));
                UnityEngine.Debug.LogException(exception);
                return;
            }

            if (madeChanges)
            {
                AssetDatabase.SaveAssets();
                AssetDatabase.Refresh();
                UnityEngine.Debug.Log(string.Format("FMOD Studio: copy banks for platform {0} : copying banks from {1} to {2} succeeded", platform.ToString(), bankSourceFolder, bankTargetFolder));
            }
        }
        FMOD.RESULT Initialize()
        {
            FMOD.RESULT result       = FMOD.RESULT.OK;
            FMOD.RESULT initResult   = FMOD.RESULT.OK;
            Settings    fmodSettings = Settings.Instance;

            fmodPlatform = RuntimeUtils.GetCurrentPlatform();

            int sampleRate      = fmodSettings.GetSampleRate(fmodPlatform);
            int realChannels    = Math.Min(fmodSettings.GetRealChannels(fmodPlatform), 256); // Prior to 1.08.10 we didn't clamp this properly in the settings screen
            int virtualChannels = fmodSettings.GetVirtualChannels(fmodPlatform);

            FMOD.SPEAKERMODE speakerMode = (FMOD.SPEAKERMODE)fmodSettings.GetSpeakerMode(fmodPlatform);
            FMOD.OUTPUTTYPE  outputType  = FMOD.OUTPUTTYPE.AUTODETECT;

            FMOD.ADVANCEDSETTINGS advancedSettings = new FMOD.ADVANCEDSETTINGS();
            advancedSettings.randomSeed = (uint)DateTime.Now.Ticks;
            #if UNITY_EDITOR || UNITY_STANDALONE
            advancedSettings.maxVorbisCodecs = realChannels;
            #elif UNITY_XBOXONE
            advancedSettings.maxXMACodecs = realChannels;
            #elif UNITY_PS4
            advancedSettings.maxAT9Codecs = realChannels;
            #else
            advancedSettings.maxFADPCMCodecs = realChannels;
            #endif

            #if UNITY_EDITOR || ((UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX) && DEVELOPMENT_BUILD)
            result = FMOD.Debug.Initialize(FMOD.DEBUG_FLAGS.LOG, FMOD.DEBUG_MODE.FILE, null, RuntimeUtils.LogFileName);
            if (result == FMOD.RESULT.ERR_FILE_NOTFOUND)
            {
                UnityEngine.Debug.LogWarningFormat("FMOD Studio: Cannot open FMOD debug log file '{0}', logs will be missing for this session.", System.IO.Path.Combine(Application.dataPath, RuntimeUtils.LogFileName));
            }
            else
            {
                CheckInitResult(result, "FMOD.Debug.Initialize");
            }
            #endif

            FMOD.Studio.INITFLAGS studioInitFlags = FMOD.Studio.INITFLAGS.NORMAL | FMOD.Studio.INITFLAGS.DEFERRED_CALLBACKS;
            if (fmodSettings.IsLiveUpdateEnabled(fmodPlatform))
            {
                studioInitFlags |= FMOD.Studio.INITFLAGS.LIVEUPDATE;

                #if UNITY_5_0 || UNITY_5_1 // These versions of Unity shipped with FMOD4 profiling enabled consuming our port number.
                UnityEngine.Debug.LogWarning("FMOD Studio: Live Update port in-use by Unity, switching to port 9265");
                advancedSettings.profilePort = 9265;
                #endif
            }

retry:
            result = FMOD.Studio.System.create(out studioSystem);
            CheckInitResult(result, "FMOD.Studio.System.create");

            result = studioSystem.getLowLevelSystem(out lowlevelSystem);
            CheckInitResult(result, "FMOD.Studio.System.getLowLevelSystem");

            result = lowlevelSystem.setOutput(outputType);
            CheckInitResult(result, "FMOD.System.setOutput");

            result = lowlevelSystem.setSoftwareChannels(realChannels);
            CheckInitResult(result, "FMOD.System.setSoftwareChannels");

            result = lowlevelSystem.setSoftwareFormat(sampleRate, speakerMode, 0);
            CheckInitResult(result, "FMOD.System.setSoftwareFormat");

            result = lowlevelSystem.setAdvancedSettings(ref advancedSettings);
            CheckInitResult(result, "FMOD.System.setAdvancedSettings");

            result = studioSystem.initialize(virtualChannels, studioInitFlags, FMOD.INITFLAGS.NORMAL, IntPtr.Zero);
            if (result != FMOD.RESULT.OK && initResult == FMOD.RESULT.OK)
            {
                initResult = result; // Save this to throw at the end (we'll attempt NO SOUND to shield ourselves from unexpected device failures)
                outputType = FMOD.OUTPUTTYPE.NOSOUND;
                UnityEngine.Debug.LogErrorFormat("FMOD Studio: Studio::System::initialize returned {0}, defaulting to no-sound mode.", result.ToString());

                goto retry;
            }
            CheckInitResult(result, "Studio::System::initialize");

            // Test network functionality triggered during System::update
            if ((studioInitFlags & FMOD.Studio.INITFLAGS.LIVEUPDATE) != 0)
            {
                studioSystem.flushCommands(); // Any error will be returned through Studio.System.update

                result = studioSystem.update();
                if (result == FMOD.RESULT.ERR_NET_SOCKET_ERROR)
                {
                    studioInitFlags &= ~FMOD.Studio.INITFLAGS.LIVEUPDATE;
                    UnityEngine.Debug.LogWarning("FMOD Studio: Cannot open network port for Live Update (in-use), restarting with Live Update disabled.");

                    result = studioSystem.release();
                    CheckInitResult(result, "FMOD.Studio.System.Release");

                    goto retry;
                }
            }

            LoadPlugins(fmodSettings);
            LoadBanks(fmodSettings);

            return(initResult);
        }
Beispiel #9
0
        static private string UpdateCache()
        {
            if (eventCache == null)
            {
                eventCache = AssetDatabase.LoadAssetAtPath(CacheAssetFullName, typeof(EventCache)) as EventCache;
                if (eventCache == null || eventCache.cacheVersion != EventCache.CurrentCacheVersion)
                {
                    Debug.Log("FMOD: Event cache is missing or in an old format; creating a new instance.");

                    eventCache = ScriptableObject.CreateInstance <EventCache>();
                    eventCache.cacheVersion = EventCache.CurrentCacheVersion;

                    Directory.CreateDirectory(Path.GetDirectoryName(CacheAssetFullName));
                    AssetDatabase.CreateAsset(eventCache, CacheAssetFullName);
                }
            }

            var settings = Settings.Instance;

            if (string.IsNullOrEmpty(settings.SourceBankPath))
            {
                ClearCache();
                return(null);
            }

            string defaultBankFolder = null;

            if (!settings.HasPlatforms)
            {
                defaultBankFolder = settings.SourceBankPath;
            }
            else
            {
                Platform platform = settings.CurrentEditorPlatform;

                if (platform == settings.DefaultPlatform)
                {
                    platform = settings.PlayInEditorPlatform;
                }

                defaultBankFolder = RuntimeUtils.GetCommonPlatformPath(Path.Combine(settings.SourceBankPath, platform.BuildDirectory));
            }

            string[] bankPlatforms = EditorUtils.GetBankPlatforms();
            string[] bankFolders   = new string[bankPlatforms.Length];
            for (int i = 0; i < bankPlatforms.Length; i++)
            {
                bankFolders[i] = RuntimeUtils.GetCommonPlatformPath(Path.Combine(settings.SourceBankPath, bankPlatforms[i]));
            }

            List <string> stringBanks = new List <string>(0);

            try
            {
                var files = Directory.GetFiles(defaultBankFolder, "*." + StringBankExtension, SearchOption.AllDirectories);
                stringBanks = new List <string>(files);
            }
            catch
            {
            }

            // Strip out OSX resource-fork files that appear on FAT32
            stringBanks.RemoveAll((x) => Path.GetFileName(x).StartsWith("._"));

            if (stringBanks.Count == 0)
            {
                ClearCache();
                return(string.Format("Directory {0} doesn't contain any banks.\nBuild the banks in Studio or check the path in the settings.", defaultBankFolder));
            }

            // If we have multiple .strings.bank files find the most recent
            stringBanks.Sort((a, b) => File.GetLastWriteTime(b).CompareTo(File.GetLastWriteTime(a)));

            // Use the most recent string bank timestamp as a marker for the most recent build of any bank because it gets exported every time
            DateTime lastWriteTime = File.GetLastWriteTime(stringBanks[0]);

            // Get a list of all banks
            List <string>  bankFileNames          = new List <string>();
            List <string>  reducedStringBanksList = new List <string>();
            HashSet <Guid> stringBankGuids        = new HashSet <Guid>();

            foreach (string stringBankPath in stringBanks)
            {
                FMOD.Studio.Bank stringBank;
                EditorUtils.CheckResult(EditorUtils.System.loadBankFile(stringBankPath, FMOD.Studio.LOAD_BANK_FLAGS.NORMAL, out stringBank));

                if (!stringBank.isValid())
                {
                    return(string.Format("{0} is not a valid bank.", stringBankPath));
                }
                else
                {
                    // Unload the strings bank
                    stringBank.unload();
                }

                Guid stringBankGuid;
                EditorUtils.CheckResult(stringBank.getID(out stringBankGuid));

                if (!stringBankGuids.Add(stringBankGuid))
                {
                    // If we encounter multiple string banks with the same GUID then only use the first. This handles the scenario where
                    // a Studio project is cloned and extended for DLC with a new master bank name.
                    continue;
                }

                reducedStringBanksList.Add(stringBankPath);
            }

            bankFileNames = new List <string>(Directory.GetFiles(defaultBankFolder, "*.bank", SearchOption.AllDirectories));
            bankFileNames.RemoveAll(x => x.Contains(".strings"));

            stringBanks = reducedStringBanksList;

            eventCache.StringsBankWriteTime = lastWriteTime;

            // Stop editor preview so no stale data being held
            EditorUtils.PreviewStop();

            // Reload the strings banks
            List <FMOD.Studio.Bank> loadedStringsBanks = new List <FMOD.Studio.Bank>();

            try
            {
                AssetDatabase.StartAssetEditing();

                eventCache.EditorBanks.ForEach((x) => x.Exists = false);
                HashSet <string> masterBankFileNames = new HashSet <string>();

                foreach (string stringBankPath in stringBanks)
                {
                    FMOD.Studio.Bank stringBank;
                    EditorUtils.CheckResult(EditorUtils.System.loadBankFile(stringBankPath, FMOD.Studio.LOAD_BANK_FLAGS.NORMAL, out stringBank));

                    if (!stringBank.isValid())
                    {
                        ClearCache();
                        return(string.Format("{0} is not a valid bank.", stringBankPath));
                    }

                    loadedStringsBanks.Add(stringBank);

                    FileInfo stringBankFileInfo = new FileInfo(stringBankPath);

                    string masterBankFileName = Path.GetFileName(stringBankPath).Replace(StringBankExtension, BankExtension);
                    masterBankFileNames.Add(masterBankFileName);

                    EditorBankRef stringsBankRef = eventCache.StringsBanks.Find(x => RuntimeUtils.GetCommonPlatformPath(stringBankPath) == x.Path);

                    if (stringsBankRef == null)
                    {
                        stringsBankRef           = ScriptableObject.CreateInstance <EditorBankRef>();
                        stringsBankRef.FileSizes = new List <EditorBankRef.NameValuePair>();
                        AssetDatabase.AddObjectToAsset(stringsBankRef, eventCache);
                        AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(stringsBankRef));
                        eventCache.EditorBanks.Add(stringsBankRef);
                        eventCache.StringsBanks.Add(stringsBankRef);
                    }

                    stringsBankRef.SetPath(stringBankPath, defaultBankFolder);
                    string studioPath;
                    stringBank.getPath(out studioPath);
                    stringsBankRef.SetStudioPath(studioPath);
                    stringsBankRef.LastModified = stringBankFileInfo.LastWriteTime;
                    stringsBankRef.Exists       = true;
                    stringsBankRef.FileSizes.Clear();

                    if (Settings.Instance.HasPlatforms)
                    {
                        for (int i = 0; i < bankPlatforms.Length; i++)
                        {
                            stringsBankRef.FileSizes.Add(new EditorBankRef.NameValuePair(bankPlatforms[i], stringBankFileInfo.Length));
                        }
                    }
                    else
                    {
                        stringsBankRef.FileSizes.Add(new EditorBankRef.NameValuePair("", stringBankFileInfo.Length));
                    }
                }

                eventCache.EditorParameters.ForEach((x) => x.Exists = false);
                foreach (string bankFileName in bankFileNames)
                {
                    EditorBankRef bankRef = eventCache.EditorBanks.Find((x) => RuntimeUtils.GetCommonPlatformPath(bankFileName) == x.Path);

                    // New bank we've never seen before
                    if (bankRef == null)
                    {
                        bankRef = ScriptableObject.CreateInstance <EditorBankRef>();
                        AssetDatabase.AddObjectToAsset(bankRef, eventCache);
                        AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(bankRef));

                        bankRef.SetPath(bankFileName, defaultBankFolder);
                        bankRef.LastModified = DateTime.MinValue;
                        bankRef.FileSizes    = new List <EditorBankRef.NameValuePair>();

                        eventCache.EditorBanks.Add(bankRef);
                    }

                    bankRef.Exists = true;

                    FileInfo bankFileInfo = new FileInfo(bankFileName);

                    // Timestamp check - if it doesn't match update events from that bank
                    if (bankRef.LastModified != bankFileInfo.LastWriteTime)
                    {
                        bankRef.LastModified = bankFileInfo.LastWriteTime;
                        UpdateCacheBank(bankRef);
                    }

                    // Update file sizes
                    bankRef.FileSizes.Clear();
                    if (Settings.Instance.HasPlatforms)
                    {
                        for (int i = 0; i < bankPlatforms.Length; i++)
                        {
                            string platformBankPath = RuntimeUtils.GetCommonPlatformPath(Path.Combine(bankFolders[i], bankFileName));
                            var    fileInfo         = new FileInfo(platformBankPath);
                            if (fileInfo.Exists)
                            {
                                bankRef.FileSizes.Add(new EditorBankRef.NameValuePair(bankPlatforms[i], fileInfo.Length));
                            }
                        }
                    }
                    else
                    {
                        string platformBankPath = RuntimeUtils.GetCommonPlatformPath(Path.Combine(Settings.Instance.SourceBankPath, bankFileName));
                        var    fileInfo         = new FileInfo(platformBankPath);
                        if (fileInfo.Exists)
                        {
                            bankRef.FileSizes.Add(new EditorBankRef.NameValuePair("", fileInfo.Length));
                        }
                    }

                    if (masterBankFileNames.Contains(bankFileInfo.Name))
                    {
                        if (!eventCache.MasterBanks.Exists(x => RuntimeUtils.GetCommonPlatformPath(bankFileName) == x.Path))
                        {
                            eventCache.MasterBanks.Add(bankRef);
                        }
                    }
                }

                // Remove any stale entries from bank, event and parameter lists
                eventCache.EditorBanks.FindAll((x) => !x.Exists).ForEach(RemoveCacheBank);
                eventCache.EditorBanks.RemoveAll((x) => !x.Exists);
                eventCache.EditorEvents.RemoveAll((x) => x.Banks.Count == 0);
                eventCache.EditorParameters.RemoveAll((x) => !x.Exists);
                eventCache.MasterBanks.RemoveAll((x) => !x.Exists);
                eventCache.StringsBanks.RemoveAll((x) => !x.Exists);
            }
            finally
            {
                // Unload the strings banks
                loadedStringsBanks.ForEach(x => x.unload());
                AssetDatabase.StopAssetEditing();
                Debug.Log("FMOD: Cache updated.");
            }

            return(null);
        }
Beispiel #10
0
        public override void OnInspectorGUI()
        {
            Settings settings = target as Settings;

            DrawLinks();

            EditorGUI.BeginChangeCheck();

            hasBankSourceChanged = false;
            bool hasBankTargetChanged = false;

            GUIStyle style = new GUIStyle(GUI.skin.label);

            style.richText = true;

            GUI.skin.FindStyle("HelpBox").richText = true;

            SourceType sourceType = settings.HasSourceProject ? SourceType.Project : (settings.HasPlatforms ? SourceType.Multi : SourceType.Single);

            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.BeginVertical();
            sourceType = GUILayout.Toggle(sourceType == SourceType.Project, "Project", "Button") ? 0 : sourceType;
            sourceType = GUILayout.Toggle(sourceType == SourceType.Single, "Single Platform Build", "Button") ? SourceType.Single : sourceType;
            sourceType = GUILayout.Toggle(sourceType == SourceType.Multi, "Multiple Platform Build", "Button") ? SourceType.Multi : sourceType;
            EditorGUILayout.EndVertical();
            EditorGUILayout.BeginVertical();

            EditorGUILayout.HelpBox(
                "<size=11>Select the way you wish to connect Unity to the FMOD Studio content:\n" +
                "<b>• Project</b>\t\tIf you have the complete FMOD Studio project avaliable\n" +
                "<b>• Single Platform</b>\tIf you have only the contents of the <i>Build</i> folder for a single platform\n" +
                "<b>• Multiple Platforms</b>\tIf you have only the contents of the <i>Build</i> folder for multiple platforms, each platform in its own sub directory\n" +
                "</size>"
                , MessageType.Info, true);
            EditorGUILayout.EndVertical();
            EditorGUILayout.EndHorizontal();
            EditorGUILayout.Space();

            if (sourceType == SourceType.Project)
            {
                EditorGUILayout.BeginHorizontal();
                string oldPath = settings.SourceProjectPath;
                EditorGUILayout.PrefixLabel("Studio Project Path", GUI.skin.textField, style);

                EditorGUI.BeginChangeCheck();
                string newPath = EditorGUILayout.TextField(GUIContent.none, settings.SourceProjectPath);
                if (EditorGUI.EndChangeCheck())
                {
                    if (newPath.EndsWith(".fspro"))
                    {
                        settings.SourceProjectPath = newPath;
                    }
                }

                if (GUILayout.Button("Browse", GUILayout.ExpandWidth(false)))
                {
                    GUI.FocusControl(null);
                    string path = EditorUtility.OpenFilePanel("Locate Studio Project", oldPath, "fspro");
                    if (!string.IsNullOrEmpty(path))
                    {
                        settings.SourceProjectPath = MakePathRelative(path);
                        Repaint();
                    }
                }
                EditorGUILayout.EndHorizontal();

                // Cache in settings for runtime access in play-in-editor mode
                string bankPath = EditorUtils.GetBankDirectory();
                settings.SourceBankPath   = bankPath;
                settings.HasPlatforms     = true;
                settings.HasSourceProject = true;

                // First time project path is set or changes, copy to streaming assets
                if (settings.SourceProjectPath != oldPath)
                {
                    hasBankSourceChanged = true;
                }
            }
            else if (sourceType == SourceType.Single || sourceType == SourceType.Multi)
            {
                EditorGUILayout.BeginHorizontal();
                string oldPath = settings.SourceBankPath;
                EditorGUILayout.PrefixLabel("Build Path", GUI.skin.textField, style);

                EditorGUI.BeginChangeCheck();
                string tempPath = EditorGUILayout.TextField(GUIContent.none, settings.SourceBankPath);
                if (EditorGUI.EndChangeCheck())
                {
                    settings.SourceBankPath = tempPath;
                }

                if (GUILayout.Button("Browse", GUILayout.ExpandWidth(false)))
                {
                    GUI.FocusControl(null);
                    string newPath = EditorUtility.OpenFolderPanel("Locate Build Folder", oldPath, null);
                    if (!string.IsNullOrEmpty(newPath))
                    {
                        settings.SourceBankPath = MakePathRelative(newPath);
                        Repaint();
                    }
                }
                EditorGUILayout.EndHorizontal();

                settings.HasPlatforms     = (sourceType == SourceType.Multi);
                settings.HasSourceProject = false;

                // First time project path is set or changes, copy to streaming assets
                if (settings.SourceBankPath != oldPath)
                {
                    hasBankSourceChanged = true;
                }
            }

            bool   validBanks;
            string failReason;

            EditorUtils.ValidateSource(out validBanks, out failReason);
            if (!validBanks)
            {
                failReason += "\n\nFor detailed setup instructions, please see the getting started guide linked above.";
                EditorGUILayout.HelpBox(failReason, MessageType.Error, true);
                if (EditorGUI.EndChangeCheck())
                {
                    EditorUtility.SetDirty(settings);
                }
                return;
            }

            ImportType importType = (ImportType)EditorGUILayout.EnumPopup("Import Type", settings.ImportType);

            if (importType != settings.ImportType)
            {
                hasBankTargetChanged = true;
                settings.ImportType  = importType;

                bool deleteBanks = EditorUtility.DisplayDialog(
                    "FMOD Bank Import Type Changed", "Do you want to delete the " + settings.ImportType.ToString() + " banks in " + settings.TargetPath,
                    "Yes", "No");
                if (deleteBanks)
                {
                    // Delete the old banks
                    EventManager.removeBanks = true;
                    EventManager.RefreshBanks();
                }
            }

            // ----- Asset Sub Directory -------------
            {
                GUI.SetNextControlName("targetSubFolder");
                targetSubFolder = settings.ImportType == ImportType.AssetBundle
                    ? EditorGUILayout.TextField("FMOD Asset Sub Folder", string.IsNullOrEmpty(targetSubFolder) ? settings.TargetAssetPath : targetSubFolder)
                    : EditorGUILayout.TextField("FMOD Bank Sub Folder", string.IsNullOrEmpty(targetSubFolder) ? settings.TargetSubFolder : targetSubFolder);
                if (GUI.GetNameOfFocusedControl() == "targetSubFolder")
                {
                    focused = true;
                    if (Event.current.isKey)
                    {
                        switch (Event.current.keyCode)
                        {
                        case KeyCode.Return:
                        case KeyCode.KeypadEnter:
                            if (settings.TargetSubFolder != targetSubFolder)
                            {
                                EventManager.RemoveBanks(settings.TargetPath);
                                settings.TargetSubFolder = targetSubFolder;
                                hasBankTargetChanged     = true;
                            }
                            targetSubFolder = "";
                            break;
                        }
                    }
                }
                else if (focused)
                {
                    if (settings.TargetPath != targetSubFolder)
                    {
                        EventManager.RemoveBanks(settings.TargetPath);
                        settings.TargetSubFolder = targetSubFolder;
                        hasBankTargetChanged     = true;
                    }
                    targetSubFolder = "";
                }
            }

            // ----- Logging -----------------
            EditorGUILayout.Separator();
            EditorGUILayout.LabelField("<b>Logging</b>", style);
            EditorGUI.indentLevel++;
            settings.LoggingLevel = (FMOD.DEBUG_FLAGS)EditorGUILayout.EnumPopup("Logging Level", settings.LoggingLevel);
            EditorGUI.indentLevel--;

            // ----- Loading -----------------
            EditorGUI.BeginDisabledGroup(settings.ImportType == ImportType.AssetBundle);
            EditorGUILayout.Separator();
            EditorGUILayout.LabelField("<b>Initialization</b>", style);
            EditorGUI.indentLevel++;

            settings.EnableMemoryTracking = EditorGUILayout.Toggle("Enable Memory Tracking", settings.EnableMemoryTracking);

            settings.BankLoadType = (BankLoadType)EditorGUILayout.EnumPopup("Load Banks", settings.BankLoadType);
            switch (settings.BankLoadType)
            {
            case BankLoadType.All:
                break;

            case BankLoadType.Specified:
                settings.AutomaticEventLoading = false;
                Texture upArrowTexture   = EditorGUIUtility.Load("FMOD/ArrowUp.png") as Texture;
                Texture downArrowTexture = EditorGUIUtility.Load("FMOD/ArrowDown.png") as Texture;
                bankFoldOutState = EditorGUILayout.Foldout(bankFoldOutState, "Specified Banks", true);
                if (bankFoldOutState)
                {
                    for (int i = 0; i < settings.BanksToLoad.Count; i++)
                    {
                        EditorGUILayout.BeginHorizontal();
                        EditorGUI.indentLevel++;

                        var bankName = settings.BanksToLoad[i];
                        EditorGUILayout.TextField(bankName.Replace(".bank", ""));

                        if (GUILayout.Button(upArrowTexture, GUILayout.ExpandWidth(false)))
                        {
                            if (i > 0)
                            {
                                var temp = settings.BanksToLoad[i];
                                settings.BanksToLoad[i]     = settings.BanksToLoad[i - 1];
                                settings.BanksToLoad[i - 1] = temp;
                            }
                            continue;
                        }
                        if (GUILayout.Button(downArrowTexture, GUILayout.ExpandWidth(false)))
                        {
                            if (i < settings.BanksToLoad.Count - 1)
                            {
                                var temp = settings.BanksToLoad[i];
                                settings.BanksToLoad[i]     = settings.BanksToLoad[i + 1];
                                settings.BanksToLoad[i + 1] = temp;
                            }
                            continue;
                        }

                        if (GUILayout.Button("Browse", GUILayout.ExpandWidth(false)))
                        {
                            GUI.FocusControl(null);
                            string path = EditorUtility.OpenFilePanel("Locate Bank", settings.TargetPath, "bank");
                            if (!string.IsNullOrEmpty(path))
                            {
                                path = RuntimeUtils.GetCommonPlatformPath(path);
                                settings.BanksToLoad[i] = path.Replace(settings.TargetPath, "");
                                Repaint();
                            }
                        }
                        if (GUILayout.Button("Remove", GUILayout.ExpandWidth(false)))
                        {
                            Settings.Instance.BanksToLoad.RemoveAt(i);
                            continue;
                        }
                        EditorGUILayout.EndHorizontal();
                        EditorGUI.indentLevel--;
                    }

                    GUILayout.BeginHorizontal();
                    GUILayout.Space(30);
                    if (GUILayout.Button("Add Bank", GUILayout.ExpandWidth(false)))
                    {
                        settings.BanksToLoad.Add("");
                    }
                    if (GUILayout.Button("Add All Banks", GUILayout.ExpandWidth(false)))
                    {
                        string sourceDir;

                        if (settings.HasSourceProject)
                        {
                            sourceDir = string.Format("{0}/{1}/", settings.SourceBankPath, settings.CurrentEditorPlatform.BuildDirectory);
                        }
                        else
                        {
                            sourceDir = settings.SourceBankPath;
                        }

                        sourceDir = RuntimeUtils.GetCommonPlatformPath(sourceDir);

                        var banksFound = new List <string>(Directory.GetFiles(sourceDir, "*.bank", SearchOption.AllDirectories));
                        for (int i = 0; i < banksFound.Count; i++)
                        {
                            string bankShortName = RuntimeUtils.GetCommonPlatformPath(banksFound[i]).Replace(sourceDir, "");
                            if (!settings.BanksToLoad.Contains(bankShortName))
                            {
                                settings.BanksToLoad.Add(bankShortName);
                            }
                        }

                        Repaint();
                    }
                    if (GUILayout.Button("Clear", GUILayout.ExpandWidth(false)))
                    {
                        settings.BanksToLoad.Clear();
                    }
                    GUILayout.EndHorizontal();
                }
                break;

            case BankLoadType.None:
                settings.AutomaticEventLoading = false;
                break;

            default:
                break;
            }

            EditorGUI.BeginDisabledGroup(settings.BankLoadType == BankLoadType.None);
            settings.AutomaticSampleLoading = EditorGUILayout.Toggle("Load Bank Sample Data", settings.AutomaticSampleLoading);
            EditorGUI.EndDisabledGroup();

            settings.EncryptionKey = EditorGUILayout.TextField("Bank Encryption Key", settings.EncryptionKey);

            EditorGUI.indentLevel--;
            EditorGUI.EndDisabledGroup();

            // ----- PIE ----------------------------------------------
            EditorGUILayout.Separator();
            DisplayPlatform(settings.PlayInEditorPlatform);

            // ----- Default ----------------------------------------------
            EditorGUILayout.Separator();
            DisplayPlatform(settings.DefaultPlatform);

            // Top-level platforms
            EditorGUILayout.Separator();
            DisplayPlatformHeader();

            EditorGUI.indentLevel++;
            foreach (Platform platform in settings.DefaultPlatform.Children)
            {
                DisplayPlatform(platform);
            }
            EditorGUI.indentLevel--;

            if (EditorGUI.EndChangeCheck())
            {
                EditorUtility.SetDirty(settings);
            }

            if (hasBankSourceChanged)
            {
                EventManager.RefreshBanks();
            }
            if (hasBankTargetChanged)
            {
                EventManager.RefreshBanks();
            }
            if (pendingPlatformDelete != null)
            {
                settings.RemovePlatformProperties(pendingPlatformDelete);

                ParentCandidates.Remove(pendingPlatformDelete);

                if (!(pendingPlatformDelete is PlatformGroup))
                {
                    MissingPlatforms.Add(pendingPlatformDelete);
                    MissingPlatforms.Sort(CompareDisplayNames);
                }

                pendingPlatformDelete = null;
            }
        }
        public void PlayInstance()
        {
            if (!instance.isValid())
            {
                instance.clearHandle();
            }

            // Let previous oneshot instances play out
            if (isOneshot && instance.isValid())
            {
                instance.release();
                instance.clearHandle();
            }

            bool is3D;

            eventDescription.is3D(out is3D);

            if (!instance.isValid())
            {
                eventDescription.createInstance(out instance);

                // Only want to update if we need to set 3D attributes
                if (is3D)
                {
                    var rigidBody   = GetComponent <Rigidbody>();
                    var rigidBody2D = GetComponent <Rigidbody2D>();
                    var transform   = GetComponent <Transform>();
                    if (rigidBody)
                    {
                        instance.set3DAttributes(RuntimeUtils.To3DAttributes(gameObject, rigidBody));
                        RuntimeManager.AttachInstanceToGameObject(instance, transform, rigidBody);
                    }
                    else
                    {
                        instance.set3DAttributes(RuntimeUtils.To3DAttributes(gameObject, rigidBody2D));
                        RuntimeManager.AttachInstanceToGameObject(instance, transform, rigidBody2D);
                    }
                }
            }

            foreach (var param in Params)
            {
                instance.setParameterByID(param.ID, param.Value);
            }

            foreach (var cachedParam in cachedParams)
            {
                instance.setParameterByID(cachedParam.ID, cachedParam.Value);
            }

            if (is3D && OverrideAttenuation)
            {
                instance.setProperty(FMOD.Studio.EVENT_PROPERTY.MINIMUM_DISTANCE, OverrideMinDistance);
                instance.setProperty(FMOD.Studio.EVENT_PROPERTY.MAXIMUM_DISTANCE, OverrideMaxDistance);
            }

            instance.start();

            hasTriggered = true;
        }
Beispiel #12
0
        private RESULT Initialize()
        {
            initializedSuccessfully = false;
            RESULT   rESULT   = RESULT.OK;
            RESULT   rESULT2  = RESULT.OK;
            Settings settings = Settings.Instance;

            fmodPlatform = RuntimeUtils.GetCurrentPlatform();
            int         sampleRate      = settings.GetSampleRate(fmodPlatform);
            int         num             = Math.Min(settings.GetRealChannels(fmodPlatform), 256);
            int         virtualChannels = settings.GetVirtualChannels(fmodPlatform);
            SPEAKERMODE speakerMode     = (SPEAKERMODE)settings.GetSpeakerMode(fmodPlatform);
            OUTPUTTYPE  output          = OUTPUTTYPE.AUTODETECT;

            FMOD.ADVANCEDSETTINGS settings2 = default(FMOD.ADVANCEDSETTINGS);
            settings2.randomSeed      = (uint)DateTime.Now.Ticks;
            settings2.maxVorbisCodecs = num;
            FMOD.Studio.INITFLAGS iNITFLAGS = FMOD.Studio.INITFLAGS.DEFERRED_CALLBACKS;
            if (settings.IsLiveUpdateEnabled(fmodPlatform))
            {
                iNITFLAGS |= FMOD.Studio.INITFLAGS.LIVEUPDATE;
            }
            while (true)
            {
                rESULT = FMOD.Studio.System.create(out studioSystem);
                CheckInitResult(rESULT, "FMOD.Studio.System.create");
                rESULT = studioSystem.getLowLevelSystem(out lowlevelSystem);
                CheckInitResult(rESULT, "FMOD.Studio.System.getLowLevelSystem");
                rESULT = lowlevelSystem.setOutput(output);
                CheckInitResult(rESULT, "FMOD.System.setOutput");
                rESULT = lowlevelSystem.setSoftwareChannels(num);
                CheckInitResult(rESULT, "FMOD.System.setSoftwareChannels");
                rESULT = lowlevelSystem.setSoftwareFormat(sampleRate, speakerMode, 0);
                CheckInitResult(rESULT, "FMOD.System.setSoftwareFormat");
                rESULT = lowlevelSystem.setAdvancedSettings(ref settings2);
                CheckInitResult(rESULT, "FMOD.System.setAdvancedSettings");
                rESULT = studioSystem.initialize(virtualChannels, iNITFLAGS, FMOD.INITFLAGS.NORMAL, IntPtr.Zero);
                if (rESULT != 0 && rESULT2 == RESULT.OK)
                {
                    rESULT2 = rESULT;
                    output  = OUTPUTTYPE.NOSOUND;
                    Debug.LogWarningFormat("FMOD Studio: Studio::System::initialize returned {0}, defaulting to no-sound mode.", rESULT.ToString());
                }
                else
                {
                    CheckInitResult(rESULT, "Studio::System::initialize");
                    if ((iNITFLAGS & FMOD.Studio.INITFLAGS.LIVEUPDATE) == FMOD.Studio.INITFLAGS.NORMAL)
                    {
                        break;
                    }
                    studioSystem.flushCommands();
                    rESULT = studioSystem.update();
                    if (rESULT != RESULT.ERR_NET_SOCKET_ERROR)
                    {
                        break;
                    }
                    iNITFLAGS = (FMOD.Studio.INITFLAGS)((int)iNITFLAGS & -2);
                    Debug.LogWarning("FMOD Studio: Cannot open network port for Live Update (in-use), restarting with Live Update disabled.");
                    rESULT = studioSystem.release();
                    CheckInitResult(rESULT, "FMOD.Studio.System.Release");
                }
            }
            LoadPlugins(settings);
            LoadBanks(settings);
            initializedSuccessfully = (rESULT == RESULT.OK);
            return(rESULT2);
        }
Beispiel #13
0
        public static void CopyToStreamingAssets()
        {
            if (string.IsNullOrEmpty(Settings.Instance.SourceBankPathFull))
            {
                return;
            }

            FMODPlatform platform = RuntimeUtils.GetEditorFMODPlatform();

            if (platform == FMODPlatform.None)
            {
                UnityEngine.Debug.LogWarning(string.Format("FMOD Studio: copy banks for platform {0} : Unsupported platform", EditorUserBuildSettings.activeBuildTarget.ToString()));
                return;
            }

            string bankTargetFolder =
                Settings.Instance.ImportType == ImportType.StreamingAssets
                ? Application.dataPath + "/StreamingAssets"
                : Application.dataPath + (string.IsNullOrEmpty(Settings.Instance.TargetAssetPath) ? "" : '/' + Settings.Instance.TargetAssetPath);

            bankTargetFolder = RuntimeUtils.GetCommonPlatformPath(bankTargetFolder);
            Directory.CreateDirectory(bankTargetFolder);

            string bankTargetExension =
                Settings.Instance.ImportType == ImportType.StreamingAssets
                ? "bank"
                : "bytes";

            string bankSourceFolder =
                Settings.Instance.HasPlatforms
                ? Settings.Instance.SourceBankPathFull + '/' + Settings.Instance.GetBankPlatform(platform)
                : Settings.Instance.SourceBankPathFull;

            bankSourceFolder = RuntimeUtils.GetCommonPlatformPath(bankSourceFolder);

            if (Path.GetFullPath(bankTargetFolder).TrimEnd('/').ToUpperInvariant() ==
                Path.GetFullPath(bankSourceFolder).TrimEnd('/').ToUpperInvariant())
            {
                return;
            }

            bool madeChanges = false;

            try
            {
                // Clean out any stale .bank files
                string[]      currentBankFiles = Directory.GetFiles(bankTargetFolder, "*." + bankTargetExension, SearchOption.AllDirectories);
                List <string> directories      = new List <string>();
                foreach (var bankFileName in currentBankFiles)
                {
                    var targetShortName = RuntimeUtils.GetCommonPlatformPath(bankFileName).Replace(bankTargetFolder + '/', "");
                    if (!eventCache.EditorBanks.Exists((x) => targetShortName == x.Name + "." + bankTargetExension))
                    {
                        File.Delete(bankFileName);
                        madeChanges = true;
                    }
                    directories.Add(RuntimeUtils.GetCommonPlatformPath(Path.GetDirectoryName(bankFileName)));
                }
                if (madeChanges)
                {
                    AssetDatabase.Refresh();
                    foreach (var dir in directories)
                    {
                        if (Directory.Exists(dir) && Directory.GetFiles(dir).Length <= 0)
                        {
                            Directory.Delete(dir);
                        }
                    }
                }

                // Copy over any files that don't match timestamp or size or don't exist
                foreach (var bankRef in eventCache.EditorBanks)
                {
                    var    dirName = RuntimeUtils.GetCommonPlatformPath(Path.GetDirectoryName(bankRef.Path));
                    string subDir  = dirName.Replace(bankSourceFolder, "");
                    bankRef.SubDir = subDir.TrimStart('/');

                    string sourcePath = bankSourceFolder + '/' + bankRef.Name + ".bank";
                    string targetPath = bankTargetFolder + '/' + bankRef.Name + "." + bankTargetExension;

                    FileInfo sourceInfo = new FileInfo(sourcePath);
                    FileInfo targetInfo = new FileInfo(targetPath);

                    if (!targetInfo.Exists ||
                        sourceInfo.Length != targetInfo.Length ||
                        sourceInfo.LastWriteTime != targetInfo.LastWriteTime)
                    {
                        if (!targetInfo.Directory.Exists)
                        {
                            targetInfo.Directory.Create();
                        }
                        else if (targetInfo.Exists)
                        {
                            targetInfo.IsReadOnly = false;
                        }
                        File.Copy(sourcePath, targetPath, true);
                        targetInfo               = new FileInfo(targetPath);
                        targetInfo.IsReadOnly    = false;
                        targetInfo.LastWriteTime = sourceInfo.LastWriteTime;

                        madeChanges = true;
                    }
                }
            }
            catch (Exception exception)
            {
                UnityEngine.Debug.LogError(string.Format("FMOD Studio: copy banks for platform {0} : copying banks from {1} to {2}", platform.ToString(), bankSourceFolder, bankTargetFolder));
                UnityEngine.Debug.LogException(exception);
                return;
            }

            if (madeChanges)
            {
                AssetDatabase.Refresh();
                UnityEngine.Debug.Log(string.Format("FMOD Studio: copy banks for platform {0} : copying banks from {1} to {2} succeeded", platform.ToString(), bankSourceFolder, bankTargetFolder));
            }
        }
Beispiel #14
0
        static public void UpdateCache()
        {
            // Deserialize the cache from the unity resources
            if (eventCache == null)
            {
                eventCache = AssetDatabase.LoadAssetAtPath(CacheAssetFullName, typeof(EventCache)) as EventCache;
                if (eventCache == null || eventCache.cacheVersion != EventCache.CurrentCacheVersion)
                {
                    UnityEngine.Debug.Log("FMOD Studio: Cannot find serialized event cache or cache in old format, creating new instance");
                    eventCache = ScriptableObject.CreateInstance <EventCache>();
                    eventCache.cacheVersion = EventCache.CurrentCacheVersion;

                    AssetDatabase.CreateAsset(eventCache, CacheAssetFullName);
                }
            }

            if (EditorUtils.GetBankDirectory() == null)
            {
                ClearCache();
                return;
            }

            string defaultBankFolder = null;

            if (!Settings.Instance.HasPlatforms)
            {
                defaultBankFolder = EditorUtils.GetBankDirectory();
            }
            else
            {
                FMODPlatform platform = RuntimeUtils.GetEditorFMODPlatform();
                if (platform == FMODPlatform.None)
                {
                    platform = FMODPlatform.PlayInEditor;
                }

                defaultBankFolder = Path.Combine(EditorUtils.GetBankDirectory(), Settings.Instance.GetBankPlatform(platform));
            }

            string[] bankPlatforms = EditorUtils.GetBankPlatforms();
            string[] bankFolders   = new string[bankPlatforms.Length];
            for (int i = 0; i < bankPlatforms.Length; i++)
            {
                bankFolders[i] = Path.Combine(EditorUtils.GetBankDirectory(), bankPlatforms[i]);
            }

            List <String> stringBanks = new List <string>(0);

            try
            {
                var files = Directory.GetFiles(defaultBankFolder, "*." + StringBankExtension);
                stringBanks = new List <string>(files);
            }
            catch
            {
            }

            // Strip out OSX resource-fork files that appear on FAT32
            stringBanks.RemoveAll((x) => Path.GetFileName(x).StartsWith("._"));

            if (stringBanks.Count == 0)
            {
                bool wasValid = eventCache.StringsBankWriteTime != DateTime.MinValue;
                ClearCache();
                if (wasValid)
                {
                    UnityEngine.Debug.LogError(String.Format("FMOD Studio: Directory {0} doesn't contain any banks. Build from the tool or check the path in the settings", defaultBankFolder));
                }
                return;
            }

            // If we have multiple .strings.bank files find the most recent
            stringBanks.Sort((a, b) => File.GetLastWriteTime(b).CompareTo(File.GetLastWriteTime(a)));
            string stringBankPath = stringBanks[0];

            // Use the string bank timestamp as a marker for the most recent build of any bank because it gets exported every time
            if (File.GetLastWriteTime(stringBankPath) == eventCache.StringsBankWriteTime)
            {
                countdownTimer = CountdownTimerReset;
                return;
            }

            if (EditorUtils.IsFileOpenByStudio(stringBankPath))
            {
                countdownTimer = CountdownTimerReset;
                return;
            }


            FMOD.Studio.Bank stringBank;
            EditorUtils.CheckResult(EditorUtils.System.loadBankFile(stringBankPath, FMOD.Studio.LOAD_BANK_FLAGS.NORMAL, out stringBank));
            if (!stringBank.isValid())
            {
                countdownTimer = CountdownTimerReset;
                return;
            }

            // Iterate every string in the strings bank and look for any that identify banks
            int stringCount;

            stringBank.getStringCount(out stringCount);
            List <string> bankFileNames = new List <string>();

            for (int stringIndex = 0; stringIndex < stringCount; stringIndex++)
            {
                string currentString;
                Guid   currentGuid;
                stringBank.getStringInfo(stringIndex, out currentGuid, out currentString);
                const string BankPrefix       = "bank:/";
                int          BankPrefixLength = BankPrefix.Length;
                if (currentString.StartsWith(BankPrefix))
                {
                    string bankFileName = currentString.Substring(BankPrefixLength) + "." + BankExtension;
                    if (!bankFileName.Contains(StringBankExtension)) // filter out the strings bank
                    {
                        bankFileNames.Add(bankFileName);
                    }
                }
            }

            // Unload the strings bank
            stringBank.unload();

            // Check if any of the files are still being written by studio
            foreach (string bankFileName in bankFileNames)
            {
                string bankPath = Path.Combine(defaultBankFolder, bankFileName);

                if (!File.Exists(bankPath))
                {
                    // TODO: this is meant to catch the case where we're in the middle of a build and a bank is being built
                    // for the first time. But it also stops someone trying to import an incomplete set of banks without any error message.
                    countdownTimer = CountdownTimerReset;
                    return;
                }

                EditorBankRef bankRef = eventCache.EditorBanks.Find((x) => bankPath == x.Path);
                if (bankRef == null)
                {
                    if (EditorUtils.IsFileOpenByStudio(bankPath))
                    {
                        countdownTimer = CountdownTimerReset;
                        return;
                    }
                    continue;
                }

                if (bankRef.LastModified != File.GetLastWriteTime(bankPath))
                {
                    if (EditorUtils.IsFileOpenByStudio(bankPath))
                    {
                        countdownTimer = CountdownTimerReset;
                        return;
                    }
                }
            }

            // Count down the timer in case we catch studio in-between updating two files.
            if (countdownTimer-- > 0)
            {
                return;
            }

            // All files are finished being modified by studio so update the cache

            // Stop editor preview so no stale data being held
            EditorUtils.PreviewStop();

            // Reload the strings bank
            EditorUtils.CheckResult(EditorUtils.System.loadBankFile(stringBankPath, FMOD.Studio.LOAD_BANK_FLAGS.NORMAL, out stringBank));
            if (!stringBank.isValid())
            {
                ClearCache();
                return;
            }
            FileInfo stringBankFileInfo = new FileInfo(stringBankPath);

            eventCache.StringsBankWriteTime = stringBankFileInfo.LastWriteTime;
            string masterBankFileName = Path.GetFileName(stringBankPath).Replace(StringBankExtension, BankExtension);

            AssetDatabase.StartAssetEditing();

            if (eventCache.StringsBankRef == null)
            {
                eventCache.StringsBankRef           = ScriptableObject.CreateInstance <EditorBankRef>();
                eventCache.StringsBankRef.FileSizes = new List <EditorBankRef.NameValuePair>();
                eventCache.EditorBanks.Add(eventCache.StringsBankRef);
                AssetDatabase.AddObjectToAsset(eventCache.StringsBankRef, eventCache);
                AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(eventCache.StringsBankRef));
            }
            eventCache.StringsBankRef.Path         = stringBankPath;
            eventCache.StringsBankRef.LastModified = eventCache.StringsBankWriteTime;
            eventCache.StringsBankRef.FileSizes.Clear();
            if (Settings.Instance.HasPlatforms)
            {
                for (int i = 0; i < bankPlatforms.Length; i++)
                {
                    eventCache.StringsBankRef.FileSizes.Add(new EditorBankRef.NameValuePair(bankPlatforms[i], stringBankFileInfo.Length));
                }
            }
            else
            {
                eventCache.StringsBankRef.FileSizes.Add(new EditorBankRef.NameValuePair("", stringBankFileInfo.Length));
            }

            eventCache.EditorBanks.ForEach((x) => x.Exists = false);
            eventCache.StringsBankRef.Exists = true;

            string[] folderContents = Directory.GetFiles(defaultBankFolder);

            foreach (string bankFileName in bankFileNames)
            {
                // Get the true file path, can't trust the character case we got from the string bank
                string bankPath = ArrayUtility.Find(folderContents, x => (string.Equals(bankFileName, Path.GetFileName(x), StringComparison.CurrentCultureIgnoreCase)));

                FileInfo      bankFileInfo = new FileInfo(bankPath);
                EditorBankRef bankRef      = eventCache.EditorBanks.Find((x) => bankFileInfo.FullName == x.Path);

                // New bank we've never seen before
                if (bankRef == null)
                {
                    bankRef = ScriptableObject.CreateInstance <EditorBankRef>();
                    AssetDatabase.AddObjectToAsset(bankRef, eventCache);
                    AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(bankRef));
                    bankRef.Path         = bankFileInfo.FullName;
                    bankRef.LastModified = DateTime.MinValue;
                    bankRef.FileSizes    = new List <EditorBankRef.NameValuePair>();
                    eventCache.EditorBanks.Add(bankRef);
                }

                bankRef.Exists = true;

                // Timestamp check - if it doesn't match update events from that bank
                if (bankRef.LastModified != bankFileInfo.LastWriteTime)
                {
                    bankRef.LastModified = bankFileInfo.LastWriteTime;
                    UpdateCacheBank(bankRef);
                }

                // Update file sizes
                bankRef.FileSizes.Clear();
                if (Settings.Instance.HasPlatforms)
                {
                    for (int i = 0; i < bankPlatforms.Length; i++)
                    {
                        string platformBankPath = Path.Combine(bankFolders[i], bankFileName);
                        var    fileInfo         = new FileInfo(platformBankPath);
                        if (fileInfo.Exists)
                        {
                            bankRef.FileSizes.Add(new EditorBankRef.NameValuePair(bankPlatforms[i], fileInfo.Length));
                        }
                    }
                }
                else
                {
                    string platformBankPath = Path.Combine(EditorUtils.GetBankDirectory(), bankFileName);
                    var    fileInfo         = new FileInfo(platformBankPath);
                    if (fileInfo.Exists)
                    {
                        bankRef.FileSizes.Add(new EditorBankRef.NameValuePair("", fileInfo.Length));
                    }
                }

                if (bankFileInfo.Name == masterBankFileName)
                {
                    eventCache.MasterBankRef = bankRef;
                }
            }


            // Unload the strings bank
            stringBank.unload();

            // Remove any stale entries from bank and event lists
            eventCache.EditorBanks.FindAll((x) => !x.Exists).ForEach(RemoveCacheBank);
            eventCache.EditorBanks.RemoveAll((x) => !x.Exists);
            eventCache.EditorEvents.RemoveAll((x) => x.Banks.Count == 0);

            OnCacheChange();
            AssetDatabase.StopAssetEditing();
        }
        static public void UpdateCache()
        {
            // Deserialize the cache from the unity resources
            if (eventCache == null)
            {
                eventCache = AssetDatabase.LoadAssetAtPath(CacheAssetFullName, typeof(EventCache)) as EventCache;
                if (eventCache == null || eventCache.cacheVersion != EventCache.CurrentCacheVersion)
                {
                    UnityEngine.Debug.Log("FMOD Studio: Cannot find serialized event cache or cache in old format, creating new instance");
                    eventCache = ScriptableObject.CreateInstance <EventCache>();
                    eventCache.cacheVersion = EventCache.CurrentCacheVersion;
                    if (!Directory.Exists("Assets/Plugins/FMOD/Resources"))
                    {
                        AssetDatabase.CreateFolder("Assets/Plugins/FMOD", "Resources");
                    }
                    AssetDatabase.CreateAsset(eventCache, CacheAssetFullName);
                }
            }

            if (EditorUtils.GetBankDirectory() == null)
            {
                ClearCache();
                return;
            }

            string defaultBankFolder = null;

            if (!Settings.Instance.HasPlatforms)
            {
                defaultBankFolder = EditorUtils.GetBankDirectory();
            }
            else
            {
                FMODPlatform platform = RuntimeUtils.GetEditorFMODPlatform();
                if (platform == FMODPlatform.None)
                {
                    platform = FMODPlatform.PlayInEditor;
                }

                defaultBankFolder = Path.Combine(EditorUtils.GetBankDirectory(), Settings.Instance.GetBankPlatform(platform));
            }

            string[] bankPlatforms = EditorUtils.GetBankPlatforms();
            string[] bankFolders   = new string[bankPlatforms.Length];
            for (int i = 0; i < bankPlatforms.Length; i++)
            {
                bankFolders[i] = Path.Combine(EditorUtils.GetBankDirectory(), bankPlatforms[i]);
            }

            List <string> stringBanks = new List <string>(0);

            try
            {
                var files = Directory.GetFiles(defaultBankFolder, "*." + StringBankExtension);
                stringBanks = new List <string>(files);
            }
            catch
            {
            }

            // Strip out OSX resource-fork files that appear on FAT32
            stringBanks.RemoveAll((x) => Path.GetFileName(x).StartsWith("._"));

            if (stringBanks.Count == 0)
            {
                bool wasValid = eventCache.StringsBankWriteTime != DateTime.MinValue;
                ClearCache();
                if (wasValid)
                {
                    UnityEngine.Debug.LogError(string.Format("FMOD Studio: Directory {0} doesn't contain any banks. Build from the tool or check the path in the settings", defaultBankFolder));
                }
                return;
            }

            // If we have multiple .strings.bank files find the most recent
            stringBanks.Sort((a, b) => File.GetLastWriteTime(b).CompareTo(File.GetLastWriteTime(a)));

            // Use the most recent string bank timestamp as a marker for the most recent build of any bank because it gets exported every time
            DateTime lastWriteTime = File.GetLastWriteTime(stringBanks[0]);

            if (lastWriteTime == eventCache.StringsBankWriteTime)
            {
                countdownTimer = CountdownTimerReset;
                return;
            }

            if (EditorUtils.IsFileOpenByStudio(stringBanks[0]))
            {
                countdownTimer = CountdownTimerReset;
                return;
            }

            // Most recent strings bank is newer than last cache update time, recache.

            // Get a list of all banks
            List <string>  bankFileNames          = new List <string>();
            List <string>  reducedStringBanksList = new List <string>();
            HashSet <Guid> stringBankGuids        = new HashSet <Guid>();

            foreach (string stringBankPath in stringBanks)
            {
                FMOD.Studio.Bank stringBank;
                EditorUtils.CheckResult(EditorUtils.System.loadBankFile(stringBankPath, FMOD.Studio.LOAD_BANK_FLAGS.NORMAL, out stringBank));

                if (!stringBank.isValid())
                {
                    countdownTimer = CountdownTimerReset;
                    return;
                }
                else
                {
                    // Unload the strings bank
                    stringBank.unload();
                }
                Guid stringBankGuid;
                EditorUtils.CheckResult(stringBank.getID(out stringBankGuid));

                if (!stringBankGuids.Add(stringBankGuid))
                {
                    // If we encounter multiple string banks with the same GUID then only use the first. This handles the scenario where
                    // a Studio project is cloned and extended for DLC with a new master bank name.
                    continue;
                }

                reducedStringBanksList.Add(stringBankPath);
            }

            bankFileNames = new List <string>(Directory.GetFiles(defaultBankFolder, "*.bank", SearchOption.AllDirectories));

            stringBanks = reducedStringBanksList;

            if (!UnityEditorInternal.InternalEditorUtility.inBatchMode)
            {
                // Check if any of the files are still being written by studio
                foreach (string bankFileName in bankFileNames)
                {
                    EditorBankRef bankRef = eventCache.EditorBanks.Find((x) => bankFileName == x.Path);
                    if (bankRef == null)
                    {
                        if (EditorUtils.IsFileOpenByStudio(bankFileName))
                        {
                            countdownTimer = CountdownTimerReset;
                            return;
                        }
                        continue;
                    }

                    if (bankRef.LastModified != File.GetLastWriteTime(bankFileName))
                    {
                        if (EditorUtils.IsFileOpenByStudio(bankFileName))
                        {
                            countdownTimer = CountdownTimerReset;
                            return;
                        }
                    }
                }

                // Count down the timer in case we catch studio in-between updating two files.
                if (countdownTimer-- > 0)
                {
                    return;
                }
            }

            eventCache.StringsBankWriteTime = lastWriteTime;

            // All files are finished being modified by studio so update the cache

            // Stop editor preview so no stale data being held
            EditorUtils.PreviewStop();

            // Reload the strings banks
            List <FMOD.Studio.Bank> loadedStringsBanks = new List <FMOD.Studio.Bank>();

            try
            {
                AssetDatabase.StartAssetEditing();

                eventCache.EditorBanks.ForEach((x) => x.Exists = false);
                HashSet <string> masterBankFileNames = new HashSet <string>();

                foreach (string stringBankPath in stringBanks)
                {
                    FMOD.Studio.Bank stringBank;
                    EditorUtils.CheckResult(EditorUtils.System.loadBankFile(stringBankPath, FMOD.Studio.LOAD_BANK_FLAGS.NORMAL, out stringBank));

                    if (!stringBank.isValid())
                    {
                        ClearCache();
                        return;
                    }

                    loadedStringsBanks.Add(stringBank);

                    FileInfo stringBankFileInfo = new FileInfo(stringBankPath);

                    string masterBankFileName = Path.GetFileName(stringBankPath).Replace(StringBankExtension, BankExtension);
                    masterBankFileNames.Add(masterBankFileName);

                    EditorBankRef stringsBankRef = eventCache.StringsBanks.Find(x => stringBankPath == x.Path);

                    if (stringsBankRef == null)
                    {
                        stringsBankRef           = ScriptableObject.CreateInstance <EditorBankRef>();
                        stringsBankRef.FileSizes = new List <EditorBankRef.NameValuePair>();
                        eventCache.EditorBanks.Add(stringsBankRef);
                        AssetDatabase.AddObjectToAsset(stringsBankRef, eventCache);
                        AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(stringsBankRef));
                        eventCache.StringsBanks.Add(stringsBankRef);
                    }

                    stringsBankRef.Path         = stringBankPath;
                    stringsBankRef.LastModified = stringBankFileInfo.LastWriteTime;
                    stringsBankRef.Exists       = true;
                    stringsBankRef.FileSizes.Clear();

                    if (Settings.Instance.HasPlatforms)
                    {
                        for (int i = 0; i < bankPlatforms.Length; i++)
                        {
                            stringsBankRef.FileSizes.Add(new EditorBankRef.NameValuePair(bankPlatforms[i], stringBankFileInfo.Length));
                        }
                    }
                    else
                    {
                        stringsBankRef.FileSizes.Add(new EditorBankRef.NameValuePair("", stringBankFileInfo.Length));
                    }
                }

                eventCache.EditorParameters.ForEach((x) => x.Exists = false);
                foreach (string bankFileName in bankFileNames)
                {
                    FileInfo      bankFileInfo = new FileInfo(bankFileName);
                    EditorBankRef bankRef      = eventCache.EditorBanks.Find((x) => bankFileInfo.FullName == x.Path);

                    // New bank we've never seen before
                    if (bankRef == null)
                    {
                        bankRef = ScriptableObject.CreateInstance <EditorBankRef>();
                        AssetDatabase.AddObjectToAsset(bankRef, eventCache);
                        AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(bankRef));
                        bankRef.Path         = bankFileInfo.FullName;
                        bankRef.LastModified = DateTime.MinValue;
                        bankRef.FileSizes    = new List <EditorBankRef.NameValuePair>();
                        eventCache.EditorBanks.Add(bankRef);
                    }

                    bankRef.Exists = true;

                    // Timestamp check - if it doesn't match update events from that bank
                    if (bankRef.LastModified != bankFileInfo.LastWriteTime)
                    {
                        bankRef.LastModified = bankFileInfo.LastWriteTime;
                        UpdateCacheBank(bankRef);
                    }

                    // Update file sizes
                    bankRef.FileSizes.Clear();
                    if (Settings.Instance.HasPlatforms)
                    {
                        for (int i = 0; i < bankPlatforms.Length; i++)
                        {
                            string platformBankPath = Path.Combine(bankFolders[i], bankFileName);
                            var    fileInfo         = new FileInfo(platformBankPath);
                            if (fileInfo.Exists)
                            {
                                bankRef.FileSizes.Add(new EditorBankRef.NameValuePair(bankPlatforms[i], fileInfo.Length));
                            }
                        }
                    }
                    else
                    {
                        string platformBankPath = Path.Combine(EditorUtils.GetBankDirectory(), bankFileName);
                        var    fileInfo         = new FileInfo(platformBankPath);
                        if (fileInfo.Exists)
                        {
                            bankRef.FileSizes.Add(new EditorBankRef.NameValuePair("", fileInfo.Length));
                        }
                    }

                    if (masterBankFileNames.Contains(bankFileInfo.Name))
                    {
                        if (!eventCache.MasterBanks.Exists(x => bankFileInfo.FullName == x.Path))
                        {
                            eventCache.MasterBanks.Add(bankRef);
                        }
                    }
                }

                // Remove any stale entries from bank, event and parameter lists
                eventCache.EditorBanks.FindAll((x) => !x.Exists).ForEach(RemoveCacheBank);
                eventCache.EditorBanks.RemoveAll((x) => !x.Exists);
                eventCache.EditorEvents.RemoveAll((x) => x.Banks.Count == 0);
                eventCache.EditorParameters.RemoveAll((x) => !x.Exists);
                eventCache.MasterBanks.RemoveAll((x) => !x.Exists);
                eventCache.StringsBanks.RemoveAll((x) => !x.Exists);

                OnCacheChange();
            }
            finally
            {
                // Unload the strings banks
                loadedStringsBanks.ForEach(x => x.unload());
                AssetDatabase.StopAssetEditing();
            }
        }
Beispiel #16
0
 void Start()
 {
     RuntimeUtils.EnforceLibraryOrder();
     HandleGameEvent(LoaderGameEvent.ObjectStart);
 }
Beispiel #17
0
 private static void SetListenerLocation2D(int listenerIndex, Transform transform, Rigidbody2D rigidBody = null, GameObject attenuationObject = null)
 {
     if (attenuationObject)
     {
         Instance.studioSystem.setListenerAttributes(0, RuntimeUtils.To3DAttributes(transform, rigidBody), RuntimeUtils.ToFMODVector(attenuationObject.transform.position));
     }
     else
     {
         Instance.studioSystem.setListenerAttributes(0, RuntimeUtils.To3DAttributes(transform, rigidBody));
     }
 }
        void Update()
        {
            if (studioSystem.isValid())
            {
                studioSystem.update();

                bool foundListener   = false;
                bool hasAllListeners = false;
                int  numListeners    = 0;
                for (int i = FMOD.CONSTANTS.MAX_LISTENERS - 1; i >= 0; i--)
                {
                    if (!foundListener && HasListener[i])
                    {
                        numListeners    = i + 1;
                        foundListener   = true;
                        hasAllListeners = true;
                    }

                    if (!HasListener[i] && foundListener)
                    {
                        hasAllListeners = false;
                    }
                }

                if (foundListener)
                {
                    studioSystem.setNumListeners(numListeners);
                }

                if (!hasAllListeners && !listenerWarningIssued)
                {
                    listenerWarningIssued = true;
                    UnityEngine.Debug.LogWarning("FMOD Studio Integration: Please add an 'FMOD Studio Listener' component to your a camera in the scene for correct 3D positioning of sounds");
                }

                for (int i = 0; i < attachedInstances.Count; i++)
                {
                    FMOD.Studio.PLAYBACK_STATE playbackState = FMOD.Studio.PLAYBACK_STATE.STOPPED;
                    attachedInstances[i].instance.getPlaybackState(out playbackState);
                    if (!attachedInstances[i].instance.isValid() ||
                        playbackState == FMOD.Studio.PLAYBACK_STATE.STOPPED ||
                        attachedInstances[i].transform == null // destroyed game object
                        )
                    {
                        attachedInstances.RemoveAt(i);
                        i--;
                        continue;
                    }

                    if (attachedInstances[i].rigidBody)
                    {
                        attachedInstances[i].instance.set3DAttributes(RuntimeUtils.To3DAttributes(attachedInstances[i].transform, attachedInstances[i].rigidBody));
                    }
                    else
                    {
                        attachedInstances[i].instance.set3DAttributes(RuntimeUtils.To3DAttributes(attachedInstances[i].transform, attachedInstances[i].rigidBody2D));
                    }
                }

                #if UNITY_EDITOR
                for (int i = eventPositionWarnings.Count - 1; i >= 0; i--)
                {
                    if (eventPositionWarnings[i].isValid())
                    {
                        FMOD.ATTRIBUTES_3D attribs;
                        eventPositionWarnings[i].get3DAttributes(out attribs);
                        if (attribs.position.x == 1e+18F &&
                            attribs.position.y == 1e+18F &&
                            attribs.position.z == 1e+18F)
                        {
                            string path;
                            FMOD.Studio.EventDescription desc;
                            eventPositionWarnings[i].getDescription(out desc);
                            desc.getPath(out path);
                            Debug.LogWarningFormat("FMOD Studio: Instance of Event {0} has not had EventInstance.set3DAttributes() called on it yet!", path);
                        }
                    }
                    eventPositionWarnings.RemoveAt(i);
                }
                #endif
            }
        }
Beispiel #19
0
        void Update()
        {
            if (studioSystem != null)
            {
                studioSystem.update();

                bool foundListener   = false;
                bool hasAllListeners = false;
                int  numListeners    = 0;
                for (int i = FMOD.CONSTANTS.MAX_LISTENERS - 1; i >= 0; i--)
                {
                    if (!foundListener && HasListener[i])
                    {
                        numListeners    = i + 1;
                        foundListener   = true;
                        hasAllListeners = true;
                    }

                    if (!HasListener[i] && foundListener)
                    {
                        hasAllListeners = false;
                    }
                }

                if (foundListener)
                {
                    studioSystem.setNumListeners(numListeners);
                }

                if (!hasAllListeners && !listenerWarningIssued)
                {
                    listenerWarningIssued = true;
                    UnityEngine.Debug.LogWarning("FMOD Studio Integration: Please add an 'FMOD Studio Listener' component to your a camera in the scene for correct 3D positioning of sounds");
                }

                for (int i = 0; i < attachedInstances.Count; i++)
                {
                    FMOD.Studio.PLAYBACK_STATE playbackState = FMOD.Studio.PLAYBACK_STATE.STOPPED;
                    attachedInstances[i].instance.getPlaybackState(out playbackState);
                    if (!attachedInstances[i].instance.isValid() ||
                        playbackState == FMOD.Studio.PLAYBACK_STATE.STOPPED ||
                        attachedInstances[i].transform == null // destroyed game object
                        )
                    {
                        attachedInstances.RemoveAt(i);
                        i--;
                        continue;
                    }

                    if (attachedInstances[i].rigidBody)
                    {
                        attachedInstances[i].instance.set3DAttributes(RuntimeUtils.To3DAttributes(attachedInstances[i].transform, attachedInstances[i].rigidBody));
                    }
                    else
                    {
                        attachedInstances[i].instance.set3DAttributes(RuntimeUtils.To3DAttributes(attachedInstances[i].transform, attachedInstances[i].rigidBody2D));
                    }
                }


                #if UNITY_EDITOR
                MuteAllEvents(UnityEditor.EditorUtility.audioMasterMute);
                #endif


                #if UNITY_EDITOR
                // Catch any 3D events that are being played at the origin
                foreach (FMOD.Studio.EventDescription desc in cachedDescriptions.Values)
                {
                    if (!desc.isValid())
                    {
                        continue;
                    }
                    bool is3d;
                    desc.is3D(out is3d);
                    if (!is3d)
                    {
                        continue;
                    }

                    string path;
                    desc.getPath(out path);

                    int instanceCount;
                    desc.getInstanceCount(out instanceCount);
                    FMOD.Studio.EventInstance[] instances = new FMOD.Studio.EventInstance[instanceCount];
                    desc.getInstanceList(out instances);
                    for (int i = 0; i < instances.Length; i++)
                    {
                        if (warnedInvalidInstances.ContainsKey(instances[i].getRaw()))
                        {
                            continue;
                        }

                        FMOD.ATTRIBUTES_3D attributes = new FMOD.ATTRIBUTES_3D();
                        instances[i].get3DAttributes(out attributes);
                        if (attributes.position.x == 0 &&
                            attributes.position.y == 0 &&
                            attributes.position.z == 0)
                        {
                            warnedInvalidInstances.Add(instances[i].getRaw(), true);
#if UNITY_5_X
                            Debug.LogWarningFormat("FMOD Studio: Instance of Event {0} found playing at the origin. EventInstance.set3DAttributes() should be called on all 3D events", path);
#else
                            Debug.LogWarning(string.Format("FMOD Studio: Instance of Event {0} found playing at the origin. EventInstance.set3DAttributes() should be called on all 3D events", path));
#endif
                        }
                    }
                }
                #endif
            }
        }
 public static void SetListenerLocation(GameObject gameObject, Rigidbody rigidBody = null)
 {
     Instance.studioSystem.setListenerAttributes(0, RuntimeUtils.To3DAttributes(gameObject, rigidBody));
 }
Beispiel #21
0
        FMOD.RESULT Initialize()
        {
#if UNITY_EDITOR
            AssemblyReloadEvents.beforeAssemblyReload += HandleBeforeAssemblyReload;
            EditorApplication.playModeStateChanged    += HandlePlayModeStateChange;
#endif // UNITY_EDITOR

            FMOD.RESULT result       = FMOD.RESULT.OK;
            FMOD.RESULT initResult   = FMOD.RESULT.OK;
            Settings    fmodSettings = Settings.Instance;
            fmodPlatform = RuntimeUtils.GetCurrentPlatform();

            int sampleRate               = fmodSettings.GetSampleRate(fmodPlatform);
            int realChannels             = Math.Min(fmodSettings.GetRealChannels(fmodPlatform), 256);
            int virtualChannels          = fmodSettings.GetVirtualChannels(fmodPlatform);
            FMOD.SPEAKERMODE speakerMode = (FMOD.SPEAKERMODE)fmodSettings.GetSpeakerMode(fmodPlatform);
            FMOD.OUTPUTTYPE  outputType  = FMOD.OUTPUTTYPE.AUTODETECT;

            FMOD.ADVANCEDSETTINGS advancedSettings = new FMOD.ADVANCEDSETTINGS();
            advancedSettings.randomSeed = (uint)DateTime.Now.Ticks;
#if UNITY_EDITOR || UNITY_STANDALONE
            advancedSettings.maxVorbisCodecs = realChannels;
#elif UNITY_XBOXONE
            advancedSettings.maxXMACodecs = realChannels;
#elif UNITY_PS4
            advancedSettings.maxAT9Codecs = realChannels;
#else
            advancedSettings.maxFADPCMCodecs = realChannels;
#endif

            SetThreadAffinity();

#if UNITY_EDITOR || DEVELOPMENT_BUILD
            result = FMOD.Debug.Initialize(fmodSettings.LoggingLevel, FMOD.DEBUG_MODE.CALLBACK, DEBUG_CALLBACK, null);
            CheckInitResult(result, "FMOD.Debug.Initialize");
#endif

            FMOD.Studio.INITFLAGS studioInitFlags = FMOD.Studio.INITFLAGS.NORMAL | FMOD.Studio.INITFLAGS.DEFERRED_CALLBACKS;
            if (fmodSettings.IsLiveUpdateEnabled(fmodPlatform))
            {
                studioInitFlags |= FMOD.Studio.INITFLAGS.LIVEUPDATE;
                advancedSettings.profilePort = fmodSettings.LiveUpdatePort;
            }

retry:
            result = FMOD.Studio.System.create(out studioSystem);
            CheckInitResult(result, "FMOD.Studio.System.create");

            result = studioSystem.getCoreSystem(out coreSystem);
            CheckInitResult(result, "FMOD.Studio.System.getCoreSystem");

            // 降低音频延迟?
            coreSystem.setDSPBufferSize(32, 2);

            result = coreSystem.setOutput(outputType);
            CheckInitResult(result, "FMOD.System.setOutput");

            result = coreSystem.setSoftwareChannels(realChannels);
            CheckInitResult(result, "FMOD.System.setSoftwareChannels");

            result = coreSystem.setSoftwareFormat(sampleRate, speakerMode, 0);
            CheckInitResult(result, "FMOD.System.setSoftwareFormat");

            result = coreSystem.setAdvancedSettings(ref advancedSettings);
            CheckInitResult(result, "FMOD.System.setAdvancedSettings");

            if (!string.IsNullOrEmpty(Settings.Instance.EncryptionKey))
            {
                FMOD.Studio.ADVANCEDSETTINGS studioAdvancedSettings = new FMOD.Studio.ADVANCEDSETTINGS();
                result = studioSystem.setAdvancedSettings(studioAdvancedSettings, Settings.Instance.EncryptionKey);
                CheckInitResult(result, "FMOD.Studio.System.setAdvancedSettings");
            }

            result = studioSystem.initialize(virtualChannels, studioInitFlags, FMOD.INITFLAGS.NORMAL, IntPtr.Zero);
            if (result != FMOD.RESULT.OK && initResult == FMOD.RESULT.OK)
            {
                initResult = result; // Save this to throw at the end (we'll attempt NO SOUND to shield ourselves from unexpected device failures)
                outputType = FMOD.OUTPUTTYPE.NOSOUND;
                UnityEngine.Debug.LogErrorFormat("[FMOD] Studio::System::initialize returned {0}, defaulting to no-sound mode.", result.ToString());

                goto retry;
            }
            CheckInitResult(result, "Studio::System::initialize");

            // Test network functionality triggered during System::update
            if ((studioInitFlags & FMOD.Studio.INITFLAGS.LIVEUPDATE) != 0)
            {
                studioSystem.flushCommands(); // Any error will be returned through Studio.System.update

                result = studioSystem.update();
                if (result == FMOD.RESULT.ERR_NET_SOCKET_ERROR)
                {
                    studioInitFlags &= ~FMOD.Studio.INITFLAGS.LIVEUPDATE;
                    UnityEngine.Debug.LogWarning("[FMOD] Cannot open network port for Live Update (in-use), restarting with Live Update disabled.");

                    result = studioSystem.release();
                    CheckInitResult(result, "FMOD.Studio.System.Release");

                    goto retry;
                }
            }

            LoadPlugins(fmodSettings);
            LoadBanks(fmodSettings);

#if (UNITY_IOS || UNITY_TVOS) && !UNITY_EDITOR
            RegisterSuspendCallback(HandleInterrupt);
#endif

            return(initResult);
        }
Beispiel #22
0
        public void Play()
        {
            if (TriggerOnce && hasTriggered)
            {
                return;
            }

            if (String.IsNullOrEmpty(Event))
            {
                return;
            }

            if (!eventDescription.isValid())
            {
                Lookup();
            }

            if (!Event.StartsWith(SnapshotString, StringComparison.CurrentCultureIgnoreCase))
            {
                eventDescription.isOneshot(out isOneshot);
            }
            bool is3D;

            eventDescription.is3D(out is3D);

            if (!instance.isValid())
            {
                instance.clearHandle();
            }

            // Let previous oneshot instances play out
            if (isOneshot && instance.isValid())
            {
                instance.release();
                instance.clearHandle();
            }

            if (!instance.isValid())
            {
                eventDescription.createInstance(out instance);

                // Only want to update if we need to set 3D attributes
                if (is3D)
                {
                    var rigidBody   = GetComponent <Rigidbody>();
                    var rigidBody2D = GetComponent <Rigidbody2D>();
                    var transform   = GetComponent <Transform>();
                    if (rigidBody)
                    {
                        instance.set3DAttributes(RuntimeUtils.To3DAttributes(gameObject, rigidBody));
                        RuntimeManager.AttachInstanceToGameObject(instance, transform, rigidBody);
                    }
                    else
                    {
                        instance.set3DAttributes(RuntimeUtils.To3DAttributes(gameObject, rigidBody2D));
                        RuntimeManager.AttachInstanceToGameObject(instance, transform, rigidBody2D);
                    }
                }
            }

            foreach (var param in Params)
            {
                instance.setParameterValue(param.Name, param.Value);
            }

            if (is3D && OverrideAttenuation)
            {
                instance.setProperty(FMOD.Studio.EVENT_PROPERTY.MINIMUM_DISTANCE, OverrideMinDistance);
                instance.setProperty(FMOD.Studio.EVENT_PROPERTY.MAXIMUM_DISTANCE, OverrideMaxDistance);
            }

            instance.start();

            hasTriggered = true;
        }
Beispiel #23
0
        void Update()
        {
            if (studioSystem.isValid())
            {
                if (numListeners <= 0 && !listenerWarningIssued)
                {
                    listenerWarningIssued = true;
                    UnityEngine.Debug.LogWarning("[FMOD] Please add an 'FMOD Studio Listener' component to your a camera in the scene for correct 3D positioning of sounds.");
                }

                for (int i = 0; i < attachedInstances.Count; i++)
                {
                    FMOD.Studio.PLAYBACK_STATE playbackState = FMOD.Studio.PLAYBACK_STATE.STOPPED;
                    attachedInstances[i].instance.getPlaybackState(out playbackState);
                    if (!attachedInstances[i].instance.isValid() ||
                        playbackState == FMOD.Studio.PLAYBACK_STATE.STOPPED ||
                        attachedInstances[i].transform == null // destroyed game object
                        )
                    {
                        attachedInstances.RemoveAt(i);
                        i--;
                        continue;
                    }

                    if (attachedInstances[i].rigidBody)
                    {
                        attachedInstances[i].instance.set3DAttributes(RuntimeUtils.To3DAttributes(attachedInstances[i].transform, attachedInstances[i].rigidBody));
                    }
                    else
                    {
                        attachedInstances[i].instance.set3DAttributes(RuntimeUtils.To3DAttributes(attachedInstances[i].transform, attachedInstances[i].rigidBody2D));
                    }
                }

#if UNITY_EDITOR
                MuteAllEvents(UnityEditor.EditorUtility.audioMasterMute);

                for (int i = eventPositionWarnings.Count - 1; i >= 0; i--)
                {
                    if (eventPositionWarnings[i].isValid())
                    {
                        FMOD.ATTRIBUTES_3D attribs;
                        eventPositionWarnings[i].get3DAttributes(out attribs);
                        if (attribs.position.x == 1e+18F &&
                            attribs.position.y == 1e+18F &&
                            attribs.position.z == 1e+18F)
                        {
                            string path;
                            FMOD.Studio.EventDescription desc;
                            eventPositionWarnings[i].getDescription(out desc);
                            desc.getPath(out path);
                            Debug.LogWarningFormat("[FMOD] Instance of Event {0} has not had EventInstance.set3DAttributes() called on it yet!", path);
                        }
                    }
                    eventPositionWarnings.RemoveAt(i);
                }

                isOverlayEnabled = Settings.Instance.IsOverlayEnabled(fmodPlatform);
#endif

                if (isOverlayEnabled)
                {
                    if (!overlayDrawer)
                    {
                        overlayDrawer = Instance.gameObject.AddComponent <FMODRuntimeManagerOnGUIHelper>();
                        overlayDrawer.TargetRuntimeManager = this;
                    }
                    else
                    {
                        overlayDrawer.gameObject.SetActive(true);
                    }
                }
                else
                {
                    if (overlayDrawer != null && overlayDrawer.gameObject.activeSelf)
                    {
                        overlayDrawer.gameObject.SetActive(false);
                    }
                }

                studioSystem.update();
            }
        }
 void Start()
 {
     RuntimeUtils.EnforceLibraryOrder();
     HandleGameEvent(EmitterGameEvent.LevelStart);
 }
Beispiel #25
0
        void Initialiase(bool forceNoNetwork)
        {
            UnityEngine.Debug.Log("FMOD Studio: Creating runtime system instance");

            FMOD.RESULT result;
            result = FMOD.Studio.System.create(out studioSystem);
            CheckInitResult(result, "Creating System Object");
            studioSystem.getLowLevelSystem(out lowlevelSystem);

            Settings fmodSettings = Settings.Instance;

            fmodPlatform = RuntimeUtils.GetCurrentPlatform();

            #if UNITY_EDITOR || ((UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX) && DEVELOPMENT_BUILD)
            result = FMOD.Debug.Initialize(FMOD.DEBUG_FLAGS.LOG, FMOD.DEBUG_MODE.FILE, null, RuntimeUtils.LogFileName);
            CheckInitResult(result, "Applying debug settings");
            #endif

            int realChannels = fmodSettings.GetRealChannels(fmodPlatform);
            result = lowlevelSystem.setSoftwareChannels(realChannels);
            CheckInitResult(result, "Set software channels");
            result = lowlevelSystem.setSoftwareFormat(
                fmodSettings.GetSampleRate(fmodPlatform),
                (FMOD.SPEAKERMODE)fmodSettings.GetSpeakerMode(fmodPlatform),
                0 // raw not supported
                );
            CheckInitResult(result, "Set software format");

            // Setup up the platforms recommended codec to match the real channel count
            FMOD.ADVANCEDSETTINGS advancedsettings = new FMOD.ADVANCEDSETTINGS();
            #if UNITY_EDITOR || UNITY_STANDALONE
            advancedsettings.maxVorbisCodecs = realChannels;
            #elif UNITY_IOS || UNITY_ANDROID || UNITY_WP8_1 || UNITY_PSP2 || UNITY_WII
            advancedsettings.maxFADPCMCodecs = realChannels;
            #elif UNITY_XBOXONE
            advancedsettings.maxXMACodecs = realChannels;
            #elif UNITY_PS4
            advancedsettings.maxAT9Codecs = realChannels;
            #endif

            #if UNITY_5_0 || UNITY_5_1
            if (fmodSettings.IsLiveUpdateEnabled(fmodPlatform) && !forceNoNetwork)
            {
                UnityEngine.Debug.LogWarning("FMOD Studio: Detected Unity 5, running on port 9265");
                advancedsettings.profilePort = 9265;
            }
            #endif

            advancedsettings.randomSeed = (uint)DateTime.Now.Ticks;
            result = lowlevelSystem.setAdvancedSettings(ref advancedsettings);
            CheckInitResult(result, "Set advanced settings");

            FMOD.INITFLAGS        lowlevelInitFlags = FMOD.INITFLAGS.NORMAL;
            FMOD.Studio.INITFLAGS studioInitFlags   = FMOD.Studio.INITFLAGS.NORMAL | FMOD.Studio.INITFLAGS.DEFERRED_CALLBACKS;

            if (fmodSettings.IsLiveUpdateEnabled(fmodPlatform) && !forceNoNetwork)
            {
                studioInitFlags |= FMOD.Studio.INITFLAGS.LIVEUPDATE;
            }

            FMOD.RESULT initResult = studioSystem.initialize(
                fmodSettings.GetVirtualChannels(fmodPlatform),
                studioInitFlags,
                lowlevelInitFlags,
                IntPtr.Zero
                );

            CheckInitResult(initResult, "Calling initialize");

            // Dummy flush and update to get network state
            studioSystem.flushCommands();
            FMOD.RESULT updateResult = studioSystem.update();

            // Restart without liveupdate if there was a socket error
            if (updateResult == FMOD.RESULT.ERR_NET_SOCKET_ERROR)
            {
                studioSystem.release();
                UnityEngine.Debug.LogWarning("FMOD Studio: Cannot open network port for Live Update, restarting with Live Update disabled. Check for other applications that are running FMOD Studio");
                Initialiase(true);
            }
            else
            {
                // Load plugins (before banks)
                foreach (var pluginName in fmodSettings.Plugins)
                {
                    string pluginPath = RuntimeUtils.GetPluginPath(pluginName);
                    uint   handle;
                    result = lowlevelSystem.loadPlugin(pluginPath, out handle);
                    #if UNITY_64 || UNITY_EDITOR_64
                    // Add a "64" suffix and try again
                    if (result == FMOD.RESULT.ERR_FILE_BAD || result == FMOD.RESULT.ERR_FILE_NOTFOUND)
                    {
                        pluginPath = RuntimeUtils.GetPluginPath(pluginName + "64");
                        result     = lowlevelSystem.loadPlugin(pluginPath, out handle);
                    }
                    #endif
                    CheckInitResult(result, String.Format("Loading plugin '{0}' from '{1}'", pluginName, pluginPath));
                    loadedPlugins.Add(pluginName, handle);
                }

                // Always load strings bank
                try
                {
                    LoadBank(fmodSettings.MasterBank + ".strings", fmodSettings.AutomaticSampleLoading);
                }
                catch (BankLoadException e)
                {
                    UnityEngine.Debug.LogException(e);
                }

                if (fmodSettings.AutomaticEventLoading)
                {
                    try
                    {
                        LoadBank(fmodSettings.MasterBank, fmodSettings.AutomaticSampleLoading);
                    }
                    catch (BankLoadException e)
                    {
                        UnityEngine.Debug.LogException(e);
                    }

                    foreach (var bank in fmodSettings.Banks)
                    {
                        try
                        {
                            LoadBank(bank, fmodSettings.AutomaticSampleLoading);
                        }
                        catch (BankLoadException e)
                        {
                            UnityEngine.Debug.LogException(e);
                        }
                    }
                }
            };

            FMOD.ChannelGroup master;
            lowlevelSystem.getMasterChannelGroup(out master);
            master.getDSP(0, out mixerHead);
            mixerHead.setMeteringEnabled(false, true);
        }
Beispiel #26
0
 // --------   Speaker Mode ----------------------
 public int GetSpeakerMode(FMODPlatform platform)
 {
     #if UNITY_EDITOR
     if (platform == FMODPlatform.PlayInEditor)
     {
         return(GetSetting(SpeakerModeSettings, platform, GetSetting(SpeakerModeSettings, RuntimeUtils.GetEditorFMODPlatform(), (int)FMOD.SPEAKERMODE.STEREO)));
     }
     else
     #endif
     {
         return(GetSetting(SpeakerModeSettings, platform, (int)FMOD.SPEAKERMODE.STEREO));
     }
 }
Beispiel #27
0
        public static void CopyToStreamingAssets()
        {
            FMODPlatform platform = RuntimeUtils.GetEditorFMODPlatform();

            if (platform == FMODPlatform.None)
            {
                UnityEngine.Debug.LogWarning(String.Format("FMOD Studio: copy banks for platform {0} : Unsupported platform", EditorUserBuildSettings.activeBuildTarget.ToString()));
                return;
            }

            string bankTargetFolder =
                Settings.Instance.ImportType == ImportType.StreamingAssets
                ? Application.dataPath + "/StreamingAssets"
                : Application.dataPath + "/" + Settings.Instance.TargetAssetPath;

            Directory.CreateDirectory(bankTargetFolder);

            string bankTargetExension =
                Settings.Instance.ImportType == ImportType.StreamingAssets
                ? "bank"
                : "bytes";

            string bankSourceFolder = EditorUtils.GetBankDirectory() + "/" + Settings.Instance.GetBankPlatform(platform);

            if (Path.GetFullPath(bankTargetFolder).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar).ToUpperInvariant() ==
                Path.GetFullPath(bankSourceFolder).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar).ToUpperInvariant())
            {
                return;
            }

            bool madeChanges = false;

            try
            {
                // Clean out any stale .bank files
                string[] currentBankFiles = Directory.GetFiles(bankTargetFolder, "*." + bankTargetExension);
                foreach (var bankFileName in currentBankFiles)
                {
                    string bankName = Path.GetFileNameWithoutExtension(bankFileName);
                    if (!eventCache.EditorBanks.Exists((x) => bankName == x.Name))
                    {
                        File.Delete(bankFileName);
                        madeChanges = true;
                    }
                }

                // Copy over any files that don't match timestamp or size or don't exist
                foreach (var bankRef in eventCache.EditorBanks)
                {
                    string sourcePath = bankSourceFolder + "/" + bankRef.Name + ".bank";
                    string targetPath = bankTargetFolder + "/" + bankRef.Name + "." + bankTargetExension;

                    FileInfo sourceInfo = new FileInfo(sourcePath);
                    FileInfo targetInfo = new FileInfo(targetPath);

                    if (!targetInfo.Exists ||
                        sourceInfo.Length != targetInfo.Length ||
                        sourceInfo.LastWriteTime != targetInfo.LastWriteTime)
                    {
                        File.Copy(sourcePath, targetPath, true);
                        targetInfo               = new FileInfo(targetPath);
                        targetInfo.IsReadOnly    = false;
                        targetInfo.LastWriteTime = sourceInfo.LastWriteTime;

                        madeChanges = true;
                    }
                }
            }
            catch (Exception exception)
            {
                UnityEngine.Debug.LogError(String.Format("FMOD Studio: copy banks for platform {0} : copying banks from {1} to {2}", platform.ToString(), bankSourceFolder, bankTargetFolder));
                UnityEngine.Debug.LogException(exception);
                return;
            }

            if (madeChanges)
            {
                AssetDatabase.Refresh();
                UnityEngine.Debug.Log(String.Format("FMOD Studio: copy banks for platform {0} : copying banks from {1} to {2} succeeded", platform.ToString(), bankSourceFolder, bankTargetFolder));
            }
        }
        public override void OnInspectorGUI()
        {
            Settings settings = target as Settings;

            EditorGUI.BeginChangeCheck();

            hasBankSourceChanged = false;
            bool hasBankTargetChanged = false;

            GUIStyle style = new GUIStyle(GUI.skin.label);

            style.richText = true;

            GUI.skin.FindStyle("HelpBox").richText = true;

            int sourceType = settings.HasSourceProject ? 0 : (settings.HasPlatforms ? 2 : 1);

            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.BeginVertical();
            sourceType = GUILayout.Toggle(sourceType == 0, "Project", "Button") ? 0 : sourceType;
            sourceType = GUILayout.Toggle(sourceType == 1, "Single Platform Build", "Button") ? 1 : sourceType;
            sourceType = GUILayout.Toggle(sourceType == 2, "Multiple Platform Build", "Button") ? 2 : sourceType;
            EditorGUILayout.EndVertical();
            EditorGUILayout.BeginVertical();

            EditorGUILayout.HelpBox(
                "<size=11>Select the way you wish to connect Unity to the FMOD Studio content:\n" +
                "<b>• Project</b>\t\tIf you have the complete FMOD Studio project avaliable\n" +
                "<b>• Single Platform</b>\tIf you have only the contents of the <i>Build</i> folder for a single platform\n" +
                "<b>• Multiple Platforms</b>\tIf you have only the contents of the <i>Build</i> folder for multiple platforms, each platform in it's own sub directory\n" +
                "</size>"
                , MessageType.Info, true);
            EditorGUILayout.EndVertical();
            EditorGUILayout.EndHorizontal();
            EditorGUILayout.Space();

            if (sourceType == 0)
            {
                EditorGUILayout.BeginHorizontal();
                string oldPath = settings.SourceProjectPathUnformatted;
                EditorGUILayout.PrefixLabel("Studio Project Path", GUI.skin.textField, style);

                EditorGUI.BeginChangeCheck();
                settings.SourceProjectPathUnformatted = EditorGUILayout.TextField(GUIContent.none, settings.SourceProjectPathUnformatted);
                if (EditorGUI.EndChangeCheck())
                {
                    settings.SourceProjectPath = settings.SourceProjectPathUnformatted;
                }

                if (GUILayout.Button("Browse", GUILayout.ExpandWidth(false)))
                {
                    GUI.FocusControl(null);
                    string path = EditorUtility.OpenFilePanel("Locate Studio Project", oldPath, "fspro");
                    if (!string.IsNullOrEmpty(path))
                    {
                        path = MakePathRelativeToProject(path);
                        settings.SourceProjectPathUnformatted = path;
                        settings.SourceProjectPath            = path;
                        Repaint();
                    }
                }
                EditorGUILayout.EndHorizontal();

                // Cache in settings for runtime access in play-in-editor mode
                string bankPath = EditorUtils.GetBankDirectoryUnformatted();
                settings.SourceBankPathUnformatted = bankPath;
                settings.SourceBankPath            = bankPath;
                settings.HasPlatforms     = true;
                settings.HasSourceProject = true;

                // First time project path is set or changes, copy to streaming assets
                if (settings.SourceProjectPathUnformatted != oldPath)
                {
                    hasBankSourceChanged = true;
                }
            }

            if (sourceType == 1 || sourceType == 2)
            {
                EditorGUILayout.BeginHorizontal();
                string oldPath = settings.SourceBankPathUnformatted;
                EditorGUILayout.PrefixLabel("Build Path", GUI.skin.textField, style);

                EditorGUI.BeginChangeCheck();
                settings.SourceBankPathUnformatted = EditorGUILayout.TextField(GUIContent.none, settings.SourceBankPathUnformatted);
                if (EditorGUI.EndChangeCheck())
                {
                    settings.SourceBankPath = settings.SourceBankPathUnformatted;
                }

                if (GUILayout.Button("Browse", GUILayout.ExpandWidth(false)))
                {
                    GUI.FocusControl(null);
                    var path = EditorUtility.OpenFolderPanel("Locate Build Folder", oldPath, null);
                    if (!string.IsNullOrEmpty(path))
                    {
                        path = MakePathRelativeToProject(path);
                        settings.SourceBankPathUnformatted = path;
                        settings.SourceBankPath            = path;
                    }
                }
                EditorGUILayout.EndHorizontal();

                settings.HasPlatforms     = (sourceType == 2);
                settings.HasSourceProject = false;

                // First time project path is set or changes, copy to streaming assets
                if (settings.SourceBankPathUnformatted != oldPath)
                {
                    hasBankSourceChanged = true;
                }
            }

            if ((settings.HasSourceProject && !settings.SourceProjectPathUnformatted.Equals(settings.SourceProjectPath)) ||
                (sourceType >= 1 && !settings.SourceBankPathUnformatted.Equals(settings.SourceBankPath)))
            {
                EditorGUI.BeginDisabledGroup(true);
                EditorGUILayout.TextField("Platform specific path", sourceType >= 1 ? settings.SourceBankPath : settings.SourceProjectPath);
                EditorGUI.EndDisabledGroup();
            }

            bool   validBanks;
            string failReason;

            EditorUtils.ValidateSource(out validBanks, out failReason);
            if (!validBanks)
            {
                EditorGUILayout.HelpBox(failReason, MessageType.Error, true);
                if (EditorGUI.EndChangeCheck())
                {
                    EditorUtility.SetDirty(settings);
                }
                return;
            }

            ImportType importType = (ImportType)EditorGUILayout.EnumPopup("Import Type", settings.ImportType);

            if (importType != settings.ImportType)
            {
                hasBankTargetChanged = true;
                settings.ImportType  = importType;
            }

            // ----- Text Assets -------------
            EditorGUI.BeginDisabledGroup(settings.ImportType != ImportType.AssetBundle);
            GUI.SetNextControlName("targetAssetPath");
            targetAssetPath = EditorGUILayout.TextField("FMOD Asset Folder", string.IsNullOrEmpty(targetAssetPath) ? settings.TargetAssetPath : targetAssetPath);
            if (GUI.GetNameOfFocusedControl() == "targetAssetPath")
            {
                focused = true;
                if (Event.current.isKey)
                {
                    switch (Event.current.keyCode)
                    {
                    case KeyCode.Return:
                    case KeyCode.KeypadEnter:
                        settings.TargetAssetPath = targetAssetPath;
                        hasBankTargetChanged     = true;
                        break;
                    }
                }
            }
            else if (focused)
            {
                settings.TargetAssetPath = targetAssetPath;
                hasBankTargetChanged     = true;
                focused = false;
            }
            EditorGUI.EndDisabledGroup();

            // ----- Logging -----------------
            EditorGUILayout.Separator();
            EditorGUILayout.LabelField("<b>Logging</b>", style);
            EditorGUI.indentLevel++;
            settings.LoggingLevel = (FMOD.DEBUG_FLAGS)EditorGUILayout.EnumPopup("Logging Level", settings.LoggingLevel);
            EditorGUI.indentLevel--;

            // ----- Loading -----------------
            EditorGUI.BeginDisabledGroup(settings.ImportType == ImportType.AssetBundle);
            EditorGUILayout.Separator();
            EditorGUILayout.LabelField("<b>Initialization</b>", style);
            EditorGUI.indentLevel++;

            settings.BankLoadType = (BankLoadType)EditorGUILayout.EnumPopup("Load Banks", settings.BankLoadType);
            switch (settings.BankLoadType)
            {
            case BankLoadType.All:
                break;

            case BankLoadType.Specified:
                settings.AutomaticEventLoading = false;
                Texture upArrowTexture   = EditorGUIUtility.Load("FMOD/ArrowUp.png") as Texture;
                Texture downArrowTexture = EditorGUIUtility.Load("FMOD/ArrowDown.png") as Texture;
                bankFoldOutState = EditorGUILayout.Foldout(bankFoldOutState, "Specified Banks", true);
                if (bankFoldOutState)
                {
                    for (int i = 0; i < settings.BanksToLoad.Count; i++)
                    {
                        EditorGUILayout.BeginHorizontal();
                        EditorGUI.indentLevel++;

                        var bankName = settings.BanksToLoad[i];
                        EditorGUILayout.TextField(bankName.Replace(".bank", ""));

                        if (GUILayout.Button(upArrowTexture, GUILayout.ExpandWidth(false)))
                        {
                            if (i > 0)
                            {
                                var temp = settings.BanksToLoad[i];
                                settings.BanksToLoad[i]     = settings.BanksToLoad[i - 1];
                                settings.BanksToLoad[i - 1] = temp;
                            }
                            continue;
                        }
                        if (GUILayout.Button(downArrowTexture, GUILayout.ExpandWidth(false)))
                        {
                            if (i < settings.BanksToLoad.Count - 1)
                            {
                                var temp = settings.BanksToLoad[i];
                                settings.BanksToLoad[i]     = settings.BanksToLoad[i + 1];
                                settings.BanksToLoad[i + 1] = temp;
                            }
                            continue;
                        }

                        if (GUILayout.Button("Browse", GUILayout.ExpandWidth(false)))
                        {
                            GUI.FocusControl(null);
                            string path = EditorUtility.OpenFilePanel("Locate Bank", Application.streamingAssetsPath, "bank");
                            if (!string.IsNullOrEmpty(path))
                            {
                                settings.BanksToLoad[i] = path.Replace(Application.streamingAssetsPath + Path.AltDirectorySeparatorChar, "");
                                Repaint();
                            }
                        }
                        if (GUILayout.Button("Remove", GUILayout.ExpandWidth(false)))
                        {
                            Settings.Instance.BanksToLoad.RemoveAt(i);
                            continue;
                        }
                        EditorGUILayout.EndHorizontal();
                        EditorGUI.indentLevel--;
                    }

                    GUILayout.BeginHorizontal();
                    GUILayout.Space(30);
                    if (GUILayout.Button("Add Bank", GUILayout.ExpandWidth(false)))
                    {
                        settings.BanksToLoad.Add("");
                    }
                    if (GUILayout.Button("Add All Banks", GUILayout.ExpandWidth(false)))
                    {
                        FMODPlatform platform = RuntimeUtils.GetEditorFMODPlatform();
                        if (platform == FMODPlatform.None)
                        {
                            platform = FMODPlatform.PlayInEditor;
                        }
                        var banksFound = new List <string>(Directory.GetFiles(EditorUtils.GetBankDirectory(), "*.bank", SearchOption.AllDirectories));
                        for (int i = 0; i < banksFound.Count; i++)
                        {
                            string path          = Path.GetFullPath(banksFound[i]);
                            string bankShortName = Path.GetFullPath(path).Replace(EditorUtils.GetBankDirectory() + Path.DirectorySeparatorChar + settings.GetBankPlatform(platform) + Path.DirectorySeparatorChar, "");
                            if (!settings.BanksToLoad.Contains(bankShortName))
                            {
                                settings.BanksToLoad.Add(bankShortName);
                            }
                        }
                        Repaint();
                    }
                    if (GUILayout.Button("Clear", GUILayout.ExpandWidth(false)))
                    {
                        settings.BanksToLoad.Clear();
                    }
                    GUILayout.EndHorizontal();
                }
                break;

            case BankLoadType.None:
                settings.AutomaticEventLoading = false;
                break;

            default:
                break;
            }

            EditorGUI.BeginDisabledGroup(settings.BankLoadType == BankLoadType.None);
            settings.AutomaticSampleLoading = EditorGUILayout.Toggle("Load Bank Sample Data", settings.AutomaticSampleLoading);
            EditorGUI.EndDisabledGroup();

            EditorGUI.indentLevel--;
            EditorGUI.EndDisabledGroup();

            // ----- PIE ----------------------------------------------
            EditorGUILayout.Separator();
            EditorGUILayout.LabelField("<b>Play In Editor Settings</b>", style);
            EditorGUI.indentLevel++;
            DisplayEditorBool("Live Update", settings.LiveUpdateSettings, FMODPlatform.PlayInEditor);
            if (settings.IsLiveUpdateEnabled(FMODPlatform.PlayInEditor))
            {
                EditorGUILayout.BeginHorizontal();
                settings.LiveUpdatePort = ushort.Parse(EditorGUILayout.TextField("Live Update Port:", settings.LiveUpdatePort.ToString()));
                if (GUILayout.Button("Reset", GUILayout.ExpandWidth(false)))
                {
                    #if UNITY_5_0 || UNITY_5_1
                    settings.LiveUpdatePort = 9265;
                    #else
                    settings.LiveUpdatePort = 9264;
                    #endif
                }
                EditorGUILayout.EndHorizontal();
                #if UNITY_5_0 || UNITY_5_1
                EditorGUILayout.HelpBox("Unity 5.0 or 5.1 detected: Live update will not be able to use port <b>9264</b>", MessageType.Warning, false);
                #endif
            }
            DisplayEditorBool("Debug Overlay", settings.OverlaySettings, FMODPlatform.PlayInEditor);
            DisplayChildFreq("Sample Rate", settings.SampleRateSettings, FMODPlatform.PlayInEditor);
            if (settings.HasPlatforms)
            {
                DisplayPIEBuildDirectory("Bank Platform", settings.BankDirectorySettings, FMODPlatform.PlayInEditor);
            }

            DisplayPIESpeakerMode("Speaker Mode", settings.SpeakerModeSettings, FMODPlatform.PlayInEditor);
            if (settings.HasPlatforms)
            {
                EditorGUILayout.HelpBox(string.Format("Match the speaker mode to the setting of the platform <b>{0}</b> inside FMOD Studio", settings.GetBankPlatform(FMODPlatform.PlayInEditor)), MessageType.Info, false);
            }
            else
            {
                EditorGUILayout.HelpBox("Match the speaker mode to the setting inside FMOD Studio", MessageType.Info, false);
            }

            EditorGUI.indentLevel--;

            // ----- Default ----------------------------------------------
            EditorGUILayout.Separator();
            EditorGUILayout.LabelField("<b>Default Settings</b>", style);
            EditorGUI.indentLevel++;
            DisplayParentBool("Live Update", settings.LiveUpdateSettings, FMODPlatform.Default);
            if (settings.IsLiveUpdateEnabled(FMODPlatform.Default))
            {
                EditorGUILayout.HelpBox("Live update will listen on port <b>9264</b>", MessageType.Info, false);
            }
            DisplayParentBool("Debug Overlay", settings.OverlaySettings, FMODPlatform.Default);
            DisplayParentFreq("Sample Rate", settings.SampleRateSettings, FMODPlatform.Default);
            if (settings.HasPlatforms)
            {
                bool prevChanged = GUI.changed;
                DisplayParentBuildDirectory("Bank Platform", settings.BankDirectorySettings, FMODPlatform.Default);
                hasBankSourceChanged |= !prevChanged && GUI.changed;
            }

            DisplayParentSpeakerMode("Speaker Mode", settings.SpeakerModeSettings, FMODPlatform.Default);
            if (settings.HasPlatforms)
            {
                EditorGUILayout.HelpBox(string.Format("Match the speaker mode to the setting of the platform <b>{0}</b> inside FMOD Studio", settings.GetBankPlatform(FMODPlatform.Default)), MessageType.Info, false);
            }
            else
            {
                EditorGUILayout.HelpBox("Match the speaker mode to the setting inside FMOD Studio", MessageType.Info, false);
            }
            DisplayParentInt("Virtual Channel Count", settings.VirtualChannelSettings, FMODPlatform.Default, 1, 2048);
            DisplayParentInt("Real Channel Count", settings.RealChannelSettings, FMODPlatform.Default, 1, 256);
            EditorGUI.indentLevel--;

            // ----- Plugins ----------------------------------------------
            EditorGUILayout.Separator();
            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.PrefixLabel("<b>Plugins</b>", GUI.skin.button, style);
            if (GUILayout.Button("Add Plugin", GUILayout.ExpandWidth(false)))
            {
                settings.Plugins.Add("");
            }
            EditorGUILayout.EndHorizontal();

            EditorGUI.indentLevel++;
            for (int count = 0; count < settings.Plugins.Count; count++)
            {
                EditorGUILayout.BeginHorizontal();
                settings.Plugins[count] = EditorGUILayout.TextField("Plugin " + (count + 1).ToString() + ":", settings.Plugins[count]);

                if (GUILayout.Button("Delete Plugin", GUILayout.ExpandWidth(false)))
                {
                    settings.Plugins.RemoveAt(count);
                }
                EditorGUILayout.EndHorizontal();
            }
            EditorGUI.indentLevel--;

            // ----- Windows ----------------------------------------------
            DisplayPlatform(FMODPlatform.Desktop, null);
            DisplayPlatform(FMODPlatform.Mobile, new FMODPlatform[] { FMODPlatform.MobileHigh, FMODPlatform.MobileLow, FMODPlatform.AppleTV });
            DisplayPlatform(FMODPlatform.Console, new FMODPlatform[] { FMODPlatform.XboxOne, FMODPlatform.PS4, FMODPlatform.Switch });

            if (EditorGUI.EndChangeCheck())
            {
                EditorUtility.SetDirty(settings);
            }

            if (hasBankSourceChanged)
            {
                EventManager.UpdateCache();
            }
            if (hasBankTargetChanged)
            {
                EventManager.CopyToStreamingAssets();
            }
        }
 public void SetPath(string filePath, string basePath)
 {
     Path      = RuntimeUtils.GetCommonPlatformPath(filePath);
     Name      = CalculateName(filePath, basePath);
     base.name = "bank:/" + Name + System.IO.Path.GetExtension(filePath);
 }