Initial Wwise Integration

Created wwise project
Integrated inventory UI sounds
Improved projectile weapon behavior (randomized start position, stopped them from self-destructing at target range when airburst is disabled)
This commit is contained in:
Reinier Vens 2021-02-27 20:53:36 +00:00
commit db8c3c7779
1019 changed files with 76372 additions and 110 deletions

View file

@ -0,0 +1,126 @@
#if UNITY_EDITOR
using System.Collections.Generic;
public partial class AkBuildPreprocessor
{
/// <summary>
/// User hook called to retrieve the custom platform name used to determine the base path. Do not modify platformName
/// to use default platform names.
/// </summary>
/// <param name="platformName">The custom platform name.</param>
static partial void GetCustomPlatformName(ref string platformName, UnityEditor.BuildTarget target);
public static Dictionary<UnityEditor.BuildTarget, string> BuildTargetToPlatformName = new Dictionary<UnityEditor.BuildTarget, string>();
private static string GetPlatformName(UnityEditor.BuildTarget target)
{
var platformSubDir = string.Empty;
GetCustomPlatformName(ref platformSubDir, target);
if (!string.IsNullOrEmpty(platformSubDir))
return platformSubDir;
if (BuildTargetToPlatformName.ContainsKey(target))
{
return BuildTargetToPlatformName[target];
}
return target.ToString();
}
}
#if UNITY_2018_1_OR_NEWER
public partial class AkBuildPreprocessor : UnityEditor.Build.IPreprocessBuildWithReport, UnityEditor.Build.IPostprocessBuildWithReport
#else
public partial class AkBuildPreprocessor : UnityEditor.Build.IPreprocessBuild, UnityEditor.Build.IPostprocessBuild
#endif
{
public int callbackOrder
{
get { return 0; }
}
private string destinationSoundBankFolder = string.Empty;
public static bool CopySoundbanks(bool generate, string platformName, ref string destinationFolder)
{
if (string.IsNullOrEmpty(platformName))
{
UnityEngine.Debug.LogErrorFormat("WwiseUnity: Could not determine platform name for <{0}> platform", platformName);
return false;
}
if (generate)
{
var platforms = new System.Collections.Generic.List<string> { platformName };
AkUtilities.GenerateSoundbanks(platforms);
}
string sourceFolder;
if (!AkBasePathGetter.GetSoundBankPaths(platformName, out sourceFolder, out destinationFolder))
return false;
if (!AkUtilities.DirectoryCopy(sourceFolder, destinationFolder, true))
{
destinationFolder = null;
UnityEngine.Debug.LogErrorFormat("WwiseUnity: Could not copy SoundBank folder for <{0}> platform", platformName);
return false;
}
UnityEngine.Debug.LogFormat("WwiseUnity: Copied SoundBank folder to streaming assets folder <{0}> for <{1}> platform build", destinationFolder, platformName);
return true;
}
public static void DeleteSoundbanks(string destinationFolder)
{
if (string.IsNullOrEmpty(destinationFolder))
return;
System.IO.Directory.Delete(destinationFolder, true);
UnityEngine.Debug.LogFormat("WwiseUnity: Deleting streaming assets folder <{0}>", destinationFolder);
}
public void OnPreprocessBuildInternal(UnityEditor.BuildTarget target, string path)
{
if (AkWwiseEditorSettings.Instance.CopySoundBanksAsPreBuildStep)
{
var platformName = GetPlatformName(target);
if (!CopySoundbanks(AkWwiseEditorSettings.Instance.GenerateSoundBanksAsPreBuildStep, platformName, ref destinationSoundBankFolder))
{
UnityEngine.Debug.LogErrorFormat("WwiseUnity: SoundBank folder has not been copied for <{0}> target at <{1}>. This will likely result in a build without sound!!!", target, path);
}
}
// @todo sjl - only update for target platform
AkPluginActivator.Update(true);
AkPluginActivator.ActivatePluginsForDeployment(target, true);
}
public void OnPostprocessBuildInternal(UnityEditor.BuildTarget target, string path)
{
AkPluginActivator.ActivatePluginsForDeployment(target, false);
DeleteSoundbanks(destinationSoundBankFolder);
destinationSoundBankFolder = string.Empty;
}
#if UNITY_2018_1_OR_NEWER
public void OnPreprocessBuild(UnityEditor.Build.Reporting.BuildReport report)
{
OnPreprocessBuildInternal(report.summary.platform, report.summary.outputPath);
}
public void OnPostprocessBuild(UnityEditor.Build.Reporting.BuildReport report)
{
OnPostprocessBuildInternal(report.summary.platform, report.summary.outputPath);
}
#else
public void OnPreprocessBuild(UnityEditor.BuildTarget target, string path)
{
OnPreprocessBuildInternal(target, path);
}
public void OnPostprocessBuild(UnityEditor.BuildTarget target, string path)
{
OnPostprocessBuildInternal(target, path);
}
#endif
}
#endif // #if UNITY_EDITOR

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: ab7e28e1da9f141488912947cb7d1b43
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 980c88fda8ae4f3489149c0c917ee9b7
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,125 @@
#if UNITY_EDITOR
// Note, this code was only written to parse the AudioManager.asset file.
// It has been written to try to be as generic as possible, but might not
// work on other .asset settings files.
public class AkUnitySettingsParser
{
public static bool SetBoolValue(string ValueName, bool ValueToSet, string ConfigFileName)
{
try
{
var SettingsPath = UnityEngine.Application.dataPath.Remove(UnityEngine.Application.dataPath.LastIndexOf("/")) +
"/ProjectSettings/" + ConfigFileName + ".asset";
System.IO.FileStream fs;
System.IO.BinaryReader br;
fs = System.IO.File.Open(SettingsPath, System.IO.FileMode.Open);
br = new System.IO.BinaryReader(fs);
// Read the unsigned int at offset 0x0C in the file.
// This contains the offset at which the setting's numerical values are stored.
br.BaseStream.Seek(0x0C, System.IO.SeekOrigin.Begin);
// For some reason, the offset is Big Endian in the file.
var SettingsOffset = GetBigEndianIntFromBinaryReader(br);
// In the file, we start with 0x14 bytes, then a string containing the unity version,
// then 0x0C bytes, then a string containing the base class name, followed by a string containing "base".
string tempStr;
br.BaseStream.Seek(0x14, System.IO.SeekOrigin.Begin);
tempStr = GetStringFromBinaryReader(br); // Unity Version
br.BaseStream.Seek(0x0C, System.IO.SeekOrigin.Current);
tempStr = GetStringFromBinaryReader(br); // Config file Name
if (tempStr != ConfigFileName)
return false;
tempStr = GetStringFromBinaryReader(br); // "Base"
if (tempStr != "Base")
return false;
// This string is then followed by 24 bytes
br.BaseStream.Seek(24, System.IO.SeekOrigin.Current);
// We then have a series of String (type), String (variable name), and 24 bytes
// We can use the type of the settings before the field we are looking for to
// find its offset after SettingsOffset.
while (br.BaseStream.Position < br.BaseStream.Length)
{
var SettingType = GetStringFromBinaryReader(br);
var SettingName = GetStringFromBinaryReader(br);
if (SettingName == ValueName)
break;
br.BaseStream.Seek(24, System.IO.SeekOrigin.Current);
if (GetSizeofTypeByString(SettingType) == -1)
return false;
SettingsOffset += GetSizeofTypeByString(SettingType);
}
// Set the setting in the file
var bw = new System.IO.BinaryWriter(fs);
bw.Seek(SettingsOffset, System.IO.SeekOrigin.Begin);
bw.Write(ValueToSet ? (byte) 1 : (byte) 0);
bw.Close();
fs.Close();
}
catch (System.Exception)
{
// Error happened
return false;
}
// Success!
return true;
}
// Read a big endian Int, and advances the BinaryReader's position
private static int GetBigEndianIntFromBinaryReader(System.IO.BinaryReader br)
{
var tempBytes = new byte[4];
tempBytes = br.ReadBytes(4);
return (tempBytes[0] << 24) | (tempBytes[1] << 16) | (tempBytes[2] << 8) | tempBytes[3];
}
// Reads a zero-terminated string at the BinaryReader's current position, and advances position
private static string GetStringFromBinaryReader(System.IO.BinaryReader br)
{
var list = new System.Collections.Generic.List<byte>();
// Do not add the \0 in the string, because comparison won't work
var currentByte = br.ReadByte();
while (currentByte != 0)
{
list.Add(currentByte);
currentByte = br.ReadByte();
}
return System.Text.Encoding.Default.GetString(list.ToArray());
}
// Returns the size in bytes of a type, as specified in the .asset file
// NOTE: this function only supports types found in AudioManager.asset.
private static int GetSizeofTypeByString(string typeStr)
{
switch (typeStr)
{
case "int":
case "unsigned int":
case "float":
case "UInt32":
case "SInt32":
return 4;
case "bool":
return 1;
default:
return -1;
}
}
}
#endif // UNITY_EDITOR

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 145fac906e434384abe0f4a7f00e31d8
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,8 @@
public static class AkWSAUtils
{
[UnityEditor.MenuItem("Assets/Wwise/WSA/Enable PrivateNetworkClientServer Capability")]
public static void EnablePrivateNetworkClientServer()
{
UnityEditor.PlayerSettings.WSA.SetCapability(UnityEditor.PlayerSettings.WSACapability.PrivateNetworkClientServer, true);
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: ba6dc7559e291d04a89db2d890f7074a
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,302 @@
#if UNITY_EDITOR
[UnityEditor.InitializeOnLoad]
public class AkWwisePostImportCallbackSetup
{
private static int m_scheduledMigrationStart;
private static bool m_scheduledReturnToLauncher;
private static bool m_pendingExecuteMethodCalled;
private static string s_CurrentScene;
static AkWwisePostImportCallbackSetup()
{
var arguments = System.Environment.GetCommandLineArgs();
if ((System.Array.IndexOf(arguments, "-nographics") != -1 ||
System.Array.IndexOf(arguments, "-batchmode") != -1)
&& System.Array.IndexOf(arguments, "-wwiseEnableWithNoGraphics") == -1)
return;
UnityEditor.EditorApplication.delayCall += CheckMigrationStatus;
AkUtilities.GetEventDurations = (uint eventID, ref float maximum, ref float minimum) =>
{
var eventInfo = AkWwiseProjectInfo.GetData().GetEventInfo(eventID);
if (eventInfo != null)
{
minimum = eventInfo.minDuration;
maximum = eventInfo.maxDuration;
}
};
}
private static void CheckMigrationStatus()
{
try
{
int migrationStart;
bool returnToLauncher;
if (IsMigrationPending(out migrationStart, out returnToLauncher))
{
m_scheduledMigrationStart = migrationStart;
m_scheduledReturnToLauncher = returnToLauncher;
ScheduleMigration();
}
else
RefreshCallback();
}
catch (System.Exception e)
{
UnityEngine.Debug.LogError("WwiseUnity: Error during migration: " + e);
}
}
private static void ScheduleMigration()
{
// TODO: Is delayCall wiped out during a script reload?
// If not, guard against having a delayCall from a previously loaded code being run after the new loading.
if (UnityEditor.EditorApplication.isPlayingOrWillChangePlaymode || UnityEditor.EditorApplication.isCompiling)
{
// Skip if not in the right mode, wait for the next callback to see if we can proceed then.
UnityEditor.EditorApplication.delayCall += ScheduleMigration;
return;
}
try
{
WwiseSetupWizard.PerformMigration(m_scheduledMigrationStart);
// Force the user to return to the launcher to perform the post-installation process if necessary
if (m_scheduledReturnToLauncher)
{
if (UnityEditor.EditorUtility.DisplayDialog("Wwise Migration Successful!",
"Please close Unity and go back to the Wwise Launcher to complete the installation.", "Quit"))
UnityEditor.EditorApplication.Exit(0);
}
else
UnityEditor.EditorApplication.delayCall += RefreshCallback;
}
catch (System.Exception e)
{
UnityEngine.Debug.LogError("WwiseUnity: Error during migration: " + e);
}
}
private static bool IsMigrationPending(out int migrationStart, out bool returnToLauncher)
{
migrationStart = 0;
returnToLauncher = false;
var filename = UnityEngine.Application.dataPath + "/../.WwiseLauncherLockFile";
if (!System.IO.File.Exists(filename))
return false;
var fileContent = System.IO.File.ReadAllText(filename);
// Instantiate the regular expression object.
var r = new System.Text.RegularExpressions.Regex(
"{\"migrateStart\":(\\d+),\"migrateStop\":(\\d+)(,\"returnToLauncher\":(true|false))?,.*}",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// Match the regular expression pattern against a text string.
var m = r.Match(fileContent);
if (!m.Success || m.Groups.Count < 2 || m.Groups[1].Captures.Count < 1 || m.Groups[2].Captures.Count < 1 ||
!int.TryParse(m.Groups[1].Captures[0].ToString(), out migrationStart))
throw new System.Exception("Error in the file format of .WwiseLauncherLockFile.");
// Handle optional properties
if (m.Groups.Count > 3 && m.Groups[4].Captures.Count > 0)
bool.TryParse(m.Groups[4].Captures[0].ToString(), out returnToLauncher);
return true;
}
private static void RefreshCallback()
{
PostImportFunction();
if (WwiseSettings.Exists)
{
AkPluginActivator.Update();
AkPluginActivator.ActivatePluginsForEditor();
}
}
private static void PostImportFunction()
{
#if UNITY_2018_1_OR_NEWER
UnityEditor.EditorApplication.hierarchyChanged += CheckWwiseGlobalExistance;
#else
UnityEditor.EditorApplication.hierarchyWindowChanged += CheckWwiseGlobalExistance;
#endif
UnityEditor.EditorApplication.delayCall += CheckPicker;
if (UnityEditor.EditorApplication.isPlayingOrWillChangePlaymode || UnityEditor.EditorApplication.isCompiling)
return;
try
{
if (!string.IsNullOrEmpty(AkWwiseEditorSettings.Instance.WwiseProjectPath))
{
AkWwisePicker.PopulateTreeview();
if (AkWwiseProjectInfo.GetData().autoPopulateEnabled)
AkWwiseWWUBuilder.StartWWUWatcher();
}
}
catch (System.Exception e)
{
UnityEngine.Debug.Log(e.ToString());
}
//Check if a WwiseGlobal object exists in the current scene
CheckWwiseGlobalExistance();
}
private static void RefreshPlugins()
{
if (string.IsNullOrEmpty(AkWwiseProjectInfo.GetData().CurrentPluginConfig))
AkWwiseProjectInfo.GetData().CurrentPluginConfig = AkPluginActivator.CONFIG_PROFILE;
AkPluginActivator.ActivatePluginsForEditor();
}
public static void CheckPicker()
{
if (UnityEditor.EditorApplication.isPlayingOrWillChangePlaymode || UnityEditor.EditorApplication.isCompiling)
{
// Skip if not in the right mode, wait for the next callback to see if we can proceed then.
UnityEditor.EditorApplication.delayCall += CheckPicker;
return;
}
var settings = AkWwiseEditorSettings.Instance;
if (!settings.CreatedPicker)
{
// Delete all the ghost tabs (Failed to load).
var windows = UnityEngine.Resources.FindObjectsOfTypeAll<UnityEditor.EditorWindow>();
if (windows != null && windows.Length > 0)
{
foreach (var window in windows)
{
var windowTitle = window.titleContent.text;
if (windowTitle.Equals("Failed to load") || windowTitle.Equals("AkWwisePicker"))
{
try
{
window.Close();
}
catch
{
// Do nothing here, this shouldn't cause any problem, however there has been
// occurrences of Unity crashing on a null reference inside that method.
}
}
}
}
// TODO: If no scene is loaded and we are using the demo scene, automatically load it to display it.
// Populate the picker
AkWwiseProjectInfo.GetData(); // Load data
if (!string.IsNullOrEmpty(settings.WwiseProjectPath))
{
AkWwiseProjectInfo.Populate();
AkWwisePicker.init();
if (AkWwiseProjectInfo.GetData().autoPopulateEnabled)
AkWwiseWWUBuilder.StartWWUWatcher();
settings.CreatedPicker = true;
settings.SaveSettings();
}
}
UnityEditor.EditorApplication.delayCall += CheckPendingExecuteMethod;
}
// TODO: Put this in AkUtilities?
private static void ExecuteMethod(string method)
{
string className = null;
string methodName = null;
var r = new System.Text.RegularExpressions.Regex("(.+)\\.(.+)",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
var m = r.Match(method);
if (!m.Success || m.Groups.Count < 3 || m.Groups[1].Captures.Count < 1 || m.Groups[2].Captures.Count < 1)
{
UnityEngine.Debug.LogError("WwiseUnity: Error parsing wwiseExecuteMethod parameter: " + method);
return;
}
className = m.Groups[1].Captures[0].ToString();
methodName = m.Groups[2].Captures[0].ToString();
try
{
var type = System.Type.GetType(className);
var clearMethod = type.GetMethod(methodName,
System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public);
clearMethod.Invoke(null, null);
}
catch (System.Exception e)
{
UnityEngine.Debug.LogError("WwiseUnity: Exception caught when calling " + method + ": " + e);
}
}
private static void CheckPendingExecuteMethod()
{
var arguments = System.Environment.GetCommandLineArgs();
var indexOfCommand = System.Array.IndexOf(arguments, "-wwiseExecuteMethod");
if (!m_pendingExecuteMethodCalled && indexOfCommand != -1 && arguments.Length > indexOfCommand + 1)
{
var methodToExecute = arguments[indexOfCommand + 1];
ExecuteMethod(methodToExecute);
m_pendingExecuteMethodCalled = true;
}
}
// Called when changes are made to the scene and when a new scene is created.
public static void CheckWwiseGlobalExistance()
{
var activeSceneName = UnityEngine.SceneManagement.SceneManager.GetActiveScene().name;
if (!string.IsNullOrEmpty(s_CurrentScene) && s_CurrentScene.Equals(activeSceneName))
return;
var settings = AkWwiseEditorSettings.Instance;
// Look for a game object which has the initializer component
var AkInitializers = UnityEngine.Object.FindObjectsOfType<AkInitializer>();
if (AkInitializers.Length == 0)
{
if (settings.CreateWwiseGlobal)
{
//No Wwise object in this scene, create one so that the sound engine is initialized and terminated properly even if the scenes are loaded
//in the wrong order.
var objWwise = new UnityEngine.GameObject("WwiseGlobal");
//Attach initializer and terminator components
UnityEditor.Undo.AddComponent<AkInitializer>(objWwise);
}
}
else if (settings.CreateWwiseGlobal == false && AkInitializers[0].gameObject.name == "WwiseGlobal")
{
UnityEditor.Undo.DestroyObjectImmediate(AkInitializers[0].gameObject);
}
if (settings.CreateWwiseListener)
{
AkUtilities.AddAkAudioListenerToMainCamera(true);
}
s_CurrentScene = activeSceneName;
}
}
#endif // UNITY_EDITOR

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: d61375296f90db64c8f08d62a9102833
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,585 @@
#if UNITY_EDITOR
public class WwiseSetupWizard
{
public static void RunModify()
{
try
{
UnityEngine.Debug.Log("WwiseUnity: Running modify setup...");
UnityEditor.SceneManagement.EditorSceneManager.NewScene(UnityEditor.SceneManagement.NewSceneSetup.DefaultGameObjects);
ModifySetup();
UnityEngine.Debug.Log("WwiseUnity: Refreshing asset database.");
UnityEditor.AssetDatabase.Refresh();
// IMPORTANT: This log line is parsed by the Launcher. Do not modify it.
UnityEngine.Debug.Log("WwiseUnity: End of setup, exiting Unity.");
}
catch (System.Exception e)
{
UnityEngine.Debug.LogError("WwiseUnity: Exception caught: " + e);
}
}
public static void RunSetup()
{
try
{
UnityEngine.Debug.Log("WwiseUnity: Running install setup...");
Setup();
UnityEngine.Debug.Log("WwiseUnity: Refreshing asset database.");
UnityEditor.AssetDatabase.Refresh();
// IMPORTANT: This log line is parsed by the Launcher. Do not modify it.
UnityEngine.Debug.Log("WwiseUnity: End of setup, exiting Unity.");
}
catch (System.Exception e)
{
UnityEngine.Debug.LogError("WwiseUnity: Exception caught: " + e);
}
}
public static void RunDemoSceneSetup()
{
try
{
UnityEngine.Debug.Log("WwiseUnity: Running demo scene setup...");
Setup();
UnityEditor.SceneManagement.EditorSceneManager.OpenScene("Assets/WwiseDemoScene/WwiseDemoScene.unity");
UnityEngine.Debug.Log("WwiseUnity: Refreshing asset database.");
UnityEditor.AssetDatabase.Refresh();
UnityEngine.Debug.Log("WwiseUnity: End of demo scene setup, exiting Unity.");
}
catch (System.Exception e)
{
UnityEngine.Debug.LogError("WwiseUnity: Exception caught: " + e);
}
}
private static int TotalNumberOfSections = 3;
private static void UpdateProgressBar(int sectionIndex, int subSectionIndex = 0, int totalSubSections = 1)
{
subSectionIndex = UnityEngine.Mathf.Clamp(subSectionIndex, 0, totalSubSections);
sectionIndex = UnityEngine.Mathf.Clamp(sectionIndex, 0, TotalNumberOfSections);
float progress = ((float)subSectionIndex / totalSubSections + sectionIndex) / TotalNumberOfSections;
UnityEditor.EditorUtility.DisplayProgressBar("Wwise Integration", "Migration in progress - Please wait...", progress);
}
public static void RunMigrate()
{
try
{
UnityEngine.Debug.Log("WwiseUnity: Running migration setup...");
UnityEngine.Debug.Log("WwiseUnity: Reading parameters...");
var arguments = System.Environment.GetCommandLineArgs();
string migrateStartString = null;
var indexMigrateStart = System.Array.IndexOf(arguments, "-wwiseInstallMigrateStart");
if (indexMigrateStart != -1)
migrateStartString = arguments[indexMigrateStart + 1];
else
{
UnityEngine.Debug.LogError("WwiseUnity: ERROR: Missing parameter wwiseInstallMigrateStart.");
return;
}
int migrateStart;
if (!int.TryParse(migrateStartString, out migrateStart))
{
UnityEngine.Debug.LogError("WwiseUnity: ERROR: wwiseInstallMigrateStart is not a number.");
return;
}
PerformMigration(migrateStart - 1);
UnityEditor.AssetDatabase.SaveAssets();
UnityEngine.Debug.Log("WwiseUnity: Refreshing asset database.");
UnityEditor.AssetDatabase.Refresh();
// IMPORTANT: This log line is parsed by the Launcher. Do not modify it.
UnityEngine.Debug.Log("WwiseUnity: End of setup, exiting Unity.");
}
catch (System.Exception e)
{
UnityEngine.Debug.LogError("WwiseUnity: Exception caught: " + e);
}
}
private static void MigrateCurrentScene(System.Type[] wwiseComponentTypes)
{
var objectTypeMap = new System.Collections.Generic.Dictionary<System.Type, UnityEngine.Object[]>();
foreach (var objectType in wwiseComponentTypes)
{
// Get all objects in the scene with the specified type.
var objects = UnityEngine.Object.FindObjectsOfType(objectType);
if (objects != null && objects.Length > 0)
objectTypeMap[objectType] = objects;
}
for (var ii = AkUtilities.MigrationStartIndex; ii < AkUtilities.MigrationStopIndex; ++ii)
{
var migrationMethodName = "Migrate" + ii;
var preMigrationMethodName = "PreMigration" + ii;
var postMigrationMethodName = "PostMigration" + ii;
foreach (var objectTypePair in objectTypeMap)
{
var objectType = objectTypePair.Key;
var objects = objectTypePair.Value;
var className = objectType.Name;
var preMigrationMethodInfo = objectType.GetMethod(preMigrationMethodName,
System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
if (preMigrationMethodInfo != null)
{
UnityEngine.Debug.Log("WwiseUnity: PreMigration step <" + ii + "> for class <" + className + ">");
preMigrationMethodInfo.Invoke(null, null);
}
var migrationMethodInfo = objectType.GetMethod(migrationMethodName,
System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
if (migrationMethodInfo != null)
{
UnityEngine.Debug.Log("WwiseUnity: Migration step <" + ii + "> for class <" + className + ">");
// Call the migration method of each object.
foreach (var currentObject in objects)
migrationMethodInfo.Invoke(currentObject, null);
}
var postMigrationMethodInfo = objectType.GetMethod(postMigrationMethodName,
System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
if (postMigrationMethodInfo != null)
{
UnityEngine.Debug.Log("WwiseUnity: PostMigration step <" + ii + "> for class <" + className + ">");
postMigrationMethodInfo.Invoke(null, null);
}
}
}
}
private static System.Type[] GetWwiseComponentTypes()
{
var wwiseComponentTypes = new System.Collections.Generic.List<System.Type>();
var wwiseComponentFolder = UnityEngine.Application.dataPath + "/Wwise/Deployment/Components";
var files = new System.IO.DirectoryInfo(wwiseComponentFolder).GetFiles("*.cs", System.IO.SearchOption.AllDirectories);
foreach (var file in files)
{
var className = System.IO.Path.GetFileNameWithoutExtension(file.Name);
var objectType = System.Type.GetType(className + ", Assembly-CSharp");
if (objectType != null && objectType.IsSubclassOf(typeof(UnityEngine.Object)))
wwiseComponentTypes.Add(objectType);
}
return wwiseComponentTypes.ToArray();
}
private static void MigrateObject(UnityEngine.Object obj)
{
if (obj == null)
{
UnityEngine.Debug.LogWarning("WwiseUnity: Missing script! Please consider resolving the missing scripts before migrating your Unity project. Any WwiseType on this object will NOT be migrated!");
return;
}
var migratable = obj as AK.Wwise.IMigratable;
if (migratable == null && !AkUtilities.IsMigrationRequired(AkUtilities.MigrationStep.WwiseTypes_v2018_1_6))
return;
var hasChanged = false;
var serializedObject = new UnityEditor.SerializedObject(obj);
if (migratable != null)
hasChanged = migratable.Migrate(serializedObject);
else
hasChanged = AK.Wwise.TypeMigration.SearchAndProcessWwiseTypes(serializedObject.GetIterator());
if (hasChanged)
serializedObject.ApplyModifiedPropertiesWithoutUndo();
}
private static void MigratePrefabs()
{
var guids = UnityEditor.AssetDatabase.FindAssets("t:Prefab", new[] { "Assets" });
for (var i = 0; i < guids.Length; i++)
{
UpdateProgressBar(0, i, guids.Length);
var path = UnityEditor.AssetDatabase.GUIDToAssetPath(guids[i]);
UnityEngine.Debug.Log("WwiseUnity: Migrating prefab: " + path);
var prefabObject = UnityEditor.AssetDatabase.LoadAssetAtPath<UnityEngine.GameObject>(path);
if (prefabObject == null)
{
UnityEngine.Debug.LogWarning("WwiseUnity: Failed to migrate prefab: " + path);
continue;
}
var objects = prefabObject.GetComponents<UnityEngine.MonoBehaviour>();
#if UNITY_2018_3_OR_NEWER
var instanceIds = new System.Collections.Generic.List<int>();
foreach (var obj in objects)
{
if (obj == null)
continue;
var id = obj.GetInstanceID();
if (!instanceIds.Contains(id))
instanceIds.Add(id);
}
for (; instanceIds.Count > 0; instanceIds.RemoveAt(0))
{
var id = instanceIds[0];
objects = prefabObject.GetComponents<UnityEngine.MonoBehaviour>();
foreach (var obj in objects)
{
if (obj && obj.GetInstanceID() == id)
{
MigrateObject(obj);
break;
}
}
}
#else
foreach (var obj in objects)
MigrateObject(obj);
#endif
}
}
private static string[] ScriptableObjectGuids = null;
private static bool ShouldProcessScriptableObject(UnityEngine.Object obj)
{
if (obj == null)
return true;
if (!(obj is UnityEngine.ScriptableObject))
return false;
if (obj is UnityEngine.GUISkin)
return false;
if (obj is AkWwiseProjectData)
return false;
if (obj is AkWwiseInitializationSettings)
return false;
if (obj is AkCommonPlatformSettings)
return false;
if (obj is WwiseObjectReference)
return false;
return true;
}
private static void MigrateScriptableObjects()
{
var guids = ScriptableObjectGuids;
if (guids == null)
return;
var processedGuids = new System.Collections.Generic.HashSet<string>();
for (var i = 0; i < guids.Length; i++)
{
UpdateProgressBar(2, i, guids.Length);
var guid = guids[i];
if (processedGuids.Contains(guid))
continue;
processedGuids.Add(guid);
var path = UnityEditor.AssetDatabase.GUIDToAssetPath(guid);
UnityEngine.Debug.Log("WwiseUnity: Migrating ScriptableObject: " + path);
var objects = UnityEditor.AssetDatabase.LoadAllAssetsAtPath(path);
foreach (var obj in objects)
{
if (ShouldProcessScriptableObject(obj))
{
MigrateObject(obj);
}
}
}
}
private static void MigrateScenes()
{
var wwiseComponentTypes = GetWwiseComponentTypes();
var guids = UnityEditor.AssetDatabase.FindAssets("t:Scene", new[] { "Assets" });
for (var i = 0; i < guids.Length; i++)
{
UpdateProgressBar(1, i, guids.Length);
var path = UnityEditor.AssetDatabase.GUIDToAssetPath(guids[i]);
UnityEngine.Debug.Log("WwiseUnity: Migrating scene: " + path);
UnityEditor.EditorUtility.UnloadUnusedAssetsImmediate();
var scene = UnityEditor.SceneManagement.EditorSceneManager.OpenScene(path);
MigrateCurrentScene(wwiseComponentTypes);
var objects = UnityEngine.Resources.FindObjectsOfTypeAll<UnityEngine.MonoBehaviour>();
#if UNITY_2018_3_OR_NEWER
var instanceIds = new System.Collections.Generic.List<int>();
foreach (var obj in objects)
{
if (obj == null)
continue;
var id = obj.GetInstanceID();
if (!instanceIds.Contains(id))
instanceIds.Add(id);
}
for (; instanceIds.Count > 0; instanceIds.RemoveAt(0))
{
var id = instanceIds[0];
objects = UnityEngine.Resources.FindObjectsOfTypeAll<UnityEngine.MonoBehaviour>();
foreach (var obj in objects)
{
if (obj && obj.GetInstanceID() == id)
{
MigrateObject(obj);
break;
}
}
}
#else
foreach (var obj in objects)
{
var isPrefabInstance = false;
if (obj != null)
{
#if UNITY_2018_2
isPrefabInstance = UnityEditor.PrefabUtility.GetCorrespondingObjectFromSource(obj) != null;
#else
isPrefabInstance = UnityEditor.PrefabUtility.GetPrefabParent(obj) != null;
#endif
if (!isPrefabInstance)
{
var isSceneObject = !UnityEditor.EditorUtility.IsPersistent(obj);
var isEditableAndSavable = (obj.hideFlags & (UnityEngine.HideFlags.NotEditable | UnityEngine.HideFlags.DontSave)) == 0;
if (!isSceneObject || !isEditableAndSavable)
continue;
}
}
MigrateObject(obj);
if (isPrefabInstance)
UnityEditor.PrefabUtility.RecordPrefabInstancePropertyModifications(obj);
}
#endif
if (UnityEditor.SceneManagement.EditorSceneManager.MarkSceneDirty(scene))
if (!UnityEditor.SceneManagement.EditorSceneManager.SaveScene(scene))
throw new System.Exception("Error occurred while saving migrated scenes.");
UnityEditor.SceneManagement.EditorSceneManager.CloseScene(scene, true);
}
}
public static void PerformMigration(int migrateStart)
{
UpdateProgressBar(0);
UnityEngine.Debug.Log("WwiseUnity: Migrating from Unity Integration Version " + migrateStart + " to " + AkUtilities.MigrationStopIndex);
AkPluginActivator.DeactivateAllPlugins();
AkPluginActivator.Update();
AkPluginActivator.ActivatePluginsForEditor();
// Get the name of the currently opened scene.
var activeScene = UnityEngine.SceneManagement.SceneManager.GetActiveScene();
var loadedScenePath = activeScene.path;
if (!string.IsNullOrEmpty(loadedScenePath))
AkUtilities.FixSlashes(ref loadedScenePath, '\\', '/', false);
UnityEditor.SceneManagement.EditorSceneManager.NewScene(UnityEditor.SceneManagement.NewSceneSetup.DefaultGameObjects);
// obtain a list of ScriptableObjects before any migration is performed
ScriptableObjectGuids = UnityEditor.AssetDatabase.FindAssets("t:ScriptableObject", new[] { "Assets" });
AkUtilities.BeginMigration(migrateStart);
if (AkUtilities.IsMigrationRequired(AkUtilities.MigrationStep.NewScriptableObjectFolder_v2019_2_0))
{
var oldScriptableObjectPath = System.IO.Path.Combine(System.IO.Path.Combine("Assets", "Wwise"), "Resources");
AkUtilities.MoveFolder(oldScriptableObjectPath, AkWwiseEditorSettings.WwiseScriptableObjectRelativePath);
}
AkWwiseProjectInfo.GetData().Migrate();
AkWwiseWWUBuilder.UpdateWwiseObjectReferenceData();
MigratePrefabs();
MigrateScenes();
MigrateScriptableObjects();
UnityEditor.EditorUtility.UnloadUnusedAssetsImmediate();
UnityEditor.SceneManagement.EditorSceneManager.NewScene(UnityEditor.SceneManagement.NewSceneSetup.DefaultGameObjects);
AkUtilities.EndMigration();
UpdateProgressBar(TotalNumberOfSections);
// Reopen the scene that was opened before the migration process started.
if (!string.IsNullOrEmpty(loadedScenePath))
UnityEditor.SceneManagement.EditorSceneManager.OpenScene(loadedScenePath);
UnityEngine.Debug.Log("WwiseUnity: Removing lock for launcher.");
// TODO: Moving one folder up is not nice at all. How to find the current project path?
try
{
System.IO.File.Delete(UnityEngine.Application.dataPath + "/../.WwiseLauncherLockFile");
}
catch
{
// Ignore if not present.
}
UnityEditor.EditorUtility.ClearProgressBar();
}
public static void ModifySetup()
{
var currentConfig = AkPluginActivator.GetCurrentConfig();
if (string.IsNullOrEmpty(currentConfig))
currentConfig = AkPluginActivator.CONFIG_PROFILE;
AkPluginActivator.DeactivateAllPlugins();
AkPluginActivator.Update();
AkPluginActivator.ActivatePluginsForEditor();
}
// Perform all necessary steps to use the Wwise Unity integration.
private static void Setup()
{
UnityEditor.SceneManagement.EditorSceneManager.NewScene(UnityEditor.SceneManagement.NewSceneSetup.DefaultGameObjects);
AkPluginActivator.DeactivateAllPlugins();
// 0. Make sure the SoundBank directory exists
var sbPath = AkUtilities.GetFullPath(UnityEngine.Application.streamingAssetsPath, AkWwiseEditorSettings.Instance.SoundbankPath);
if (!System.IO.Directory.Exists(sbPath))
System.IO.Directory.CreateDirectory(sbPath);
// 1. Disable built-in audio
if (!DisableBuiltInAudio())
{
UnityEngine.Debug.LogWarning(
"WwiseUnity: Could not disable built-in audio. Please disable built-in audio by going to Project->Project Settings->Audio, and check \"Disable Audio\".");
}
// 2. Create a "WwiseGlobal" game object and set the AkSoundEngineInitializer and terminator scripts
// 3. Set the SoundBank path property on AkSoundEngineInitializer
CreateWwiseGlobalObject();
// 5. Disable the built-in audio listener, and add AkAudioListener component to camera
if (AkWwiseEditorSettings.Instance.CreateWwiseListener)
{
AkUtilities.AddAkAudioListenerToMainCamera();
}
// 6. Enable "Run In Background" in PlayerSettings (PlayerSettings.runInbackground property)
UnityEditor.PlayerSettings.runInBackground = true;
AkPluginActivator.Update();
AkPluginActivator.ActivatePluginsForEditor();
// 9. Activate WwiseIDs file generation, and point Wwise to the Assets/Wwise folder
// 10. Change the SoundBanks options so it adds Max Radius information in the Wwise project
if (!SetSoundbankSettings())
UnityEngine.Debug.LogWarning("WwiseUnity: Could not modify Wwise Project to generate the header file!");
// 11. Activate XboxOne network sockets.
AkXboxOneUtils.EnableXboxOneNetworkSockets();
}
// Create a Wwise Global object containing the initializer and terminator scripts. Set the SoundBank path of the initializer script.
// This game object will live for the whole project; there is no need to instanciate one per scene.
private static void CreateWwiseGlobalObject()
{
// Look for a game object which has the initializer component
var AkInitializers = UnityEngine.Object.FindObjectsOfType<AkInitializer>();
if (AkInitializers.Length > 0)
UnityEditor.Undo.DestroyObjectImmediate(AkInitializers[0].gameObject);
var WwiseGlobalGameObject = new UnityEngine.GameObject("WwiseGlobal");
// attach initializer component
UnityEditor.Undo.AddComponent<AkInitializer>(WwiseGlobalGameObject);
// Set focus on WwiseGlobal
UnityEditor.Selection.activeGameObject = WwiseGlobalGameObject;
}
private static bool DisableBuiltInAudio()
{
UnityEditor.SerializedObject audioSettingsAsset = null;
UnityEditor.SerializedProperty disableAudioProperty = null;
var assets = UnityEditor.AssetDatabase.LoadAllAssetsAtPath("ProjectSettings/AudioManager.asset");
if (assets.Length > 0)
audioSettingsAsset = new UnityEditor.SerializedObject(assets[0]);
if (audioSettingsAsset != null)
disableAudioProperty = audioSettingsAsset.FindProperty("m_DisableAudio");
if (disableAudioProperty == null)
return false;
disableAudioProperty.boolValue = true;
audioSettingsAsset.ApplyModifiedProperties();
return true;
}
// Modify the .wproj file to set needed SoundBank settings
private static bool SetSoundbankSettings()
{
var settings = AkWwiseEditorSettings.Instance;
if (string.IsNullOrEmpty(settings.WwiseProjectPath))
return true;
var r = new System.Text.RegularExpressions.Regex("_WwiseIntegrationTemp.*?([/\\\\])");
var SoundbankPath = AkUtilities.GetFullPath(r.Replace(UnityEngine.Application.streamingAssetsPath, "$1"), settings.SoundbankPath);
var WprojPath = AkUtilities.GetFullPath(UnityEngine.Application.dataPath, settings.WwiseProjectPath);
#if UNITY_EDITOR_OSX
SoundbankPath = "Z:" + SoundbankPath;
#endif
SoundbankPath = AkUtilities.MakeRelativePath(System.IO.Path.GetDirectoryName(WprojPath), SoundbankPath);
if (AkUtilities.EnableBoolSoundbankSettingInWproj("SoundBankGenerateHeaderFile", WprojPath))
if (AkUtilities.SetSoundbankHeaderFilePath(WprojPath, SoundbankPath))
return AkUtilities.EnableBoolSoundbankSettingInWproj("SoundBankGenerateMaxAttenuationInfo", WprojPath);
return false;
}
}
#endif // UNITY_EDITOR

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: d0d48ff16ff37354cae0635a64035666
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -0,0 +1,39 @@
public static class AkXboxOneUtils
{
private static readonly int[] Usages = { 0, 1, 4, 7 };
private static readonly int SessionRequirement = 0;
private static readonly int[] DeviceUsages = { 0 };
[UnityEditor.MenuItem("Assets/Wwise/Xbox One/Enable Network Sockets")]
public static void EnableXboxOneNetworkSockets()
{
var definitions = new[]
{
new SocketDefinition("WwiseDiscoverySocket", "24024", 1, "WwiseDiscovery"),
new SocketDefinition("WwiseCommandSocket", "24025", 0, "WwiseCommand"),
new SocketDefinition("WwiseNotificationSocket", "24026", 0, "WwiseNotification")
};
foreach (var def in definitions)
{
UnityEditor.PlayerSettings.XboxOne.SetSocketDefinition(def.Name, def.Port, def.Protocol, Usages, def.TemplateName,
SessionRequirement, DeviceUsages);
}
}
private class SocketDefinition
{
public readonly string Name;
public readonly string Port;
public readonly int Protocol;
public readonly string TemplateName;
public SocketDefinition(string name, string port, int protocol, string templateName)
{
Name = name;
Port = port;
Protocol = protocol;
TemplateName = templateName;
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 8924aeb16cd6593468c3e6137eee4659
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant: