diff --git a/Assets/CriData.meta b/Assets/CriData.meta new file mode 100644 index 0000000..8f1a304 --- /dev/null +++ b/Assets/CriData.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 41f1ed3680373bc4d9f545af7285c5dd +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CriData/Settings.meta b/Assets/CriData/Settings.meta new file mode 100644 index 0000000..a61ad58 --- /dev/null +++ b/Assets/CriData/Settings.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: f6ac1c54436d2b544a475c918885ed8f +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/CriData/Settings/CriAtomEditorSettings.asset b/Assets/CriData/Settings/CriAtomEditorSettings.asset new file mode 100644 index 0000000..e6930e4 --- /dev/null +++ b/Assets/CriData/Settings/CriAtomEditorSettings.asset @@ -0,0 +1,85 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!114 &11400000 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 0} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: bdb0b816a0bf0284282bd91a06a57a05, type: 3} + m_Name: CriAtomEditorSettings + m_EditorClassIdentifier: + trySceneSettings: 0 + atomConfig: + acfFileName: + maxVirtualVoices: 32 + maxVoiceLimitGroups: 32 + maxCategories: 32 + maxAisacs: 8 + maxBusSends: 8 + maxSequenceEventsPerFrame: 2 + maxBeatSyncCallbacksPerFrame: 1 + maxCueLinkCallbacksPerFrame: 1 + standardVoicePoolConfig: + memoryVoices: 16 + streamingVoices: 8 + hcaMxVoicePoolConfig: + memoryVoices: 0 + streamingVoices: 0 + outputSamplingRate: 0 + usesInGamePreview: 0 + inGamePreviewMode: 3 + switchInitializeSocket: 0 + inGamePreviewConfig: + maxPreviewObjects: 200 + communicationBufferSize: 2048 + playbackPositionUpdateInterval: 8 + serverFrequency: 60 + asrOutputChannels: 0 + useRandomSeedWithTime: 1 + categoriesPerPlayback: 4 + maxFaders: 4 + maxBuses: 8 + maxParameterBlocks: 1024 + vrMode: 0 + keepPlayingSoundOnPause: 1 + editorPcmOutputConfig: + enable: 0 + bufferLength: 4096 + pcBufferingTime: 0 + linuxOutput: 0 + linuxPulseLatencyUsec: 60000 + iosEnableSonicSync: 1 + iosBufferingTime: 50 + iosOverrideIPodMusic: 0 + androidEnableSonicSync: 1 + androidBufferingTime: 133 + androidStartBufferingTime: 100 + androidLowLatencyStandardVoicePoolConfig: + memoryVoices: 0 + streamingVoices: 0 + androidUsesAndroidFastMixer: 1 + androidForceToUseAsrForDefaultPlayback: 1 + androidUsesAAudio: 0 + vitaManaVoicePoolConfig: + numberOfManaDecoders: 8 + vitaAtrac9VoicePoolConfig: + memoryVoices: 0 + streamingVoices: 0 + ps4Atrac9VoicePoolConfig: + memoryVoices: 0 + streamingVoices: 0 + switchEnableSonicSync: 1 + switchOpusVoicePoolConfig: + memoryVoices: 0 + streamingVoices: 0 + ps4Audio3dConfig: + useAudio3D: 0 + voicePoolConfig: + memoryVoices: 0 + streamingVoices: 0 + webglWebAudioVoicePoolConfig: + voices: 16 diff --git a/Assets/CriData/Settings/CriAtomEditorSettings.asset.meta b/Assets/CriData/Settings/CriAtomEditorSettings.asset.meta new file mode 100644 index 0000000..15a5e36 --- /dev/null +++ b/Assets/CriData/Settings/CriAtomEditorSettings.asset.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: cb7519de6d9d6414aa654607e19f59bb +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 11400000 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW.meta b/Assets/Scripts/CRIMW.meta new file mode 100644 index 0000000..2cbbbe3 --- /dev/null +++ b/Assets/Scripts/CRIMW.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 994dd8b8169af3646809acee61a0902e +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare.meta b/Assets/Scripts/CRIMW/CriWare.meta new file mode 100644 index 0000000..ae3a4c4 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 6a05db99aed6ec949adfc390a40edb58 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Editor.meta b/Assets/Scripts/CRIMW/CriWare/Editor.meta new file mode 100644 index 0000000..1d62781 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Editor.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 886ff5893aa663a46a61c7bfa6514e0e +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom.meta b/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom.meta new file mode 100644 index 0000000..ead793b --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 9961547ad1dabaa4681e59243bd8afdf +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/CriAtomEditor.cs b/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/CriAtomEditor.cs new file mode 100644 index 0000000..31a8ff0 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/CriAtomEditor.cs @@ -0,0 +1,92 @@ +/**************************************************************************** + * + * Copyright (c) 2011 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +using UnityEngine; +using UnityEditor; +using System; + +namespace CriWare { + +[CustomEditor(typeof(CriAtom))] +public class CriAtomEditor : UnityEditor.Editor +{ + #region Variables + private CriAtom atom = null; + #endregion + + #region GUI Functions + private void OnEnable() + { + atom = (CriAtom)base.target; + } + + public override void OnInspectorGUI() + { + if (atom == null) { + return; + } + + Undo.RecordObject(target, null); + + GUI.changed = false; + { + atom.acfFile = EditorGUILayout.TextField("ACF File", atom.acfFile); + atom.dspBusSetting = EditorGUILayout.TextField("DSP Bus Setting", atom.dspBusSetting); + + for (int i = 0; i < atom.cueSheets.Length; i++) { + var cueSheet = atom.cueSheets[i]; + EditorGUILayout.BeginVertical("HelpBox"); + EditorGUILayout.BeginHorizontal(); + EditorGUILayout.PrefixLabel("Cue Sheet"); + if (GUILayout.Button("Remove")) { + atom.RemoveCueSheetInternal(cueSheet.name); + break; + } + EditorGUILayout.EndHorizontal(); + EditorGUI.indentLevel++; + cueSheet.name = EditorGUILayout.TextField("Name", cueSheet.name); + cueSheet.acbFile = EditorGUILayout.TextField("ACB File", cueSheet.acbFile); + cueSheet.awbFile = EditorGUILayout.TextField("AWB File", cueSheet.awbFile); + EditorGUI.indentLevel--; + EditorGUILayout.EndVertical(); + } + if (GUILayout.Button("Add CueSheet")) { + atom.AddCueSheetInternal("", "", "", null); + } + + atom.dontRemoveExistsCueSheet = EditorGUILayout.Toggle("Dont Remove Exists CueSheet", atom.dontRemoveExistsCueSheet); + atom.dontDestroyOnLoad = EditorGUILayout.Toggle("Dont Destroy On Load", atom.dontDestroyOnLoad); + } + if (GUI.changed) { + EditorUtility.SetDirty(atom); + } + } + #endregion + + #region Editor Utilities + /** + * \deprecated + * This is a deprecated API that will be removed. + * Please consider using CriAtomEditorUtilities.InitializeLibrary() instead. + */ + [Obsolete("Consider using CriAtomEditorUtilities.InitializeLibrary() instead.")] + public static void InitializePluginForEditor() { + CriWare.Editor.CriAtomEditorUtilities.InitializeLibrary(); + } + + /** + * \deprecated + * This is a deprecated API that will be removed. + * Please consider using CriAtomEditorUtilities.PreviewPlayer instead. + */ + [Obsolete("Consider using CriAtomEditorUtilities.PreviewPlayer instead.")] + public class PreviewPlayer : CriWare.Editor.CriAtomEditorUtilities.PreviewPlayer { } + #endregion +} // end of class + +} //namespace CriWare + +/* end of file */ \ No newline at end of file diff --git a/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/CriAtomEditor.cs.meta b/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/CriAtomEditor.cs.meta new file mode 100644 index 0000000..5ee304a --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/CriAtomEditor.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 4580729b648468042bc67394cbfe5c75 +timeCreated: 1433816076 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/CriAtomEditorSettings.cs b/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/CriAtomEditorSettings.cs new file mode 100644 index 0000000..523f722 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/CriAtomEditorSettings.cs @@ -0,0 +1,153 @@ +/**************************************************************************** + * + * Copyright (c) CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +using System.Collections.Generic; +using UnityEngine; +using UnityEditor; + + +namespace CriWare.Editor { + + public class CriAtomEditorSettingsProvider : SettingsProvider + { + static readonly string settingPath = "Project/CRIWARE/Editor/Atom Preview"; + + public CriAtomEditorSettingsProvider(string path, SettingsScope scope) : base(path, scope) { } + + public override void OnGUI(string searchContext) { + EditorGUI.indentLevel++; + EditorGUILayout.Space(); + EditorGUILayout.LabelField("Library Initialization Settings for Audio Previewing in the Editor", EditorStyles.boldLabel); + EditorGUI.indentLevel++; + EditorGUILayout.Space(); + CriAtomEditorSettings.Instance.EditorInstance.OnInspectorGUI(); + EditorGUI.indentLevel -= 2; + } + + [SettingsProvider] + static SettingsProvider Create() { + var provider = new CriAtomEditorSettingsProvider(settingPath, SettingsScope.Project); + return provider; + } + } //class CriAtomEditorSettingsProvider + + public class CriAtomEditorSettings : ScriptableObject + { + static readonly string SettingsDirPath = "Assets/CriData/Settings"; + static CriAtomEditorSettings instance = null; + + private UnityEditor.Editor editorInstance = null; + internal UnityEditor.Editor EditorInstance { + get { + if (editorInstance == null) { + editorInstance = UnityEditor.Editor.CreateEditor(this); + } + return editorInstance; + } + } + + private bool hasSettingsChanged = false; + internal void SetChangeFlag() { hasSettingsChanged = true; } + internal bool GetChangeStatusOnce() { + bool currentChangeStatus = hasSettingsChanged; + hasSettingsChanged = false; + return currentChangeStatus; + } + + [SerializeField] + private bool trySceneSettings = false; + internal bool TrySceneSettings { get { return trySceneSettings; } } + + [SerializeField] + private CriAtomConfig atomConfig = new CriAtomConfig(); + internal CriAtomConfig AtomConfig { get { return atomConfig; } } + + internal static CriAtomEditorSettings Instance { + get { + if (instance == null) { + var guids = AssetDatabase.FindAssets("t:" + typeof(CriAtomEditorSettings).Name); + if (guids.Length <= 0) { + if (!System.IO.Directory.Exists(SettingsDirPath)) { + System.IO.Directory.CreateDirectory(SettingsDirPath); + } + instance = CreateInstance(); + AssetDatabase.CreateAsset(instance, System.IO.Path.Combine(SettingsDirPath, typeof(CriAtomEditorSettings).Name + ".asset")); + } else { + var assetPath = AssetDatabase.GUIDToAssetPath(guids[0]); + if (guids.Length > 1) { + Debug.LogWarning("[CRIWARE] Multiple setting files founded. Using " + assetPath); + } + instance = AssetDatabase.LoadAssetAtPath(assetPath); + } + } + return instance; + } + } + + internal void ResetConfig() { + atomConfig = new CriAtomConfig(); + } + } //class CriAtomEditorSettings + + [CustomEditor(typeof(CriAtomEditorSettings))] + public class CriAtomEditorSettingsEditor : UnityEditor.Editor + { + private SerializedProperty trySceneSettingsProp; + private List atomConfigProps = new List(); + + private void OnEnable() { + trySceneSettingsProp = serializedObject.FindProperty("trySceneSettings"); + + atomConfigProps.Add(serializedObject.FindProperty("atomConfig.maxVirtualVoices")); + atomConfigProps.Add(serializedObject.FindProperty("atomConfig.maxVoiceLimitGroups")); + atomConfigProps.Add(serializedObject.FindProperty("atomConfig.maxCategories")); + atomConfigProps.Add(serializedObject.FindProperty("atomConfig.maxSequenceEventsPerFrame")); + atomConfigProps.Add(serializedObject.FindProperty("atomConfig.maxBeatSyncCallbacksPerFrame")); + atomConfigProps.Add(serializedObject.FindProperty("atomConfig.maxCueLinkCallbacksPerFrame")); + atomConfigProps.Add(serializedObject.FindProperty("atomConfig.standardVoicePoolConfig")); + atomConfigProps.Add(serializedObject.FindProperty("atomConfig.hcaMxVoicePoolConfig")); + atomConfigProps.Add(serializedObject.FindProperty("atomConfig.outputSamplingRate")); + atomConfigProps.Add(serializedObject.FindProperty("atomConfig.serverFrequency")); + atomConfigProps.Add(serializedObject.FindProperty("atomConfig.asrOutputChannels")); + atomConfigProps.Add(serializedObject.FindProperty("atomConfig.useRandomSeedWithTime")); + atomConfigProps.Add(serializedObject.FindProperty("atomConfig.categoriesPerPlayback")); + atomConfigProps.Add(serializedObject.FindProperty("atomConfig.maxFaders")); + atomConfigProps.Add(serializedObject.FindProperty("atomConfig.maxBuses")); + atomConfigProps.Add(serializedObject.FindProperty("atomConfig.maxParameterBlocks")); + atomConfigProps.Add(serializedObject.FindProperty("atomConfig.vrMode")); + atomConfigProps.Add(serializedObject.FindProperty("atomConfig.pcBufferingTime")); + } + + public override void OnInspectorGUI() { + const float LABEL_WIDTH = 250; + float prevLabelWidth; + + serializedObject.Update(); + prevLabelWidth = EditorGUIUtility.labelWidth; + EditorGUIUtility.labelWidth = LABEL_WIDTH; + EditorGUILayout.PropertyField(trySceneSettingsProp); + if (trySceneSettingsProp.boolValue) { + EditorGUILayout.HelpBox("Will use project settings if CriLibraryInitializer does not exist in the scene.", MessageType.Info); + } + EditorGUILayout.Space(); + foreach (var prop in atomConfigProps) { + EditorGUILayout.PropertyField(prop); + } + EditorGUIUtility.labelWidth = prevLabelWidth; + if (serializedObject.hasModifiedProperties) { + (target as CriAtomEditorSettings).SetChangeFlag(); + } + serializedObject.ApplyModifiedProperties(); + + EditorGUILayout.Space(); + if (GUILayout.Button("Reset to Default")) { + (target as CriAtomEditorSettings).ResetConfig(); + (target as CriAtomEditorSettings).SetChangeFlag(); + } + } + } //class CriAtomEditorSettingsEditor + +} //namespace CriWare.Editor \ No newline at end of file diff --git a/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/CriAtomEditorSettings.cs.meta b/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/CriAtomEditorSettings.cs.meta new file mode 100644 index 0000000..d87d47b --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/CriAtomEditorSettings.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: bdb0b816a0bf0284282bd91a06a57a05 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/CriAtomEditorUtilities.cs b/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/CriAtomEditorUtilities.cs new file mode 100644 index 0000000..a5c81c9 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/CriAtomEditorUtilities.cs @@ -0,0 +1,192 @@ +/**************************************************************************** + * + * Copyright (c) 2021 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +using System.Collections.Generic; +using UnityEngine; +using UnityEditor; +using System; + +/** + * \addtogroup CRIWARE_EDITOR_UTILITY + * @{ + */ + +/** + * CriWare.Editor namespace + * + * This is a namespace which includes a collection of classes that can be used in the Unity Editor environment. + * + */ +namespace CriWare.Editor { + +/** + * Class for the editor-only features of CRI Atom + * + * Class that contains the editor-specific functions of CRI Atom. + * When using this class with the Assembly Definition version plug-in,
+ * it is necessary to reference the following assembly definitions:
+ * - CriMw.CriWare.Editor
+ * - CriMw.CriWare.Runtime
+ *
+ */ +public class CriAtomEditorUtilities +{ + /** + * Initialize the CRI Atom library in the editor + * Whether the initialization process was executed + * + * This method is used to initialize the CRI Atom library dedicated to the Edit mode.
+ * The Atom library will be initialized according to the Atom editor settings in the project settings.
+ * Depending on the project settings, it is also possible to initialize + * using the settings of the CriWareInitializer component in the currently loaded scene.
+ *
+ */ + public static bool InitializeLibrary() { + bool settingChanged = CriAtomEditorSettings.Instance.GetChangeStatusOnce(); + if (CriAtomPlugin.IsLibraryInitialized() && settingChanged == false) { + return false; + } + if (settingChanged) { + CriAtomPlugin.FinalizeLibrary(); + } + + CriAtomConfig atomConfigEditor; + if (CriAtomEditorSettings.Instance.TrySceneSettings == false) { + atomConfigEditor = CriAtomEditorSettings.Instance.AtomConfig; + } else { + CriWareInitializer criInitializer = GameObject.FindObjectOfType(); + if (criInitializer != null) { + atomConfigEditor = criInitializer.atomConfig; + } else { + atomConfigEditor = CriAtomEditorSettings.Instance.AtomConfig; + Debug.Log("[CRIWARE] Atom Preview: No CriWareInitializer component found in current scene. " + + "Using project settings instead."); + } + } + return CriWareInitializer.InitializeAtom(atomConfigEditor); + } + + /** + * Audio player dedicated to previewing in the editor + * + * This class is used to preview the playback of ADX2 audio in the Edit mode.
+ * The loading of the relevant ACB data must be managed externally.
+ *
+ */ + public class PreviewPlayer : CriDisposable { + public CriAtomExPlayer player { get; private set; } + private bool finalizeSuppressed = false; + private bool isPlayerReady = false; + + private void Initialize() { + CriAtomEditorUtilities.InitializeLibrary(); + if (CriAtomPlugin.IsLibraryInitialized() == false) { return; } + + player = new CriAtomExPlayer(); + if (player == null) { return; } + + player.SetPanType(CriAtomEx.PanType.Pan3d); + player.UpdateAll(); + + isPlayerReady = true; + + CriDisposableObjectManager.Register(this, CriDisposableObjectManager.ModuleType.Atom); + + if (finalizeSuppressed) { + GC.ReRegisterForFinalize(this); + } + } + + /** + * Initialization of the player + */ + public PreviewPlayer() { + Initialize(); + } + + /** + * Destroying the player + */ + public override void Dispose() { + this.dispose(); + GC.SuppressFinalize(this); + finalizeSuppressed = true; + } + + private void dispose() { + CriDisposableObjectManager.Unregister(this); + if (player != null) { + player.Dispose(); + player = null; + } + this.isPlayerReady = false; + } + + ~PreviewPlayer() { + this.dispose(); + } + + /** + * Set the audio data and play + * ACB data + * Cue name + * + * Specify the ACB data and Cue name and then play. + * + */ + public void Play(CriAtomExAcb acb, string cueName) { + if (isPlayerReady == false) { + this.Initialize(); + } + + if (acb != null) { + if (player != null) { + player.SetCue(acb, cueName); + player.Start(); + } else { + Debug.LogWarning("[CRIWARE] Player is not ready. Please try reloading the inspector / editor window"); + } + } else { + Debug.LogWarning("[CRIWARE] ACB data is not set for previewing playback"); + } + } + + /** + * Stops the playback + * Whether to stop without release time + * + * Stops all audio playback. + * + */ + public void Stop(bool withoutRelease = false) { + if (player != null) { + if (withoutRelease) { + player.StopWithoutReleaseTime(); + } else { + player.Stop(); + } + } + } + + /** + * Resets the parameters of the player + */ + public void ResetPlayer() { + player.SetVolume(1f); + player.SetPitch(0); + player.Loop(false); + } + } + +} // end of class + +} //namespace CriWare.Editor + +/** + * @} + */ + +/* end of file */ \ No newline at end of file diff --git a/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/CriAtomEditorUtilities.cs.meta b/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/CriAtomEditorUtilities.cs.meta new file mode 100644 index 0000000..7e6e9e3 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/CriAtomEditorUtilities.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 15f32809ca2a1cf40982c3336cc81366 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/CriAtomListenerEditor.cs b/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/CriAtomListenerEditor.cs new file mode 100644 index 0000000..ee0f28a --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/CriAtomListenerEditor.cs @@ -0,0 +1,18 @@ +/**************************************************************************** + * + * Copyright (c) 2011 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +using UnityEditor; + +namespace CriWare { + +[CustomEditor(typeof(CriAtomListener))] +public class CriAtomListenerEditor : UnityEditor.Editor +{ +} // end of class + +} //namespace CriWare + +/* end of file */ diff --git a/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/CriAtomListenerEditor.cs.meta b/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/CriAtomListenerEditor.cs.meta new file mode 100644 index 0000000..243ca35 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/CriAtomListenerEditor.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: f7ddeb461d32378408896179255bf0cd +timeCreated: 1433816082 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/CriAtomSourceBaseEditor.cs b/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/CriAtomSourceBaseEditor.cs new file mode 100644 index 0000000..0fb9aa3 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/CriAtomSourceBaseEditor.cs @@ -0,0 +1,133 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using UnityEditor; + +namespace CriWare { + public abstract class CriAtomSourceBaseEditor : UnityEditor.Editor + { + #region Variables + protected CriAtomSourceBase source = null; + private bool showAndroidConfig; + private GUIStyle style; + + private SerializedProperty m_followsOriginalSource; + private SerializedProperty m_calculationType; + private SerializedProperty m_calculationParameters; + #endregion + + #region Functions + protected virtual void OnEnable() + { + this.source = (CriAtomSourceBase)base.target; + this.style = new GUIStyle(); + m_followsOriginalSource = serializedObject.FindProperty("randomize3dConfig.followsOriginalSource"); + m_calculationType = serializedObject.FindProperty("randomize3dConfig.calculationType"); + m_calculationParameters = serializedObject.FindProperty("randomize3dConfig.calculationParameters"); + } + + protected abstract void InspectorCueReferenceGUI(); + protected abstract void InspectorPreviewGUI(); + + public override void OnInspectorGUI() + { + if (this.source == null) + { + return; + } + + Undo.RecordObject(target, null); + + GUI.changed = false; + { + EditorGUI.indentLevel++; + InspectorCueReferenceGUI(); + InspectorPreviewGUI(); + this.source.playOnStart = EditorGUILayout.Toggle("Play On Start", this.source.playOnStart); + EditorGUILayout.Space(); + this.source.volume = EditorGUILayout.Slider("Volume", this.source.volume, 0.0f, 1.0f); + this.source.pitch = EditorGUILayout.Slider("Pitch", this.source.pitch, -1200f, 1200); + this.source.loop = EditorGUILayout.Toggle("Loop", this.source.loop); + if (this.source.use3dPositioning = EditorGUILayout.Toggle("3D Positioning", this.source.use3dPositioning)) + { + EditorGUI.indentLevel++; + this.source.freezeOrientation = EditorGUILayout.Toggle("Freeze Orientation", this.source.freezeOrientation); + this.source.regionOnStart = EditorGUILayout.ObjectField("Region On Start", this.source.regionOnStart, typeof(CriAtomRegion), true) as CriAtomRegion; + this.source.listenerOnStart = EditorGUILayout.ObjectField("Listener On Start", this.source.listenerOnStart, typeof(CriAtomListener), true) as CriAtomListener; + bool tempRandomizeSetting = EditorGUILayout.Toggle("3D Randomization", this.source.use3dRandomization); + if (tempRandomizeSetting != this.source.use3dRandomization) + { + this.source.use3dRandomization = tempRandomizeSetting; + } + if (this.source.use3dRandomization) + { + EditorGUILayout.BeginVertical("HelpBox"); + EditorGUI.indentLevel++; + EditorGUI.BeginChangeCheck(); + this.m_followsOriginalSource.boolValue = EditorGUILayout.Toggle("Follow origin", this.m_followsOriginalSource.boolValue); + var calcType = (int)(CriAtomEx.Randomize3dCalcType)EditorGUILayout.EnumPopup("Type", (CriAtomEx.Randomize3dCalcType)this.m_calculationType.intValue); + if (calcType != this.m_calculationType.intValue) + { + this.m_calculationType.intValue = calcType; + /* set new parameter to 1 */ + for (int i = 0; i < CriAtomEx.Randomize3dConfig.NumOfCalcParams; ++i) + { + if (this.m_calculationParameters.GetArrayElementAtIndex(i).floatValue <= 0f) + { + this.m_calculationParameters.GetArrayElementAtIndex(i).floatValue = 1f; + } + } + } + for (int i = 0; i < CriAtomEx.Randomize3dConfig.NumOfCalcParams; ++i) + { + var paramType = CriAtomEx.randomize3dParamTable[(CriAtomEx.Randomize3dCalcType)m_calculationType.intValue][i]; + if (paramType == CriAtomEx.Randomize3dParamType.None) + { + this.m_calculationParameters.GetArrayElementAtIndex(i).floatValue = 0f; + continue; + } + this.m_calculationParameters.GetArrayElementAtIndex(i).floatValue = EditorGUILayout.FloatField(paramType.ToString(), this.m_calculationParameters.GetArrayElementAtIndex(i).floatValue); + } + switch ((CriAtomEx.Randomize3dCalcType)m_calculationType.intValue) + { + case CriAtomEx.Randomize3dCalcType.List: + var templength = (uint)Mathf.Abs(EditorGUILayout.IntField("Max length of list", (int)this.source.randomPositionListMaxLength)); + if (templength != this.source.randomPositionListMaxLength) + { + this.source.randomPositionListMaxLength = templength; + } + EditorGUILayout.HelpBox("Please set the list of positions by using CriAtomSource.SetRandomPositionList()", MessageType.Info); + break; + default: + break; + } + if (EditorGUI.EndChangeCheck()) + { + serializedObject.ApplyModifiedProperties(); + this.source.use3dRandomization = this.source.use3dRandomization; /* apply change */ + } + EditorGUI.indentLevel--; + EditorGUILayout.EndVertical(); + } + EditorGUI.indentLevel--; + } + + this.showAndroidConfig = EditorGUILayout.Foldout(this.showAndroidConfig, "Android Config"); + if (this.showAndroidConfig) + { + EditorGUI.indentLevel++; + EditorGUILayout.BeginHorizontal(); + style.stretchWidth = true; + this.source.androidUseLowLatencyVoicePool = EditorGUILayout.Toggle("Low Latency Playback", this.source.androidUseLowLatencyVoicePool); + EditorGUILayout.EndHorizontal(); + EditorGUI.indentLevel--; + } + } + if (GUI.changed) + { + EditorUtility.SetDirty(this.source); + } + } + #endregion + } // end of class +} // namespace CriWare diff --git a/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/CriAtomSourceBaseEditor.cs.meta b/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/CriAtomSourceBaseEditor.cs.meta new file mode 100644 index 0000000..9140ac6 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/CriAtomSourceBaseEditor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b656357d81bf0d0408dc264ac483ccf4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/CriAtomSourceEditor.cs b/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/CriAtomSourceEditor.cs new file mode 100644 index 0000000..b3bd616 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/CriAtomSourceEditor.cs @@ -0,0 +1,117 @@ +/**************************************************************************** + * + * Copyright (c) 2014 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +#define CRI_UNITY_EDITOR_PREVIEW + +using UnityEngine; +using UnityEditor; +using System.IO; + +namespace CriWare { + +[CustomEditor(typeof(CriAtomSource))] +public class CriAtomSourceEditor : CriAtomSourceBaseEditor { + #region Variables +#if CRI_UNITY_EDITOR_PREVIEW + public CriAtom atomComponent; + private CriWare.Editor.CriAtomEditorUtilities.PreviewPlayer previewPlayer; + private string strPreviewAcb = null; + private string strPreviewAwb = null; + private CriAtomExAcb previewAcb = null; + private string lastCuesheet = ""; +#endif + #endregion + + #region Functions + + protected override void OnEnable() + { + base.OnEnable(); + +#if CRI_UNITY_EDITOR_PREVIEW + /* シーンからCriAtomコンポーネントを見つけ出す */ + atomComponent = (CriAtom)FindObjectOfType(typeof(CriAtom)); +#endif + previewPlayer = new CriWare.Editor.CriAtomEditorUtilities.PreviewPlayer(); + } + + private void OnDisable() { + if (previewAcb != null) { + previewAcb.Dispose(); + previewAcb = null; + } + lastCuesheet = ""; + if (previewPlayer != null) { + previewPlayer.Dispose(); + previewPlayer = null; + } + } + + protected override void InspectorCueReferenceGUI() + { + (source as CriAtomSource).cueSheet = EditorGUILayout.TextField("Cue Sheet", (source as CriAtomSource).cueSheet); + (source as CriAtomSource).cueName = EditorGUILayout.TextField("Cue Name", (source as CriAtomSource).cueName); + } + + protected override void InspectorPreviewGUI() + { +#if CRI_UNITY_EDITOR_PREVIEW + GUI.enabled = false; + atomComponent = (CriAtom)EditorGUILayout.ObjectField("CriAtom Object", atomComponent, typeof(CriAtom), true); + GUI.enabled = (atomComponent != null); + GUILayout.BeginHorizontal(); + { + EditorGUILayout.LabelField("Preview", GUILayout.MaxWidth(EditorGUIUtility.labelWidth - 5)); + if (GUILayout.Button("Play", GUILayout.MaxWidth(60))) { + this.StartPreviewPlayer(); + } + if (GUILayout.Button("Stop", GUILayout.MaxWidth(60))) { + this.previewPlayer.Stop(); + } + } + GUILayout.EndHorizontal(); + GUI.enabled = true; +#endif + } + +#if CRI_UNITY_EDITOR_PREVIEW + /* プレビュ用:音声データ設定・再生関数 */ + private void StartPreviewPlayer() { + if (previewPlayer == null) { + return; + } + + if (lastCuesheet != (source as CriAtomSource).cueSheet) { + if (previewAcb != null) { + previewAcb.Dispose(); + previewAcb = null; + } + foreach (var cuesheet in atomComponent.cueSheets) { + if (cuesheet.name == (source as CriAtomSource).cueSheet) { + strPreviewAcb = Path.Combine(CriWare.Common.streamingAssetsPath, cuesheet.acbFile); + strPreviewAwb = (cuesheet.awbFile == null) ? null : Path.Combine(CriWare.Common.streamingAssetsPath, cuesheet.awbFile); + previewAcb = CriAtomExAcb.LoadAcbFile(null, strPreviewAcb, strPreviewAwb); + lastCuesheet = cuesheet.name; + } + } + } + if (previewAcb != null) { + previewPlayer.player.SetVolume(this.source.volume); + previewPlayer.player.SetPitch(this.source.pitch); + previewPlayer.player.Loop(this.source.loop); + previewPlayer.Play(previewAcb, (source as CriAtomSource).cueName); + } else { + Debug.LogWarning("[CRIWARE] Specified cue sheet could not be found"); + } + } +#endif + + #endregion +} + +} //namespace CriWare + +/* end of file */ diff --git a/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/CriAtomSourceEditor.cs.meta b/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/CriAtomSourceEditor.cs.meta new file mode 100644 index 0000000..e53c183 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/CriAtomSourceEditor.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: b7ba25dde88df304ea6345254cb82626 +timeCreated: 1433816076 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/CriAtomTransceiverEditor.cs b/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/CriAtomTransceiverEditor.cs new file mode 100644 index 0000000..48c2ed7 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/CriAtomTransceiverEditor.cs @@ -0,0 +1,221 @@ +/**************************************************************************** + * + * Copyright (c) 2020 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +using System.Reflection; +using UnityEditor; +using UnityEngine; + +namespace CriWare { + +[CustomEditor(typeof(CriAtomTransceiver)), CanEditMultipleObjects] +public class CriAtomTransceiverEditor : UnityEditor.Editor { + /* parameters */ + private SerializedProperty m_regionOnStart; + private SerializedProperty m_useDedicatedInput; + private SerializedProperty m_dedicatedInput; + private SerializedProperty m_outputVolume; + private SerializedProperty m_directAudioRadius; + private SerializedProperty m_crossFadeDistance; + private SerializedProperty m_coneInsideAngle; + private SerializedProperty m_coneOutsideAngle; + private SerializedProperty m_coneOutsideVolume; + private SerializedProperty m_transceiverRadius; + private SerializedProperty m_interiorDistance; + private SerializedProperty m_minAttenuation; + private SerializedProperty m_maxAttenuation; + private SerializedProperty m_globalAisacName; + private SerializedProperty m_maxAngleAisacDelta; + private SerializedProperty m_distanceAisacControlId; + private SerializedProperty m_listenerAzimuthAisacControlId; + private SerializedProperty m_listenerElevationAisacControlId; + private SerializedProperty m_outputAzimuthAisacControlId; + private SerializedProperty m_outputElevationAisacControlId; + private MethodInfo m_applyParametersMethod; + + static private readonly GUIContent cUseDedicatedInputLabel = new GUIContent("Use Dedicated Input", "Use another game object as input position"); + static private readonly GUIContent cTranceiverRadiusLabel = new GUIContent("Non-Panning Radius"); + static private readonly GUIContent cConeInsideAngleLabel = new GUIContent("Inside"); + static private readonly GUIContent cConeOutsideAngle = new GUIContent("Outside"); + static private readonly GUIContent cDistanceAisacLabel = new GUIContent("Distance"); + static private readonly GUIContent cListenerAzimuthAisacLabel = new GUIContent("Listener Azimuth Angle"); + static private readonly GUIContent cListenerElevationAisacLabel = new GUIContent("Listener Elevation Angle"); + static private readonly GUIContent cOutputAzimuthAisacLabel = new GUIContent("Output Azimuth Angle"); + static private readonly GUIContent cOutputElevationAisacLabel = new GUIContent("Output Elevation Angle"); + + private void OnEnable() { + m_regionOnStart = serializedObject.FindProperty("regionOnStart"); + m_useDedicatedInput = serializedObject.FindProperty("useDedicatedInput"); + m_dedicatedInput = serializedObject.FindProperty("dedicatedInput"); + m_outputVolume = serializedObject.FindProperty("outputVolume"); + m_directAudioRadius = serializedObject.FindProperty("directAudioRadius"); + m_crossFadeDistance = serializedObject.FindProperty("crossFadeDistance"); + m_coneInsideAngle = serializedObject.FindProperty("coneInsideAngle"); + m_coneOutsideAngle = serializedObject.FindProperty("coneOutsideAngle"); + m_coneOutsideVolume = serializedObject.FindProperty("coneOutsideVolume"); + m_transceiverRadius = serializedObject.FindProperty("transceiverRadius"); + m_interiorDistance = serializedObject.FindProperty("interiorDistance"); + m_minAttenuation = serializedObject.FindProperty("minAttenuation"); + m_maxAttenuation = serializedObject.FindProperty("maxAttenuation"); + m_globalAisacName = serializedObject.FindProperty("globalAisacName"); + m_maxAngleAisacDelta = serializedObject.FindProperty("maxAngleAisacDelta"); + m_distanceAisacControlId = serializedObject.FindProperty("distanceAisacControlId"); + m_listenerAzimuthAisacControlId = serializedObject.FindProperty("listenerAzimuthAisacControlId"); + m_listenerElevationAisacControlId = serializedObject.FindProperty("listenerElevationAisacControlId"); + m_outputAzimuthAisacControlId = serializedObject.FindProperty("outputAzimuthAisacControlId"); + m_outputElevationAisacControlId = serializedObject.FindProperty("outputElevationAisacControlId"); + + m_applyParametersMethod = typeof(CriAtomTransceiver).GetMethod("ApplyParameters", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance); + } + + public override void OnInspectorGUI() { + var targetObj = target as CriAtomTransceiver; + + EditorGUILayout.PropertyField(m_regionOnStart); + EditorGUILayout.Space(); + + EditorGUILayout.PropertyField(m_useDedicatedInput, cUseDedicatedInputLabel); + if (m_useDedicatedInput.boolValue) { + EditorGUI.indentLevel++; + EditorGUILayout.PropertyField(m_dedicatedInput); + EditorGUI.indentLevel--; + } + EditorGUILayout.Space(); + EditorGUILayout.PropertyField(m_outputVolume); + EditorGUILayout.Space(); + + EditorGUILayout.LabelField("Transceiving"); + EditorGUI.indentLevel++; + EditorGUILayout.PropertyField(m_directAudioRadius); + EditorGUILayout.PropertyField(m_crossFadeDistance); + EditorGUI.indentLevel--; + EditorGUILayout.Space(); + + EditorGUILayout.LabelField("Cone Angles"); + EditorGUI.indentLevel++; + EditorGUILayout.PropertyField(m_coneInsideAngle, cConeInsideAngleLabel); + EditorGUILayout.PropertyField(m_coneOutsideAngle, cConeOutsideAngle); + using (var hScope = new EditorGUILayout.HorizontalScope()) { + EditorGUILayout.PrefixLabel(" "); + if (GUILayout.Button("Set to Omni-Directional", GUILayout.Width(150))) { + m_coneInsideAngle.floatValue = 360f; + m_coneOutsideAngle.floatValue = 360f; + } + } + EditorGUI.indentLevel--; + EditorGUILayout.PropertyField(m_coneOutsideVolume); + EditorGUILayout.Space(); + + EditorGUILayout.LabelField("Panning"); + EditorGUI.indentLevel++; + EditorGUILayout.PropertyField(m_transceiverRadius, cTranceiverRadiusLabel); + EditorGUILayout.PropertyField(m_interiorDistance); + EditorGUI.indentLevel--; + EditorGUILayout.Space(); + + EditorGUILayout.LabelField("Attenuation"); + EditorGUI.indentLevel++; + EditorGUILayout.PropertyField(m_minAttenuation); + EditorGUILayout.PropertyField(m_maxAttenuation); + EditorGUI.indentLevel--; + EditorGUILayout.Space(); + + if (targetObj.inspectorAisacSettingFoldout = EditorGUILayout.Foldout(targetObj.inspectorAisacSettingFoldout, "AISAC")) { + EditorGUI.indentLevel++; + EditorGUILayout.PropertyField(m_globalAisacName); + EditorGUILayout.PropertyField(m_maxAngleAisacDelta); + EditorGUILayout.LabelField("AISAC Control IDs"); + EditorGUI.indentLevel++; + EditorGUILayout.PropertyField(m_distanceAisacControlId, cDistanceAisacLabel); + EditorGUILayout.PropertyField(m_listenerAzimuthAisacControlId, cListenerAzimuthAisacLabel); + EditorGUILayout.PropertyField(m_listenerElevationAisacControlId, cListenerElevationAisacLabel); + EditorGUILayout.PropertyField(m_outputAzimuthAisacControlId, cOutputAzimuthAisacLabel); + EditorGUILayout.PropertyField(m_outputElevationAisacControlId, cOutputElevationAisacLabel); + EditorGUI.indentLevel -= 2; + } + + if (GUI.changed) { + ValidateParameters(); + serializedObject.ApplyModifiedProperties(); + if (m_applyParametersMethod != null) { + m_applyParametersMethod.Invoke(targetObj, null); + } + } + } + + private void ValidateParameters() { + if (m_outputVolume.floatValue < 0) { m_outputVolume.floatValue = 0; } + if (m_directAudioRadius.floatValue < 0) { m_directAudioRadius.floatValue = 0; } + if (m_crossFadeDistance.floatValue < 0) { m_crossFadeDistance.floatValue = 0; } + m_coneInsideAngle.floatValue = Mathf.Clamp(m_coneInsideAngle.floatValue, 0, 360); + m_coneOutsideAngle.floatValue = Mathf.Clamp(m_coneOutsideAngle.floatValue, 0, 360); + m_coneInsideAngle.floatValue = Mathf.Min(m_coneInsideAngle.floatValue, m_coneOutsideAngle.floatValue); + if (m_coneOutsideVolume.floatValue < 0) { m_coneOutsideVolume.floatValue = 0; } + if (m_transceiverRadius.floatValue < 0) { m_transceiverRadius.floatValue = 0; } + if (m_interiorDistance.floatValue < 0) { m_interiorDistance.floatValue = 0; } + if (m_minAttenuation.floatValue < 0) { m_minAttenuation.floatValue = 0; } + if (m_maxAttenuation.floatValue < 0) { m_maxAttenuation.floatValue = 0; } + m_minAttenuation.floatValue = Mathf.Min(m_minAttenuation.floatValue, m_maxAttenuation.floatValue); + if (m_maxAngleAisacDelta.floatValue < 0) { m_maxAngleAisacDelta.floatValue = 0; } + } + + private void OnSceneGUI() { + var targetObj = target as CriAtomTransceiver; + if (targetObj.enabled == false) { return; } + + var transformObj = targetObj.transform; + var outsideArcStartVector = Quaternion.AngleAxis(-m_coneOutsideAngle.floatValue / 2f, transformObj.up) * transformObj.forward; + var insideArcStartVector = Quaternion.AngleAxis(-m_coneInsideAngle.floatValue / 2f, transformObj.up) * transformObj.forward; + float screenSpaceConstant = Mathf.Min(HandleUtility.GetHandleSize(transformObj.position) * 3, targetObj.maxAttenuation); + var dedicatedInput = m_dedicatedInput.objectReferenceValue as GameObject; + + Handles.color = new Color(1, 1, 1, 0.3f); + Handles.DrawDottedLine(transformObj.position, transformObj.position + transformObj.forward * screenSpaceConstant, 5f); + Handles.color = new Color(1, 1, 1, 0.03f); + if (m_coneInsideAngle.floatValue < 360) { + Handles.DrawSolidArc(transformObj.position, transformObj.up, outsideArcStartVector, m_coneOutsideAngle.floatValue, screenSpaceConstant); + Handles.DrawSolidArc(transformObj.position, transformObj.up, insideArcStartVector, m_coneInsideAngle.floatValue, screenSpaceConstant); + } + Handles.color = new Color(0.627f, 0.890f, 0.388f); + Handles.DrawWireArc(transformObj.position, transformObj.up, outsideArcStartVector, m_coneOutsideAngle.floatValue, m_transceiverRadius.floatValue); + Handles.color = new Color(1f, 0.537f, 0); + Handles.DrawWireArc(transformObj.position, transformObj.up, outsideArcStartVector, m_coneOutsideAngle.floatValue, m_transceiverRadius.floatValue + m_interiorDistance.floatValue); + + Handles.color = new Color(0.890f, 0.862f, 0.388f, 0.1f); + if (m_useDedicatedInput.boolValue && dedicatedInput != null) { + Handles.DrawSolidDisc(dedicatedInput.transform.position, dedicatedInput.transform.up, m_directAudioRadius.floatValue); + } else { + Handles.DrawSolidDisc(transformObj.position, transformObj.up, m_directAudioRadius.floatValue); + } + Handles.color = new Color(0.290f, 0.556f, 0.827f, 0.1f); + if (m_useDedicatedInput.boolValue && dedicatedInput != null) { + Handles.DrawSolidDisc(dedicatedInput.transform.position, dedicatedInput.transform.up, m_directAudioRadius.floatValue + m_crossFadeDistance.floatValue); + } else { + Handles.DrawSolidDisc(transformObj.position, transformObj.up, m_directAudioRadius.floatValue + m_crossFadeDistance.floatValue); + } + + using (var changeScope = new EditorGUI.ChangeCheckScope()) { + Handles.color = new Color(0.3317462f, 0.6611561f, 0.990566f, 0.7f); + float minAtt = Handles.RadiusHandle(Quaternion.identity, transformObj.position, targetObj.minAttenuation); + float maxAtt = Handles.RadiusHandle(Quaternion.identity, transformObj.position, targetObj.maxAttenuation); + if (changeScope.changed) { + Undo.RecordObject(target, "Change Transceiver Attenuation"); + + minAtt = Mathf.Min(minAtt, maxAtt); + targetObj.minAttenuation = minAtt; + targetObj.maxAttenuation = maxAtt; + + EditorUtility.SetDirty(target); + + if (m_applyParametersMethod != null) { + m_applyParametersMethod.Invoke(targetObj, null); + } + } + } + } +} + +} //namespace CriWare +/* end of file */ \ No newline at end of file diff --git a/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/CriAtomTransceiverEditor.cs.meta b/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/CriAtomTransceiverEditor.cs.meta new file mode 100644 index 0000000..740c7da --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/CriAtomTransceiverEditor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 79840c63aad7bb44f948a5b0fb1b81d3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/CriAtomWaveFile.cs b/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/CriAtomWaveFile.cs new file mode 100644 index 0000000..61045db --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/CriAtomWaveFile.cs @@ -0,0 +1,89 @@ +/**************************************************************************** + * + * Copyright (c) 2021 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +using System.Runtime.InteropServices; + +/** + * \addtogroup CRIWARE_EDITOR_UTILITY + * @{ + */ + +namespace CriWare.Editor { + +/** + * This is a class used for bouncing the audio output to a file. + * + * This class can be used to bounce the audio output from the ASR. + * + */ +public static class CriAtomWaveFile +{ + + /** + * Starts the bouncing + * File path for the bouncing output + * Number of channels in the bounced output file (1, 2, 4, 6 or 8) + * Whether the bouncing has been started + * + * Starts bouncing with the specified parameters.
+ * 1, 2, 4, 6 or 8 can be specified for numChannels.
+ * If numChannels is less than the number of ASR output channels, it will be automatically downmixed to the specified number of channels before bouncing.
+ * If the number of numChannels is larger than the number of output channels of ASR, silence will be recorded for the extra channels.
+ *
+ * + */ + public static bool StartBounce(string path, uint numChannels) + { + return criAtomWaveFile_StartBounce(path, numChannels); + } + + /** + * Stops the bouncing + * + * Stops the bouncing initiated by CriWare.Editor.CriAtomWaveFile.StartBounce . + * + * + */ + public static void StopBounce() + { + criAtomWaveFile_StopBounce(); + } + + /** + * Acquiring the duration (expressed in ms) of the bounced waveform + * Duration of the bounced waveform + * + * Gets the duration of the bounced waveform, expressed in milliseconds. + * + */ + public static uint GetBounceTime() + { + return criAtomWaveFile_GetBounceTime(); + } + + #region DLL Import +#if (UNITY_EDITOR && !UNITY_EDITOR_LINUX) && !CRIWARE_ENABLE_HEADLESS_MODE + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool criAtomWaveFile_StartBounce(string path, System.UInt32 num_channels); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomWaveFile_StopBounce(); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern System.UInt32 criAtomWaveFile_GetBounceTime(); +#else + private static bool criAtomWaveFile_StartBounce(string path, System.UInt32 num_channels) { return false; } + private static void criAtomWaveFile_StopBounce() { } + private static System.UInt32 criAtomWaveFile_GetBounceTime() { return 0; } +#endif + #endregion + } + +} //namespace CriWare.Editor + +/** + * @} + */ + +/* end of file */ \ No newline at end of file diff --git a/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/CriAtomWaveFile.cs.meta b/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/CriAtomWaveFile.cs.meta new file mode 100644 index 0000000..9dc4ab6 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/CriAtomWaveFile.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3b84f2ec5e0ac4724ac25c0df9625a72 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/CriAtomWindow.cs b/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/CriAtomWindow.cs new file mode 100644 index 0000000..44d89ca --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/CriAtomWindow.cs @@ -0,0 +1,743 @@ +/**************************************************************************** + * + * Copyright (c) 2011 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +#if UNITY_2017 && UNITY_EDITOR_WIN +#define OPENFOLDERPANEL_IS_BROKEN +#endif + +using UnityEngine; +using UnityEditor; +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; + +namespace CriWare { + +public sealed class CriAtomWindow : EditorWindow +{ + #region Variables + private int selectedAcfId = 0; + private int selectedDspBusSettingId = 0; + private int selectedCueInfoIndex = 0; + private int selectedCueSheetId = 0; + private string lastLoadedAcbGuid = null; + private string lastLoadedAcfGuid = null; + private bool isCueSheetListInitiated = false; + private int lastPreviewCueSheetId = -1; + private Vector2 scrollPosCueSheetList; + private Vector2 scrollPosCueList; + private Vector2 scrollPosWindow; + private bool useCopyAssetsFromCriAtomCraft = false; + private string[] popupAcfList = null; + private Color currentGuiColor; + private float cuesheetListWidth = 200; + private float cueIdListWidth = 70; + private bool isResizingLeftSplitter = false; + private bool isResizingRightSplitter = false; + private Vector2 lastMousePosLeftSplitter = new Vector2(); + private Vector2 lastMousePosRightSplitter = new Vector2(); + + private GameObject targetObject = null; + private CriAtomSource targetAtomSource = null; + private CriWare.Editor.CriAtomEditorUtilities.PreviewPlayer previewPlayer = null; + private CriAtomExAcb previewAcb = null; + + /* @cond excludele */ + private ulong acbKey = 0; + private ulong lastAcbKey = 0; + private string lastSelectedAcbGuid = null; + /* @endcond */ + + [SerializeField] private string searchPath = ""; + [SerializeField] private CriAtomWindowInfo projInfo = new CriAtomWindowInfo(); + [SerializeField] private CriAtomWindowPrefs criAtomWindowPrefs = null; + [SerializeField] private GUIStyle toolBarButtonStyle = null; + + [SerializeField] private bool showPrivateCue = false; + #endregion + + #region Functions + + [MenuItem("Window/CRIWARE/Atom Browser", false, 100)] + static void OpenWindow() + { + EditorWindow.GetWindow(false, "Atom Browser"); + } + + private void OnEnable() { + searchPath = Application.streamingAssetsPath; + criAtomWindowPrefs = CriAtomWindowPrefs.Load(); + + /* @cond excludele */ + if (criAtomWindowPrefs.useCommonKey) { + var initializerObj = FindObjectOfType(); + ulong parsedKey = 0; + if (initializerObj != null && initializerObj.useDecrypter == true && initializerObj.decrypterConfig != null + && ulong.TryParse(initializerObj.decrypterConfig.key, out parsedKey)) { + criAtomWindowPrefs.SetOrRenewKeyThenSave("any", parsedKey); + } + } + /* @endcond */ + + if (Selection.gameObjects.Length > 0) { + targetObject = Selection.gameObjects[0]; + targetAtomSource = targetObject.GetComponent(); + } + + ReloadAcbInfo(); + } + + private void OnDisable() { + if (previewAcb != null) { + previewAcb.Dispose(); + previewAcb = null; + } + lastLoadedAcbGuid = null; + if (previewPlayer != null) { + previewPlayer.Dispose(); + previewPlayer = null; + } + } + + private void OnSelectionChange() { + if (Selection.gameObjects.Length > 0) { + targetObject = Selection.gameObjects[0]; + targetAtomSource = targetObject.GetComponent(); + } + + Repaint(); + } + + private void OnLostFocus() { + StopPreview(); + if (previewAcb != null) { + previewAcb.Dispose(); + previewAcb = null; + } + lastLoadedAcbGuid = null; + } + + private void OnGUI() { + if (toolBarButtonStyle == null) { + toolBarButtonStyle = new GUIStyle(EditorStyles.toolbarButton); + toolBarButtonStyle.alignment = TextAnchor.MiddleLeft; + } + + currentGuiColor = GUI.color; + this.scrollPosWindow = GUILayout.BeginScrollView(this.scrollPosWindow); + { + GUISearchAndReload(); + GUIACFSettings(); + GUICueList(); + EditorGUILayout.Space(); + GUIImportAssetsFromAtomCraft(); + EditorGUILayout.Space(); + } + GUILayout.EndScrollView(); + GUI.color = currentGuiColor; + } + + private void ReloadAcbInfo() { + TryInitializePlugin(); + projInfo.GetAcfInfoList(true, searchPath); + projInfo.GetAcbInfoList(true, searchPath); + selectedAcfId = 0; + selectedDspBusSettingId = 0; + selectedCueSheetId = 0; + selectedCueInfoIndex = 0; + ResetDataRecord(); + } + + private void ResetDataRecord() { + lastLoadedAcfGuid = null; + lastLoadedAcbGuid = null; + } + + private void PlayPreview(CriAtomExAcb acb, string cuename) { + if (previewPlayer == null) { + previewPlayer = new CriWare.Editor.CriAtomEditorUtilities.PreviewPlayer(); + } + previewPlayer.Play(acb, cuename); + } + + private void StopPreview(bool withoutRelease = true) { + if (previewPlayer != null) { + previewPlayer.Stop(withoutRelease); + } + } + + private void TryInitializePlugin() { + if (CriAtomPlugin.IsLibraryInitialized() == false) { + previewAcb = null; + } + if (CriWare.Editor.CriAtomEditorUtilities.InitializeLibrary()) { + ResetDataRecord(); + } + } + + private void GUISearchAndReload() + { + EditorGUILayout.BeginHorizontal(); + { + this.searchPath = EditorGUILayout.TextField("Path to Search", this.searchPath); +#if !OPENFOLDERPANEL_IS_BROKEN + if (GUILayout.Button("...", EditorStyles.miniButton, GUILayout.Width(50))) + { + string pathTemp = EditorUtility.OpenFolderPanel("Select folder to search", this.searchPath, ""); + if (string.IsNullOrEmpty(pathTemp) == false) { + if (pathTemp.Contains(Application.dataPath)) { + this.searchPath = pathTemp; + ReloadAcbInfo(); + } else { + Debug.LogWarning("[CRIWARE] Selected folder should be inside this project. Search path will not be changed."); + } + } + } +#endif + if (GUILayout.Button("Reload Info", EditorStyles.miniButton, GUILayout.Width(100))) { + ReloadAcbInfo(); + } + } + EditorGUILayout.EndHorizontal(); + } + + private void GUIACFSettings() + { + var acfInfo = projInfo.GetAcfInfoList(false, this.searchPath); + popupAcfList = new string[acfInfo.Count]; + for (int i = 0; i < acfInfo.Count; i++) { + popupAcfList[i] = acfInfo[i].filePath; + } + if (acfInfo.Count > 0) { + selectedAcfId = EditorGUILayout.Popup("ACF Files", selectedAcfId, popupAcfList); + selectedDspBusSettingId = EditorGUILayout.Popup("DSPBusSettings", selectedDspBusSettingId, acfInfo[selectedAcfId].dspBusSettingsList.ToArray()); + } else { + EditorGUILayout.LabelField("ACF Files", "No ACF has been found"); + EditorGUILayout.LabelField("DSPBusSettings", "-"); + } + } + + private void GUICueList() + { + const int cCueListItemHeight = 18; + var acfInfoList = projInfo.GetAcfInfoList(false, this.searchPath); + var acbInfoList = projInfo.GetAcbInfoList(false, searchPath); + bool isAcfInfoAvailable = (selectedAcfId > acfInfoList.Count) && (selectedDspBusSettingId > acfInfoList[selectedAcfId].dspBusSettingsList.Count); + bool isCueSheetAvailable = false; + Rect splitterRect; + + if (isCueSheetListInitiated == true) { + lastPreviewCueSheetId = this.selectedCueSheetId; + } else { + isCueSheetListInitiated = true; + } + + EditorGUILayout.BeginHorizontal(); + + /* cuesheet list */ + using (var cuesheetListScope = new EditorGUILayout.VerticalScope("CN Box", GUILayout.Width(cuesheetListWidth))) { + using (var horizontalScope = new EditorGUILayout.HorizontalScope()) { + if (GUILayout.Button("Cue Sheet", toolBarButtonStyle)) { + projInfo.SortCueSheet(); + this.selectedCueSheetId = 0; + } + } + using (var cuesheetScrollViewScope = new EditorGUILayout.ScrollViewScope(scrollPosCueSheetList)) { + scrollPosCueSheetList = cuesheetScrollViewScope.scrollPosition; + int listLengthInView = (int)position.height / cCueListItemHeight; + int idFirstItemInView = Mathf.Clamp((int)scrollPosCueSheetList.y / cCueListItemHeight, 0, Mathf.Max(0, acbInfoList.Count - listLengthInView)); + + GUILayout.Space(idFirstItemInView * cCueListItemHeight); + for (int i = idFirstItemInView; i < Mathf.Min(idFirstItemInView + listLengthInView, acbInfoList.Count); i++) { + GUI.color = (this.lastPreviewCueSheetId == i) ? Color.yellow : currentGuiColor; + EditorGUILayout.BeginHorizontal(); + if (GUILayout.Button(acbInfoList[i].name, EditorStyles.label)) { + this.selectedCueSheetId = i; + } + EditorGUILayout.EndHorizontal(); + } + GUILayout.Space(Mathf.Max(0, acbInfoList.Count - idFirstItemInView - listLengthInView) * cCueListItemHeight); + GUI.color = currentGuiColor; + } + } + + splitterRect = EditorGUILayout.GetControlRect(false, 2, "CN Box", GUILayout.Width(2), GUILayout.ExpandHeight(true)); + cuesheetListWidth += GUILayoutResizeHandler(splitterRect, true, ref lastMousePosLeftSplitter, ref isResizingLeftSplitter).x; + + if (this.selectedCueSheetId != lastPreviewCueSheetId) { + this.selectedCueInfoIndex = 0; + } + + isCueSheetAvailable = (acbInfoList.Count > this.selectedCueSheetId); + + using (var cueListAndInfoScope = new EditorGUILayout.VerticalScope("CN Box")) { + bool playButtonPushed = false; + bool isCueAvailable = false; + CriAtomWindowInfo.CueInfo selectedCueInfo = null; + /* @cond excludele */ + bool saveKeyButtonPushed = false; + bool commonKeyToggled = false; + /* @endcond */ + + /* list title */ + using (var cueListTitleScope = new EditorGUILayout.HorizontalScope()) { + if (GUILayout.Button("Cue Name", toolBarButtonStyle)) { + if (isCueSheetAvailable) { + acbInfoList[selectedCueSheetId].SortCueInfo(CriAtomWindowInfo.CueSortType.Name); + this.selectedCueInfoIndex = 0; + } + } + splitterRect = EditorGUILayout.GetControlRect(false, 20, toolBarButtonStyle, GUILayout.Width(2)); + cueIdListWidth -= GUILayoutResizeHandler(splitterRect, true, ref lastMousePosRightSplitter, ref isResizingRightSplitter).x; + if (GUILayout.Button("Cue ID", toolBarButtonStyle, GUILayout.Width(cueIdListWidth + 20))) { + if (isCueSheetAvailable) { + acbInfoList[selectedCueSheetId].SortCueInfo(CriAtomWindowInfo.CueSortType.Id); + this.selectedCueInfoIndex = 0; + } + } + } + + /* cue list */ + using (var cueListScope = new EditorGUILayout.ScrollViewScope(scrollPosCueList, GUILayout.ExpandHeight(true))) { + scrollPosCueList = cueListScope.scrollPosition; + if (isCueSheetAvailable) { + var acbInfo = acbInfoList[this.selectedCueSheetId]; + List currentList; + if (this.showPrivateCue) { + currentList = acbInfo.cueInfoList; + } else { + currentList = acbInfo.publicCueInfoList; + } + + if (currentList.Count <= 0) { + EditorGUILayout.HelpBox("Nothing to be shown here.\nTry push the \"Reload Info\" button to refresh the list.", MessageType.Error); + } else { + int listLengthInView = (int)position.height / cCueListItemHeight; + int idFirstCueInView = Mathf.Clamp((int)scrollPosCueList.y / cCueListItemHeight, 0, Mathf.Max(0, currentList.Count - listLengthInView)); + + GUILayout.Space(idFirstCueInView * cCueListItemHeight); + for (int i = idFirstCueInView; i < Mathf.Min(idFirstCueInView + listLengthInView, currentList.Count); ++i) { + GUI.color = (this.selectedCueInfoIndex == i) ? Color.yellow : currentGuiColor; + using (var cueItemScope = new EditorGUILayout.HorizontalScope(GUILayout.Height(cCueListItemHeight))) { + if (GUILayout.Button(EditorGUIUtility.IconContent("Animation.Play"), EditorStyles.miniButton, GUILayout.Width(30))) { + this.selectedCueInfoIndex = i; + playButtonPushed = true; + } + if (GUILayout.Button(currentList[i].name + " (" + (currentList[i].length < 0 ? "loop" : Ms2String(currentList[i].length)) + ")", EditorStyles.label)) { + if (selectedCueInfoIndex != i) { + StopPreview(); + } + this.selectedCueInfoIndex = i; + } + GUILayout.Label(currentList[i].id.ToString(), GUILayout.Width(cueIdListWidth)); + } + } + GUILayout.Space(Mathf.Max(0, currentList.Count - idFirstCueInView - listLengthInView) * cCueListItemHeight); + GUI.color = currentGuiColor; + } + + isCueAvailable = currentList.Count > this.selectedCueInfoIndex; + if (isCueAvailable) { + selectedCueInfo = currentList[selectedCueInfoIndex]; + } + } else { + EditorGUILayout.HelpBox("No cue sheet is found.\nPlease check the search path. Press \"Reload Info\" button to refresh the list.", MessageType.Info); + } + } + + /* @cond excludele */ + if (isCueSheetAvailable) { + var acbInfo = acbInfoList[selectedCueSheetId]; + if (acbInfo.assetGuid != lastSelectedAcbGuid) { + this.lastAcbKey = criAtomWindowPrefs.GetKey(acbInfo.assetGuid); + this.acbKey = this.lastAcbKey; + GUI.FocusControl(null); + } + this.lastSelectedAcbGuid = acbInfo.assetGuid; + } + /* @endcond */ + EditorGUILayout.BeginHorizontal(EditorStyles.toolbar,GUILayout.ExpandWidth(true)); + { + { + var tempToggleVal = GUILayout.Toggle(this.showPrivateCue, "Show Private Cue", GUILayout.Width(120)); + if (tempToggleVal != this.showPrivateCue) { + /* Clear cue selection when change setting */ + this.selectedCueInfoIndex = 0; + } + this.showPrivateCue = tempToggleVal; + } + if (GUILayout.Button("Stop All", EditorStyles.toolbarButton, GUILayout.Width(100))) { + StopPreview(); + } + } + EditorGUILayout.EndHorizontal(); + /* @cond excludele */ + EditorGUILayout.BeginHorizontal(EditorStyles.toolbar,GUILayout.ExpandWidth(true)); + { + GUILayout.Label("Decryption Key:", GUILayout.Width(100)); + this.acbKey = (ulong)Math.Abs(EditorGUILayout.LongField("", (long)this.acbKey, EditorStyles.miniTextField, GUILayout.Width(100))); + if (GUILayout.Button("Save", EditorStyles.toolbarButton, GUILayout.Width(40))) { saveKeyButtonPushed = true; GUI.FocusControl(null);} + { + var tempToggleVal = GUILayout.Toggle(criAtomWindowPrefs.useCommonKey, "Common Key", GUILayout.Width(100)); + if (tempToggleVal != criAtomWindowPrefs.useCommonKey) { + commonKeyToggled = true; + } + criAtomWindowPrefs.useCommonKey = tempToggleVal; + } + if (GUILayout.Button("Clear", EditorStyles.toolbarButton, GUILayout.Width(50))) { this.acbKey = 0; saveKeyButtonPushed = true; } + if (GUILayout.Button("Clear All Saved", EditorStyles.toolbarButton, GUILayout.Width(100))) { this.acbKey = 0; saveKeyButtonPushed = true; criAtomWindowPrefs.ClearKeysAndSave(); } + } + EditorGUILayout.EndHorizontal(); + /* @endcond */ + + EditorGUILayout.Space(); + + EditorGUILayout.BeginHorizontal("AppToolbar"); + { + GUILayout.Label("Cue Information"); + } + EditorGUILayout.EndHorizontal(); + EditorGUILayout.LabelField("Cue ID", (isCueSheetAvailable && isCueAvailable) ? selectedCueInfo.id.ToString() : "N/A"); + string cueName = "N/A"; + string userData = ""; + if (isCueSheetAvailable && isCueAvailable) { + cueName = selectedCueInfo.name; + userData = selectedCueInfo.comment; + } + GUILayout.BeginHorizontal(); + GUILayout.Label("Cue Name", GUILayout.Width(145)); + GUILayout.Label(cueName, GUILayout.ExpandWidth(false)); + if (GUILayout.Button("Copy", GUILayout.Width(100))) { + GUIUtility.systemCopyBuffer = cueName; + } + GUILayout.EndHorizontal(); + EditorGUILayout.LabelField("User Data", userData, EditorStyles.wordWrappedLabel, GUILayout.Height(28)); + + if (GUI.changed && isCueSheetAvailable) { + CriAtomWindowInfo.AcfInfo acfInfo = null; + var acbInfo = acbInfoList[selectedCueSheetId]; + if (isAcfInfoAvailable) { + acfInfo = acfInfoList[selectedAcfId]; + } + + /* @cond excludele */ + if (commonKeyToggled) { + this.acbKey = criAtomWindowPrefs.GetKey(acbInfo.assetGuid); + this.lastAcbKey = this.acbKey; + if (previewAcb != null) { + previewAcb.Dispose(); + } + previewAcb = null; + lastLoadedAcbGuid = null; + } + if (saveKeyButtonPushed && acbKey != lastAcbKey) { + criAtomWindowPrefs.SetOrRenewKeyThenSave(acbInfoList[selectedCueSheetId].assetGuid, this.acbKey); + this.lastAcbKey = this.acbKey; + if (previewAcb != null) { + previewAcb.Dispose(); + } + previewAcb = null; + lastLoadedAcbGuid = null; + } + /* @endcond */ + if (playButtonPushed && isCueAvailable) { + StopPreview(); + + TryInitializePlugin(); + if (isAcfInfoAvailable == false) { + CriAtomEx.UnregisterAcf(); + lastLoadedAcfGuid = null; + selectedDspBusSettingId = 0; + } else if (lastLoadedAcfGuid != acfInfo.assetGuid) { + CriAtomEx.UnregisterAcf(); + CriAtomEx.RegisterAcf(null, Path.Combine(CriWare.Common.streamingAssetsPath, acfInfo.filePath)); + lastLoadedAcfGuid = acfInfo.assetGuid; + selectedDspBusSettingId = 0; + } + if (lastLoadedAcbGuid != acbInfo.assetGuid) { + if (previewAcb != null) { + previewAcb.Dispose(); + } + previewAcb = CriAtomExAcb.LoadAcbFile( + null, + Path.Combine(CriWare.Common.streamingAssetsPath, acbInfo.acbPath), + string.IsNullOrEmpty(acbInfo.awbPath) ? null : Path.Combine(CriWare.Common.streamingAssetsPath, acbInfo.awbPath) + ); + /* @cond excludele */ + if (this.acbKey != 0) { + previewAcb.Decrypt(this.acbKey, 0); + } + /* @endcond */ + lastLoadedAcbGuid = acbInfo.assetGuid; + } + if (previewAcb != null) { + CriAtomEx.DetachDspBusSetting(); + if (isAcfInfoAvailable) { + CriAtomEx.AttachDspBusSetting(acfInfo.dspBusSettingsList[selectedDspBusSettingId]); + } + PlayPreview(previewAcb, selectedCueInfo.name); + } + } + } + + /* edit buttons */ + GUIEdit(); + } /* cueListAndInfoScope */ + + EditorGUILayout.EndHorizontal(); + } + + private void GUIEdit() + { + EditorGUILayout.BeginHorizontal(); + { + if (GUILayout.Button("Create GameObject", GUILayout.Height(22))) { + this.CreateAtomSourceGameObject(true); + } + + if (this.targetObject == null) { + GUI.enabled = false; + } + if (GUILayout.Button("Add Component", GUILayout.Height(22))) { + if (targetObject != null) { + if (targetAtomSource != null) { + if (EditorUtility.DisplayDialog("Duplicate Component", "CriAtomSource Component already exists. \nDo you really want to add more?", "Yes", "Cancel")) { + this.CreateAtomSourceGameObject(false); + } + } else { + this.CreateAtomSourceGameObject(false); + } + } + } + + if (this.targetAtomSource == null) { + GUI.enabled = false; + } + if (GUILayout.Button("Update Component", GUILayout.Height(22))) { + if (targetAtomSource != null) { + var acbInfoList = projInfo.GetAcbInfoList(false, searchPath); + if (acbInfoList.Count > this.selectedCueSheetId) { + var acbInfo = acbInfoList[this.selectedCueSheetId]; + var cueInfo = acbInfo.cueInfoList[this.selectedCueInfoIndex]; + Undo.RegisterCompleteObjectUndo(targetAtomSource, "AtomSource Update"); + targetAtomSource.cueSheet = acbInfo.name; + targetAtomSource.cueName = cueInfo.name; + Selection.activeGameObject = targetObject; + } + } + } + GUI.enabled = true; + } + EditorGUILayout.EndHorizontal(); + } + + private void GUIImportAssetsFromAtomCraft() + { + if (criAtomWindowPrefs == null) { + criAtomWindowPrefs = CriAtomWindowPrefs.Load(); + } + + useCopyAssetsFromCriAtomCraft = CriFoldout(useCopyAssetsFromCriAtomCraft, "Import Assets from Atom Craft Project"); + if (useCopyAssetsFromCriAtomCraft) { + EditorGUI.indentLevel++; + + GUILayout.BeginHorizontal(); + { + if (criAtomWindowPrefs != null) { + criAtomWindowPrefs.outputAssetsRoot = EditorGUILayout.TextField("Import From:", criAtomWindowPrefs.outputAssetsRoot); + } + +#if !OPENFOLDERPANEL_IS_BROKEN + if (GUILayout.Button("...", EditorStyles.miniButton, GUILayout.Width(50))) { + string tmpPath = ""; + string errorMsg; + tmpPath = EditorUtility.OpenFolderPanel("Select CRI Atom Craft output Assets Folder", criAtomWindowPrefs.outputAssetsRoot, ""); + if (CheckPathIsAtomCraftAssetRoot(tmpPath, out errorMsg)) { + criAtomWindowPrefs.outputAssetsRoot = tmpPath; + criAtomWindowPrefs.Save(); + } else { + Debug.LogWarning(errorMsg); + } + } +#endif + } + GUILayout.EndHorizontal(); + + GUILayout.BeginHorizontal(); + { + GUI.color = Color.yellow; + EditorGUILayout.PrefixLabel(" "); + if (GUILayout.Button("Import Assets", GUILayout.Width(160), GUILayout.Height(40))) { + string errorMsg; + if (CheckPathIsAtomCraftAssetRoot(criAtomWindowPrefs.outputAssetsRoot, out errorMsg) == false) { + Debug.LogWarning(errorMsg); + } else { + try { + CopyDirectory(criAtomWindowPrefs.outputAssetsRoot, Application.dataPath); + Debug.Log("[CRIWARE] Assets successfully imported from " + criAtomWindowPrefs.outputAssetsRoot); + } catch (Exception ex) { + Debug.LogError(ex.Message); + Debug.LogError("[CRIWARE] Failed to import assets from " + criAtomWindowPrefs.outputAssetsRoot); + } + AssetDatabase.Refresh(); + + ReloadAcbInfo(); + } + } + GUI.color = Color.white; + EditorGUILayout.HelpBox("Copy \"Assets\" folder (created in CRI Atom Craft) to the \"StreamingAssets\" folder.\nThe folder can be created by building with the \"With Unity Assets\" flag in CRI Atom Craft.", MessageType.Info); + } + GUILayout.EndHorizontal(); + + EditorGUI.indentLevel--; + } + } + + private bool CheckPathIsAtomCraftAssetRoot(string outString, out string errorMsg) + { + errorMsg = ""; + try { + if (string.IsNullOrEmpty(outString) == false && Path.GetFileName(outString) == "Assets") { + if (Directory.Exists(outString) == false) { + errorMsg = "[CRIWARE] Path to the assets does not exist: " + outString; + return false; + } + foreach (string dir in Directory.GetDirectories(outString)) { + if (Path.GetFileName(dir) == "Editor") { + errorMsg = "[CRIWARE] Please choose the Assets folder in your Atom Craft project instead of the one in your Unity project. Import path will not be changed."; + return false; + } + } + return true; + } else { + errorMsg = "[CRIWARE] Unmatched folder name. Please set the right import path (\"Assets\" folder)."; + return false; + } + } catch (Exception ex) { + errorMsg = "[CRIWARE] I/O Error: " + ex.Message; + return false; + } + } + + private static void CopyDirectory(string sourceDirName, string destDirName) + { + try { + if (Directory.Exists(destDirName) == false) { + Directory.CreateDirectory(destDirName); + File.SetAttributes(destDirName, File.GetAttributes(sourceDirName)); + } + + foreach (var file in Directory.GetFiles(sourceDirName)) { + string ext = Path.GetExtension(file.Replace("\\", "/")); + if (ext == ".acf" || ext == ".acb" || ext == ".awb") { + string targetPath = Path.Combine(destDirName, Path.GetFileName(file)); + Debug.Log(String.Format("[CRIWARE] Copying \"{0}\" to \"{1}\"", file, targetPath)); + File.Copy(file, targetPath, true); + } + } + + foreach (var dir in Directory.GetDirectories(sourceDirName)) { + /* sub directories */ + CopyDirectory(dir, Path.Combine(destDirName, Path.GetFileName(dir))); + } + } catch { + throw; + } + } + + private void CreateAtomSourceGameObject(bool createGameObjectFlag) + { + if (Selection.gameObjects.Length == 0) { + createGameObjectFlag = true; + } + var acbInfoList = projInfo.GetAcbInfoList(false, searchPath); + if (acbInfoList.Count > this.selectedCueSheetId) { + GameObject go = null; + if (createGameObjectFlag) { + go = new GameObject(acbInfoList[this.selectedCueSheetId].cueInfoList[this.selectedCueInfoIndex].name + "(CriAtomSource)"); + if (Selection.gameObjects.Length > 0) { + go.transform.parent = Selection.gameObjects[0].transform; + } + Undo.RegisterCreatedObjectUndo(go, "Create AtomSource GameObject"); + } else { + go = Selection.gameObjects[0]; + } + var acbInfo = acbInfoList[this.selectedCueSheetId]; + CriAtom atom = GameObject.FindObjectOfType(typeof(CriAtom)) as CriAtom; + if (atom == null) { + var criObject = GameObject.Find("/CRIWARE"); + if (criObject == null) { + criObject = new GameObject("CRIWARE"); + Undo.RegisterCreatedObjectUndo(criObject, "Add CRIWARE GameObject"); + } + atom = Undo.AddComponent(criObject); + var acfList = projInfo.GetAcfInfoList(false, searchPath); + if (acfList.Count > selectedAcfId) { + atom.acfFile = acfList[selectedAcfId].filePath; + } + } + CriAtomCueSheet cueSheet = atom.GetCueSheetInternal(acbInfo.name); + if (cueSheet == null) { + cueSheet = atom.AddCueSheetInternal(null, acbInfo.acbPath, acbInfo.awbPath, null); + } + CriAtomSource newCriAtomSource = Undo.AddComponent(go); + newCriAtomSource.cueSheet = cueSheet.name; + newCriAtomSource.cueName = acbInfo.cueInfoList[this.selectedCueInfoIndex].name; + Selection.activeObject = go; + } + } + + private Vector2 GUILayoutResizeHandler(Rect rect, bool isVertical, ref Vector2 lastMousePos, ref bool isResizing) { + EditorGUIUtility.AddCursorRect(rect, isVertical ? MouseCursor.SplitResizeLeftRight : MouseCursor.SplitResizeUpDown); + + if (Event.current.type == EventType.MouseDown && rect.Contains(Event.current.mousePosition)) { + lastMousePos = Event.current.mousePosition; + isResizing = true; + } + + if (isResizing) { + var mousePos = Event.current.mousePosition; + GUI.DrawTexture(new Rect(isVertical ? new Vector2(mousePos.x, rect.y) : new Vector2(rect.x, mousePos.y), rect.size), EditorGUIUtility.whiteTexture); + Repaint(); + if (new Rect(Vector2.zero, this.position.size).Contains(mousePos) == false) { + isResizing = false; + } + } + + if (Event.current.type == EventType.MouseUp) { + if (isResizing) { + isResizing = false; + return Event.current.mousePosition - lastMousePos; + } + isResizing = false; + } + + return Vector2.zero; + } + + private string Ms2String(long timeMs) { + long hh, mm, ss, ms; + hh = timeMs / 3600000; + mm = (timeMs % 3600000) / 60000; + ss = (timeMs % 60000) / 1000; + ms = timeMs % 1000; + string res = ((hh > 0) ? hh.ToString("00") + ":" : "") + ((mm > 0) ? mm.ToString("00") + ":" : "") + ss.ToString("00") + ":" + ms.ToString("000"); + return res; + } + + private bool CriFoldout(bool foldout, string content) { +#if UNITY_5_5_OR_NEWER + return EditorGUILayout.Foldout(foldout, content, true); +#else + return EditorGUILayout.Foldout(foldout, content); +#endif + } +#endregion +} + +} //namespace CriWare +/* end of file */ diff --git a/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/CriAtomWindow.cs.meta b/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/CriAtomWindow.cs.meta new file mode 100644 index 0000000..6e20fd5 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/CriAtomWindow.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: bacfcb712a3304a40b91990e9f581c6d +timeCreated: 1433816076 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/CriAtomWindowPrefs.asset b/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/CriAtomWindowPrefs.asset new file mode 100644 index 0000000..54672d8 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/CriAtomWindowPrefs.asset @@ -0,0 +1,17 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!114 &11400000 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 0} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 7dbb5a65a01a1de4ebfe0c4a1352cc1a, type: 3} + m_Name: CriAtomWindowPrefs + m_EditorClassIdentifier: + outputAssetsRoot: + useCommonKey: 1 + cuesheetKeyList: [] diff --git a/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/CriAtomWindowPrefs.asset.meta b/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/CriAtomWindowPrefs.asset.meta new file mode 100644 index 0000000..169da78 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/CriAtomWindowPrefs.asset.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 88e77466f0e64194e982232dcf64d4e7 +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 11400000 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/CriAtomWindowPrefs.cs b/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/CriAtomWindowPrefs.cs new file mode 100644 index 0000000..994a5df --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/CriAtomWindowPrefs.cs @@ -0,0 +1,401 @@ +/**************************************************************************** + * + * Copyright (c) 2011 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +using UnityEngine; +using UnityEditor; +using System; +using System.Collections.Generic; +using System.IO; + +namespace CriWare { + +[Serializable] +public class CriAtomWindowPrefs : ScriptableObject +{ + public string outputAssetsRoot = String.Empty; + + /* @cond excludele */ + static readonly private string commonCuesheetGuid = "000000000"; + + public bool useCommonKey = true; + [SerializeField] private List cuesheetKeyList = new List(); + + private Dictionary searchableKeyList = new Dictionary(); + /* @endcond */ + + static string FindInstance() { + var guids = AssetDatabase.FindAssets("t:" + typeof(CriAtomWindowPrefs).Name); + if (guids.Length <= 0) + return null; + if (guids.Length > 1) { + Debug.LogWarning("[CRIWARE] There are multiple preferences file of CriAtomWindow."); + } + return guids[0]; + } + + /* @cond excludele */ + [Serializable] + public class CueSheetKeyPair { + public string cuesheetGuid; + public ulong key; + + public CueSheetKeyPair(string cuesheetGuid, ulong key) { + this.cuesheetGuid = cuesheetGuid; + this.key = key; + } + } + + /* Slow. Don't run it every frame */ + public void SetOrRenewKeyThenSave(string cuesheetGuid, ulong key) { + if (useCommonKey) { + cuesheetGuid = commonCuesheetGuid; + } + if (searchableKeyList.ContainsKey(cuesheetGuid)) { + if (key == 0) { + searchableKeyList.Remove(cuesheetGuid); + } else { + searchableKeyList[cuesheetGuid] = key; + } + } else { + searchableKeyList.Add(cuesheetGuid, key); + } + this.Save(); + } + + /* Slow. Don't run it every frame */ + public ulong GetKey(string cuesheetGuid) { + if (useCommonKey) { + cuesheetGuid = commonCuesheetGuid; + } + return searchableKeyList.ContainsKey(cuesheetGuid) ? searchableKeyList[cuesheetGuid] : 0; + } + + public void ClearKeysAndSave() { + searchableKeyList.Clear(); + useCommonKey = true; + this.Save(); + } + + private void SerializeKeyDict() { + this.cuesheetKeyList.Clear(); + foreach (var elem in searchableKeyList) { + cuesheetKeyList.Add(new CueSheetKeyPair(elem.Key, elem.Value)); + } + } + + private void DeserializeKeyDict() { + this.searchableKeyList.Clear(); + foreach(var elem in cuesheetKeyList) { + searchableKeyList.Add(elem.cuesheetGuid, elem.key); + } + } + /* @endcond */ + + public void Save () + { + /* @cond excludele */ + this.SerializeKeyDict(); + /* @endcond */ + + if (string.IsNullOrEmpty(FindInstance())) { + var script = MonoScript.FromScriptableObject(this); + var prefsFilePath = Path.Combine(Path.GetDirectoryName(AssetDatabase.GetAssetPath(script)), "CriAtomWindowPrefs.asset"); + AssetDatabase.CreateAsset(this, prefsFilePath); + } else { + EditorUtility.SetDirty(this); + } + AssetDatabase.SaveAssets (); + AssetDatabase.Refresh (); + } + + public static CriAtomWindowPrefs Load () + { + CriAtomWindowPrefs preference; + var guid = FindInstance(); + if (string.IsNullOrEmpty(guid)) { + preference = CreateInstance(); + preference.Save(); + } else { + var path = AssetDatabase.GUIDToAssetPath(guid); + preference = AssetDatabase.LoadAssetAtPath(path); + } + + /* @cond excludele */ + preference.DeserializeKeyDict(); + /* @endcond */ + + return preference; + } +} + +[Serializable] +public class CriAtomWindowInfo { + #region Serializable Classes + [Serializable] + public class InfoBase { + public string name = ""; + public int id = 0; + public string assetGuid = null; + public string comment = ""; + } + + [Serializable] + public class AcfInfo : InfoBase { + public string filePath = ""; + public List dspBusSettingsList = new List(); + + public AcfInfo(string name, int id, string comment, string filePath) { + this.name = name; + this.id = id; + this.comment = comment; + + this.filePath = filePath; + } + } + + [Serializable] + public class AcbInfo : InfoBase { + public string acbPath = ""; + public string awbPath = ""; + public List cueInfoList; + public List publicCueInfoList; + + private bool sortOrder = true; /* true = incremental */ + + public AcbInfo(string name, int id, string comment, string acbPath, string awbPath) { + this.name = name; + this.id = id; + this.comment = comment; + + this.acbPath = acbPath; + this.awbPath = awbPath; + this.cueInfoList = new List(); + this.publicCueInfoList = new List(); + } + + public void SortCueInfo(CueSortType type) { + if (cueInfoList.Count <= 0) { + return; + } + + switch (type) { + case CueSortType.Id: + this.cueInfoList.Sort((CueInfo x, CueInfo y) => { + return sortOrder ? (x.id - y.id) : (y.id - x.id); + }); + this.publicCueInfoList.Sort((CueInfo x, CueInfo y) => { + return sortOrder ? (x.id - y.id) : (y.id - x.id); + }); + break; + case CueSortType.Name: + this.cueInfoList.Sort((CueInfo x, CueInfo y) => { + return sortOrder ? string.Compare(x.name, y.name) : string.Compare(y.name, x.name); + }); + this.publicCueInfoList.Sort((CueInfo x, CueInfo y) => { + return sortOrder ? string.Compare(x.name, y.name) : string.Compare(y.name, x.name); + }); + break; + default: + break; + } + + sortOrder = !sortOrder; + } + } + + public void SortCueSheet() { + switch (cuesheetSortType) { + case CueSheetSortType.NameInc: + this.acbInfoList.Sort((AcbInfo x, AcbInfo y) => ( + string.Compare(x.name, y.name) + )); + cuesheetSortType = CueSheetSortType.NameDec; + break; + case CueSheetSortType.NameDec: + this.acbInfoList.Sort((AcbInfo x, AcbInfo y) => ( + string.Compare(y.name, x.name) + )); + cuesheetSortType = CueSheetSortType.Id; + break; + case CueSheetSortType.Id: + this.acbInfoList.Sort((AcbInfo x, AcbInfo y) => ( + x.id - y.id + )); + cuesheetSortType = CueSheetSortType.NameInc; + break; + default: + break; + } + } + + private enum CueSheetSortType { + NameInc, + NameDec, + Id + } + private CueSheetSortType cuesheetSortType = CueSheetSortType.NameInc; + + public enum CueSortType { + Id, + Name + } + + [Serializable] + public class CueInfo : InfoBase { + public long length; + public bool isPublic; + public CueInfo(string name, int id, string comment, long length, bool isPublic) { + this.name = name; + this.id = id; + this.comment = comment; + this.length = length; + this.isPublic = isPublic; + } + } /* end of class */ + #endregion + + #region Fields + [SerializeField] private List acfInfoList = new List(); + [SerializeField] private List acbInfoList = new List(); + #endregion + + + public List GetAcbInfoList(bool forceReload, string searchPath) { + if (acbInfoList == null || forceReload) { + if (acbInfoList != null) { acbInfoList.Clear(); } + acbInfoList = new List(); + + string[] files = null; + try { + files = Directory.GetFiles(searchPath, "*.acb", SearchOption.AllDirectories); + } catch (Exception ex) { + if (ex is ArgumentException || ex is ArgumentNullException) { + Debug.LogWarning("[CRIWARE] Insufficient search path. Please check the path for file searching."); + } else if (ex is DirectoryNotFoundException) { + Debug.LogWarning("[CRIWARE] Search path not found: " + searchPath); + } else { + Debug.LogError("[CRIWARE] Error getting ACB files. Message: " + ex.Message); + } + } + if (files != null && CriAtomPlugin.IsLibraryInitialized()) { + int acbIndex = 0; + foreach (string file in files) { + string acbFilePath = file.Replace("\\", "/"); + AcbInfo acbInfo = new AcbInfo( + Path.GetFileNameWithoutExtension(acbFilePath), + acbIndex++, + "", + TryGetRelFilePath(acbFilePath), + TryGetAwbFile(acbFilePath)); + /* 指定したACBファイル名(キューシート名)を指定してキュー情報を取得 */ + CriAtomExAcb acb = CriAtomExAcb.LoadAcbFile(null, acbFilePath, ""); + if (acb != null) { + acbInfo.assetGuid = AssetDatabase.AssetPathToGUID("Assets" + acbFilePath.Substring(Application.dataPath.Length)); + /* キュー名リストの作成 */ + CriAtomEx.CueInfo[] cueInfoList = acb.GetCueInfoList(); + foreach (CriAtomEx.CueInfo cueInfo in cueInfoList) { + bool found = false; + foreach (var key in acbInfo.cueInfoList) { + if (key.id == cueInfo.id) { + found = true; + break; + } + } + if (found == false) { + var newCueInfo = new CueInfo(cueInfo.name, cueInfo.id, cueInfo.userData, cueInfo.length, Convert.ToBoolean(cueInfo.headerVisibility)); + acbInfo.cueInfoList.Add(newCueInfo); + if (newCueInfo.isPublic) { + acbInfo.publicCueInfoList.Add(newCueInfo); + } + } else { + /* inGame時のサブシーケンスの場合あり */ + Debug.Log("[CRIWARE] Duplicate cue ID " + cueInfo.id.ToString() + " in cue sheet " + acbInfo.name + ". Last cue name:" + cueInfo.name); + } + } + acb.Dispose(); + } else { + Debug.Log("[CRIWARE] Failed to load ACB file: " + file); + } + acbInfoList.Add(acbInfo); + } + } + } + return acbInfoList; + } + + public List GetAcfInfoList(bool forceReload, string searchPath) { + if (acfInfoList == null || forceReload) { + if (acfInfoList != null) { acfInfoList.Clear(); } + acfInfoList = new List(); + + string[] files = null; + try { + files = System.IO.Directory.GetFiles(searchPath, "*.acf", System.IO.SearchOption.AllDirectories); + } catch (Exception ex) { + if (ex is ArgumentException || ex is ArgumentNullException) { + Debug.LogWarning("[CRIWARE] Insufficient search path. Please check the path for file searching."); + } else if (ex is DirectoryNotFoundException) { + Debug.LogWarning("[CRIWARE] Search path not found: " + searchPath); + } else { + Debug.LogError("[CRIWARE] Error getting ACF files. Message: " + ex.Message); + } + } + if (files != null && CriAtomPlugin.IsLibraryInitialized()) { + int index = 0; + foreach (string file in files) { + string acfFilePath = file.Replace("\\", "/"); + var acfInfo = new AcfInfo( + System.IO.Path.GetFileNameWithoutExtension(acfFilePath), + index++, + "", + TryGetRelFilePath(acfFilePath)); + acfInfo.assetGuid = AssetDatabase.AssetPathToGUID("Assets" + acfFilePath.Substring(Application.dataPath.Length)); + CriAtomEx.RegisterAcf(null, acfFilePath); + CriAtomExAcf.AcfInfo nativeAcfInfo; + CriAtomExAcf.GetAcfInfo(out nativeAcfInfo); + for (ushort i = 0; i < nativeAcfInfo.numDspSettings; ++i) { + acfInfo.dspBusSettingsList.Add(CriAtomExAcf.GetDspSettingNameByIndex(i)); + } + CriAtomEx.UnregisterAcf(); + acfInfoList.Add(acfInfo); + } + } + } + return acfInfoList; + } + + public void ResetInfo() { + this.acfInfoList.Clear(); + this.acfInfoList = null; + this.acbInfoList.Clear(); + this.acbInfoList = null; + } + + private string TryGetRelFilePath(string path) { + Uri streamingAssetsUri = new Uri(CriWare.Common.streamingAssetsPath); + Uri fullPathUri = new Uri(path); + if (fullPathUri.ToString().Contains(streamingAssetsUri.ToString())) { + string[] splitter = { streamingAssetsUri.ToString() + "/" }; + var pathChunks = fullPathUri.ToString().Split(splitter, StringSplitOptions.RemoveEmptyEntries); + return pathChunks[pathChunks.Length - 1]; + } else { + return path; + } + } + + private string TryGetAwbFile(string acbPath) { + string dir = Path.GetDirectoryName(acbPath); + string filenameNoExt = Path.GetFileNameWithoutExtension(acbPath); + string presumedAwbPath = Path.Combine(dir, filenameNoExt + ".awb"); + if (File.Exists(presumedAwbPath)) { + return TryGetRelFilePath(presumedAwbPath); + } else { + return ""; + } + } +} + +} //namespace CriWare \ No newline at end of file diff --git a/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/CriAtomWindowPrefs.cs.meta b/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/CriAtomWindowPrefs.cs.meta new file mode 100644 index 0000000..63d040d --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/CriAtomWindowPrefs.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 7dbb5a65a01a1de4ebfe0c4a1352cc1a +timeCreated: 1445602397 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/Extension.meta b/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/Extension.meta new file mode 100644 index 0000000..091ce90 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/Extension.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 4cbed90d60f1598439f1b8e8ca810b49 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/Extension/CriAtomClipWaveformCanvas.cs b/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/Extension/CriAtomClipWaveformCanvas.cs new file mode 100644 index 0000000..3f9d0b9 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/Extension/CriAtomClipWaveformCanvas.cs @@ -0,0 +1,213 @@ +/**************************************************************************** + * + * Copyright (c) CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +#if UNITY_2019_3_OR_NEWER && CRIWARE_TIMELINE_1_OR_NEWER + +using UnityEditor; +using UnityEngine; +using UnityEditor.Timeline; +using UnityEngine.Events; +using System; + +namespace CriWare { + +namespace CriTimeline.Atom { + + public partial class CriAtomClipWaveformPreviewer { + + private class CriAtomClipWaveformCanvas : IDisposable { + private const string SHADER = "CRIWARE/CriAtomClipWaveformRender"; + private const int DEFAULT_TEXTURE_WIDTH = 4096; + private static readonly Color backgroundColor = Color.clear; + private static readonly Color waveColorForAll = new Color(1.0f, 0.635f, 0.0f, 1.0f); /* yellow */ + private static readonly Color waveColorForMono = new Color(0.332f, 0.661f, 0.991f, 1f); /* blue */ + + private Texture2D texture; + private Material material; + private int scanPosition = 0; + private ClipBackgroundRegion lastRegion; + private int lastWidth = 0; + private bool lastLoop = false; + private bool isDirty = true; + private bool isDisposed = false; + + public UnityAction updated = null; + + public bool IsDirty { + get { return isDirty; } + set { + if (isDirty = value) { + scanPosition = 0; + } + } + } + + public CriAtomClipWaveformCanvas() { + this.texture = null; + this.material = new Material(Shader.Find(SHADER)); + } + + ~CriAtomClipWaveformCanvas() { + dispose(); + } + + public void Dispose() { + dispose(); + GC.SuppressFinalize(this); + } + + public void UpdateTexture(ref CriAtomClipWaveformInfo info, bool loop, ClipBackgroundRegion? region = null, bool renderOnce = false) { + const int BATCH_NUM_PIXEL = 50; + + int scanWidth = region.HasValue ? (int)region.Value.position.width : DEFAULT_TEXTURE_WIDTH; + + if (texture == null) { + texture = new Texture2D(scanWidth, info.waveformInfo.numChannels, TextureFormat.RG16, false); + texture.wrapMode = TextureWrapMode.Clamp; + texture.filterMode = FilterMode.Bilinear; + } else if (renderOnce == false) { + if (region.HasValue && lastWidth != scanWidth) { +#if UNITY_2021_2_OR_NEWER + texture.Reinitialize(scanWidth, texture.height); +#else + texture.Resize(scanWidth, texture.height); +#endif + this.IsDirty = true; + lastWidth = scanWidth; + } + if (region.HasValue && region.Value != lastRegion) { + this.IsDirty = true; + lastRegion = region.Value; + } + if (loop != lastLoop) { + this.IsDirty = true; + lastLoop = loop; + } + } + + if (isDirty) { + if (this.scanPosition >= scanWidth) { + this.IsDirty = false; + return; + } + } else { + return; + } + + long startSmpIdx = region.HasValue + ? (long)((region.Value.startTime / info.waveDurationSecond) * info.waveformInfo.numSamples) + : 0; + long endSmpIdx = region.HasValue + ? (long)((region.Value.endTime / info.waveDurationSecond) * info.waveformInfo.numSamples) + : (info.waveformInfo.numSamples - 1); + long smpLength = endSmpIdx - startSmpIdx + 1; + + float samplePerPixel = smpLength / (float)scanWidth; + if (samplePerPixel <= 0) { + samplePerPixel = float.Epsilon; + } + + for (int y = 0; y < texture.height; ++y) { + for (int x = scanPosition; x < scanPosition + BATCH_NUM_PIXEL; ++x) { + Int16 maxValue, minValue; + long startPnt = (long)(startSmpIdx + x * samplePerPixel); + if (loop) { + startPnt %= info.waveformInfo.numSamples; + } + long range = (long)Mathf.Ceil(samplePerPixel); + if (startPnt + range > info.waveformInfo.numSamples) { + range = (long)Mathf.Floor(info.waveformInfo.numSamples - startPnt); + } + GetMinMaxPcmArray(info.lpcmBufferByInterleave, + startPnt, + range, + y, + info.waveformInfo.numChannels, + out minValue, out maxValue); + texture.SetPixel(x, y, new Color( + maxValue / (float)Int16.MaxValue, + minValue / (float)Int16.MinValue, + 0)); + } + } + + texture.Apply(); + + scanPosition += BATCH_NUM_PIXEL; + + if (this.updated != null) { + this.updated(); + } + } + + private static void GetMinMaxPcmArray(Int16[] array, long index, long length, int channel, int numChannels, out Int16 min, out Int16 max) { + Int16 maxValue = 0; + Int16 minValue = 0; + for (long i = 0; i < length; i++) { + var currentIndex = (index + i) * numChannels + channel; + var amplitude = array[currentIndex]; + if (maxValue < amplitude) { + maxValue = amplitude; + } + if (minValue > amplitude) { + minValue = amplitude; + } + } + max = maxValue; + min = minValue; + } + + public void Draw(Rect rect) { + if (this.texture == null || this.material == null) { return; } + Graphics.DrawTexture(rect, this.texture, this.material); + } + + public void SetMatParams( + RenderChannelMode channelMode, + int numChannels, + bool isLooping, + bool isMuted, + float scale, + float offset) + { + this.material.SetTexture("_MainTex", this.texture); + this.material.SetColor("_BacCol", backgroundColor); + this.material.SetColor("_ForCol", channelMode == RenderChannelMode.All ? waveColorForAll : waveColorForMono); + this.material.SetFloat("_Channel", channelMode == RenderChannelMode.All ? numChannels : 1); + + this.material.SetFloat("_Scale", scale); + this.material.SetFloat("_Offset", offset); + + this.material.SetInt("_IsLoop", isLooping ? 1 : 0); + this.material.SetInt("_IsMute", isMuted ? 1 : 0); + this.material.SetInt("_ForceMono", channelMode == RenderChannelMode.Mono ? 1 : 0); + } + + private void dispose() { + if (this.isDisposed) { return; } + + if (Application.isPlaying) { + UnityEngine.Object.Destroy(this.texture); + UnityEngine.Object.Destroy(this.material); + } else { + UnityEngine.Object.DestroyImmediate(this.texture); + UnityEngine.Object.DestroyImmediate(this.material); + } + this.texture = null; + this.material = null; + + this.isDisposed = true; + } + + } //class CriAtomClipWaveformCanvas + + } //partial class CriAtomClipWaveformPreviewer + +} //namespace CriTimeline.Atom + +} //namespace CriWare + +#endif \ No newline at end of file diff --git a/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/Extension/CriAtomClipWaveformCanvas.cs.meta b/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/Extension/CriAtomClipWaveformCanvas.cs.meta new file mode 100644 index 0000000..6f63be7 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/Extension/CriAtomClipWaveformCanvas.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f0f13bdc836d8464aabbebf21dab6560 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/Extension/CriAtomClipWaveformRender.shader b/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/Extension/CriAtomClipWaveformRender.shader new file mode 100644 index 0000000..01098fc --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/Extension/CriAtomClipWaveformRender.shader @@ -0,0 +1,84 @@ +Shader "CRIWARE/CriAtomClipWaveformRender" { +Properties{ + _MainTex("Main Texture", 2D) = "white" { } +} + +SubShader{ +Pass { + Tags { "RenderType" = "Opaque" } + Cull Off + ZWrite Off + ZTest Always + + CGPROGRAM +#pragma vertex vert +#pragma fragment frag +#include "UnityCG.cginc" + + uniform sampler2D _MainTex; + uniform float4 _MainTex_ST; + uniform fixed4 _BacCol; + uniform fixed4 _ForCol; + uniform float _Offset; + uniform float _Scale; + uniform int _IsLoop; + uniform int _IsMute; + uniform float _Channel; + uniform int _ForceMono; + + struct appdata { + float4 vertex : POSITION; + float4 texcoord : TEXCOORD0; + }; + + struct v2f { + float4 pos : SV_POSITION; + float2 uv : TEXCOORD0; + }; + + inline float zero_amplitude(v2f v, float volume) { + return floor(volume * 100.0) == 0.0 ? abs(ddy(v.uv.y)) : volume; + } + + v2f vert(appdata v) { + v2f o; + o.pos = UnityObjectToClipPos(v.vertex); + o.uv = TRANSFORM_TEX(v.texcoord, _MainTex); + o.uv.x *= _Scale; + o.uv.x += _Offset; + return o; + } + + fixed4 frag(v2f v) : SV_Target { + float channel_height = (1.0 / (_Channel)); + int ch = floor(v.uv.y / (1.0 / _Channel)) + 1; + + /* uv.y reads the values in reverse order of texture creation. */ + /* but _ForceMono is true, read the first channel at the end. */ + float2 ch_vec2 = {frac(v.uv.x), _Channel > 1 ? (ch - 1) * (1.0 / (_Channel - 1)) : 0.0 }; + ch_vec2.y = _ForceMono < 1 ? 1.0 - ch_vec2.y : ch_vec2.y; + + float volume_max = tex2D(_MainTex, ch_vec2).r * channel_height / 2.0; + volume_max = zero_amplitude(v, volume_max); + volume_max = v.uv.x > 1 && _IsLoop < 1 ? abs(ddy(v.uv.y)) : volume_max; + volume_max = _IsMute >= 1 ? abs(ddy(v.uv.y)) : volume_max; + + float volume_min = tex2D(_MainTex, ch_vec2).g * channel_height / 2.0; + volume_min = zero_amplitude(v, volume_min); + volume_min = v.uv.x > 1 && _IsLoop < 1 ? abs(ddy(v.uv.y)) : volume_min; + volume_min = _IsMute >= 1 ? abs(ddy(v.uv.y)) : volume_min; + + float uvY = v.uv.y - ((channel_height / 2.0) * ch * 2.0) + channel_height / 2.0; + fixed4 col = lerp( + _BacCol, + _ForCol, + -volume_min <= uvY && uvY <= volume_max + ); + clip(col.a - 0.5); + return col; + } + + ENDCG + } +} +} diff --git a/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/Extension/CriAtomClipWaveformRender.shader.meta b/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/Extension/CriAtomClipWaveformRender.shader.meta new file mode 100644 index 0000000..eeb3f12 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/Extension/CriAtomClipWaveformRender.shader.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: f420a9b00c3898a4eb0ed6f645a04081 +timeCreated: 1606370626 +licenseType: Pro +ShaderImporter: + externalObjects: {} + defaultTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/Extension/CriAtomTimelineDrawer.cs b/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/Extension/CriAtomTimelineDrawer.cs new file mode 100644 index 0000000..6ce6f95 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/Extension/CriAtomTimelineDrawer.cs @@ -0,0 +1,302 @@ +/**************************************************************************** + * + * Copyright (c) 2019 CRI Middleware Co., Ltd. + * + ****************************************************************************/ +//#define CRI_TIMELINE_ATOM_VERBOSE_DEBUG + +#if UNITY_2018_1_OR_NEWER && CRIWARE_TIMELINE_1_OR_NEWER + +using UnityEditor; +using UnityEngine; +using UnityEditor.Timeline; +using UnityEngine.Timeline; +using System.Runtime.InteropServices; +using System; +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace CriWare { + +namespace CriTimeline.Atom { + + [CustomPropertyDrawer(typeof(CriAtomBehaviour))] + public class CriAtomTimelineDrawer : PropertyDrawer { + public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { + SerializedProperty volumeProp = property.FindPropertyRelative("volume"); + SerializedProperty pitchProp = property.FindPropertyRelative("pitch"); + SerializedProperty aisacProp = property.FindPropertyRelative("AISACValue"); + + EditorGUILayout.PropertyField(volumeProp); + EditorGUILayout.PropertyField(pitchProp); + EditorGUILayout.PropertyField(aisacProp); + } + } + + [CustomEditor(typeof(CriAtomClipBase)), CanEditMultipleObjects] + public class CriAtomClipEditor : UnityEditor.Editor { } + + [CustomEditor(typeof(CriAtomTrack))] + public class CriAtomTrackEditor : UnityEditor.Editor { + private CriAtomTrack m_object; + + public void OnEnable() { + if (target != null) { + m_object = target as CriAtomTrack; + } + } + + public override void OnInspectorGUI() { + if (m_object == null) { + return; + } + + serializedObject.Update(); + EditorGUI.BeginChangeCheck(); + + + EditorGUILayout.LabelField("Track Settings", EditorStyles.boldLabel); + DrawLine(Color.black); + m_object.m_AisacControls + = EditorGUILayout.TextField("Aisac Control", m_object.m_AisacControls); + m_object.m_StopOnWrapping + = EditorGUILayout.Toggle("Stop On Wrapping", m_object.m_StopOnWrapping); + m_object.m_StopAtGraphEnd + = EditorGUILayout.Toggle("Stop At Graph End", m_object.m_StopAtGraphEnd); + + EditorGUILayout.Space(); + + EditorGUILayout.LabelField("Unity Editor", EditorStyles.boldLabel); + DrawLine(Color.black); + + m_object.m_IsRenderMono + = EditorGUILayout.Toggle("Show Mono Waveform", m_object.m_IsRenderMono); + + serializedObject.ApplyModifiedProperties(); + if (EditorGUI.EndChangeCheck()) { + EditorUtility.SetDirty(m_object); + } + } + + private static void DrawLine(Color color, int thickness = 1, int padding = 10) { + Rect rect = EditorGUILayout.GetControlRect(GUILayout.Height(padding + thickness)); + rect.height = thickness; + rect.y += padding / 2; + rect.x -= 2; + rect.width += 6; + EditorGUI.DrawRect(rect, color); + } + } + +#if UNITY_2019_3_OR_NEWER + + [CustomTimelineEditor(typeof(CriAtomClipBase))] + public class CriAtomClipWaveformEditor : UnityEditor.Timeline.ClipEditor { + private Dictionary atomClipPreviewDirectory + = new Dictionary(); + + public override void OnCreate(TimelineClip clip, TrackAsset track, TimelineClip clonedFrom) { + base.OnCreate(clip, track, clonedFrom); +#if CRI_TIMELINE_ATOM_VERBOSE_DEBUG + Debug.Log("[CRIWARE][Timeline] OnCreate"); +#endif + + atomClipPreviewDirectory.Clear(); + + CriAtomClipBase atomClip = clip.asset as CriAtomClipBase; + atomClipPreviewDirectory.Add(atomClip, new CriAtomClipWaveformPreviewer(atomClip)); + } + + public override void OnClipChanged(TimelineClip clip) { + base.OnClipChanged(clip); +#if CRI_TIMELINE_ATOM_VERBOSE_DEBUG + Debug.Log("[CRIWARE][Timeline] OnClipChanged"); +#endif + + CriAtomClipBase atomClip = clip.asset as CriAtomClipBase; + if (atomClipPreviewDirectory.ContainsKey(atomClip)) { + return; + } + atomClipPreviewDirectory.Add(atomClip, new CriAtomClipWaveformPreviewer(atomClip)); + } + + public override void DrawBackground(TimelineClip clip, ClipBackgroundRegion region) { + base.DrawBackground(clip, region); +#if CRI_TIMELINE_ATOM_VERBOSE_DEBUG + Debug.Log("[CRIWARE][Timeline] DrawBackground"); + + Debug.Log("region.startTime : " + region.startTime.ToString() + "region.endTime : " + region.endTime.ToString()); +#endif + + CriAtomClipBase atomClip = clip.asset as CriAtomClipBase; + CriAtomClipWaveformPreviewer atomClipPreviewer; + if (!atomClipPreviewDirectory.TryGetValue(atomClip, out atomClipPreviewer)) { +#if CRI_TIMELINE_ATOM_VERBOSE_DEBUG + Debug.LogError("[CRIWARE][Timeline] not contains key : " + clip.displayName); +#endif + return; + } + if (!atomClipPreviewer.HasDecodeTask()) { + atomClipPreviewDirectory.Remove(atomClip); + atomClipPreviewDirectory.Add(atomClip, new CriAtomClipWaveformPreviewer(atomClip)); + } + + if (!atomClipPreviewer.HasPreviewData()) { + /* While decoding or decode error. Skip renderring. */ + return; + } + + atomClipPreviewer.IsLooping = atomClip.loopWithinClip; + atomClipPreviewer.IsMuted = atomClip.muted; + CriAtomTrack atomTrack = clip.parentTrack as CriAtomTrack; + if (atomTrack.m_IsRenderMono) { + atomClipPreviewer.ChannelMode = CriAtomClipWaveformPreviewer.RenderChannelMode.Mono; + } else { + atomClipPreviewer.ChannelMode = CriAtomClipWaveformPreviewer.RenderChannelMode.All; + } + + if (Event.current.type == EventType.Repaint) { + atomClipPreviewer.RenderMaterial(region); + } + } + } + + public partial class CriAtomClipWaveformPreviewer { + /* Number of drawing channels */ + public enum RenderChannelMode { + Mono = 0, /* Mono(Left Channel) */ + All /* All Channels */ + } + + public bool IsLooping = false; + public bool IsMuted = true; + public RenderChannelMode ChannelMode = RenderChannelMode.Mono; + + private struct CriAtomClipWaveformInfo { + public CriAtomEx.WaveformInfo waveformInfo; + public double waveDurationSecond; + public Int16[] lpcmBufferByInterleave; + } + + private Task decodeTask = null; + private CriAtomClipWaveformInfo atomClipWaveformInfo; + private CriAtomClipWaveformCanvas simpleCanvas; + private CriAtomClipWaveformCanvas regionalCanvas; + + public CriAtomClipWaveformPreviewer(CriAtomClipBase criAtomClip) { + if (!CriAtomTimelinePreviewer.IsInitialized || string.IsNullOrEmpty(criAtomClip.AcbPath)) { + return; + } + var acb = CriAtomTimelinePreviewer.Instance.GetAcb(criAtomClip.AcbPath, criAtomClip.AwbPath); + if (acb == null) { + Debug.LogError("[CRIWARE][Timeline] faild to load acb object."); + return; + } + + decodeTask = Task.Run(() => + { + this.atomClipWaveformInfo = new CriAtomClipWaveformInfo(); + if (!acb.GetWaveFormInfo(criAtomClip.CueName, out this.atomClipWaveformInfo.waveformInfo)) { + /* without waveform */ + return; + } + this.atomClipWaveformInfo.lpcmBufferByInterleave = new Int16[this.atomClipWaveformInfo.waveformInfo.numSamples * this.atomClipWaveformInfo.waveformInfo.numChannels]; + if (!LoadWaveform(acb.nativeHandle, criAtomClip.CueName, ref this.atomClipWaveformInfo.lpcmBufferByInterleave)) { + this.atomClipWaveformInfo.lpcmBufferByInterleave = null; + return; + } + this.atomClipWaveformInfo.waveDurationSecond = this.atomClipWaveformInfo.waveformInfo.numSamples / (double)this.atomClipWaveformInfo.waveformInfo.samplingRate; + }); + + simpleCanvas = new CriAtomClipWaveformCanvas(); + simpleCanvas.updated += () => { + TimelineEditor.Refresh(RefreshReason.WindowNeedsRedraw); + }; + regionalCanvas = new CriAtomClipWaveformCanvas(); + regionalCanvas.updated += () => { + TimelineEditor.Refresh(RefreshReason.WindowNeedsRedraw); + }; + } + + ~CriAtomClipWaveformPreviewer() { + if (decodeTask != null) { + if (!decodeTask.IsCompleted) { + decodeTask.Wait(); + } + decodeTask.Dispose(); + decodeTask = null; + } + simpleCanvas.Dispose(); + simpleCanvas = null; + regionalCanvas.Dispose(); + regionalCanvas = null; + } + + public bool HasDecodeTask() { + return decodeTask == null ? false : true; + } + + public bool HasPreviewData() { + if (decodeTask == null || decodeTask.IsFaulted || decodeTask.IsCanceled || !decodeTask.IsCompleted) { + return false; + } + /* decodeTask.IsCompleted == true and buffer == null is decode error. */ + return this.atomClipWaveformInfo.lpcmBufferByInterleave != null; + } + + public void RenderMaterial(ClipBackgroundRegion region) { + if (region.position.height <= 0 | region.position.width <= 0) { + /* region.position is invalid. */ + return; + } + + simpleCanvas.UpdateTexture(ref this.atomClipWaveformInfo, this.IsLooping, renderOnce:true); + regionalCanvas.UpdateTexture(ref this.atomClipWaveformInfo, this.IsLooping, region); + + simpleCanvas.SetMatParams( + channelMode: ChannelMode, + numChannels: this.atomClipWaveformInfo.waveformInfo.numChannels, + isLooping: this.IsLooping, + isMuted: this.IsMuted, + scale: (float)((region.endTime - region.startTime) / this.atomClipWaveformInfo.waveDurationSecond), + offset: (float)(region.startTime / this.atomClipWaveformInfo.waveDurationSecond)); + + regionalCanvas.SetMatParams( + channelMode: ChannelMode, + numChannels: this.atomClipWaveformInfo.waveformInfo.numChannels, + isLooping: this.IsLooping, + isMuted: this.IsMuted, + scale: 1f, + offset: 0); + + if (regionalCanvas.IsDirty) { + simpleCanvas.Draw(region.position); + } else { + regionalCanvas.Draw(region.position); + } + } + + private static bool LoadWaveform(IntPtr acbHn, string cueName, ref System.Int16[] decodeLpcmBuffer) { + var gcHandle = GCHandle.Alloc(decodeLpcmBuffer, GCHandleType.Pinned); + var result = CRIWAREF2B79675(acbHn, cueName, gcHandle.AddrOfPinnedObject(), decodeLpcmBuffer.LongLength); + gcHandle.Free(); + return result; + } + + #region DLL Import +#if !CRIWARE_ENABLE_HEADLESS_MODE + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool CRIWAREF2B79675(IntPtr acbHn, string cue_name, IntPtr decode_lpcm_buffer, System.Int64 decodeLpcmBufferLength); +#else + private static bool CRIWAREF2B79675(IntPtr acbHn, string cue_name, IntPtr decode_lpcm_buffer, System.Int64 decodeLpcmBufferLength) {return false;} +#endif + #endregion + } + +#endif //UNITY_2019_3_OR_NEWER + +} + +} //namespace CriWare + +#endif //UNITY_2018_1_OR_NEWER \ No newline at end of file diff --git a/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/Extension/CriAtomTimelineDrawer.cs.meta b/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/Extension/CriAtomTimelineDrawer.cs.meta new file mode 100644 index 0000000..ed57cf6 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Editor/CriAtom/Extension/CriAtomTimelineDrawer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 64709c1c359e022439e2bde0e6afa2d4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Editor/CriLogConsole.cs b/Assets/Scripts/CRIMW/CriWare/Editor/CriLogConsole.cs new file mode 100644 index 0000000..2fe7199 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Editor/CriLogConsole.cs @@ -0,0 +1,321 @@ +/**************************************************************************** + * + * Copyright (c) CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +using System.Collections.Generic; +using System.IO; +using System.Text.RegularExpressions; +using UnityEditor; +using UnityEngine; + +namespace CriWare.Editor { + + public class CriLogConsole : EditorWindow + { + private const int logLineCount = 2; + private const int logBoxHeight = logLineCount * 16; + private const string PATTERN_W = "W[0-9]{8,12}M{0,1}"; + private const string PATTERN_E = "E[0-9]{8,12}M{0,1}"; + + private Rect upperArea; + private Rect lowerArea; + private Rect dividingLine; + private Rect menuBar; + + private Texture2D selectedBoxBg; + private Texture2D oddBoxBg; + private Texture2D infoIcon; + private Texture2D errorIcon; + private Texture2D warningIcon; + + private float sizeRatio = 0.5f; + private float middleLineHeight = 10f; + private float menuBarHeight = 20f; + + private bool repaintDividingLine; + private bool isManualButtonActive = false; + private bool needToResetScrollBar = true; + + private Vector2 lowerPanelScroll; + private Vector2 upperPanelScrollPos; + + private GUIStyle dividingLineStyle; + private GUIStyle lowerAreaStyle; + private GUIStyle upperAreaLogStyle; + + private string manualServerUrl = "https://docs.criware.jp/error/common/"; + private string[] optionLanguage = { "jpn", "eng" }; + private int optionLanguageIndex; + private List logDataList; + private LogData selectedLog; + + [MenuItem("Window/CRIWARE/CRI Log Console")] + private static void OpenWindow() { + CriLogConsole criLogConsole = GetWindow(); + criLogConsole.titleContent = new GUIContent("CRI Log Console"); + } + + private class LogData { + public bool isSelected; + public string logContent; + public LogType type; + public string errorNumber; + + public LogData(bool isSelected, string logContent, LogType type, string errorNumber) { + this.isSelected = isSelected; + this.logContent = logContent; + this.type = type; + this.errorNumber = errorNumber; + } + + public LogData(bool isSelected, string logContent, LogType type) { + this.isSelected = isSelected; + this.logContent = logContent; + this.type = type; + + var matchW = Regex.Match(logContent, PATTERN_W); + var matchE = Regex.Match(logContent, PATTERN_E); + if(matchW.Success) { + errorNumber = matchW.ToString(); + } else if(matchE.Success) { + errorNumber = matchE.ToString(); + } else { + errorNumber = ""; + } + } + } + + private void OnEnable() { + errorIcon = EditorGUIUtility.Load("icons/console.erroricon.png") as Texture2D; + warningIcon = EditorGUIUtility.Load("icons/console.warnicon.png") as Texture2D; + infoIcon = EditorGUIUtility.Load("icons/console.infoicon.png") as Texture2D; + + dividingLineStyle = new GUIStyle(); + upperAreaLogStyle = new GUIStyle(); + lowerAreaStyle = new GUIStyle(); + dividingLineStyle.normal.background = EditorGUIUtility.Load("icons/d_AvatarBlendBackground.png") as Texture2D; + upperAreaLogStyle.normal.textColor = new Color(0.7f, 0.7f, 0.7f); + lowerAreaStyle.normal.textColor = new Color(0.9f, 0.9f, 0.9f); + lowerAreaStyle.normal.background = EditorGUIUtility.Load("builtin skins/darkskin/images/projectbrowsericonareabg.png") as Texture2D; + + oddBoxBg = EditorGUIUtility.Load("builtin skins/darkskin/images/cn entrybackodd.png") as Texture2D; + selectedBoxBg = EditorGUIUtility.Load("builtin skins/darkskin/images/menuitemhover.png") as Texture2D; + + if (logDataList == null) { + logDataList = new List(); + } + selectedLog = null; + Application.logMessageReceived += OnLogMessageReceived; + } + + private void Awake() { + logDataList = new List(); + ParseUnityLogFile(CriWareErrorHandler.logPrefix); + } + + private void OnDisable() { + Application.logMessageReceived -= OnLogMessageReceived; + } + + private void OnDestroy() { + Application.logMessageReceived -= OnLogMessageReceived; + } + + private void OnGUI() { + GenerateManualBar(); + GenerateUpperArea(); + GenerateLowerArea(); + GenerateDividingLine(); + DividingLineEvent(Event.current); + if (GUI.changed) { + Repaint(); + } + } + + private void GenerateManualBar() { + menuBar = new Rect(0, 0, position.width, menuBarHeight); + GUILayout.BeginArea(menuBar, EditorStyles.toolbar); + GUILayout.BeginHorizontal(); + if (GUILayout.Button(new GUIContent("Clear"), EditorStyles.toolbarButton, GUILayout.Width(50))) { + logDataList.Clear(); + selectedLog = null; + isManualButtonActive = false; + } + GUILayout.Space(5); + + GUI.enabled = isManualButtonActive; + if (GUILayout.Button(new GUIContent("Open Online Manual"), EditorStyles.toolbarButton, GUILayout.Width(130))) { + if (selectedLog != null) { + ShowManualFromBrowser(selectedLog.errorNumber); + } + } + GUI.enabled = true; + + optionLanguageIndex = EditorGUILayout.Popup("Language", optionLanguageIndex, optionLanguage); + GUILayout.FlexibleSpace(); + GUILayout.EndHorizontal(); + GUILayout.EndArea(); + } + + private void GenerateUpperArea() { + upperArea = new Rect(0, menuBarHeight, position.width, (position.height * sizeRatio) - menuBarHeight); + GUILayout.BeginArea(upperArea); + if (needToResetScrollBar) { + upperPanelScrollPos = new Vector2(0, position.height * sizeRatio); + needToResetScrollBar = false; + } + using (var upperPanelScope = new EditorGUILayout.ScrollViewScope(upperPanelScrollPos, GUILayout.ExpandHeight(true))) { + upperPanelScrollPos = upperPanelScope.scrollPosition; + int listNumInView = ((int)(position.height * sizeRatio) - (int)menuBarHeight) / logBoxHeight; + int firstLogId = Mathf.Clamp((int)upperPanelScrollPos.y / logBoxHeight, 0, Mathf.Max(0, logDataList.Count - listNumInView)); + GUILayout.Space(logBoxHeight * firstLogId); + for (int i = firstLogId; i < Mathf.Min(firstLogId + listNumInView, logDataList.Count); ++i) { + string InfoShownOnBox = ""; + StringReader rs = new System.IO.StringReader(logDataList[i].logContent); + for (int x = 0; x < logLineCount; ++x) { + InfoShownOnBox = InfoShownOnBox + rs.ReadLine(); + if (x != logLineCount - 1) { + InfoShownOnBox = InfoShownOnBox + "\r\n"; + } + } + if (GenerateLogBox(InfoShownOnBox, logDataList[i].type, i % 2 == 0, logDataList[i].isSelected)) { + if (selectedLog != null) { + selectedLog.isSelected = false; + } + logDataList[i].isSelected = true; + selectedLog = logDataList[i]; + if (selectedLog.errorNumber != "") { + isManualButtonActive = true; + } else { + isManualButtonActive = false; + } + } + } + GUILayout.Space(Mathf.Max(0, logDataList.Count - firstLogId - listNumInView) * logBoxHeight); + } + GUILayout.EndArea(); + } + + private void GenerateLowerArea() { + lowerArea = new Rect(0, position.height * sizeRatio, position.width, position.height * (1 - sizeRatio)); + GUILayout.BeginArea(lowerArea); + lowerPanelScroll = GUILayout.BeginScrollView(lowerPanelScroll); + if (selectedLog != null) { + GUILayout.TextArea(selectedLog.logContent, lowerAreaStyle); + } + if (isManualButtonActive) { + if (GUILayout.Button(new GUIContent("Open Online Manual"), GUILayout.Width(130))) { + ShowManualFromBrowser(selectedLog.errorNumber); + } + } + GUILayout.EndScrollView(); + GUILayout.EndArea(); + } + + private void GenerateDividingLine() { + dividingLine = new Rect(0, (position.height * sizeRatio) - middleLineHeight, position.width, middleLineHeight * 2); + GUILayout.BeginArea(new Rect(dividingLine.position + (Vector2.up * middleLineHeight), new Vector2(position.width, 2)), dividingLineStyle); + GUILayout.EndArea(); + EditorGUIUtility.AddCursorRect(dividingLine, MouseCursor.ResizeVertical); + } + + private void DividingLineEvent(Event mouseEvent) { + if (mouseEvent.type == EventType.MouseDown && mouseEvent.button == 0 && dividingLine.Contains(mouseEvent.mousePosition)) { + sizeRatio = mouseEvent.mousePosition.y / position.height; + Repaint(); + } + } + + private bool GenerateLogBox(string content, LogType boxType, bool isOdd, bool isSelected) { + Texture2D icon = null; + upperAreaLogStyle.normal.background = isSelected ? selectedBoxBg : oddBoxBg; + switch (boxType) { + case LogType.Error: + icon = errorIcon; + break; + case LogType.Warning: + icon = warningIcon; + break; + case LogType.Log: + icon = infoIcon; + break; + default: + break; + } + GUIContent buttonContent = new GUIContent(content, icon); + return GUILayout.Button(buttonContent, upperAreaLogStyle, GUILayout.ExpandWidth(true), GUILayout.Height(logBoxHeight)); + } + + private bool IsCriLogCheck(string log) { + return log.Contains(CriWareErrorHandler.logPrefix); + } + + private void OnLogMessageReceived(string condition, string stackTrace, LogType type) { + bool isCri = IsCriLogCheck(condition); + if (!isCri) { + return; + } + string templogstring = condition + "\n" + stackTrace; + LogData tmpLog = new LogData(false, templogstring, type); + logDataList.Add(tmpLog); + needToResetScrollBar = true; + Repaint(); + } + + private void ShowManualFromBrowser(string errorNum) { + Application.OpenURL(GenerateManualUrl(errorNum)); + } + + private string GenerateManualUrl(string errorNum) { + return manualServerUrl + optionLanguage[optionLanguageIndex] + "/cri_external_error_list.html#" + errorNum; + } + + private void ParseUnityLogFile(string keyword) { + bool foundCriLog = false; + string criTmpFilePath = System.IO.Path.Combine(Path.GetTempPath() + "/Editor.log"); + try { + File.Copy(Application.consoleLogPath, criTmpFilePath); + string parsedLog = ""; + foreach (string line in File.ReadLines(criTmpFilePath)) { + if (!foundCriLog) { + if (line.Contains(keyword)) { + parsedLog = line + "\r\n"; + foundCriLog = true; + } + } else { + if (line != "") { + parsedLog = parsedLog + line + "\r\n"; + } else { + CategorizeLog(parsedLog); + foundCriLog = false; + } + } + } + } catch (IOException copyError) { + Debug.Log(copyError.Message); + return; + } + + try { + File.Delete(criTmpFilePath); + } catch (IOException deleteError) { + Debug.Log(deleteError.Message); + } + } + + private void CategorizeLog(string log) { + var matchW = Regex.Match(log, PATTERN_W); + var matchE = Regex.Match(log, PATTERN_E); + if(matchW.Success) { + logDataList.Add(new LogData(false, log, LogType.Warning, matchW.ToString())); + } else if(matchE.Success) { + logDataList.Add(new LogData(false, log, LogType.Error, matchE.ToString())); + } else { + logDataList.Add(new LogData(false, log, LogType.Log, "")); + } + } + } + +} //namespace CriWare.Editor \ No newline at end of file diff --git a/Assets/Scripts/CRIMW/CriWare/Editor/CriLogConsole.cs.meta b/Assets/Scripts/CRIMW/CriWare/Editor/CriLogConsole.cs.meta new file mode 100644 index 0000000..b9c375d --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Editor/CriLogConsole.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 189064c72c85d7c419a4bc2d55d2bbb2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Editor/CriMana.meta b/Assets/Scripts/CRIMW/CriWare/Editor/CriMana.meta new file mode 100644 index 0000000..13b791f --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Editor/CriMana.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: a6fe224288ee5bc47b8c9e7bdabef791 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Editor/CriMana/CriManaMovieControllerEditor.cs b/Assets/Scripts/CRIMW/CriWare/Editor/CriMana/CriManaMovieControllerEditor.cs new file mode 100644 index 0000000..90dbaad --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Editor/CriMana/CriManaMovieControllerEditor.cs @@ -0,0 +1,106 @@ +/**************************************************************************** + * + * Copyright (c) 2015 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +using UnityEngine; +using UnityEditor; + +namespace CriWare { + +[CustomEditor(typeof(CriManaMovieController))] +public class CriManaMovieControllerEditor : UnityEditor.Editor +{ + private CriManaMovieController source = null; + + private void OnEnable() + { + source = (CriManaMovieController)base.target; + } + + public override void OnInspectorGUI() + { + if (this.source == null) { + return; + } + + Undo.RecordObject(target, null); + + GUI.changed = false; + { + EditorGUILayout.PrefixLabel("Startup Parameters"); + ++EditorGUI.indentLevel; + { + + EditorGUI.BeginChangeCheck(); + string moviePath = EditorGUILayout.TextField(new GUIContent("Movie Path", "The path to the movie file."), source.moviePath); + if (EditorGUI.EndChangeCheck()) { + source.moviePath = moviePath; + } + source.playOnStart = EditorGUILayout.Toggle(new GUIContent("Play On Start", "Immediatly play movie after Start of the component."), source.playOnStart); + EditorGUI.BeginChangeCheck(); + bool loop = EditorGUILayout.Toggle(new GUIContent("Loop", "Movie is played in continuous loop."), source.loop); + if (EditorGUI.EndChangeCheck()) { + source.loop = loop; + } + source.restartOnEnable = EditorGUILayout.Toggle(new GUIContent("Restart On Enable", "Restart playback after disabling and then enabling the component."), source.restartOnEnable); + EditorGUI.BeginChangeCheck(); + bool advancedAudioMode = EditorGUILayout.BeginToggleGroup(new GUIContent("Advanced Audio Mode", "Enable advanced audio mode."), source.advancedAudio); + if (EditorGUI.EndChangeCheck()) + { + source.advancedAudio = advancedAudioMode; + } + if (source.advancedAudio) + { + EditorGUI.indentLevel += 2; + EditorGUI.BeginChangeCheck(); + bool useAmbisonics = EditorGUILayout.Toggle(new GUIContent("Ambisonics", "Use Ambisonics."), source.ambisonics); + if (EditorGUI.EndChangeCheck()) + { + source.ambisonics = useAmbisonics; + } + EditorGUI.indentLevel -= 2; + } + EditorGUILayout.EndToggleGroup(); + } + --EditorGUI.indentLevel; + EditorGUILayout.PrefixLabel("Render Parameters"); + ++EditorGUI.indentLevel; + { + + EditorGUI.BeginChangeCheck(); + bool additiveMode = EditorGUILayout.Toggle(new GUIContent("Additive Mode", "Movie is rendered in additive blend mode."), source.additiveMode); + if (EditorGUI.EndChangeCheck()) { + source.additiveMode = additiveMode; + } + source.material = (Material)EditorGUILayout.ObjectField(new GUIContent("Material", + "The material to render movie.\n" + + "If 'none' use an internal default material."), source.material, typeof(Material), true); + source.renderMode = (CriManaMovieMaterialBase.RenderMode)EditorGUILayout.EnumPopup(new GUIContent("Render Mode", + "- Always: Render movie at each frame.\n" + + "- OnVisibility: Render movie only when owner GameObject or Renderer Target is visible.\nOptimization when movie is not visible on screen.\n" + + "- Never: Never render movie to the material. You need to call 'RenderMovie()' to control rendering."), source.renderMode); + source.maxFrameDrop = (CriManaMovieMaterialBase.MaxFrameDrop)EditorGUILayout.EnumPopup(new GUIContent("Max Frame Drop", + "- Disable: Disable frame dropping.\n" + + "- One~Ten: Drops one or more maximum frames before each rendering if not in-sync.\n" + + "- Infinite: Drops all frames until playback is in-sync.\n" + + "Default is 'Two'."), source.maxFrameDrop); + + EditorGUILayout.PrefixLabel("Renderer Control"); + ++EditorGUI.indentLevel; + { + source.target = (Renderer)EditorGUILayout.ObjectField(new GUIContent("Target", "Renderer object target to override its material with movie material.\nIf 'none', use owner GameObject Renderer if present."), source.target, typeof(Renderer), true); + source.useOriginalMaterial = EditorGUILayout.Toggle(new GUIContent("Use Original Material", "If set to 'true', use the original Renderer Target material when movie is stopped."), source.useOriginalMaterial); + } + --EditorGUI.indentLevel; + } + --EditorGUI.indentLevel; + } + if (GUI.changed) { + EditorUtility.SetDirty(this.source); + } + } +} + +} //namespace CriWare \ No newline at end of file diff --git a/Assets/Scripts/CRIMW/CriWare/Editor/CriMana/CriManaMovieControllerEditor.cs.meta b/Assets/Scripts/CRIMW/CriWare/Editor/CriMana/CriManaMovieControllerEditor.cs.meta new file mode 100644 index 0000000..31e3ffa --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Editor/CriMana/CriManaMovieControllerEditor.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 90f75aa41c1f34217898c275711b3e73 +timeCreated: 1445241046 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Editor/CriMana/CriManaMovieControllerForUIEditor.cs b/Assets/Scripts/CRIMW/CriWare/Editor/CriMana/CriManaMovieControllerForUIEditor.cs new file mode 100644 index 0000000..aacd984 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Editor/CriMana/CriManaMovieControllerForUIEditor.cs @@ -0,0 +1,91 @@ +/**************************************************************************** + * + * Copyright (c) 2015 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +using UnityEngine; +using UnityEditor; + +namespace CriWare { + +[CustomEditor(typeof(CriManaMovieControllerForUI))] +public class CriManaMovieControllerForUIEditor : UnityEditor.Editor +{ + private CriManaMovieControllerForUI source = null; + + private void OnEnable() + { + source = (CriManaMovieControllerForUI)base.target; + } + + public override void OnInspectorGUI() + { + if (this.source == null) { + return; + } + + Undo.RecordObject(target, null); + + GUI.changed = false; + { + EditorGUILayout.PrefixLabel("Startup Parameters"); + ++EditorGUI.indentLevel; + { + EditorGUI.BeginChangeCheck(); + string moviePath = EditorGUILayout.TextField(new GUIContent("Movie Path", "The path to the movie file."), source.moviePath); + if (EditorGUI.EndChangeCheck()) { + source.moviePath = moviePath; + } + source.playOnStart = EditorGUILayout.Toggle(new GUIContent("Play On Start", "Immediatly play movie after Start of the component."), source.playOnStart); + EditorGUI.BeginChangeCheck(); + bool loop = EditorGUILayout.Toggle(new GUIContent("Loop", "Movie is played in continuous loop."), source.loop); + if (EditorGUI.EndChangeCheck()) { + source.loop = loop; + } + source.restartOnEnable = EditorGUILayout.Toggle(new GUIContent("Restart On Enable", "Restart playback after disabling and then enabling the component."), source.restartOnEnable); + } + --EditorGUI.indentLevel; + ++EditorGUI.indentLevel; + { + EditorGUILayout.PrefixLabel("Render Parameters"); + EditorGUI.BeginChangeCheck(); + bool additiveMode = EditorGUILayout.Toggle(new GUIContent("Additive Mode", "Movie is rendered in additive blend mode."), source.additiveMode); + if (EditorGUI.EndChangeCheck()) { + source.additiveMode = additiveMode; + } + EditorGUI.BeginChangeCheck(); + bool applyTargetAlpha = EditorGUILayout.Toggle(new GUIContent("Apply Target Alpha", "Movie is rendered with Alpha color of the attached object."), source.applyTargetAlpha); + if (EditorGUI.EndChangeCheck()) { + source.applyTargetAlpha = applyTargetAlpha; + } + source.material = (Material)EditorGUILayout.ObjectField(new GUIContent("Material", + "The material to render movie.\n" + + "If 'none' use an internal default material."), source.material, typeof(Material), true); + source.renderMode = (CriManaMovieMaterialBase.RenderMode)EditorGUILayout.EnumPopup(new GUIContent("Render Mode", + "- Always: Render movie at each frame.\n" + + "- OnVisibility: Render movie only when owner GameObject is visible or UI.Graphic Target is active. Optimization when movie is not visible on screen.\n" + + "- Never: Never render movie to the material. You need to call 'RenderMovie()' to control rendering."), source.renderMode); + source.maxFrameDrop = (CriManaMovieMaterialBase.MaxFrameDrop)EditorGUILayout.EnumPopup(new GUIContent("Max Frame Drop", + "- Disable: Disable frame dropping.\n" + + "- One~Ten: Drops one or more maximum frames before each rendering if not in-sync.\n" + + "- Infinite: Drops all frames until playback is in-sync.\n" + + "Default is 'Two'."), source.maxFrameDrop); + + EditorGUILayout.PrefixLabel("Renderer Control"); + ++EditorGUI.indentLevel; + { + source.target = (UnityEngine.UI.Graphic)EditorGUILayout.ObjectField("Target", source.target, typeof(UnityEngine.UI.Graphic), true); + source.useOriginalMaterial = EditorGUILayout.Toggle("Use Original Material", source.useOriginalMaterial); + } + --EditorGUI.indentLevel; + } + --EditorGUI.indentLevel; + } + if (GUI.changed) { + EditorUtility.SetDirty(this.source); + } + } +} + +} //namespace CriWare \ No newline at end of file diff --git a/Assets/Scripts/CRIMW/CriWare/Editor/CriMana/CriManaMovieControllerForUIEditor.cs.meta b/Assets/Scripts/CRIMW/CriWare/Editor/CriMana/CriManaMovieControllerForUIEditor.cs.meta new file mode 100644 index 0000000..a998b6f --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Editor/CriMana/CriManaMovieControllerForUIEditor.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: fe74e047c1a2845458bd23c1670338b4 +timeCreated: 1445245705 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Editor/CriMana/CriManaMovieMaterialEditor.cs b/Assets/Scripts/CRIMW/CriWare/Editor/CriMana/CriManaMovieMaterialEditor.cs new file mode 100644 index 0000000..2c1e7c3 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Editor/CriMana/CriManaMovieMaterialEditor.cs @@ -0,0 +1,78 @@ +/**************************************************************************** + * + * Copyright (c) 2015 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +using UnityEngine; +using UnityEditor; + +namespace CriWare { + +[CustomEditor(typeof(CriManaMovieMaterial))] +public class CriManaMovieMaterialEditor : UnityEditor.Editor +{ + private CriManaMovieMaterial source = null; + + private void OnEnable() + { + source = (CriManaMovieMaterial)base.target; + } + + public override void OnInspectorGUI() + { + if (this.source == null) { + return; + } + + Undo.RecordObject(target, null); + + GUI.changed = false; + { + EditorGUILayout.PrefixLabel("Startup Parameters"); + ++EditorGUI.indentLevel; + { + EditorGUI.BeginChangeCheck(); + string moviePath = EditorGUILayout.TextField(new GUIContent("Movie Path", "The path to the movie file."), source.moviePath); + if (EditorGUI.EndChangeCheck()) { + source.moviePath = moviePath; + } + source.playOnStart = EditorGUILayout.Toggle(new GUIContent("Play On Start", "Immediatly play movie after Start of the component."), source.playOnStart); + EditorGUI.BeginChangeCheck(); + bool loop = EditorGUILayout.Toggle(new GUIContent("Loop", "Movie is played in continuous loop."), source.loop); + if (EditorGUI.EndChangeCheck()) { + source.loop = loop; + } + source.restartOnEnable = EditorGUILayout.Toggle(new GUIContent("Restart On Enable", "Restart playback after disabling and then enabling the component."), source.restartOnEnable); + } + --EditorGUI.indentLevel; + EditorGUILayout.PrefixLabel("Render Parameters"); + ++EditorGUI.indentLevel; + { + EditorGUI.BeginChangeCheck(); + bool additiveMode = EditorGUILayout.Toggle(new GUIContent("Additive Mode", "Movie is rendered in additive blend mode."), source.additiveMode); + if (EditorGUI.EndChangeCheck()) { + source.additiveMode = additiveMode; + } + source.material = (Material)EditorGUILayout.ObjectField(new GUIContent("Material", + "The material to render movie.\n" + + "If 'none' use an internal default material."), source.material, typeof(Material), true); + source.renderMode = (CriManaMovieMaterial.RenderMode)EditorGUILayout.EnumPopup(new GUIContent("Render Mode", + "- Always: Render movie at each frame.\n" + + "- OnVisibility: Render movie only when owner GameObject is visible. Optimization when movie is not visible on screen.\n" + + "- Never: Never render movie to the material. You need to call 'RenderMovie()' to control rendering."), source.renderMode); + source.maxFrameDrop = (CriManaMovieMaterial.MaxFrameDrop)EditorGUILayout.EnumPopup(new GUIContent("Max Frame Drop", + "- Disabled: Disable frame dropping.\n" + + "- One~Ten: Drops successively one or more frames at maximum if not in-sync.\n" + + "- Infinite: Drops all frames until playback is in-sync.\n" + + "Default is 'Disabled'."), source.maxFrameDrop); + } + --EditorGUI.indentLevel; + } + if (GUI.changed) { + EditorUtility.SetDirty(this.source); + } + } +} + +} //namespace CriWare \ No newline at end of file diff --git a/Assets/Scripts/CRIMW/CriWare/Editor/CriMana/CriManaMovieMaterialEditor.cs.meta b/Assets/Scripts/CRIMW/CriWare/Editor/CriMana/CriManaMovieMaterialEditor.cs.meta new file mode 100644 index 0000000..0b16256 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Editor/CriMana/CriManaMovieMaterialEditor.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 397790fc6753445de95b2745a82b84aa +timeCreated: 1445249558 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Editor/CriMana/Extension.meta b/Assets/Scripts/CRIMW/CriWare/Editor/CriMana/Extension.meta new file mode 100644 index 0000000..413fe6e --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Editor/CriMana/Extension.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 28f29c601d9172d42a399e65de50bd21 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Editor/CriMana/Extension/CriManaTimelineDrawer.cs b/Assets/Scripts/CRIMW/CriWare/Editor/CriMana/Extension/CriManaTimelineDrawer.cs new file mode 100644 index 0000000..3a0746c --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Editor/CriMana/Extension/CriManaTimelineDrawer.cs @@ -0,0 +1,172 @@ +/**************************************************************************** + * + * Copyright (c) 2019 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +#if UNITY_2018_1_OR_NEWER && CRIWARE_TIMELINE_1_OR_NEWER + +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using UnityEditor; +using System.Text.RegularExpressions; +using UnityEditor.Timeline; +using UnityEngine.Timeline; + +namespace CriWare { + +namespace CriTimeline.Mana +{ + [CustomEditor(typeof(CriManaClip)), CanEditMultipleObjects] + public class CriManaTimelineComponentEditor : UnityEditor.Editor + { + private SerializedObject m_object; + private SerializedProperty m_filePath; + private SerializedProperty m_loopWithinClip; + private SerializedProperty m_movieFrameRate; + private SerializedProperty m_clipDuration; + private SerializedProperty m_movieData; + private SerializedProperty m_useOnMemoryPlayback; + private SerializedProperty m_fadeinDuration; + private SerializedProperty m_fadeinCurve; + private SerializedProperty m_fadeoutDuration; + private SerializedProperty m_fadeoutCurve; + private SerializedProperty m_fadeAudio; + + public void OnEnable() + { + if (target != null) { + m_object = new SerializedObject(target); + m_filePath = m_object.FindProperty("m_moviePath"); + m_loopWithinClip = m_object.FindProperty("m_loopWithinClip"); + m_movieFrameRate = m_object.FindProperty("m_movieFrameRate"); + m_clipDuration = m_object.FindProperty("m_clipDuration"); + m_movieData = m_object.FindProperty("m_movieData"); + m_useOnMemoryPlayback = m_object.FindProperty("m_useOnMemoryPlayback"); + m_fadeinDuration = m_object.FindProperty("m_fadeinDuration"); + m_fadeoutDuration = m_object.FindProperty("m_fadeoutDuration"); + m_fadeAudio = m_object.FindProperty("m_fadeAudio"); + m_fadeinCurve = m_object.FindProperty("m_fadeinCurve"); + m_fadeoutCurve = m_object.FindProperty("m_fadeoutCurve"); + } + } + + public override void OnInspectorGUI() + { + if (m_object == null || + m_filePath == null || + m_loopWithinClip == null) { + return; + } + + m_object.Update(); + EditorGUILayout.PropertyField(m_useOnMemoryPlayback); + EditorGUILayout.PropertyField(m_movieData); + if (m_useOnMemoryPlayback.boolValue) { + GUI.enabled = false; + } + + EditorGUILayout.PropertyField(m_filePath); + + Event evt = Event.current; + Rect moviePathFieldRect = GUILayoutUtility.GetLastRect(); + int id = GUIUtility.GetControlID(FocusType.Passive); + switch (evt.type) { + case EventType.DragUpdated: + case EventType.DragPerform: + if (!moviePathFieldRect.Contains(evt.mousePosition)) { + break; + } + DragAndDrop.visualMode = DragAndDropVisualMode.Copy; + DragAndDrop.activeControlID = id; + if (evt.type == EventType.DragPerform) { + DragAndDrop.AcceptDrag(); + foreach (var path in DragAndDrop.paths) { + if (System.IO.Path.GetExtension(path).Equals(".usm")) { + string[] splitPath = Regex.Split(path, "Assets/StreamingAssets/"); + if(splitPath.Length < 2) { + Debug.LogWarning("[Warning] Not in StreamingAssets Folder [" + System.IO.Path.GetFileName(path) + "]."); + } else { + m_filePath.stringValue = splitPath[1]; + } + + } else { + Debug.LogWarning("[Warning] Not usm file [" + System.IO.Path.GetFileName(path) + "]."); + } + } + DragAndDrop.activeControlID = 0; + } + Event.current.Use(); + break; + } + + EditorGUI.indentLevel++; + GUI.enabled = false; + EditorGUILayout.PropertyField(m_movieFrameRate); + EditorGUILayout.PropertyField(m_clipDuration); + GUI.enabled = true; + EditorGUI.indentLevel--; + EditorGUILayout.PropertyField(m_loopWithinClip); + + if ((target as CriManaClip).m_clip == null) return; + var duration = (target as CriManaClip).m_clip.duration; + EditorGUILayout.LabelField("Fade In", EditorStyles.boldLabel); + EditorGUI.indentLevel++; + EditorGUILayout.Slider(m_fadeinDuration, 0, (float)duration - m_fadeoutDuration.floatValue, new GUIContent("Duration [sec]")); + EditorGUILayout.CurveField(m_fadeinCurve, Color.cyan, new Rect(0, 0, 1, 1), new GUIContent("Curve")); + EditorGUI.indentLevel--; + EditorGUILayout.LabelField("Fade Out", EditorStyles.boldLabel); + EditorGUI.indentLevel++; + EditorGUILayout.Slider(m_fadeoutDuration, 0, (float)duration-m_fadeinDuration.floatValue, new GUIContent("Duration [sec]")); + EditorGUILayout.CurveField(m_fadeoutCurve, Color.cyan, new Rect(0, 0, 1, 1), new GUIContent("Curve")); + EditorGUI.indentLevel--; + EditorGUILayout.PropertyField(m_fadeAudio); + + m_object.ApplyModifiedProperties(); + } + } + +#if UNITY_2019_3_OR_NEWER + + [CustomTimelineEditor(typeof(CriManaClip))] + public class CriManaClipEditor : ClipEditor + { + public override void DrawBackground(TimelineClip clip, ClipBackgroundRegion region) + { + var manaClip = clip.asset as CriManaClip; + + var fullRect = region.position; + fullRect.x = Mathf.LerpUnclamped(region.position.xMax, region.position.xMin, (float)region.endTime / (float)(region.endTime - region.startTime)); + fullRect.width *= (float)clip.duration / (float)(region.endTime - region.startTime); + + var fadeinEnd = fullRect.xMin + fullRect.width * (float)(manaClip.m_fadeinDuration / clip.duration); + var fadeoutStart = fullRect.xMax - fullRect.width * (float)(manaClip.m_fadeoutDuration / clip.duration); + + GL.Begin(GL.TRIANGLES); + GL.Color(Color.black); + GL.Vertex3(fullRect.xMin, fullRect.yMin, 0); + GL.Vertex3(fadeinEnd, fullRect.yMin, 0); + GL.Vertex3(fullRect.xMin, fullRect.yMax, 0); + GL.Vertex3(fullRect.xMax, fullRect.yMin, 0); + GL.Vertex3(fullRect.xMax, fullRect.yMax, 0); + GL.Vertex3(fadeoutStart, fullRect.yMin, 0); + GL.End(); + + GL.Begin(GL.LINES); + GL.Color(Color.gray); + GL.Vertex3(fadeinEnd, fullRect.yMin, 0); + GL.Vertex3(fadeinEnd, fullRect.yMax, 0); + GL.Vertex3(fadeoutStart, fullRect.yMin, 0); + GL.Vertex3(fadeoutStart, fullRect.yMax, 0); + GL.End(); + } + } + +#endif + +} + +} //namespace CriWare + +#endif \ No newline at end of file diff --git a/Assets/Scripts/CRIMW/CriWare/Editor/CriMana/Extension/CriManaTimelineDrawer.cs.meta b/Assets/Scripts/CRIMW/CriWare/Editor/CriMana/Extension/CriManaTimelineDrawer.cs.meta new file mode 100644 index 0000000..ff0f6f1 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Editor/CriMana/Extension/CriManaTimelineDrawer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 904fa2bb9e56dd1478e687f7e9861c52 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Editor/CriMw.CriWare.Editor.asmdef b/Assets/Scripts/CRIMW/CriWare/Editor/CriMw.CriWare.Editor.asmdef new file mode 100644 index 0000000..d6fe746 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Editor/CriMw.CriWare.Editor.asmdef @@ -0,0 +1,25 @@ +{ + "name": "CriMw.CriWare.Editor", + "references": [ + "CriMw.CriWare.Runtime", + "Unity.Timeline", + "Unity.Timeline.Editor" + ], + "optionalUnityReferences": [], + "includePlatforms": [ + "Editor" + ], + "excludePlatforms": [], + "allowUnsafeCode": false, + "overrideReferences": false, + "precompiledReferences": [], + "autoReferenced": true, + "defineConstraints": [], + "versionDefines": [ + { + "name": "com.unity.timeline", + "expression": "1.0.0", + "define": "CRIWARE_TIMELINE_1_OR_NEWER" + } + ] +} \ No newline at end of file diff --git a/Assets/Scripts/CRIMW/CriWare/Editor/CriMw.CriWare.Editor.asmdef.meta b/Assets/Scripts/CRIMW/CriWare/Editor/CriMw.CriWare.Editor.asmdef.meta new file mode 100644 index 0000000..f84973f --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Editor/CriMw.CriWare.Editor.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: bd6f7e3ec622d1444bbb205e750a56c8 +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Editor/CriProfiler.cs b/Assets/Scripts/CRIMW/CriWare/Editor/CriProfiler.cs new file mode 100644 index 0000000..9e6e9b7 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Editor/CriProfiler.cs @@ -0,0 +1,1435 @@ +/**************************************************************************** + * + * Copyright (c) 2018 CRI Middleware Co., Ltd. + * + ****************************************************************************/ +#if UNITY_EDITOR + +using System; +using System.IO; +using System.Linq; +using System.Collections; +using System.Collections.Generic; +using System.Net; +using System.Net.Sockets; +using System.Threading; +using System.Diagnostics; +using UnityEngine; + +namespace CriWare { + +public partial class CriProfiler +{ + private static CriProfiler singleton = new CriProfiler(); + public static CriProfiler GetSingleton() { return singleton; } + + #region Structs and Classes + // TCP connection parameters to be send to the thread + protected struct TcpParams { + public readonly IPAddress ipAddress; + public readonly int port; + public readonly int chunkSize; + public readonly int connectionTimeoutMillisec; + public readonly int connectionRetryIntervalMillisec; + public readonly int connectionRetryLimit; + public readonly int enBufferIntervalMillisec; + public TcpParams( + IPAddress ipAddress, + int port, + int chunkSize, + int connectionTimeoutMillisec, + int connectionRetryIntervalMillisec, + int connectionRetryLimit, + int enBufferIntervalMillisec) + { + this.ipAddress = ipAddress; + this.port = port; + this.chunkSize = chunkSize; + this.connectionTimeoutMillisec = connectionTimeoutMillisec; + this.connectionRetryIntervalMillisec = connectionRetryIntervalMillisec; + this.connectionRetryLimit = connectionRetryLimit; + this.enBufferIntervalMillisec = enBufferIntervalMillisec; + } + } + + // TCP data buffer + private class RingBuffer { + protected T[] data; + protected int size; + protected int head; + protected int tail; + protected int mask; /* for remainder operation */ + + static private int RegulateToPow2(uint n) { + int res = 0; + for (n -= 1; n != 0; n >>= 1) { + res = (res << 1) + 1; + } + return res + 1; + } + + // Specify the size of the buffer. + // The resulted size will be rounded up to the nearest 2^n number for the sake of performance. + public RingBuffer(int _size) { + size = RegulateToPow2((uint)_size); + data = new T[size]; + head = 0; + tail = 0; + mask = size - 1; + } + + // Get the number of elements in the buffer + public int Count { + get { + int _count = this.tail - this.head; + if (_count < 0) _count += this.size; + return _count; + } + } + + public int Capacity { + get { + return size - 1; + } + } + + // Index access to the buffer. + public T this[int i] { + get { + return this.data[(i + this.head) & this.mask]; + } + private set { + this.data[(i + this.head) & this.mask] = value; + } + } + + // Copy [inputSize] of elements from inputData to the tail of the buffer. + // return false if the buffer is full. + public bool EnBuffer(T[] inputData, int inputSize) { + if (this.Count + inputSize >= this.size) { + return false; + } + + for (int i = 0; i < inputSize; ++i) { + this.data[this.tail] = inputData[i]; + this.tail = (this.tail + 1) & this.mask; + } + + return true; + } + + // Read [outputSize] of elements and delete it from the head of the buffer. + // Return null if there is nothing to read. + // The resulted array may be smaller in length than requested. + public T[] DeBuffer(int outputSize) { + if (outputSize <= 0 || this.Count <= 0) { + return null; + } + if (outputSize > this.Count) { + return null; + } + + T[] res = new T[outputSize]; + for (int i = 0; i < outputSize; ++i) { + res[i] = this[i]; + } + this.head = (this.head + outputSize) & this.mask; + + return res; + } + + // Clear the buffer. Memory spaces will still be occupied. + public void Clear() { + this.head = 0; + this.tail = 0; + } + } + + private class RingBufferAutoDequeue : RingBuffer { + public RingBufferAutoDequeue(int size) : base(size) { } + + public new bool EnBuffer(T[] inputData, int inputSize) { + if (this.Count + inputSize >= this.size) { + this.DeBuffer(this.Count + inputSize - this.size + 1); + } + + for (int i = 0; i < inputSize; ++i) { + this.data[this.tail] = inputData[i]; + this.tail = (this.tail + 1) & this.mask; + } + + return true; + } + + public void FillWithZeros() { + T[] zeros = new T[Capacity]; + this.EnBuffer(zeros, Capacity); + } + } + + #region Loading / Saving data from big-endian data stream + public static Byte LoadBigEndianByte(Byte[] data, int ofst) { + return data[ofst]; + } + public static void SaveBigEndianByte(Byte[] data, int ofst, Byte input) { + data[ofst] = input; + } + + public static UInt16 LoadBigEndianUInt16(Byte[] data, int ofst) { + return (UInt16)( ((data[ofst + 0]) << 8) + | (data[ofst + 1])); + } + public static void SaveBigEndianUInt16(Byte[] data, int ofst, UInt16 input) { + data[ofst + 0] = (byte)((input >> 8) & 0xff); + data[ofst + 1] = (byte)( input & 0xff); + } + + public static UInt32 LoadBigEndianUInt32(Byte[] data, int ofst) { + return (UInt32)( ((data[ofst + 0]) << 24) + | ((data[ofst + 1]) << 16) + | ((data[ofst + 2]) << 8) + | (data[ofst + 3])); + } + public static void SaveBigEndianUInt32(Byte[] data, int ofst, UInt32 input) { + data[ofst + 0] = (byte)((input >> 24) & 0xff); + data[ofst + 1] = (byte)((input >> 16) & 0xff); + data[ofst + 2] = (byte)((input >> 8) & 0xff); + data[ofst + 3] = (byte)( input & 0xff); + } + + public static Single LoadBigEndianSingle(Byte[] data, int ofst) { + /* convert to little-endian for System.BitConverter */ + byte[] byteVals = new[] { data[ofst + 3], data[ofst + 2], data[ofst + 1], data[ofst + 0] }; + return BitConverter.ToSingle(byteVals, 0); + } + + public static UInt64 LoadBigEndianUInt64(Byte[] data, int ofst) { + return (UInt64)( ((data[ofst + 0]) << 56) + | ((data[ofst + 1]) << 48) + | ((data[ofst + 2]) << 40) + | ((data[ofst + 3]) << 32) + | ((data[ofst + 4]) << 24) + | ((data[ofst + 5]) << 16) + | ((data[ofst + 6]) << 8) + | (data[ofst + 7])); + } + public static void SaveBigEndianUInt64(Byte[] data, int ofst, UInt64 input) { + data[ofst + 0] = (byte)((input >> 56) & 0xff); + data[ofst + 1] = (byte)((input >> 48) & 0xff); + data[ofst + 2] = (byte)((input >> 40) & 0xff); + data[ofst + 3] = (byte)((input >> 32) & 0xff); + data[ofst + 4] = (byte)((input >> 24) & 0xff); + data[ofst + 5] = (byte)((input >> 16) & 0xff); + data[ofst + 6] = (byte)((input >> 8) & 0xff); + data[ofst + 7] = (byte)( input & 0xff); + } + #endregion + + protected struct TcpLogHeader { + public const int properSize + /* = sizeof(UInt32) + sizeof(UInt16) + sizeof(Byte) + sizeof(Byte) + sizeof(UInt64) + * + sizeof(UInt16) + sizeof(UInt16) + sizeof(UInt32) + sizeof(UInt64); + */ = 32; + public readonly UInt32 packetSize; + public readonly UInt16 command; + public readonly Byte ptr_size; + public readonly Byte log_type; + public readonly UInt64 time; + public readonly UInt16 function_id; + public readonly UInt16 padding_size; + public readonly UInt32 control_id; + public readonly UInt64 thread_id; + public readonly bool isPtr64; + public readonly int size; + + public TcpLogHeader(byte[] data) { + int offset = 0; + isPtr64 = false; + + packetSize = LoadBigEndianUInt32(data, offset); + offset += sizeof(UInt32); + + command = LoadBigEndianUInt16(data, offset); + offset += sizeof(UInt16); + + ptr_size = LoadBigEndianByte(data, offset); + isPtr64 = ((ptr_size - sizeof(UInt32)) == 0) ? false : true; + offset += sizeof(Byte); + + log_type = LoadBigEndianByte(data, offset); + offset += sizeof(Byte); + + time = LoadBigEndianUInt64(data, offset); + offset += sizeof(UInt64); + + function_id = LoadBigEndianUInt16(data, offset); + offset += sizeof(UInt16); + + padding_size = LoadBigEndianUInt16(data, offset); + offset += sizeof(UInt16); + + control_id = LoadBigEndianUInt32(data, offset); + offset += sizeof(UInt32); + + if(isPtr64 == true) { + thread_id = LoadBigEndianUInt64(data, offset); + offset += sizeof(UInt64); + } else { + offset += sizeof(UInt32); + thread_id = LoadBigEndianUInt32(data, offset); + offset += sizeof(UInt32); + } + + size = offset; + if (size != properSize) { + UnityEngine.Debug.LogError("[CRIWARE] (Profiler) Corrupted log header"); + } + } + } + + private class ParamIdDoesNotMatchException : Exception { + public ParamIdDoesNotMatchException() { } + + public ParamIdDoesNotMatchException(string message) : base(message) { } + + public ParamIdDoesNotMatchException(string message, Exception inner) : base(message, inner) { } + } + + public class PlaybackInfo { + public readonly UInt32 playbackId; + public readonly String cueName; + public readonly String cueSheetName; + public readonly UInt64 timestamp; + public int? StreamType; + public PlaybackInfo(UInt32 playbackId, String cueName, String cueSheetName, UInt64 timestamp) + { + this.playbackId = playbackId; + this.cueName = cueName; + this.cueSheetName = cueSheetName; + this.timestamp = timestamp; + this.StreamType = null; + } + } + + public class VoicePoolInfo { + public UInt32 soundFormat; + public int numUsedVoices; + public int? StreamType; + public VoicePoolInfo(UInt32 soundFormat, int? StreamType = null) + { + this.soundFormat = soundFormat; + this.StreamType = StreamType; + this.numUsedVoices = -1; /* <0: no data yet */ + } + } + + public struct LevelInfo { + public Single levelPeak; + public Single levelRms; + public Single levelPeakHold; + public LevelInfo(Single levelPeak, Single levelRms, Single levelPeakHold) + { + this.levelPeak = levelPeak; + this.levelRms = levelRms; + this.levelPeakHold = levelPeakHold; + } + } + #endregion + + #region Internal data + private Thread threadTcpClient; + private Thread threadPacketReading; + private ManualResetEvent threadTerminator = new ManualResetEvent(false); + private RingBuffer TcpBuffer = new RingBuffer(16384); + private List eventLogList = new List(); + private bool isProfiling = false; + private bool isConnected = false; + private bool isBufferCorrupted = false; + private bool doSaveLog; + private FileStream logStream = null; + private const int cRwLockTimeoutMs = 100; + public bool IsProfiling { + get { return isProfiling; } + } + #endregion + + #region Fields / Properties + public UInt64 timestamp { get; private set; } + public UInt64 timestampStart { get; private set; } + public Single cpu_load { get; private set; } + private RingBufferAutoDequeue cpuLoadHistory = new RingBufferAutoDequeue(100); + public Single[] CpuLoadHistory { + get { + lock (cpuLoadHistory) { + Single[] histArray = new Single[cpuLoadHistory.Count]; + for (int i = 0; i < cpuLoadHistory.Count; ++i) { + histArray[i] = cpuLoadHistory[i]; + } + return histArray; + } + } + } + public UInt32 num_used_voices { get; private set; } + private RingBufferAutoDequeue voiceUsageHistory = new RingBufferAutoDequeue(100); + public UInt32[] VoiceUsageHistory { + get { + lock (voiceUsageHistory) { + UInt32[] histArray = new UInt32[voiceUsageHistory.Count]; + for (int i = 0; i < voiceUsageHistory.Count; ++i) { + histArray[i] = voiceUsageHistory[i]; + } + return histArray; + } + } + } + public UInt32 num_used_streams { get; private set; } + public Single total_bps { get; private set; } + public UInt32 maxVoice_stdOnMemory { get; private set; } + public UInt32 maxVoice_stdStreaming { get; private set; } + public UInt32 maxVoice_hcamxOnMemory { get; private set; } + public UInt32 maxVoice_hcamxStreaming { get; private set; } + public Single loudness_momentary { get; private set; } + public Single loudness_shortTerm { get; private set; } + public Single loudness_integrated { get; private set; } + public int numChMasterOut { get; private set; } + private List levels = new List(); /* Channel => Levels */ + public LevelInfo[] LevelsAllCh { + get { + if(levels.Count > 0) { + LevelInfo[] levelsCopy; + lock (levels) { + levelsCopy = new LevelInfo[levels.Count]; + levels.CopyTo(levelsCopy); + } + return levelsCopy; + } else { + return null; + } + } + } + public String cuename_lastPlayed { get; private set; } + public String cuesheetName_lastPlayed { get; private set; } + private Hashtable playbackHashtable = new Hashtable(); /* Playback ID => Playback Info */ + public PlaybackInfo[] PlaybackList { + get { + lock (playbackHashtable) { + PlaybackInfo[] playbackList = new PlaybackInfo[playbackHashtable.Count]; + playbackHashtable.Values.CopyTo(playbackList, 0); + return playbackList.OrderBy(x => x.timestamp).ToArray(); + } + } + } + private Dictionary multiLaneTimeline = new Dictionary(); + private Hashtable voicePoolInfoTable = new Hashtable(); /* VoicePool Handle => VoicePool Info */ + public enum VoicePoolFormat { + Standard, + HcaMx + } + public int GetVoicePoolUsage(VoicePoolFormat format) { + int usage = 0; + bool haveData = false; + UInt32 formatBits = FORMAT_NONE; + switch (format) { + case VoicePoolFormat.Standard: + formatBits = FORMAT_ADX | FORMAT_HCA; + break; + case VoicePoolFormat.HcaMx: + formatBits = FORMAT_HCA_MX; + break; + default: + break; + } + lock (voicePoolInfoTable) { + foreach(VoicePoolInfo elem in voicePoolInfoTable.Values) { + if (elem.soundFormat == formatBits && elem.numUsedVoices >= 0) { + usage += (int)elem.numUsedVoices; + haveData = true; + } + } + } + if(haveData) { + return usage; + } else { + return -1; + } + } + public List GetLogList() { + return eventLogList; + } + public List GetLogList(int offset, int count) { + try { + offset = Mathf.Clamp(offset, 0, eventLogList.Count - 1); + count = Mathf.Clamp(count, 0, eventLogList.Count - offset); + return eventLogList.GetRange(offset, count); + } catch { + return new List(); + } + } + public void ClearLog() { + eventLogList.Clear(); + } + #endregion Fields / Properties + + #region Data Initialization + private void ResetVals() { + this.InitVals(); + } + + private void InitVals() { + this.timestamp = 0; + this.timestampStart = 0; + this.cpu_load = 0; + this.cpuLoadHistory.FillWithZeros(); + this.num_used_voices = 0; + this.voiceUsageHistory.FillWithZeros(); + this.num_used_streams = 0; + this.total_bps = 0.0f; + this.maxVoice_stdOnMemory = 0; + this.maxVoice_stdStreaming = 0; + this.maxVoice_hcamxOnMemory = 0; + this.maxVoice_hcamxStreaming = 0; + this.loudness_momentary = Mathf.NegativeInfinity; + this.loudness_shortTerm = Mathf.NegativeInfinity; + this.loudness_integrated = Mathf.NegativeInfinity; + this.cuename_lastPlayed = ""; + this.numChMasterOut = 0; + this.voicePoolInfoTable.Clear(); + this.playbackHashtable.Clear(); + this.multiLaneTimeline.Clear(); + this.levels.Clear(); + this.eventLogList.Clear(); + } + #endregion + + #region Profiler Control + /* connection settings */ + private const int TCP_PORT = 2002; + private const int TCP_CHUNK = 2048; + private const int TCP_CONNECT_TIMEOUT_MS = 500; + private const int TCP_RETRY_INTERVAL_MS = 2000; + private const int TCP_RETRY = 5; + private const int BUFFERING_INTERVAL_MS = 10; + public const string LOG_FILE_EXTENSION = "crimon"; + + public string ipAddressString = "127.0.0.1"; + public string LogFileSavePath { get; private set; } + // Starting the TCP sub thread. + public void StartProfiling(bool saveLog, string logDirPath = null) { + IPAddress validIp; + if(IPAddress.TryParse(ipAddressString, out validIp) == false) { + UnityEngine.Debug.LogWarning("[CRIWARE] (Profiler) IP address not valid - connection aborted. "); + return; + } + + this.doSaveLog = saveLog; + if (this.doSaveLog) { + if (string.IsNullOrEmpty(logDirPath)) { + /* default log file path */ + logDirPath = Path.Combine(Directory.GetParent(Application.dataPath).ToString(), "CriWareProfilerLog"); + } + this.LogFileSavePath = logDirPath; + if (Directory.Exists(LogFileSavePath) == false) { + try { + Directory.CreateDirectory(LogFileSavePath); + } catch (Exception e) { + UnityEngine.Debug.LogError("[CRIWARE] Profiler: failed to create directory for log files. Msg: " + e.Message); + } + } + var filePath = Path.Combine(LogFileSavePath, "CriProfilerLog-" + DateTime.Now.ToString("yyyy-MM-dd-HHmmss") + "." + LOG_FILE_EXTENSION); + try { + this.logStream = new FileStream(filePath, FileMode.Create, FileAccess.Write); + } catch (Exception e) { + UnityEngine.Debug.LogError("[CRIWARE] Profiler: failed to create log file. Msg: " + e.Message); + this.logStream = null; + this.doSaveLog = false; + } + } + + TcpParams tcpParams = new TcpParams( + validIp, + TCP_PORT, + TCP_CHUNK, + TCP_CONNECT_TIMEOUT_MS, + TCP_RETRY_INTERVAL_MS, + TCP_RETRY, + BUFFERING_INTERVAL_MS); + const int READ_INTERVAL_MS = 0; + + if ((threadTcpClient == null || threadTcpClient.IsAlive == false) && + (threadPacketReading == null || threadPacketReading.IsAlive == false) + ) { + InitVals(); + threadTerminator.Reset(); + threadTcpClient = new Thread(() => TaskTcpClient(tcpParams)); + threadPacketReading = new Thread(() => TaskPacketReading(READ_INTERVAL_MS)); + threadTcpClient.Start(); + threadPacketReading.Start(); + } + } + + // Stopping the TCP sub thread. + public void StopProfiling() { + threadTerminator.Set(); + ResetVals(); + + if (this.logStream != null) { + this.doSaveLog = false; + try { + this.logStream.Flush(); + this.logStream.Close(); + this.logStream = null; + } catch (Exception e) { + UnityEngine.Debug.LogError("[CRIWARE] Profiler: failed to flush log file. Msg: " + e.Message); + } + } + } + + private CriProfiler() { + /* hide constructor for singleton */ + InitVals(); + } + + ~CriProfiler() { + this.StopProfiling(); + } + #endregion + + #region TCP Connection Management + // TCP connection sub thread task. + private void TaskTcpClient(TcpParams tcpParams) { + int failedConnectCnt = 0; + + this.isProfiling = true; + + using (var tcpClient = new TcpClient()) { + while (true) { + try { + tcpClient.Connect(tcpParams.ipAddress, tcpParams.port); + this.isConnected = true; + UnityEngine.Debug.Log("[CRIWARE] CRI Profiler connected."); + BufferingLoop(tcpClient, tcpParams); + } catch { + failedConnectCnt += 1; + if(failedConnectCnt > tcpParams.connectionRetryLimit) { + UnityEngine.Debug.LogWarning("[CRIWARE] Retry count exceeded limit(" + tcpParams.connectionRetryLimit + "); Stopped."); + threadTerminator.Set(); + } else { + UnityEngine.Debug.LogWarning("[CRIWARE] Unable to connect CRI profiler. (Check if \"Uses In Game Preview\" is turned on)" + +"\nWaiting for " + (tcpParams.connectionRetryIntervalMillisec / 1000.0f).ToString("F1") + " seconds to reconnect... (" + failedConnectCnt+ "/" + tcpParams.connectionRetryLimit + " tries)"); + } + } + this.isConnected = false; + + if (threadTerminator.WaitOne(tcpParams.connectionRetryIntervalMillisec)) { + UnityEngine.Debug.Log("[CRIWARE] CRI Profiler disconnected."); + this.isProfiling = false; + break; + } + } + } + } + + // Looping process to push the socket input to the buffer. + private void BufferingLoop(TcpClient tcpClient, TcpParams tcpParams) { + int numBytesRead = 0; + byte[] chunk = new byte[tcpParams.chunkSize]; + byte[] sendPacket; + bool enbufferRes = true; + + this.TcpBuffer.Clear(); + using (var netStream = tcpClient.GetStream()) { + if (netStream == null) { + UnityEngine.Debug.LogError("[CRIWARE] (Profiler) TCP connection not available."); + return; + } + + if (netStream.CanRead == false) { + UnityEngine.Debug.LogError("[CRIWARE] (Profiler) TCP connection not readable."); + return; + } + + sendPacket = MakeLogPacket4StartStopLog(SendPacketType.StartLog); + if (sendPacket != null && netStream.CanWrite) { + netStream.Write(sendPacket, 0, sendPacket.Length); + } + + while (true) { + try { + if (netStream.DataAvailable) { + numBytesRead = netStream.Read(chunk, 0, chunk.Length); + if (this.isBufferCorrupted == false) { + lock (this.TcpBuffer) { + enbufferRes = this.TcpBuffer.EnBuffer(chunk, numBytesRead); + } + } + if (enbufferRes == false) { + UnityEngine.Debug.LogWarning("[CRIWARE] TCP reading buffer overflowed."); + + // -- buffer corrupted -> prepare to reset -- + // Enbuffer failure may cause incomplete packets in the packet queue. + // The solution we take is skipping all incoming data until a "tail" chunk (followed by no data) arrives, + // right after which the buffer will be reset. + this.isBufferCorrupted = true; + } + } else { + if (this.isBufferCorrupted == true) { + lock (this.TcpBuffer) { + /* reset the corrupted buffer when all available data are received */ + this.TcpBuffer.Clear(); + } + this.isBufferCorrupted = false; + } + } + } catch (System.IO.IOException) { + threadTerminator.Set(); + } + + if (threadTerminator.WaitOne(tcpParams.enBufferIntervalMillisec)) { + break; + } + } + + sendPacket = MakeLogPacket4StartStopLog(SendPacketType.StopLog); + if (sendPacket != null && netStream.CanWrite) { + netStream.Write(sendPacket, 0, sendPacket.Length); + } + } + } + + // Sending control packet to start / stop receiving log data + private enum SendPacketType { + StartLog, + StopLog + } + private byte[] MakeLogPacket4StartStopLog(SendPacketType sendType) { + int ptr_size = IntPtr.Size; + const LogTypes log_type = LogTypes.NON; + const UInt64 time = 0; + const LogFuncId function_id = LogFuncId.LOG_COMMAND_Non; + const UInt32 control_id = 0; + const UInt64 thread_id = 0; + + int size; + TcpCommandId command; + int padding_size; + + switch (sendType) { + case SendPacketType.StartLog: + size = TcpLogHeader.properSize + /* + sizeof(UInt16) + * + CriProfiler.LogParams[(int)LogParamItems.LOG_STRINGS_ITEM_LogRecordMode].size32/64; + */ + 6; + command = TcpCommandId.CRITCP_MAIL_START_LOG_RECORD; + padding_size = 2; /* 8 - (38 mod 8) */ + size += padding_size; + break; + case SendPacketType.StopLog: + size = TcpLogHeader.properSize; + command = TcpCommandId.CRITCP_MAIL_STOP_LOG_RECORD; + padding_size = 0; /* 8 - (32 mod 8) */ + size += padding_size; + break; + default: + return null; + } + + byte[] packetBytes = new byte[size]; + int offset = 0; + + SaveBigEndianUInt32(packetBytes, offset, (UInt32)size); + offset += sizeof(UInt32); + SaveBigEndianUInt16(packetBytes, offset, (UInt16)command); + offset += sizeof(UInt16); + SaveBigEndianByte(packetBytes, offset, (Byte)ptr_size); + offset += sizeof(Byte); + SaveBigEndianByte(packetBytes, offset, (Byte)log_type); + offset += sizeof(Byte); + SaveBigEndianUInt64(packetBytes, offset, (UInt64)time); + offset += sizeof(UInt64); + SaveBigEndianUInt16(packetBytes, offset, (UInt16)(function_id + CriProfiler.logFuncBaseNum)); + offset += sizeof(UInt16); + SaveBigEndianUInt16(packetBytes, offset, (UInt16)padding_size); + offset += sizeof(UInt16); + SaveBigEndianUInt32(packetBytes, offset, (UInt32)control_id); + offset += sizeof(UInt32); + SaveBigEndianUInt64(packetBytes, offset, (UInt64)thread_id); + offset += sizeof(UInt64); + + switch (sendType) { + case SendPacketType.StartLog: + SaveBigEndianUInt16(packetBytes, offset, (UInt16)LogParamId.LOG_STRINGS_ITEM_LogRecordMode); + offset += sizeof(UInt16); + SaveBigEndianUInt32(packetBytes, offset, (UInt32)LOG_MODE_ALL); /* size of LOG_STRINGS_ITEM_LogRecordMode */ + offset += sizeof(UInt32); + break; + case SendPacketType.StopLog: + break; + default: + return null; + } + + for (int i = 0; i < padding_size; ++i) { + packetBytes[offset] = 0; + offset += 1; + } + + if (offset == size) { + return packetBytes; + } else { + return null; + } + } + #endregion + + #region Parser + // Sub thread task to extract TCP packets from the buffer. + private void TaskPacketReading(int readIntervalMillisec) { + Stopwatch stopwatch = new Stopwatch(); + const int threadMaxLifeMs = 20000; /* should be longer than total TCP retrying time */ + const int threadRetryLifeMs = 500; + + byte[] data = null; + TcpLogHeader packetHeader; + int packetSize = 0; + + stopwatch.Start(); + while (true) { + if (this.isBufferCorrupted == false) { + lock (this.TcpBuffer) { + packetSize = GetPacketSize(TcpBuffer); + data = this.TcpBuffer.DeBuffer(packetSize); + } + if (data != null) { + stopwatch.Reset(); + stopwatch.Start(); + packetHeader = new TcpLogHeader(data); + try { + if (packetHeader.size > 0) { + if (this.doSaveLog && this.logStream != null) { + try { + this.logStream.Write(data, 0, data.Length); + } catch (Exception e) { + UnityEngine.Debug.LogError("[CRIWARE] Profiler: failed to write logs. Msg: " + e.Message); + this.doSaveLog = false; + } + } + this.Parser(data, packetHeader); + } /* if headerSize > 0 */ + } catch (Exception ex) { /* Any parsing error */ + if(ex is ParamIdDoesNotMatchException) { + UnityEngine.Debug.LogWarning("[CRIWARE] " + ex.Message.ToString()); + } + UnityEngine.Debug.LogWarning("[CRIWARE] (Profiler) Packet parsing failed: buffer may be corrupted. Reconstructing buffer..." + +"\nLog Function: " + GetLogFuncId(packetHeader.function_id).ToString()); + this.isBufferCorrupted = true; + } + } else { + /* kill all threads if waited for too long */ + if (this.isConnected == true) { + if (stopwatch.ElapsedMilliseconds > threadRetryLifeMs) { + this.isProfiling = false; + threadTerminator.Set(); + } + } else { + if (stopwatch.ElapsedMilliseconds > threadMaxLifeMs) { + this.isProfiling = false; + threadTerminator.Set(); + } + } + } /* if data != null */ + } /* if isBufferCorrupted == false */ + + if (threadTerminator.WaitOne(readIntervalMillisec)) { + this.isProfiling = false; + break; + } + } + } + + // Get the size of the packet from the header. + // Return 0 if there is no enough data to determine the size. + private int GetPacketSize(RingBuffer buffer) { + if (buffer == null || buffer.Count < DATA_LENGTH_PARAM_SIZE) { + return 0; + } + + uint result = buffer[0]; + for (int i = 1; i < DATA_LENGTH_PARAM_SIZE; ++i) { + result <<= 8; + result += buffer[i]; + } + + return (int)result; + } + + private int GetPacketSize(byte[] data, uint offset = 0) { + if (data == null || data.Length - offset < DATA_LENGTH_PARAM_SIZE) { + return 0; + } + + uint result = data[offset]; + for (int i = 0; i < DATA_LENGTH_PARAM_SIZE; i++) { + result <<= 8; + result += data[i + offset]; + } + + return (int)result; + } + + public void LoadLogFromFile(string path) { + if (string.IsNullOrEmpty(path)) { + UnityEngine.Debug.LogError("[CRIWARE] Profiler: Log file path cannot be empty"); + } + + try { + using (var fileStream = new FileStream(path, FileMode.Open, FileAccess.Read)) { + if (fileStream.CanRead) { + eventLogList.Clear(); + byte[] reusedSizeData = new byte[DATA_LENGTH_PARAM_SIZE]; + while (fileStream.Position + DATA_LENGTH_PARAM_SIZE < fileStream.Length) { + var read = fileStream.Read(reusedSizeData, 0, DATA_LENGTH_PARAM_SIZE); + /* roll back read position */ + fileStream.Position -= read; + /* get actual data size */ + var dataSize = GetPacketSize(reusedSizeData); + if (dataSize > 0) { + byte[] data = new byte[dataSize]; + fileStream.Read(data, 0, dataSize); + this.LogParser(data); + } else { + UnityEngine.Debug.LogError("[CRIWARE] Profiler: Error while reading log"); + break; + } + } + } else { + UnityEngine.Debug.LogError("[CRIWARE] Profiler: Log file cannot be read"); + } + } + } catch (Exception e) { + UnityEngine.Debug.LogError("[CRIWARE] Profiler: Error while opening log: " + e.Message); + } + } + + private void LogParser(byte[] data) { + var header = new TcpLogHeader(data); + + switch ((TcpCommandId)header.command) { + case TcpCommandId.CRITCP_MAIL_SEND_LOG: + switch (GetLogFuncId(header.function_id)) { + case LogFuncId.LOG_COMMAND_ExPlaybackId: + this.AddEventLog(data); + break; + default: + break; + } + break; + case TcpCommandId.CRITCP_MAIL_MONITOR_ATOM_EXPLAYBACKINFO_PLAY_END: + switch (GetLogFuncId(header.function_id)) { + case LogFuncId.LOG_COMMAND_ExPlaybackInfo_FreeInfo: + this.AddEventLog(data); + break; + default: + break; + } + break; + default: + break; + } + } + + private void Parser(byte[] data, TcpLogHeader header) { + int offset = 0; + int offset2 = 0; + int dataSize = 0; + int dataSize2 = 0; + + UInt32 playbackId; + StreamTypes streamType; + VoicePoolInfo voicePoolInfo; + UInt64 voicePoolHn; + Single levelPeak; + Single levelRms; + Single levelPeakHold; + int numCh = 0; + int numOutputCh; + int numMaxCh = 0; + + switch ((TcpCommandId)header.command) { + case TcpCommandId.CRITCP_MAIL_PREVIEW_CPU_LOAD: + this.timestamp = header.time; + if (this.timestampStart == 0) { + this.timestampStart = this.timestamp; + } + if (GetLogFuncId(header.function_id) == LogFuncId.LOG_COMMAND_CpuLoadAndNumUsedVoices) { + this.cpu_load = LoadBigEndianSingle(data, FindParamOffset(data, header, LogParamId.LOG_STRINGS_ITEM_CpuLoad, out offset)); + this.num_used_voices = LoadBigEndianUInt32(data, GetNextParamOffset(data, header, LogParamId.LOG_STRINGS_ITEM_NumUsedVoices, ref offset)); + lock (cpuLoadHistory) { + cpuLoadHistory.EnBuffer(new Single[] { cpu_load }, 1); + } + lock (voiceUsageHistory) { + voiceUsageHistory.EnBuffer(new UInt32[] { num_used_voices }, 1); + } + } + break; + case TcpCommandId.CRITCP_MAIL_SEND_LOG: + this.timestamp = header.time; + if (this.timestampStart == 0) { + this.timestampStart = this.timestamp; + } + switch (GetLogFuncId(header.function_id)) { + case LogFuncId.LOG_COMMAND_LoudnessInfo: + this.loudness_momentary = LoadBigEndianSingle(data, FindParamOffset(data, header, LogParamId.LOG_STRINGS_ITEM_MomentaryValue, out offset)); + this.loudness_shortTerm = LoadBigEndianSingle(data, GetNextParamOffset(data, header, LogParamId.LOG_STRINGS_ITEM_ShortTermValue, ref offset)); + this.loudness_integrated = LoadBigEndianSingle(data, GetNextParamOffset(data, header, LogParamId.LOG_STRINGS_ITEM_IntegratedValue, ref offset)); + break; + case LogFuncId.LOG_COMMAND_StreamingInfo: + this.num_used_streams = LoadBigEndianUInt32(data, FindParamOffset(data, header, LogParamId.LOG_STRINGS_ITEM_NumUsedVoices, out offset)); + this.total_bps = LoadBigEndianSingle(data, GetNextParamOffset(data, header, LogParamId.LOG_STRINGS_ITEM_TotalBps, ref offset)); + break; + case LogFuncId.LOG_COMMAND_AsrBusAnalyzeInfoAllCh: + if (LoadBigEndianByte(data, FindParamOffset(data, header, LogParamId.LOG_STRINGS_ITEM_BusNo, out offset)) == 0) { /* if the bus is MasterOut(bus0) */ + numCh = LoadBigEndianByte(data, FindParamOffset(data, header, LogParamId.LOG_STRINGS_ITEM_NumCh, out offset)); + lock (levels) { + if (numMaxCh == 0) { + numMaxCh = numCh; + levels.Clear(); + for (int i = 0; i < numMaxCh; ++i) { + levels.Add(new LevelInfo(Mathf.NegativeInfinity, Mathf.NegativeInfinity, Mathf.NegativeInfinity)); + } + } + if (numMaxCh == numCh) { + for (int i = 0; i < numCh; ++i) { + levelPeak = LoadBigEndianSingle(data, GetNextParamOffset(data, header, LogParamId.LOG_STRINGS_ITEM_PeakLevel, ref offset)); + levelRms = LoadBigEndianSingle(data, GetNextParamOffset(data, header, LogParamId.LOG_STRINGS_ITEM_RmsLevel, ref offset)); + levelPeakHold = LoadBigEndianSingle(data, GetNextParamOffset(data, header, LogParamId.LOG_STRINGS_ITEM_PeakHoldLevel, ref offset)); + levels[i] = new LevelInfo(levelPeak, levelRms, levelPeakHold); + } + } + } + } + break; + case LogFuncId.LOG_COMMAND_ExStandardVoicePoolConfig: + if (Convert.ToBoolean(LoadBigEndianByte(data, FindParamOffset(data, header, LogParamId.LOG_STRINGS_ITEM_StreamingFlag, out offset))) == false) { + this.maxVoice_stdOnMemory = LoadBigEndianUInt32(data, FindParamOffset(data, header, LogParamId.LOG_STRINGS_ITEM_NumVoices, out offset)); + } else { + this.maxVoice_stdStreaming = LoadBigEndianUInt32(data, FindParamOffset(data, header, LogParamId.LOG_STRINGS_ITEM_NumVoices, out offset)); + } + break; + case LogFuncId.LOG_COMMAND_ExHcaMxVoicePoolConfig: + if (Convert.ToBoolean(LoadBigEndianByte(data, FindParamOffset(data, header, LogParamId.LOG_STRINGS_ITEM_StreamingFlag, out offset))) == false) { + this.maxVoice_hcamxOnMemory = LoadBigEndianUInt32(data, FindParamOffset(data, header, LogParamId.LOG_STRINGS_ITEM_NumVoices, out offset)); + } else { + this.maxVoice_hcamxStreaming = LoadBigEndianUInt32(data, FindParamOffset(data, header, LogParamId.LOG_STRINGS_ITEM_NumVoices, out offset)); + } + break; + case LogFuncId.LOG_COMMAND_ExVoicePoolHn: + try { + voicePoolHn = LoadBigEndianUInt64(data, FindParamOffset(data, header, LogParamId.LOG_STRINGS_ITEM_ExVoicePoolHn, out offset)); + voicePoolInfo = new VoicePoolInfo(LoadBigEndianUInt32(data, GetNextParamOffset(data, header, LogParamId.LOG_STRINGS_ITEM_SoundFormat, ref offset)), null); + lock (voicePoolInfoTable) { + voicePoolInfoTable.Add(voicePoolHn, voicePoolInfo); + } + } catch (ArgumentException) { + /* Voice pool info already exists; Do nothing */ + } + break; + case LogFuncId.LOG_COMMAND_ExVoicePool_Free: + voicePoolHn = LoadBigEndianUInt64(data, FindParamOffset(data, header, LogParamId.LOG_STRINGS_ITEM_ExVoicePoolHn, out offset)); + lock (voicePoolInfoTable) { + voicePoolInfoTable.Remove(voicePoolHn); + } + break; + case LogFuncId.LOG_COMMAND_PlayerPool_NumVoices: + voicePoolHn = LoadBigEndianUInt64(data, FindParamOffset(data, header, LogParamId.LOG_STRINGS_ITEM_ExVoicePoolHn, out offset)); + lock (voicePoolInfoTable) { + if (voicePoolInfoTable[voicePoolHn] != null) { + (voicePoolInfoTable[voicePoolHn] as VoicePoolInfo).numUsedVoices = (int)LoadBigEndianUInt32(data, GetNextParamOffset(data, header, LogParamId.LOG_STRINGS_ITEM_NumUsedVoices, ref offset)); + } + } + break; + case LogFuncId.LOG_COMMAND_ExPlaybackId: + playbackId = LoadBigEndianUInt32(data, FindParamOffset(data, header, LogParamId.LOG_STRINGS_ITEM_ExPlaybackId, out offset)); + dataSize = LoadBigEndianUInt16(data, FindParamOffset(data, header, LogParamId.LOG_STRINGS_ITEM_CueName, out offset)); /* cue name */ + dataSize2 = LoadBigEndianUInt16(data, FindParamOffset(data, header, LogParamId.LOG_STRINGS_ITEM_ExAcbName, out offset2)); /* cuesheet name */ + if (dataSize > 1 && dataSize2 > 1) { + this.cuename_lastPlayed = System.Text.Encoding.Default.GetString(data, GetStrDataOffset(header, offset), dataSize); + this.cuesheetName_lastPlayed = System.Text.Encoding.Default.GetString(data, GetStrDataOffset(header, offset2), dataSize2); + try { + lock (playbackHashtable) { + this.playbackHashtable.Add(playbackId, new PlaybackInfo(playbackId, cuename_lastPlayed, cuesheetName_lastPlayed, header.time)); + } + } catch (ArgumentException) { + /* Duplicated playback info received; Do nothing */ + } + this.AddEventLog(data); + this.AddPlaybackToTimeline(new Playback(playbackId, header.time, true, cuename_lastPlayed, cuesheetName_lastPlayed)); + } else { + this.cuename_lastPlayed = ""; + } + break; + case LogFuncId.LOG_COMMAND_SoundVoice_Allocate: + playbackId = LoadBigEndianUInt32(data, FindParamOffset(data, header, LogParamId.LOG_STRINGS_ITEM_ExPlaybackId, out offset)); + streamType = (StreamTypes)LoadBigEndianByte(data, FindParamOffset(data, header, LogParamId.LOG_STRINGS_ITEM_StreamType, out offset)); + lock (playbackHashtable) { + if (playbackHashtable.ContainsKey(playbackId)) { + (playbackHashtable[playbackId] as PlaybackInfo).StreamType = (int)streamType; + } + } + break; + case LogFuncId.LOG_COMMAND_ExAsrConfig: + numOutputCh = LoadBigEndianByte(data, FindParamOffset(data, header, LogParamId.LOG_STRINGS_ITEM_OutputChannels, out offset)); + if (numOutputCh > this.numChMasterOut) { + numChMasterOut = numOutputCh; + } + break; + default: + break; + } + break; + case TcpCommandId.CRITCP_MAIL_MONITOR_ATOM_EXPLAYBACKINFO_PLAY_END: + this.timestamp = header.time; + if (this.timestampStart == 0) { + this.timestampStart = this.timestamp; + } + switch (GetLogFuncId(header.function_id)) { + case LogFuncId.LOG_COMMAND_ExPlaybackInfo_FreeInfo: + playbackId = LoadBigEndianUInt32(data, FindParamOffset(data, header, LogParamId.LOG_STRINGS_ITEM_ExPlaybackId, out offset)); + lock (playbackHashtable) { + if (playbackHashtable.ContainsKey(playbackId)) { + var info = playbackHashtable[playbackId] as PlaybackInfo; + this.AddEventLog(data); + this.AddPlaybackToTimeline(new Playback(playbackId, header.time, false, info.cueName, info.cueSheetName)); + playbackHashtable.Remove(playbackId); + } + } + break; + default: + break; + } + break; + default: + UserDefinedParser(data, header); + break; + } + } + + // Override this method to add new parsing procedure + protected virtual void UserDefinedParser(byte[] data, TcpLogHeader packetHeader) { + // e.g. + //int offset; + //switch ((TcpCommandId)packetHeader.command) { + // case TcpCommandId.: + // switch (GetLogFuncId(packetHeader.function_id)) { + // case LogFuncId.: + // + // break; + // default: + // break; + // } + // break; + // default: + // break; + //} + } + + private void AddEventLog(byte[] data) { + this.eventLogList.Add(data); + } + + static private LogFuncId GetLogFuncId(UInt16 rawId) { + return (LogFuncId)(rawId - CriProfiler.logFuncBaseNum); + } + + public string FilteredLog2String(byte[] data) { + if (data == null || data.Length < TcpLogHeader.properSize) { return string.Empty; } + + var header = new TcpLogHeader(data); + var funcId = GetLogFuncId(header.function_id); + uint playbackId; + int dataSize, dataSize2, offset, offset2; + string str1, str2; + + string output = string.Empty; + switch (funcId) { + case LogFuncId.LOG_COMMAND_ExPlaybackId: + playbackId = LoadBigEndianUInt32(data, FindParamOffset(data, header, LogParamId.LOG_STRINGS_ITEM_ExPlaybackId, out offset)); + dataSize = LoadBigEndianUInt16(data, FindParamOffset(data, header, LogParamId.LOG_STRINGS_ITEM_CueName, out offset)); /* cue name */ + dataSize2 = LoadBigEndianUInt16(data, FindParamOffset(data, header, LogParamId.LOG_STRINGS_ITEM_ExAcbName, out offset2)); /* cuesheet name */ + str1 = System.Text.Encoding.Default.GetString(data, GetStrDataOffset(header, offset), dataSize); + str2 = System.Text.Encoding.Default.GetString(data, GetStrDataOffset(header, offset2), dataSize2); + output = MicroSec2String(header.time) + " | Start ID : " + playbackId + " | cuename : " + str1 + " | cuesheet : " + str2; + break; + case LogFuncId.LOG_COMMAND_ExPlaybackInfo_FreeInfo: + playbackId = LoadBigEndianUInt32(data, FindParamOffset(data, header, LogParamId.LOG_STRINGS_ITEM_ExPlaybackId, out offset)); + output = MicroSec2String(header.time) + " | End ID : " + playbackId; + break; + default: + break; + } + + return output; + } + + static private string MicroSec2String(ulong microSec) { + ulong hour = microSec / 3600000000; + ulong min = (microSec % 3600000000) / 60000000; + ulong sec = (microSec % 60000000) / 1000000; + ulong msec = (microSec % 1000000) / 1000; + return string.Format("{0}:{1}:{2}.{3}", hour, min, sec, msec); + } + + #region Methods for data offset calculation + private const int paramIdSize = 2; + + private int GetStrDataOffset(TcpLogHeader header, int paramIdOffset) { + return paramIdOffset + CriProfiler.paramIdSize + (header.isPtr64 + ? ParamTypeSizes64[(int)CriProfiler.LogParamTypes.TYPE_CHAR] + : ParamTypeSizes32[(int)CriProfiler.LogParamTypes.TYPE_CHAR]); + } + + private int FindParamOffset(byte[] data, TcpLogHeader header, LogParamId logParamId, out int currentOffset) { + if (data.Length < TcpLogHeader.properSize) { + throw new ParamIdDoesNotMatchException("Could not find parameter: " + logParamId.ToString()); + } + int offset = header.size; + int paramId; + int dataSize; + while (offset < header.packetSize) { + paramId = LoadBigEndianUInt16(data, offset); + if ((LogParamId)paramId == logParamId) { + currentOffset = offset; + return offset + paramIdSize; + } + + dataSize = header.isPtr64 ? LogParams[paramId].size64 : LogParams[paramId].size32; + if (LogParams[paramId].type == LogParamTypes.TYPE_CHAR) { + dataSize += LoadBigEndianUInt16(data, offset + paramIdSize); + } + offset += paramIdSize + dataSize; + } + + throw new ParamIdDoesNotMatchException("Could not find parameter: " + logParamId.ToString()); + } + + private int GetNextParamOffset(byte[] data, TcpLogHeader header, LogParamId logParamId, ref int currentOffset) { + if (currentOffset >= header.packetSize) { + throw new ParamIdDoesNotMatchException("Could not find parameter: " + logParamId.ToString()); + } + int paramId = LoadBigEndianUInt16(data, currentOffset); + int dataSize = header.isPtr64 ? CriProfiler.LogParams[paramId].size64 : CriProfiler.LogParams[paramId].size32; + if (CriProfiler.LogParams[paramId].type == LogParamTypes.TYPE_CHAR) { + dataSize += LoadBigEndianUInt16(data, currentOffset + paramIdSize); + } + /* set parameter id offset */ + currentOffset += paramIdSize + dataSize; + + if ((LogParamId)LoadBigEndianUInt16(data, currentOffset) != logParamId) { + throw new ParamIdDoesNotMatchException("Parsed parameter ID does not match with " + logParamId.ToString()); + } + + /* return parameter data offset */ + return currentOffset + paramIdSize; + } + #endregion Methods for data offset calculation + + #endregion Parser + + + #region Timeline + + /* CueSheet - Cue - Playback Lane (multiple non-overlapping playback lists) - Timestamp (true = start, false = end) */ + + private void AddPlaybackToTimeline(Playback playback) { + CueSheetGroup group; + if (multiLaneTimeline.TryGetValue(playback.cuesheet, out group) == false) { + group = new CueSheetGroup(playback.cuesheet); + multiLaneTimeline.Add(playback.cuesheet, group); + } + group.AddPlayback(playback); + } + + public Dictionary TimelineDataSlice { + get { + var output = new Dictionary(); + foreach (var elem in multiLaneTimeline) { + output.Add(elem.Key, elem.Value.Clone()); + } + return output; + } + } + + public class CueSheetGroup : ICloneable { + public string name; + public Color cuesheetColor = Color.white; + public Dictionary cueLaneDict; + + static private readonly Color baseColor = new Color(0.5412f, 1f, 0.3451f); + + public CueSheetGroup(string name) { + this.name = name; + {/* set distinguishing color */ + float h, s, v; + Color.RGBToHSV(baseColor, out h, out s, out v); + System.Random rand = new System.Random(); + this.cuesheetColor = Color.HSVToRGB(rand.Next(0, 10000) / 10000f, s, v); + } + cueLaneDict = new Dictionary(); + } + + public CueSheetGroup(CueSheetGroup group) { + this.name = group.name; + this.cuesheetColor = group.cuesheetColor; + this.cueLaneDict = new Dictionary(); + foreach (var elem in group.cueLaneDict) { + cueLaneDict.Add(elem.Key, elem.Value.Clone()); + } + } + public CueSheetGroup Clone() { return new CueSheetGroup(this); } + object ICloneable.Clone() { return Clone(); } + + public void AddPlayback(Playback playback) { + CueLane lane; + if (cueLaneDict.TryGetValue(playback.cuename, out lane) == false) { + lane = new CueLane(playback.cuename, playback.cuesheet); + cueLaneDict.Add(playback.cuename, lane); + } + lane.AddPlayback(playback); + } + + public int TotalLaneCount { + get { + int cnt = 0; + foreach (var elem in cueLaneDict) { + cnt += elem.Value.playbackLaneList.Count; + } + return cnt; + } + } + } + + public class CueLane : ICloneable { + public string name; + public string cuesheet; + public Color cueColor; + public List playbackLaneList; + + static private readonly Color baseColor = new Color(0.537f, 0.922f, 0.424f); + private Dictionary playingDict; /* ; wont be cloned */ + + public CueLane(string name, string cuesheet) { + this.name = name; + this.cuesheet = cuesheet; + {/* set distinguishing color */ + float h, s, v; + Color.RGBToHSV(baseColor, out h, out s, out v); + System.Random rand = new System.Random(); + this.cueColor = Color.HSVToRGB(rand.Next(0, 10000) / 10000f, s, v); + } + playbackLaneList = new List(); + playingDict = new Dictionary(); + } + + public CueLane(CueLane cuelane) { + this.name = cuelane.name; + this.cuesheet = cuelane.cuesheet; + this.cueColor = cuelane.cueColor; + this.playbackLaneList = new List(); + this.playbackLaneList.AddRange(cuelane.playbackLaneList.Select(i => i.Clone())); + } + + public CueLane Clone() { return new CueLane(this); } + object ICloneable.Clone() { return Clone(); } + + public void AddPlayback(Playback playback) { + if (playback.isStart) { /* playback start */ + bool added = false; + for (int i = 0; i < playbackLaneList.Count; ++i) { + if (playbackLaneList[i].isPlaying == false) { + if (playbackLaneList[i].AddPlayback(playback)) { + playingDict.Add(playback.id, i); + added = true; + break; + } + } + } + if (added == false) { /* no empty lane */ + playbackLaneList.Add(new PlaybackLane()); + if (playbackLaneList[playbackLaneList.Count - 1].AddPlayback(playback)) { + playingDict.Add(playback.id, playbackLaneList.Count - 1); + } + } + } else { /* playback end */ + int laneId; + if (playingDict.TryGetValue(playback.id, out laneId)) { + playbackLaneList[laneId].AddPlayback(playback); + playingDict.Remove(playback.id); + } + } + } + } + + public class PlaybackLane : ICloneable { + public List playbackList; + private int balance; + + public bool isConsistent { + get { + if (balance > 1 || balance < 0) { + return false; + } + return true; + } + } + + public PlaybackLane() { + playbackList = new List(); + balance = 0; + } + + public PlaybackLane(PlaybackLane playbackLane) { + this.playbackList = new List(playbackLane.playbackList); + this.balance = playbackLane.balance; + } + + public PlaybackLane Clone() { return new PlaybackLane(this); } + object ICloneable.Clone() { return Clone(); } + + public bool AddPlayback(Playback playback) { + if (playbackList.Count > 0 && + (playbackList[playbackList.Count - 1].timestamp > playback.timestamp || + playbackList[playbackList.Count - 1].isStart == playback.isStart)) { + UnityEngine.Debug.LogError("[CRIWARE] Profiler internal: playback timestamp order error"); + return false; + } + playbackList.Add(playback); + balance += playback.isStart ? 1 : -1; + return true; + } + + public bool isPlaying { + get { + return playbackList[playbackList.Count - 1].isStart; + } + } + } + + public struct Playback { + public uint id; + public ulong timestamp; + public bool isStart; + public string cuename; + public string cuesheet; + public Playback(uint id, ulong timestamp, bool isStart, string cuename, string cuesheet) { + this.id = id; + this.timestamp = timestamp; + this.isStart = isStart; + this.cuename = cuename; + this.cuesheet = cuesheet; + } + } + #endregion +} + +} //namespace CriWare + +#endif \ No newline at end of file diff --git a/Assets/Scripts/CRIMW/CriWare/Editor/CriProfiler.cs.meta b/Assets/Scripts/CRIMW/CriWare/Editor/CriProfiler.cs.meta new file mode 100644 index 0000000..0727910 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Editor/CriProfiler.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 2ed031df3829ef741928cd2aa2f8075a +timeCreated: 1513761507 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Editor/CriProfilerConfig.cs b/Assets/Scripts/CRIMW/CriWare/Editor/CriProfilerConfig.cs new file mode 100644 index 0000000..3d37cdc --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Editor/CriProfilerConfig.cs @@ -0,0 +1,947 @@ +/**************************************************************************** + * + * Copyright (c) 2018 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +#if UNITY_EDITOR + +namespace CriWare { + +public partial class CriProfiler +{ + /* CRI Atom Preview connection ver. */ + private const int CRI_ATOM_PREVIEW_CONNECTION_VERSION = 0x00600000; + + /* the size of the parameter "packet size" in bytes */ + private const int DATA_LENGTH_PARAM_SIZE = 4; + + protected enum TcpCommandId { + CRITCP_MAIL_OPEN = 1, + CRITCP_MAIL_OPEN_RESULT, + CRITCP_MAIL_RECV, + CRITCP_MAIL_CHANGE, + CRITCP_MAIL_EXIT, + CRITCP_MAIL_SEND_CUESHEET_BINARY, + CRITCP_MAIL_SEND_CUESHEET_BINARY_RESULT, + CRITCP_MAIL_SEND_CUESHEET_BINARYDATA, + CRITCP_MAIL_SEND_CUESHEET_BINARYDATA_RESULT, + CRITCP_MAIL_START_MONITOR, /* 10 */ + CRITCP_MAIL_START_MONITOR_RESULT, + CRITCP_MAIL_STOP_MONITOR, + CRITCP_MAIL_STOP_MONITOR_RESULT, + CRITCP_MAIL_MONITOR_AUOBJ_STATUS, + CRITCP_MAIL_MONITOR_AUOBJ_STATUS_RESULT, + CRITCP_MAIL_SEND_LOG_REQUEST, + CRITCP_MAIL_SEND_LOG_REQUEST_RESULT, + CRITCP_MAIL_START_LOG_PLAYBACK, + CRITCP_MAIL_START_LOG_PLAYBACK_RESULT, + CRITCP_MAIL_STOP_LOG_PLAYBACK, /* 20 */ + CRITCP_MAIL_STOP_LOG_PLAYBACK_RESULT, + CRITCP_MAIL_START_LOG_RECORD, + CRITCP_MAIL_START_LOG_RECORD_RESULT, + CRITCP_MAIL_STOP_LOG_RECORD, + CRITCP_MAIL_STOP_LOG_RECORD_RESULT, + CRITCP_MAIL_DO_AUDIO_API, + CRITCP_MAIL_DO_AUDIO_API_RESULT, + CRITCP_MAIL_GET_COMMAND, + CRITCP_MAIL_NON, + CRITCP_MAIL_NUM_AUOBJ, /* 30 */ + CRITCP_MAIL_SEND_LOG, + CRITCP_MAIL_SEND_LOG_RESULT, + CRITCP_MAIL_PREVIEW_FLAG, + CRITCP_MAIL_PREVIEW_FLAG_RESULT, + CRITCP_MAIL_SEND_FILE_INFORMATION, + CRITCP_MAIL_SEND_FILE_INFORMATION_RESULT, + CRITCP_MAIL_SEND_FILE_DATA, + CRITCP_MAIL_SEND_FILE_DATA_RESULT, + CRITCP_MAIL_SEND_LOG_FOR_PLAYBACK, + CRITCP_MAIL_SEND_LOG_FOR_PLAYBACK_RESULT, /* 40 */ + CRITCP_MAIL_PREVIEW_SEND_DETA_RESULT, + CRITCP_MAIL_PREVIEW_SEND_DETA_RESULT_RESULT, + CRITCP_MAIL_PREVIEW_CPU_LOAD, + CRITCP_MAIL_PREVIEW_CPU_LOAD_RESULT, + CRITCP_MAIL_PREVIEW_PLAYER_STATUS, + CRITCP_MAIL_PREVIEW_PLAYER_STATUS_RESULT, + CRITCP_MAIL_DO_FILE_SYSTEM_API, + CRITCP_MAIL_DO_FILE_SYSTEM_API_RESULT, + CRITCP_MAIL_SEND_REGISTER_ATOM_CONFIG_BINARY, + CRITCP_MAIL_SEND_REGISTER_ATOM_CONFIG_BINARY_RESULT, /* 50 */ + CRITCP_MAIL_SEND_ATOM_CONFIG_BINARYDATA, + CRITCP_MAIL_SEND_ATOM_CONFIG_BINARYDATA_RESULT, + CRITCP_MAIL_SEND_ATOM_CUESHEET_BINARY, + CRITCP_MAIL_SEND_ATOM_CUESHEET_BINARY_RESULT, + CRITCP_MAIL_SEND_ATOM_CUESHEET_BINARYDATA, + CRITCP_MAIL_SEND_ATOM_CUESHEET_BINARYDATA_RESULT, + CRITCP_MAIL_MONITOR_ATOM_EXPLAYBACKINFO_PLAY_POSITION, + CRITCP_MAIL_MONITOR_ATOM_EXPLAYBACKINFO_PLAY_POSITION_RESULT, + CRITCP_MAIL_MONITOR_ATOM_EXPLAYBACKINFO_PLAY_END, + CRITCP_MAIL_MONITOR_ATOM_EXPLAYBACKINFO_PLAY_END_RESULT, /* 60 */ + CRITCP_MAIL_MONITOR_ATOMEXPLAYERS_STATUS, + CRITCP_MAIL_MONITOR_ATOMEXPLAYERS_STATUS_RESULT, + CRITCP_MAIL_MONITOR_ATOM_AUTO_MODULATION_AISAC_CONTROL, + CRITCP_MAIL_MONITOR_ATOM_AUTO_MODULATION_AISAC_CONTROL_RESULT, + CRITCP_MAIL_UPDATE_ATOM_CUESHEET_BINARY, + CRITCP_MAIL_UPDATE_ATOM_CUESHEET_BINARY_RESULT, + CRITCP_MAIL_UPDATE_ATOM_CUESHEET_BINARYDATA, + CRITCP_MAIL_UPDATE_ATOM_CUESHEET_BINARYDATA_RESULT, + CRITCP_MAIL_REQUEST_SEND_ACB, + CRITCP_MAIL_REQUEST_SEND_ACB_RESULT, /* 70 */ + CRITCP_MAIL_SHOW_WINDOW, + CRITCP_MAIL_SHOW_WINDOW_RESULT, + CRITCP_MAIL_MONITOR_OVERWRITE_ACB, + CRITCP_MAIL_MONITOR_OVERWRITE_ACB_RESULT, + CRITCP_MAIL_OVERWRITE_ACB, + CRITCP_MAIL_OVERWRITE_ACB_RESULT, + CRITCP_MAIL_OVERWRITE_ACB_DATA, + CRITCP_MAIL_OVERWRITE_ACB_DATA_RESULT, + CRITCP_MAIL_MONITOR_RELEASE_ACB, + CRITCP_MAIL_MONITOR_RELEASE_ACB_RESULT, /* 80 */ + CRITCP_MAIL_SEND_DUMMY, + CRITCP_MAIL_SEND_DUMMY_RESULT, + CRITCP_MAIL_UPDATE_PART_OF_ACF, + CRITCP_MAIL_UPDATE_PART_OF_ACF_RESULT, + CRITCP_MAIL_UPDATE_PART_OF_ACF_DATA, + CRITCP_MAIL_UPDATE_PART_OF_ACF_DATA_RESULT, + CRITCP_MAIL_MONITOR_OVERWRITE_ACF, + CRITCP_MAIL_MONITOR_OVERWRITE_ACF_RESULT, + CRITCP_MAIL_OVERWRITE_ACF, + CRITCP_MAIL_OVERWRITE_ACF_RESULT, /* 90 */ + CRITCP_MAIL_OVERWRITE_ACF_DATA, + CRITCP_MAIL_OVERWRITE_ACF_DATA_RESULT, + CRITCP_MAIL_MONITOR_ATOMEXASR_BUS_INFO, + CRITCP_MAIL_MONITOR_ATOMEXASR_BUS_INFO_RESULT, + CRITCP_MAIL_MONITOR_ATOMEX_ERR_INFO, + CRITCP_MAIL_MONITOR_ATOMEX_ERR_INFO_RESULT, + CRITCP_MAIL_MONITOR_ATOMEXASR_DSP_SPECTRA, + CRITCP_MAIL_MONITOR_ATOMEXASR_DSP_SPECTRA_RESULT, + CRITCP_MAIL_START_BOUNCE, + CRITCP_MAIL_START_BOUNCE_RESULT, /* 100 */ + CRITCP_MAIL_STOP_BOUNCE, + CRITCP_MAIL_STOP_BOUNCE_RESULT, + CRITCP_MAIL_MONITOR_SEQUENCER_CALLBACK, + CRITCP_MAIL_MONITOR_SEQUENCER_CALLBACK_RESULT, + CRITCP_MAIL_MONITOR_ATOM_TRACK_MUTE, + CRITCP_MAIL_MONITOR_ATOM_TRACK_MUTE_RESULT, + CRITCP_MAIL_MONITOR_PREVIEW_INFO, + CRITCP_MAIL_MONITOR_PREVIEW_INFO_RESULT, + CRITCP_MAIL_MONITOR_STREAM_AWB_INFO, + CRITCP_MAIL_MONITOR_STREAM_AWB_INFO_RESULT, /* 110 */ + CRITCP_MAIL_CONNECTION_VERSION, + CRITCP_MAIL_CONNECTION_VERSION_RESULT, + CRITCP_MAIL_MONITOR_ATOM_EXPLAYBACKINFO_PLAY_POSITION_WITH_PLAY_STATUS, + CRITCP_MAIL_MONITOR_REJECT_OVERWRITE_ACB, + }; + + /* ログ用API識別番号 */ + protected const int logFuncBaseNum = 2000; + protected enum LogFuncId { + LOG_COMMAND_Non = 0, /* Non */ + LOG_COMMAND_Ex_Initialize, /* criAtomEx_Initialize */ + LOG_COMMAND_Ex_Finalize, /* criAtomEx_Finalize */ + LOG_COMMAND_ExAsr_Initialize, /* criAtomExAsr_Initialize */ + LOG_COMMAND_ExAsr_Finalize, /* criAtomExAsr_Finalize */ + LOG_COMMAND_ExHcaMx_Initialize, /* criAtomExHcaMx_Initialize */ + LOG_COMMAND_ExHcaMx_Finalize, /* criAtomExHcaMx_Finalize */ + LOG_COMMAND_Dbas_Create, /* criAtomDbas_Create */ + LOG_COMMAND_Dbas_Destroy, /* criAtomDbas_Destroy */ + LOG_COMMAND_StreamingCache_Create, /* criAtomStreamingCache_Create */ + LOG_COMMAND_StreamingCache_Destroy, /* criAtomStreamingCache_Destroy */ + LOG_COMMAND_ExVoicePool_AllocateStandardVoicePool, /* criAtomExVoicePool_AllocateStandardVoicePool */ + LOG_COMMAND_ExVoicePool_AllocateAdxVoicePool, /* criAtomExVoicePool_AllocateAdxVoicePool */ + LOG_COMMAND_ExVoicePool_AllocateAhxVoicePool, /* criAtomExVoicePool_AllocateAhxVoicePool */ + LOG_COMMAND_ExVoicePool_AllocateHcaVoicePool, /* criAtomExVoicePool_AllocateHcaVoicePool */ + LOG_COMMAND_ExVoicePool_AllocateHcaMxVoicePool, /* criAtomExVoicePool_AllocateHcaMxVoicePool */ + LOG_COMMAND_ExVoicePool_AllocateWaveVoicePool, /* criAtomExVoicePool_AllocateWaveVoicePool */ + LOG_COMMAND_ExVoicePool_AllocateRawPcmVoicePool, /* criAtomExVoicePool_AllocateRawPcmVoicePool */ + LOG_COMMAND_ExVoicePool_AllocateAdpcmVoicePool_WII, /* criAtomExVoicePool_AllocateAdpcmVoicePool_WII */ + LOG_COMMAND_ExVoicePool_AllocateVagVoicePool_PSP, /* criAtomExVoicePool_AllocateVagVoicePool_PSP */ + LOG_COMMAND_ExVoicePool_AllocateAdpcmVoicePool_3DS, /* criAtomExVoicePool_AllocateAdpcmVoicePool_3DS */ + LOG_COMMAND_ExVoicePool_AllocateVagVoicePool_VITA, /* criAtomExVoicePool_AllocateVagVoicePool_VITA */ + LOG_COMMAND_ExVoicePool_AllocateAtrac3VoicePool_PSP,/* criAtomExVoicePool_AllocateAtrac3VoicePool_PSP */ + LOG_COMMAND_ExVoicePool_AllocateAt9VoicePool_VITA, /* criAtomExVoicePool_AllocateAt9VoicePool_VITA */ + LOG_COMMAND_ExVoicePool_Free, /* criAtomExVoicePool_Free */ + LOG_COMMAND_ExPlayer_Create, /* criAtomExPlayer_Create */ + LOG_COMMAND_ExPlayer_Destroy, /* criAtomExPlayer_Destroy */ + LOG_COMMAND_ExTween_Create, /* criAtomExTween_Create */ + LOG_COMMAND_ExTween_Destroy, /* criAtomExTween_Destroy */ + LOG_COMMAND_Decrypter_Create, /* criAtomDecrypter_Create */ + LOG_COMMAND_Decrypter_Destroy, /* criAtomDecrypter_Destroy */ + LOG_COMMAND_Ex3dSource_Create, /* criAtomEx3dSource_Create */ + LOG_COMMAND_Ex3dSource_Destroy, /* criAtomEx3dSource_Destroy */ + LOG_COMMAND_Ex3dListener_Create, /* criAtomEx3dListener_Create */ + LOG_COMMAND_Ex3dListener_Destroy, /* criAtomEx3dListener_Destroy */ + LOG_COMMAND_ExPlayer_AttachFader, /* criAtomExPlayer_AttachFader */ + LOG_COMMAND_ExPlayer_DetachFader, /* criAtomExPlayer_DetachFader */ + LOG_COMMAND_Ex_RegisterAcfConfig, /* criAtomEx_RegisterAcfConfig */ + LOG_COMMAND_Ex_RegisterAcfData, /* criAtomEx_RegisterAcfData */ + LOG_COMMAND_Ex_RegisterAcfFile, /* criAtomEx_RegisterAcfFile */ + LOG_COMMAND_Ex_RegisterAcfFileById, /* criAtomEx_RegisterAcfFileById */ + LOG_COMMAND_Ex_UnregisterAcf, /* criAtomEx_UnregisterAcf */ + LOG_COMMAND_ExAcb_LoadAcbData, /* criAtomExAcb_LoadAcbData */ + LOG_COMMAND_ExAcb_LoadAcbDataById, /* criAtomExAcb_LoadAcbDataById */ + LOG_COMMAND_ExAcb_LoadAcbFile, /* criAtomExAcb_LoadAcbFile */ + LOG_COMMAND_ExAcb_LoadAcbFileById, /* criAtomExAcb_LoadAcbFileById */ + LOG_COMMAND_ExAcb_Release, /* criAtomExAcb_Release */ + LOG_COMMAND_ExAcb_ReleaseAll, /* criAtomExAcb_ReleaseAll */ + LOG_COMMAND_ExPlayer_Start, /* criAtomExPlayer_Start */ + LOG_COMMAND_ExPlayer_Prepare, /* criAtomExPlayer_Prepare */ + LOG_COMMAND_ExPlayer_Stop, /* criAtomExPlayer_Stop */ + LOG_COMMAND_ExPlayer_StopWithoutReleaseTime, /* criAtomExPlayer_StopWithoutReleaseTime */ + LOG_COMMAND_ExPlayback_Stop, /* criAtomExPlayback_Stop */ + LOG_COMMAND_ExPlayback_StopWithoutReleaseTime, /* criAtomExPlayback_StopWithoutReleaseTime */ + LOG_COMMAND_ExPlayer_Pause, /* criAtomExPlayer_Pause */ + LOG_COMMAND_ExPlayer_Resume, /* criAtomExPlayer_Resume */ + LOG_COMMAND_ExPlayback_Pause, /* criAtomExPlayback_Pause */ + LOG_COMMAND_ExPlayback_Resume, /* criAtomExPlayback_Resume */ + LOG_COMMAND_ExPlaybackInfo_AllocateInfo, /* criAtomExPlaybackInfo_AllocateInfo */ + LOG_COMMAND_ExPlaybackInfo_FreeInfo, /* criAtomExPlaybackInfo_FreeInfo */ + LOG_COMMAND_Error, /* criError */ + LOG_COMMAND_ExPlaybackInfo_AddSound, /* criAtomExPlaybackInfo_AddSound */ + LOG_COMMAND_ExPlaybackSound_FreeSound, /* criAtomExPlaybackSound_FreeSound */ + LOG_COMMAND_SoundPlayer_Start, /* criAtomSoundPlayer_Start */ + LOG_COMMAND_SoundPlayer_Stop, /* criAtomSoundPlayer_Stop */ + LOG_COMMAND_SoundPlayer_StopWithoutRelease, /* criAtomSoundPlayer_StopWithoutRelease */ + LOG_COMMAND_SoundPlayer_PausePlayback, /* criAtomSoundPlayer_PausePlayback */ + LOG_COMMAND_SoundPlayer_SetWaveId, /* criAtomSoundPlayer_SetWaveId */ + LOG_COMMAND_SoundPlayer_SetContentId, /* criAtomSoundPlayer_SetContentId */ + LOG_COMMAND_SoundPlayer_SetData, /* criAtomSoundPlayer_SetData */ + LOG_COMMAND_SoundPlayer_SetFileStringPointer, /* criAtomSoundPlayer_SetFileStringPointer */ + LOG_COMMAND_ExPlayer_SetCueId, /* criAtomExPlayer_SetCueId */ + LOG_COMMAND_ExPlayer_SetCueName, /* criAtomExPlayer_SetCueName */ + LOG_COMMAND_ExPlayer_SetCueIndex, /* criAtomExPlayer_SetCueIndex */ + LOG_COMMAND_ExPlayer_SetData, /* criAtomExPlayer_SetData */ + LOG_COMMAND_ExPlayer_SetFile, /* criAtomExPlayer_SetFile */ + LOG_COMMAND_ExPlayer_SetContentId, /* criAtomExPlayer_SetContentId */ + LOG_COMMAND_ExPlayer_SetWaveId, /* criAtomExPlayer_SetWaveId */ + LOG_COMMAND_DbasId, /* CriAtomDbasId */ + LOG_COMMAND_StreamingCacheId, /* CriAtomStreamingCacheId */ + LOG_COMMAND_ExVoicePoolHn, /* CriAtomExVoicePoolHn */ + LOG_COMMAND_ExPlayerHn, /* CriAtomExPlayerHn */ + LOG_COMMAND_ExTweenHn, /* CriAtomExTweenHn */ + LOG_COMMAND_DecrypterHn, /* CriAtomDecrypterHn */ + LOG_COMMAND_Ex3dSourceHn, /* CriAtomEx3dSourceHn */ + LOG_COMMAND_Ex3dListenerHn, /* CriAtomEx3dListenerHn */ + LOG_COMMAND_ExPlaybackId, /* CriAtomExPlaybackId */ + LOG_COMMAND_ExConfig, /* CriAtomExConfig */ + LOG_COMMAND_ExAsrConfig, /* CriAtomExAsrConfig */ + LOG_COMMAND_ExHcaMxConfig, /* CriAtomExHcaMxConfig */ + LOG_COMMAND_DbasConfig, /* CriAtomDbasConfig */ + LOG_COMMAND_StreamingCacheConfig, /* CriAtomStreamingCacheConfig */ + LOG_COMMAND_ExStandardVoicePoolConfig, /* CriAtomExStandardVoicePoolConfig */ + LOG_COMMAND_ExAdxVoicePoolConfig, /* CriAtomExAdxVoicePoolConfig */ + LOG_COMMAND_ExAhxVoicePoolConfig, /* CriAtomExAhxVoicePoolConfig */ + LOG_COMMAND_ExHcaVoicePoolConfig, /* CriAtomExHcaVoicePoolConfig */ + LOG_COMMAND_ExHcaMxVoicePoolConfig, /* CriAtomExHcaMxVoicePoolConfig */ + LOG_COMMAND_ExWaveVoicePoolConfig, /* CriAtomExWaveVoicePoolConfig */ + LOG_COMMAND_ExRawPcmVoicePoolConfig, /* CriAtomExRawPcmVoicePoolConfig */ + LOG_COMMAND_ExAdpcmVoicePoolConfig_3DS, /* CriAtomExAdpcmVoicePoolConfig_3DS */ + LOG_COMMAND_ExAdpcmVoicePoolConfig_WII, /* CriAtomExAdpcmVoicePoolConfig_WII */ + LOG_COMMAND_ExVagVoicePoolConfig_PSP, /* CriAtomExVagVoicePoolConfig_PSP */ + LOG_COMMAND_ExAtrac3VoicePoolConfig_PSP, /* CriAtomExAtrac3VoicePoolConfig_PSP */ + LOG_COMMAND_ExVagVoicePoolConfig_VITA, /* CriAtomExVagVoicePoolConfig_VITA */ + LOG_COMMAND_ExAt9VoicePoolConfig_VITA, /* CriAtomExAt9VoicePoolConfig_VITA */ + LOG_COMMAND_ExPlayerConfig, /* CriAtomExPlayerConfig */ + LOG_COMMAND_ExTweenConfig, /* CriAtomExTweenConfig */ + LOG_COMMAND_DecrypterConfig, /* CriAtomDecrypterConfig */ + LOG_COMMAND_ExAcfConfig, /* CriAtomExAcfConfig */ + LOG_COMMAND_Ex3dSourceConfig, /* CriAtomEx3dSourceConfig */ + LOG_COMMAND_Ex3dListenerConfig, /* CriAtomEx3dListenerConfig */ + LOG_COMMAND_ExFaderConfig, /* CriAtomExFaderConfig */ + LOG_COMMAND_ExAcbHn, /* CriAtomExAcbHn */ + LOG_COMMAND_ExFaderHn, /* CriAtomExFaderHn */ + LOG_COMMAND_PlayerPoolPlayerInfo, /* CriAtomPlayerPoolPlayerInfo */ + LOG_COMMAND_PlayerPool_ReleasePlayer, /* criAtomPlayerPool_ReleasePlayer */ + LOG_COMMAND_SoundPlayer_Allocate_Element, /* criatomsoundplayer_allocate_element */ + LOG_COMMAND_ExCategory_CancelCuePlayback, /* criAtomExCategory_CancelCuePlayback */ + LOG_COMMAND_ExCue_StopByLimit, /* criAtomExCue_StopByLimit */ + LOG_COMMAND_ExCue_CancelCuePlayback, /* criAtomExCue_CancelCuePlayback */ + LOG_COMMAND_CancelPlaybackByProbability, /* criAtomExCue_CancelPlaybackByProbability */ + LOG_COMMAND_CancelPlaybackByCueTypeRandom, /* criAtomExCue_CancelPlaybackByyCueTypeRandom */ + LOG_COMMAND_CancelPlaybackByCueTypeSwitch, /* criAtomExCue_CancelPlaybackByyCueTypeSwitch */ + LOG_COMMAND_ExCategory_IncrementNumPlaybackCues, /* criAtomExCategory_IncrementNumPlaybackCues */ + LOG_COMMAND_ExCategory_DecrementNumPlaybackCues, /* criAtomExCategory_DecrementNumPlaybackCues */ + LOG_COMMAND_SoundVoice_Volume, /* criatomsoundvoice_parameter_update_on_changed:volume */ + LOG_COMMAND_SoundVoice_FreeVoice, /* criatomsoundvoice_FreeVoice */ + LOG_COMMAND_ExSequence_GetFreeBlock, /* criAtomExSequence_GetFreeSequenceBlock */ + LOG_COMMAND_ExSequence_SetFreeBlock, /* criAtomExSequence_SetFreeSequenceBlock */ + LOG_COMMAND_ExSequence_GetFreeSeqInfo, /* criAtomExSequence_GetFreeSequenceInfo */ + LOG_COMMAND_ExSequence_SetFreeSeqInfo, /* criAtomExSequence_SetFreeSequenceInfo */ + LOG_COMMAND_SoundVoice_Allocate, /* criAtomSoundVoice_AllocateVoice */ + LOG_COMMAND_GetAisacDestinationValue, /* criAtomCueSheet_GetAisacDestinationValue */ + LOG_COMMAND_SequenceTrack_Mute, /* criAtomSequenceTrack_Mute */ + LOG_COMMAND_Preview_RequestSendLog, /* CriAtomMonitorLoc::MakeLogSendRequestPacket */ + LOG_COMMAND_RequestSendAcb, /* CriAtomMonitorLoc::MakeRequestPacket4SendAcb */ + LOG_COMMAND_Monitor_MakeClosePacket, /* CriAtomMonitorLoc::MakeClosePacket */ + LOG_COMMAND_Monitor_MakeSendDataResultPacket, /* CriAtomMonitorLoc::MakeSendDataResultPacket */ + LOG_COMMAND_CpuLoadAndNumUsedVoices, /* CriAtomMonitorLoc::MakePerformanceInfoPacket */ + LOG_COMMAND_SequenceCallback, /* SequenceCallback */ + LOG_COMMAND_OverwriteAcf, /* CriAtomMonitorLoc::MakeRequestPacket4OverwriteAcf */ + LOG_COMMAND_StartLogging, /* CriAtomMonitorLoc::MakeLoggingStartTimePacket */ + LOG_COMMAND_SequenceLoopInfo, /* SequenceLoopInfo */ + LOG_COMMAND_Ex3dSource_Update, /* criAtomEx3dSource_Update */ + LOG_COMMAND_Ex3dListener_Update, /* criAtomEx3dListener_Update */ + LOG_COMMAND_ExVoicePool_AllocateAiffVoicePool, /* criAtomExVoicePool_AllocateAiffVoicePool */ + LOG_COMMAND_ExAiffVoicePoolConfig, /* CriAtomExAiffVoicePoolConfig */ + LOG_COMMAND_ExVoicePool_AllocateAt9VoicePool_PS4, /* criAtomExVoicePool_AllocateAt9VoicePool_PS4 */ + LOG_COMMAND_ExAt9VoicePoolConfig_PS4, /* CriAtomExAt9VoicePoolConfig_PS4 */ + LOG_COMMAND_UserLog, /* criAtomExMonitor_OutputUserLog */ + LOG_COMMAND_ExCategoryConfig, /* CriAtomExCategoryConfig */ + LOG_COMMAND_SoundVoice_KillByLimit, /* criatomsoundvoice_KillByLimit */ + LOG_COMMAND_SoundVoice_Virtualize, /* criatomsoundvoice_Virtualize */ + LOG_COMMAND_SoundVoice_UnVirtualize, /* criatomsoundvoice_UnVirtualize */ + LOG_COMMAND_AsrBusAnalyzeInfo, /* criAtomPreview_MakeAsrBusInfoPacket */ + LOG_COMMAND_LoudnessInfo, /* criAtomPreview_MakeLoudnessInfoPacket */ + LOG_COMMAND_StreamingInfo, /* criAtomPreview_MakeStreamingInfoPacket */ + LOG_COMMAND_PlayerPool_NumVoices, /* criAtomPreview_MakeLogPacketNumVoiceInVoicePool */ + LOG_COMMAND_ExVoicePool_AllocateAdpcmVoicePool_WIIU,/* criAtomExVoicePool_AllocateAdpcmVoicePool_WIIU */ + LOG_COMMAND_ExAdpcmVoicePoolConfig_WIIU, /* CriAtomExAdpcmVoicePoolConfig_WIIU */ + LOG_COMMAND_StreamTypeMemory, /* StreamTypeMemory */ + LOG_COMMAND_StreamTypeStream, /* StreamTypeStream */ + LOG_COMMAND_StreamTypeZeroLatencyStream, /* StreamTypeZeroLatencyStream */ + LOG_COMMAND_AsrBusAnalyzeInfoAllCh, /* criAtomPreview_MakeAsrBusInfoPacketForProfiler */ + LOG_COMMAND_ExPlayer_SetAisacControlValue, /* criAtomExPlayer_SetAisacControlByName, ById */ + LOG_COMMAND_SequenceTrack_Start, /* SetupSeuenceTrack */ + LOG_COMMAND_SequenceTrack_Stop, /* criAtomSequence_FreeSequenceTrack */ + LOG_COMMAND_SoundPlayer_SetVibrationId, /* criAtomSoundPlayer_SoundPlayer_SetVibrationId */ + LOG_COMMAND_ExGameVariableConfig, /* CriAtomExGameVariableConfig */ + LOG_COMMAND_SetGameVariable, /* SetGameVariableByname, ById */ + LOG_COMMAND_ExVibrationVoicePoolConfig, /* CriAtomExVibrationVoicePoolConfig */ + LOG_COMMAND_ExVoicePool_AllocateVibrationVoicePool, /* criAtomExVoicePool_AllocateVibrationVoicePool */ + LOG_COMMAND_ExVoicePlayer_Pause, /* criAtomExPlayer_Pause */ + LOG_COMMAND_SoundPlayer_SetVibrationName, /* criAtomSoundPlayer_SoundPlayer_SetVibrationName */ + LOG_COMMAND_ExCategory_Stop, /* criAtomExCategory_Stop */ + LOG_COMMAND_ExCategory_StopWithoutReleaseTime, /* criAtomExCategory_StopWithoutReleaseTime */ + LOG_COMMAND_Ex3dTransceiver_Create, /* criAtomEx3dTransceiver_Create */ + LOG_COMMAND_Ex3dTransceiver_Destroy, /* criAtomEx3dTransceiver_Destroy */ + LOG_COMMAND_Ex3dTransceiverHn, /* criAtomEx3dTransceiverHn */ + LOG_COMMAND_Ex3dTransceiverConfig, /* criAtomEx3dTransceiverConfig */ + LOG_COMMAND_Ex3dTransceiver_UpdateInput, /* criAtomEx3dTransceiver_UpdateInput */ + LOG_COMMAND_Ex3dTransceiver_UpdateOutput, /* criAtomEx3dTransceiver_UpdateOutput */ + LOG_COMMAND_SoundVoice_CalcFinalVoiceParamAndSilentVolumeCore, /* criAtomVoice_CalcFinalVoiceParamAndSilentVolumeCore */ + LOG_COMMAND_AdmPlayer_Create, /* criAtomAdmPlayer_Create */ + LOG_COMMAND_AdmPlayer_Destroy, /* criAtomAdmPlayer_Destroy */ + LOG_COMMAND_AdmPlayer_InternalStart, /* criatomadmplayer_internal_start */ /* フェーズ単位の再生処理 */ + LOG_COMMAND_AdmPlayer_Start, /* criAtomAdmPlayer_Start */ + LOG_COMMAND_AdmPlayer_Stop, /* criAtomAdmPlayer_Stop */ + LOG_COMMAND_AdmPlayer_StopByPhraseEnd, /* criAtomAdmPlayer_StopByPhraseEnd */ + }; + + protected enum LogParamId { + LOG_STRINGS_ITEM_CRIATOMDEF = 0, /* #CRIATOMDEF */ + LOG_STRINGS_ITEM_CRIATOM, /* #CRIATOM */ + LOG_STRINGS_ITEM_TimeStamp, /* TimeStamp */ + LOG_STRINGS_ITEM_ThreadId, /* ThreadId */ + LOG_STRINGS_ITEM_ThreadModel, /* thread_model */ + LOG_STRINGS_ITEM_ServerFrequency, /* server_frequency */ + LOG_STRINGS_ITEM_ParameterUpdateInterval, /* parameter_update_interval */ + LOG_STRINGS_ITEM_MaxVirtualVoices, /* max_virtual_voices */ + LOG_STRINGS_ITEM_MaxVoiceLimitGroups, /* max_voice_limit_groups */ + LOG_STRINGS_ITEM_MaxCategories, /* max_categories */ + LOG_STRINGS_ITEM_MaxSequences, /* max_sequences */ + LOG_STRINGS_ITEM_MaxTracks, /* max_tracks */ + LOG_STRINGS_ITEM_MaxTrackItems, /* max_track_items */ + LOG_STRINGS_ITEM_MaxAisacAutoModulations, /* max_aisac_auto_modulations */ + LOG_STRINGS_ITEM_MaxPitch, /* max_pitch */ + LOG_STRINGS_ITEM_CoordinateSystem, /* coordinate_system */ + LOG_STRINGS_ITEM_RngIf, /* rng_if */ + LOG_STRINGS_ITEM_FsConfig, /* fs_config */ + LOG_STRINGS_ITEM_Context, /* context */ + LOG_STRINGS_ITEM_OutputChannels, /* output_channels */ + LOG_STRINGS_ITEM_OutputSamplingRate, /* output_sampling_rate */ + LOG_STRINGS_ITEM_SoundRendererType, /* sound_renderer_type */ + LOG_STRINGS_ITEM_NumMixers, /* num_mixers */ + LOG_STRINGS_ITEM_MaxVoices, /* max_voices */ + LOG_STRINGS_ITEM_MaxInputChannels, /* max_input_channels */ + LOG_STRINGS_ITEM_MaxSamplingRate, /* max_sampling_rate */ + LOG_STRINGS_ITEM_Identifier, /* identifier */ + LOG_STRINGS_ITEM_MaxStreams, /* max_streams */ + LOG_STRINGS_ITEM_MaxBps, /* max_bps */ + LOG_STRINGS_ITEM_DbasId, /* CriAtomDbasId */ + LOG_STRINGS_ITEM_MaxPath, /* max_path */ + LOG_STRINGS_ITEM_MaxFiles, /* max_files */ + LOG_STRINGS_ITEM_CacheSize, /* cache_size */ + LOG_STRINGS_ITEM_StreamingCacheId, /* CriAtomStreamingCacheId */ + LOG_STRINGS_ITEM_NumVoices, /* num_voices */ + LOG_STRINGS_ITEM_MaxChannels, /* max_channels */ + LOG_STRINGS_ITEM_StreamingFlag, /* streaming_flag */ + LOG_STRINGS_ITEM_DecodeLatency, /* decode_latency */ + LOG_STRINGS_ITEM_ExVoicePoolHn, /* CriAtomExVoicePoolHn */ + LOG_STRINGS_ITEM_AllocationMethod, /* allocation_method */ + LOG_STRINGS_ITEM_MaxPathStrings, /* max_path_strings */ + LOG_STRINGS_ITEM_UpdatesTime, /* updates_time */ + LOG_STRINGS_ITEM_ExPlayerHn, /* CriAtomExPlayerHn */ + LOG_STRINGS_ITEM_Id, /* id */ + LOG_STRINGS_ITEM_ParameterType, /* parameter_type */ + LOG_STRINGS_ITEM_Key, /* key */ + LOG_STRINGS_ITEM_DecrypterHn, /* CriAtomDecrypterHn */ + LOG_STRINGS_ITEM_Work, /* work */ + LOG_STRINGS_ITEM_WorkSize, /* work_size */ + LOG_STRINGS_ITEM_Ex3dSourceHn, /* CriAtomEx3dSourceHn */ + LOG_STRINGS_ITEM_Ex3dListenerHn, /* CriAtomEx3dListenerHn */ + LOG_STRINGS_ITEM_ExPlaybackId, /* CriAtomExPlaybackId */ + LOG_STRINGS_ITEM_ExFaderConfig, /* CriAtomExFaderConfig */ + LOG_STRINGS_ITEM_ExAcfConfig, /* CriAtomExAcfConfig */ + LOG_STRINGS_ITEM_AcfData, /* acf_data */ + LOG_STRINGS_ITEM_AcfDataSize, /* acf_data_size */ + LOG_STRINGS_ITEM_FsBinderHn, /* CriFsBinderHn */ + LOG_STRINGS_ITEM_Path, /* path */ + LOG_STRINGS_ITEM_AcbData, /* acb_data */ + LOG_STRINGS_ITEM_AcbDataSize, /* acb_data_size */ + LOG_STRINGS_ITEM_AwbPath, /* awb_path */ + LOG_STRINGS_ITEM_AwbId, /* awb_id */ + LOG_STRINGS_ITEM_AcbPath, /* acb_path */ + LOG_STRINGS_ITEM_AcbId, /* acb_id */ + LOG_STRINGS_ITEM_ExAcbHn, /* CriAtomExAcbHn */ + LOG_STRINGS_ITEM_Sw, /* sw */ + LOG_STRINGS_ITEM_ExResumeMode, /* CriAtomExResumeMode */ + LOG_STRINGS_ITEM_ErrorString, /* error_string */ + LOG_STRINGS_ITEM_SoundPlaybackId, /* CriAtomSoundPlaybackId */ + LOG_STRINGS_ITEM_SoundPlayerHn, /* CriAtomSoundPlayerHn */ + LOG_STRINGS_ITEM_AwbHn, /* CriAtomAwbHn */ + LOG_STRINGS_ITEM_ExCueId, /* CriAtomExCueId */ + LOG_STRINGS_ITEM_CueName, /* cue_name */ + LOG_STRINGS_ITEM_ExCueIndex, /* CriAtomExCueIndex */ + LOG_STRINGS_ITEM_Buffer, /* buffer */ + LOG_STRINGS_ITEM_Size, /* size */ + LOG_STRINGS_ITEM_ExWaveId, /* CriAtomExWaveId */ + LOG_STRINGS_ITEM_MemoryAwbHn, /* CriAtomAwbHn for Memory */ + LOG_STRINGS_ITEM_StreamAwbHn, /* CriAtomAwbHn for Stream */ + LOG_STRINGS_ITEM_ExTweenHn, /* CriAtomExTweenHn */ + LOG_STRINGS_ITEM_ExConfig, /* CriAtomExConfig */ + LOG_STRINGS_ITEM_ExAsrConfig, /* CriAtomExAsrConfig */ + LOG_STRINGS_ITEM_ExHcaMxConfig, /* CriAtomExHcaMxConfig */ + LOG_STRINGS_ITEM_ExDbasConfig, /* CriAtomExDbasConfig */ + LOG_STRINGS_ITEM_ExStreamingCacheConfig, /* CriAtomExStreamingCacheConfig */ + LOG_STRINGS_ITEM_ExStandardVoicePoolConfig, /* CriAtomExStandardVoicePoolConfig */ + LOG_STRINGS_ITEM_ExAdxVoicePoolConfig, /* CriAtomExAdxVoicePoolConfig */ + LOG_STRINGS_ITEM_ExAhxVoicePoolConfig, /* CriAtomExAhxVoicePoolConfig */ + LOG_STRINGS_ITEM_ExHcaVoicePoolConfig, /* CriAtomExHcaVoicePoolConfig */ + LOG_STRINGS_ITEM_ExHcaMxVoicePoolConfig, /* CriAtomExHcaMxVoicePoolConfig */ + LOG_STRINGS_ITEM_ExWaveVoicePoolConfig, /* CriAtomExWaveVoicePoolConfig */ + LOG_STRINGS_ITEM_ExRawPcmVoicePoolConfig, /* CriAtomExRawPcmVoicePoolConfig */ + LOG_STRINGS_ITEM_ExPlayerConfig, /* CriAtomExPlayerConfig */ + LOG_STRINGS_ITEM_ExTweenConfig, /* CriAtomExTweenConfig */ + LOG_STRINGS_ITEM_DecrypterConfig, /* CriAtomDecrypterConfig */ + LOG_STRINGS_ITEM_Ex3dSourceConfig, /* CriAtomEx3dSourceConfig */ + LOG_STRINGS_ITEM_Ex3dListenerConfig, /* CriAtomEx3dListenerConfig */ + LOG_STRINGS_ITEM_ExAdpcmVoicePoolConfig_3DS, /* CriAtomExAdpcmVoicePoolConfig_3DS */ + LOG_STRINGS_ITEM_ExAdpcmVoicePoolConfig_WII, /* CriAtomExAdpcmVoicePoolConfig_WII */ + LOG_STRINGS_ITEM_ExVagVoicePoolConfig_PSP, /* CriAtomExVagVoicePoolConfig_PSP */ + LOG_STRINGS_ITEM_ExAtrac3VoicePoolConfig_PSP, /* CriAtomExAtrac3VoicePoolConfig_PSP */ + LOG_STRINGS_ITEM_ExVagVoicePoolConfig_VITA, /* CriAtomExVagVoicePoolConfig_VITA */ + LOG_STRINGS_ITEM_ExAt9VoicePoolConfig_VITA, /* CriAtomExAt9VoicePoolConfig_VITA */ + LOG_STRINGS_ITEM_NumGroups, /* num_groups */ + LOG_STRINGS_ITEM_VoicesPerGroup, /* voices_per_group */ + LOG_STRINGS_ITEM_NumCategoryGroups, /* num_category_groups */ + LOG_STRINGS_ITEM_NumCategories, /* num_categories */ + LOG_STRINGS_ITEM_reserved, /* reserved */ + LOG_STRINGS_ITEM_ExFaderHn, /* CriAtomExFaderHn */ + LOG_STRINGS_ITEM_Guid, /* Guid */ + LOG_STRINGS_ITEM_parent_info_id, /* parent CriAtomExPlaybackId */ + LOG_STRINGS_ITEM_PlayerPoolPlayerInfo, /* CriAtomPlayerPoolPlayerInfo */ + LOG_STRINGS_ITEM_SoundElementHn, /* CriAtomSoundElementHn */ + LOG_STRINGS_ITEM_SoundVoiceHn, /* CriAtomSoundVoiceHn */ + LOG_STRINGS_ITEM_ExPlaybackId_Cause, /* Cause CriAtomExPlaybackId */ + LOG_STRINGS_ITEM_Index, /* Index */ + LOG_STRINGS_ITEM_NumAllPlaybacks, /* NumAllPlaybacks */ + LOG_STRINGS_ITEM_NumPlaybacks, /* NumPlaybacks */ + LOG_STRINGS_ITEM_CategoriesPerPlayback, /* categories_per_playback */ + LOG_STRINGS_ITEM_EnableVoicePriorityDecay, /* enable_voice_priority_decay */ + LOG_STRINGS_ITEM_Volume, /* volume */ + LOG_STRINGS_ITEM_SoundElementId, /* CriAtomSoundElementId */ + LOG_STRINGS_ITEM_SoundVoiceId, /* CriAtomSoundVoiceId */ + LOG_STRINGS_ITEM_ExAcbName, /* Acb Name */ + LOG_STRINGS_ITEM_PlayerPoolPlayerInfoId, /* CriAtomPlayerPoolPlayerInfoId */ + LOG_STRINGS_ITEM_AisacControl, /* Aisac Control */ + LOG_STRINGS_ITEM_TrackNo, /* track no */ + LOG_STRINGS_ITEM_Mute, /* mute */ + LOG_STRINGS_ITEM_Result, /* Result */ + LOG_STRINGS_ITEM_LogRecordMode, /* log record mode */ + LOG_STRINGS_ITEM_NumCh, /* Num Ch */ + LOG_STRINGS_ITEM_NumLoaders, /* Num Loaders */ + LOG_STRINGS_ITEM_NumPlayers, /* Num Players */ + LOG_STRINGS_ITEM_Status, /* Status */ + LOG_STRINGS_ITEM_PlayingTime, /* PlayingTime */ + LOG_STRINGS_ITEM_DspBusSpectra, /* DspBusSpectra */ + LOG_STRINGS_ITEM_CpuLoad, /* CpuLoad */ + LOG_STRINGS_ITEM_NumUsedVoices, /* NumUsedVoices */ + LOG_STRINGS_ITEM_SequencePlaybackPosition, /* SequencePlaybackPosition */ + LOG_STRINGS_ITEM_CallbackValue, /* CallbackValue */ + LOG_STRINGS_ITEM_CallbackString, /* CallbackString */ + LOG_STRINGS_ITEM_PeakLevel, /* PeakLevel */ + LOG_STRINGS_ITEM_RmsLevel, /* RmsLevel */ + LOG_STRINGS_ITEM_PeakHoldLevel, /* PeakHoldLevel */ + LOG_STRINGS_ITEM_RequestId, /* RequestId */ + LOG_STRINGS_ITEM_TargetId, /* TargetId */ + LOG_STRINGS_ITEM_Md5, /* Md5 */ + LOG_STRINGS_ITEM_GameVariable, /* GameVariable */ + LOG_STRINGS_ITEM_GameVariableName, /* GameVariableName */ + LOG_STRINGS_ITEM_TimeMs, /* TimeMs */ + LOG_STRINGS_ITEM_SnapShotName, /* SnapShotName */ + LOG_STRINGS_ITEM_AisacControlId, /* AisacControlId */ + LOG_STRINGS_ITEM_StartTimeMs, /* StartTimeMs */ + LOG_STRINGS_ITEM_SelectorName, /* SelectorName */ + LOG_STRINGS_ITEM_LabelName, /* LabelName */ + LOG_STRINGS_ITEM_BlockName, /* BlockName */ + LOG_STRINGS_ITEM_CategoryName, /* CategoryName */ + LOG_STRINGS_ITEM_AisacControlName, /* AisacControlName */ + LOG_STRINGS_ITEM_SettingName, /* SettingName */ + LOG_STRINGS_ITEM_CueSheetId, /* CueSheetId */ + LOG_STRINGS_ITEM_BusNo, /* BusNo */ + LOG_STRINGS_ITEM_FxType, /* FxType */ + LOG_STRINGS_ITEM_RemainedLoopCount, /* RemainedLoopCount */ + LOG_STRINGS_ITEM_SequenceLoopId, /* SequenceLoopId */ + LOG_STRINGS_ITEM_Ex3dPosVector_Position, /* 3dPosVector_Position */ + LOG_STRINGS_ITEM_Ex3dPosVector_Velocity, /* 3dPosVector_Velocity */ + LOG_STRINGS_ITEM_Ex3dPosVector_Forward, /* 3dPosVector_Forward */ + LOG_STRINGS_ITEM_Ex3dPosVector_Upward, /* 3dPosVector_Upward */ + LOG_STRINGS_ITEM_Ex3dPosVector_FocusPoint, /* 3dPosVector_FocusPoint */ + LOG_STRINGS_ITEM_Ex3dPosVector_Cone, /* 3dPosVector_Cone */ + LOG_STRINGS_ITEM_Ex3dMaxAngleAisacDelta, /* 3dMaxAngleAisacDelta */ + LOG_STRINGS_ITEM_Ex3dEnablePriorityDecay, /* 3dEnablePriorityDecay */ + LOG_STRINGS_ITEM_Ex3dDistanceFactor, /* 3dDistanceFactor */ + LOG_STRINGS_ITEM_Ex3dDistanceFocusLevel, /* 3dDistanceFocusLevel */ + LOG_STRINGS_ITEM_Ex3dDirectionFocusLevel, /* 3dDirectionFocusLevel */ + LOG_STRINGS_ITEM_Result3dPos, /* Result3dPos */ + LOG_STRINGS_ITEM_ExAiffVoicePoolConfig, /* CriAtomExAiffVoicePoolConfig */ + LOG_STRINGS_ITEM_SrType, /* SoundRendererTyoe */ + LOG_STRINGS_ITEM_ExAt9VoicePoolConfig_PS4, /* CriAtomExAt9VoicePoolConfig_PS4 */ + LOG_STRINGS_ITEM_AverageServerTime, /* AverageServerTime */ + LOG_STRINGS_ITEM_AverageServerInterval, /* AverageServerInterval */ + LOG_STRINGS_ITEM_MaxServerTime, /* MaxServerTime */ + LOG_STRINGS_ITEM_MaxServerInterval, /* MaxServerInterval */ + LOG_STRINGS_ITEM_UserLog, /* UserLog */ + LOG_STRINGS_ITEM_ByVoiceGroupLimitation, /* ByVoiceGroupLimitation */ + LOG_STRINGS_ITEM_ByVoicePoolLimitation, /* ByVoicePoolLimitation */ + LOG_STRINGS_ITEM_RetryFlag, /* RetryFlag */ + LOG_STRINGS_ITEM_BusName, /* BusName */ + LOG_STRINGS_ITEM_StreamType, /* StreamType */ + LOG_STRINGS_ITEM_MomentaryValue, /* MomentaryValue */ + LOG_STRINGS_ITEM_ShortTermValue, /* ShortTermValue */ + LOG_STRINGS_ITEM_IntegratedValue, /* IntegratedValue */ + LOG_STRINGS_ITEM_TotalBps, /* TotalBps */ + LOG_STRINGS_ITEM_NumCues, /* num_cues */ + LOG_STRINGS_ITEM_SoundFormat, /* SoundFormat *//* (CriAtomSoundFormatのこと) */ + LOG_STRINGS_ITEM_ExAdpcmVoicePoolConfig_WIIU, /* CriAtomExAdpcmVoicePoolConfig_WIIU */ + LOG_STRINGS_ITEM_AwbName, /* AwbName */ + LOG_STRINGS_ITEM_NumStreamAwb, /* NumStreamAwb */ + LOG_STRINGS_ITEM_ExPlayback_AllocateModule, /* ExPlayback_AllocateModule */ + LOG_STRINGS_ITEM_AisacControlValue, /* AisacControlValue */ + LOG_STRINGS_ITEM_NumAllPlaybacksForReact, /* NumAllPlaybacksForReact */ + LOG_STRINGS_ITEM_PreviewContext, /* PreviewContext */ + LOG_STRINGS_ITEM_MaxParameterBlocks, /* max_parameter_blocks */ + LOG_STRINGS_ITEM_MaxFaders, /* max_faders */ + LOG_STRINGS_ITEM_NumBuses, /* num_buses */ + LOG_STRINGS_ITEM_MaxRacks, /* max_racks */ + LOG_STRINGS_ITEM_OutputChannels4HcaMx, /* output_channels(HcaMxConfig用) */ + LOG_STRINGS_ITEM_OutputSamplingRate4HcaMx, /* output_sampling_rate(HcaMxConfig用) */ + LOG_STRINGS_ITEM_SoundRendererType4HcaMx, /* sound_renderer_type(HcaMxConfig用) */ + LOG_STRINGS_ITEM_SPEAKER_SYSTEM, /* speaker_system */ + LOG_STRINGS_ITEM_SPEAKER_ANGLE_LEFT, /* left_speaker_angle */ + LOG_STRINGS_ITEM_SPEAKER_ANGLE_RIGHT, /* right_speaker_angle */ + LOG_STRINGS_ITEM_SPEAKER_ANGLE_CENTER, /* center_speaker_angle */ + LOG_STRINGS_ITEM_SPEAKER_ANGLE_LFE, /* lfe_speaker_angle */ + LOG_STRINGS_ITEM_SPEAKER_ANGLE_SURROUND_LEFT, /* surround_left_speaker_angle */ + LOG_STRINGS_ITEM_SPEAKER_ANGLE_SURROUND_RIGHT, /* surround_right_speaker_angle */ + LOG_STRINGS_ITEM_SPEAKER_ANGLE_SURROUND_BACK_LEFT, /* surround_back_left_speaker_angle */ + LOG_STRINGS_ITEM_SPEAKER_ANGLE_SURROUND_BACK_RIGHT, /* surround_back_right_speaker_angle */ + LOG_STRINGS_ITEM_PAN_SPEAKER_TYPE, /* pan_speaker_type */ + LOG_STRINGS_ITEM_VOICE_STOP_REASON, /* CriAtomVoiceStopReason */ + LOG_STRINGS_ITEM_ExVibrationVoicePoolConfig, /* CriAtomExVibrationVoicePoolConfig */ + LOG_STRINGS_ITEM_TouchSenceEffectName, /* TouchSenceEffectName */ + LOG_STRINGS_ITEM_DspName, /* DspName */ + LOG_STRINGS_ITEM_DspObject, /* DspObject */ + LOG_STRINGS_ITEM_DspSlotNo, /* DspSlotNo */ + LOG_STRINGS_ITEM_DspPluginType, /* DspPluginType */ + LOG_STRINGS_ITEM_Ex3dPosVector_ListenerTop, /* 3dPosVector_ListenerTop */ + LOG_STRINGS_ITEM_Playback_Status, /* Playback_Status */ + LOG_STRINGG_ITEM_InstrumentInstanceCbFunc, + LOG_STRINGG_ITEM_InstrumentInstanceCbObj, + LOG_STRINGG_ITEM_AttachInstrumentInstancePlayerHn, + LOG_STRINGG_ITEM_InstrumentInstance, + LOG_STRINGS_ITEM_Ex3dTransceiverHn, /* CriAtomEx3dTransceiverHn */ + LOG_STRINGS_ITEM_Ex3dTransceiverConfig, /* CriAtomEx3dTransceiverConfig */ + LOG_STRINGS_ITEM_Ex3dRegionHn, /* CriAtomExRegionHn */ + LOG_STRINGS_ITEM_Ex3dTransceiverDirectAudioRadius, /* TransceiverDirectAudioRadius */ + LOG_STRINGS_ITEM_Ex3dTransceiverCrossFadeDistance, /* TransceiverCrossFadeDistance */ + LOG_STRINGS_ITEM_ProgramNo, /* サウンドプログラムバングプレビュー用Program No */ + LOG_STRINGS_ITEM_KeyNo, /* サウンドプログラムバングプレビュー用Key No */ + LOG_STRINGS_ITEM_Velocity, /* サウンドプログラムバングプレビュー用Velocity */ + LOG_STRINGS_ITEM_PitchBend, /* サウンドプログラムバングプレビュー用PitchBend */ + LOG_STRINGS_ITEM_Format, /* コーデックフォーマット:HCA, ADX, HCA-MX... */ + LOG_STRINGS_ITEM_MaxRhythmTracks, /* CriAtomAdmPlayerConfig.max_rhythm_tracks */ + LOG_STRINGS_ITEM_MaxMelodyTracks, /* CriAtomAdmPlayerConfig.max_melody_tracks */ + LOG_STRINGS_ITEM_MaxVocalTracks, /* CriAtomAdmPlayerConfig.max_vocal_tracks */ + LOG_STRINGS_ITEM_AdmPlayerHn, /* CriAtomAdmPlayerHn */ + }; + + /* ログのパラメータ引数の型 */ + protected enum LogParamTypes { + TYPE_INT8 = 0, + TYPE_INT16, + TYPE_INT32, + TYPE_INT64, + TYPE_FLOAT32, + TYPE_CHAR, + TYPE_UINTPTR, + TYPE_GUID, + TYPE_128, + TYPE_VECTOR + } + static protected readonly int[] ParamTypeSizes32 = new int[] { + 1, /* SIZE_INT8 */ + 2, /* SIZE_INT16 */ + 4, /* SIZE_INT32 */ + 8, /* SIZE_INT64 */ + 4, /* SIZE_FLOAT32 */ + 2, /* SIZE_CHAR (String Size) */ + 4, /* SIZE_UINTPTR (Handles) */ + 16, /* SIZE_GUID */ + 128, /* SIZE_128 */ + 12 /* SIZE_VECTOR (Vector3f) */ + }; + static protected readonly int[] ParamTypeSizes64 = new int[] { + 1, /* SIZE_INT8 */ + 2, /* SIZE_INT16 */ + 4, /* SIZE_INT32 */ + 8, /* SIZE_INT64 */ + 4, /* SIZE_FLOAT32 */ + 2, /* SIZE_CHAR (String Size) */ + 8, /* SIZE_UINTPTR (Handles) */ + 16, /* SIZE_GUID */ + 128, /* SIZE_128 */ + 12 /* SIZE_VECTOR (Vector3f) */ + }; + + protected struct LogParam { + public readonly string name; + public readonly LogParamTypes type; + public readonly int size32; + public readonly int size64; + public LogParam(string name, LogParamTypes type) + { + this.name = name; + this.type = type; + this.size32 = CriProfiler.ParamTypeSizes32[(int)type]; + this.size64 = CriProfiler.ParamTypeSizes64[(int)type]; + } + } + + static protected readonly LogParam[] LogParams = new LogParam[] { + new LogParam( "#CRIATOMDEF", LogParamTypes.TYPE_CHAR ), /* 0 */ + new LogParam( "#CRIATOM", LogParamTypes.TYPE_CHAR ), /* 1 */ + new LogParam( "TimeStamp[usec]", LogParamTypes.TYPE_INT64 ), /* 2 */ + new LogParam( "ThreadId", LogParamTypes.TYPE_UINTPTR ), /* 3 */ + new LogParam( "thread_model", LogParamTypes.TYPE_INT8 ), /* 4 */ + new LogParam( "server_frequency", LogParamTypes.TYPE_FLOAT32 ), /* 5 */ + new LogParam( "parameter_update_interval", LogParamTypes.TYPE_INT16 ), /* 6 */ + new LogParam( "max_virtual_voices", LogParamTypes.TYPE_INT16 ), /* 7 */ + new LogParam( "max_voice_limit_groups", LogParamTypes.TYPE_INT16 ), /* 8 */ + new LogParam( "max_categories", LogParamTypes.TYPE_INT16 ), /* 9 */ + new LogParam( "max_sequences", LogParamTypes.TYPE_INT16 ), /* 10 */ + new LogParam( "max_tracks", LogParamTypes.TYPE_INT16 ), /* 11 */ + new LogParam( "max_track_items", LogParamTypes.TYPE_INT16 ), /* 12 */ + new LogParam( "max_aisac_auto_modulations", LogParamTypes.TYPE_INT16 ), /* 13 */ + new LogParam( "max_pitch", LogParamTypes.TYPE_FLOAT32 ), /* 14 */ + new LogParam( "coordinate_system", LogParamTypes.TYPE_INT8 ), /* 15 */ + new LogParam( "rng_if", LogParamTypes.TYPE_UINTPTR ), /* 16 */ + new LogParam( "fs_config", LogParamTypes.TYPE_UINTPTR ), /* 17 */ + new LogParam( "context", LogParamTypes.TYPE_UINTPTR ), /* 18 */ + new LogParam( "output_channels", LogParamTypes.TYPE_INT8 ), /* 19 */ + new LogParam( "output_sampling_rate", LogParamTypes.TYPE_INT32 ), /* 20 */ + new LogParam( "sound_renderer_type", LogParamTypes.TYPE_INT8 ), /* 21 */ + new LogParam( "num_mixers", LogParamTypes.TYPE_INT16 ), /* 22 */ + new LogParam( "max_voices", LogParamTypes.TYPE_INT16 ), /* 23 */ + new LogParam( "max_input_channels", LogParamTypes.TYPE_INT8 ), /* 24 */ + new LogParam( "max_sampling_rate", LogParamTypes.TYPE_INT32 ), /* 25 */ + new LogParam( "identifier", LogParamTypes.TYPE_INT32 ), /* 26 */ + new LogParam( "max_streams", LogParamTypes.TYPE_INT32 ), /* 27 */ + new LogParam( "max_bps", LogParamTypes.TYPE_INT32 ), /* 28 */ + new LogParam( "CriAtomDbasId", LogParamTypes.TYPE_INT32 ), /* 29 */ + new LogParam( "max_path", LogParamTypes.TYPE_INT16 ), /* 30 */ + new LogParam( "max_files", LogParamTypes.TYPE_INT32 ), /* 31 */ + new LogParam( "cache_size", LogParamTypes.TYPE_INT32 ), /* 32 */ + new LogParam( "CriAtomStreamingCacheId", LogParamTypes.TYPE_UINTPTR ), /* 33 */ + new LogParam( "num_voices", LogParamTypes.TYPE_INT32 ), /* 34 */ + new LogParam( "max_channels", LogParamTypes.TYPE_INT8 ), /* 35 */ + new LogParam( "streaming_flag", LogParamTypes.TYPE_INT8 ), /* 36 */ + new LogParam( "decode_latency", LogParamTypes.TYPE_INT32 ), /* 37 */ + new LogParam( "CriAtomExVoicePoolHn", LogParamTypes.TYPE_UINTPTR ), /* 38 */ + new LogParam( "allocation_method", LogParamTypes.TYPE_INT8 ), /* 39 */ + new LogParam( "max_path_strings", LogParamTypes.TYPE_INT16 ), /* 40 */ + new LogParam( "updates_time", LogParamTypes.TYPE_INT8 ), /* 41 */ + new LogParam( "CriAtomExPlayerHn", LogParamTypes.TYPE_UINTPTR ), /* 42 */ + new LogParam( "id", LogParamTypes.TYPE_INT32 ), /* 43 */ + new LogParam( "parameter_type", LogParamTypes.TYPE_INT8 ), /* 44 */ + new LogParam( "key", LogParamTypes.TYPE_INT64 ), /* 45 */ + new LogParam( "CriAtomDecrypterHn", LogParamTypes.TYPE_UINTPTR ), /* 46 */ + new LogParam( "work", LogParamTypes.TYPE_UINTPTR ), /* 47 */ + new LogParam( "work_size", LogParamTypes.TYPE_INT32 ), /* 48 */ + new LogParam( "CriAtomEx3dSourceHn", LogParamTypes.TYPE_UINTPTR ), /* 49 */ + new LogParam( "CriAtomEx3dListenerHn", LogParamTypes.TYPE_UINTPTR ), /* 50 */ + new LogParam( "CriAtomExPlaybackId", LogParamTypes.TYPE_INT32 ), /* 51 */ + new LogParam( "CriAtomExFaderConfig", LogParamTypes.TYPE_UINTPTR ), /* 52 */ + new LogParam( "CriAtomExAcfConfig", LogParamTypes.TYPE_UINTPTR ), /* 53 */ + new LogParam( "acf_data", LogParamTypes.TYPE_UINTPTR ), /* 54 */ + new LogParam( "acf_data_size", LogParamTypes.TYPE_INT32 ), /* 55 */ + new LogParam( "CriFsBinderHn", LogParamTypes.TYPE_UINTPTR ), /* 56 */ + new LogParam( "path", LogParamTypes.TYPE_CHAR ), /* 57 */ + new LogParam( "acb_data", LogParamTypes.TYPE_UINTPTR ), /* 58 */ + new LogParam( "acb_data_size", LogParamTypes.TYPE_INT32 ), /* 59 */ + new LogParam( "awb_path", LogParamTypes.TYPE_CHAR ), /* 60 */ + new LogParam( "awb_id", LogParamTypes.TYPE_INT32 ), /* 61 */ + new LogParam( "acb_path", LogParamTypes.TYPE_CHAR ), /* 62 */ + new LogParam( "acb_id", LogParamTypes.TYPE_INT32 ), /* 63 */ + new LogParam( "CriAtomExAcbHn", LogParamTypes.TYPE_UINTPTR ), /* 64 */ + new LogParam( "sw", LogParamTypes.TYPE_INT8 ), /* 65 */ + new LogParam( "CriAtomExResumeMode", LogParamTypes.TYPE_INT8 ), /* 66 */ + new LogParam( "error_string", LogParamTypes.TYPE_CHAR ), /* 67 */ + new LogParam( "CriAtomSoundPlaybackId", LogParamTypes.TYPE_INT32 ), /* 68 */ + new LogParam( "CriAtomSoundPlayerHn", LogParamTypes.TYPE_UINTPTR ), /* 69 */ + new LogParam( "CriAtomAwbHn", LogParamTypes.TYPE_UINTPTR ), /* 70 */ + new LogParam( "CriAtomExCueId", LogParamTypes.TYPE_INT32 ), /* 71 */ + new LogParam( "cue_name", LogParamTypes.TYPE_CHAR ), /* 72 */ + new LogParam( "CriAtomExCueIndex", LogParamTypes.TYPE_INT32 ), /* 73 */ + new LogParam( "buffer", LogParamTypes.TYPE_UINTPTR ), /* 74 */ + new LogParam( "size", LogParamTypes.TYPE_INT32 ), /* 75 */ + new LogParam( "CriAtomExWaveId", LogParamTypes.TYPE_INT32 ), /* 76 */ + new LogParam( "CriAtomAwbHn for Memory", LogParamTypes.TYPE_UINTPTR ), /* 77 */ + new LogParam( "CriAtomAwbHn for Stream", LogParamTypes.TYPE_UINTPTR ), /* 78 */ + new LogParam( "CriAtomExTweenHn", LogParamTypes.TYPE_UINTPTR ), /* 79 */ + new LogParam( "CriAtomExConfig", LogParamTypes.TYPE_UINTPTR ), /* 80 */ + new LogParam( "CriAtomExAsrConfig", LogParamTypes.TYPE_UINTPTR ), /* 81 */ + new LogParam( "CriAtomExHcaMxConfig", LogParamTypes.TYPE_UINTPTR ), /* 82 */ + new LogParam( "CriAtomDbasConfig", LogParamTypes.TYPE_UINTPTR ), /* 83 */ + new LogParam( "CriAtomStreamingCacheConfig", LogParamTypes.TYPE_UINTPTR ), /* 84 */ + new LogParam( "CriAtomExStandardVoicePoolConfig",LogParamTypes.TYPE_UINTPTR ), /* 85 */ + new LogParam( "CriAtomExAdxVoicePoolConfig", LogParamTypes.TYPE_UINTPTR ), /* 86 */ + new LogParam( "CriAtomExAhxVoicePoolConfig", LogParamTypes.TYPE_UINTPTR ), /* 87 */ + new LogParam( "CriAtomExHcaVoicePoolConfig", LogParamTypes.TYPE_UINTPTR ), /* 88 */ + new LogParam( "CriAtomExHcaMxVoicePoolConfig", LogParamTypes.TYPE_UINTPTR ), /* 89 */ + new LogParam( "CriAtomExWaveVoicePoolConfig", LogParamTypes.TYPE_UINTPTR ), /* 90 */ + new LogParam( "CriAtomExRawPcmVoicePoolConfig", LogParamTypes.TYPE_UINTPTR ), /* 91 */ + new LogParam( "CriAtomExPlayerConfig", LogParamTypes.TYPE_UINTPTR ), /* 92 */ + new LogParam( "CriAtomExTweenConfig", LogParamTypes.TYPE_UINTPTR ), /* 93 */ + new LogParam( "CriAtomDecrypterConfig", LogParamTypes.TYPE_UINTPTR ), /* 94 */ + new LogParam( "CriAtomEx3dSourceConfig", LogParamTypes.TYPE_UINTPTR ), /* 95 */ + new LogParam( "CriAtomEx3dListenerConfig", LogParamTypes.TYPE_UINTPTR ), /* 96 */ + new LogParam( "CriAtomExAdpcmVoicePoolConfig_3DS",LogParamTypes.TYPE_UINTPTR ), /* 97 */ + new LogParam( "CriAtomExAdpcmVoicePoolConfig_WII",LogParamTypes.TYPE_UINTPTR ), /* 98 */ + new LogParam( "CriAtomExVagVoicePoolConfig_PSP",LogParamTypes.TYPE_UINTPTR ), /* 99 */ + new LogParam( "CriAtomExAtrac3VoicePoolConfig_PSP",LogParamTypes.TYPE_UINTPTR ), /* 100 */ + new LogParam( "CriAtomExVagVoicePoolConfig_VITA",LogParamTypes.TYPE_UINTPTR ), /* 101 */ + new LogParam( "CriAtomExAt9VoicePoolConfig_VITA",LogParamTypes.TYPE_UINTPTR ), /* 102 */ + new LogParam( "num_groups", LogParamTypes.TYPE_INT16 ), /* 103 */ + new LogParam( "voices_per_group", LogParamTypes.TYPE_INT16 ), /* 104 */ + new LogParam( "num_category_groups", LogParamTypes.TYPE_INT16 ), /* 105 */ + new LogParam( "num_categories", LogParamTypes.TYPE_INT16 ), /* 106 */ + new LogParam( "reserved", LogParamTypes.TYPE_INT32 ), /* 107 */ + new LogParam( "CriAtomExFaderHn", LogParamTypes.TYPE_UINTPTR ), /* 108 */ + new LogParam( "Guid", LogParamTypes.TYPE_GUID ), /* 109 */ + new LogParam( "parent CriAtomExPlaybackId", LogParamTypes.TYPE_INT32 ), /* 110 */ + new LogParam( "CriAtomPlayerPoolPlayerInfo", LogParamTypes.TYPE_UINTPTR ), /* 111 */ + new LogParam( "CriAtomSoundElementHn", LogParamTypes.TYPE_UINTPTR ), /* 112 */ + new LogParam( "CriAtomSoundVoiceHn", LogParamTypes.TYPE_UINTPTR ), /* 113 */ + new LogParam( "cause CriAtomExPlaybackId", LogParamTypes.TYPE_INT32 ), /* 114 */ + new LogParam( "Index", LogParamTypes.TYPE_INT16 ), /* 115 */ + new LogParam( "NumAllPlaybacks", LogParamTypes.TYPE_INT16 ), /* 116 */ + new LogParam( "NumPlaybacks", LogParamTypes.TYPE_INT16 ), /* 117 */ + new LogParam( "categories_per_playback", LogParamTypes.TYPE_INT8 ), /* 118 */ + new LogParam( "enable_voice_priority_decay", LogParamTypes.TYPE_INT8 ), /* 119 */ + new LogParam( "volume", LogParamTypes.TYPE_FLOAT32 ), /* 120 */ + new LogParam( "CriAtomSoundElementId", LogParamTypes.TYPE_INT32 ), /* 121 */ + new LogParam( "CriAtomSoundVoiceId", LogParamTypes.TYPE_INT32 ), /* 122 */ + new LogParam( "Acb Name", LogParamTypes.TYPE_CHAR ), /* 123 */ + new LogParam( "CriAtomPlayerPoolPlayerInfoId", LogParamTypes.TYPE_INT32 ), /* 124 */ + new LogParam( "Aisac Control", LogParamTypes.TYPE_FLOAT32 ), /* 125 */ + new LogParam( "Track No", LogParamTypes.TYPE_INT16 ), /* 126 */ + new LogParam( "Mute", LogParamTypes.TYPE_INT8 ), /* 127 */ + new LogParam( "Result", LogParamTypes.TYPE_INT8 ), /* 128 */ + new LogParam( "Log Record Mode", LogParamTypes.TYPE_INT32 ), /* 129 */ + new LogParam( "NumCh", LogParamTypes.TYPE_INT8 ), /* 130 */ + new LogParam( "NumLoaders", LogParamTypes.TYPE_INT32 ), /* 131 */ + new LogParam( "NumPlayers", LogParamTypes.TYPE_INT32 ), /* 132 */ + new LogParam( "Status", LogParamTypes.TYPE_INT8 ), /* 133 */ + new LogParam( "PlayingTime", LogParamTypes.TYPE_INT32 ), /* 134 */ + new LogParam( "DspBusSpectra", LogParamTypes.TYPE_128 ), /* 135 */ + new LogParam( "CpuLoad", LogParamTypes.TYPE_FLOAT32 ), /* 136 */ + new LogParam( "NumUsedVoices", LogParamTypes.TYPE_INT32 ), /* 137 */ + new LogParam( "SequencePlaybackPosition", LogParamTypes.TYPE_INT64 ), /* 138 */ + new LogParam( "CallbackValue", LogParamTypes.TYPE_INT32 ), /* 139 */ + new LogParam( "CallbackString", LogParamTypes.TYPE_CHAR ), /* 140 */ + new LogParam( "PeakLevel", LogParamTypes.TYPE_FLOAT32 ), /* 141 */ + new LogParam( "RmsLevel", LogParamTypes.TYPE_FLOAT32 ), /* 142 */ + new LogParam( "PeakHoldLevel", LogParamTypes.TYPE_FLOAT32 ), /* 143 */ + new LogParam( "RequestId", LogParamTypes.TYPE_INT32 ), /* 144 */ + new LogParam( "TargetId", LogParamTypes.TYPE_INT32 ), /* 145 */ + new LogParam( "Md5", LogParamTypes.TYPE_GUID ), /* 146 */ + new LogParam( "GameVariable", LogParamTypes.TYPE_FLOAT32 ), /* 147 */ + new LogParam( "GameVariableName", LogParamTypes.TYPE_CHAR ), /* 148 */ + new LogParam( "TimeMs", LogParamTypes.TYPE_INT32 ), /* 149 */ + new LogParam( "SnapShotName", LogParamTypes.TYPE_CHAR ), /* 150 */ + new LogParam( "AisacControlId", LogParamTypes.TYPE_INT32 ), /* 151 */ + new LogParam( "StartTimeMs", LogParamTypes.TYPE_INT64 ), /* 152 */ + new LogParam( "SelectorName", LogParamTypes.TYPE_CHAR ), /* 153 */ + new LogParam( "LabelName", LogParamTypes.TYPE_CHAR ), /* 154 */ + new LogParam( "BlockName", LogParamTypes.TYPE_CHAR ), /* 155 */ + new LogParam( "CategoryName", LogParamTypes.TYPE_CHAR ), /* 156 */ + new LogParam( "AisacControlName", LogParamTypes.TYPE_CHAR ), /* 157 */ + new LogParam( "SettingName", LogParamTypes.TYPE_CHAR ), /* 158 */ + new LogParam( "CueSheetId", LogParamTypes.TYPE_INT32 ), /* 159 */ + new LogParam( "BusNo", LogParamTypes.TYPE_INT8 ), /* 160 */ + new LogParam( "FxType", LogParamTypes.TYPE_INT32 ), /* 161 */ + new LogParam( "RemainedLoopCount", LogParamTypes.TYPE_INT32 ), /* 162 */ + new LogParam( "SequenceLoopId", LogParamTypes.TYPE_INT16 ), /* 163 */ + new LogParam( "3dPosVector_Position", LogParamTypes.TYPE_VECTOR ), /* 164 */ + new LogParam( "3dPosVector_Velocity", LogParamTypes.TYPE_VECTOR ), /* 165 */ + new LogParam( "3dPosVector_Forward", LogParamTypes.TYPE_VECTOR ), /* 166 */ + new LogParam( "3dPosVector_Upward", LogParamTypes.TYPE_VECTOR ), /* 167 */ + new LogParam( "3dPosVector_FocusPoint", LogParamTypes.TYPE_VECTOR ), /* 168 */ + new LogParam( "3dPosVector_Cone", LogParamTypes.TYPE_VECTOR ), /* 169 */ + new LogParam( "3dMaxAngleAisacDelta", LogParamTypes.TYPE_FLOAT32 ), /* 170 */ + new LogParam( "3dEnablePriorityDecay", LogParamTypes.TYPE_FLOAT32 ), /* 171 */ + new LogParam( "3dDistanceFactor", LogParamTypes.TYPE_FLOAT32 ), /* 172 */ + new LogParam( "3dDistanceFocusLevel", LogParamTypes.TYPE_FLOAT32 ), /* 173 */ + new LogParam( "3dDirectionFocusLevel", LogParamTypes.TYPE_FLOAT32 ), /* 174 */ + new LogParam( "Result3dPos", LogParamTypes.TYPE_INT8 ), /* 175 */ + new LogParam( "CriAtomExAiffVoicePoolConfig", LogParamTypes.TYPE_UINTPTR ), /* 176 */ + new LogParam( "SoundRendererTyoe", LogParamTypes.TYPE_INT8 ), /* 177 */ + new LogParam( "CriAtomExAt9VoicePoolConfig_PS4",LogParamTypes.TYPE_UINTPTR ), /* 178 */ + new LogParam( "AverageServerTime", LogParamTypes.TYPE_INT32 ), /* 179 */ + new LogParam( "AverageServerInterval", LogParamTypes.TYPE_INT32 ), /* 180 */ + new LogParam( "MaxServerTime", LogParamTypes.TYPE_INT32 ), /* 181 */ + new LogParam( "MaxServerInterval", LogParamTypes.TYPE_INT32 ), /* 182 */ + new LogParam( "UserLog", LogParamTypes.TYPE_CHAR ), /* 183 */ + new LogParam( "ByVoiceGroupLimitation", LogParamTypes.TYPE_INT8 ), /* 184 */ + new LogParam( "ByVoicePoolLimitation", LogParamTypes.TYPE_INT8 ), /* 185 */ + new LogParam( "RetryFlag", LogParamTypes.TYPE_INT8 ), /* 186 */ + new LogParam( "BusName", LogParamTypes.TYPE_CHAR ), /* 187 */ + new LogParam( "StreamType", LogParamTypes.TYPE_INT8 ), /* 188 */ + new LogParam( "MomentaryValue", LogParamTypes.TYPE_FLOAT32 ), /* 189 */ + new LogParam( "ShortTermValue", LogParamTypes.TYPE_FLOAT32 ), /* 190 */ + new LogParam( "IntegratedValue", LogParamTypes.TYPE_FLOAT32 ), /* 191 */ + new LogParam( "TotalBps", LogParamTypes.TYPE_FLOAT32 ), /* 192 */ + new LogParam( "num_cues", LogParamTypes.TYPE_INT32 ), /* 193 */ + new LogParam( "SoundFormat", LogParamTypes.TYPE_INT32 ), /* 194 */ + new LogParam( "CriAtomExAdpcmVoicePoolConfig_WIIU",LogParamTypes.TYPE_UINTPTR ), /* 195 */ + new LogParam( "AwbName", LogParamTypes.TYPE_CHAR ), /* 196 */ + new LogParam( "NumStreamAwb", LogParamTypes.TYPE_INT32 ), /* 197 */ + new LogParam( "ExPlayback_AllocateModule", LogParamTypes.TYPE_INT8 ), /* 198 */ + new LogParam( "AisacControlValue", LogParamTypes.TYPE_FLOAT32 ), /* 199 */ + new LogParam( "NumAllPlaybacksForReact", LogParamTypes.TYPE_INT16 ), /* 200 */ + new LogParam( "PreviewContext", LogParamTypes.TYPE_INT32 ), /* 201 */ + new LogParam( "max_parameter_blocks", LogParamTypes.TYPE_INT16 ), /* 202 */ + new LogParam( "max_faders", LogParamTypes.TYPE_INT16 ), /* 203 */ + new LogParam( "num_buses", LogParamTypes.TYPE_INT16 ), /* 204 */ + new LogParam( "max_racks", LogParamTypes.TYPE_INT16 ), /* 205 */ + new LogParam( "output_channels_4_hcamx", LogParamTypes.TYPE_INT8 ), /* 206 */ + new LogParam( "output_sampling_rate_4_hcamx", LogParamTypes.TYPE_INT32 ), /* 207 */ + new LogParam( "sound_renderer_type_4_hcamx", LogParamTypes.TYPE_INT8 ), /* 208 */ + new LogParam( "speaker_system", LogParamTypes.TYPE_INT8 ), /* 209 */ + new LogParam( "left_speaker_angle", LogParamTypes.TYPE_FLOAT32 ), /* 210 */ + new LogParam( "right_speaker_angle", LogParamTypes.TYPE_FLOAT32 ), /* 211 */ + new LogParam( "center_speaker_angle", LogParamTypes.TYPE_FLOAT32 ), /* 212 */ + new LogParam( "lfe_speaker_angle", LogParamTypes.TYPE_FLOAT32 ), /* 213 */ + new LogParam( "surround_left_speaker_angle", LogParamTypes.TYPE_FLOAT32 ), /* 214 */ + new LogParam( "surround_right_speaker_angle", LogParamTypes.TYPE_FLOAT32 ), /* 215 */ + new LogParam( "surround_back_left_speaker_angle",LogParamTypes.TYPE_FLOAT32 ), /* 216 */ + new LogParam( "surround_back_right_speaker_angle",LogParamTypes.TYPE_FLOAT32 ), /* 217 */ + new LogParam( "pan_speaker_type", LogParamTypes.TYPE_INT8 ), /* 218 */ + new LogParam( "VoiceStopReason", LogParamTypes.TYPE_INT16 ), /* 219 */ + new LogParam( "CriAtomExVibrationVoicePoolConfig",LogParamTypes.TYPE_UINTPTR ), /* 220 */ + new LogParam( "TouceSenceEffectName", LogParamTypes.TYPE_CHAR ), /* 221 */ + new LogParam( "dsp_name", LogParamTypes.TYPE_CHAR ), /* 222 */ + new LogParam( "dsp_object", LogParamTypes.TYPE_UINTPTR ), /* 223 */ + new LogParam( "dsp_slot_no", LogParamTypes.TYPE_INT32 ), /* 224 */ + new LogParam( "dsp_plugin_type", LogParamTypes.TYPE_INT32 ), /* 225 */ + new LogParam( "3dPosVector_ListenerTop", LogParamTypes.TYPE_VECTOR ), /* 226 */ + new LogParam( "playback_status", LogParamTypes.TYPE_INT32 ), /* 227 */ + new LogParam( "instrument_instance_callback", LogParamTypes.TYPE_UINTPTR ), /* 228 */ + new LogParam( "instrument_instance_callback_obj", LogParamTypes.TYPE_UINTPTR ), /* 229 */ + new LogParam( "instrument_instance_attach_player",LogParamTypes.TYPE_UINTPTR ), /* 230 */ + new LogParam( "instrument_instance", LogParamTypes.TYPE_UINTPTR ), /* 231 */ + new LogParam( "CriAtomEx3dTransceiverHn", LogParamTypes.TYPE_UINTPTR ), /* 232 */ + new LogParam( "CriAtomEx3dTransceiverConfig", LogParamTypes.TYPE_UINTPTR ), /* 233 */ + new LogParam( "CriAtomEx3dRegionHn", LogParamTypes.TYPE_UINTPTR ), /* 234 */ + new LogParam( "CriAtomEx3dTransceiverDirectAudioRadius", LogParamTypes.TYPE_FLOAT32 ), /* 235 */ + new LogParam( "CriAtomEx3dTransceiverCrossFadeDistance", LogParamTypes.TYPE_FLOAT32 ), /* 236 */ + new LogParam( "program_no", LogParamTypes.TYPE_INT32 ), /* 237 */ + new LogParam( "key_no", LogParamTypes.TYPE_INT32 ), /* 238 */ + new LogParam( "Velocity", LogParamTypes.TYPE_INT16 ), /* 239 */ + new LogParam( "PitchBend", LogParamTypes.TYPE_INT16 ), /* 240 */ + + new LogParam("Format", LogParamTypes.TYPE_INT32 ), /* 241 */ /* CriAtomFormat */ + new LogParam("MaxRhythmTracks", LogParamTypes.TYPE_INT16 ), /* 242 */ + new LogParam("MaxMelodyTracks", LogParamTypes.TYPE_INT16 ), /* 243 */ + new LogParam("MaxVocalTracks", LogParamTypes.TYPE_INT16 ), /* 244 */ + new LogParam("AdmPlayerHn", LogParamTypes.TYPE_UINTPTR ), /* 245 */ + }; + + protected const uint LOG_MODE_OFF = 0; + protected const uint LOG_MODE_PLAYBACK = 1; + protected const uint LOG_MODE_ERROR = 1 << 1; + protected const uint LOG_MODE_LOW_LEVEL_PLAYBACK = 1 << 2; + protected const uint LOG_MODE_SYSTEM_INFO = 1 << 3; + protected const uint LOG_MODE_HANDLE_INFO = 1 << 4; + protected const uint LOG_MODE_CUE_LIMIT = 1 << 5; + protected const uint LOG_MODE_PROBABILITY = 1 << 6; + protected const uint LOG_MODE_CATEGORY = 1 << 7; + protected const uint LOG_MODE_EXECUTING_INFORMATION = 1 << 8; + protected const uint LOG_MODE_3D_INFO = 1 << 9; + protected const uint LOG_MODE_USER_LOG = 1 << 10; + protected const uint LOG_MODE_VOICE_VOLUME = 1 << 11; + protected const uint LOG_MODE_ALL = 0xFFFFFFFF; + + protected enum LogTypes { + NON = 0, + PLAYBACK, + ERROR, + LOW_LEVEL_PLAYBACK, + SYSTEM_INFORMATION, + HANDLE_INFORMATION, + CUE_LIMIT, + PROBABILITY, + CATEGORY, + EXECUTING_INFORMATION, + INFORMATION_3D, + USER_LOG, + VOICE_VOLUME + }; + + protected const uint FORMAT_NONE = 0; + protected const uint FORMAT_ADX = 1 << 0; + protected const uint FORMAT_HCA = 1 << 2; + protected const uint FORMAT_HCA_MX = 1 << 3; + protected const uint FORMAT_PCM = 1 << 4; + protected const uint FORMAT_WAVE = 1 << 5; + protected const uint FORMAT_RAW_PCM = 1 << 6; + protected const uint FORMAT_AIFF = 1 << 7; + protected const uint FORMAT_VIBRATION = 1 << 8; + protected const uint FORMAT_AUDIO_BUFFER = 1 << 9; + protected const uint FORMAT_SOUND_GENERATOR = 1 << 10; + protected const uint FORMAT_RAW_PCM_FLOAT = 1 << 11; + protected const uint FORMAT_HW1 = 1 << 16; + protected const uint FORMAT_HW2 = 1 << 17; + /* aliases */ + protected const uint FORMAT_XMA = FORMAT_HW1; + protected const uint FORMAT_NDS_ADPCM = FORMAT_HW1; + protected const uint FORMAT_WII_ADPCM = FORMAT_HW1; + protected const uint FORMAT_WIIU_ADPCM = FORMAT_HW1; + protected const uint FORMAT_3DS_ADPCM = FORMAT_HW1; + protected const uint FORMAT_VAG = FORMAT_HW1; + protected const uint FORMAT_ATRAC3 = FORMAT_HW2; + protected const uint FORMAT_PSP2_HEVAG = FORMAT_HW1; + protected const uint FORMAT_ATRAC9 = FORMAT_HW2; + + protected enum StreamTypes { + UNKNOWN = 0, + ONMEMORY, + STREAM, + ZERO_LATENCY_STREAM, + } +} + +} //namespace CriWare + +#endif \ No newline at end of file diff --git a/Assets/Scripts/CRIMW/CriWare/Editor/CriProfilerConfig.cs.meta b/Assets/Scripts/CRIMW/CriWare/Editor/CriProfilerConfig.cs.meta new file mode 100644 index 0000000..706de6a --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Editor/CriProfilerConfig.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 9b5c9ddcfce383b46a04326d92d43c4f +timeCreated: 1513761507 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Editor/CriProfilerEditor.cs b/Assets/Scripts/CRIMW/CriWare/Editor/CriProfilerEditor.cs new file mode 100644 index 0000000..f0c0b2e --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Editor/CriProfilerEditor.cs @@ -0,0 +1,1293 @@ +/**************************************************************************** + * + * Copyright (c) 2018 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +using System; +using System.Text; +using System.Collections.Generic; +using UnityEngine; +using UnityEditor; + +namespace CriWare { + +[Serializable] +public sealed class CriProfilerEditor : EditorWindow +{ + private static CriProfiler profiler = CriProfiler.GetSingleton(); + + #region Unity Event Callbacks + + [MenuItem ("Window/CRIWARE/CRI Profiler")] + static void InitWindow() { + CriProfilerEditor window = (CriProfilerEditor)EditorWindow.GetWindow(typeof(CriProfilerEditor)); +#if UNITY_5_2 || UNITY_5_3 || UNITY_5_4_OR_NEWER + window.titleContent = new GUIContent("CRI Profiler"); +#else + window.title = "CRI Profiler"; +#endif + window.Show(); + } + + private struct PlaymodeState { + public readonly bool isPlaying; + public readonly bool isPaused; + public readonly bool isPlayingOrWillChangePlaymode; + public PlaymodeState(bool isPlaying, bool isPaused, bool isPlayingOrWillChangePlaymode) { + this.isPlaying = isPlaying; + this.isPaused = isPaused; + this.isPlayingOrWillChangePlaymode = isPlayingOrWillChangePlaymode; + } + } + private PlaymodeState prevPlaymodeState = new PlaymodeState(false, false, false); + + private void OnStateChanged() { + if (EditorApplication.isPlayingOrWillChangePlaymode == false) { + profiler.StopProfiling(); + } else if (startWithUnityPlayer == true && EditorApplication.isPlaying == true && prevPlaymodeState.isPlaying == false) { + this.remoteProfiling = false; + profiler.ipAddressString = DEFAULT_IP_ADDR; + profiler.StartProfiling(saveLogFile, logFileDir); + } + if (this.pauseWithUnityPlayer == true) { + this.isWindowPaused = EditorApplication.isPaused; + } + prevPlaymodeState = new PlaymodeState(EditorApplication.isPlaying, EditorApplication.isPaused, EditorApplication.isPlayingOrWillChangePlaymode); + } + +#if UNITY_2017_2_OR_NEWER + private void OnPlayModeStateChanged(PlayModeStateChange state) { + OnStateChanged(); + } + private void OnPauseStateChanged(PauseState state) { + OnStateChanged(); + } +#endif + + private void OnEnable() { +#if UNITY_2017_2_OR_NEWER + UnityEditor.EditorApplication.playModeStateChanged += OnPlayModeStateChanged; + UnityEditor.EditorApplication.pauseStateChanged += OnPauseStateChanged; +#else + UnityEditor.EditorApplication.playmodeStateChanged += OnStateChanged; +#endif + } + + private void OnDisable() { + if (profiler != null) { + profiler.StopProfiling(); + } + DestroyResources(); + +#if UNITY_2017_2_OR_NEWER + UnityEditor.EditorApplication.playModeStateChanged -= OnPlayModeStateChanged; + UnityEditor.EditorApplication.pauseStateChanged -= OnPauseStateChanged; +#else + UnityEditor.EditorApplication.playmodeStateChanged -= OnStateChanged; +#endif + } + + #endregion Unity Event Callbacks + + #region Data Slice Definition + + private struct DataSlicePerformance { + public readonly Single cpuLoad; + public readonly Single[] cpuLoadHistory; + public readonly UInt32 maxVoices; + public readonly UInt32 usedVoices; + public readonly UInt32[] voiceUsageHistory; + public readonly UInt32 maxStandardVoices; + public readonly int usedStandardVoices; + public readonly UInt32 maxHcaMxVoices; + public readonly int usedHcaMxVoices; + public readonly UInt32 usedStreams; + public readonly Single totalBps; + public DataSlicePerformance(CriProfiler profiler) { + this.cpuLoad = profiler.cpu_load; + this.cpuLoadHistory = profiler.CpuLoadHistory; + this.maxVoices = + profiler.maxVoice_stdStreaming + + profiler.maxVoice_hcamxStreaming + + profiler.maxVoice_stdOnMemory + + profiler.maxVoice_hcamxOnMemory; + this.usedVoices = profiler.num_used_voices; + this.voiceUsageHistory = profiler.VoiceUsageHistory; + this.maxStandardVoices = profiler.maxVoice_stdOnMemory + profiler.maxVoice_stdStreaming; + this.usedStandardVoices = profiler.GetVoicePoolUsage(CriProfiler.VoicePoolFormat.Standard); + this.maxHcaMxVoices = profiler.maxVoice_hcamxOnMemory + profiler.maxVoice_hcamxStreaming; + this.usedHcaMxVoices = profiler.GetVoicePoolUsage(CriProfiler.VoicePoolFormat.HcaMx); + this.usedStreams = profiler.num_used_streams; + this.totalBps = profiler.total_bps; + } + } + + private struct DataSlicePlayback { + public readonly CriProfiler.PlaybackInfo[] playbackList; + public readonly StringBuilder playbackListString; + public readonly string cuenameLastPlayed; + public DataSlicePlayback(CriProfiler profiler) { + this.playbackList = profiler.PlaybackList; + this.playbackListString = new StringBuilder(); + for (int i = 0; i < playbackList.Length; ++i) { + playbackListString.Append(playbackList[i].cueName + " "); + } + this.cuenameLastPlayed = string.IsNullOrEmpty(profiler.cuename_lastPlayed) ? "---" : profiler.cuename_lastPlayed + " (" + profiler.cuesheetName_lastPlayed + ")"; + } + } + private struct DataSliceLoudness { + public readonly Single momentary; + public readonly Single shortTerm; + public readonly Single integrated; + public DataSliceLoudness(CriProfiler profiler) { + this.momentary = profiler.loudness_momentary; + this.shortTerm = profiler.loudness_shortTerm; + this.integrated = profiler.loudness_integrated; + } + } + private struct DataSliceLevels { + public readonly CriProfiler.LevelInfo[] levels; + public readonly int outputCh; + public DataSliceLevels(CriProfiler profiler) { + this.levels = profiler.LevelsAllCh; + this.outputCh = profiler.numChMasterOut; + } + } + + private struct DataSliceLocalRuntime { + public readonly uint memUsageAtom; + public readonly uint memUsageFs; + public DataSliceLocalRuntime(bool isPlaying) { + if (isPlaying == true) { + memUsageAtom = CriAtomPlugin.IsLibraryInitialized() ? CriWare.Common.GetAtomMemoryUsage() : 0; + memUsageFs = CriFsPlugin.IsLibraryInitialized() ? CriWare.Common.GetFsMemoryUsage() : 0; + } else { + memUsageAtom = 0; + memUsageFs = 0; + } + } + } + + #endregion Data Slice Definition + + #region Internal Fields + + /* configurations */ + private const Single DB_MIN = -96.0f; + private const Single DB_MAX = 20.0f; + private const Single DEFAULT_DB_FLOOR = -48.0f; + private const Single DEFAULT_DB_CEILING = 0; + private const Single DEFAULT_DB_TARGET = -24.0f; + private const Single DB_RANGE_PLUSMINUS_MAX = 20.0f; + private const Single DB_RANGE_PLUSMINUS_MIN = 0; + private const Single DEFAULT_DB_RANGE_PLUSMINUS = 2.0f; + private const Single DEFAULT_DB_WARNING = -6.0f; + private const Single DEFAULT_LEVEL_FLOOR = -48.0f; + private const Single DEFAULT_LEVEL_CEILING = 0; + private const Single DEFAULT_LEVEL_WARNING = -6.0f; + private const int DEFAULT_LEVEL_CAL_INTVL = 6; + private const int DEFAULT_LEVEL_CAL_INTVL_MIN = 1; + private const int DEFAULT_LEVEL_CAL_INTVL_MAX = 24; + private const MultiChannelMeterType DEFAULT_LEVEL_TYPE = MultiChannelMeterType.Peak; + private const string DEFAULT_IP_ADDR = "127.0.0.1"; + [SerializeField] private bool startWithUnityPlayer = true; + [SerializeField] private bool pauseWithUnityPlayer = true; + [SerializeField] private bool saveLogFile = false; + [SerializeField] private string logFileDir = ""; + [SerializeField] private bool remoteProfiling = false; + [SerializeField] private bool isWindowPaused = false; + [SerializeField] private Single currentDbFloor = DEFAULT_DB_FLOOR; + [SerializeField] private Single currentDbCeiling = DEFAULT_DB_CEILING; + [SerializeField] private Single currentDbTarget = DEFAULT_DB_TARGET; + [SerializeField] private Single currentDbRangePlusMinus = DEFAULT_DB_RANGE_PLUSMINUS; + [SerializeField] private Single currentDbWarning = DEFAULT_DB_WARNING; + [SerializeField] private Single currentLevelFloor = DEFAULT_LEVEL_FLOOR; + [SerializeField] private Single currentLevelCeiling = DEFAULT_LEVEL_CEILING; + [SerializeField] private Single currentLevelWarning = DEFAULT_LEVEL_WARNING; + [SerializeField] private int currentLevelCalInterval = DEFAULT_LEVEL_CAL_INTVL; + [SerializeField] private MultiChannelMeterType currentLevelType = DEFAULT_LEVEL_TYPE; + + /* GUI constants */ + private const float LABEL_WIDTH = 148.0f; + private const float CHART_INDENT_WIDTH = 15.0f; + private const float GUI_INDENT_WIDTH = 15.0f; + private const int TEXT_SIZE_CALIBRATOR = 10; + private const int TEXT_SIZE_LABEL = 11; + private const int TEXT_SIZE_CUE_LIST = 12; + private const int TEXT_SIZE_GIANT = 20; + private const int LOG_ITEM_HEIGHT = 20; + static private Vector2 textOffsetChartTitle = new Vector2(3.0f, 2.0f); + static private Vector2 textOffsetCalibrator = new Vector2(-4.0f, -6.0f); + static private Color colorWarningHigh = new Color(224 / 255.0f, 44 / 255.0f, 44 / 255.0f); + static private Color colorWarningHighTolerant = new Color(244 / 255.0f, 170 / 255.0f, 44 / 255.0f); + static private Color colorMidRange = new Color(107 / 255.0f, 224 / 255.0f, 44 / 255.0f); + static private Color colorWarningLow = new Color(44 / 255.0f, 107 / 255.0f, 224 / 255.0f); + static private Color colorGrid = new Color(0.2f, 0.2f, 0.2f); + private const int CNT_CUSTOM_STYLES = 20; + static private GUIStyle[] customStyles = new GUIStyle[CNT_CUSTOM_STYLES]; + static private Texture2D[] customStyleTex = new Texture2D[CNT_CUSTOM_STYLES]; + private GUIStyle barBorderStyle { get { return InitializeStyleWithBgColor(0, Color.gray); } } + private GUIStyle barBackgroundStyle { get { return InitializeStyleWithBgColor(1, Color.black); } } + private GUIStyle barStyle { get { return InitializeStyleWithBgColor(2, Color.gray); } } + private GUIStyle barWarningHighStyle { get { return InitializeStyleWithBgColor(3, colorWarningHigh); } } + private GUIStyle barWarningHighTolerantStyle { get { return InitializeStyleWithBgColor(4, colorWarningHighTolerant); } } + private GUIStyle barMidRangeStyle { get { return InitializeStyleWithBgColor(5, colorMidRange); } } + private GUIStyle barWarningLowStyle { get { return InitializeStyleWithBgColor(6, colorWarningLow); } } + private GUIStyle barTextStyle { get { return InitializeTextStyle(7, TEXT_SIZE_LABEL, Color.white, TextAnchor.UpperLeft); } } + private GUIStyle barTextShadowStyle { get { return InitializeTextStyle(8, TEXT_SIZE_LABEL, Color.black, TextAnchor.UpperLeft); } } + private GUIStyle meterTextWarningHighStyle { get { return InitializeTextStyle(9, TEXT_SIZE_GIANT, colorWarningHigh, TextAnchor.MiddleCenter); } } + private GUIStyle meterTextWarningHighTolerantStyle { get { return InitializeTextStyle(10, TEXT_SIZE_GIANT, colorWarningHighTolerant, TextAnchor.MiddleCenter); } } + private GUIStyle meterTextMidRangeStyle { get { return InitializeTextStyle(11, TEXT_SIZE_GIANT, colorMidRange, TextAnchor.MiddleCenter); } } + private GUIStyle meterTextWarningLowStyle { get { return InitializeTextStyle(12, TEXT_SIZE_GIANT, colorWarningLow, TextAnchor.MiddleCenter); } } + private GUIStyle multiChMeterTextStyle { get { return InitializeTextStyle(13, TEXT_SIZE_LABEL, Color.white, TextAnchor.MiddleCenter); } } + private GUIStyle cueListStyle { get { return InitializeTextStyle(14, TEXT_SIZE_CUE_LIST, Color.white, TextAnchor.UpperLeft, s => { + s.fontStyle = FontStyle.Bold; + s.wordWrap = true; + }); } } + private GUIStyle chartLabelStyle { get { return InitializeTextStyle(15, TEXT_SIZE_CALIBRATOR, Color.gray, TextAnchor.UpperRight); } } + private GUIStyle timelineHeaderStyle { get { return InitializeStyleWithBgColor(16, new Color(0.15f, 0.15f, 0.15f)); } } + private GUIStyle timelineStyle { get { return InitializeStyleWithBgColor(17, new Color(0.1f, 0.1f, 0.1f)); } } + private GUIStyle timelineButtonStyle { get { return InitializeStyleWithGradColor(18, new Color(0.8f, 0.8f, 0.8f), new Color(0.7f, 0.7f, 0.7f), s => { + s.fixedHeight = 18; + s.alignment = TextAnchor.MiddleCenter; + s.clipping = TextClipping.Clip; + s.margin = new RectOffset(1, 1, 1, 1); + s.padding = new RectOffset(1, 1, 1, 1); + }); } } + private GUIStyle timelineCueSheetStyle { get { return InitializeStyleWithGradColor(19, new Color(0.4f, 0.4f, 0.4f), new Color(0.3f, 0.3f, 0.3f), s => { + s.alignment = TextAnchor.MiddleCenter; + s.clipping = TextClipping.Clip; + s.fontStyle = FontStyle.Bold; + s.normal.textColor = Color.white; + s.margin = new RectOffset(1, 1, 1, 1); + s.padding = new RectOffset(1, 1, 1, 1); + }); } } + private delegate void AdditionalStyleDelegate(GUIStyle style); + static private Color[] chartGradientColors = new Color[] { + Color.green, + Color.green * 0.8f + Color.yellow * 0.2f, + Color.green * 0.6f + Color.yellow * 0.4f, + Color.green * 0.4f + Color.yellow * 0.6f, + Color.green * 0.2f + Color.yellow * 0.8f, + Color.yellow, + Color.yellow * 0.8f + Color.red * 0.2f, + Color.yellow * 0.6f + Color.red * 0.4f, + Color.yellow * 0.4f + Color.red * 0.6f, + Color.yellow * 0.2f + Color.red * 0.8f, + Color.red + }; + + /* GUI variables */ + [SerializeField] private bool foldTogglerConfig = false; + [SerializeField] private bool foldTogglerExperimental = false; + [SerializeField] private bool foldTogglerPerformance = true; + [SerializeField] private bool foldTogglerPlayingList = true; + [SerializeField] private bool foldTogglerLoudness = true; + [SerializeField] private bool foldTogglerLoudnessAppearance = false; + [SerializeField] private bool foldTogglerLevels = true; + [SerializeField] private bool foldTogglerLevelAppearance = false; + [SerializeField] private bool foldTogglerTimeline = true; + [SerializeField] private bool foldTogglerLogList = true; + [SerializeField] private bool timelineAutoScroll = true; + private Vector2 monitorPanelScrollPos; + private Vector2 timelinePanelScrollPos; + private Vector2 logListPanelScrollPos; + private Vector2 logListScrollPos; + private Vector2 textareaScrollViewPostion; + private int logItemCount = 0; + private bool isLogItemCountChanged = false; + private int logViewCount = 0; + private int logFirstViewIndex = 0; + private bool refreshLogListOnce = false; + private List logViewSubList = null; + private Color currentGuiColor; + private Rect timelineWinRect; + private Shader m_shader; + private Material m_mat; + private Material mat { + get { + if (m_shader == null) { +#if UNITY_5_2 || UNITY_5_3 || UNITY_5_4_OR_NEWER + m_shader = Shader.Find("Hidden/Internal-Colored"); +#else + m_shader = Shader.Find("Sprites/Default"); +#endif + } + if (m_mat == null && m_shader != null) { + m_mat = new Material(m_shader); + } else if (m_mat.shader != m_shader) { + DestroyImmediate(m_mat); + m_mat = new Material(m_shader); + } + return m_mat; + } + } + private StringBuilder gStrBuilder = new StringBuilder(50); + private StringBuilder gStrBuilderSub = new StringBuilder(50); + + /* Data slices */ + private DataSlicePerformance perfData = new DataSlicePerformance(profiler); + private DataSlicePlayback playbackData = new DataSlicePlayback(profiler); + private DataSliceLoudness loudnessData = new DataSliceLoudness(profiler); + private DataSliceLevels levelsData = new DataSliceLevels(profiler); + private DataSliceLocalRuntime runtimeData = new DataSliceLocalRuntime(false); + private Dictionary timeline = null; + private ulong firstTimeStamp = 0; + private ulong currentTimeStamp = 0; + private CriProfiler.Playback? currentTimelinePlayback = null; + + private GUIStyle InitializeStyleWithBgColor(int id, Color color, AdditionalStyleDelegate func = null) { + if (customStyleTex[id] == null) { + customStyleTex[id] = new Texture2D(1, 1, TextureFormat.RGB24, false); + customStyleTex[id].SetPixel(1, 1, color); + customStyleTex[id].Apply(); + } + if (customStyles[id] == null) { + customStyles[id] = new GUIStyle(); + if (func != null) { + func(customStyles[id]); + } + } + customStyles[id].normal.background = customStyleTex[id]; + return customStyles[id]; + } + + private GUIStyle InitializeStyleWithGradColor(int id, Color color1, Color color2, AdditionalStyleDelegate func = null) { + if (customStyleTex[id] == null) { + customStyleTex[id] = new Texture2D(1, 4, TextureFormat.RGB24, false); + customStyleTex[id].SetPixel(1, 1, color2); + customStyleTex[id].SetPixel(1, 2, color1); + customStyleTex[id].SetPixel(1, 3, color1); + customStyleTex[id].SetPixel(1, 4, color2); + customStyleTex[id].Apply(); + } + if (customStyles[id] == null) { + customStyles[id] = new GUIStyle(); + if (func != null) { + func(customStyles[id]); + } + } + customStyles[id].normal.background = customStyleTex[id]; + return customStyles[id]; + } + + private GUIStyle InitializeTextStyle(int id, int size, Color color, TextAnchor anchor, AdditionalStyleDelegate func = null) { + if (customStyles[id] == null) { + customStyles[id] = new GUIStyle(); + customStyles[id].normal.textColor = color; + customStyles[id].fontSize = size; + customStyles[id].alignment = anchor; + if (func != null) { + func(customStyles[id]); + } + } + return customStyles[id]; + } + + private void DestroyResources() { + if (m_mat != null) { + DestroyImmediate(m_mat); + } + } + + #endregion Internal Fields + + #region Const strings on GUI + private const string S_DIVIDER = " / "; + private const string S_NAN = "-"; + private readonly GUIContent S_LOGFILEDIR = new GUIContent("Log file directory", "leave empty to use default location"); + private readonly GUIContent GC_LEVELRANGE = new GUIContent("Disp. Range (dB)"); + private readonly string[] S_MultiChMeterButton = { "Peak", "RMS" }; + private readonly string[] S_ChannelNames = { "L", "R", "C", "LFE", "Ls", "Rs", "Ex1", "Ex2" }; + #endregion Const strings on GUI + + #region OnGUI + + private void OnGUI() { + GUILayoutOption buttonHeightSetting = GUILayout.Height(25); + this.currentGuiColor = GUI.color; + + using (var globalHorizontal = new GUILayout.HorizontalScope()) { + using (var leftPaneVertical = new GUILayout.VerticalScope(GUILayout.Width(430))) { + GUILayout.Space(5.0f); + using (var startControlHorizontal = new GUILayout.HorizontalScope()) { + GUI.enabled = EditorApplication.isPlaying || remoteProfiling; + if (profiler.IsProfiling == false) { + if (GUILayout.Button("Start", buttonHeightSetting)) { + profiler.StartProfiling(saveLogFile, logFileDir); + this.isWindowPaused = false; + } + } else { + if (GUILayout.Button("Stop", buttonHeightSetting)) { + profiler.StopProfiling(); + } + } + GUI.enabled = profiler.IsProfiling; + if (this.isWindowPaused == false) { + if (GUILayout.Button("Pause", buttonHeightSetting)) { + this.isWindowPaused = true; + } + } else { + if (GUILayout.Button("Resume", buttonHeightSetting)) { + this.isWindowPaused = false; + } + } + GUI.enabled = true; + } + using (var monitorScrollView = new GUILayout.ScrollViewScope(monitorPanelScrollPos)) { + monitorPanelScrollPos = monitorScrollView.scrollPosition; + + DrawConfigurationInfo(); + + GUILayout.Label("Monitoring", EditorStyles.whiteBoldLabel); + + DrawrPerformanceInfo(); + DrawrPlaybackInfo(); + DrawLoudnessInfo(); + DrawLevelsInfo(); + + GUILayout.Space(20.0f); + } + } + + using (var rightPaneVertical = new GUILayout.VerticalScope()) { + DrawTimeline(); + DrawLogList(); + } + } + + this.Repaint(); + } + + private void DrawConfigurationInfo() { + EditorGUILayout.BeginVertical(EditorStyles.helpBox); + foldTogglerConfig = CriFoldout(foldTogglerConfig, "Configuration"); + if (foldTogglerConfig) { + EditorGUI.indentLevel++; + startWithUnityPlayer = EditorGUILayout.Toggle("Start with Player", startWithUnityPlayer); + pauseWithUnityPlayer = EditorGUILayout.Toggle("Pause with Player", pauseWithUnityPlayer); + saveLogFile = EditorGUILayout.Toggle("Save log file", saveLogFile); + GUI.enabled = saveLogFile; + EditorGUI.indentLevel++; + logFileDir = EditorGUILayout.TextField(S_LOGFILEDIR, profiler.LogFileSavePath); + EditorGUI.indentLevel--; + GUI.enabled = true; + foldTogglerExperimental = CriFoldout(foldTogglerExperimental, "Experimental"); + if (foldTogglerExperimental) { + EditorGUI.indentLevel++; + GUI.enabled = (profiler.IsProfiling == false); + remoteProfiling = EditorGUILayout.Toggle("Remote Profiling", remoteProfiling); + if (remoteProfiling == false) { + profiler.ipAddressString = DEFAULT_IP_ADDR; + } + GUI.enabled = remoteProfiling && (profiler.IsProfiling == false); + profiler.ipAddressString = EditorGUILayout.TextField("IP Address", profiler.ipAddressString); + GUI.enabled = true; + EditorGUI.indentLevel--; + } + EditorGUI.indentLevel--; + } + EditorGUILayout.EndVertical(); + } + + private void DrawrPerformanceInfo() { + EditorGUILayout.BeginVertical(EditorStyles.helpBox); + foldTogglerPerformance = CriFoldout(foldTogglerPerformance, "Performance"); + if (foldTogglerPerformance) { + if (isWindowPaused == false) { + perfData = new DataSlicePerformance(profiler); + if (this.remoteProfiling == false) { + runtimeData = new DataSliceLocalRuntime(EditorApplication.isPlaying); + } + } + EditorGUI.indentLevel++; + Rect chartRect = EditorGUILayout.GetControlRect(GUILayout.Height(80)); + chartRect.xMin += CHART_INDENT_WIDTH; + LineGraph(chartRect, ClearedStr.Append("CPU Usage: ").AppendFormat("{0:F2}", perfData.cpuLoad).Append("%").ToString(), perfData.cpuLoadHistory, 100.0f, 5, 5.0f, true); + chartRect = EditorGUILayout.GetControlRect(GUILayout.Height(80)); + chartRect.xMin += CHART_INDENT_WIDTH; + LineGraph(chartRect, ClearedStr.Append("Number of Voices: ").Append(perfData.usedVoices).Append(S_DIVIDER).Append(perfData.maxVoices).ToString(), Array.ConvertAll(perfData.voiceUsageHistory, x => (float)x), perfData.maxVoices, 5, 4.0f, false); + GUILayout.BeginHorizontal(); + { + EditorGUILayout.LabelField("Standard Pool Usage", GUILayout.Width(LABEL_WIDTH)); + SimpleBarGraph(EditorGUILayout.GetControlRect(), perfData.usedStandardVoices, 0, perfData.maxStandardVoices, + ClearedStr.Append(perfData.usedStandardVoices >= 0 ? perfData.usedStandardVoices.ToString() : S_NAN) + .Append(S_DIVIDER) + .Append(perfData.maxStandardVoices > 0 ? perfData.maxStandardVoices.ToString() : S_NAN) + .ToString()); + } + GUILayout.EndHorizontal(); + GUILayout.BeginHorizontal(); + { + EditorGUILayout.LabelField("HCA-MX Pool Usage", GUILayout.Width(LABEL_WIDTH)); + SimpleBarGraph(EditorGUILayout.GetControlRect(), perfData.usedHcaMxVoices, 0, perfData.maxHcaMxVoices, + ClearedStr.Append(perfData.usedHcaMxVoices >= 0 ? perfData.usedHcaMxVoices.ToString() : S_NAN) + .Append(S_DIVIDER) + .Append(perfData.maxHcaMxVoices > 0 ? perfData.maxHcaMxVoices.ToString() : S_NAN) + .ToString()); + } + GUILayout.EndHorizontal(); + if (this.remoteProfiling == false) { + EditorGUILayout.LabelField("Atom Memory Usage", DataSize2String(runtimeData.memUsageAtom)); + EditorGUILayout.LabelField("FS Memory Usage", DataSize2String(runtimeData.memUsageFs)); + } + EditorGUILayout.LabelField("Streaming Usage", ClearedStr.Append(perfData.usedStreams).Append(" voice(s) (").AppendFormat("{0:F2}", perfData.totalBps / 1000000).Append(" Mbps)").ToString()); + EditorGUI.indentLevel--; + } + EditorGUILayout.EndVertical(); + } + + private void DrawrPlaybackInfo() { + EditorGUILayout.BeginVertical(EditorStyles.helpBox); + foldTogglerPlayingList = CriFoldout(foldTogglerPlayingList, "Playing"); + if (foldTogglerPlayingList) { + if (isWindowPaused == false) { + playbackData = new DataSlicePlayback(profiler); + } + GUILayout.BeginHorizontal(); + { + GUILayout.Space(GUI_INDENT_WIDTH); + textareaScrollViewPostion = GUILayout.BeginScrollView(new Vector2(textareaScrollViewPostion.x, Mathf.Infinity), EditorStyles.helpBox, GUILayout.Height(60)); + GUILayout.Label(playbackData.playbackListString.ToString(), cueListStyle, GUILayout.ExpandHeight(true)); + GUILayout.EndScrollView(); + } + GUILayout.EndHorizontal(); + EditorGUI.indentLevel++; + EditorGUILayout.LabelField("Last Played", ClearedStr.Append("[ ").Append(playbackData.cuenameLastPlayed).Append(" ]").ToString()); + EditorGUI.indentLevel--; + } + EditorGUILayout.EndVertical(); + } + + private void DrawLoudnessInfo() { + EditorGUILayout.BeginVertical(EditorStyles.helpBox); + foldTogglerLoudness = CriFoldout(foldTogglerLoudness, "Loudness"); + if (foldTogglerLoudness) { + if (isWindowPaused == false) { + loudnessData = new DataSliceLoudness(profiler); + } + Rect chartRect; + GUILayoutOption[] numberRectGUISettings = { GUILayout.Height(60), GUILayout.MinWidth(60) }; + GUILayoutOption barHeightSetting = GUILayout.Height(15); + const float paddingOffset = 2.0f; + GUILayout.BeginHorizontal(); + { + chartRect = EditorGUILayout.GetControlRect(numberRectGUISettings); + chartRect.x += CHART_INDENT_WIDTH; + NumericMeter(chartRect, "Momentary LKFS", loudnessData.momentary); + chartRect = EditorGUILayout.GetControlRect(numberRectGUISettings); + chartRect.x += CHART_INDENT_WIDTH - paddingOffset; + NumericMeter(chartRect, "Short Term LKFS", loudnessData.shortTerm); + chartRect = EditorGUILayout.GetControlRect(numberRectGUISettings); + chartRect.xMin += CHART_INDENT_WIDTH - paddingOffset * 2; + NumericMeter(chartRect, "Integrated LKFS", loudnessData.integrated); + } + GUILayout.EndHorizontal(); + chartRect = EditorGUILayout.GetControlRect(barHeightSetting); + chartRect.xMin += CHART_INDENT_WIDTH; + LoudnessBarGraph(chartRect, loudnessData.momentary, currentDbFloor, currentDbCeiling, currentDbTarget, currentDbRangePlusMinus, currentDbWarning, "Momentary"); + chartRect = EditorGUILayout.GetControlRect(barHeightSetting); + chartRect.xMin += CHART_INDENT_WIDTH; + LoudnessBarGraph(chartRect, loudnessData.shortTerm, currentDbFloor, currentDbCeiling, currentDbTarget, currentDbRangePlusMinus, currentDbWarning, "Short Term"); + chartRect = EditorGUILayout.GetControlRect(barHeightSetting); + chartRect.xMin += CHART_INDENT_WIDTH; + LoudnessBarGraph(chartRect, loudnessData.integrated, currentDbFloor, currentDbCeiling, currentDbTarget, currentDbRangePlusMinus, currentDbWarning, "Integrated"); + EditorGUI.indentLevel++; + foldTogglerLoudnessAppearance = CriFoldout(foldTogglerLoudnessAppearance, "Appearance"); + if (foldTogglerLoudnessAppearance) { + EditorGUI.indentLevel++; + EditorGUILayout.MinMaxSlider(GC_LEVELRANGE, ref currentDbFloor, ref currentDbCeiling, DB_MIN, DB_MAX); + EditorGUILayout.LabelField(" ", ClearedStr.Append("Min: ").AppendFormat("{0:F2}", currentDbFloor).Append(S_DIVIDER).Append("Max: ").AppendFormat("{0:F2}", currentDbCeiling).ToString()); + currentDbTarget = EditorGUILayout.Slider("Target (dB)", currentDbTarget, DB_MIN, DB_MAX); + currentDbRangePlusMinus = EditorGUILayout.Slider("Tgt. Range (+/-dB)", currentDbRangePlusMinus, DB_RANGE_PLUSMINUS_MIN, DB_RANGE_PLUSMINUS_MAX); + currentDbWarning = EditorGUILayout.Slider("Warning (dB)", currentDbWarning, DB_MIN, DB_MAX); + GUILayout.BeginHorizontal(); + { + EditorGUILayout.LabelField("", GUILayout.Width(LABEL_WIDTH)); + if (GUILayout.Button("Reset", GUILayout.ExpandWidth(false))) { + currentDbFloor = DEFAULT_DB_FLOOR; + currentDbCeiling = DEFAULT_DB_CEILING; + currentDbTarget = DEFAULT_DB_TARGET; + currentDbRangePlusMinus = DEFAULT_DB_RANGE_PLUSMINUS; + currentDbWarning = DEFAULT_DB_WARNING; + } + } + GUILayout.EndHorizontal(); + EditorGUI.indentLevel--; + } + EditorGUI.indentLevel--; + } + EditorGUILayout.EndVertical(); + } + + private void DrawLevelsInfo() { + EditorGUILayout.BeginVertical(EditorStyles.helpBox); + foldTogglerLevels = CriFoldout(foldTogglerLevels, "Peak / RMS"); + if (foldTogglerLevels) { + if (isWindowPaused == false) { + levelsData = new DataSliceLevels(profiler); + } + GUILayout.BeginHorizontal(); + { + GUILayout.Space(GUI_INDENT_WIDTH); + currentLevelType = (MultiChannelMeterType)GUILayout.Toolbar((int)currentLevelType, S_MultiChMeterButton); + } + GUILayout.EndHorizontal(); + Rect chartRect = EditorGUILayout.GetControlRect(GUILayout.Height(200)); + chartRect.xMin += CHART_INDENT_WIDTH; + MultiChannelMeter(chartRect, levelsData.levels, levelsData.outputCh, currentLevelType, currentLevelFloor, currentLevelCeiling, currentLevelWarning, S_MultiChMeterButton[(int)currentLevelType]); + EditorGUI.indentLevel++; + foldTogglerLevelAppearance = CriFoldout(foldTogglerLevelAppearance, "Appearance"); + if (foldTogglerLevelAppearance) { + EditorGUI.indentLevel++; + EditorGUILayout.MinMaxSlider(GC_LEVELRANGE, ref currentLevelFloor, ref currentLevelCeiling, DB_MIN, DB_MAX); + EditorGUILayout.LabelField(" ", ClearedStr.Append("Min: ").AppendFormat("{0:F2}", currentLevelFloor).Append(S_DIVIDER).Append("Max: ").AppendFormat("{0:F2}", currentLevelCeiling).ToString()); + currentLevelWarning = EditorGUILayout.Slider("Warning (dB)", currentLevelWarning, DB_MIN, DB_MAX); + currentLevelCalInterval = EditorGUILayout.IntSlider("Grid Interval (dB)", currentLevelCalInterval, DEFAULT_LEVEL_CAL_INTVL_MIN, DEFAULT_LEVEL_CAL_INTVL_MAX); + GUILayout.BeginHorizontal(); + { + EditorGUILayout.LabelField("", GUILayout.Width(LABEL_WIDTH)); + if (GUILayout.Button("Reset", GUILayout.ExpandWidth(false))) { + currentLevelFloor = DEFAULT_LEVEL_FLOOR; + currentLevelCeiling = DEFAULT_LEVEL_CEILING; + currentLevelWarning = DEFAULT_LEVEL_WARNING; + currentLevelCalInterval = DEFAULT_LEVEL_CAL_INTVL; + } + } + GUILayout.EndHorizontal(); + EditorGUI.indentLevel--; + } + EditorGUI.indentLevel--; + } + EditorGUILayout.EndVertical(); + } + + private void DrawTimeline() { + const float timeScaleFromMicroSec = 0.00005f; + + if (Event.current.type == EventType.Layout) { + if (this.isWindowPaused == false && profiler.IsProfiling) { + this.timeline = profiler.TimelineDataSlice; + this.firstTimeStamp = profiler.timestampStart; + this.currentTimeStamp = profiler.timestamp; + } + } + + using (var scope = new GUILayout.HorizontalScope("ToolBar")) { + this.foldTogglerTimeline = GUILayout.Toggle(this.foldTogglerTimeline, "Timeline", EditorStyles.toolbarButton, GUILayout.Width(100)); + GUILayout.Label(currentTimelinePlayback.HasValue ? currentTimelinePlayback.Value.cuename + " (" + currentTimelinePlayback.Value.cuesheet + ") started at " + MicroSec2String(currentTimelinePlayback.Value.timestamp) : " "); + this.timelineAutoScroll = GUILayout.Toggle(this.timelineAutoScroll, "Auto Scroll", EditorStyles.toolbarButton, GUILayout.Width(100)); + } + + if (this.foldTogglerTimeline == false) { return; } + + GUI.color = Color.white; + EditorGUILayout.BeginHorizontal(); + + var heightStyle = this.foldTogglerLogList ? GUILayout.MinHeight(300) : GUILayout.ExpandHeight(true); + + /* CueSheet Group */ + using (var scrollView = new GUILayout.ScrollViewScope(new Vector2(0, timelinePanelScrollPos.y), false, false, GUIStyle.none, GUIStyle.none, timelineHeaderStyle, heightStyle, GUILayout.Width(100))) { + GUILayout.Space(0); + if (timeline != null && timeline.Count > 0) foreach (var elem in timeline) { + GUI.color = elem.Value.cuesheetColor; + GUILayout.Label(elem.Value.name, timelineCueSheetStyle, GUILayout.Height((timelineButtonStyle.fixedHeight + 1) * elem.Value.TotalLaneCount - 1)); + GUI.color = Color.white; + } + GUILayout.Space(18); + } + /* Timeline */ + using (var scrollView = new GUILayout.ScrollViewScope(timelinePanelScrollPos, timelineStyle, heightStyle)) { + float timelinePixelLength = (this.currentTimeStamp - this.firstTimeStamp) * timeScaleFromMicroSec; + timelinePanelScrollPos = (this.timelineAutoScroll && this.isWindowPaused == false && profiler.IsProfiling) ? new Vector2(Mathf.Max(0, timelinePixelLength + 12 - this.timelineWinRect.width), scrollView.scrollPosition.y) : scrollView.scrollPosition; + + EditorGUILayout.BeginHorizontal(); + EditorGUILayout.BeginVertical(GUILayout.Width(timelinePixelLength)); + if (timeline == null || timeline.Count <= 0) { + GUILayout.Space(timelinePixelLength); + } else { + foreach (var cuesheetGroup in timeline) { + EditorGUILayout.BeginVertical(); + foreach (var cuelane in cuesheetGroup.Value.cueLaneDict) { + EditorGUILayout.BeginVertical(); + for (int j = 0; j < cuelane.Value.playbackLaneList.Count; ++j) { + EditorGUILayout.BeginHorizontal(); + var pbList = cuelane.Value.playbackLaneList[j].playbackList; + bool firstPlaybackDrawn = false; + if (timelinePanelScrollPos.x > 0) { + GUILayout.Space(timelinePanelScrollPos.x); + } + for (int k = 0; k < pbList.Count; ++k) { + float posRelative = ((long)pbList[k].timestamp - (long)this.firstTimeStamp) * timeScaleFromMicroSec - timelinePanelScrollPos.x; + + if (posRelative > this.timelineWinRect.width) { break; } /* skip invisible */ + + if (pbList[k].isStart) { + float currentLength = 0; + float priorSpaceWidth = 0; + + if (k < pbList.Count - 1) { + if (((long)pbList[k + 1].timestamp - (long)this.firstTimeStamp) * timeScaleFromMicroSec - timelinePanelScrollPos.x < 0) { /* skip invisible */ + k++; + continue; + } + currentLength = ((long)pbList[k + 1].timestamp - (long)pbList[k].timestamp) * timeScaleFromMicroSec; + } else { + currentLength = ((long)this.currentTimeStamp - (long)pbList[k].timestamp) * timeScaleFromMicroSec; + } + currentLength = Mathf.Min(currentLength + Mathf.Min(0, posRelative), this.timelineWinRect.width - Mathf.Max(0, posRelative)); + + if (firstPlaybackDrawn == false) { + priorSpaceWidth = Mathf.Max(0, posRelative); + } else { + priorSpaceWidth = ((long)pbList[k].timestamp - (long)pbList[k - 1].timestamp) * timeScaleFromMicroSec; + } + + GUILayout.Space(priorSpaceWidth); + GUI.color = cuelane.Value.cueColor; + DrawPlaybackEventButton(pbList[k], currentLength); + GUI.color = Color.white; + firstPlaybackDrawn = true; + } else if (firstPlaybackDrawn == false && posRelative > 0) { + GUI.color = cuelane.Value.cueColor; + DrawPlaybackEventButton(pbList[k], posRelative); + GUI.color = Color.white; + firstPlaybackDrawn = true; + } + } + + if (firstPlaybackDrawn == false) { + GUILayout.Label("", timelineButtonStyle, GUILayout.Width(0)); /* empty lane */ + } + EditorGUILayout.EndHorizontal(); + } + EditorGUILayout.EndVertical(); + } + EditorGUILayout.EndVertical(); + } + } + EditorGUILayout.EndVertical(); + GUILayout.Box("", barBorderStyle, GUILayout.Width(1), GUILayout.ExpandHeight(true)); + GUILayout.Box("", barBorderStyle, GUILayout.Width(2), GUILayout.Height(30)); + GUILayout.Space(9); + EditorGUILayout.EndHorizontal(); + } + if (Event.current.type == EventType.Repaint) { + this.timelineWinRect = GUILayoutUtility.GetLastRect(); + } + + EditorGUILayout.EndHorizontal(); + GUI.color = this.currentGuiColor; + } + + private void DrawPlaybackEventButton(CriProfiler.Playback playback, float width) { + if (GUILayout.Button(playback.cuename, timelineButtonStyle, GUILayout.Width(width - 1), GUILayout.MinWidth(-100))) { + this.currentTimelinePlayback = playback; + this.timelineAutoScroll = false; + } + } + + private void DrawLogList() { + if (Event.current.type == EventType.Layout && ((this.isWindowPaused == false && profiler.IsProfiling) || refreshLogListOnce)) { + refreshLogListOnce = false; + int logListlen = profiler.GetLogList().Count; + if (this.logItemCount != logListlen) { + this.logItemCount = logListlen; + this.isLogItemCountChanged = true; + } + this.logViewCount = (int)position.height / LOG_ITEM_HEIGHT; + this.logFirstViewIndex = Mathf.Clamp((int)logListScrollPos.y / LOG_ITEM_HEIGHT, 0, Mathf.Max(0, logItemCount - logViewCount)); + this.logViewSubList = profiler.GetLogList(logFirstViewIndex, logViewCount); + } + + using (var scope = new GUILayout.HorizontalScope("ToolBar", GUILayout.ExpandWidth(true))) { + this.foldTogglerLogList = GUILayout.Toggle(this.foldTogglerLogList, "Event Log", EditorStyles.toolbarButton, GUILayout.Width(100)); + GUILayout.Label(logItemCount.ToString() + " lines", EditorStyles.miniLabel); + if (GUILayout.Button("Open Log File", EditorStyles.toolbarButton, GUILayout.Width(120))) { + var path = EditorUtility.OpenFilePanel("Open Log File", profiler.LogFileSavePath, CriProfiler.LOG_FILE_EXTENSION); + if (string.IsNullOrEmpty(path) == false) { + profiler.ClearLog(); + profiler.LoadLogFromFile(path); + refreshLogListOnce = true; + } + } + if (GUILayout.Button("Clear Log", EditorStyles.toolbarButton, GUILayout.Width(100))) { + profiler.ClearLog(); + refreshLogListOnce = true; + } + } + + if (this.foldTogglerLogList == false) { return; } + + using (var scrollView = new GUILayout.ScrollViewScope(logListPanelScrollPos, "CN Box")) { + logListPanelScrollPos = scrollView.scrollPosition; + if (this.isLogItemCountChanged) { + this.isLogItemCountChanged = false; + this.logListScrollPos = new Vector2(0, logItemCount * LOG_ITEM_HEIGHT); + } + logListScrollPos = GUILayout.BeginScrollView(logListScrollPos); + { + /* only render visible UI elements */ + if (logViewSubList != null) { + GUILayout.Space(logFirstViewIndex * LOG_ITEM_HEIGHT); + for (int i = 0; i < logViewSubList.Count; i++) { + GUILayout.Label(profiler.FilteredLog2String(logViewSubList[i]), EditorStyles.textArea, GUILayout.Height(LOG_ITEM_HEIGHT)); + } + GUILayout.Space(Mathf.Max(0, logItemCount - logFirstViewIndex - logViewCount) * LOG_ITEM_HEIGHT); + } + } + GUILayout.EndScrollView(); + } + } + + #endregion OnGUI + + #region Drawing Functions + + private void SimpleBarGraph(UnityEngine.Rect rect, Single val, Single min, Single max, String text) { + Single ratio = Value2Ratio(val, min, max); + + UnityEngine.GUI.Box(rect, "", barBorderStyle); + rect.xMin++; + rect.yMin++; + rect.xMax--; + rect.yMax--; + UnityEngine.GUI.Box(rect, "", barBackgroundStyle); + if (Event.current.type == EventType.Repaint) { + if (ratio > 0.0f) { + Rect barRect = rect; + if (ratio > 0.999999f) { + UnityEngine.GUI.Box(barRect, "", barWarningHighStyle); + } else { + barRect.width *= ratio; + UnityEngine.GUI.Box(barRect, "", barStyle); + } + } + } + rect.xMin += 2; + UnityEngine.GUI.Label(new Rect(rect.x + 1, rect.y + 1, rect.width, rect.height), text, barTextShadowStyle); + UnityEngine.GUI.Label(rect, text, barTextStyle); + } + + private void LoudnessBarGraph( + UnityEngine.Rect rect, + Single val, + Single min, + Single max, + Single valTarget, + Single valRangePlusMinus, + Single valWarningHigh, + String text) + { + Single ratio = Value2Ratio(val, min, max); + Single ratioTarget = Value2Ratio(valTarget, min, max); + Single ratioRange = Value2Ratio(min + valRangePlusMinus, min, max); + Single ratioWarning = Value2Ratio(valWarningHigh, min, max); + + UnityEngine.GUI.Box(rect, "", barBorderStyle); + rect.xMin++; + rect.yMin++; + rect.xMax--; + rect.yMax--; + UnityEngine.GUI.Box(rect, "", barBackgroundStyle); + if (Event.current.type == EventType.Repaint) { + if (ratio > 0.0f) { + Rect barRect = rect; + if (ratio > ratioWarning) { + barRect.width = rect.width * ratio; + UnityEngine.GUI.Box(barRect, "", barWarningHighStyle); + } + if (ratio > ratioTarget + ratioRange) { + barRect.width = rect.width * Mathf.Min(ratio, ratioWarning); + UnityEngine.GUI.Box(barRect, "", barWarningHighTolerantStyle); + } + if (ratio > ratioTarget - ratioRange) { + barRect.width = rect.width * Mathf.Min(ratio, ratioTarget + ratioRange); + UnityEngine.GUI.Box(barRect, "", barMidRangeStyle); + } + if (ratio > 0) { + barRect.width = rect.width * Mathf.Max(0, Mathf.Min(ratio, ratioTarget - ratioRange)); + UnityEngine.GUI.Box(barRect, "", barWarningLowStyle); + } + } + } + rect.xMin += 2; + UnityEngine.GUI.Label(new Rect(rect.x + 1, rect.y + 1, rect.width, rect.height), text, barTextShadowStyle); + UnityEngine.GUI.Label(rect, text, barTextStyle); + } + + /* Positive values only */ + private void LineGraph(Rect rect, string title, float[] data, float maxVal, int sections, float minInterVal, bool adaptiveScale) { + const float titleHeight = 20; + const float labelWidth = 30; + const float labelHeight = 10.0f; + float cellHeight = 0; + int count = 0; + Rect labelRect; + + float currentMaxVal = maxVal; + if(adaptiveScale == true) { + currentMaxVal = Mathf.Min(Mathf.Max(data) * 2.0f, maxVal); + } + float interVal = (int)(currentMaxVal / sections); + if (interVal < minInterVal) { + interVal = minInterVal; + } + + GUI.Box(rect, "", barBorderStyle); + rect.xMin++; + rect.yMin++; + rect.xMax--; + rect.yMax--; + GUI.Box(rect, "", barBackgroundStyle); + labelRect = new Rect(rect.x + textOffsetChartTitle.x, rect.y + textOffsetChartTitle.y, rect.width, titleHeight); + GUI.Label(labelRect, title, barTextStyle); + rect.xMin += labelWidth; + rect.yMin += titleHeight; + GUI.Box(rect, "", barBorderStyle); + rect.xMin++; + rect.yMin++; + GUI.Box(rect, "", barBackgroundStyle); + + if (mat != null && Event.current.type == EventType.Repaint) { + GUI.BeginClip(rect); + GL.PushMatrix(); + { + mat.SetPass(0); + + /* grid */ + GL.Begin(GL.LINES); + cellHeight = rect.height * interVal / currentMaxVal; + count = (int)(currentMaxVal / interVal); + if(currentMaxVal % interVal == 0) { + count -= 1; + } + GL.Color(colorGrid); + float lineYPos = 0; + for (int i = 1; i <= count; i++) { + lineYPos = rect.height - i * cellHeight; + GL.Vertex3(0, lineYPos, 0); + GL.Vertex3(rect.width, lineYPos, 0); + } + GL.End(); + + /* data */ +#if UNITY_5_6_OR_NEWER + GL.Begin(GL.LINE_STRIP); + for (int i = 0; i < data.Length; i++) { + GL.Color(ColorSelector(data[i], maxVal)); + GL.Vertex3((rect.width / (data.Length - 1)) * i, rect.height * (1 - data[i] / currentMaxVal), 0); + } + GL.End(); +#else + GL.Begin(GL.LINES); + for (int i = 1; i < data.Length; i++) + { + GL.Color(ColorSelector(data[i - 1], maxVal)); + GL.Vertex3((rect.width / (data.Length - 1)) * (i - 1), rect.height * (1 - data[i - 1] / currentMaxVal), 0); + GL.Color(ColorSelector(data[i], maxVal)); + GL.Vertex3((rect.width / (data.Length - 1)) * i, rect.height * (1 - data[i] / currentMaxVal), 0); + } + GL.End(); +#endif + } + GL.PopMatrix(); + GUI.EndClip(); + + /* labels*/ + rect.xMin -= labelWidth; + labelRect = new Rect(rect.x + textOffsetCalibrator.x, rect.y + textOffsetCalibrator.y, labelWidth, labelHeight); + GUI.Label(labelRect, currentMaxVal.ToString("F0"), chartLabelStyle); + for (int i = 1; i <= count; i++) { + labelRect.y = rect.y + rect.height - i * cellHeight + textOffsetCalibrator.y; + if (labelRect.y > rect.y) { + GUI.Label(labelRect, (interVal * i).ToString("F0"), chartLabelStyle); + } + } + } /* if Event == Repaint */ + } + + private void NumericMeter(UnityEngine.Rect rect, String meterLabel, Single meterVal) { + const Single titleHeight = 20; + Rect labelRect; + Rect numRect; + + UnityEngine.GUI.Box(rect, "", barBorderStyle); + rect.xMin++; + rect.yMin++; + rect.xMax--; + rect.yMax--; + UnityEngine.GUI.Box(rect, "", barBackgroundStyle); + + labelRect = new Rect(rect.x + textOffsetChartTitle.x, rect.y + textOffsetChartTitle.y, rect.width, titleHeight); + GUI.Label(labelRect, meterLabel, barTextStyle); + numRect = new Rect(rect.center.x, rect.center.y, 10, 10); + if (meterVal > currentDbWarning) { + GUI.Label(numRect, Dbfs2String(meterVal, "F1"), meterTextWarningHighStyle); + } else if (meterVal > currentDbTarget + currentDbRangePlusMinus) { + GUI.Label(numRect, Dbfs2String(meterVal, "F1"), meterTextWarningHighTolerantStyle); + } else if (meterVal > currentDbTarget - currentDbRangePlusMinus) { + GUI.Label(numRect, Dbfs2String(meterVal, "F1"), meterTextMidRangeStyle); + } else { + GUI.Label(numRect, Dbfs2String(meterVal, "F1"), meterTextWarningLowStyle); + } + } + + private enum MultiChannelMeterType { + Peak, + RMS + } + private void MultiChannelMeter( + UnityEngine.Rect rect, + CriProfiler.LevelInfo[] info, + int numCh, + MultiChannelMeterType type, + float min, + float max, + float warningThresh, + string title) + { + float warningRatio = (warningThresh - min) / (max - min); + + const float barInterval = 20.0f; + const float calWidth = 30.0f; + const float calHeight = 10.0f; + const float titleHeight = 20.0f; + const float headHeight = 20.0f; + const float footHeight = 20.0f; + const float baseValue = 0.0f; + Color barColor = Color.green; + Color barWarningColor = Color.red; + Color holderColor = Color.green; + Color holderWarningColor = Color.red; + Rect chartRect; + + GUI.Box(rect, "", barBorderStyle); + rect.xMin++; + rect.yMin++; + rect.xMax--; + rect.yMax--; + GUI.Box(rect, "", barBackgroundStyle); + + chartRect = rect; + chartRect.xMin += calWidth; + chartRect.xMax++; + chartRect.yMin += titleHeight + headHeight; + chartRect.yMax -= footHeight; + GUI.Box(chartRect, "", barBorderStyle); + chartRect.xMin++; + chartRect.yMin++; + chartRect.xMax--; + chartRect.yMax--; + GUI.Box(chartRect, "", barBackgroundStyle); + + /* title */ + GUI.Label(new Rect(rect.x + textOffsetChartTitle.x, rect.y + textOffsetChartTitle.y, rect.width, rect.height), title, barTextStyle); + rect.yMin += titleHeight; + + /* horizontal labels */ + float barWidth = (chartRect.width - barInterval * (numCh + 1)) / numCh; + float labelXStart = calWidth + 1 + barInterval; + if (info != null && info.Length >= numCh) { + for (int i = 0; i < numCh; ++i) { + switch (type) { + case MultiChannelMeterType.Peak: + GUI.Label(new Rect(rect.x + labelXStart, rect.y, barWidth, headHeight), Dbfs2String(Level2Db(info[i].levelPeak), "F1"), multiChMeterTextStyle); + break; + case MultiChannelMeterType.RMS: + GUI.Label(new Rect(rect.x + labelXStart, rect.y, barWidth, headHeight), Dbfs2String(Level2Db(info[i].levelRms), "F1"), multiChMeterTextStyle); + break; + default: + break; + } + GUI.Label(new Rect(rect.x + labelXStart, rect.y + rect.height - footHeight, barWidth, footHeight), i < S_ChannelNames.Length ? S_ChannelNames[i] : "CH" + (i + 1), multiChMeterTextStyle); + labelXStart += barInterval + barWidth; + } + } + + /* vertical labels */ + rect.yMin += headHeight + 1; + rect.yMax -= footHeight + 1; + float cellHeight = rect.height * currentLevelCalInterval / (currentLevelCeiling - currentLevelFloor); + + float firstCellInterval = ((currentLevelCeiling - baseValue) % currentLevelCalInterval + currentLevelCalInterval) % currentLevelCalInterval; + if (firstCellInterval == 0) { + firstCellInterval = currentLevelCalInterval; + } + float firstCellHeight = rect.height * firstCellInterval / (currentLevelCeiling - currentLevelFloor); + + float remainingInterval = currentLevelCeiling - firstCellInterval - currentLevelFloor; + int cellCount = (int)(remainingInterval / currentLevelCalInterval); + if (remainingInterval % currentLevelCalInterval == 0) { + cellCount -= 1; + } + + GUI.Label(new Rect(rect.x + textOffsetCalibrator.x, rect.y + textOffsetCalibrator.y, calWidth, calHeight), currentLevelCeiling.ToString("F0"), chartLabelStyle); + GUI.Label(new Rect(rect.x + textOffsetCalibrator.x, rect.y + rect.height + textOffsetCalibrator.y, calWidth, calHeight), currentLevelFloor.ToString("F0"), chartLabelStyle); + for (int i=0; i < cellCount + 1; ++i) { + GUI.Label(new Rect(rect.x + textOffsetCalibrator.x, rect.y + firstCellHeight + cellHeight * i + textOffsetCalibrator.y, calWidth, calHeight), (currentLevelCeiling - firstCellInterval - currentLevelCalInterval * i).ToString("F0"), chartLabelStyle); + } + + /* GL drawing */ + if (mat != null && Event.current.type == EventType.Repaint) { + GUI.BeginClip(chartRect); + GL.PushMatrix(); + { + mat.SetPass(0); + + /* grid */ + float lineYPos = 0; + GL.Begin(GL.LINES); + GL.Color(colorGrid); + for (int i = 0; i < cellCount + 1; ++i) { + lineYPos = firstCellHeight + i * cellHeight; + GL.Vertex3(0, lineYPos, 0); + GL.Vertex3(chartRect.width, lineYPos, 0); + } + GL.End(); + + /* bars */ + if (info != null && info.Length >= numCh && barInterval * (numCh + 1) < chartRect.width) { + float barHeight; + float barWarningHeight; + float barXStart; + for (int i = 0; i < numCh; ++i) { + float heightRatio = 0; + switch (type) { + case MultiChannelMeterType.Peak: + heightRatio = ((Level2Db(info[i].levelPeak) - currentLevelFloor) / (currentLevelCeiling - currentLevelFloor)); + break; + case MultiChannelMeterType.RMS: + heightRatio = ((Level2Db(info[i].levelRms) - currentLevelFloor) / (currentLevelCeiling - currentLevelFloor)); + break; + default: + break; + } + if (heightRatio > 1.0f) { + heightRatio = 1.0f; + } + if (heightRatio < 0) { + heightRatio = 0; + } + barHeight = chartRect.height * heightRatio; + barWarningHeight = chartRect.height * warningRatio; + barXStart = (barInterval + barWidth) * i + barInterval; + GL.Begin(GL.QUADS); + if (heightRatio > warningRatio) { + GL.Color(barWarningColor); + GL.Vertex3(barXStart, chartRect.height, 0); + GL.Vertex3(barXStart + barWidth, chartRect.height, 0); + GL.Vertex3(barXStart + barWidth, chartRect.height - barHeight, 0); + GL.Vertex3(barXStart, chartRect.height - barHeight, 0); + } + GL.Color(barColor); + GL.Vertex3(barXStart, chartRect.height, 0); + GL.Vertex3(barXStart + barWidth, chartRect.height, 0); + GL.Vertex3(barXStart + barWidth, chartRect.height - Mathf.Max(0, Mathf.Min(barHeight, barWarningHeight)), 0); + GL.Vertex3(barXStart, chartRect.height - Mathf.Max(0, Mathf.Min(barHeight, barWarningHeight)), 0); + GL.End(); + + /* holders */ + if (type == MultiChannelMeterType.Peak) { + heightRatio = ((Level2Db(info[i].levelPeakHold) - currentLevelFloor) / (currentLevelCeiling - currentLevelFloor)); + if (heightRatio > 1.0f) { + heightRatio = 1.0f; + } + if (heightRatio < 0) { + heightRatio = 0; + } + barHeight = chartRect.height * heightRatio; + GL.Begin(GL.LINES); + if (heightRatio > warningRatio) { + GL.Color(holderWarningColor); + } else { + GL.Color(holderColor); + } + GL.Vertex3(barXStart, chartRect.height - barHeight, 0); + GL.Vertex3(barXStart + barWidth, chartRect.height - barHeight, 0); + GL.End(); + } + } + } + } + GL.PopMatrix(); + GUI.EndClip(); + } + } + + #endregion Drawing Functions + + #region Utilities + + static private bool CriFoldout(bool foldout, string content) { +#if UNITY_5_5_OR_NEWER + return EditorGUILayout.Foldout(foldout, content, true); +#else + return EditorGUILayout.Foldout(foldout, content); +#endif + } + + static private Single Level2Db(Single level) { + return Mathf.Log10(level) * 20.0f; + } + + static private Single Value2Ratio(Single val, Single min, Single max) { + if (max - min == 0.0f) { + return 0.0f; + } + if (val > max) { + return 1.0f; + } + if (val < min) { + return 0.0f; + } + return (val - min) / (max - min); + } + + static private string Dbfs2String(Single dbVal, string format) { + if (dbVal < Single.MinValue) { + return "---"; + } else { + return dbVal.ToString(format); + } + } + + static private string MicroSec2String(ulong microSec) { + ulong hour = microSec / 3600000000; + ulong min = (microSec % 3600000000) / 60000000; + ulong sec = (microSec % 60000000) / 1000000; + ulong msec = (microSec % 1000000) / 1000; + return string.Format("{0}:{1}:{2}.{3}", hour, min, sec, msec); + } + + /* Only to use on the first layer of OnGUI */ + private StringBuilder ClearedStr { + get { + this.gStrBuilder.Length = 0; + return this.gStrBuilder; + } + } + + private string DataSize2String(float sizeByte) { + gStrBuilderSub.Length = 0; + if (sizeByte > 524288.0f) { + return gStrBuilderSub.AppendFormat("{0:F2}", sizeByte / 1048576.0f).Append(" MB").ToString(); + } else if (sizeByte > 512.0f) { + return gStrBuilderSub.AppendFormat("{0:F2}", sizeByte / 1024.0f).Append(" KB").ToString(); + } else { + return gStrBuilderSub.AppendFormat("{0:F0}", sizeByte).Append(" Byte").ToString(); + } + } + + private Color ColorSelector(float sample, float maxVal) { + int index = (int)((chartGradientColors.Length - 1) * (maxVal == 0 ? 0 : sample / maxVal)); + Mathf.Clamp(index, 0, chartGradientColors.Length - 1); + + return (chartGradientColors.Length > 0) ? chartGradientColors[index] : Color.white; + } + + #endregion Utilities +} + +} //namespace CriWare \ No newline at end of file diff --git a/Assets/Scripts/CRIMW/CriWare/Editor/CriProfilerEditor.cs.meta b/Assets/Scripts/CRIMW/CriWare/Editor/CriProfilerEditor.cs.meta new file mode 100644 index 0000000..e275619 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Editor/CriProfilerEditor.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 770ee637bb793ce42bf80dce6485d913 +timeCreated: 1513758004 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Editor/CriWareBuildPostprocessor.cs b/Assets/Scripts/CRIMW/CriWare/Editor/CriWareBuildPostprocessor.cs new file mode 100644 index 0000000..7786782 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Editor/CriWareBuildPostprocessor.cs @@ -0,0 +1,212 @@ +/**************************************************************************** + * + * Copyright (c) 2018 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +using UnityEngine; +using UnityEditor; +using UnityEditor.Callbacks; +using System; +using System.IO; +#if (UNITY_5 || UNITY_2017_1_OR_NEWER) && (UNITY_IOS || UNITY_TVOS) +using UnityEditor.iOS.Xcode; +#endif + +namespace CriWare { + +public class CriWareBuildPostprocessor : ScriptableObject +{ + private static string prefsFilePath; + public bool iosAddDependencyFrameworks = true; + public bool iosReorderLibraryLinkingsForVp9 = true; + + [MenuItem("GameObject/CRIWARE/Create CriWareBuildPostprocessorPrefs.asset")] + public static void Create() + { + CriWareBuildPostprocessor instance = LoadExistingAsset(); + if (instance) { + Debug.LogError("[CRIWARE] Preferences file of CriWareBuildPostprocessor already exists."); + Selection.activeObject = instance; + return; + } + + var scobj = ScriptableObject.CreateInstance(); + if (scobj == null) { + Debug.Log("[CRIWARE] Failed to create CriWareBuildPostprocessor"); + return; + } + + var script = MonoScript.FromScriptableObject(scobj); + prefsFilePath = Path.Combine(Path.GetDirectoryName(AssetDatabase.GetAssetPath(script)), "CriWareBuildPostprocessorPrefs.asset"); + + AssetDatabase.CreateAsset(scobj, prefsFilePath); + + AssetDatabase.SaveAssets(); + AssetDatabase.Refresh(); + + Debug.Log("[CRIWARE] Created the preferences file of CriWareBuildPostprocessor. (" + prefsFilePath + ")"); + + Selection.activeObject = scobj; + } + + private static CriWareBuildPostprocessor LoadExistingAsset() + { + string postProcessorPath = ""; + string[] searchResult = AssetDatabase.FindAssets("t:CriWareBuildPostprocessor"); + if (searchResult.Length == 0) { + return null; + } + postProcessorPath = AssetDatabase.GUIDToAssetPath(searchResult[0]); + var instance = (CriWareBuildPostprocessor)AssetDatabase.LoadAssetAtPath(postProcessorPath, typeof(CriWareBuildPostprocessor)); + + return instance; + } + + [PostProcessScene] + public static void OnPostProcessScene() { + CheckGraphicsApiProcess (); + } + + + [PostProcessBuild] + public static void OnPostprocessBuild(BuildTarget build_target, string path) + { + CriWareBuildPostprocessor instance = LoadExistingAsset(); + if (instance == null) { + instance = ScriptableObject.CreateInstance(); + Debug.Log( + "[CRIWARE] Run CriWareBuildPostprocessor.OnPostprocessBuild with default preferences.\n" + + "If you want to change the preferences, please create the preferences file by 'GameObject/CRIWARE/Create CriWareBuildPostprocessorPrefs.asset' menu." + ); + } else { + Debug.Log( + "[CRIWARE] Run CriWareBuildPostprocessor.OnPostprocessBuild with default preferences.\n" + + "If you want to change the preferences, please edit the preferences file (" + prefsFilePath + ")" + ); + } + + instance.IosAddDependencyFrameworksProcess(build_target, path, + instance.iosAddDependencyFrameworks, + instance.iosReorderLibraryLinkingsForVp9); + switch (build_target) { + case BuildTarget.WebGL: + instance.PostprocessBuildWebGL(path); + break; + } + } + + private string GetAssetPath(string assetName, string substring) + { + string[] pathStock = AssetDatabase.FindAssets(assetName); + if (pathStock == null) { + return null; + } + foreach (string path in pathStock) { + string strPath = AssetDatabase.GUIDToAssetPath(path); + if (strPath.Contains(substring)) { + return strPath; + } + } + return null; + } + + private void IosAddDependencyFrameworksProcess(BuildTarget build_target, string path, bool add_frameworks, bool reorder_linkings) + { +#if UNITY_IOS || UNITY_TVOS +#if UNITY_5 || UNITY_2017_1_OR_NEWER + if ((build_target != BuildTarget.iOS && build_target != BuildTarget.tvOS) || + (!add_frameworks && !reorder_linkings)) { + return; + } + string project_path = path + "/Unity-iPhone.xcodeproj/project.pbxproj"; + PBXProject project = new PBXProject(); + project.ReadFromString(File.ReadAllText(project_path)); +#if UNITY_2019_3_OR_NEWER + string target = project.GetUnityFrameworkTargetGuid(); +#else + string target = project.TargetGuidByName("Unity-iPhone"); +#endif + if (add_frameworks) { + Debug.Log("[CRIWARE][iOS] Add dependency frameworks (VideoToolbox/OpenGLES/Metal)"); + project.AddFrameworkToProject(target, "VideoToolbox.framework", false); + project.AddFrameworkToProject(target, "OpenGLES.framework", false); + project.AddFrameworkToProject(target, "Metal.framework", false); + } + if (reorder_linkings) { + bool isVp9Enabled = false; + string libPartialPath = null; + if (build_target == BuildTarget.iOS) { + libPartialPath = "iOS/libcri_mana_vpx.a"; + } else { /* tvOS */ + libPartialPath = "tvOS/libcri_mana_vpx.a"; + } + string unityLibRelPath = GetAssetPath("libcri_mana_vpx", libPartialPath); + if (unityLibRelPath == null) { + isVp9Enabled = false; + } else { + if (!(unityLibRelPath.StartsWith("Assets") || unityLibRelPath.StartsWith("Package"))) { + Debug.LogAssertion("[CRIWARE] Internal: Not supported directory root name : " + unityLibRelPath + + "libcri_mana_vpx should be placed in the directory below Assets/ and Package/."); + } + unityLibRelPath = unityLibRelPath.Replace("\\", "/"); + string unityRootDirName = unityLibRelPath.Split('/')[0]; + string xcodeProjectRelPath = unityLibRelPath.Replace(unityRootDirName, "Libraries"); + isVp9Enabled = project.ContainsFileByRealPath(xcodeProjectRelPath); + } + if (isVp9Enabled) { + string guid = project.FindFileGuidByRealPath("Libraries/libiPhone-lib.a", PBXSourceTree.Source); + if (!string.IsNullOrEmpty(guid)) { + project.RemoveFileFromBuild(target, guid); + project.AddFileToBuild(target, guid); + Debug.Log("[CRIWARE][iOS] Reordered linking of libiPhone-lib.a for VP9 support."); + } else { + Debug.LogWarning("[CRIWARE][iOS] Failed to reorder linkings of libraries for VP9 support."); + } + } + } + + File.WriteAllText(project_path, project.WriteToString()); +#else + if (build_target != BuildTarget.iPhone) { + return; + } + Debug.LogWarning("[CRIWARE][iOS] Please add dependency frameworks (VideoToolbox.framework, Metal.framework) on Xcode."); +#endif +#endif + } + + + private static bool CheckGraphicsApiProcess() { + return true; + } + + + private void PostprocessBuildWebGL(string path) + { + string SourceDir = GetAssetPath("sofdec2.worker", "WebGL/sofdec2.worker.bin"); + if (SourceDir == null) { + SourceDir = GetAssetPath("sofdec2.worker", "WebGL2/sofdec2.worker.bin"); + Debug.Assert((SourceDir != null), "[CRIWARE] Internal: Failed to copy WebGL library files."); + } + SourceDir = Directory.GetParent(SourceDir).ToString(); + string DestnationDir = path + "/StreamingAssets/"; + + bool ret = true; + try { + Directory.CreateDirectory(DestnationDir); + File.Copy(Path.Combine(SourceDir, "sofdec2.worker.bin"), DestnationDir + "sofdec2.worker.js", true); + File.Copy(Path.Combine(SourceDir, "sofdec2.worker.wajs.bin"), DestnationDir + "sofdec2wasm.worker.js", true); + File.Copy(Path.Combine(SourceDir, "sofdec2.worker.wasm.bin"), DestnationDir + "sofdec2.worker.wasm", true); + } + catch (System.Exception) { + Debug.LogError("[CRIWARE][WebGL] Copying sofdec2.worker.js failed."); + ret = false; + } + if (ret) { + Debug.Log("[CRIWARE][WebGL] Copying sofdec2.worker.js succeeded."); + } + } +} + +} //namespace CriWare \ No newline at end of file diff --git a/Assets/Scripts/CRIMW/CriWare/Editor/CriWareBuildPostprocessor.cs.meta b/Assets/Scripts/CRIMW/CriWare/Editor/CriWareBuildPostprocessor.cs.meta new file mode 100644 index 0000000..e2bb7df --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Editor/CriWareBuildPostprocessor.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 6ec5f96f85afa264b976655949c8c72a +timeCreated: 1445602397 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Editor/CriWareBuildPreprocessor.cs b/Assets/Scripts/CRIMW/CriWare/Editor/CriWareBuildPreprocessor.cs new file mode 100644 index 0000000..f3061e5 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Editor/CriWareBuildPreprocessor.cs @@ -0,0 +1,192 @@ +/**************************************************************************** + * + * Copyright (c) 2017 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +#if UNITY_EDITOR && UNITY_5_6_OR_NEWER + +using System.Collections; +using System.Collections.Generic; +using System.IO; +using UnityEngine; +using UnityEditor; +using UnityEditor.Build; +using System.Runtime.CompilerServices; +using UnityEngine.Assertions; + +[assembly: InternalsVisibleTo("EditorTests")] +namespace CriWare { + +public class CriWareBuildPreprocessor : ScriptableObject { + public bool muteOtherAudio = true; + + public static CriWareBuildPreprocessor LoadExistingAsset() { + string preProcessorPath = ""; + string[] searchResult = AssetDatabase.FindAssets("t:CriWareBuildPreprocessor"); + if (searchResult.Length == 0) { + return null; + } + preProcessorPath = AssetDatabase.GUIDToAssetPath(searchResult[0]); + var instance = (CriWareBuildPreprocessor)AssetDatabase.LoadAssetAtPath(preProcessorPath, typeof(CriWareBuildPreprocessor)); + return instance; + } +} + +public class CriWareBuildPreprocessExcecutor : +#if UNITY_2018_1_OR_NEWER + IPreprocessBuildWithReport +#else + IPreprocessBuild +#endif +{ + private static string prefsFilePath; + + public int callbackOrder { get { return 0; } } + + [MenuItem("GameObject/CRIWARE/Create CriWareBuildPreprocessorPrefs.asset")] + public static void Create() + { + CriWareBuildPreprocessor instance = CriWareBuildPreprocessor.LoadExistingAsset(); + if (instance) { + Debug.LogError("[CRIWARE] Preferences file of CriWareBuildPreprocessor already exists."); + Selection.activeObject = instance; + return; + } + + var scobj = ScriptableObject.CreateInstance(); + if (scobj == null) { + Debug.Log("[CRIWARE] Failed to create CriWareBuildPreprocessor asset"); + return; + } + + var script = MonoScript.FromScriptableObject(scobj); + prefsFilePath = Path.Combine(Path.GetDirectoryName(AssetDatabase.GetAssetPath(script)), "CriWareBuildPreprocessorPrefs.asset"); + + AssetDatabase.CreateAsset(scobj, prefsFilePath); + + AssetDatabase.SaveAssets(); + AssetDatabase.Refresh(); + + Debug.Log("[CRIWARE] Created the preferences file of CriWareBuildPreprocessor. (" + prefsFilePath + ")"); + + Selection.activeObject = scobj; + } + +#if UNITY_2018_1_OR_NEWER + public void OnPreprocessBuild(UnityEditor.Build.Reporting.BuildReport report) + { + OnPreprocessBuild(report.summary.platform, report.summary.outputPath); + } +#endif + + public void OnPreprocessBuild(BuildTarget build_target, string path) + { + CriWareBuildPreprocessor instance = CriWareBuildPreprocessor.LoadExistingAsset(); + if (instance == null) { + instance = ScriptableObject.CreateInstance(); + Debug.Log( + "[CRIWARE] Run CriWareBuildPreprocessor.OnPreprocessBuild with default preferences.\n" + + "If you want to change the preferences, please create the preferences file by 'GameObject/CRIWARE/Create CriWareBuildPreprocessorPrefs.asset' menu." + ); + } else { + Debug.Log( + "[CRIWARE] CriWareBuildPreprocessor preferences file has been loaded.\n" + + "If you want to change the preferences, please edit the preferences file (" + prefsFilePath + ")" + ); + } + + if (instance.muteOtherAudio == true) { + ModifyAudioManager(build_target, path); + } +/* @cond excludele */ +#if UNITY_WEBGL + CheckEmscriptenVersion(); +#endif +/* @endcond */ + } + + private static void ModifyAudioManager(BuildTarget build_target, string path) + { + string audioManagerPath = "ProjectSettings/AudioManager.asset"; + SerializedObject audioManager = new SerializedObject(AssetDatabase.LoadAllAssetsAtPath(audioManagerPath)[0]); + SerializedProperty propertyDisableUnityAudio = audioManager.FindProperty("m_DisableAudio"); + + if (build_target == BuildTarget.Android) { + if (PlayerSettings.muteOtherAudioSources == true) { + propertyDisableUnityAudio.boolValue = false; + } + } else { + propertyDisableUnityAudio.boolValue = true; + } + + audioManager.ApplyModifiedProperties(); + } + +/* @cond excludele */ + private void CheckEmscriptenVersion() { + var pluginInfoList = GetPluginInfoList(); + var webglPluginInfoList = ExtractWebGLPluginInfoList(pluginInfoList); + MatchingWebglPlatformInfo(webglPluginInfoList); + } + + internal static List GetPluginInfoList() { + CriWareVersionWindow _criWareVersionWindow = ScriptableObject.CreateInstance("CriWareVersionWindow") as CriWareVersionWindow; + _criWareVersionWindow.Reload(CriWareVersionWindow.PluginType.CRIWARE, true); + var pluginInfoList = _criWareVersionWindow.PluginInfos; + return pluginInfoList; + } + + internal static List ExtractWebGLPluginInfoList(List pluginInfoList) { + const string webgl1PlatformSymbol = "WebGL"; + const string webgl2PlatformSymbol = "WebGL2"; + var webglPluginInfoList = new List(); + + foreach (var pluginInfo in pluginInfoList) { + if (pluginInfo.platform.Equals(webgl1PlatformSymbol) || pluginInfo.platform.Equals(webgl2PlatformSymbol)) { + webglPluginInfoList.Add(pluginInfo); + } + } + return webglPluginInfoList; + } + + internal static void MatchingWebglPlatformInfo(List webglPluginInfoList) { + string ExceptionMessage = null; + + if (webglPluginInfoList.Count == 0) { + return; + } else if (webglPluginInfoList.Count > 1) { + ExceptionMessage = "[CRIWARE] Several competing CRIWARE WebGL libraries are included." + + "Please refer to the manual and import the appropriate plug-in library."; + } else { + string requriedWebglPlatformSymbol; +#if UNITY_2021_2_OR_NEWER + requriedWebglPlatformSymbol = "WebGL2"; + if (webglPluginInfoList[0].platform.Equals(requriedWebglPlatformSymbol)) { + return; + } else { + ExceptionMessage = "[CRIWARE] CRIWARE Unity Plug-in built with Emscripten v1 only runs on Unity 2021.1 or earlier." + + "Please refer to the manual and import the appropriate plug-in library."; + } +# else + requriedWebglPlatformSymbol = "WebGL"; + if (webglPluginInfoList[0].platform.Equals(requriedWebglPlatformSymbol)) { + return; + } else { + ExceptionMessage = "[CRIWARE] CRIWARE Unity Plug-in built with Emscripten v2 only runs on Unity 2021.2 or later." + + "Please refer to the manual and import the appropriate plug-in library."; + } +#endif + } + throw new BuildFailedException(ExceptionMessage); + } +/* @endcond */ + +} + + +} //namespace CriWare + +#endif + +/* end of file */ \ No newline at end of file diff --git a/Assets/Scripts/CRIMW/CriWare/Editor/CriWareBuildPreprocessor.cs.meta b/Assets/Scripts/CRIMW/CriWare/Editor/CriWareBuildPreprocessor.cs.meta new file mode 100644 index 0000000..08f2b7a --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Editor/CriWareBuildPreprocessor.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: db5c2e0b215f3400f99a53d5c91fead2 +timeCreated: 1507701071 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Editor/CriWareEditor.cs b/Assets/Scripts/CRIMW/CriWare/Editor/CriWareEditor.cs new file mode 100644 index 0000000..cbd7e48 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Editor/CriWareEditor.cs @@ -0,0 +1,55 @@ +/**************************************************************************** + * + * Copyright (c) 2011 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +using UnityEditor; +using UnityEngine; + +namespace CriWare { + +public class CriWareEditor : UnityEditor.Editor +{ + [MenuItem("GameObject/CRIWARE/Create CRIWARE Library Initializer", false, 150)] + public static void CreateCriwareLibraryInitalizer() + { + CriWareInitializer[] criWareInitializerList = FindObjectsOfType(typeof(CriWareInitializer)) as CriWareInitializer[]; + if (criWareInitializerList.Length > 0) { + Debug.LogError("\"CriWareLibraryInitializer\" already exists."); + + Selection.activeGameObject = criWareInitializerList[0].gameObject; + + } else { + GameObject go = null; + go = new GameObject("CriWareLibraryInitializer"); + + go.AddComponent(); + + Selection.activeGameObject = go; + } + } + + [MenuItem("GameObject/CRIWARE/Create CRIWARE Error Handler", false, 150)] + public static void CreateCriwareErrorHandler() + { + CriWareErrorHandler[] criWareErrorHandlerList = FindObjectsOfType(typeof(CriWareErrorHandler)) as CriWareErrorHandler[]; + if (criWareErrorHandlerList.Length > 0) { + Debug.LogError("\"CriWareErrorHandler\" already exists."); + + Selection.activeGameObject = criWareErrorHandlerList[0].gameObject; + + } else { + GameObject go = null; + go = new GameObject("CriWareErrorHandler"); + + go.AddComponent(); + + Selection.activeGameObject = go; + } + } + +} // end of class + +} //namespace CriWare +/* end of file */ diff --git a/Assets/Scripts/CRIMW/CriWare/Editor/CriWareEditor.cs.meta b/Assets/Scripts/CRIMW/CriWare/Editor/CriWareEditor.cs.meta new file mode 100644 index 0000000..452055f --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Editor/CriWareEditor.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: cf50923c69c53c54895cb08f93d2db47 +timeCreated: 1433816077 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Editor/CriWareErrorHandlerEditor.cs b/Assets/Scripts/CRIMW/CriWare/Editor/CriWareErrorHandlerEditor.cs new file mode 100644 index 0000000..ac7d3c4 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Editor/CriWareErrorHandlerEditor.cs @@ -0,0 +1,38 @@ +/**************************************************************************** + * + * Copyright (c) 2020 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +using UnityEngine; +using UnityEditor; + +namespace CriWare { + +[CustomEditor(typeof(CriWareErrorHandler))] +public class CriWareErrorHandlerEditor : UnityEditor.Editor { + private SerializedProperty m_enableForceCrashOnError; + private SerializedProperty m_dontDestroyOnLoad; + + private void OnEnable() { + m_enableForceCrashOnError = serializedObject.FindProperty("enableForceCrashOnError"); + m_dontDestroyOnLoad = serializedObject.FindProperty("dontDestroyOnLoad"); + } + + public override void OnInspectorGUI() { + EditorGUILayout.PropertyField(m_enableForceCrashOnError, new GUIContent("Force Crash on Error")); + EditorGUILayout.HelpBox("Force Crash on Error:\nAny CRIWARE error will cause the editor to crash.\nDon't enable this when debugging in the editor.", m_enableForceCrashOnError.boolValue ? MessageType.Warning : MessageType.Info); + EditorGUILayout.PropertyField(m_dontDestroyOnLoad, new GUIContent("Dont Destroy on Load")); + + serializedObject.ApplyModifiedProperties(); + } + + private int GenIntField(string label_str, string tooltip, int field_value, int min, int max) + { + GUIContent content = new GUIContent(label_str, tooltip); + return Mathf.Min(max, Mathf.Max(min, EditorGUILayout.IntField(content, field_value))); + } +} + +} //namespace CriWare +/* end of file */ \ No newline at end of file diff --git a/Assets/Scripts/CRIMW/CriWare/Editor/CriWareErrorHandlerEditor.cs.meta b/Assets/Scripts/CRIMW/CriWare/Editor/CriWareErrorHandlerEditor.cs.meta new file mode 100644 index 0000000..2218ebd --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Editor/CriWareErrorHandlerEditor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b87a25f74c8edf344858ddfe92560ec0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Editor/CriWareInitializerEditor.cs b/Assets/Scripts/CRIMW/CriWare/Editor/CriWareInitializerEditor.cs new file mode 100644 index 0000000..dfec7a5 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Editor/CriWareInitializerEditor.cs @@ -0,0 +1,470 @@ +/**************************************************************************** + * + * Copyright (c) 2011 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +using UnityEngine; +using UnityEditor; +using System; + +namespace CriWare { + +[CustomEditor(typeof(CriWareInitializer))] +public class CriWareInitializerEditor : UnityEditor.Editor +{ + private void GenToggleField(string label_str, string tooltip, ref bool field_value) + { + GUIContent content = new GUIContent(label_str, tooltip); + field_value = EditorGUILayout.Toggle(content, field_value); + } + + private void GenIntField(string label_str, string tooltip, ref int field_value, int min, int max) + { + GUIContent content = new GUIContent(label_str, tooltip); + field_value = Math.Min(max, Math.Max(min, EditorGUILayout.IntField(content, field_value))); + } + + private void GenIntFieldWithUnit(string label_str, string label_unit, string tooltip, ref int field_value, int min, int max) + { + //GUIContent content = new GUIContent(label_str, tooltip); + //field_value = Math.Min(max, Math.Max(min, EditorGUILayout.IntField(content, field_value))); + + EditorGUILayout.BeginHorizontal(); + { + GUIContent content = new GUIContent(label_str, tooltip); + field_value = Math.Min(max, Math.Max(min, EditorGUILayout.IntField(content, field_value))); + int indentLevel = EditorGUI.indentLevel; + EditorGUI.indentLevel = 0; + EditorGUILayout.LabelField(label_unit); + EditorGUI.indentLevel = indentLevel; + } + EditorGUILayout.EndHorizontal(); + + } + + private void GenPositiveFloatField(string label_str, string tooltip, ref float field_value, float min, float max) + { + GUIContent content = new GUIContent(label_str, tooltip); + field_value = Math.Min(max, Math.Max(min, EditorGUILayout.FloatField(content, field_value))); + } + + private void GenPositiveFloatField(string label_str, string label_unit, string tooltip, ref float field_value, float min, float max) + { + EditorGUILayout.BeginHorizontal(); + { + GUIContent content = new GUIContent(label_str, tooltip); + field_value = Math.Min(max, Math.Max(min, EditorGUILayout.FloatField(content, field_value))); + int indentLevel = EditorGUI.indentLevel; + EditorGUI.indentLevel = 0; + EditorGUILayout.LabelField(label_unit); + EditorGUI.indentLevel = indentLevel; + } + EditorGUILayout.EndHorizontal(); + } + + private void GenStringField(string label_str, string tooltip, ref string field_value) + { + GUIContent content = new GUIContent(label_str, tooltip); + field_value = EditorGUILayout.TextField(content, field_value); + } + + private Enum GenEnumField(string label_str, string tooltip, Enum field_value) + { + EditorGUILayout.BeginHorizontal(); + { + GUIContent content = new GUIContent(label_str, tooltip); + field_value = EditorGUILayout.EnumPopup(content, field_value); + } + EditorGUILayout.EndHorizontal(); + return field_value; + } + + static private bool showFileSystemAndroidConfig = false; + static private bool showAtomStandardVoicePoolConfig = false; + static private bool showAtomHcaMxVoicePoolConfig = false; + static private bool showAtomEditorConfig = false; + static private bool showAtomPCConfig = false; + /* @cond excludele */ + static private bool showAtomLINUXConfig = false; + /* @endcond */ + static private bool showAtomIOSConfig = false; + static private bool showAtomAndroidConfig = false; + static private bool showAtomAndroidVoicePoolConfig = true; + /* @cond excludele */ + static private bool showAtomVitaConfig = false; + static private bool showAtomVitaAtrac9VoicePoolConfig = true; + static private bool showAtomPs4Config = false; + static private bool showAtomPs4Atrac9VoicePoolConfig = true; + static private bool showAtomPs4Audio3dVoicePoolConfig = true; + static private bool showAtomSwitchConfig = false; + static private bool showAtomSwitchOpusVoicePoolConfig = true; + static private bool showAtomWebGLConfig = false; + static private bool showAtomWebGLWebAudioVoicePoolConfig = true; + static private bool showManaVitaConfig = false; + static private bool showManaWebGLConfig = false; + /* @endcond */ + + static private string[] asrOutputModes = {"Default", "Stereo", "4ch", "6ch(5.1ch)", "8ch(7.1ch)"}; + static private int[] asrNumOutputChannels = {0, 2, 4, 6, 8}; + static private string[] inGamePreviewSwitchModes = { "Disable", "Enable", "Follow Build Setting" }; + static private CriAtomConfig.InGamePreviewSwitchMode[] inGamePreviewSwitchModeValues + = { CriAtomConfig.InGamePreviewSwitchMode.Disable, CriAtomConfig.InGamePreviewSwitchMode.Enable, CriAtomConfig.InGamePreviewSwitchMode.FollowBuildSetting }; + + public override void OnInspectorGUI() + { + CriWareInitializer initializer = target as CriWareInitializer; + + Undo.RecordObject(target, null); + + GUI.changed = false; + { + // FileSystem Config + initializer.initializesFileSystem = + EditorGUILayout.BeginToggleGroup("Initialize FileSystem", initializer.initializesFileSystem); + EditorGUI.indentLevel += 1; + { + GenIntField("Number of Loaders", "The maximum number of CriFsLoader objects used at a time. " + + "NOTE: Count the number of CriFsLoadFileRequest objects and the total number of Streaming Voices in CRI Atom settings and the number of CriMana.Player component,", + ref initializer.fileSystemConfig.numberOfLoaders, 0, 128); + GenIntField("Number of Binders", "", ref initializer.fileSystemConfig.numberOfBinders, 0, 128); + GenIntField("Number of Installers", "", ref initializer.fileSystemConfig.numberOfInstallers, 0, 128); + GenIntFieldWithUnit("Install Buffer Size", "[KiB]", "Internal buffer size to install data. A larger buffer size result in better performance.", ref initializer.fileSystemConfig.installBufferSize, 32, int.MaxValue); + GenIntField("Max Length of Path", "The maximum length of path (file path or url path) that can be passed.", ref initializer.fileSystemConfig.maxPath, 64, 2048); + GenStringField("User Agent String", "", ref initializer.fileSystemConfig.userAgentString); + GenToggleField("Minimize FD Usage", "With this option, the plugin minimizes file descriptor usage so that applicaiton can save file descriptor resource. However, this may increase file I/O instead.", ref initializer.fileSystemConfig.minimizeFileDescriptorUsage); + GenToggleField("Enable CRC Check", "This option enables a CRC check on loading or binding when the cpk file contains CRC.", ref initializer.fileSystemConfig.enableCrcCheck); + + showFileSystemAndroidConfig = EditorGUILayout.Foldout(showFileSystemAndroidConfig, "Android Config"); + if (showFileSystemAndroidConfig) { + EditorGUI.indentLevel += 1; + { + /* Ver.2.03.03 以前は 0 がデフォルト値だったことの互換性維持のための処理 */ + if (initializer.fileSystemConfig.androidDeviceReadBitrate == 0) { + initializer.fileSystemConfig.androidDeviceReadBitrate = CriFsConfig.defaultAndroidDeviceReadBitrate; + } + } + GenIntFieldWithUnit("Device Read Bitrate", "[bps]", "Expected minimum device read bitrate to be used for multi-streaming management." + CriFsConfig.defaultAndroidDeviceReadBitrate + " bps", + ref initializer.fileSystemConfig.androidDeviceReadBitrate, 0, int.MaxValue); + EditorGUI.indentLevel -= 1; + } + } + EditorGUI.indentLevel -= 1; + EditorGUILayout.EndToggleGroup(); + + // Atom Config + initializer.initializesAtom = + EditorGUILayout.BeginToggleGroup("Initialize Atom", initializer.initializesAtom); + EditorGUI.indentLevel += 1; + { + + + GenStringField("ACF File Name", "", ref initializer.atomConfig.acfFileName); + GenIntField("Max Virtual Voices", "", ref initializer.atomConfig.maxVirtualVoices, CriAtomPlugin.GetRequiredMaxVirtualVoices(initializer.atomConfig), 1024); + GenIntField("Max Voice Limit Groups", "", ref initializer.atomConfig.maxVoiceLimitGroups, 0, 1024); + GenIntField("Max Parameter Blocks", "", ref initializer.atomConfig.maxParameterBlocks, 1024, 4096); + GenIntField("Max Buses", "Maximum number of buses.", ref initializer.atomConfig.maxBuses, 1, 64); + GenIntField("Max Categories", "Maximum number of categories.", ref initializer.atomConfig.maxCategories, 0, 1024); + GenIntField("Max Aisacs", "Maximum number of Aisacs.", ref initializer.atomConfig.maxAisacs,1,55); + GenIntField("Max Bus Sends", "Maximum number of Bus Sends.", ref initializer.atomConfig.maxBusSends,1,32); + GenIntField("Max Sequence Events Per Frame", "Maximum number of sequence events that will be triggered in one application frame.", ref initializer.atomConfig.maxSequenceEventsPerFrame, 0, 64); + GenIntField("Max Beat Sync Callbacks Per Frame", "Maximum number of beat synchronized callback that will be triggered in one application frame.", ref initializer.atomConfig.maxBeatSyncCallbacksPerFrame, 0, 64); + GenIntField("Max Cue Link Callbacks Per Frame", "Maximum number of cue link callback that will be triggered in one application frame.", ref initializer.atomConfig.maxCueLinkCallbacksPerFrame, 0, 64); + GenIntField("Categories per Playback", "Number of category references per playback.", ref initializer.atomConfig.categoriesPerPlayback, 0, 16); + GenIntField("Max Faders", "Maximum number of faders.", ref initializer.atomConfig.maxFaders, 0, 1024); + GenIntFieldWithUnit("Sampling Rate", "[Hz]", + "Sound output sampling rate. " + + "HCA-MX needs to set the sampling rate of HCA-MX data. " + + "A value of 0 (the default value) means that the internal value will be applied.", + ref initializer.atomConfig.outputSamplingRate, 0, 192000); + GenPositiveFloatField("Server Frequency", "[Hz]", "", ref initializer.atomConfig.serverFrequency, 15.0f, 120.0f); + + int selected_output_mode = 0; + foreach (int num_channnels in asrNumOutputChannels) { + if (num_channnels == initializer.atomConfig.asrOutputChannels) { + break; + } + selected_output_mode++; + } + selected_output_mode = EditorGUILayout.Popup("ASR Output Mode", selected_output_mode, asrOutputModes); + initializer.atomConfig.asrOutputChannels = asrNumOutputChannels[selected_output_mode]; + + GenToggleField("Use Time For Seed", "", ref initializer.atomConfig.useRandomSeedWithTime); + + if (initializer.atomConfig.inGamePreviewMode == CriAtomConfig.InGamePreviewSwitchMode.Default) { + initializer.atomConfig.inGamePreviewMode = initializer.atomConfig.usesInGamePreview ? + CriAtomConfig.InGamePreviewSwitchMode.Enable : + CriAtomConfig.InGamePreviewSwitchMode.Disable; + initializer.atomConfig.usesInGamePreview = false; + } + int selected_ingamepreview_switch_mode = 0; + foreach (CriAtomConfig.InGamePreviewSwitchMode mode in inGamePreviewSwitchModeValues) { + if (mode == initializer.atomConfig.inGamePreviewMode) { + break; + } + selected_ingamepreview_switch_mode++; + } + selected_ingamepreview_switch_mode = EditorGUILayout.Popup("In Game Preview", selected_ingamepreview_switch_mode, inGamePreviewSwitchModes); + initializer.atomConfig.inGamePreviewMode = inGamePreviewSwitchModeValues[selected_ingamepreview_switch_mode]; + + if (initializer.atomConfig.inGamePreviewMode != CriAtomConfig.InGamePreviewSwitchMode.Disable) { + EditorGUI.indentLevel += 1; + GenIntField("Max Preview Objects", "", ref initializer.atomConfig.inGamePreviewConfig.maxPreviewObjects, 0, 1024); + GenIntFieldWithUnit("Communication Buffer Size", "[KiB]", "Size of buffer for communication between library and tool.", ref initializer.atomConfig.inGamePreviewConfig.communicationBufferSize, 2048, int.MaxValue); + GenIntFieldWithUnit("Update Interval", "[counts of server process]", "Interval to update playback position.", ref initializer.atomConfig.inGamePreviewConfig.playbackPositionUpdateInterval, 1, 8); + EditorGUI.indentLevel -= 1; + } + + /* @cond excludele */ + if (initializer.atomConfig.inGamePreviewMode == CriAtomConfig.InGamePreviewSwitchMode.Enable || + initializer.atomConfig.inGamePreviewMode == CriAtomConfig.InGamePreviewSwitchMode.FollowBuildSetting) { + EditorGUI.indentLevel += 2; + showAtomStandardVoicePoolConfig = EditorGUILayout.Foldout(showAtomStandardVoicePoolConfig, "Switch Monitor Config"); + if (showAtomStandardVoicePoolConfig) { + EditorGUI.indentLevel += 1; + GenToggleField("Initialize Socket", "Initialize Socket library while CriWare Monitor initialization. Please turn off this flag if your project initializes Socket library.", + ref initializer.atomConfig.switchInitializeSocket); + EditorGUI.indentLevel -= 1; + } + EditorGUI.indentLevel -= 2; + } + /* @endcond */ + + /* @cond excludele */ + GenToggleField("VR Mode", "", ref initializer.atomConfig.vrMode); + /* @endcond */ + GenToggleField("Keep Playing Sound On Pause", "", ref initializer.atomConfig.keepPlayingSoundOnPause); + + showAtomStandardVoicePoolConfig = EditorGUILayout.Foldout(showAtomStandardVoicePoolConfig, "Standard Voice Pool Config"); + if (showAtomStandardVoicePoolConfig) { + EditorGUI.indentLevel += 1; + GenIntField("Memory Voices", "", ref initializer.atomConfig.standardVoicePoolConfig.memoryVoices, 0, 1024); + GenIntField("Streaming Voices", "", ref initializer.atomConfig.standardVoicePoolConfig.streamingVoices, 0, 1024); + EditorGUI.indentLevel -= 1; + } + + showAtomHcaMxVoicePoolConfig = EditorGUILayout.Foldout(showAtomHcaMxVoicePoolConfig, "HCA-MX Voice Pool Config"); + if (showAtomHcaMxVoicePoolConfig) { + EditorGUI.indentLevel += 1; + GenIntField("Memory Voices", "", ref initializer.atomConfig.hcaMxVoicePoolConfig.memoryVoices, 0, 1024); + GenIntField("Streaming Voices", "", ref initializer.atomConfig.hcaMxVoicePoolConfig.streamingVoices, 0, 1024); + EditorGUI.indentLevel -= 1; + } + + showAtomEditorConfig = EditorGUILayout.Foldout(showAtomEditorConfig, "Editor Config"); + if (showAtomEditorConfig) { + EditorGUI.indentLevel += 1; + GenToggleField("Enable User PCM Out Mode", "For audio recording or manual output.", ref initializer.atomConfig.editorPcmOutputConfig.enable); + GenIntField("PCM Buffer Length", "", ref initializer.atomConfig.editorPcmOutputConfig.bufferLength, 1024, 48000); + EditorGUI.indentLevel -= 1; + } + + showAtomPCConfig = EditorGUILayout.Foldout(showAtomPCConfig, "PC Config"); + if (showAtomPCConfig) { + EditorGUI.indentLevel += 1; + GenIntFieldWithUnit("Buffering Time", "[msec]", "Sound buffering time in msec.", ref initializer.atomConfig.pcBufferingTime, 0, 2000); + EditorGUI.indentLevel -= 1; + } + /* @cond excludele */ + showAtomLINUXConfig = EditorGUILayout.Foldout(showAtomLINUXConfig, "Linux Config"); + if (showAtomLINUXConfig) { + EditorGUI.indentLevel += 1; + initializer.atomConfig.linuxOutput = (CriAtomConfig.LinuxOutput)GenEnumField("Sound Output", "Sound output system (default is PulseAudio).", initializer.atomConfig.linuxOutput); + GenIntFieldWithUnit("PulseAudio Latency", "[usec]", "Latency setting for PluseAudio.", ref initializer.atomConfig.linuxPulseLatencyUsec, 0, 200000); + EditorGUI.indentLevel -= 1; + } + /* @endcond */ + showAtomIOSConfig = EditorGUILayout.Foldout(showAtomIOSConfig, "iOS Config"); + if (showAtomIOSConfig) { + EditorGUI.indentLevel += 1; + GenToggleField("Enable SonicSYNC", "", ref initializer.atomConfig.iosEnableSonicSync); + EditorGUI.BeginDisabledGroup(initializer.atomConfig.iosEnableSonicSync); + { + GenIntFieldWithUnit("Buffering Time", "[msec]", "Sound buffering time in msec.", ref initializer.atomConfig.iosBufferingTime, 16, 200); + } + EditorGUI.EndDisabledGroup(); + GenToggleField("Override iPod Music", "", ref initializer.atomConfig.iosOverrideIPodMusic); + EditorGUI.indentLevel -= 1; + } + + showAtomAndroidConfig = EditorGUILayout.Foldout(showAtomAndroidConfig, "Android Config"); + if (showAtomAndroidConfig) { + EditorGUI.indentLevel += 1; + GenToggleField("Enable SonicSYNC", "", ref initializer.atomConfig.androidEnableSonicSync); + EditorGUI.BeginDisabledGroup(initializer.atomConfig.androidEnableSonicSync); + { + /* Ver.2.03.03 以前は 0 がデフォルト値だったことの互換性維持のための処理 */ + if (initializer.atomConfig.androidBufferingTime == 0) { + initializer.atomConfig.androidBufferingTime = (int)(4 * 1000.0 / initializer.atomConfig.serverFrequency); + } + if (initializer.atomConfig.androidStartBufferingTime == 0) { + initializer.atomConfig.androidStartBufferingTime = (int)(3 * 1000.0 / initializer.atomConfig.serverFrequency); + } + } + GenIntFieldWithUnit("Buffering Time", "[msec]", "Sound buffering time in msec.", ref initializer.atomConfig.androidBufferingTime, 50, 500); + GenIntFieldWithUnit("Start Buffering", "[msec]", "Sound buffering time to start playing. This value will be applied when using the low latency voice pool.", ref initializer.atomConfig.androidStartBufferingTime, 50, 500); + EditorGUI.EndDisabledGroup(); + showAtomAndroidVoicePoolConfig = EditorGUILayout.Foldout(showAtomAndroidVoicePoolConfig, "Low Latency Standard Voice Pool Config"); + if (showAtomAndroidVoicePoolConfig) { + EditorGUI.indentLevel += 1; + GenIntField("Memory Voices", "", ref initializer.atomConfig.androidLowLatencyStandardVoicePoolConfig.memoryVoices, 0, 32); + GenIntField("Streaming Voices", "", ref initializer.atomConfig.androidLowLatencyStandardVoicePoolConfig.streamingVoices, 0, 32); + EditorGUI.indentLevel -= 1; + } + GenToggleField("Use Android Fast Mixer", "", ref initializer.atomConfig.androidUsesAndroidFastMixer); + GenToggleField("Use Asr For Default Playback", "", ref initializer.atomConfig.androidForceToUseAsrForDefaultPlayback); + GenToggleField("[Beta] Use AAudio", "", ref initializer.atomConfig.androidUsesAAudio); + EditorGUI.indentLevel -= 1; + } + + /* @cond excludele */ + showAtomVitaConfig = EditorGUILayout.Foldout(showAtomVitaConfig, "PS Vita Config"); + if (showAtomVitaConfig) { + EditorGUI.indentLevel += 1; + showAtomVitaAtrac9VoicePoolConfig = EditorGUILayout.Foldout(showAtomVitaAtrac9VoicePoolConfig, "ATRAC9 Voice Pool Config"); + if (showAtomVitaAtrac9VoicePoolConfig) { + EditorGUI.indentLevel += 1; + GenIntField("Memory Voices", "", ref initializer.atomConfig.vitaAtrac9VoicePoolConfig.memoryVoices, 0, 32); + GenIntField("Streaming Voices", "", ref initializer.atomConfig.vitaAtrac9VoicePoolConfig.streamingVoices, 0, 32); + EditorGUI.indentLevel -= 1; + } + EditorGUI.indentLevel -= 1; + } + + showAtomPs4Config = EditorGUILayout.Foldout(showAtomPs4Config, "PS4 Config"); + if (showAtomPs4Config) { + EditorGUI.indentLevel += 1; + showAtomPs4Atrac9VoicePoolConfig = EditorGUILayout.Foldout(showAtomPs4Atrac9VoicePoolConfig, "ATRAC9 Voice Pool Config"); + if (showAtomPs4Atrac9VoicePoolConfig) { + EditorGUI.indentLevel += 1; + GenIntField("Memory Voices", "", ref initializer.atomConfig.ps4Atrac9VoicePoolConfig.memoryVoices, 0, 256); + GenIntField("Streaming Voices", "", ref initializer.atomConfig.ps4Atrac9VoicePoolConfig.streamingVoices, 0, 256); + EditorGUI.indentLevel -= 1; + } + EditorGUI.indentLevel -= 1; + + initializer.atomConfig.ps4Audio3dConfig.useAudio3D = + EditorGUILayout.BeginToggleGroup("Object-Based Audio", initializer.atomConfig.ps4Audio3dConfig.useAudio3D); + EditorGUI.indentLevel += 2; + showAtomPs4Audio3dVoicePoolConfig = EditorGUILayout.Foldout(showAtomPs4Audio3dVoicePoolConfig, "Audio 3D Voice Pool Config"); + if (showAtomPs4Audio3dVoicePoolConfig) { + EditorGUI.indentLevel += 1; + GenIntField("Memory Voices", "", ref initializer.atomConfig.ps4Audio3dConfig.voicePoolConfig.memoryVoices, 0, 256); + GenIntField("Streaming Voices", "", ref initializer.atomConfig.ps4Audio3dConfig.voicePoolConfig.streamingVoices, 0, 256); + EditorGUI.indentLevel -= 1; + } + EditorGUI.indentLevel -= 2; + EditorGUILayout.EndToggleGroup(); + } + + showAtomSwitchConfig = EditorGUILayout.Foldout(showAtomSwitchConfig, "Switch Config"); + if (showAtomSwitchConfig) { + EditorGUI.indentLevel += 1; + GenToggleField("Enable SonicSYNC", "", ref initializer.atomConfig.switchEnableSonicSync); + showAtomSwitchOpusVoicePoolConfig = EditorGUILayout.Foldout(showAtomSwitchOpusVoicePoolConfig, "Opus Voice Pool Config"); + if (showAtomSwitchOpusVoicePoolConfig) { + EditorGUI.indentLevel += 1; + GenIntField("Memory Voices", "", ref initializer.atomConfig.switchOpusVoicePoolConfig.memoryVoices, 0, 256); + GenIntField("Streaming Voices", "", ref initializer.atomConfig.switchOpusVoicePoolConfig.streamingVoices, 0, 256); + EditorGUI.indentLevel -= 1; + } + EditorGUI.indentLevel -= 1; + } + + showAtomWebGLConfig = EditorGUILayout.Foldout(showAtomWebGLConfig, "WebGL Config"); + if (showAtomWebGLConfig) { + EditorGUI.indentLevel += 1; + showAtomWebGLWebAudioVoicePoolConfig = EditorGUILayout.Foldout(showAtomWebGLWebAudioVoicePoolConfig, "WebAudio Voice Pool Config"); + if (showAtomWebGLWebAudioVoicePoolConfig) { + EditorGUI.indentLevel += 1; + GenIntField("Voices", "", ref initializer.atomConfig.webglWebAudioVoicePoolConfig.voices, 0, 32); + EditorGUI.indentLevel -= 1; + } + EditorGUI.indentLevel -= 1; + } + /* @endcond */ + } + EditorGUI.indentLevel -= 1; + EditorGUILayout.EndToggleGroup(); + + /* @cond excludele */ + // Mana Config + initializer.initializesMana = + EditorGUILayout.BeginToggleGroup("Initialize Mana", initializer.initializesMana); + EditorGUI.indentLevel += 1; + { + GenIntField("Number Of Decoders", "The maximum number of CriMana.Player component at a time. NOTE: Count as 2 when playing a movie with alpha channel.", + ref initializer.manaConfig.numberOfDecoders, 0, 128); + GenIntField("Number Of Max Entries", "", ref initializer.manaConfig.numberOfMaxEntries, 0, 1024); + + showManaVitaConfig = EditorGUILayout.Foldout(showManaVitaConfig, "PS Vita Config"); + if (showManaVitaConfig) { + EditorGUI.indentLevel += 1; + { + initializer.manaConfig.vitaH264PlaybackConfig.useH264Playback = + EditorGUILayout.BeginToggleGroup("H.264 Playback", initializer.manaConfig.vitaH264PlaybackConfig.useH264Playback); + EditorGUI.indentLevel += 1; + { + GenIntField("Max Width", "", ref initializer.manaConfig.vitaH264PlaybackConfig.maxWidth, 64, 1280); + GenIntField("Max Height", "", ref initializer.manaConfig.vitaH264PlaybackConfig.maxHeight, 64, 720); + GenToggleField("Get Memory From CDRAM", + "Let Mana H264 decoder use VRAM.\n" + + "This significantly boost decoding and drawing of movie textures. " + + "But It may takes longer to prepare the player depending movie size." + , ref initializer.manaConfig.vitaH264PlaybackConfig.getMemoryFromTexture); + } + EditorGUI.indentLevel -= 1; + EditorGUILayout.EndToggleGroup(); + } + EditorGUI.indentLevel -= 1; + } + + showManaWebGLConfig = EditorGUILayout.Foldout(showManaWebGLConfig, "WebGL Config"); + if (showManaWebGLConfig) { + EditorGUI.indentLevel += 1; + { + GenStringField("WebWorker Path", + "The directory path where sofdec2.worker.js is located.\n" + + "sofdec2.worker.js is generated in StreamingAssets at build time." + , ref initializer.manaConfig.webglConfig.webworkerPath); + GenIntFieldWithUnit("Heap Size" + ,"[MiB]" + ,"Set heap size.\n" + , ref initializer.manaConfig.webglConfig.heapSize + , 32 + , 512); + } + EditorGUI.indentLevel -= 1; + } + } + EditorGUI.indentLevel -= 1; + EditorGUILayout.EndToggleGroup(); + /* @endcond */ + + /* @cond excludele */ + // Decrypter Config + initializer.useDecrypter = + EditorGUILayout.BeginToggleGroup("Decrypter Settings", initializer.useDecrypter); + EditorGUI.indentLevel += 1; + { + initializer.decrypterConfig.key = + EditorGUILayout.TextField("Key Value", initializer.decrypterConfig.key); + GenStringField("Auth File Name", "", ref initializer.decrypterConfig.authenticationFile); + GenToggleField("Enable Atom Decryption", "", ref initializer.decrypterConfig.enableAtomDecryption); + GenToggleField("Enable Mana Decryption", "", ref initializer.decrypterConfig.enableManaDecryption); + } + EditorGUI.indentLevel -= 1; + EditorGUILayout.EndToggleGroup(); + /* @endcond */ + GenToggleField("Dont Initialize On Awake", "", ref initializer.dontInitializeOnAwake); + GenToggleField("Dont Destroy On Load", "", ref initializer.dontDestroyOnLoad); + } + if (GUI.changed) { + EditorUtility.SetDirty(initializer); + } + } +} // end of class + +} //namespace CriWare + +/* end of file */ \ No newline at end of file diff --git a/Assets/Scripts/CRIMW/CriWare/Editor/CriWareInitializerEditor.cs.meta b/Assets/Scripts/CRIMW/CriWare/Editor/CriWareInitializerEditor.cs.meta new file mode 100644 index 0000000..d185332 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Editor/CriWareInitializerEditor.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 3495d48c4496a8148ba10db9308bd557 +timeCreated: 1433816076 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Editor/CriWareVersionWindow.cs b/Assets/Scripts/CRIMW/CriWare/Editor/CriWareVersionWindow.cs new file mode 100644 index 0000000..41d6089 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Editor/CriWareVersionWindow.cs @@ -0,0 +1,720 @@ +/**************************************************************************** + * + * Copyright (c) 2014 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +using UnityEngine; +using UnityEditor; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Text.RegularExpressions; +using System.IO; + +namespace CriWare { + +public sealed class CriWareVersionWindow : EditorWindow +{ + List searchresult = new List(); + private readonly string[][] pluginBinaryFilenames = { + new string[]{"PC", "PCx64", "CRIWARE Monitor Unity", "x86_64/cri_ware_unity.dll"}, + new string[]{"PC", "PCx86", "CRIWARE Monitor Unity", "x86/cri_ware_unity.dll"}, + new string[]{"MacOSX", "Mac_X86_64", "CRIWARE Monitor Unity", "cri_ware_unity.bundle/Contents/MacOS/cri_ware_unity"}, + new string[]{"MacOSX", "Mac_ARMv8_A64", "CRIWARE Monitor Unity", "cri_ware_unity.bundle/Contents/MacOS/cri_ware_unity"}, + new string[]{"Android", "Android", "CRIWARE Monitor Unity", "Android/libs/arm64-v8a/libcri_ware_unity.so"}, + new string[]{"Android", "Android", "CRIWARE Monitor Unity", "Android/libs/armeabi-v7a/libcri_ware_unity.so"}, + new string[]{"Android", "Android", "CRIWARE Monitor Unity", "Android/libs/x86/libcri_ware_unity.so"}, + new string[]{"Android", "Android", "CRIWARE Monitor Unity", "Android/libs/x86_64/libcri_ware_unity.so"}, + new string[]{"iOS", "iOS_ARMv7", "CRIWARE Monitor Unity", "iOS/libcri_ware_unity.a"}, + new string[]{"iOS", "iOS_ARMv7s", "CRIWARE Monitor Unity", "iOS/libcri_ware_unity.a"}, + new string[]{"iOS", "iOS_ARMv8_A64", "CRIWARE Monitor Unity", "iOS/libcri_ware_unity.a"}, + new string[]{"iOS", "iOS_SIM_X86", "CRIWARE Monitor Unity", "iOS/libcri_ware_unity.a"}, + new string[]{"iOS", "iOS_SIM_X86_64", "CRIWARE Monitor Unity", "iOS/libcri_ware_unity.a"}, + /* @cond excludele */ + new string[]{"tvOS", "iOS_ARMv8_A64", "CRIWARE Monitor Unity", "tvOS/libcri_ware_unity.a"}, + new string[]{"tvOS", "iOS_SIM_X86_64", "CRIWARE Monitor Unity", "tvOS/libcri_ware_unity.a"}, + new string[]{"PS4", "PS4", "CRIWARE Monitor Unity", "PS4/cri_ware_unity.prx"}, + new string[]{"PS5", "PS5", "CRIWARE Monitor Unity", "PS5/cri_ware_unity.prx"}, + new string[]{"XboxOne", "XboxOne", "CRIWARE Monitor Unity", "XboxOne/cri_ware_unity.dll"}, + new string[]{"XboxOne", "XboxOne", "CRIWARE Monitor Unity", "GameCoreXboxOne/cri_ware_unity.dll"}, + new string[]{"Scarlett", "Scarlett", "CRIWARE Monitor Unity", "Scarlett/cri_ware_unity.dll"}, + new string[]{"Scarlett", "Scarlett", "CRIWARE Monitor Unity", "GameCoreScarlett/cri_ware_unity.dll"}, + new string[]{"SWITCH", "SWITCH", "CRIWARE Monitor Unity", "NX64/cri_ware_unity.a"}, + new string[]{"UWP", "WinRT ARM64", "CRIWARE Monitor Unity", "UWP/ARM64/cri_ware_unity.dll"}, + new string[]{"UWP", "WinRT ARM", "CRIWARE Monitor Unity", "UWP/ARM/cri_ware_unity.dll"}, + new string[]{"UWP", "WinRT x86", "CRIWARE Monitor Unity", "UWP/x86/cri_ware_unity.dll"}, + new string[]{"UWP", "WinRT x64", "CRIWARE Monitor Unity", "UWP/x64/cri_ware_unity.dll"}, + new string[]{"WebGL", "Emscripten", "CRIWARE Unity", "WebGL/cri_ware_unity.bc"}, + new string[]{"WebGL2", "Emscripten", "CRIWARE Unity", "WebGL2/cri_ware_unity.bc"}, + new string[]{"Linux", "LINUX_X86_64", "CRIWARE Unity", "x86_64/libcri_ware_unity.so"}, + new string[]{"Stadia", "LINUX_X86_64", "CRIWARE Unity", "GGP/cri_ware_unity.so"}, + /* @endcond */ + }; + + private readonly string[][] lipsBinaryFilenames = { + /* @cond excludele */ + new string[]{"PC", "PCx64", "CRI Lips Unity", "x86_64/cri_lips_unity.dll"}, + new string[]{"PC", "PCx86", "CRI Lips Unity", "x86/cri_lips_unity.dll"}, + new string[]{"MacOSX", "Mac_X86_64", "CRI Lips Unity", "cri_lips_unity.bundle/Contents/MacOS/cri_lips_unity"}, + new string[]{"MacOSX", "Mac_ARMv8_A64", "CRI Lips Unity", "cri_lips_unity.bundle/Contents/MacOS/cri_lips_unity"}, + new string[]{"Android", "Android", "CRI Lips Unity", "Android/libs/arm64-v8a/libcri_lips_unity.so"}, + new string[]{"Android", "Android", "CRI Lips Unity", "Android/libs/armeabi-v7a/libcri_lips_unity.so"}, + new string[]{"Android", "Android", "CRI Lips Unity", "Android/libs/x86/libcri_lips_unity.so"}, + new string[]{"Android", "Android", "CRI Lips Unity", "Android/libs/x86_64/libcri_lips_unity.so"}, + new string[]{"iOS", "iOS_ARMv7", "CRI Lips Unity", "iOS/libcri_lips_unity.a"}, + new string[]{"iOS", "iOS_ARMv7s", "CRI Lips Unity", "iOS/libcri_lips_unity.a"}, + new string[]{"iOS", "iOS_ARMv8_A64", "CRI Lips Unity", "iOS/libcri_lips_unity.a"}, + new string[]{"iOS", "iOS_SIM_X86", "CRI Lips Unity", "iOS/libcri_lips_unity.a"}, + new string[]{"iOS", "iOS_SIM_X86_64", "CRI Lips Unity", "iOS/libcri_lips_unity.a"}, + new string[]{"tvOS", "iOS_ARMv8_A64", "CRI Lips Unity", "tvOS/libcri_lips_unity.a"}, + new string[]{"tvOS", "iOS_SIM_X86_64", "CRI Lips Unity", "tvOS/libcri_lips_unity.a"}, + new string[]{"PS4", "PS4", "CRI Lips Unity", "PS4/cri_lips_unity.prx"}, + new string[]{"PS5", "PS5", "CRI Lips Unity", "PS5/cri_lips_unity.prx"}, + new string[]{"XboxOne", "XboxOne", "CRI Lips Unity", "XboxOne/cri_lips_unity.dll"}, + new string[]{"Scarlett", "Scarlett", "CRI Lips Unity", "Scarlett/cri_lips_unity.dll"}, + new string[]{"SWITCH", "SWITCH", "CRI Lips Unity", "NX64/cri_lips_unity.a"}, + /* @endcond */ + }; + + private readonly string[][] mcDspBinaryFilenames = { + /* @cond excludele */ + new string[]{"PC", "PCx64", "CRI AFX MCDSP", "x86_64/criafx_mcdsp.dll"}, + new string[]{"PC", "PCx86", "CRI AFX MCDSP", "x86/criafx_mcdsp.dll"}, + new string[]{"MacOSX", "Mac_X86_64", "CRI AFX MCDSP", "criafx_mcdsp.bundle/Contents/MacOS/criafx_mcdsp"}, + new string[]{"MacOSX", "Mac_ARMv8_A64", "CRI AFX MCDSP", "criafx_mcdsp.bundle/Contents/MacOS/criafx_mcdsp"}, + new string[]{"Android", "Android", "CRI AFX MCDSP", "Android/libs/arm64-v8a/libcriafx_mcdsp.so"}, + new string[]{"Android", "Android", "CRI AFX MCDSP", "Android/libs/armeabi-v7a/libcriafx_mcdsp.so"}, + new string[]{"Android", "Android", "CRI AFX MCDSP", "Android/libs/x86/libcriafx_mcdsp.so"}, + new string[]{"Android", "Android", "CRI AFX MCDSP", "Android/libs/x86_64/libcriafx_mcdsp.so"}, + new string[]{"iOS", "iOS_ARMv7", "CRI AFX MCDSP", "iOS/libcriafx_mcdsp.a"}, + new string[]{"iOS", "iOS_ARMv7s", "CRI AFX MCDSP", "iOS/libcriafx_mcdsp.a"}, + new string[]{"iOS", "iOS_ARMv8_A64", "CRI AFX MCDSP", "iOS/libcriafx_mcdsp.a"}, + new string[]{"iOS", "iOS_SIM_X86", "CRI AFX MCDSP", "iOS/libcriafx_mcdsp.a"}, + new string[]{"iOS", "iOS_SIM_X86_64", "CRI AFX MCDSP", "iOS/libcriafx_mcdsp.a"}, + new string[]{"tvOS", "iOS_ARMv8_A64", "CRI AFX MCDSP", "tvOS/libcriafx_mcdsp.a"}, + new string[]{"tvOS", "iOS_SIM_X86_64", "CRI AFX MCDSP", "tvOS/libcriafx_mcdsp.a"}, + new string[]{"PS4", "PS4", "CRI AFX MCDSP", "PS4/criafx_mcdsp.prx"}, + new string[]{"XboxOne", "XboxOne", "CRI AFX MCDSP", "XboxOne/criafx_mcdsp.dll"}, + new string[]{"SWITCH", "SWITCH", "CRI AFX MCDSP", "NX64/criafx_mcdsp.a" } + /* @endcond */ + }; + + private readonly string[][] vp9BinaryFilenames = { + /* @cond excludele */ + new string[]{"PC", "PCx64", "CRI Vpx", "x86_64/cri_mana_vpx.dll"}, + new string[]{"PC", "PCx86", "CRI Vpx", "x86/cri_mana_vpx.dll"}, + new string[]{"MacOSX", "Mac_X86_64", "CRI Vpx", "cri_mana_vpx.bundle/Contents/MacOS/cri_mana_vpx"}, + new string[]{"MacOSX", "Mac_ARMv8_A64", "CRI Vpx", "cri_mana_vpx.bundle/Contents/MacOS/cri_mana_vpx"}, + new string[]{"Android", "Android", "CRI Vpx", "Android/libs/arm64-v8a/libcri_mana_vpx.so"}, + new string[]{"Android", "Android", "CRI Vpx", "Android/libs/armeabi-v7a/libcri_mana_vpx.so"}, + new string[]{"Android", "Android", "CRI Vpx", "Android/libs/x86/libcri_mana_vpx.so"}, + new string[]{"Android", "Android", "CRI Vpx", "Android/libs/x86_64/libcri_mana_vpx.so"}, + new string[]{"iOS", "iOS_ARMv7", "CRI Vpx", "iOS/libcri_mana_vpx.a"}, + new string[]{"iOS", "iOS_ARMv7s", "CRI Vpx", "iOS/libcri_mana_vpx.a"}, + new string[]{"iOS", "iOS_ARMv8_A64", "CRI Vpx", "iOS/libcri_mana_vpx.a"}, + new string[]{"iOS", "iOS_SIM_X86", "CRI Vpx", "iOS/libcri_mana_vpx.a"}, + new string[]{"iOS", "iOS_SIM_X86_64", "CRI Vpx", "iOS/libcri_mana_vpx.a"}, + new string[]{"tvOS", "iOS_ARMv8_A64", "CRI Vpx", "tvOS/libcri_mana_vpx.a"}, + new string[]{"tvOS", "iOS_SIM_X86_64", "CRI Vpx", "tvOS/libcri_mana_vpx.a"}, + new string[]{"XboxOne", "XboxOne", "CRI Vpx", "XboxOne/cri_mana_vpx.dll"}, + new string[]{"Scarlett", "Scarlett", "CRI Vpx", "Scarlett/cri_mana_vpx.dll" } + /* @endcond */ + }; + + internal enum PluginType + { + CRIWARE = 0, + LIPS, + MCDSP, + VP9 + } + + private static readonly string[] pluginTypeName = { + "CRIWARE", + "LipSync", + "McDSP", + "VP9" + }; + + [Serializable] + internal class ModuleInfo + { + public string name; + public string target; + public string version; + public string buildDate; + public string appendix; + } + + [Serializable] + internal class PluginInfo + { + public string platform; + public string target; + public string path; + public ModuleInfo info; + public List moduleVersionInfos; + } + + [SerializeField] + private List pluginInfos; + internal List PluginInfos { + get { return pluginInfos; } + } + [SerializeField] + private int selectedInfoIndex = 0; + private string detailVersionsString = ""; + private string[] detailVersionsStrings = {""}; + private Vector2 detailViewScrollPosition = Vector2.zero; + private PluginType currentPluginType = PluginType.CRIWARE; + private string scriptVerionText = ""; + private bool asmDefSupport = true; + private bool hasDoubleByteChar = true; + + /* GUI用スタイル定義 */ + private readonly GUILayoutOption platformColumnWidth = GUILayout.Width(80); + private readonly GUILayoutOption targetColumnWidth = GUILayout.Width(120); + private readonly GUILayoutOption versionColumnWidth = GUILayout.Width(140); + private readonly GUILayoutOption buildDateColumnWidth = GUILayout.Width(200); + private readonly GUILayoutOption appendixColumnWidth = GUILayout.Width(200); + private readonly GUILayoutOption[] pathColumnWidth = {GUILayout.MinWidth(400), GUILayout.ExpandWidth(true)}; + + /* 詳細バージョン表示用等幅フォント定義 */ + static private Font _detailFont; + static private GUIStyle _detailStyle; + static private GUIStyle detailStyle { + get { + if (_detailFont == null) { + string fontname = ""; +#if UNITY_EDITOR_WIN + fontname = "Consolas"; +#elif UNITY_EDITOR_OSX + fontname = "Courier"; +#endif + _detailFont = Font.CreateDynamicFontFromOSFont(fontname, 12); + _detailStyle = null; + } + if (_detailStyle == null) { + _detailStyle = new GUIStyle(EditorStyles.largeLabel); + _detailStyle.font = _detailFont; + } + return _detailStyle; + } + } + + private string GetScriptVersion(PluginType type) + { + Assembly assembly = null; + this.asmDefSupport = true; + + try { + switch (type) { + case PluginType.CRIWARE: { assembly = Assembly.Load("CriMw.CriWare.Runtime"); break; } + case PluginType.LIPS: { assembly = Assembly.Load("CriMw.CriWare.Adxlipsync.Runtime"); break; } + case PluginType.MCDSP: { assembly = Assembly.Load("CriMw.CriWare.Mcdsp.Runtime"); break; } + case PluginType.VP9: { assembly = Assembly.Load("CriMw.CriWare.Vp9.Runtime"); break; } + default: break; + } + } catch { + this.asmDefSupport = false; + try { + assembly = Assembly.Load("Assembly-CSharp-firstpass"); + } catch { + try { + assembly = Assembly.Load("Assembly-CSharp"); + } catch { + return null; + } + } + } + + try { + switch (type) { + case PluginType.CRIWARE: return (string)assembly.GetType("CriWare.Common").GetField("scriptVersionString", BindingFlags.NonPublic | BindingFlags.Static).GetValue(null); + case PluginType.LIPS: return (string)assembly.GetType(asmDefSupport ? "CriWare.CriLipsPlugin" : "CriLipsPlugin").GetField("scriptVersionString", BindingFlags.NonPublic | BindingFlags.Static).GetValue(null); + case PluginType.MCDSP: return (string)assembly.GetType(asmDefSupport ? "CriWare.CriAfxMcDspInitializer" : "CriAfxMcDspInitializer").GetField("scriptVersionString", BindingFlags.NonPublic | BindingFlags.Static).GetValue(null); + case PluginType.VP9: return (string)assembly.GetType(asmDefSupport ? "CriWare.CriManaVp9" : "CriManaVp9").GetField("scriptVersionString", BindingFlags.NonPublic | BindingFlags.Static).GetValue(null); + default: return null; + } + } catch { + return null; + } + } + + private string ScriptVersionFullText { + get { + return "Ver." + (this.scriptVerionText ?? " (not available)") + " " + (asmDefSupport ? " (with Assembly Definition)" : "") + (hasDoubleByteChar ? " [J]" : " [E]"); + } + } + + private string GetSearchRule(PluginType type) + { + switch(type) { + case PluginType.CRIWARE: return "t:DefaultAsset cri_ware_unity"; + case PluginType.LIPS: return "t:DefaultAsset cri_lips_unity"; + case PluginType.MCDSP: return "t:DefaultAsset criafx_mcdsp"; + case PluginType.VP9: return "t:DefaultAsset cri_mana_vpx"; + default: return "t:DefaultAsset"; + } + } + + private string[][] GetSearchInfo(PluginType type) + { + switch(type) { + case PluginType.CRIWARE: return pluginBinaryFilenames; + case PluginType.LIPS: return lipsBinaryFilenames; + case PluginType.MCDSP: return mcDspBinaryFilenames; + case PluginType.VP9: return vp9BinaryFilenames; + default: return null; + } + } + + private bool HasDoubleByteChar(PluginType type) { + const bool DefaultResult = false; + + string searchKeyword; + switch (type) { + case PluginType.CRIWARE: { searchKeyword = "CriWare"; break; } + case PluginType.LIPS: { searchKeyword = "CriLips"; break; } + case PluginType.MCDSP: { searchKeyword = "CriAfxMcDspInitializer"; break; } + case PluginType.VP9: { searchKeyword = "CriManaVp9"; break; } + default: { searchKeyword = "CriWare"; break; } + } + string exactRegEx = "[\\/]" + searchKeyword + ".cs"; + searchKeyword = "t:Script " + searchKeyword; + + string[] searchResGuid = AssetDatabase.FindAssets(searchKeyword); + if (searchResGuid == null || searchResGuid.Length <= 0) { return DefaultResult; } + var exactResGuid = searchResGuid.Where(item => Regex.IsMatch(AssetDatabase.GUIDToAssetPath(item), exactRegEx)); + if (exactResGuid.Count() <= 0) { return DefaultResult; } + + string filePath = AssetDatabase.GUIDToAssetPath(exactResGuid.First()); + var lines = File.ReadAllLines(filePath).Where(line => line.Contains("")); + if (lines.Count() > 0) { + return Regex.IsMatch(lines.First(), "[^\x01-\x7E]"); + } else { + return DefaultResult; + } + } + + + [MenuItem("Window/CRIWARE/Version Information", false, 200)] + static void OpenWindow() + { + EditorWindow.GetWindow(false, "CRI Versions"); + } + + private struct TargetInfo + { + public TargetInfo(string Path, string[] Info) + { + path = Path; + info = Info; + } + + public string path; + public string[] info; + } + + private string[] GenerateStock(string libName) + { + return AssetDatabase.FindAssets(libName); + } + + private List SearchItem(string[] stock, string[][] targetList) + { + List result = new List(); + foreach (string[] target in targetList) { + foreach (string path in stock) { + string strPath = AssetDatabase.GUIDToAssetPath(path).Replace("\\", "/"); + if (strPath.Contains("/" + target[3])) { + if (target[0] == "PC" && strPath.Contains("UWP")) { + continue; + } + result.Add(new TargetInfo(strPath, target)); + break; + } + } + } + return result; + } + + private void OnEnable() + { + Reload(currentPluginType); + } + + private void OnGUI() + { + using (var scope = new EditorGUILayout.HorizontalScope()) { + currentPluginType = PluginType.CRIWARE; + /* @cond excludele */ + currentPluginType = (PluginType)GUILayout.Toolbar((int)currentPluginType, pluginTypeName); + /* @endcond */ + if (GUI.changed) { + selectedInfoIndex = 0; + Reload(currentPluginType, true); + } + EditorGUILayout.Space(); + if (GUILayout.Button("Copy to Clipboard", GUILayout.Width(180))) { + var clipboardText = PluginVersionsString(); + if (string.IsNullOrEmpty(clipboardText) == false ) { + EditorGUIUtility.systemCopyBuffer = clipboardText; + Debug.Log("[CRIWARE] Plugin version informations have been copied to the clipboard."); + GUI.FocusControl(""); + } + } + if (GUILayout.Button("Reload", GUILayout.Width(80))) { + Reload(currentPluginType, true); + GUI.FocusControl(""); + } + } + + EditorGUILayout.Space(); + + EditorGUILayout.LabelField(((int)currentPluginType > 0 ? pluginTypeName[(int)currentPluginType] + " Expansion " : "") + "Script Version"); + + /* スクリプトバージョン表示 */ + EditorGUI.indentLevel++; + { + EditorGUILayout.LabelField(this.ScriptVersionFullText); + } + EditorGUI.indentLevel--; + + EditorGUILayout.Space(); + + /* バイナリバージョン表示 */ + EditorGUILayout.LabelField(((int)currentPluginType > 0 ? pluginTypeName[(int)currentPluginType] + " Expansion " : "") + "Binary Version"); + + /* プラットフォーム別プラグインバイナリバージョン表示 */ + if (pluginInfos != null) { + for (int i = 0; i < pluginInfos.Count; ++i) { + using (var scope = new EditorGUILayout.HorizontalScope()) { + EditorGUILayout.LabelField("", GUILayout.Width(15)); + var tempColor = GUI.color; + if (i == selectedInfoIndex) { + GUI.color = Color.yellow; + } + if (GUILayout.Button(pluginInfos[i].platform, EditorStyles.miniButton, platformColumnWidth)) { + /* 表示の制限のため表示可能な文字数で切り出す */ + detailVersionsString = ModuleInfosToAlignedString(pluginInfos[i].moduleVersionInfos); + detailVersionsStrings = SplitTextAreaMaxLength(detailVersionsString); + selectedInfoIndex = i; + detailViewScrollPosition = new Vector2(0.0f, 0.0f); + GUI.FocusControl(""); + } + if (i == selectedInfoIndex) { + GUI.color = tempColor; + } + + if (pluginInfos[i].info != null) { + EditorGUILayout.LabelField((pluginInfos[i].target ?? "--"), targetColumnWidth); + EditorGUILayout.LabelField((pluginInfos[i].info.version ?? "--"), versionColumnWidth); + EditorGUILayout.LabelField((pluginInfos[i].info.buildDate ?? "--"), buildDateColumnWidth); + EditorGUILayout.LabelField((pluginInfos[i].info.appendix ?? "--"), appendixColumnWidth); + } else { + EditorGUILayout.LabelField("--", targetColumnWidth); + EditorGUILayout.LabelField("--", versionColumnWidth); + EditorGUILayout.LabelField("--", buildDateColumnWidth); + EditorGUILayout.LabelField("--", appendixColumnWidth); + } + + EditorGUILayout.LabelField(pluginInfos[i].path, pathColumnWidth); + } + } + } + + EditorGUILayout.Space(); + + /* 詳細バージョン情報表示 */ + using (var scope = new EditorGUILayout.HorizontalScope()) { + EditorGUILayout.LabelField("Details [ " + (pluginInfos.Count > selectedInfoIndex ? pluginInfos[selectedInfoIndex].platform + " / " + pluginInfos[selectedInfoIndex].target : "") + " ]", GUILayout.ExpandWidth(true)); + if (GUILayout.Button("Copy Details to Clipboard", GUILayout.Width(180)) && string.IsNullOrEmpty(detailVersionsString) == false) { + EditorGUIUtility.systemCopyBuffer = detailVersionsString; + Debug.Log("[CRIWARE] Plugin version details have been copied to the clipboard."); + GUI.FocusControl(""); + } + } + + using (var scope = new EditorGUILayout.ScrollViewScope(detailViewScrollPosition, EditorStyles.textArea)) { + detailViewScrollPosition = scope.scrollPosition; + if (pluginInfos.Count > selectedInfoIndex) { + foreach (var item in detailVersionsStrings) { + GUILayout.TextArea(item, detailStyle); + } + } else { + GUILayout.TextArea("No library has been found. This plugin may not have been installed.\n", detailStyle); + } + } + } + + + internal void Reload(PluginType type, bool forceRefresh = false) + { + this.scriptVerionText = GetScriptVersion(currentPluginType); + this.hasDoubleByteChar = HasDoubleByteChar(currentPluginType); + + string[] searchedResultStock = GenerateStock(GetSearchRule(type)); + this.searchresult = SearchItem(searchedResultStock, GetSearchInfo(type)); + + if (forceRefresh == false && pluginInfos != null) { return; } + + pluginInfos = LoadPluginInfos(searchresult); + if (pluginInfos.Count > 0) { + /* 表示の制限のため表示可能な文字数で切り出す */ + detailVersionsString = ModuleInfosToAlignedString(pluginInfos[0].moduleVersionInfos); + detailVersionsStrings = SplitTextAreaMaxLength(detailVersionsString); + } else { + detailVersionsString = ""; + detailVersionsStrings = new string[]{""}; + } + detailViewScrollPosition = new Vector2(0.0f, 0.0f); + } + + + private string PluginVersionsString() + { + if (pluginInfos == null || pluginInfos.Count <= 0) { return null; } + + string[] moduleInfoStrings; + try { + moduleInfoStrings = ModuleInfosToAlignedString( + (from item in pluginInfos select item.info).ToList() + ).Split(new string[]{System.Environment.NewLine}, System.StringSplitOptions.None); + } catch (Exception e) { + Debug.LogError("[CRIWARE] Internal/VersionWindow: Exception on getting version strings for clipboard / Message: " + e.Message); + return null; + } + + int platformLength = pluginInfos.Max(item => (item != null) ? item.platform.Length : 0); + string platformFormat = string.Format("{{0,-{0}}} ", platformLength); + + string s = ""; + s += ((int)currentPluginType > 0 ? pluginTypeName[(int)currentPluginType] + " Expansion" : "CRIWARE Unity Plugin") + " Script Version" + System.Environment.NewLine + + " " + this.ScriptVersionFullText + + System.Environment.NewLine + System.Environment.NewLine + + ((int)currentPluginType > 0 ? pluginTypeName[(int)currentPluginType] + " Expansion" : "CRIWARE Unity Plugin") + " Binary Version" + System.Environment.NewLine; + for (int i = 0; i < pluginInfos.Count; i++) { + s += " " + string.Format(platformFormat, pluginInfos[i].platform) + moduleInfoStrings[i] + System.Environment.NewLine; + } + + return s; + } + + + private static string ModuleInfosToAlignedString(List infos) + { + int nameLength = 0; + int targetLength = 0; + int versionLength = 0; + int buildDateLength = 0; + int appendixLength = 0; + foreach (var info in infos) { + if (info != null) { + nameLength = System.Math.Max(nameLength, ((info.name != null) ? info.name.Length : 0)); + targetLength = System.Math.Max(targetLength , ((info.target != null) ? info.target.Length : 0)); + versionLength = System.Math.Max(versionLength, ((info.version != null) ? info.version.Length : 0)); + buildDateLength = System.Math.Max(buildDateLength, ((info.buildDate != null) ? info.buildDate.Length : 0)); + appendixLength = System.Math.Max(appendixLength, ((info.appendix != null) ? info.appendix.Length : 0)); + } + } + string format = string.Format( + "{{0,-{0}}} {{1,-{1}}} {{2,-{2}}} {{3,-{3}}} {{4,-{4}}}" + System.Environment.NewLine, + nameLength, targetLength, versionLength, buildDateLength, appendixLength + ); + string s = ""; + foreach (var info in infos) { + if (info != null) { + s += string.Format(format, info.name, info.target, info.version, info.buildDate, info.appendix); + } else { + s += string.Format(format, "--", "--", "--", "--", "--"); + } + } + return s; + } + + + private static string[] SplitTextAreaMaxLength(string s) + { + const int textAreaMaxLength = 16000; + + List stringList = new List(); + int currentPos = 0; + while(currentPos < s.Length) { + if (currentPos + textAreaMaxLength >= s.Length) { + string subString = s.Substring(currentPos, s.Length - currentPos); + stringList.Add(subString); + break; + } else { + string subString = s.Substring(currentPos, textAreaMaxLength); + int lineEnd = subString.LastIndexOf("\n", StringComparison.Ordinal); + if (lineEnd >= 0) { + subString = subString.Substring(0, lineEnd); + currentPos++; // ignore last line end + } + stringList.Add(subString); + currentPos += subString.Length; + } + } + + return stringList.ToArray(); + } + + + private static List LoadPluginInfos(List targetInfos) + { + var pluginInfos = new List(); + int itemCnt = targetInfos.Count; + int currentCnt = 0; + foreach (var item in targetInfos) { + EditorUtility.DisplayProgressBar("Gathering Information", "Getting library information for " + item.info[1], currentCnt / (float)itemCnt); + try { + var path = item.path; + var moduleVersionInfos = LoadModuleInfos(path, item.info); + if (moduleVersionInfos != null) { + var info = new PluginInfo(); + info.moduleVersionInfos = moduleVersionInfos; + info.info = info.moduleVersionInfos.Find((minfo) => minfo.target.Contains(item.info[1]) && (minfo.name.Contains(item.info[2]))); + if (info.info != null) { + info.platform = item.info[0]; + info.target = info.info.target; + info.path = item.path; + pluginInfos.Add(info); + } + } + currentCnt++; + } catch (Exception e) { + Debug.LogError("[CRIWARE] Internal/VersionWindow: Exception on getting information from " + item.info[3] + " / Message: " + e.Message); + } + } + EditorUtility.ClearProgressBar(); + return pluginInfos; + } + + + private static List LoadModuleInfos(string path, string[] targetInfo) + { + if (!System.IO.File.Exists(path)) { + return null; + } + + var bytes = System.IO.File.ReadAllBytes(path); + if (System.IO.Path.GetExtension(path) == ".bc") { + return LoadModuleInfosWithBitShift(bytes, targetInfo); + } else { + return LoadModuleInfos(bytes, targetInfo); + } + } + + + private static List LoadModuleInfos(byte[] bytes, string[] targetInfo) + { + var data = System.Text.Encoding.ASCII.GetString(bytes); + var infos = new List(); + + var versionRegex = new System.Text.RegularExpressions.Regex("^([^/]+)(?:/(.+))? (Ver\\..+) (Build:(?:.*))$"); + var versionAppendixRegex = new System.Text.RegularExpressions.Regex("^Append: (.*)$"); + + /* Get informations only if the target name is exactly the same. For libraries with multiple targets in a single file. */ + bool checkTargetEquality = targetInfo[0].Equals("iOS") || targetInfo[0].Equals("tvOS") || targetInfo[0].Equals("MacOSX"); + + int pos = 0; + while (true) { + pos = data.IndexOf(" Build:", pos, StringComparison.Ordinal); + if (pos == -1) { + break; + } + ++pos; + { + int beginPos = FindNonPrintableCharBackward(data, pos); + int endPos = FindNonPrintableCharFoward(data, pos); + if ((data[beginPos] != '\n') || (data[endPos] != '\n')) { + continue; + } + ++beginPos; + var s = data.Substring(beginPos, (endPos - beginPos)); + var match = versionRegex.Match(s); + if (!match.Success) { + continue; + } + var info = new ModuleInfo(); + info.name = match.Groups[1].Value; + info.target = match.Groups[2].Value; + info.version = match.Groups[3].Value; + info.buildDate = match.Groups[4].Value; + if (checkTargetEquality + && !info.target.Contains(' ') + && !info.target.Equals(targetInfo[1])) { + continue; + } + /* Appendix */ + if ((endPos + 2) < data.Length) { + int appendisBeginPos = endPos + 1; + int appendixEndPos = FindNonPrintableCharFoward(data, appendisBeginPos + 1); + if ((data[appendisBeginPos] != '\0') || (data[appendixEndPos] != '\n')) { + } else { + ++appendisBeginPos; + s = data.Substring(appendisBeginPos, (appendixEndPos - appendisBeginPos)); + match = versionAppendixRegex.Match(s); + if (match.Success) { + info.appendix = match.Groups[1].Value; + } + } + } + infos.Add(info); + } + } + + /* モジュール情報をモジュール名順にソート */ + infos.Sort((x, y) => x.name.CompareTo(y.name) ); + + return infos; + } + + + private static List LoadModuleInfosWithBitShift(byte[] bytes, string[] targetInfo) + { + var infos = LoadModuleInfos(bytes, targetInfo); + + for (int shift = 1; shift <= 7; shift++) { + int rshift = 8 - shift; + byte[] shifted = new byte[bytes.Length + 1]; + for (int i = 0; i < bytes.Length; i++) { + shifted[i] |= (byte)((bytes[i] << shift)); + shifted[i + 1] |= (byte)(bytes[i] >> rshift); + } + infos.AddRange(LoadModuleInfos(shifted, targetInfo)); + } + + /* モジュール情報をモジュール名順にソート */ + infos.Sort((x, y) => x.name.CompareTo(y.name) ); + + return infos; + } + + + private static int FindNonPrintableCharBackward(string s, int index) + { + for (; index >= 0; --index) { + if ((s[index] < 32) || (s[index] > 126)) { + break; + } + } + return index; + } + + + private static int FindNonPrintableCharFoward(string s, int index) + { + for (; index < s.Length; index++) { + if ((s[index] < 32) || (s[index] > 126)) { + break; + } + } + return index; + } +} + +} //namespace CriWare \ No newline at end of file diff --git a/Assets/Scripts/CRIMW/CriWare/Editor/CriWareVersionWindow.cs.meta b/Assets/Scripts/CRIMW/CriWare/Editor/CriWareVersionWindow.cs.meta new file mode 100644 index 0000000..9d467d2 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Editor/CriWareVersionWindow.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 4cb38bf522cf7074c8fdf1c88cf79463 +timeCreated: 1433816076 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Editor/Internal.meta b/Assets/Scripts/CRIMW/CriWare/Editor/Internal.meta new file mode 100644 index 0000000..d4ada12 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Editor/Internal.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: b6c0e84fa4127e24db13d5dab4398e7b +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Editor/Internal/CriEditorUtilitiesInternal.cs b/Assets/Scripts/CRIMW/CriWare/Editor/Internal/CriEditorUtilitiesInternal.cs new file mode 100644 index 0000000..9cbd00f --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Editor/Internal/CriEditorUtilitiesInternal.cs @@ -0,0 +1,46 @@ +/**************************************************************************** + * + * Copyright (c) 2021 CRI Middleware Co., Ltd. + * + ****************************************************************************/ +#if UNITY_2019_3_OR_NEWER +using System.Collections.Generic; +using UnityEditor; +using System.Linq; +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("CriMw.CriWare.Adxlipsync.Editor")] +[assembly: InternalsVisibleTo("CriMw.CriWare.Assets.Editor")] + +namespace CriWare { + + internal static class CriEditorUtilitiesInternal + { + public static float SingleReturnHeight + { + get + { + return EditorGUIUtility.singleLineHeight + 2f; + } + } + + public static string BackingFieldNameOf(string propertyName) + { + return "<" + propertyName + ">k__BackingField"; + } + + static Dictionary> typesCache = new Dictionary>(); + public static List GetSubclassesOf(System.Type baseType) + { + if (typesCache.ContainsKey(baseType)) + return typesCache[baseType]; + + var types = System.AppDomain.CurrentDomain.GetAssemblies().SelectMany(assem => assem.GetTypes()). + Where(t => baseType.IsAssignableFrom(t) && !(t == baseType)).ToList(); + typesCache.Add(baseType, types); + return types; + } + } +} //namespace CriWare + +#endif \ No newline at end of file diff --git a/Assets/Scripts/CRIMW/CriWare/Editor/Internal/CriEditorUtilitiesInternal.cs.meta b/Assets/Scripts/CRIMW/CriWare/Editor/Internal/CriEditorUtilitiesInternal.cs.meta new file mode 100644 index 0000000..20fc432 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Editor/Internal/CriEditorUtilitiesInternal.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e42361bfebaaf4deabdbc39094e45f1d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Icons.meta b/Assets/Scripts/CRIMW/CriWare/Icons.meta new file mode 100644 index 0000000..a42d447 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Icons.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 0868a9b55b2e51a40bbc1ac416ae821e +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Icons/Listener.png b/Assets/Scripts/CRIMW/CriWare/Icons/Listener.png new file mode 100644 index 0000000..3e71a29 Binary files /dev/null and b/Assets/Scripts/CRIMW/CriWare/Icons/Listener.png differ diff --git a/Assets/Scripts/CRIMW/CriWare/Icons/Listener.png.meta b/Assets/Scripts/CRIMW/CriWare/Icons/Listener.png.meta new file mode 100644 index 0000000..ba80b16 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Icons/Listener.png.meta @@ -0,0 +1,92 @@ +fileFormatVersion: 2 +guid: 54b14f2540d554f4c9bafa3501e6dc9f +TextureImporter: + internalIDToNameTable: [] + externalObjects: {} + serializedVersion: 11 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + sRGBTexture: 1 + linearTexture: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapsPreserveCoverage: 0 + alphaTestReferenceValue: 0.5 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: 0.25 + normalMapFilter: 0 + isReadable: 0 + streamingMipmaps: 0 + streamingMipmapsPriority: 0 + grayScaleToAlpha: 0 + generateCubemap: 6 + cubemapConvolution: 0 + seamlessCubemap: 0 + textureFormat: 1 + maxTextureSize: 2048 + textureSettings: + serializedVersion: 2 + filterMode: -1 + aniso: -1 + mipBias: -100 + wrapU: -1 + wrapV: -1 + wrapW: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: 0.5, y: 0.5} + spritePixelsToUnits: 100 + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spriteGenerateFallbackPhysicsShape: 1 + alphaUsage: 1 + alphaIsTransparency: 0 + spriteTessellationDetail: -1 + textureType: 0 + textureShape: 1 + singleChannelComponent: 0 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + applyGammaDecoding: 0 + platformSettings: + - serializedVersion: 3 + buildTarget: DefaultTexturePlatform + maxTextureSize: 2048 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + spriteSheet: + serializedVersion: 2 + sprites: [] + outline: [] + physicsShape: [] + bones: [] + spriteID: + internalID: 0 + vertices: [] + indices: + edges: [] + weights: [] + secondaryTextures: [] + spritePackingTag: + pSDRemoveMatte: 0 + pSDShowRemoveMatteOption: 0 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Icons/Transceiver.png b/Assets/Scripts/CRIMW/CriWare/Icons/Transceiver.png new file mode 100644 index 0000000..53b05d3 Binary files /dev/null and b/Assets/Scripts/CRIMW/CriWare/Icons/Transceiver.png differ diff --git a/Assets/Scripts/CRIMW/CriWare/Icons/Transceiver.png.meta b/Assets/Scripts/CRIMW/CriWare/Icons/Transceiver.png.meta new file mode 100644 index 0000000..8f16e26 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Icons/Transceiver.png.meta @@ -0,0 +1,91 @@ +fileFormatVersion: 2 +guid: 092d44bfa808b4645826d36c43846fa4 +TextureImporter: + internalIDToNameTable: [] + externalObjects: {} + serializedVersion: 10 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + sRGBTexture: 1 + linearTexture: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapsPreserveCoverage: 0 + alphaTestReferenceValue: 0.5 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: 0.25 + normalMapFilter: 0 + isReadable: 0 + streamingMipmaps: 0 + streamingMipmapsPriority: 0 + grayScaleToAlpha: 0 + generateCubemap: 6 + cubemapConvolution: 0 + seamlessCubemap: 0 + textureFormat: 1 + maxTextureSize: 2048 + textureSettings: + serializedVersion: 2 + filterMode: -1 + aniso: -1 + mipBias: -100 + wrapU: -1 + wrapV: -1 + wrapW: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: 0.5, y: 0.5} + spritePixelsToUnits: 100 + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spriteGenerateFallbackPhysicsShape: 1 + alphaUsage: 1 + alphaIsTransparency: 0 + spriteTessellationDetail: -1 + textureType: 0 + textureShape: 1 + singleChannelComponent: 0 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + platformSettings: + - serializedVersion: 3 + buildTarget: DefaultTexturePlatform + maxTextureSize: 2048 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + androidETC2FallbackOverride: 0 + forceMaximumCompressionQuality_BC6H_BC7: 0 + spriteSheet: + serializedVersion: 2 + sprites: [] + outline: [] + physicsShape: [] + bones: [] + spriteID: + internalID: 0 + vertices: [] + indices: + edges: [] + weights: [] + secondaryTextures: [] + spritePackingTag: + pSDRemoveMatte: 0 + pSDShowRemoveMatteOption: 0 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Icons/VoiceOn.png b/Assets/Scripts/CRIMW/CriWare/Icons/VoiceOn.png new file mode 100644 index 0000000..c3c0842 Binary files /dev/null and b/Assets/Scripts/CRIMW/CriWare/Icons/VoiceOn.png differ diff --git a/Assets/Scripts/CRIMW/CriWare/Icons/VoiceOn.png.meta b/Assets/Scripts/CRIMW/CriWare/Icons/VoiceOn.png.meta new file mode 100644 index 0000000..9249600 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Icons/VoiceOn.png.meta @@ -0,0 +1,55 @@ +fileFormatVersion: 2 +guid: c7b655dd5eeac7b489f2ddd1304fb5f4 +timeCreated: 1433816082 +licenseType: Pro +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + cubemapConvolution: 0 + cubemapConvolutionSteps: 8 + cubemapConvolutionExponent: 1.5 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 2048 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + rGBM: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Icons/film.png b/Assets/Scripts/CRIMW/CriWare/Icons/film.png new file mode 100644 index 0000000..5709501 Binary files /dev/null and b/Assets/Scripts/CRIMW/CriWare/Icons/film.png differ diff --git a/Assets/Scripts/CRIMW/CriWare/Icons/film.png.meta b/Assets/Scripts/CRIMW/CriWare/Icons/film.png.meta new file mode 100644 index 0000000..635872a --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Icons/film.png.meta @@ -0,0 +1,55 @@ +fileFormatVersion: 2 +guid: a4c14449c19b8f346be66595b3db44ff +timeCreated: 1433816082 +licenseType: Pro +TextureImporter: + fileIDToRecycleName: {} + serializedVersion: 2 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + linearTexture: 0 + correctGamma: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: .25 + normalMapFilter: 0 + isReadable: 0 + grayScaleToAlpha: 0 + generateCubemap: 0 + cubemapConvolution: 0 + cubemapConvolutionSteps: 8 + cubemapConvolutionExponent: 1.5 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 2048 + textureSettings: + filterMode: -1 + aniso: -1 + mipBias: -1 + wrapMode: -1 + nPOTScale: 1 + lightmap: 0 + rGBM: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: .5, y: .5} + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spritePixelsToUnits: 100 + alphaIsTransparency: 0 + textureType: -1 + buildTargetSettings: [] + spriteSheet: + sprites: [] + spritePackingTag: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime.meta b/Assets/Scripts/CRIMW/CriWare/Runtime.meta new file mode 100644 index 0000000..15c5f43 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 15971ef3a8b088e4f89db2ff3f82d0e8 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/CriMw.CriWare.Runtime.asmdef b/Assets/Scripts/CRIMW/CriWare/Runtime/CriMw.CriWare.Runtime.asmdef new file mode 100644 index 0000000..836097a --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/CriMw.CriWare.Runtime.asmdef @@ -0,0 +1,21 @@ +{ + "name": "CriMw.CriWare.Runtime", + "references": [ + "Unity.Timeline" + ], + "optionalUnityReferences": [], + "includePlatforms": [], + "excludePlatforms": [], + "allowUnsafeCode": false, + "overrideReferences": false, + "precompiledReferences": [], + "autoReferenced": true, + "defineConstraints": [], + "versionDefines": [ + { + "name": "com.unity.timeline", + "expression": "1.0.0", + "define": "CRIWARE_TIMELINE_1_OR_NEWER" + } + ] +} \ No newline at end of file diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/CriMw.CriWare.Runtime.asmdef.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/CriMw.CriWare.Runtime.asmdef.meta new file mode 100644 index 0000000..b688f11 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/CriMw.CriWare.Runtime.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 800597811bcc5d848b15e12807d6de45 +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms.meta new file mode 100644 index 0000000..08a28bb --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 2aec2f381367b8e4897166bdbe92fb9b +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android.meta new file mode 100644 index 0000000..92d7479 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 0513e446cdd53d344b6394b88cec50fb +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/CriMana.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/CriMana.meta new file mode 100644 index 0000000..7a98446 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/CriMana.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 3c1f75350d960914cb70909e86065ca3 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/CriMana/Detail.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/CriMana/Detail.meta new file mode 100644 index 0000000..1de134e --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/CriMana/Detail.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 497dbcc8f29bc4f4491b76ffb68daeca +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/CriMana/Detail/RendererResources.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/CriMana/Detail/RendererResources.meta new file mode 100644 index 0000000..d73def3 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/CriMana/Detail/RendererResources.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: b4f3b826ae7019f4cbc0122e140dda20 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/CriMana/Detail/RendererResources/AndroidH264Rgb.cs b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/CriMana/Detail/RendererResources/AndroidH264Rgb.cs new file mode 100644 index 0000000..742bec0 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/CriMana/Detail/RendererResources/AndroidH264Rgb.cs @@ -0,0 +1,356 @@ +/**************************************************************************** + * + * Copyright (c) 2018 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +#if !UNITY_EDITOR && UNITY_ANDROID + +using UnityEngine; +using System.Runtime.InteropServices; + +namespace CriWare { + +namespace CriMana.Detail +{ + public static partial class AutoResisterRendererResourceFactories + { + [RendererResourceFactoryPriority(7000)] + public class RendererResourceFactoryAndroidH264Rgb : RendererResourceFactory + { + public override RendererResource CreateRendererResource(int playerId, MovieInfo movieInfo, bool additive, Shader userShader) + { + bool isCodecSuitable = movieInfo.codecType == CodecType.H264 && !CriManaPlugin.criManaUnity_IsBufferOutputForH264Enabled_ANDROID(); + bool isGraphicsApiSuitable = (UnityEngine.SystemInfo.graphicsDeviceType != UnityEngine.Rendering.GraphicsDeviceType.Vulkan); + bool isSuitable = isCodecSuitable && isGraphicsApiSuitable; + return isSuitable + ? new RendererResourceAndroidH264Rgb(playerId, movieInfo, additive, userShader) + : null; + } + + protected override void OnDisposeManaged() + { + } + + protected override void OnDisposeUnmanaged() + { + } + } + } + + + + + public class RendererResourceAndroidH264Rgb : RendererResource + { + private const int RenderEventAction_ATTACH = (int)Player.CriManaUnityPlayer_RenderEventAction.DESTROY + 1; + + private int playerId; + + private int width; + private int height; + private int dispWidth; + private int dispHeight; + private int alphaWidth; + private int alphaHeight; + private bool useUserShader; + + private Vector4 movieTextureST = new Vector4(1, -1, 0, 1); + private Vector4 alphaTextureST = Vector4.zero; + private Texture2D[] textures; + private System.IntPtr[] nativePtrs = new System.IntPtr[1]; + + private bool needsUpdateTexture = false; + private bool needsToDetachInitTexture = false; + private bool areTexturesUpdated = false; + + private bool isStoppingForSeek = false; + private bool isStartTriggered = true; + private System.UInt32 nativeTextureId; + + public RendererResourceAndroidH264Rgb(int playerId, MovieInfo movieInfo, bool additive, Shader userShader) + { + this.playerId = playerId; + width = (int)movieInfo.width; + height = (int)movieInfo.height; + dispWidth = (int)movieInfo.dispWidth; + dispHeight = (int)movieInfo.dispHeight; + + hasAlpha = movieInfo.hasAlpha; + if (hasAlpha) { + alphaWidth = Ceiling32(Ceiling16(CeilingWith(width, 8))); + alphaHeight = CeilingWith(height, 16); + } + this.additive = additive; + useUserShader = userShader != null; + + if (userShader != null) { + shader = userShader; + } else { + string shaderName = "CriMana/AndroidH264Rgb"; + shader = Shader.Find(shaderName); + } + } + + protected override void OnDisposeManaged() + { + } + + protected override void OnDisposeUnmanaged() + { + DisposeTextures(textures); + textures = null; + } + + public override bool IsPrepared() + { return true; } + + public override bool ContinuePreparing() + { return true; } + + public override bool IsSuitable(int playerId, MovieInfo movieInfo, bool additive, Shader userShader) + { + bool isPlayerSuitable = playerId == this.playerId; + bool isCodecSuitable = movieInfo.codecType == CodecType.H264; + bool isSizeSuitable = (width == (int)movieInfo.width) && (height == (int)movieInfo.height); + bool isAlphaSuitable = hasAlpha == movieInfo.hasAlpha; + bool isAdditiveSuitable = this.additive == additive; + bool isShaderSuitable = this.useUserShader ? (userShader == shader) : true; + return isPlayerSuitable && isCodecSuitable && isSizeSuitable && isAlphaSuitable && isAdditiveSuitable && isShaderSuitable; + } + + public override bool OnPlayerStopForSeek() + { + if (textures == null) { + return true; + } + isStoppingForSeek = true; + isStartTriggered = false; + return true; + } + + public override void OnPlayerStart() + { + isStartTriggered = true; + } + + public override bool ShouldSkipDestroyOnStopForSeek() + { return true; } + + private void forceUpdateMaterialTextures(Texture[] newTextures) + { + if (currentMaterial != null) { + currentMaterial.mainTexture = newTextures[0]; + currentMaterial.SetTexture("_TextureRGB", newTextures[0]); + if (hasAlpha) { + currentMaterial.SetTexture("_TextureA", newTextures[1]); + } + } + } + + public override void AttachToPlayer(int playerId) + { + if (!isStoppingForSeek) { + nativeTextureId = 0xffffffff; + } + criManaUnityPlayer_MediaCodecAttachTexture_ANDROID(playerId, nativeTextureId); + needsToDetachInitTexture = true; + } + + + public override bool UpdateFrame(int playerId, FrameInfo frameInfo, ref bool frameDrop) + { + if (needsToDetachInitTexture) { // only once + needsToDetachInitTexture = false; + criManaUnityPlayer_MediaCodecDetachTexture_ANDROID(playerId, 0xffffffff); + } + + bool isFrameUpdated = CRIWARE9061FF01(playerId, 0, null, frameInfo, ref frameDrop); + if (isFrameUpdated && !frameDrop) { + needsUpdateTexture = true; + } + + return isFrameUpdated; + } + + + public override bool UpdateMaterial(Material material) + { + if (!areTexturesUpdated) { + return false; + } + + if (currentMaterial != material) { + currentMaterial = material; + SetupStaticMaterialProperties(); + } + if (textures != null) { + material.mainTexture = textures[0]; + material.SetTexture("_TextureRGB", textures[0]); + if (hasAlpha && textures[1] != null) { + material.SetTexture("_TextureA", textures[1]); + } + } + material.SetVector("_MovieTexture_ST", movieTextureST); + if (hasAlpha) { + material.SetVector("_AlphaTexture_ST", alphaTextureST); + } + + return true; + } + + private void UpdateMovieTextureST(float[] texCoords, float dispWidth, float dispHeight) + { + movieTextureST.x = texCoords[0]; + movieTextureST.y = texCoords[1]; + movieTextureST.z = texCoords[2]; + movieTextureST.w = texCoords[3]; + + float uScale = (dispWidth != alphaWidth) ? ((float)dispWidth - 0.5f) / (float)alphaWidth : 1.0f; + float vScale = (dispHeight != alphaHeight) ? ((float)dispHeight - 0.5f) / (float)alphaHeight : 1.0f; + alphaTextureST.x = uScale; + alphaTextureST.y = -vScale; + alphaTextureST.z = 0.0f; + alphaTextureST.w = vScale; + } + + public override void UpdateTextures() + { + if (needsUpdateTexture) { // only once by frame (updates texture may be called multiple time because it is by object an camera + int numTextures = hasAlpha ? 2 : 1; + nativePtrs[0] = System.IntPtr.Zero; + bool isTextureUpdated = CRIWAREDA63C3D7(playerId, numTextures, nativePtrs); + areTexturesUpdated |= isTextureUpdated; + + if (isTextureUpdated && nativePtrs[0] != System.IntPtr.Zero && isStartTriggered) { + needsUpdateTexture = false; + var nativeTexture = (NativeTexture)Marshal.PtrToStructure(nativePtrs[0], typeof(NativeTexture)); + + if (textures == null) { + textures = new Texture2D[2]; + textures[0] = Texture2D.CreateExternalTexture(width, height, TextureFormat.ARGB32, false, false, new System.IntPtr(nativeTexture.nativePtrRGB)); + textures[0].wrapMode = TextureWrapMode.Clamp; + if (hasAlpha) { +#if !UNITY_5_6_OR_NEWER || UNITY_5_6_0 || UNITY_5_6_1 + TextureFormat format = TextureFormat.Alpha8; +#else + TextureFormat format = TextureFormat.R8; +#endif + textures[1] = Texture2D.CreateExternalTexture(alphaWidth, alphaHeight, format, false, false, new System.IntPtr(nativeTexture.nativePtrA)); + textures[1].wrapMode = TextureWrapMode.Clamp; + } + if (currentMaterial != null) { + forceUpdateMaterialTextures(textures); + } + nativeTextureId = nativeTexture.nativePtrRGB; + } else { + textures[0].UpdateExternalTexture(new System.IntPtr(nativeTexture.nativePtrRGB)); + if (hasAlpha) { + textures[1].UpdateExternalTexture(new System.IntPtr(nativeTexture.nativePtrA)); + } + } + + UpdateMovieTextureST(nativeTexture.texCoords, dispWidth, dispHeight); + isStoppingForSeek = false; + } + } + } + + [StructLayout(LayoutKind.Sequential)] + struct NativeTexture + { + public System.UInt32 nativePtrRGB; // opengl GLuint texture name + public System.UInt32 nativePtrA; // opengl GLuint texture name + + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)] + public float[] texCoords; // texture coordinates + } + + public static bool IsSupported() + { + if (SystemInfo.graphicsDeviceType == UnityEngine.Rendering.GraphicsDeviceType.Vulkan) { + Debug.Log("[CRIWARE] Another RendererResource will be used for Vulkan. Please use CriManaPlugin.IsCodecSupported instead."); + return true; + } + + /* check if native code for Android MediaCodec is supported by device */ + if (!criManaUnity_IsMediaCodecSupported_ANDROID((int)SystemInfo.graphicsDeviceType)) { + Debug.Log("[CRIWARE] criManaUnity_IsMediaCodecSupported_ANDROID returned false."); + return false; + } + + /* If OpenGLES2, all devices can render h.264 videos */ + if (SystemInfo.graphicsDeviceType == UnityEngine.Rendering.GraphicsDeviceType.OpenGLES2) { + return true; + } + + /* Load a shader for rendering test */ + Shader shader = Shader.Find("CriMana/AndroidH264DummySupportCheck"); + + /* Check the compiled shader is supported(only works on old Unity) */ + if (!shader.isSupported) { + return false; + } + + /* Save current active RenderTexture */ + var current = RenderTexture.active; + + /* Create textures for shader rendering test */ + Texture2D texture = new Texture2D(1, 1, TextureFormat.ARGB32, false); + RenderTexture renderTexture = new RenderTexture(1, 1, 0); + renderTexture.Create(); + /* Create material with the shader */ + Material material = new Material(shader); + /* Render on RenderTexture */ + Graphics.Blit(texture, renderTexture, material, 0); + + /* Copy pixels of RenderTexture to Texture */ + RenderTexture.active = renderTexture; + texture.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0); + texture.Apply(); + /* Check pixel color */ + var color = texture.GetPixel(0, 0); + bool ret = (color.r == 1.0f) && (color.g == 1.0f) && (color.b == 1.0f); + + /* Reset current active RenderTexture */ + RenderTexture.active = current; + + /* Cleaning */ + Material.Destroy(material); + Texture2D.Destroy(texture); + Texture2D.Destroy(renderTexture); + + return ret; + } + + #region DLL Import + #if !CRIWARE_ENABLE_HEADLESS_MODE + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool criManaUnity_IsMediaCodecSupported_ANDROID(int device_type); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern System.UInt32 criManaUnity_MediaCodecCreateTexture_ANDROID(); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criManaUnity_MediaCodecDeleteTexture_ANDROID(System.UInt32 oes_texture); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool criManaUnityPlayer_MediaCodecAttachTexture_ANDROID(int player_id, System.UInt32 oes_texture); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criManaUnityPlayer_MediaCodecDetachTexture_ANDROID(int player_id, System.UInt32 oes_texture); + #else + private static bool criManaUnity_IsMediaCodecSupported_ANDROID(int device_type) { return true; } + private static System.UInt32 criManaUnity_MediaCodecCreateTexture_ANDROID() { return 0x0; } + private static void criManaUnity_MediaCodecDeleteTexture_ANDROID(System.UInt32 oes_texture) { } + private static bool criManaUnityPlayer_MediaCodecAttachTexture_ANDROID(int player_id, System.UInt32 oes_texture) { return true; } + private static void criManaUnityPlayer_MediaCodecDetachTexture_ANDROID(int player_id, System.UInt32 oes_texture) { } + #endif + #endregion + + } +} + +} //namespace CriWare + +#endif diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/CriMana/Detail/RendererResources/AndroidH264Rgb.cs.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/CriMana/Detail/RendererResources/AndroidH264Rgb.cs.meta new file mode 100644 index 0000000..fa1fe72 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/CriMana/Detail/RendererResources/AndroidH264Rgb.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 4d3185896891e4109a5d1e0802757b9e +timeCreated: 1445063317 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/CriMana/Detail/RendererResources/AndroidSofdecPrimeYuv.cs b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/CriMana/Detail/RendererResources/AndroidSofdecPrimeYuv.cs new file mode 100644 index 0000000..35c661b --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/CriMana/Detail/RendererResources/AndroidSofdecPrimeYuv.cs @@ -0,0 +1,341 @@ +/**************************************************************************** + * + * Copyright (c) 2015-2018 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +#if !UNITY_EDITOR && UNITY_ANDROID + +using UnityEngine; +using System; + +namespace CriWare { + +namespace CriMana.Detail +{ + public static partial class AutoResisterRendererResourceFactories + { + [RendererResourceFactoryPriority(5050)] + public class RendererResourceFactoryAndroidSofdecPrimeYuv : RendererResourceFactory + { + public override RendererResource CreateRendererResource(int playerId, MovieInfo movieInfo, bool additive, Shader userShader) + { + bool isCodecSuitable = movieInfo.codecType == CodecType.SofdecPrime || + movieInfo.codecType == CodecType.VP9 || + (CriManaPlugin.criManaUnity_IsBufferOutputForH264Enabled_ANDROID() && movieInfo.codecType == CodecType.H264); + bool isGraphicsApiSuitable = (UnityEngine.SystemInfo.graphicsDeviceType == UnityEngine.Rendering.GraphicsDeviceType.OpenGLES3); + bool isSuitable = isCodecSuitable && isGraphicsApiSuitable; + return isSuitable + ? new RendererResourceAndroidSofdecPrimeYuv(playerId, movieInfo, additive, userShader) + : null; + } + + protected override void OnDisposeManaged() + { + } + + protected override void OnDisposeUnmanaged() + { + } + } + } + + + + + public class RendererResourceAndroidSofdecPrimeYuv : RendererResource + { + private int width, height; + private int chromaWidth, chromaHeight; + private int alphaWidth, alphaHeight; + private bool useUserShader; + private CodecType codecType; + + private const TextureFormat format = TextureFormat.R8; + private const TextureFormat formatUV = TextureFormat.RG16; + + private Vector4 movieTextureST = Vector4.zero; + private Vector4 movieChromaTextureST = Vector4.zero; + private Vector4 movieAlphaTextureST = Vector4.zero; + + private Texture2D[] textures; + private int numImages = -1; + private int numImagesForYUV = -1; + System.IntPtr[] nativePtrs = new System.IntPtr[4]; + private RenderTexture[] renderTextures; + + private Int32 playerID; + private bool areTexturesUpdated = false; + private bool isFrameUpdated = false; + private bool isStoppingForSeek = false; + private bool isStartTriggered = true; + + + public RendererResourceAndroidSofdecPrimeYuv(int playerId, MovieInfo movieInfo, bool additive, Shader userShader) + { + CalculateTextureSize(ref width, ref height, (int)movieInfo.width, (int)movieInfo.height, movieInfo.codecType, false); + CalculateTextureSize(ref chromaWidth, ref chromaHeight, (int)movieInfo.width, (int)movieInfo.height, movieInfo.codecType, true); + + this.additive = additive; + hasAlpha = movieInfo.hasAlpha; + useUserShader = userShader != null; + codecType = movieInfo.codecType; + + if (userShader != null) { + shader = userShader; + } else { + string shaderName = "CriMana/AndroidSofdecPrimeYuv"; + shader = Shader.Find(shaderName); + } + + if (hasAlpha) { + CalculateTextureSize(ref alphaWidth, ref alphaHeight, (int)movieInfo.width, (int)movieInfo.height, movieInfo.alphaCodecType, false); + } + + UpdateMovieTextureST(movieInfo.dispWidth, movieInfo.dispHeight); + + nativePtrs = new IntPtr[4]; + playerID = playerId; + } + + + protected override void OnDisposeManaged() + { + } + + + protected override void OnDisposeUnmanaged() + { + DisposeTextures(textures); + DisposeTextures(renderTextures); + + textures = null; + renderTextures = null; + } + + + public override bool IsPrepared() + { + return areTexturesUpdated && isFrameUpdated; + } + + + public override bool ContinuePreparing() + { return true; } + + + public override bool IsSuitable(int playerId, MovieInfo movieInfo, bool additive, Shader userShader) + { + int w = 0, h = 0; + CalculateTextureSize(ref w, ref h, (int)movieInfo.width, (int)movieInfo.height, movieInfo.codecType, false); + bool isCodecSuitable = movieInfo.codecType == codecType; + bool isSizeSuitable = (width == w) && (height == h); + bool isAlphaSuitable = hasAlpha == movieInfo.hasAlpha; + bool isAdditiveSuitable = this.additive == additive; + bool isShaderSuitable = this.useUserShader ? (userShader == shader) : true; + return isCodecSuitable && isSizeSuitable && isAlphaSuitable && isAdditiveSuitable && isShaderSuitable; + } + + + public override bool OnPlayerStopForSeek() + { + isStoppingForSeek = true; + isStartTriggered = false; + + if (renderTextures != null || textures == null || textures[0] == null) { + return true; + } + + renderTextures = new RenderTexture[hasAlpha ? 4 : 3]; + + for (int i = 0; i < renderTextures.Length; i++) { + Texture2D baseTexture = textures[i]; + RenderTexture texture = new RenderTexture(baseTexture.width, baseTexture.height, 0, RenderTextureFormat.R8); + texture.Create(); + + Graphics.Blit(baseTexture, texture); + renderTextures[i] = texture; + } + + forceUpdateMaterialTextures(renderTextures); + + DisposeTextures(textures); + + return true; + } + + + public override void OnPlayerStart() { + isStartTriggered = true; + } + + + private void forceUpdateMaterialTextures(Texture[] newTextures) { + if (currentMaterial != null) { + currentMaterial.SetTexture("_TextureY", newTextures[0]); + currentMaterial.SetTexture("_TextureU", newTextures[1]); + currentMaterial.SetTexture("_TextureV", newTextures[2]); + if (hasAlpha) { + currentMaterial.SetTexture("_TextureA", newTextures[3]); + } + } + } + + + public override void AttachToPlayer(int playerId) + { + DisposeTextures(textures); + areTexturesUpdated = false; + isFrameUpdated = false; + } + + + public override bool UpdateFrame(int playerId, FrameInfo frameInfo, ref bool frameDrop) + { + bool updated = CRIWARE9061FF01(playerId, 4, null, frameInfo, ref frameDrop); + if (updated && !frameDrop) { + UpdateMovieTextureST(frameInfo.dispWidth, frameInfo.dispHeight); + } + isFrameUpdated |= updated; + if (isFrameUpdated) { + numImages = (int)frameInfo.numImages; + numImagesForYUV = hasAlpha ? numImages - 1 : numImages; + } + return updated; + } + + + public override bool UpdateMaterial(Material material) + { + if (areTexturesUpdated) { + if (textures != null && textures[0] != null) { + if (currentMaterial != material) { + currentMaterial = material; + SetupStaticMaterialProperties(); + + if (numImagesForYUV == 3) { + material.DisableKeyword("CRI_UV_FORMAT"); + } else { + material.EnableKeyword("CRI_UV_FORMAT"); + } + } + material.SetVector("_MovieTexture_ST", movieTextureST); + material.SetVector("_MovieChromaTexture_ST", movieChromaTextureST); + + if (!isStoppingForSeek) { + material.SetTexture("_TextureY", textures[0]); + if (numImagesForYUV == 3) { + material.SetTexture("_TextureU", textures[1]); + material.SetTexture("_TextureV", textures[2]); + } else { + material.SetTexture("_TextureUV", textures[1]); + } + if (hasAlpha) { + material.SetVector("_MovieAlphaTexture_ST", movieAlphaTextureST); + material.SetTexture("_TextureA", textures[numImages - 1]); + } + DisposeTextures(renderTextures); + renderTextures = null; + } + } + return true; + } else { + return renderTextures != null; + } + } + + private void UpdateMovieTextureST(System.UInt32 dispWidth, System.UInt32 dispHeight) + { + float uScale = (dispWidth != width) ? (float)(dispWidth - 1) / width : 1.0f; + float vScale = (dispHeight != height) ? (float)(dispHeight - 1) / height : 1.0f; + movieTextureST.x = uScale; + movieTextureST.y = -vScale; + movieTextureST.z = 0.0f; + movieTextureST.w = vScale; + + uScale = (dispWidth != chromaWidth * 2) ? (float)(dispWidth / 2 - 1) / (chromaWidth * 2) * 2 : 1.0f; + vScale = (dispHeight != chromaHeight * 2) ? (float)(dispHeight / 2 - 1) / (chromaHeight * 2) * 2 : 1.0f; + movieChromaTextureST.x = uScale; + movieChromaTextureST.y = -vScale; + movieChromaTextureST.z = 0.0f; + movieChromaTextureST.w = vScale; + + if (hasAlpha) { + uScale = (dispWidth != alphaWidth) ? (float)(dispWidth - 1) / alphaWidth : 1.0f; + vScale = (dispHeight != alphaHeight) ? (float)(dispHeight - 1) / alphaHeight : 1.0f; + movieAlphaTextureST.x = uScale; + movieAlphaTextureST.y = -vScale; + movieAlphaTextureST.z = 0.0f; + movieAlphaTextureST.w = vScale; + } + } + + public override void UpdateTextures() + { + nativePtrs[0] = System.IntPtr.Zero; + bool updated = CRIWAREDA63C3D7(playerID, numImages, nativePtrs); + areTexturesUpdated |= updated; + + if (updated && nativePtrs[0] != System.IntPtr.Zero && isStartTriggered) { + if (textures == null || textures[0] == null) { + textures = new Texture2D[numImages]; + textures[0] = Texture2D.CreateExternalTexture(width, height, format, false, false, nativePtrs[0]); + textures[0].wrapMode = TextureWrapMode.Clamp; + if (numImagesForYUV == 3) { /* Y/U/V */ + textures[1] = Texture2D.CreateExternalTexture(chromaWidth, chromaHeight, format, false, false, nativePtrs[1]); + textures[1].wrapMode = TextureWrapMode.Clamp; + textures[2] = Texture2D.CreateExternalTexture(chromaWidth, chromaHeight, format, false, false, nativePtrs[2]); + textures[2].wrapMode = TextureWrapMode.Clamp; + } else { /* Y/UV */ + textures[1] = Texture2D.CreateExternalTexture(chromaWidth, chromaHeight, formatUV, false, false, nativePtrs[1]); + textures[1].wrapMode = TextureWrapMode.Clamp; + } + if (hasAlpha) { + textures[numImages - 1] = Texture2D.CreateExternalTexture(alphaWidth, alphaHeight, format, false, false, nativePtrs[numImages - 1]); + textures[numImages - 1].wrapMode = TextureWrapMode.Clamp; + } + } else { + for (int i = 0; i < numImages; i++) { + textures[i].UpdateExternalTexture(nativePtrs[i]); + } + } + isStoppingForSeek = false; + } + } + + private static void CalculateTextureSize(ref int w, ref int h, int videoWidth, int videoHeight, CodecType type, bool isChroma) + { + if (type == CodecType.SofdecPrime) { + if (!isChroma) { + w = Ceiling32(Ceiling16(CeilingWith(videoWidth, 8))); + h = CeilingWith(videoHeight, 8); + } else { + w = Ceiling32(Ceiling16(CeilingWith(videoWidth, 8)) / 2); + h = CeilingWith(videoHeight, 8) / 2; + } + + } else if (type == CodecType.VP9) { + if (!isChroma) { + w = CeilingWith(CeilingWith(videoWidth, 2), 8); + h = CeilingWith(videoHeight, 2); + } else { + w = CeilingWith(CeilingWith(videoWidth, 2) / 2, 8); + h = CeilingWith(videoHeight, 2) / 2; + } + } else if (type == CodecType.H264) { + if (!isChroma) { + w = Ceiling16(Ceiling16(CeilingWith(videoWidth, 8))); + h = CeilingWith(videoHeight, 8); + } else { + w = Ceiling16(Ceiling16(CeilingWith(videoWidth, 8)) / 2); + h = CeilingWith(videoHeight, 8) / 2; + } + } + } + + } // class +} // namespace + +} //namespace CriWare + +#endif diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/CriMana/Detail/RendererResources/AndroidSofdecPrimeYuv.cs.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/CriMana/Detail/RendererResources/AndroidSofdecPrimeYuv.cs.meta new file mode 100644 index 0000000..df54565 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/CriMana/Detail/RendererResources/AndroidSofdecPrimeYuv.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 2c1b5bfeca611e446ad85bec1af765ec +timeCreated: 1504693376 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/CriMana/Detail/RendererResources/AndroidSofdecPrimeYuvLegacyGles2.cs b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/CriMana/Detail/RendererResources/AndroidSofdecPrimeYuvLegacyGles2.cs new file mode 100644 index 0000000..489626b --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/CriMana/Detail/RendererResources/AndroidSofdecPrimeYuvLegacyGles2.cs @@ -0,0 +1,303 @@ +/**************************************************************************** + * + * Copyright (c) 2015 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +#if !UNITY_EDITOR && UNITY_ANDROID + +using UnityEngine; +using System; + +namespace CriWare { + +namespace CriMana.Detail +{ + public static partial class AutoResisterRendererResourceFactories + { + [RendererResourceFactoryPriority(5060)] + public class RendererResourceFactoryAndroidSofdecPrimeYuvLegacyGles2 : RendererResourceFactory + { + public override RendererResource CreateRendererResource(int playerId, MovieInfo movieInfo, bool additive, Shader userShader) + { + bool isCodecSuitable = movieInfo.codecType == CodecType.SofdecPrime || movieInfo.codecType == CodecType.VP9 || + (CriManaPlugin.criManaUnity_IsBufferOutputForH264Enabled_ANDROID() && movieInfo.codecType == CodecType.H264); + bool isGraphicsApiSuitable = (UnityEngine.SystemInfo.graphicsDeviceType == UnityEngine.Rendering.GraphicsDeviceType.OpenGLES2 || + UnityEngine.SystemInfo.graphicsDeviceType == UnityEngine.Rendering.GraphicsDeviceType.Vulkan); + bool isSuitable = isCodecSuitable && isGraphicsApiSuitable; + return isSuitable + ? new RendererResourceAndroidSofdecPrimeYuvLegacyGles2(playerId, movieInfo, additive, userShader) + : null; + } + + protected override void OnDisposeManaged() + { + } + + protected override void OnDisposeUnmanaged() + { + } + } + } + + + public class RendererResourceAndroidSofdecPrimeYuvLegacyGles2 : RendererResource + { + private int width, height; + private int chromaWidth, chromaHeight; + private int alphaWidth, alphaHeight; + private bool useUserShader; + CodecType codecType; + + private int movieWidth, movieHeight; + + private const TextureFormat format = TextureFormat.Alpha8; + private const TextureFormat formatUV = TextureFormat.RG16; + + private Vector4 movieTextureST = Vector4.zero; + private Vector4 movieChromaTextureST = Vector4.zero; + private Vector4 movieAlphaTextureST = Vector4.zero; + + private Texture2D[][] textures; + private RenderTexture[] renderTextures; + private IntPtr[][] nativeTextures; + private int numImages = -1; + private int numImagesForYUV = -1; + + private Int32 numTextureSets = 2; + private Int32 currentTextureSet = 0; + private Int32 drawTextureSet = -1; + private Int32 playerID; + private bool isStoppingForSeek = false; + + public RendererResourceAndroidSofdecPrimeYuvLegacyGles2(int playerId, MovieInfo movieInfo, bool additive, Shader userShader) + { + hasAlpha = movieInfo.hasAlpha; + this.additive = additive; + useUserShader = userShader != null; + + movieWidth = (int)movieInfo.width; + movieHeight = (int)movieInfo.height; + + if (userShader != null) { + shader = userShader; + } else { + string shaderName = "CriMana/AndroidSofdecPrimeYuvLegacy"; + shader = Shader.Find(shaderName); + } + + textures = new Texture2D[numTextureSets][]; + for (int i = 0; i < numTextureSets; i++) { + textures[i] = new Texture2D[4]; + for (int j = 0; j < 4; j++) { + textures[i][j] = null; + } + } + nativeTextures = new IntPtr[numTextureSets][]; + + for (int i = 0; i < numTextureSets; i++) { + nativeTextures[i] = new IntPtr[4]; + for (int j = 0; j < 4; j++) { + nativeTextures[i][j] = IntPtr.Zero; + } + } + codecType = movieInfo.codecType; + playerID = playerId; + } + + + protected override void OnDisposeManaged() + {} + + + protected override void OnDisposeUnmanaged() + { + CRIWARE2676F2A5(playerID, 0 ,null); + + for (int i = 0; i < numTextureSets; i++) { + DisposeTextures(textures[i]); + } + textures = null; + nativeTextures = null; + } + + public override bool IsPrepared() + { return true; } + + + public override bool ContinuePreparing() + { return true; } + + + public override bool IsSuitable(int playerId, MovieInfo movieInfo, bool additive, Shader userShader) { + bool isCodecSuitable = movieInfo.codecType == codecType; + bool isSizeSuitable = (movieWidth == (int)movieInfo.width) && (movieHeight == (int)movieInfo.height); + bool isAlphaSuitable = hasAlpha == movieInfo.hasAlpha; + bool isAdditiveSuitable = this.additive == additive; + bool isShaderSuitable = this.useUserShader ? (userShader == shader) : true; + return isCodecSuitable && isSizeSuitable && isAlphaSuitable && isAdditiveSuitable && isShaderSuitable; + } + + + public override bool OnPlayerStopForSeek() { + isStoppingForSeek = (drawTextureSet >= 0); + return true; + } + + public override void AttachToPlayer(int playerId) { + CRIWARE71A23DE1(playerID, 0, new IntPtr[1]); + drawTextureSet = -1; + } + + public override bool UpdateFrame(int playerId, FrameInfo frameInfo, ref bool frameDrop) { + bool isFrameUpdated = CRIWARE9061FF01(playerId, 0, null, frameInfo, ref frameDrop); + if (isFrameUpdated && !frameDrop) { + drawTextureSet = currentTextureSet; + currentTextureSet = (currentTextureSet + 1) % numTextureSets; + isStoppingForSeek = false; + } + + if (isFrameUpdated && textures[0][0] == null) { + numImages = (int)frameInfo.numImages; + numImagesForYUV = hasAlpha ? numImages - 1 : numImages; + + CalculateTextureSize(ref width, ref height, (int)frameInfo.width, (int)frameInfo.height, codecType, false); + CalculateTextureSize(ref chromaWidth, ref chromaHeight, (int)frameInfo.width, (int)frameInfo.height, codecType, true); + if (hasAlpha) { + CalculateTextureSize(ref alphaWidth, ref alphaHeight, (int)frameInfo.width, (int)frameInfo.height, CodecType.SofdecPrime, false); + } + UpdateMovieTextureST(frameInfo.dispWidth, frameInfo.dispHeight); + + for (int i = 0; i < numTextureSets; i++) { + textures[i][0] = new Texture2D(width, height, format, false, true); + textures[i][0].wrapMode = TextureWrapMode.Clamp; + if (numImagesForYUV == 3) { + textures[i][1] = new Texture2D(chromaWidth, chromaHeight, format, false, true); + textures[i][1].wrapMode = TextureWrapMode.Clamp; + textures[i][2] = new Texture2D(chromaWidth, chromaHeight, format, false, true); + textures[i][2].wrapMode = TextureWrapMode.Clamp; + } else { + textures[i][1] = new Texture2D(chromaWidth, chromaHeight, formatUV, false, true); + textures[i][1].wrapMode = TextureWrapMode.Clamp; + } + for (int j = 0; j < numImagesForYUV; j++) { + nativeTextures[i][j] = textures[i][j].GetNativeTexturePtr(); + } + if (hasAlpha) { + textures[i][numImages - 1] = new Texture2D(alphaWidth, alphaHeight, format, false, true); + textures[i][numImages - 1].wrapMode = TextureWrapMode.Clamp; + nativeTextures[i][numImages - 1] = textures[i][numImages - 1].GetNativeTexturePtr(); + } + } + } + + return isFrameUpdated; + } + + public override bool UpdateMaterial(Material material) { + if (isStoppingForSeek) + return true; + + if (drawTextureSet < 0) + return false; + + if (currentMaterial != material) { + currentMaterial = material; + SetupStaticMaterialProperties(); + + if (numImagesForYUV == 3) { + material.DisableKeyword("CRI_UV_FORMAT"); + } else { + material.EnableKeyword("CRI_UV_FORMAT"); + } + } + material.SetVector("_MovieTexture_ST", movieTextureST); + material.SetVector("_MovieChromaTexture_ST", movieChromaTextureST); + + material.SetTexture("_TextureY", textures[drawTextureSet][0]); + if (numImagesForYUV == 3) { + material.SetTexture("_TextureU", textures[drawTextureSet][1]); + material.SetTexture("_TextureV", textures[drawTextureSet][2]); + } else { + material.SetTexture("_TextureUV", textures[drawTextureSet][1]); + } + if (hasAlpha) { + material.SetVector("_MovieAlphaTexture_ST", movieAlphaTextureST); + material.SetTexture("_TextureA", textures[drawTextureSet][numImages - 1]); + } + + return true; + } + + + private void UpdateMovieTextureST(System.UInt32 dispWidth, System.UInt32 dispHeight) { + float uScale = (dispWidth != width) ? (float)(dispWidth - 1) / width : 1.0f; + float vScale = (dispHeight != height) ? (float)(dispHeight - 1) / height : 1.0f; + movieTextureST.x = uScale; + movieTextureST.y = -vScale; + movieTextureST.z = 0.0f; + movieTextureST.w = vScale; + + uScale = (dispWidth != chromaWidth * 2) ? + (float)(dispWidth / 2 - 1) / (chromaWidth * 2) * 2 : + 1.0f; + vScale = (dispHeight != chromaHeight * 2) ? + (float)(dispHeight / 2 - 1) / (chromaHeight * 2) * 2 : + 1.0f; + movieChromaTextureST.x = uScale; + movieChromaTextureST.y = -vScale; + movieChromaTextureST.z = 0.0f; + movieChromaTextureST.w = vScale; + + if (hasAlpha) { + uScale = (dispWidth != alphaWidth) ? (float)(dispWidth - 1) / alphaWidth : 1.0f; + vScale = (dispHeight != alphaHeight) ? (float)(dispHeight - 1) / alphaHeight : 1.0f; + movieAlphaTextureST.x = uScale; + movieAlphaTextureST.y = -vScale; + movieAlphaTextureST.z = 0.0f; + movieAlphaTextureST.w = vScale; + } + } + + public override void UpdateTextures() + { + if (drawTextureSet < 0) + return; + + CRIWAREDA63C3D7(playerID, numImages, nativeTextures[drawTextureSet]); + } + + private static void CalculateTextureSize(ref int w, ref int h, int videoWidth, int videoHeight, CodecType type, bool isChroma) { + if (type == CodecType.SofdecPrime) { + if (!isChroma) { + w = Ceiling32(Ceiling16(CeilingWith(videoWidth, 8))); + h = CeilingWith(videoHeight, 8); + } else { + w = Ceiling32(Ceiling16(CeilingWith(videoWidth, 8)) / 2); + h = CeilingWith(videoHeight, 8) / 2; + } + + } else if (type == CodecType.VP9) { + if (!isChroma) { + w = CeilingWith(CeilingWith(videoWidth, 2), 8); + h = CeilingWith(CeilingWith(videoHeight, 2), 8); + } else { + w = CeilingWith(CeilingWith(videoWidth, 2) / 2, 8); + h = CeilingWith(CeilingWith(videoHeight, 2) / 2, 8); + } + } else if (type == CodecType.H264) { + if (!isChroma) { + w = videoWidth; + h = videoHeight; + } else { + w = videoWidth / 2; + h = videoHeight / 2; + } + } + } + } +} + +} //namespace CriWare + +#endif diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/CriMana/Detail/RendererResources/AndroidSofdecPrimeYuvLegacyGles2.cs.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/CriMana/Detail/RendererResources/AndroidSofdecPrimeYuvLegacyGles2.cs.meta new file mode 100644 index 0000000..a14e2f7 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/CriMana/Detail/RendererResources/AndroidSofdecPrimeYuvLegacyGles2.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0278ee25c85693943bd37be41852fa52 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/CriMana/Resources.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/CriMana/Resources.meta new file mode 100644 index 0000000..1e2d3ed --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/CriMana/Resources.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: c4a7bb2022b729345931dc907d6ab8a5 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/CriMana/Resources/CriMana.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/CriMana/Resources/CriMana.meta new file mode 100644 index 0000000..9d8e5ae --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/CriMana/Resources/CriMana.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 6ecbb7559c822d94e9e5864caa40b65f +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/CriMana/Resources/CriMana/Android.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/CriMana/Resources/CriMana/Android.meta new file mode 100644 index 0000000..bf335c1 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/CriMana/Resources/CriMana/Android.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: fc89c6c3bcab4e148b1f6396cb7fd89f +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/CriMana/Resources/CriMana/Android/AndroidH264Rgb.shader b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/CriMana/Resources/CriMana/Android/AndroidH264Rgb.shader new file mode 100644 index 0000000..5f78d07 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/CriMana/Resources/CriMana/Android/AndroidH264Rgb.shader @@ -0,0 +1,106 @@ +Shader "CriMana/AndroidH264Rgb" +{ + Properties + { + _MainTex ("Texture", 2D) = "white" {} + [HideInInspector] _MovieTexture_ST ("MovieTexture_ST", Vector) = (1.0, 1.0, 0, 0) + [HideInInspector] _AlphaTexture_ST("AlphaTexture_ST", Vector) = (1.0, 1.0, 0, 0) + [HideInInspector] _TextureRGB ("TextureRGB", 2D) = "white" {} + [HideInInspector] _TextureA ("TextureA", 2D) = "white" {} + [HideInInspector] _SrcBlendMode ("SrcBlendMode", Int) = 0 + [HideInInspector] _DstBlendMode ("DstBlendMode", Int) = 0 + [HideInInspector] _CullMode("CullMode", Int) = 2 + [HideInInspector] _ZWriteMode("ZWriteMode", Int) = 1 + } + + SubShader + { + Tags + { + "Queue" = "Transparent" + "PreviewType"="Plane" + } + + Pass + { + Blend [_SrcBlendMode] [_DstBlendMode] + Cull [_CullMode] + ZWrite [_ZWriteMode] + ZTest [unity_GUIZTestMode] + + GLSLPROGRAM + #version 100 // this will be converted to 300 es when using OpenGLES3 + #pragma multi_compile _ CRI_ALPHA_MOVIE + #pragma multi_compile _ CRI_APPLY_TARGET_ALPHA + #pragma multi_compile _ CRI_LINEAR_COLORSPACE + #ifdef VERTEX + attribute vec4 _glesVertex; + attribute vec4 _glesMultiTexCoord0; + #ifdef CRI_APPLY_TARGET_ALPHA + attribute vec4 _glesColor; + varying lowp float alpha; + #endif + uniform highp vec4 _MainTex_ST; + uniform highp vec4 _MovieTexture_ST; + varying mediump vec2 xlv_TEXCOORD0; + #ifdef CRI_ALPHA_MOVIE + uniform highp vec4 _AlphaTexture_ST; + varying mediump vec2 xlv_TEXCOORD1; + #endif + void main () + { + highp vec4 tmpvar; + tmpvar.w = 1.0; + tmpvar.xyz = _glesVertex.xyz; + gl_Position = (unity_MatrixVP * (unity_ObjectToWorld * tmpvar)); // UnityObjectToClipPos(*) + xlv_TEXCOORD0 = (((_glesMultiTexCoord0.xy * _MainTex_ST.xy) + _MainTex_ST.zw) * _MovieTexture_ST.xy) + _MovieTexture_ST.zw; + #ifdef CRI_ALPHA_MOVIE + xlv_TEXCOORD1 = (((_glesMultiTexCoord0.xy * _MainTex_ST.xy) + _MainTex_ST.zw) * _AlphaTexture_ST.xy) + _AlphaTexture_ST.zw; + #endif + #ifdef CRI_APPLY_TARGET_ALPHA + alpha = _glesColor.w; + #endif + } + #endif + #ifdef FRAGMENT + #extension GL_OES_EGL_image_external : enable + #extension GL_OES_EGL_image_external_essl3 : enable + #if (defined(SHADER_API_GLES3) && defined(GL_OES_EGL_image_external_essl3)) || defined(GL_OES_EGL_image_external) && !defined(SHADER_API_GLCORE) + uniform samplerExternalOES _TextureRGB; + #else + uniform sampler2D _TextureRGB; + #endif + varying mediump vec2 xlv_TEXCOORD0; + uniform lowp float _Transparency; + #ifdef CRI_ALPHA_MOVIE + uniform sampler2D _TextureA; + varying mediump vec2 xlv_TEXCOORD1; + #endif + #ifdef CRI_APPLY_TARGET_ALPHA + varying lowp float alpha; + #endif + void main () + { + #if (defined(SHADER_API_GLES3) && defined(GL_OES_EGL_image_external_essl3)) || defined(GL_OES_EGL_image_external) && !defined(SHADER_API_GLCORE) + gl_FragData[0] = texture2D(_TextureRGB, xlv_TEXCOORD0); + #else + gl_FragData[0].x = gl_FragData[0].y = gl_FragData[0].z = 0.0f; + #endif + #ifdef CRI_LINEAR_COLORSPACE + gl_FragData[0].x = pow(max(gl_FragData[0].x, 0.001), 2.2); + gl_FragData[0].y = pow(max(gl_FragData[0].y, 0.001), 2.2); + gl_FragData[0].z = pow(max(gl_FragData[0].z, 0.001), 2.2); + #endif + #ifdef CRI_ALPHA_MOVIE + gl_FragData[0].w = texture2D(_TextureA, xlv_TEXCOORD1).x; + #endif + #ifdef CRI_APPLY_TARGET_ALPHA + gl_FragData[0].w *= alpha; + #endif + gl_FragData[0].w *= 1.0 - _Transparency; + } + #endif + ENDGLSL + } + } +} diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/CriMana/Resources/CriMana/Android/AndroidH264Rgb.shader.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/CriMana/Resources/CriMana/Android/AndroidH264Rgb.shader.meta new file mode 100644 index 0000000..eae0203 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/CriMana/Resources/CriMana/Android/AndroidH264Rgb.shader.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 01205c74879764ae9b7e3fe90473f53f +timeCreated: 1445063687 +licenseType: Pro +ShaderImporter: + defaultTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/CriMana/Resources/CriMana/Android/AndroidH264SupportCheck.shader b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/CriMana/Resources/CriMana/Android/AndroidH264SupportCheck.shader new file mode 100644 index 0000000..a7f2275 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/CriMana/Resources/CriMana/Android/AndroidH264SupportCheck.shader @@ -0,0 +1,46 @@ +Shader "CriMana/AndroidH264DummySupportCheck" +{ + Properties + { + _MainTex("Texture", 2D) = "white" {} + } + + SubShader + { + Pass + { + ZTest Always + Cull Off + Zwrite Off + Blend One Zero + + GLSLPROGRAM + #version 100 // this will be converted to 300 es when using OpenGLES3 + #ifdef VERTEX + attribute vec4 _glesVertex; + void main() + { + highp vec4 tmpvar; + tmpvar.w = 1.0; + tmpvar.xyz = _glesVertex.xyz; + gl_Position = (unity_MatrixVP * (unity_ObjectToWorld * tmpvar)); // UnityObjectToClipPos(*) + } + + #endif + #ifdef FRAGMENT + #extension GL_OES_EGL_image_external : enable + #extension GL_OES_EGL_image_external_essl3 : enable + void main() + { +#if (defined(SHADER_API_GLES3) && defined(GL_OES_EGL_image_external_essl3)) || defined(GL_OES_EGL_image_external) + gl_FragData[0].x = gl_FragData[0].y = gl_FragData[0].z = 1.0f; +#else + gl_FragData[0].x = gl_FragData[0].y = gl_FragData[0].z = 0.0f; + Dummy code for shader compilation failure. +#endif + } + #endif + ENDGLSL + } + } +} diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/CriMana/Resources/CriMana/Android/AndroidH264SupportCheck.shader.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/CriMana/Resources/CriMana/Android/AndroidH264SupportCheck.shader.meta new file mode 100644 index 0000000..265eb4b --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/CriMana/Resources/CriMana/Android/AndroidH264SupportCheck.shader.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 51ee31cd511ac614ea39aa4dd7841c15 +timeCreated: 1510192307 +licenseType: Pro +ShaderImporter: + externalObjects: {} + defaultTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/CriMana/Resources/CriMana/Android/AndroidSofdecPrimeYuv.shader b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/CriMana/Resources/CriMana/Android/AndroidSofdecPrimeYuv.shader new file mode 100644 index 0000000..9d0276e --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/CriMana/Resources/CriMana/Android/AndroidSofdecPrimeYuv.shader @@ -0,0 +1,144 @@ +Shader "CriMana/AndroidSofdecPrimeYuv" +{ + Properties + { + _MainTex ("Texture", 2D) = "white" {} + [HideInInspector] _MovieTexture_ST ("MovieTexture_ST", Vector) = (1.0, 1.0, 0, 0) + [HideInInspector] _MovieChromaTexture_ST("MovieChromaTexture_ST", Vector) = (1.0, 1.0, 0, 0) + [HideInInspector] _MovieAlphaTexture_ST("MovieAlphaTexture_ST", Vector) = (1.0, 1.0, 0, 0) + [HideInInspector] _TextureY ("TextureY", 2D) = "white" {} + [HideInInspector] _TextureU ("TextureU", 2D) = "white" {} + [HideInInspector] _TextureV ("TextureV", 2D) = "white" {} + [HideInInspector] _TextureUV ("TextureUV", 2D) = "white" {} + [HideInInspector] _TextureA ("TextureA", 2D) = "white" {} + [HideInInspector] _SrcBlendMode ("SrcBlendMode", Int) = 0 + [HideInInspector] _DstBlendMode ("DstBlendMode", Int) = 0 + [HideInInspector] _CullMode("CullMode", Int) = 2 + [HideInInspector] _ZWriteMode("ZWriteMode", Int) = 1 + } + + SubShader + { + Tags + { + "Queue" = "Transparent" + "PreviewType"="Plane" + } + + Pass + { + Blend [_SrcBlendMode] [_DstBlendMode] + Cull [_CullMode] + ZWrite [_ZWriteMode] + ZTest [unity_GUIZTestMode] + + CGPROGRAM + #pragma vertex vert + #pragma fragment frag + #if defined(SHADER_API_PSP2) || defined(SHADER_API_PS3) + // seems that ARB_precision_hint_fastest is not supported on these platforms. + #else + #pragma fragmentoption ARB_precision_hint_fastest + #endif + + #include "UnityCG.cginc" + + #pragma multi_compile _ CRI_UV_FORMAT + #pragma multi_compile _ CRI_ALPHA_MOVIE + #pragma multi_compile _ CRI_APPLY_TARGET_ALPHA + #pragma multi_compile _ CRI_LINEAR_COLORSPACE + + struct appdata + { + float4 vertex : POSITION; + half2 texcoord : TEXCOORD0; +#ifdef CRI_APPLY_TARGET_ALPHA + float4 color : COLOR; +#endif + }; + + struct v2f + { + float4 pos : SV_POSITION; + half2 uv : TEXCOORD0; + half2 uv2 : TEXCOORD1; +#ifdef CRI_ALPHA_MOVIE + half2 uv3 : TEXCOORD2; +#endif +#ifdef CRI_APPLY_TARGET_ALPHA + float4 color : COLOR; +#endif + }; + + float4 _MainTex_ST; + float4 _MovieTexture_ST; + float4 _MovieChromaTexture_ST; +#ifdef CRI_ALPHA_MOVIE + float4 _MovieAlphaTexture_ST; +#endif + + v2f vert(appdata v) + { + v2f o; + o.pos = UnityObjectToClipPos(v.vertex); + o.uv = (TRANSFORM_TEX(v.texcoord, _MainTex) * _MovieTexture_ST.xy) + _MovieTexture_ST.zw; + o.uv2 = (TRANSFORM_TEX(v.texcoord, _MainTex) * _MovieChromaTexture_ST.xy) + _MovieChromaTexture_ST.zw; +#ifdef CRI_ALPHA_MOVIE + o.uv3 = (TRANSFORM_TEX(v.texcoord, _MainTex) * _MovieAlphaTexture_ST.xy) + _MovieAlphaTexture_ST.zw; +#endif +#ifdef CRI_APPLY_TARGET_ALPHA + o.color = v.color; +#endif + return o; + } + + static const fixed3x3 yuv_to_rgb = { + {1.16438, 0.0, 1.59603}, + {1.16438, -0.39176, -0.81297}, + {1.16438, 2.01723, 0.0} + }; + + sampler2D _TextureY; +#ifdef CRI_UV_FORMAT + sampler2D _TextureUV; +#else + sampler2D _TextureU; + sampler2D _TextureV; +#endif +#ifdef CRI_ALPHA_MOVIE + sampler2D _TextureA; +#endif + fixed _Transparency; + + fixed4 frag(v2f i) : COLOR + { + fixed4 color; + color.r = tex2D(_TextureY, i.uv).r; +#ifdef CRI_UV_FORMAT + color.g = tex2D(_TextureUV, i.uv2).r; + color.b = tex2D(_TextureUV, i.uv2).a; +#else + color.g = tex2D(_TextureU, i.uv2).r; + color.b = tex2D(_TextureV, i.uv2).r; +#endif +#ifdef CRI_ALPHA_MOVIE + color.a = tex2D(_TextureA, i.uv3).r; +#else + color.a = 1.0; +#endif + color.rgb = color.rgb + fixed3(-0.06275, -0.50196, -0.50196); + color.rgb = mul(yuv_to_rgb, color.rgb); +#ifdef CRI_LINEAR_COLORSPACE + color.rgb = pow(max(color.rgb, 0), 2.2); +#endif +#ifdef CRI_APPLY_TARGET_ALPHA + color.a = color.a * i.color.a; +#endif + color.a *= 1 - _Transparency; + + return color; + } + ENDCG + } + } +} diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/CriMana/Resources/CriMana/Android/AndroidSofdecPrimeYuv.shader.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/CriMana/Resources/CriMana/Android/AndroidSofdecPrimeYuv.shader.meta new file mode 100644 index 0000000..ed4b32e --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/CriMana/Resources/CriMana/Android/AndroidSofdecPrimeYuv.shader.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 545dfb3f920144f7bb3599122209656b +timeCreated: 1510116192 +licenseType: Pro +ShaderImporter: + externalObjects: {} + defaultTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/CriMana/Resources/CriMana/Android/AndroidSofdecPrimeYuvLegacy.shader b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/CriMana/Resources/CriMana/Android/AndroidSofdecPrimeYuvLegacy.shader new file mode 100644 index 0000000..9b2b19b --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/CriMana/Resources/CriMana/Android/AndroidSofdecPrimeYuvLegacy.shader @@ -0,0 +1,141 @@ +Shader "CriMana/AndroidSofdecPrimeYuvLegacy" +{ + Properties + { + _MainTex ("Texture", 2D) = "white" {} + [HideInInspector] _MovieTexture_ST ("MovieTexture_ST", Vector) = (1.0, 1.0, 0, 0) + [HideInInspector] _MovieChromaTexture_ST ("MovieChromaTexture_ST", Vector) = (1.0, 1.0, 0, 0) + [HideInInspector] _MovieAlphaTexture_ST ("MovieAlphaTexture_ST", Vector) = (1.0, 1.0, 0, 0) + [HideInInspector] _TextureY ("TextureY", 2D) = "white" {} + [HideInInspector] _TextureU ("TextureU", 2D) = "white" {} + [HideInInspector] _TextureV ("TextureV", 2D) = "white" {} + [HideInInspector] _TextureUV ("TextureUV", 2D) = "white" {} + [HideInInspector] _TextureA ("TextureA", 2D) = "white" {} + [HideInInspector] _SrcBlendMode ("SrcBlendMode", Int) = 0 + [HideInInspector] _DstBlendMode ("DstBlendMode", Int) = 0 + [HideInInspector] _CullMode ("CullMode", Int) = 2 + [HideInInspector] _ZWriteMode ("ZWriteMode", Int) = 1 + } + + SubShader + { + Tags + { + "Queue" = "Transparent" + "PreviewType"="Plane" + } + + Pass + { + Blend [_SrcBlendMode] [_DstBlendMode] + Cull [_CullMode] + ZWrite [_ZWriteMode] + ZTest [unity_GUIZTestMode] + + CGPROGRAM + #pragma vertex vert + #pragma fragment frag + #pragma fragmentoption ARB_precision_hint_fastest + + #include "UnityCG.cginc" + + #pragma multi_compile _ CRI_UV_FORMAT + #pragma multi_compile _ CRI_ALPHA_MOVIE + #pragma multi_compile _ CRI_APPLY_TARGET_ALPHA + #pragma multi_compile _ CRI_LINEAR_COLORSPACE + + struct appdata + { + float4 vertex : POSITION; + half2 texcoord : TEXCOORD0; +#ifdef CRI_APPLY_TARGET_ALPHA + float4 color : COLOR; +#endif + }; + + struct v2f + { + float4 pos : SV_POSITION; + half2 uv : TEXCOORD0; + half2 uv2 : TEXCOORD1; +#ifdef CRI_ALPHA_MOVIE + half2 uv3 : TEXCOORD2; +#endif +#ifdef CRI_APPLY_TARGET_ALPHA + float4 color : COLOR; +#endif + }; + + float4 _MainTex_ST; + float4 _MovieTexture_ST; + float4 _MovieChromaTexture_ST; +#ifdef CRI_ALPHA_MOVIE + float4 _MovieAlphaTexture_ST; +#endif + + v2f vert(appdata v) + { + v2f o; + o.pos = UnityObjectToClipPos(v.vertex); + o.uv = (TRANSFORM_TEX(v.texcoord, _MainTex) * _MovieTexture_ST.xy) + _MovieTexture_ST.zw; + o.uv2 = (TRANSFORM_TEX(v.texcoord, _MainTex) * _MovieChromaTexture_ST.xy) + _MovieChromaTexture_ST.zw; +#ifdef CRI_ALPHA_MOVIE + o.uv3 = (TRANSFORM_TEX(v.texcoord, _MainTex) * _MovieAlphaTexture_ST.xy) + _MovieAlphaTexture_ST.zw; +#endif +#ifdef CRI_APPLY_TARGET_ALPHA + o.color = v.color; +#endif + return o; + } + + static const fixed3x3 yuv_to_rgb = { + {1.16438, 0.0, 1.59603}, + {1.16438, -0.39176, -0.81297}, + {1.16438, 2.01723, 0.0} + }; + + sampler2D _TextureY; +#ifdef CRI_UV_FORMAT + sampler2D _TextureUV; +#else + sampler2D _TextureU; + sampler2D _TextureV; +#endif +#ifdef CRI_ALPHA_MOVIE + sampler2D _TextureA; +#endif + fixed _Transparency; + + fixed4 frag(v2f i) : COLOR + { + fixed3 yuv; + yuv.r = tex2D(_TextureY, i.uv).a; +#ifdef CRI_UV_FORMAT + yuv.g = tex2D(_TextureUV, i.uv2).r; + yuv.b = tex2D(_TextureUV, i.uv2).g; +#else + yuv.g = tex2D(_TextureU, i.uv2).a; + yuv.b = tex2D(_TextureV, i.uv2).a; +#endif + yuv = yuv + fixed3(-0.06275, -0.50196, -0.50196); + fixed4 color; + color.rgb = mul(yuv_to_rgb, yuv); +#ifdef CRI_LINEAR_COLORSPACE + color.rgb = pow(max(color.rgb, 0), 2.2); +#endif +#ifdef CRI_ALPHA_MOVIE + color.a = tex2D(_TextureA, i.uv3).a; +#else + color.a = 1.0; +#endif +#ifdef CRI_APPLY_TARGET_ALPHA + color.a = color.a * i.color.a; +#endif + color.a *= 1 - _Transparency; + + return color; + } + ENDCG + } + } +} diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/CriMana/Resources/CriMana/Android/AndroidSofdecPrimeYuvLegacy.shader.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/CriMana/Resources/CriMana/Android/AndroidSofdecPrimeYuvLegacy.shader.meta new file mode 100644 index 0000000..db0a5d4 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/CriMana/Resources/CriMana/Android/AndroidSofdecPrimeYuvLegacy.shader.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 510c610c0d60660428de1beaa9982292 +ShaderImporter: + externalObjects: {} + defaultTextures: [] + nonModifiableTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/libs.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/libs.meta new file mode 100644 index 0000000..cb0f058 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/libs.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 1f17bd2af1cbd884fb63295a765287fb +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/libs/CriJavaClasses.aar b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/libs/CriJavaClasses.aar new file mode 100644 index 0000000..ca4d526 Binary files /dev/null and b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/libs/CriJavaClasses.aar differ diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/libs/CriJavaClasses.aar.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/libs/CriJavaClasses.aar.meta new file mode 100644 index 0000000..ae5e685 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/libs/CriJavaClasses.aar.meta @@ -0,0 +1,32 @@ +fileFormatVersion: 2 +guid: 521d7b784dd40df459e34bafc2167eab +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 0 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + Android: Android + second: + enabled: 1 + settings: {} + - first: + Any: + second: + enabled: 0 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/libs/arm64-v8a.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/libs/arm64-v8a.meta new file mode 100644 index 0000000..0a99231 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/libs/arm64-v8a.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: dd5b85be0649e2646ad30cd7c49913b2 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/libs/arm64-v8a/libcri_ware_unity.so b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/libs/arm64-v8a/libcri_ware_unity.so new file mode 100644 index 0000000..6e092db Binary files /dev/null and b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/libs/arm64-v8a/libcri_ware_unity.so differ diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/libs/arm64-v8a/libcri_ware_unity.so.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/libs/arm64-v8a/libcri_ware_unity.so.meta new file mode 100644 index 0000000..8ab9c40 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/libs/arm64-v8a/libcri_ware_unity.so.meta @@ -0,0 +1,94 @@ +fileFormatVersion: 2 +guid: fd84e4785f0e6d1408d320599643aa77 +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + isPreloaded: 0 + isOverridable: 0 + platformData: + - first: + '': Any + second: + enabled: 0 + settings: + Exclude Android: 0 + Exclude Editor: 1 + Exclude Linux: 1 + Exclude Linux64: 1 + Exclude LinuxUniversal: 1 + Exclude OSXUniversal: 1 + Exclude WebGL: 1 + Exclude Win: 1 + Exclude Win64: 1 + - first: + Android: Android + second: + enabled: 1 + settings: + CPU: ARM64 + - first: + Any: + second: + enabled: 0 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + CPU: AnyCPU + DefaultValueInitialized: true + OS: AnyOS + - first: + Facebook: Win + second: + enabled: 0 + settings: + CPU: AnyCPU + - first: + Facebook: Win64 + second: + enabled: 0 + settings: + CPU: AnyCPU + - first: + Standalone: Linux + second: + enabled: 0 + settings: + CPU: x86 + - first: + Standalone: Linux64 + second: + enabled: 0 + settings: + CPU: x86_64 + - first: + Standalone: LinuxUniversal + second: + enabled: 0 + settings: + CPU: None + - first: + Standalone: OSXUniversal + second: + enabled: 0 + settings: + CPU: AnyCPU + - first: + Standalone: Win + second: + enabled: 0 + settings: + CPU: AnyCPU + - first: + Standalone: Win64 + second: + enabled: 0 + settings: + CPU: AnyCPU + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/libs/armeabi-v7a.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/libs/armeabi-v7a.meta new file mode 100644 index 0000000..de332b1 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/libs/armeabi-v7a.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 68c2d2dcab5ddcc47a56b2c3c165e7f8 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/libs/armeabi-v7a/libcri_ware_unity.so b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/libs/armeabi-v7a/libcri_ware_unity.so new file mode 100644 index 0000000..2650b48 Binary files /dev/null and b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/libs/armeabi-v7a/libcri_ware_unity.so differ diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/libs/armeabi-v7a/libcri_ware_unity.so.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/libs/armeabi-v7a/libcri_ware_unity.so.meta new file mode 100644 index 0000000..679f86d --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/libs/armeabi-v7a/libcri_ware_unity.so.meta @@ -0,0 +1,145 @@ +fileFormatVersion: 2 +guid: d6295746feec9704e95338f43a6d517a +timeCreated: 1433816086 +licenseType: Pro +PluginImporter: + serializedVersion: 2 + iconMap: {} + executionOrder: {} + isPreloaded: 0 + isOverridable: 0 + platformData: + data: + first: + '': Any + second: + enabled: 0 + settings: + Exclude Android: 0 + Exclude Editor: 1 + Exclude Linux: 1 + Exclude Linux64: 1 + Exclude LinuxUniversal: 1 + Exclude OSXIntel: 1 + Exclude OSXIntel64: 1 + Exclude OSXUniversal: 1 + Exclude WebGL: 1 + Exclude Win: 1 + Exclude Win64: 1 + Exclude WindowsStoreApps: 1 + Exclude iOS: 1 + Exclude tvOS: 1 + data: + first: + '': Editor + second: + enabled: 0 + settings: + CPU: AnyCPU + OS: AnyOS + data: + first: + Android: Android + second: + enabled: 1 + settings: + CPU: ARMv7 + data: + first: + Any: + second: + enabled: 0 + settings: {} + data: + first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + data: + first: + Facebook: Win + second: + enabled: 0 + settings: + CPU: AnyCPU + data: + first: + Facebook: Win64 + second: + enabled: 0 + settings: + CPU: AnyCPU + data: + first: + Standalone: Linux + second: + enabled: 0 + settings: + CPU: x86 + data: + first: + Standalone: Linux64 + second: + enabled: 0 + settings: + CPU: x86_64 + data: + first: + Standalone: OSXIntel + second: + enabled: 0 + settings: + CPU: AnyCPU + data: + first: + Standalone: OSXIntel64 + second: + enabled: 0 + settings: + CPU: AnyCPU + data: + first: + Standalone: Win + second: + enabled: 0 + settings: + CPU: AnyCPU + data: + first: + Standalone: Win64 + second: + enabled: 0 + settings: + CPU: AnyCPU + data: + first: + Windows Store Apps: WindowsStoreApps + second: + enabled: 0 + settings: + CPU: AnyCPU + DontProcess: False + PlaceholderPath: + SDK: AnySDK + ScriptingBackend: AnyScriptingBackend + data: + first: + iPhone: iOS + second: + enabled: 0 + settings: + CompileFlags: + FrameworkDependencies: + data: + first: + tvOS: tvOS + second: + enabled: 0 + settings: + CompileFlags: + FrameworkDependencies: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/libs/libcri_file_system_android.jar b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/libs/libcri_file_system_android.jar new file mode 100644 index 0000000..9007425 Binary files /dev/null and b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/libs/libcri_file_system_android.jar differ diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/libs/libcri_file_system_android.jar.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/libs/libcri_file_system_android.jar.meta new file mode 100644 index 0000000..ebf8b96 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/libs/libcri_file_system_android.jar.meta @@ -0,0 +1,146 @@ +fileFormatVersion: 2 +guid: 7b4b9afed8aedea4dafc1a56bf9806f0 +timeCreated: 1486043713 +licenseType: Pro +PluginImporter: + serializedVersion: 2 + iconMap: {} + executionOrder: {} + isPreloaded: 0 + isOverridable: 0 + platformData: + data: + first: + '': Any + second: + enabled: 0 + settings: + Exclude Android: 0 + Exclude Editor: 1 + Exclude Linux: 1 + Exclude Linux64: 1 + Exclude LinuxUniversal: 1 + Exclude OSXIntel: 1 + Exclude OSXIntel64: 1 + Exclude OSXUniversal: 1 + Exclude PS4: 1 + Exclude WebGL: 1 + Exclude Win: 1 + Exclude Win64: 1 + Exclude WindowsStoreApps: 1 + Exclude iOS: 1 + Exclude tvOS: 1 + data: + first: + '': Editor + second: + enabled: 0 + settings: + CPU: AnyCPU + OS: AnyOS + data: + first: + Android: Android + second: + enabled: 1 + settings: + CPU: ARMv7 + data: + first: + Any: + second: + enabled: 0 + settings: {} + data: + first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + data: + first: + Facebook: Win + second: + enabled: 0 + settings: + CPU: AnyCPU + data: + first: + Facebook: Win64 + second: + enabled: 0 + settings: + CPU: AnyCPU + data: + first: + Standalone: Linux + second: + enabled: 0 + settings: + CPU: x86 + data: + first: + Standalone: Linux64 + second: + enabled: 0 + settings: + CPU: x86_64 + data: + first: + Standalone: OSXIntel + second: + enabled: 0 + settings: + CPU: AnyCPU + data: + first: + Standalone: OSXIntel64 + second: + enabled: 0 + settings: + CPU: AnyCPU + data: + first: + Standalone: Win + second: + enabled: 0 + settings: + CPU: AnyCPU + data: + first: + Standalone: Win64 + second: + enabled: 0 + settings: + CPU: AnyCPU + data: + first: + Windows Store Apps: WindowsStoreApps + second: + enabled: 0 + settings: + CPU: AnyCPU + DontProcess: False + PlaceholderPath: + SDK: AnySDK + ScriptingBackend: AnyScriptingBackend + data: + first: + iPhone: iOS + second: + enabled: 0 + settings: + CompileFlags: + FrameworkDependencies: + data: + first: + tvOS: tvOS + second: + enabled: 0 + settings: + CompileFlags: + FrameworkDependencies: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/libs/x86.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/libs/x86.meta new file mode 100644 index 0000000..41ae81b --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/libs/x86.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 1c126827a14a46747863272b2b214f9b +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/libs/x86/libcri_ware_unity.so b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/libs/x86/libcri_ware_unity.so new file mode 100644 index 0000000..d4f65be Binary files /dev/null and b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/libs/x86/libcri_ware_unity.so differ diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/libs/x86/libcri_ware_unity.so.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/libs/x86/libcri_ware_unity.so.meta new file mode 100644 index 0000000..7629852 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Android/libs/x86/libcri_ware_unity.so.meta @@ -0,0 +1,145 @@ +fileFormatVersion: 2 +guid: 8a5e2b17a976caf4397218dfc89ddd43 +timeCreated: 1433816086 +licenseType: Pro +PluginImporter: + serializedVersion: 2 + iconMap: {} + executionOrder: {} + isPreloaded: 0 + isOverridable: 0 + platformData: + data: + first: + '': Any + second: + enabled: 0 + settings: + Exclude Android: 0 + Exclude Editor: 1 + Exclude Linux: 1 + Exclude Linux64: 1 + Exclude LinuxUniversal: 1 + Exclude OSXIntel: 1 + Exclude OSXIntel64: 1 + Exclude OSXUniversal: 1 + Exclude WebGL: 1 + Exclude Win: 1 + Exclude Win64: 1 + Exclude WindowsStoreApps: 1 + Exclude iOS: 1 + Exclude tvOS: 1 + data: + first: + '': Editor + second: + enabled: 0 + settings: + CPU: AnyCPU + OS: AnyOS + data: + first: + Android: Android + second: + enabled: 1 + settings: + CPU: x86 + data: + first: + Any: + second: + enabled: 0 + settings: {} + data: + first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + data: + first: + Facebook: Win + second: + enabled: 0 + settings: + CPU: AnyCPU + data: + first: + Facebook: Win64 + second: + enabled: 0 + settings: + CPU: AnyCPU + data: + first: + Standalone: Linux + second: + enabled: 0 + settings: + CPU: x86 + data: + first: + Standalone: Linux64 + second: + enabled: 0 + settings: + CPU: x86_64 + data: + first: + Standalone: OSXIntel + second: + enabled: 0 + settings: + CPU: AnyCPU + data: + first: + Standalone: OSXIntel64 + second: + enabled: 0 + settings: + CPU: AnyCPU + data: + first: + Standalone: Win + second: + enabled: 0 + settings: + CPU: AnyCPU + data: + first: + Standalone: Win64 + second: + enabled: 0 + settings: + CPU: AnyCPU + data: + first: + Windows Store Apps: WindowsStoreApps + second: + enabled: 0 + settings: + CPU: AnyCPU + DontProcess: False + PlaceholderPath: + SDK: AnySDK + ScriptingBackend: AnyScriptingBackend + data: + first: + iPhone: iOS + second: + enabled: 0 + settings: + CompileFlags: + FrameworkDependencies: + data: + first: + tvOS: tvOS + second: + enabled: 0 + settings: + CompileFlags: + FrameworkDependencies: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Linux.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Linux.meta new file mode 100644 index 0000000..97f1d00 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Linux.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: ad93b238b2f121f4f9c7b9641edf0532 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Linux/x86_64.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Linux/x86_64.meta new file mode 100644 index 0000000..09290e2 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Linux/x86_64.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 7e1c713fe6d13674196babf3a983b02a +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Linux/x86_64/libcri_ware_unity.so b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Linux/x86_64/libcri_ware_unity.so new file mode 100644 index 0000000..c5feb29 Binary files /dev/null and b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Linux/x86_64/libcri_ware_unity.so differ diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Linux/x86_64/libcri_ware_unity.so.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Linux/x86_64/libcri_ware_unity.so.meta new file mode 100644 index 0000000..572c08b --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/Linux/x86_64/libcri_ware_unity.so.meta @@ -0,0 +1,140 @@ +fileFormatVersion: 2 +guid: 980c2fc129fa3174d98e044f20a0252e +timeCreated: 1492403957 +licenseType: Pro +PluginImporter: + serializedVersion: 2 + iconMap: {} + executionOrder: {} + isPreloaded: 0 + isOverridable: 0 + platformData: + data: + first: + '': Any + second: + enabled: 0 + settings: + Exclude Android: 1 + Exclude Editor: 0 + Exclude Linux: 1 + Exclude Linux64: 0 + Exclude LinuxUniversal: 0 + Exclude OSXIntel: 1 + Exclude OSXIntel64: 1 + Exclude OSXUniversal: 1 + Exclude WebGL: 1 + Exclude Win: 1 + Exclude Win64: 1 + Exclude iOS: 1 + data: + first: + '': Editor + second: + enabled: 0 + settings: + CPU: x86_64 + OS: Linux + data: + first: + Android: Android + second: + enabled: 0 + settings: + CPU: ARMv7 + data: + first: + Any: + second: + enabled: 0 + settings: {} + data: + first: + Editor: Editor + second: + enabled: 1 + settings: + CPU: x86_64 + DefaultValueInitialized: true + OS: Linux + data: + first: + Facebook: Win + second: + enabled: 0 + settings: + CPU: None + data: + first: + Facebook: Win64 + second: + enabled: 0 + settings: + CPU: None + data: + first: + Standalone: Linux + second: + enabled: 0 + settings: + CPU: None + data: + first: + Standalone: Linux64 + second: + enabled: 1 + settings: + CPU: x86_64 + data: + first: + Standalone: LinuxUniversal + second: + enabled: 1 + settings: + CPU: x86_64 + data: + first: + Standalone: OSXIntel + second: + enabled: 0 + settings: + CPU: None + data: + first: + Standalone: OSXIntel64 + second: + enabled: 0 + settings: + CPU: None + data: + first: + Standalone: OSXUniversal + second: + enabled: 0 + settings: + CPU: None + data: + first: + Standalone: Win + second: + enabled: 0 + settings: + CPU: None + data: + first: + Standalone: Win64 + second: + enabled: 0 + settings: + CPU: None + data: + first: + iPhone: iOS + second: + enabled: 0 + settings: + CompileFlags: + FrameworkDependencies: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/MacOSX.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/MacOSX.meta new file mode 100644 index 0000000..92f141d --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/MacOSX.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: f4d4b8194ff0f894790c01453f140608 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/MacOSX/CriMana.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/MacOSX/CriMana.meta new file mode 100644 index 0000000..e7283c9 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/MacOSX/CriMana.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: ba14ea67cbf77c64a830d06c4509d0f8 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/MacOSX/CriMana/Detail.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/MacOSX/CriMana/Detail.meta new file mode 100644 index 0000000..6dc7e2f --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/MacOSX/CriMana/Detail.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 3e43bf2102ffb8146a97ee8251425939 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/MacOSX/CriMana/Detail/RendererResources.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/MacOSX/CriMana/Detail/RendererResources.meta new file mode 100644 index 0000000..a43c2bb --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/MacOSX/CriMana/Detail/RendererResources.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: cceabf142838dcb4a8a13baa3d5f491a +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/MacOSX/CriMana/Detail/RendererResources/OSXH264Yuv.cs b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/MacOSX/CriMana/Detail/RendererResources/OSXH264Yuv.cs new file mode 100644 index 0000000..18b0d6c --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/MacOSX/CriMana/Detail/RendererResources/OSXH264Yuv.cs @@ -0,0 +1,227 @@ +/**************************************************************************** + * + * Copyright (c) 2015 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +#if UNITY_EDITOR_OSX || (!UNITY_EDITOR && UNITY_STANDALONE_OSX) +using UnityEngine; +using System.Runtime.InteropServices; + +namespace CriWare { + +namespace CriMana.Detail +{ + public static partial class AutoResisterRendererResourceFactories + { + [RendererResourceFactoryPriority(7000)] + public class RendererResourceFactoryOSXH264Yuv : RendererResourceFactory + { + public override RendererResource CreateRendererResource(int playerId, MovieInfo movieInfo, bool additive, Shader userShader) + { + bool isCodecSuitable = movieInfo.codecType == CodecType.H264; + bool isSuitable = isCodecSuitable; + return isSuitable + ? new RendererResourceOSXH264Yuv(playerId, movieInfo, additive, userShader) + : null; + } + + protected override void OnDisposeManaged() + { + } + + protected override void OnDisposeUnmanaged() + { + } + } + } + + public class RendererResourceOSXH264Yuv : RendererResource + { + private int width; + private int height; + private int playerId; + private bool useUserShader; + private Vector4 movieTextureST = Vector4.zero; + private Texture2D[] textures; + private RenderTexture[] renderTextures; + System.IntPtr[] nativePtrs; + private bool isStoppingForSeek = false; + private bool isStartTriggered = true; + private bool hasRenderedNewFrame = false; + + public RendererResourceOSXH264Yuv(int playerId, MovieInfo movieInfo, bool additive, Shader userShader) + { + this.width = (int)movieInfo.width; + this.height = (int)movieInfo.height; + this.playerId = playerId; + this.hasAlpha = movieInfo.hasAlpha; + this.additive = additive; + this.useUserShader = userShader != null; + + if (userShader != null) { + shader = userShader; + } else { + string shaderName = "CriMana/OSXH264Yuv"; + shader = Shader.Find(shaderName); + } + + if (hasAlpha) { + nativePtrs = new System.IntPtr[2]; + } else { + nativePtrs = new System.IntPtr[1]; + } + } + + protected override void OnDisposeManaged() + { + } + + protected override void OnDisposeUnmanaged() + { + DisposeTextures(textures); + DisposeTextures(renderTextures); + textures = null; + renderTextures = null; + currentMaterial = null; + } + + public override bool IsPrepared() + { return true; } + + public override bool ContinuePreparing() + { return true; } + + public override bool IsSuitable(int playerId, MovieInfo movieInfo, bool additive, Shader userShader) + { + bool isCodecSuitable = movieInfo.codecType == CodecType.H264; + bool isAlphaSuitable = hasAlpha == movieInfo.hasAlpha; + bool isAdditiveSuitable = this.additive == additive; + bool isShaderSuitable = this.useUserShader ? (userShader == shader) : true; + return isCodecSuitable && isAlphaSuitable && isAdditiveSuitable && isShaderSuitable; + } + + public override bool OnPlayerStopForSeek() + { + isStoppingForSeek = true; + isStartTriggered = false; + if (renderTextures != null || textures == null) { + return true; + } + renderTextures = new RenderTexture[hasAlpha ? 2 : 1]; + for (int i = 0; i < renderTextures.Length; i++) { + Texture2D baseTexture = textures[i]; + RenderTexture texture = new RenderTexture(baseTexture.width, baseTexture.height, 0, + i == 0 ? RenderTextureFormat.ARGB32 : RenderTextureFormat.R8); + texture.Create(); + Graphics.Blit(baseTexture, texture); + renderTextures[i] = texture; + } + forceUpdateMaterialTextures(renderTextures); + DisposeTextures(textures); + textures = null; + return true; + } + + public override void OnPlayerStart() + { + isStartTriggered = true; + } + + public override bool HasRenderedNewFrame() + { + return hasRenderedNewFrame; + } + + private void forceUpdateMaterialTextures(Texture[] newTextures) + { + if (currentMaterial != null) { + currentMaterial.mainTexture = newTextures[0]; + currentMaterial.SetTexture("_TextureRGB", newTextures[0]); + if (hasAlpha) { + currentMaterial.SetTexture("_TextureA", newTextures[1]); + } + } + } + + public override void AttachToPlayer(int playerId) + { + // reset texture if exist + DisposeTextures(textures); + textures = null; + hasRenderedNewFrame = false; + } + + public override bool UpdateFrame(int playerId, FrameInfo frameInfo, ref bool frameDrop) + { + bool isFrameUpdated = CRIWARE9061FF01(playerId, 0, null, frameInfo, ref frameDrop); + if (isFrameUpdated && !frameDrop) { + UpdateMovieTextureST(frameInfo.dispWidth, frameInfo.dispHeight); + } + + return isFrameUpdated; + } + + public override bool UpdateMaterial(Material material) + { + if (currentMaterial != material) { + if (textures != null || isStoppingForSeek) { + currentMaterial = material; + SetupStaticMaterialProperties(); + } else { + return false; + } + } + material.SetVector("_MovieTexture_ST", movieTextureST); + if (textures != null && !isStoppingForSeek) { + material.SetTexture("_TextureRGB", textures[0]); + if (hasAlpha) { + material.SetTexture("_TextureA", textures[1]); + } + DisposeTextures(renderTextures); + renderTextures = null; + hasRenderedNewFrame = true; + } + return true; + } + + private void UpdateMovieTextureST(System.UInt32 dispWidth, System.UInt32 dispHeight) + { + float uScale = (dispWidth != width) ? (float)(dispWidth - 0.5f) / width : 1.0f; + float vScale = (dispHeight != height) ? (float)(dispHeight - 0.5f) / height : 1.0f; + movieTextureST.x = uScale; + movieTextureST.y = -vScale; + movieTextureST.z = 0.0f; + movieTextureST.w = vScale; + } + + public override void UpdateTextures() + { + for (int i = 0; i < nativePtrs.Length; i++) { + nativePtrs[i] = System.IntPtr.Zero; + } + bool isTextureUpdated = CRIWAREDA63C3D7(playerId, nativePtrs.Length, nativePtrs); + if (isTextureUpdated && nativePtrs[0] != System.IntPtr.Zero && isStartTriggered) { + if (textures == null) { + textures = new Texture2D[2]; + textures[0] = Texture2D.CreateExternalTexture(width, height, TextureFormat.BGRA32, false, false, nativePtrs[0]); + textures[0].wrapMode = TextureWrapMode.Clamp; + if (hasAlpha) { + textures[1] = Texture2D.CreateExternalTexture(width, height, TextureFormat.R8, false, false, nativePtrs[1]); + textures[1].wrapMode = TextureWrapMode.Clamp; + } + } else { + textures[0].UpdateExternalTexture(nativePtrs[0]); + if (hasAlpha) { + textures[1].UpdateExternalTexture(nativePtrs[1]); + } + } + isStoppingForSeek = false; + } + } + } +} + +} //namespace CriWare + +#endif diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/MacOSX/CriMana/Detail/RendererResources/OSXH264Yuv.cs.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/MacOSX/CriMana/Detail/RendererResources/OSXH264Yuv.cs.meta new file mode 100644 index 0000000..e61e29c --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/MacOSX/CriMana/Detail/RendererResources/OSXH264Yuv.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 90d607173f1704c988704d3aed98260c +timeCreated: 1461031521 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/MacOSX/CriMana/Resources.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/MacOSX/CriMana/Resources.meta new file mode 100644 index 0000000..0ce4959 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/MacOSX/CriMana/Resources.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 18b37d25e817cb04f88473c6a7eb1f7f +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/MacOSX/CriMana/Resources/CriMana.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/MacOSX/CriMana/Resources/CriMana.meta new file mode 100644 index 0000000..21fdcc6 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/MacOSX/CriMana/Resources/CriMana.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 7d05e68ec8b2ea84f9fc2b883101751e +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/MacOSX/CriMana/Resources/CriMana/OSXH264Yuv.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/MacOSX/CriMana/Resources/CriMana/OSXH264Yuv.meta new file mode 100644 index 0000000..72a7586 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/MacOSX/CriMana/Resources/CriMana/OSXH264Yuv.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 9586ec280901aae4d876151aee8ab969 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/MacOSX/CriMana/Resources/CriMana/OSXH264Yuv/OSXH264Yuv.shader b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/MacOSX/CriMana/Resources/CriMana/OSXH264Yuv/OSXH264Yuv.shader new file mode 100644 index 0000000..bf14301 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/MacOSX/CriMana/Resources/CriMana/OSXH264Yuv/OSXH264Yuv.shader @@ -0,0 +1,99 @@ +Shader "CriMana/OSXH264Yuv" +{ + Properties + { + _MainTex ("Texture", 2D) = "white" {} + [HideInInspector] _MovieTexture_ST ("MovieTexture_ST", Vector) = (1.0, 1.0, 0, 0) + [HideInInspector] _TextureRGB("TextureRGB", 2D) = "white" {} + [HideInInspector] _TextureA("TextureA", 2D) = "white" {} + [HideInInspector] _SrcBlendMode("SrcBlendMode", Int) = 0 + [HideInInspector] _DstBlendMode("DstBlendMode", Int) = 0 + [HideInInspector] _CullMode("CullMode", Int) = 2 + [HideInInspector] _ZWriteMode("ZWriteMode", Int) = 1 + } + + SubShader + { + Tags + { + "Queue" = "Transparent" + "PreviewType"="Plane" + } + + Pass + { + Blend [_SrcBlendMode] [_DstBlendMode] + Cull [_CullMode] + ZWrite [_ZWriteMode] + ZTest [unity_GUIZTestMode] + + CGPROGRAM + #pragma vertex vert + #pragma fragment frag + #pragma fragmentoption ARB_precision_hint_fastest + + #include "UnityCG.cginc" + + #pragma multi_compile _ CRI_ALPHA_MOVIE + #pragma multi_compile _ CRI_APPLY_TARGET_ALPHA + #pragma multi_compile _ CRI_LINEAR_COLORSPACE + + struct appdata + { + float4 vertex : POSITION; + half2 texcoord : TEXCOORD0; +#ifdef CRI_APPLY_TARGET_ALPHA + float4 color : COLOR; +#endif + }; + + struct v2f + { + float4 pos : SV_POSITION; + half2 uv : TEXCOORD0; +#ifdef CRI_APPLY_TARGET_ALPHA + float4 color : COLOR; +#endif + }; + + float4 _MainTex_ST; + float4 _MovieTexture_ST; + + v2f vert(appdata v) + { + v2f o; + o.pos = UnityObjectToClipPos(v.vertex); + o.uv = (TRANSFORM_TEX(v.texcoord, _MainTex) * _MovieTexture_ST.xy) + _MovieTexture_ST.zw; +#ifdef CRI_APPLY_TARGET_ALPHA + o.color = v.color; +#endif + return o; + } + + sampler2D _TextureRGB; +#ifdef CRI_ALPHA_MOVIE + sampler2D _TextureA; +#endif + fixed _Transparency; + + fixed4 frag(v2f i) : COLOR + { + fixed4 color = tex2D(_TextureRGB, i.uv); +#ifdef CRI_ALPHA_MOVIE + fixed4 alpha = tex2D(_TextureA, i.uv); + color.a = alpha.r; +#endif +#ifdef CRI_LINEAR_COLORSPACE + color.rgb = pow(max(color.rgb, 0), 2.2); +#endif +#ifdef CRI_APPLY_TARGET_ALPHA + color.a = color.a * i.color.a; +#endif + color.a *= 1 - _Transparency; + + return color; + } + ENDCG + } + } +} diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/MacOSX/CriMana/Resources/CriMana/OSXH264Yuv/OSXH264Yuv.shader.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/MacOSX/CriMana/Resources/CriMana/OSXH264Yuv/OSXH264Yuv.shader.meta new file mode 100644 index 0000000..f1654f0 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/MacOSX/CriMana/Resources/CriMana/OSXH264Yuv/OSXH264Yuv.shader.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 3ecadf8cf71554c599b839bc4a1933ec +timeCreated: 1461226273 +licenseType: Pro +ShaderImporter: + defaultTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/MacOSX/cri_ware_unity.bundle.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/MacOSX/cri_ware_unity.bundle.meta new file mode 100644 index 0000000..e6a8b8e --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/MacOSX/cri_ware_unity.bundle.meta @@ -0,0 +1,34 @@ +fileFormatVersion: 2 +guid: f94522956777deb4e8d972962d38163b +folderAsset: yes +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 0 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + Any: + second: + enabled: 0 + settings: {} + - first: + Editor: Editor + second: + enabled: 1 + settings: + DefaultValueInitialized: true + - first: + Standalone: OSXUniversal + second: + enabled: 1 + settings: + CPU: AnyCPU + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/MacOSX/cri_ware_unity.bundle/Contents.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/MacOSX/cri_ware_unity.bundle/Contents.meta new file mode 100644 index 0000000..27899b8 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/MacOSX/cri_ware_unity.bundle/Contents.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 88559606d836bf24a993061c34c02e08 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/MacOSX/cri_ware_unity.bundle/Contents/Info.plist b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/MacOSX/cri_ware_unity.bundle/Contents/Info.plist new file mode 100644 index 0000000..09efd44 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/MacOSX/cri_ware_unity.bundle/Contents/Info.plist @@ -0,0 +1,50 @@ + + + + + BuildMachineOSBuild + 20G165 + CFBundleDevelopmentRegion + English + CFBundleExecutable + cri_ware_unity + CFBundleIdentifier + CRI-MIddleware.cri-ware-unity + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + cri_ware_unity + CFBundlePackageType + BNDL + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleSupportedPlatforms + + MacOSX + + CFBundleVersion + 1 + DTCompiler + com.apple.compilers.llvm.clang.1_0 + DTPlatformBuild + 12E262 + DTPlatformName + macosx + DTPlatformVersion + 11.3 + DTSDKBuild + 20E214 + DTSDKName + macosx11.3 + DTXcode + 1250 + DTXcodeBuild + 12E262 + LSMinimumSystemVersion + 10.8 + NSHumanReadableCopyright + Copyright © 2011 CRI Middleware Co., Ltd. All rights reserved. + + diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/MacOSX/cri_ware_unity.bundle/Contents/Info.plist.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/MacOSX/cri_ware_unity.bundle/Contents/Info.plist.meta new file mode 100644 index 0000000..cd30fe1 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/MacOSX/cri_ware_unity.bundle/Contents/Info.plist.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 46f76bc75ce101d4296a6a2cf1a54468 +timeCreated: 1433816075 +licenseType: Pro +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/MacOSX/cri_ware_unity.bundle/Contents/MacOS.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/MacOSX/cri_ware_unity.bundle/Contents/MacOS.meta new file mode 100644 index 0000000..11857d6 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/MacOSX/cri_ware_unity.bundle/Contents/MacOS.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: b42da6358acfc714f824d34950105eaa +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/MacOSX/cri_ware_unity.bundle/Contents/MacOS/cri_ware_unity b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/MacOSX/cri_ware_unity.bundle/Contents/MacOS/cri_ware_unity new file mode 100644 index 0000000..d259dce Binary files /dev/null and b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/MacOSX/cri_ware_unity.bundle/Contents/MacOS/cri_ware_unity differ diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/MacOSX/cri_ware_unity.bundle/Contents/MacOS/cri_ware_unity.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/MacOSX/cri_ware_unity.bundle/Contents/MacOS/cri_ware_unity.meta new file mode 100644 index 0000000..e287ef5 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/MacOSX/cri_ware_unity.bundle/Contents/MacOS/cri_ware_unity.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 389f1b8cdccb3dd41b4ce4196bebdf2c +timeCreated: 1433816075 +licenseType: Pro +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/PC.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/PC.meta new file mode 100644 index 0000000..ec116cc --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/PC.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: e5612404e556d7a4fbd0a90e33e403a0 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/PC/CriMana.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/PC/CriMana.meta new file mode 100644 index 0000000..14a48d1 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/PC/CriMana.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 1486e94701ec91a49bbf03853d7dcc6f +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/PC/CriMana/Detail.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/PC/CriMana/Detail.meta new file mode 100644 index 0000000..1fc6ca1 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/PC/CriMana/Detail.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: f9fd4d8483bedeb42af10f32fb1f5edc +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/PC/CriMana/Detail/RendererResources.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/PC/CriMana/Detail/RendererResources.meta new file mode 100644 index 0000000..1990277 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/PC/CriMana/Detail/RendererResources.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: c1acf7590ab665846b0f97f1e6964343 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/PC/CriMana/Detail/RendererResources/PCH264Yuv.cs b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/PC/CriMana/Detail/RendererResources/PCH264Yuv.cs new file mode 100644 index 0000000..bc2ce2b --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/PC/CriMana/Detail/RendererResources/PCH264Yuv.cs @@ -0,0 +1,55 @@ +/**************************************************************************** + * + * Copyright (c) 2018 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +#if UNITY_EDITOR_WIN || (!UNITY_EDITOR && UNITY_STANDALONE_WIN) + +using UnityEngine; +using System; +using System.Runtime.InteropServices; + +namespace CriWare { + +namespace CriMana.Detail +{ + public static partial class AutoResisterRendererResourceFactories + { + [RendererResourceFactoryPriority(7050)] + public class RendererResourceFactoryH264Yuv : RendererResourceFactory + { + public override RendererResource CreateRendererResource(int playerId, MovieInfo movieInfo, bool additive, Shader userShader) + { + bool isCodecSuitable = movieInfo.codecType == CodecType.H264; + bool isSuitable = isCodecSuitable; + return isSuitable + ? new RendererResourceH264Yuv(playerId, movieInfo, additive, userShader) + : null; + } + + protected override void OnDisposeManaged() + { + } + + protected override void OnDisposeUnmanaged() + { + } + } + } + + + + + public class RendererResourceH264Yuv : RendererResourceSofdecPrimeYuv + { + public RendererResourceH264Yuv(int playerId, MovieInfo movieInfo, bool additive, Shader userShader) + : base(playerId, movieInfo, additive, userShader) + { + } + } +} + +} //namespace CriWare + +#endif diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/PC/CriMana/Detail/RendererResources/PCH264Yuv.cs.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/PC/CriMana/Detail/RendererResources/PCH264Yuv.cs.meta new file mode 100644 index 0000000..0282922 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/PC/CriMana/Detail/RendererResources/PCH264Yuv.cs.meta @@ -0,0 +1,13 @@ +fileFormatVersion: 2 +guid: 22b685975748b4f458c2d610d4c0fa8a +timeCreated: 1519977517 +licenseType: Pro +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/PC/x86.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/PC/x86.meta new file mode 100644 index 0000000..88364af --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/PC/x86.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 0085654a191787142b488dd4b2f6f630 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/PC/x86/cri_ware_unity.dll b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/PC/x86/cri_ware_unity.dll new file mode 100644 index 0000000..01dd501 Binary files /dev/null and b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/PC/x86/cri_ware_unity.dll differ diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/PC/x86/cri_ware_unity.dll.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/PC/x86/cri_ware_unity.dll.meta new file mode 100644 index 0000000..edbf692 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/PC/x86/cri_ware_unity.dll.meta @@ -0,0 +1,170 @@ +fileFormatVersion: 2 +guid: 97f1044c5eb4800469ccddc26b4b5051 +timeCreated: 1426744594 +licenseType: Pro +PluginImporter: + serializedVersion: 2 + iconMap: {} + executionOrder: {} + isPreloaded: 0 + isOverridable: 0 + platformData: + data: + first: + '': Any + second: + enabled: 0 + settings: + Exclude Android: 1 + Exclude Editor: 0 + Exclude Linux: 1 + Exclude Linux64: 1 + Exclude LinuxUniversal: 1 + Exclude OSXIntel: 1 + Exclude OSXIntel64: 1 + Exclude OSXUniversal: 1 + Exclude WebGL: 1 + Exclude Win: 0 + Exclude Win64: 1 + Exclude WindowsStoreApps: 1 + Exclude iOS: 1 + Exclude tvOS: 1 + data: + first: + '': Editor + second: + enabled: 0 + settings: + CPU: x86 + OS: Windows + data: + first: + '': WP8 + second: + enabled: 0 + settings: + CPU: AnyCPU + DontProcess: False + PlaceholderPath: + data: + first: + Android: Android + second: + enabled: 0 + settings: + CPU: ARMv7 + data: + first: + Any: + second: + enabled: 0 + settings: {} + data: + first: + Editor: Editor + second: + enabled: 1 + settings: + CPU: x86 + DefaultValueInitialized: true + OS: Windows + data: + first: + Facebook: Win + second: + enabled: 1 + settings: + CPU: AnyCPU + data: + first: + Facebook: Win64 + second: + enabled: 0 + settings: + CPU: None + data: + first: + Standalone: Linux + second: + enabled: 0 + settings: + CPU: None + data: + first: + Standalone: Linux64 + second: + enabled: 0 + settings: + CPU: None + data: + first: + Standalone: LinuxUniversal + second: + enabled: 0 + settings: + CPU: None + data: + first: + Standalone: OSXIntel + second: + enabled: 0 + settings: + CPU: None + data: + first: + Standalone: OSXIntel64 + second: + enabled: 0 + settings: + CPU: None + data: + first: + Standalone: OSXUniversal + second: + enabled: 0 + settings: + CPU: None + data: + first: + Standalone: Win + second: + enabled: 1 + settings: + CPU: AnyCPU + data: + first: + Standalone: Win64 + second: + enabled: 0 + settings: + CPU: None + data: + first: + Windows Store Apps: WindowsStoreApps + second: + enabled: 0 + settings: + CPU: AnyCPU + DontProcess: False + PlaceholderPath: + SDK: AnySDK + ScriptingBackend: AnyScriptingBackend + data: + first: + iPhone: iOS + second: + enabled: 0 + settings: + CompileFlags: + FrameworkDependencies: + data: + first: + tvOS: tvOS + second: + enabled: 0 + settings: + CompileFlags: + FrameworkDependencies: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/PC/x86_64.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/PC/x86_64.meta new file mode 100644 index 0000000..2ea35f2 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/PC/x86_64.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: e98eac060c5549243955f09502bb8fe9 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/PC/x86_64/cri_ware_unity.dll b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/PC/x86_64/cri_ware_unity.dll new file mode 100644 index 0000000..579e96a Binary files /dev/null and b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/PC/x86_64/cri_ware_unity.dll differ diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/PC/x86_64/cri_ware_unity.dll.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/PC/x86_64/cri_ware_unity.dll.meta new file mode 100644 index 0000000..8f1d14e --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/PC/x86_64/cri_ware_unity.dll.meta @@ -0,0 +1,170 @@ +fileFormatVersion: 2 +guid: 11dc7019b5cfcce4fa41ab5aeed0d100 +timeCreated: 1426744594 +licenseType: Pro +PluginImporter: + serializedVersion: 2 + iconMap: {} + executionOrder: {} + isPreloaded: 0 + isOverridable: 0 + platformData: + data: + first: + '': Any + second: + enabled: 0 + settings: + Exclude Android: 1 + Exclude Editor: 0 + Exclude Linux: 1 + Exclude Linux64: 1 + Exclude LinuxUniversal: 1 + Exclude OSXIntel: 1 + Exclude OSXIntel64: 1 + Exclude OSXUniversal: 1 + Exclude WebGL: 1 + Exclude Win: 1 + Exclude Win64: 0 + Exclude WindowsStoreApps: 1 + Exclude iOS: 1 + Exclude tvOS: 1 + data: + first: + '': Editor + second: + enabled: 0 + settings: + CPU: x86_64 + OS: Windows + data: + first: + '': WP8 + second: + enabled: 0 + settings: + CPU: AnyCPU + DontProcess: False + PlaceholderPath: + data: + first: + Android: Android + second: + enabled: 0 + settings: + CPU: ARMv7 + data: + first: + Any: + second: + enabled: 0 + settings: {} + data: + first: + Editor: Editor + second: + enabled: 1 + settings: + CPU: x86_64 + DefaultValueInitialized: true + OS: Windows + data: + first: + Facebook: Win + second: + enabled: 0 + settings: + CPU: None + data: + first: + Facebook: Win64 + second: + enabled: 1 + settings: + CPU: AnyCPU + data: + first: + Standalone: Linux + second: + enabled: 0 + settings: + CPU: None + data: + first: + Standalone: Linux64 + second: + enabled: 0 + settings: + CPU: None + data: + first: + Standalone: LinuxUniversal + second: + enabled: 0 + settings: + CPU: None + data: + first: + Standalone: OSXIntel + second: + enabled: 0 + settings: + CPU: None + data: + first: + Standalone: OSXIntel64 + second: + enabled: 0 + settings: + CPU: None + data: + first: + Standalone: OSXUniversal + second: + enabled: 0 + settings: + CPU: None + data: + first: + Standalone: Win + second: + enabled: 0 + settings: + CPU: None + data: + first: + Standalone: Win64 + second: + enabled: 1 + settings: + CPU: AnyCPU + data: + first: + Windows Store Apps: WindowsStoreApps + second: + enabled: 0 + settings: + CPU: AnyCPU + DontProcess: False + PlaceholderPath: + SDK: AnySDK + ScriptingBackend: AnyScriptingBackend + data: + first: + iPhone: iOS + second: + enabled: 0 + settings: + CompileFlags: + FrameworkDependencies: + data: + first: + tvOS: tvOS + second: + enabled: 0 + settings: + CompileFlags: + FrameworkDependencies: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/iOS.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/iOS.meta new file mode 100644 index 0000000..854445a --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/iOS.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 68b614df2c042ad4398088c45c588c00 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/iOS/CriMana.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/iOS/CriMana.meta new file mode 100644 index 0000000..e191414 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/iOS/CriMana.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: c403dfd3a2abce649a9d6614ea01b477 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/iOS/CriMana/Detail.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/iOS/CriMana/Detail.meta new file mode 100644 index 0000000..5bebd63 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/iOS/CriMana/Detail.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 4076c7d5838e59547a5e9564d834c0ec +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/iOS/CriMana/Detail/RendererResources.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/iOS/CriMana/Detail/RendererResources.meta new file mode 100644 index 0000000..cf1a470 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/iOS/CriMana/Detail/RendererResources.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 8a40a096f7fd29442897934a830baf4f +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/iOS/CriMana/Detail/RendererResources/IOSH264Yuv.cs b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/iOS/CriMana/Detail/RendererResources/IOSH264Yuv.cs new file mode 100644 index 0000000..e52a96b --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/iOS/CriMana/Detail/RendererResources/IOSH264Yuv.cs @@ -0,0 +1,304 @@ +/**************************************************************************** + * + * Copyright (c) 2015 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +#if !UNITY_TVOS +#define CRIMANAUNITY_ENABLE_PAUSE_TEXTURE +#endif + +#if !UNITY_EDITOR && (UNITY_IOS || UNITY_TVOS) + +using UnityEngine; +using System.Runtime.InteropServices; + +namespace CriWare { + +namespace CriMana.Detail +{ + public static partial class AutoResisterRendererResourceFactories + { + [RendererResourceFactoryPriority(7000)] + public class RendererResourceFactoryIOSH264Yuv : RendererResourceFactory + { + public override RendererResource CreateRendererResource(int playerId, MovieInfo movieInfo, bool additive, Shader userShader) + { + bool isCodecSuitable = movieInfo.codecType == CodecType.H264; + bool isSuitable = isCodecSuitable; + return isSuitable + ? new RendererResourceIOSH264Yuv(playerId, movieInfo, additive, userShader) + : null; + } + + protected override void OnDisposeManaged() + { + } + + protected override void OnDisposeUnmanaged() + { + } + } + } + + + public class RendererResourceIOSH264Yuv : RendererResource + { + private int width; + private int height; + private int playerId; + private bool useUserShader; + private bool useOGLTempTextures; + private bool isPaused; + + private Vector4 movieTextureST = Vector4.zero; + + private Texture2D[] textures; + private RenderTexture[] pauseTextures; + private Texture[] currentTextures; + private System.IntPtr[] nativePtrs; + private bool isStoppingForSeek = false; + private bool isStartTriggered = true; + + public RendererResourceIOSH264Yuv(int playerId, MovieInfo movieInfo, bool additive, Shader userShader) + { + this.width = (int)movieInfo.width; + this.height = (int)movieInfo.height; + this.playerId = playerId; + hasAlpha = movieInfo.hasAlpha; + this.additive = additive; + useUserShader = userShader != null; + + if (userShader != null) { + shader = userShader; + } else { + string shaderName = "CriMana/IOSH264Yuv"; + shader = Shader.Find(shaderName); + } + + int numTextures = hasAlpha ? 3 : 2; + textures = new Texture2D[numTextures]; + nativePtrs = new System.IntPtr[numTextures]; + + UpdateMovieTextureST(movieInfo.dispWidth, movieInfo.dispHeight); + +#if (UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7 || UNITY_5_0) + useOGLTempTextures = SystemInfo.graphicsDeviceVersion.StartsWith("OpenGL"); +#else + useOGLTempTextures = (SystemInfo.graphicsDeviceType == UnityEngine.Rendering.GraphicsDeviceType.OpenGLES2); +#endif + currentTextures = textures; + } + + + protected override void OnDisposeManaged() + { + } + + + protected override void OnDisposeUnmanaged() + { + DisposeTextures(textures); + DisposeTextures(pauseTextures); + textures = null; + pauseTextures = null; + currentMaterial = null; + } + + + public override bool IsPrepared() + { return true; } + + + public override bool ContinuePreparing() + { return true; } + + public override bool IsSuitable(int playerId, MovieInfo movieInfo, bool additive, Shader userShader) + { + bool isCodecSuitable = movieInfo.codecType == CodecType.H264; + bool isAlphaSuitable = hasAlpha == movieInfo.hasAlpha; + bool isAdditiveSuitable = this.additive == additive; + bool isShaderSuitable = this.useUserShader ? (userShader == shader) : true; + return isCodecSuitable && isAlphaSuitable && isAdditiveSuitable && isShaderSuitable; + } + + public override void AttachToPlayer(int playerId) + { + DisposeTextures(textures); + if (!isStoppingForSeek) { + DisposeTextures(pauseTextures); + pauseTextures = null; + currentTextures = textures; + } + isPaused = false; + } + + // app did goes background / will goes foreground or player is paused + public override void OnPlayerPause(bool pauseStatus, bool triggredFromApplciationPause) + { +#if CRIMANAUNITY_ENABLE_PAUSE_TEXTURE + if (pauseStatus && !triggredFromApplciationPause) { + // Do nothing if the user code triggered Pause(true). + return; + } + + if (pauseStatus == true) { + if (isPaused == false && !isStoppingForSeek) { + isPaused = true; + applyCurrentTexturesToPausedTextures(); + } + } else { + isPaused = false; + } +#endif + } + + public override bool OnPlayerStopForSeek() { + isStoppingForSeek = true; + isStartTriggered = false; + if (pauseTextures != null || textures[0] == null) { + return true; + } + applyCurrentTexturesToPausedTextures(); + DisposeTextures(textures); + return true; + } + + public override void OnPlayerStart() { + isStartTriggered = true; + } + + private void restorePausedTextures() + { + forceUpdateMaterialTextures(textures); + DisposeTextures(pauseTextures); + pauseTextures = null; + } + + private void applyCurrentTexturesToPausedTextures() { + if (textures[0] == null) { + return; + } + pauseTextures = new RenderTexture[hasAlpha ? 3 : 2]; + for (int i = 0; i < pauseTextures.Length; i++) { + Texture2D baseTexture = textures[i]; + RenderTexture texture = new RenderTexture(baseTexture.width, baseTexture.height, 0, + i == 1 ? RenderTextureFormat.RG16 : RenderTextureFormat.R8); + texture.Create(); + Graphics.Blit(baseTexture, texture); + pauseTextures[i] = texture; + } + forceUpdateMaterialTextures(pauseTextures); + } + + private void forceUpdateMaterialTextures(Texture[] newTextures) + { + currentTextures = newTextures; + if (currentMaterial != null) { + currentMaterial.SetTexture("_TextureY", currentTextures[0]); + currentMaterial.SetTexture("_TextureUV", currentTextures[1]); + if (hasAlpha) { + currentMaterial.SetTexture("_TextureA", currentTextures[2]); + } + } + } + + public override bool UpdateFrame(int playerId, FrameInfo frameInfo, ref bool frameDrop) + { + bool isFrameUpdated = CRIWARE9061FF01(playerId, 0, null, frameInfo, ref frameDrop); + if (isFrameUpdated && !frameDrop) { + UpdateMovieTextureST(frameInfo.dispWidth, frameInfo.dispHeight); + } + return isFrameUpdated; + } + + public override bool UpdateMaterial(Material material) + { + if (currentTextures[0] != null) { + if (currentMaterial != material) { + currentMaterial = material; + SetupStaticMaterialProperties(); + } + + if (!(isPaused || isStoppingForSeek) && pauseTextures != null && + !CRIWARE98E7CD5C(playerId)) { + restorePausedTextures(); + isStoppingForSeek = false; + } else { + material.SetTexture("_TextureY", currentTextures[0]); + material.SetTexture("_TextureUV", currentTextures[1]); + if (hasAlpha) { + material.SetTexture("_TextureA", currentTextures[2]); + } + } + material.SetVector("_MovieTexture_ST", movieTextureST); + + return true; + } + return false; + } + + + private void UpdateMovieTextureST(System.UInt32 dispWidth, System.UInt32 dispHeight) + { + float uScale = (dispWidth != width) ? (float)(dispWidth - 0.5f) / width : 1.0f; + float vScale = (dispHeight != height) ? (float)(dispHeight - 0.5f) / height : 1.0f; + movieTextureST.x = uScale; + movieTextureST.y = -vScale; + movieTextureST.z = 0.0f; + movieTextureST.w = vScale; + } + + + public override void UpdateTextures() + { + int numTextures = hasAlpha ? 3 : 2; + for (int i = 0; i < numTextures; i++) { + nativePtrs[i] = System.IntPtr.Zero; + } + bool isTextureUpdated = CRIWAREDA63C3D7(playerId, numTextures, nativePtrs); // out textures + if (isTextureUpdated && nativePtrs[0] != System.IntPtr.Zero && isStartTriggered) { + if (useOGLTempTextures) { + for (int i = 0; i < numTextures; i++) { + if (textures[i] == null) { + textures[i] = Texture2D.CreateExternalTexture((i == 1) ? width / 2 : width, + (i == 1) ? height / 2 : height, + TextureFormat.Alpha8, false, false, nativePtrs[i]); + } + Texture2D tmptexture = Texture2D.CreateExternalTexture(textures[i].width, textures[i].height, + textures[i].format, false, false, nativePtrs[i]); + tmptexture.wrapMode = TextureWrapMode.Clamp; + textures[i].UpdateExternalTexture(tmptexture.GetNativeTexturePtr()); + Texture2D.Destroy(tmptexture); + } + } else { + if (textures[0] == null) { + for (int i = 0; i < numTextures; i++) { + textures[i] = Texture2D.CreateExternalTexture((i == 1) ? width / 2 : width, + (i == 1) ? height / 2 : height, + TextureFormat.Alpha8, false, false, nativePtrs[i]); + textures[i].wrapMode = TextureWrapMode.Clamp; + } + } else { + for (int i = 0; i < numTextures; i++) { + textures[i].UpdateExternalTexture(nativePtrs[i]); + } + } + } + isStoppingForSeek = false; + } + } +#region DLL Import +#if !CRIWARE_ENABLE_HEADLESS_MODE + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool CRIWARE98E7CD5C(int player_id); +#else + private static bool CRIWARE98E7CD5C(int player_id) { return false; } +#endif +#endregion + } +} + +} //namespace CriWare + +#endif diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/iOS/CriMana/Detail/RendererResources/IOSH264Yuv.cs.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/iOS/CriMana/Detail/RendererResources/IOSH264Yuv.cs.meta new file mode 100644 index 0000000..0abe26c --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/iOS/CriMana/Detail/RendererResources/IOSH264Yuv.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 94c1562415bc34e84ae61159d64be8ba +timeCreated: 1445063317 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/iOS/CriMana/Resources.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/iOS/CriMana/Resources.meta new file mode 100644 index 0000000..ea80f67 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/iOS/CriMana/Resources.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: b738fb39de55bf04082cd90d03122f77 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/iOS/CriMana/Resources/CriMana.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/iOS/CriMana/Resources/CriMana.meta new file mode 100644 index 0000000..b39cd52 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/iOS/CriMana/Resources/CriMana.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: ba8d491c70288244f8c3c7e611f5de1c +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/iOS/CriMana/Resources/CriMana/IOSH264Yuv.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/iOS/CriMana/Resources/CriMana/IOSH264Yuv.meta new file mode 100644 index 0000000..f0e219e --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/iOS/CriMana/Resources/CriMana/IOSH264Yuv.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 96ba295336ea5bb4180347189069a981 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/iOS/CriMana/Resources/CriMana/IOSH264Yuv/IOSH264Yuv.shader b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/iOS/CriMana/Resources/CriMana/IOSH264Yuv/IOSH264Yuv.shader new file mode 100644 index 0000000..da15a0c --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/iOS/CriMana/Resources/CriMana/IOSH264Yuv/IOSH264Yuv.shader @@ -0,0 +1,113 @@ +Shader "CriMana/IOSH264Yuv" +{ + Properties + { + _MainTex ("Texture", 2D) = "white" {} + [HideInInspector] _MovieTexture_ST ("MovieTexture_ST", Vector) = (1.0, 1.0, 0, 0) + [HideInInspector] _TextureY ("TextureY", 2D) = "white" {} + [HideInInspector] _TextureUV ("TextureUV", 2D) = "white" {} + [HideInInspector] _TextureA("TextureA", 2D) = "white" {} + [HideInInspector] _SrcBlendMode("SrcBlendMode", Int) = 0 + [HideInInspector] _DstBlendMode("DstBlendMode", Int) = 0 + [HideInInspector] _CullMode("CullMode", Int) = 2 + [HideInInspector] _ZWriteMode("ZWriteMode", Int) = 1 + } + + SubShader + { + Tags + { + "Queue" = "Transparent" + "PreviewType"="Plane" + } + + Pass + { + Blend [_SrcBlendMode] [_DstBlendMode] + Cull [_CullMode] + ZWrite [_ZWriteMode] + ZTest [unity_GUIZTestMode] + + CGPROGRAM + #pragma vertex vert + #pragma fragment frag + #pragma fragmentoption ARB_precision_hint_fastest + + #include "UnityCG.cginc" + + #pragma multi_compile _ CRI_ALPHA_MOVIE + #pragma multi_compile _ CRI_APPLY_TARGET_ALPHA + #pragma multi_compile _ CRI_LINEAR_COLORSPACE + + struct appdata + { + float4 vertex : POSITION; + half2 texcoord : TEXCOORD0; +#ifdef CRI_APPLY_TARGET_ALPHA + float4 color : COLOR; +#endif + }; + + struct v2f + { + float4 pos : SV_POSITION; + half2 uv : TEXCOORD0; +#ifdef CRI_APPLY_TARGET_ALPHA + float4 color : COLOR; +#endif + }; + + float4 _MainTex_ST; + float4 _MovieTexture_ST; + + v2f vert(appdata v) + { + v2f o; + o.pos = UnityObjectToClipPos(v.vertex); + o.uv = (TRANSFORM_TEX(v.texcoord, _MainTex) * _MovieTexture_ST.xy) + _MovieTexture_ST.zw; +#ifdef CRI_APPLY_TARGET_ALPHA + o.color = v.color; +#endif + return o; + } + + static const fixed3x3 yuv_to_rgb = { + {1.16438, 0.0, 1.59603}, + {1.16438, -0.39176, -0.81297}, + {1.16438, 2.01723, 0.0} + }; + + sampler2D _TextureY; + sampler2D _TextureUV; +#ifdef CRI_ALPHA_MOVIE + sampler2D _TextureA; +#endif + fixed _Transparency; + + fixed4 frag(v2f i) : COLOR + { + fixed3 yuv = { + (tex2D(_TextureY, i.uv).r - 0.06275), + (tex2D(_TextureUV, i.uv).rg - 0.50196) + }; + fixed4 color; + color.rgb = mul(yuv_to_rgb, yuv); +#ifdef CRI_LINEAR_COLORSPACE + color.rgb = pow(max(color.rgb, 0), 2.2); +#endif +#ifdef CRI_ALPHA_MOVIE + color.a = tex2D(_TextureA, i.uv).r; +#else + color.a = 1.0; +#endif +#ifdef CRI_APPLY_TARGET_ALPHA + color.a = color.a * i.color.a; +#endif + color.a *= 1 - _Transparency; + + return color; + } + ENDCG + } + } +} diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/iOS/CriMana/Resources/CriMana/IOSH264Yuv/IOSH264Yuv.shader.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/iOS/CriMana/Resources/CriMana/IOSH264Yuv/IOSH264Yuv.shader.meta new file mode 100644 index 0000000..091d907 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/iOS/CriMana/Resources/CriMana/IOSH264Yuv/IOSH264Yuv.shader.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 656f87fa1d9f944d58250696a84e9156 +timeCreated: 1445063698 +licenseType: Pro +ShaderImporter: + defaultTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/iOS/libcri_ware_unity.a b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/iOS/libcri_ware_unity.a new file mode 100644 index 0000000..c5b7310 Binary files /dev/null and b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/iOS/libcri_ware_unity.a differ diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/iOS/libcri_ware_unity.a.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/iOS/libcri_ware_unity.a.meta new file mode 100644 index 0000000..f7145c2 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Platforms/iOS/libcri_ware_unity.a.meta @@ -0,0 +1,158 @@ +fileFormatVersion: 2 +guid: 7ffa5e8469874b54bbf51f0e75e154fa +timeCreated: 1433816085 +licenseType: Pro +PluginImporter: + serializedVersion: 2 + iconMap: {} + executionOrder: {} + isPreloaded: 0 + isOverridable: 0 + platformData: + data: + first: + '': Any + second: + enabled: 0 + settings: + Exclude Android: 1 + Exclude Editor: 1 + Exclude Linux: 1 + Exclude Linux64: 1 + Exclude LinuxUniversal: 1 + Exclude OSXIntel: 1 + Exclude OSXIntel64: 1 + Exclude OSXUniversal: 1 + Exclude WebGL: 1 + Exclude Win: 1 + Exclude Win64: 1 + Exclude WindowsStoreApps: 1 + Exclude iOS: 0 + Exclude tvOS: 1 + data: + first: + '': Editor + second: + enabled: 0 + settings: + CPU: AnyCPU + OS: AnyOS + data: + first: + Android: Android + second: + enabled: 0 + settings: + CPU: ARMv7 + data: + first: + Any: + second: + enabled: 0 + settings: + Exclude Android: 1 + Exclude Editor: 1 + Exclude Linux: 1 + Exclude Linux64: 1 + Exclude LinuxUniversal: 1 + Exclude OSXIntel: 1 + Exclude OSXIntel64: 1 + Exclude OSXUniversal: 1 + Exclude WebGL: 1 + Exclude Win: 1 + Exclude Win64: 1 + Exclude iOS: 0 + Exclude tvOS: 1 + data: + first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + data: + first: + Facebook: Win + second: + enabled: 0 + settings: + CPU: AnyCPU + data: + first: + Facebook: Win64 + second: + enabled: 0 + settings: + CPU: AnyCPU + data: + first: + Standalone: Linux + second: + enabled: 0 + settings: + CPU: x86 + data: + first: + Standalone: Linux64 + second: + enabled: 0 + settings: + CPU: x86_64 + data: + first: + Standalone: OSXIntel + second: + enabled: 0 + settings: + CPU: AnyCPU + data: + first: + Standalone: OSXIntel64 + second: + enabled: 0 + settings: + CPU: AnyCPU + data: + first: + Standalone: Win + second: + enabled: 0 + settings: + CPU: AnyCPU + data: + first: + Standalone: Win64 + second: + enabled: 0 + settings: + CPU: AnyCPU + data: + first: + Windows Store Apps: WindowsStoreApps + second: + enabled: 0 + settings: + CPU: AnyCPU + DontProcess: False + PlaceholderPath: + SDK: AnySDK + ScriptingBackend: AnyScriptingBackend + data: + first: + iPhone: iOS + second: + enabled: 1 + settings: + CompileFlags: + FrameworkDependencies: + data: + first: + tvOS: tvOS + second: + enabled: 0 + settings: + CompileFlags: + FrameworkDependencies: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts.meta new file mode 100644 index 0000000..61255a8 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 3ce84d2ef51a0b341ad70b233b61bfa0 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom.meta new file mode 100644 index 0000000..be0b488 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: a828a7fe5697c384c8e4decaa8373824 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/CriAtom.cs b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/CriAtom.cs new file mode 100644 index 0000000..c071afe --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/CriAtom.cs @@ -0,0 +1,1689 @@ +/**************************************************************************** + * + * Copyright (c) 2011 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +/*--------------------------- + * Force Load Data with Async Method Defines + *---------------------------*/ +#if UNITY_WEBGL + #define CRIWARE_FORCE_LOAD_ASYNC +#endif + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using System.IO; +using UnityEngine; +using UnityEngine.Events; +#if !UNITY_EDITOR && (UNITY_WINRT && !ENABLE_IL2CPP) +using System.Reflection; +#endif + +/*========================================================================== + * CRI Atom Unity Integration + *=========================================================================*/ + +/** + * \addtogroup CRIATOM_UNITY_INTEGRATION + * @{ + */ + +namespace CriWare { + +/** + * Global class of the CRI Atom library. + * + * Class that contains the initialization functions of the CRI Atom library as well as the definitions of the types used within the library.
+ *
+ */ +public static class CriAtomPlugin +{ + #region Editor/Runtime共通 + +#if UNITY_EDITOR + public static bool showDebugLog = false; + public delegate void PreviewCallback(); + public static PreviewCallback previewCallback = null; +#endif + + public static void Log(string log) + { + #if UNITY_EDITOR + if (CriAtomPlugin.showDebugLog) { + Debug.Log(log); + } + #endif + } + + /* 初期化カウンタ */ + private static int initializationCount = 0; + + public static bool isInitialized { get { return initializationCount > 0; } } + + /** + * Execution of the Cue Link callback + * + * A function to execute a Cue Link callback event triggered by the Atom Server thread.
+ * When this function is called, the callback function registered in CriAtomEx::OnCueLinkCallback will be executed if an event has occurred.
+ * This function is called periodically by the CriAtomServer component and usually does not need to be called by the user.
+ * Calls this function if callbacks are needed when the application is not running (e.g. in an Editor extension).
+ *
+ */ + public static void ExecuteQueuedCueLinkCallbacks() + { + CRIWARE85890687(); + } + + /** + * Execution of the sequence event callback + * + * A function to execute a callback event synchronized with a callback marker triggered by the Atom Server thread.
+ * When this function is called, the callback function registered in CriAtomExSequencer::OnCallback will be executed if an event has occurred.
+ * This function is called periodically by the CriAtomServer component and usually does not need to be called by the user.
+ * Calls this function if callbacks are needed when the application is not running (e.g. in an Editor extension).
+ *
+ */ + public static void ExecuteQueuedEventCallbacks() + { + CRIWAREC0C8F361(); + } + + /** + * Execution of the beat synchronization callback + * + * A function to execute a beat-synchronized callback event triggered by the Atom Server thread.
+ * When this function is called, the callback functions registered in CriAtomExPlayer::OnBeatSyncCallback and CriAtomExBeatSync::OnCallback will be executed if an event has occurred.
+ * This function is called periodically by the CriAtomServer component and usually does not need to be called by the user.
+ * Calls this function if callbacks are needed when the application is not running (e.g. in an Editor extension).
+ *
+ */ + public static void ExecuteQueuedBeatSyncCallbacks() + { + CRIWARE49850D78(); + } + + private static List effectInterfaceList = null; + public static bool GetAudioEffectInterfaceList(out List effect_interface_list) + { + if (CriAtomPlugin.IsLibraryInitialized() == true) { + effect_interface_list = null; + return false; + } + if (effectInterfaceList == null) { + effectInterfaceList = new List(); + } + effect_interface_list = effectInterfaceList; + return true; + } + + /* @cond excludele */ + private static IntPtr GetSpatializerCoreInterfaceFromAtomOculusAudioBridge() + { + /* Ambisonic データを再生するために、プラットフォームによってはブリッジプラグインを必要とするかもしれない + * 例えば PC では Oculus Audio ブリッジプラグインを使う。 + * 例えば PS4 では ブリッジプラグインを使わない */ + /* 以下、CRI Atom Oculus Audio ブリッジプラグインがインポートされている場合の処理 */ + Type type = Type.GetType("CriAtomOculusAudio"); + if (type == null) { + /* BridgePluginが見つからなかった */ + Debug.LogError("[CRIWARE] ERROR: Cri Atom Oculus Audio Bridge Plugin is not imported."); + } else { + /* 現在のプラットフォームは Oculus Audio Bridge Plugin をサポートしているか確認 */ +#if !UNITY_EDITOR && (UNITY_WINRT && !ENABLE_IL2CPP) + System.Reflection.MethodInfo method_support_current_platform = type.GetTypeInfo().GetDeclaredMethod("SupportCurrentPlatform"); +#else + System.Reflection.MethodInfo method_support_current_platform = type.GetMethod("SupportCurrentPlatform"); +#endif + if (method_support_current_platform == null) { + Debug.LogError("[CRIWARE] ERROR: CriAtomOculusAudio.SupportCurrentPlatform method is not found."); + return IntPtr.Zero; + } + bool current_platform_supports_oculus_audio = (bool)method_support_current_platform.Invoke(null, null); + /* カレントプラットフォームをサポートしているなら準備。 + * サポートしていないならスキップ。引き続き Atom 初期化処理を行う */ + if (current_platform_supports_oculus_audio) { + /* 必要なメソッド情報を取得 */ +#if !UNITY_EDITOR && (UNITY_WINRT && !ENABLE_IL2CPP) + System.Reflection.MethodInfo method_get_spatializer_core_interface = type.GetTypeInfo().GetDeclaredMethod("GetSpatializerCoreInterface"); +#else + System.Reflection.MethodInfo method_get_spatializer_core_interface = type.GetMethod("GetSpatializerCoreInterface"); +#endif + if (method_get_spatializer_core_interface == null) { + Debug.LogError("[CRIWARE] ERROR: CriAtomOculusAudio.GetSpatializerCoreInterface method is not found."); + return IntPtr.Zero; + } + /* Spatilalizer の初期化に必要な情報を取得 */ + return (IntPtr)method_get_spatializer_core_interface.Invoke(null, null); + } + } + return IntPtr.Zero; + } + /* @endcond */ + + public static void SetConfigParameters(int max_virtual_voices, + int max_voice_limit_groups, int max_categories, + int max_aisacs, int max_bus_sends, + int max_sequence_events_per_frame, int max_beatsync_callbacks_per_frame, + int max_cuelink_callbacks_per_frame, + int num_standard_memory_voices, int num_standard_streaming_voices, + int num_hca_mx_memory_voices, int num_hca_mx_streaming_voices, + int output_sampling_rate, int num_asr_output_channels, + bool uses_in_game_preview, float server_frequency, + int max_parameter_blocks, int categories_per_playback, + int max_faders, int num_buses, bool vr_mode) + { + IntPtr spatializer_core_interface = IntPtr.Zero; + /* @cond excludele */ + /* Ambisonic データの再生に必要な初期化パラメータを取得する */ + if (vr_mode) { +#if UNITY_EDITOR_WIN || (!UNITY_EDITOR && (UNITY_STANDALONE_WIN || UNITY_ANDROID)) + spatializer_core_interface = CriAtomPlugin.GetSpatializerCoreInterfaceFromAtomOculusAudioBridge(); +#endif + } +#if UNITY_WEBGL + /* WebGLでは普通のボイスは作成することができない */ + num_standard_memory_voices = 0; + num_standard_streaming_voices = 0; + num_hca_mx_memory_voices = 0; + num_hca_mx_streaming_voices = 0; +#endif + /* @endcond */ + CRIWAREB44093D4(max_virtual_voices, + max_voice_limit_groups, max_categories, + max_aisacs, max_bus_sends, + max_sequence_events_per_frame, max_beatsync_callbacks_per_frame, + max_cuelink_callbacks_per_frame, + num_standard_memory_voices, num_standard_streaming_voices, + num_hca_mx_memory_voices, num_hca_mx_streaming_voices, + output_sampling_rate, num_asr_output_channels, + uses_in_game_preview, server_frequency, + max_parameter_blocks, categories_per_playback, + max_faders, num_buses, vr_mode, + spatializer_core_interface); + + CriAtomPlugin.isConfigured = true; + } + + public static void SetConfigMonitorParametes(int max_preview_objects, + int communication_buffer_size, int playback_position_update_interval) + { + Debug.Assert(max_preview_objects >= 0 && communication_buffer_size >= 0 && playback_position_update_interval >= 0); + CRIWARED77F25E8((uint)max_preview_objects, + (uint)(communication_buffer_size * 1024), playback_position_update_interval); + } + + public static void SetConfigAdditionalParameters_EDITOR(bool enable_user_pcm_output, int user_pcm_buffer_length) + { + CRIWAREC0366CD7(enable_user_pcm_output); + CriAtomExAsr.SetPcmBufferSize(user_pcm_buffer_length); + } + + public static void SetConfigAdditionalParameters_PC(long buffering_time_pc) + { + CRIWAREE250CF9E(buffering_time_pc); + } + + /* @cond excludele */ + public static void SetConfigAdditionalParameters_LINUX(CriAtomConfig.LinuxOutput output, int pulse_latency_usec) + { + CRIWARE663D7320((int)output, pulse_latency_usec); + } + /* @endcond */ + + public static void SetConfigAdditionalParameters_IOS(bool enable_sonicsync, uint buffering_time_ios, bool override_ipod_music_ios) + { + CRIWARE151EFBE4(enable_sonicsync, buffering_time_ios, override_ipod_music_ios); + } + + public static void SetConfigAdditionalParameters_ANDROID(bool enable_sonicsync, + int num_low_delay_memory_voices, int num_low_delay_streaming_voices, + int sound_buffering_time, int sound_start_buffering_time, + bool use_fast_mixer, bool use_aaudio) + { + CRIWAREC29D25E6(enable_sonicsync, + num_low_delay_memory_voices, num_low_delay_streaming_voices, + sound_buffering_time, sound_start_buffering_time, + use_fast_mixer); +#if !UNITY_EDITOR && UNITY_ANDROID + if (use_fast_mixer == true) { + IntPtr android_context = IntPtr.Zero; + using (AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer")) + using (AndroidJavaObject activity = jc.GetStatic("currentActivity")) { + android_context = activity.GetRawObject(); + CRIWAREA6D52E14(android_context); + } + } + CRIWARE2BFCED9D(use_aaudio); +#endif + } + + /* @cond excludele */ + public static void SetConfigAdditionalParameters_VITA(int num_atrac9_memory_voices, int num_atrac9_streaming_voices, int num_mana_decoders) + { + #if !UNITY_EDITOR && UNITY_PSP2 + CRIWAREC9DFF2DD(num_atrac9_memory_voices, num_atrac9_streaming_voices, num_mana_decoders); + #endif + } + + public static void SetConfigAdditionalParameters_PS4(int num_atrac9_memory_voices, int num_atrac9_streaming_voices, + bool use_audio3d, int num_audio3d_memory_voices, int num_audio3d_streaming_voices) + { + #if !UNITY_EDITOR && (UNITY_PS4 || UNITY_PS5) + CRIWAREE2464C15(num_atrac9_memory_voices, num_atrac9_streaming_voices, + use_audio3d, num_audio3d_memory_voices, num_audio3d_streaming_voices); + #endif + } + + public static void SetConfigAdditionalParameters_SWITCH(bool enable_sonicsync, int num_opus_memory_voices, + int num_opus_streaming_voices, bool init_socket) { + #if !UNITY_EDITOR && UNITY_SWITCH + CRIWAREEDEC7BC7(enable_sonicsync, num_opus_memory_voices, num_opus_streaming_voices, init_socket); + #endif + } + + public static void SetConfigAdditionalParameters_WEBGL(int num_webaudio_voices) + { + #if UNITY_WEBGL + CRIWARE21B0F3E2(num_webaudio_voices); + #endif + } + /* @endcond */ + + public static void SetMaxSamplingRateForStandardVoicePool(int sampling_rate_for_memory, int sampling_rate_for_streaming) + { + CRIWARE219A582D(sampling_rate_for_memory, sampling_rate_for_streaming); + } + + public static int GetRequiredMaxVirtualVoices(CriAtomConfig atomConfig) + { + /* バーチャルボイスは、全ボイスプールのボイスの合計値よりも多くなくてはならない */ + int requiredVirtualVoices = 0; + + requiredVirtualVoices += atomConfig.standardVoicePoolConfig.memoryVoices; + requiredVirtualVoices += atomConfig.standardVoicePoolConfig.streamingVoices; + requiredVirtualVoices += atomConfig.hcaMxVoicePoolConfig.memoryVoices; + requiredVirtualVoices += atomConfig.hcaMxVoicePoolConfig.streamingVoices; + + #if UNITY_ANDROID + requiredVirtualVoices += atomConfig.androidLowLatencyStandardVoicePoolConfig.memoryVoices; + requiredVirtualVoices += atomConfig.androidLowLatencyStandardVoicePoolConfig.streamingVoices; + /* @cond excludele */ + #elif UNITY_PSP2 + requiredVirtualVoices += atomConfig.vitaAtrac9VoicePoolConfig.memoryVoices; + requiredVirtualVoices += atomConfig.vitaAtrac9VoicePoolConfig.streamingVoices; + /* @endcond */ + #endif + + return requiredVirtualVoices; + } + + public static void InitializeLibrary() + { + /* 初期化カウンタの更新 */ + CriAtomPlugin.initializationCount++; + if (CriAtomPlugin.initializationCount != 1) { + return; + } + + /* シーン実行前に初期化済みの場合は終了させる */ + if (CriAtomPlugin.IsLibraryInitialized() == true) { + CriAtomPlugin.FinalizeLibrary(); + CriAtomPlugin.initializationCount = 1; + } + + /* 初期化パラメータが設定済みかどうかを確認 */ + if (CriAtomPlugin.isConfigured == false) { + Debug.Log("[CRIWARE] Atom initialization parameters are not configured. " + + "Initializes Atom by default parameters."); + } + + /* 依存ライブラリの初期化 */ + CriFsPlugin.InitializeLibrary(); + + /* ライブラリの初期化 */ + CriAtomPlugin.CRIWARE9AA6A10A(); + + /* @cond excludele */ + /* ユーザカスタムエフェクトプラグインのインタフェースを登録 */ + #if !UNITY_EDITOR && UNITY_PSP2 + // unsupported + #else + if (effectInterfaceList != null) + { + for (int i = 0; i < effectInterfaceList.Count; i++) + { + CriAtomExAsr.RegisterEffectInterface(effectInterfaceList[i]); + } + } + #endif + /* @endcond */ + + /* CriAtomServerのインスタンスを生成 */ + #if UNITY_EDITOR + /* ゲームプレビュー時のみ生成する */ + if (UnityEngine.Application.isPlaying) { + CriAtomServer.CreateInstance(); + } + #else + CriAtomServer.CreateInstance(); + #endif + + /* CriAtomListenerが存在しない場合のためのダミーリスナーを生成 */ + CriAtomListener.CreateDummyNativeListener(); + } + + public static bool IsLibraryInitialized() + { + /* ライブラリが初期化済みかチェック */ + return CRIWARE2AC85FB9(); + } + + public static void FinalizeLibrary() + { + /* 初期化カウンタの更新 */ + CriAtomPlugin.initializationCount--; + if (CriAtomPlugin.initializationCount < 0) { + CriAtomPlugin.initializationCount = 0; + if (CriAtomPlugin.IsLibraryInitialized() == false) { + return; + } + } + if (CriAtomPlugin.initializationCount != 0) { + return; + } + + /* CriAtomListenerが存在しない場合のためのダミーリスナーを破棄 */ + CriAtomListener.DestroyDummyNativeListener(); + + /* CriAtomServerのインスタンスを破棄 */ + CriAtomServer.DestroyInstance(); + + /* 未破棄のDisposableを破棄 */ + CriDisposableObjectManager.CallOnModuleFinalization(CriDisposableObjectManager.ModuleType.Atom); + + /* ユーザエフェクトインタフェースのリストをクリア */ + if (effectInterfaceList != null) { + effectInterfaceList.Clear(); + effectInterfaceList = null; + } + + /* ライブラリの終了 */ + CriAtomPlugin.CRIWARE04B66F6D(); + + /* 依存ライブラリの終了 */ + CriFsPlugin.FinalizeLibrary(); + } + + public static void Pause(bool pause) + { + if (isInitialized) { + CRIWAREF71E04E6(pause); + } + } + + #if !UNITY_EDITOR && UNITY_IOS + public static void CallOnApplicationResume_IOS() + { + criAtomUnity_SleepToDelay_IOS(100); + } + #endif + + private static bool isConfigured = false; + private static float timeSinceStartup = Time.realtimeSinceStartup; + private static CriWare.Common.CpuUsage cpuUsage; + public static CriWare.Common.CpuUsage GetCpuUsage() + { + float currentTimeSinceStartup = Time.realtimeSinceStartup; + if (currentTimeSinceStartup - timeSinceStartup > 1.0f) { + CriAtomEx.PerformanceInfo info; + CriAtomEx.GetPerformanceInfo(out info); + + cpuUsage.last = info.lastServerTime * 100.0f / info.averageServerInterval; + cpuUsage.average = info.averageServerTime * 100.0f / info.averageServerInterval; + cpuUsage.peak = info.maxServerTime * 100.0f / info.averageServerInterval; + + CriAtomEx.ResetPerformanceMonitor(); + timeSinceStartup = currentTimeSinceStartup; + } + return cpuUsage; + } + + /** + * Gets the output sampling rate + * Output sampling rate + * + * Gets the sampling rate of the PCM data output by the Atom library. + * + */ + public static int GetOutputSamplingRate() + { + return CRIWARE899CB391(); + } + + + /** + * Gets the number of output channels + * The number of output channels + * + * Gets the number of channels of the PCM data output by the Atom library. + * + */ + public static int GetOutputChannels() + { + return CRIWAREE8138117(); + } + + public static bool IsInitializedForPcmOutput() + { + #if UNITY_EDITOR + return CRIWARE7955C029(); + #else + return false; + #endif + } + + private static int CRIATOMUNITY_PARAMETER_ID_LOOP_COUNT = 0; + private static ushort CRIATOMPARAMETER2_ID_INVALID = ushort.MaxValue; + + public static ushort GetLoopCountParameterId() + { + ushort ret = CRIWARE43EC6991(CRIATOMUNITY_PARAMETER_ID_LOOP_COUNT); + if (ret == CRIATOMPARAMETER2_ID_INVALID) { + throw new Exception("GetNativeParameterId failed."); + } + return ret; + } + + /* @cond notpublic */ + public static void DecryptAcb(IntPtr acb_hn, ulong key, ulong nonce) + { + temporalStorage = key ^ 0x0017D207B5350050UL; + CRIWARE0597FC3A(acb_hn, CallbackFromNative, IntPtr.Zero); + temporalStorage = 0; + } + /* @endcond */ + + /* @cond notpublic */ + /* 変数の一時的な格納場所 */ + private static ulong temporalStorage = 0; + /* @endcond */ + + #region Private Methods + /* @cond notpublic */ + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public delegate ulong CallbackFromNativeDelegate(System.IntPtr ptr1); + + [AOT.MonoPInvokeCallback(typeof(CallbackFromNativeDelegate))] + private static ulong CallbackFromNative(System.IntPtr ptr1) + { + return temporalStorage; + } + /* @endcond */ + #endregion + + #region DLL Import + #if !CRIWARE_ENABLE_HEADLESS_MODE + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void CRIWAREB44093D4(int max_virtual_voices, + int max_voice_limit_groups, int max_categories, + int max_aisacs, int max_bus_sends, + int max_sequence_events_per_frame, int max_beatsync_callbacks_per_frame, + int max_cuelink_callbacks_per_frame, + int num_standard_memory_voices, int num_standard_streaming_voices, + int num_hca_mx_memory_voices, int num_hca_mx_streaming_voices, + int output_sampling_rate, int num_asr_output_channels, + bool uses_in_game_preview, float server_frequency, + int max_parameter_blocks, int categories_per_playback, + int max_faders, int num_buses, bool use_ambisonics, + IntPtr spatializer_core_interface); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void CRIWARED77F25E8(uint max_preivew_objects, + uint communication_buffer_size, int playback_position_update_interval); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void CRIWAREC0366CD7(bool enable_user_pcm_out_mode); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void CRIWAREE250CF9E(long buffering_time_pc); + + /* @cond excludele */ + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void CRIWARE663D7320(int output, int pulse_latency_usec); + /* @endcond */ + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void CRIWARE151EFBE4(bool enable_sonicsync, uint buffering_time_ios, bool override_ipod_music_ios); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void CRIWAREC29D25E6(bool enable_sonicsync, + int num_low_delay_memory_voices, int num_low_delay_streaming_voices, + int sound_buffering_time, int sound_start_buffering_time, + bool apply_hw_property); + + #if !UNITY_EDITOR && UNITY_ANDROID + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void CRIWAREA6D52E14(IntPtr android_context); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void CRIWARE2BFCED9D(bool flag); + #endif + + /* @cond excludele */ + #if !UNITY_EDITOR && UNITY_PSP2 + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void CRIWAREC9DFF2DD(int num_atrac9_memory_voices, int num_atrac9_streaming_voices, int num_mana_decoders); + #endif + + #if !UNITY_EDITOR && (UNITY_PS4 || UNITY_PS5) + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void CRIWAREE2464C15(int num_atrac9_memory_voices, int num_atrac9_streaming_voices, + bool use_audio3d, int num_audio3d_memory_voices, int num_audio3d_streaming_voices); + #endif + + #if !UNITY_EDITOR && UNITY_SWITCH + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void CRIWAREEDEC7BC7(bool enable_sonicsync, int num_opus_memory_voices, + int num_opus_streaming_voices, bool init_socket); + #endif + + #if UNITY_WEBGL + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void CRIWARE21B0F3E2(int num_webaudio_voices); + #endif + /* @endcond */ + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void CRIWARE9AA6A10A(); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + public static extern bool CRIWARE2AC85FB9(); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void CRIWARE04B66F6D(); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void CRIWAREF71E04E6(bool pause); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + public static extern uint CRIWARE581F45FE(); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + public static extern void CRIWARE873820B1(int code); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + public static extern void CRIWARE61D452DC(IntPtr cbfunc, string separator_string); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + public static extern void CRIWAREACA4DD5F(IntPtr cbfunc); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void CRIWAREC0C8F361(); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + public static extern void CRIWAREC739641B(IntPtr cbfunc); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void CRIWARE49850D78(); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + public static extern void CRIWAREEF0CC849(IntPtr cbfunc); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void CRIWARE85890687(); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void CRIWARE219A582D(int sampling_rate_for_memory, int sampling_rate_for_streaming); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + public static extern void CRIWARE80063D84(); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + public static extern void CRIWARE2294A8CF(); + + /* @cond notpublic */ + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + public static extern void CRIWARE0597FC3A(IntPtr acb_hn, CallbackFromNativeDelegate func, IntPtr obj); + /* @endcond */ + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + public static extern ushort CRIWARE43EC6991(int id); + + #if !UNITY_EDITOR && UNITY_IOS + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + public static extern void criAtomUnity_SleepToDelay_IOS(int milliseconds); + #endif + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool CRIWARE7955C029(); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int CRIWARE899CB391(); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int CRIWAREE8138117(); + + #else + private static void CRIWAREB44093D4(int max_virtual_voices, + int max_voice_limit_groups, int max_categories, + int max_aisacs, int max_bus_sends, + int max_sequence_events_per_frame, int max_beatsync_callbacks_per_frame, + int max_cuelink_callbacks_per_frame, + int num_standard_memory_voices, int num_standard_streaming_voices, + int num_hca_mx_memory_voices, int num_hca_mx_streaming_voices, + int output_sampling_rate, int num_asr_output_channels, + bool uses_in_game_preview, float server_frequency, + int max_parameter_blocks, int categories_per_playback, + int max_faders, int num_buses, bool use_ambisonics, + IntPtr spatializer_core_interface) { } + private static void CRIWARED77F25E8(uint max_preivew_objects, + uint communication_buffer_size, int playback_position_update_interval) { } + private static void CRIWAREC0366CD7(bool enable_user_pcm_out_mode) { } + private static void CRIWAREE250CF9E(long buffering_time_pc) { } + /* @cond excludele */ + private static void CRIWARE663D7320(int output, int pulse_latency_usec) { } + /* @endcond */ + private static void CRIWARE151EFBE4(bool enable_sonicsync, uint buffering_time_ios, bool override_ipod_music_ios) { } + private static void CRIWAREC29D25E6(bool enable_sonicsync, + int num_low_delay_memory_voices, int num_low_delay_streaming_voices, + int sound_buffering_time, int sound_start_buffering_time, + bool apply_hw_property) { } + #if !UNITY_EDITOR && UNITY_ANDROID + private static void CRIWAREA6D52E14(IntPtr android_context) { } + private static void CRIWARE2BFCED9D(bool flag) { } + #endif + + /* @cond excludele */ + #if !UNITY_EDITOR && UNITY_PSP2 + private static void CRIWAREC9DFF2DD(int num_atrac9_memory_voices, int num_atrac9_streaming_voices, + int num_mana_decoders) { } + #endif + #if !UNITY_EDITOR && UNITY_PS4 + private static void CRIWAREE2464C15(int num_atrac9_memory_voices, int num_atrac9_streaming_voices, + bool use_audio3d, int num_audio3d_memory_voices, int num_audio3d_streaming_voices) { } + #endif + #if !UNITY_EDITOR && UNITY_SWITCH + private static void CRIWAREEDEC7BC7(bool enable_sonicsync, int num_opus_memory_voices, + int num_opus_streaming_voices, bool init_socket) { } + #endif + #if UNITY_WEBGL + private static void CRIWARE21B0F3E2(int num_webaudio_voices) { } + #endif + /* @endcond */ + private static bool _dummyInitialized = false; + private static void CRIWARE9AA6A10A() { _dummyInitialized = true; } + public static bool CRIWARE2AC85FB9() { return _dummyInitialized; } + private static void CRIWARE04B66F6D() { _dummyInitialized = false; } + private static void CRIWAREF71E04E6(bool pause) { } + public static uint CRIWARE581F45FE() { return 0; } + public static void CRIWARE873820B1(int code) { } + public static void CRIWARE61D452DC(IntPtr cbfunc, string separator_string) { } + public static void CRIWAREACA4DD5F(IntPtr cbfunc) { } + public static void CRIWAREC0C8F361() { } + public static void CRIWAREC739641B(IntPtr cbfunc) { } + public static void CRIWARE49850D78() { } + public static void CRIWAREEF0CC849(IntPtr cbfunc) { } + public static void CRIWARE85890687() { } + private static void CRIWARE219A582D(int sampling_rate_for_memory, int sampling_rate_for_streaming) { } + public static void CRIWARE80063D84() { } + public static void CRIWARE2294A8CF() { } + /* @cond notpublic */ + public static void CRIWARE0597FC3A(IntPtr acb_hn, CallbackFromNativeDelegate func, IntPtr obj) { } + /* @endcond */ + public static ushort CRIWARE43EC6991(int id) { return 0; } +#if !UNITY_EDITOR && UNITY_IOS + public static void criAtomUnity_SleepToDelay_IOS(int milliseconds) { } +#endif + private static bool CRIWARE7955C029() { return false; } + private static int CRIWARE899CB391() { return 0; } + private static int CRIWAREE8138117() { return 0; } + #endif + #endregion + + #endregion +} + +[Serializable] +public class CriAtomCueSheet +{ + public string name = ""; + public string acbFile = ""; + public string awbFile = ""; + public CriAtomExAcb acb; + public CriAtomExAcbLoader.Status loaderStatus = CriAtomExAcbLoader.Status.Stop; + public bool IsLoading { get { return loaderStatus == CriAtomExAcbLoader.Status.Loading; } } + public bool IsError { get { return (loaderStatus == CriAtomExAcbLoader.Status.Error) || (!IsLoading && acb == null); } } +} + +} //namespace CriWare + +/** + * @} + */ + +/** + * \addtogroup CRIATOM_UNITY_COMPONENT + * @{ + */ + +namespace CriWare { + +/** + * A component for controlling the overall sound playback. + * + * You need to prepare one for each scene.
+ * If you create a CriAtomSource using the CRI Atom window on UnityEditor, + * it will automatically be created as an object with the name "CRIWARE". Normally, you do not need to create it.
+ *
+ */ +[AddComponentMenu("CRIWARE/CRI Atom")] +public class CriAtom : CriMonoBehaviour +{ + + /* @cond DOXYGEN_IGNORE */ + public string acfFile = ""; + private bool acfIsLoading = false; +#if CRIWARE_FORCE_LOAD_ASYNC + private byte[] acfData = null; +#endif + public CriAtomCueSheet[] cueSheets = {}; + public string dspBusSetting = ""; + public bool dontDestroyOnLoad = false; + private static CriAtomExSequencer.EventCallback eventUserCallback = null; + internal static event CriAtomExSequencer.EventCallback OnEventSequencerCallback { + add { + RegisterEventCallbackChain(value); + } + remove { + UnregisterEventCallbackChain(value); + } + } + private static CriAtomExSequencer.EventCbFunc eventUserCbFunc = null; + private static event CriAtomExBeatSync.CbFunc beatsyncUserCbFunc = null; + internal static event CriAtomExBeatSync.CbFunc OnBeatSyncCallback { + add { + RegisterBeatSyncCallbackChain(value); + } + remove { + UnregisterBeatSyncCallbackChain(value); + } + } + private static CriAtomExBeatSync.CbFunc obsoleteBeatSyncFunc = null; + private static event CriAtomEx.CueLinkCbFunc cueLinkUserCbFunc = null; + internal static event CriAtomEx.CueLinkCbFunc OnCueLinkCallback { + add { + RegisterCueLinkCallbackChain(value); + } + remove { + UnregisterCueLinkCallbackChain(value); + } + } + private static CriAtom instance { + get; set; + } + private GCHandle acfRegisterGCHandle; + + /* @endcond */ + + #region Functions + + /** + * Attaching the DSP bus settings + * Name of the DSP bus setting + * + * Builds a DSP bus from the DSP bus settings and attaches it to the sound renderer.
+ * If you want to switch the DSP bus settings currently set, detach the bus and then reattach it. + *
+ * This function is a return-on-complete function.
+ * Calling this function blocks the server processing of the Atom library for a while.
+ * If this function is called during sound playback, problems such as sound interruption may occur, + * so call this function at a timing when load fluctuations is accepted such as when switching scenes.
+ *
+ * + */ + public static void AttachDspBusSetting(string settingName) + { + CriAtom.instance.dspBusSetting = settingName; + if (!String.IsNullOrEmpty(settingName)) { + CriAtomEx.AttachDspBusSetting(settingName); + } else { + CriAtomEx.DetachDspBusSetting(); + } + } + + /** + * Detaches the DSP bus settings + * + * Detaches the DSP bus settings.
+ *
+ * This function is a return-on-complete function.
+ * Calling this function blocks the server processing of the Atom library for a while.
+ * If this function is called during sound playback, problems such as sound interruption may occur, + * so call this function at a timing when load fluctuations is accepted such as when switching scenes.
+ *
+ * + */ + public static void DetachDspBusSetting() + { + CriAtom.instance.dspBusSetting = ""; + CriAtomEx.DetachDspBusSetting(); + } + + /** + * Gets a Cue Sheet + * Cue Sheet name + * Cue Sheet object + * + * Gets the registered Cue Sheet object based on the Cue Sheet name specified in the argument.
+ *
+ */ + public static CriAtomCueSheet GetCueSheet(string name) + { + return CriAtom.instance.GetCueSheetInternal(name); + } + + /** + * Adds a Cue Sheet + * Cue Sheet name + * ACB file path + * AWB file path + * Binder object (optional) + * Cue Sheet object + * + * A Cue Sheet is added based on the file path information specified in the argument.
+ * It is possible to register multiple Cue Sheets at the same time.
+ *
+ * If a relative path is specified for each file path, the file is loaded relative to the StreamingAssets folder.
+ * The file is loaded using the specified path if an absolute path or URL is specified.
+ *
+ * When adding a Cue Sheet from the ACB and AWB files packed in the CPK file, + * specify the binder which bound the CPK in the binder argument.
+ * The binder function cannot be used in ADX2LE.
+ *
+ */ + public static CriAtomCueSheet AddCueSheet(string name, string acbFile, string awbFile, CriFsBinder binder = null) + { + #if CRIWARE_FORCE_LOAD_ASYNC + return CriAtom.AddCueSheetAsync(name, acbFile, awbFile, binder); + #else + CriAtomCueSheet cueSheet = CriAtom.instance.AddCueSheetInternal(name, acbFile, awbFile, binder); + if (Application.isPlaying) { + cueSheet.acb = CriAtom.instance.LoadAcbFile(binder, acbFile, awbFile); + } + return cueSheet; + #endif + } + + /** + * Adds a Cue Sheet asynchronously + * Cue Sheet name + * ACB file path + * AWB file path + * Binder object (optional) + * Whether to load the AWB file on the memory (optional) + * Cue Sheet object + * + * A Cue Sheet is added asynchronously based on the file path information specified in the argument.
+ * It is possible to register multiple Cue Sheets at the same time.
+ *
+ * If a relative path is specified for each file path, the file is loaded relative to the StreamingAssets folder.
+ * The file is loaded using the specified path if an absolute path or URL is specified.
+ *
+ * When adding a Cue Sheet from the ACB and AWB files packed in the CPK file, + * specify the binder which bound the CPK in the binder argument.
+ * The binder function cannot be used in ADX2LE.
+ *
+ * Loading is in progress while the CriAtomCueSheet::isLoading member of the returned Cue Sheet object is True.
+ * Be sure to check that it returns False before playing the Cue.
+ *
+ * If loadAwbOnMemory is set to False, only the header part of the AWB file is loaded on the memory and stream playback is performed.
+ * If loadAwbOnMemory is set to True, the entire AWB file is loaded into memory, effectively resulting in memory playback.
+ * In WebGL(Editor running), loadAwbOnMemory is forced to True for internal reasons.
+ *
+ */ + public static CriAtomCueSheet AddCueSheetAsync(string name, string acbFile, string awbFile, CriFsBinder binder = null, bool loadAwbOnMemory = false) + { + #if UNITY_EDITOR && UNITY_WEBGL + loadAwbOnMemory = true; + #endif + CriAtomCueSheet cueSheet = CriAtom.instance.AddCueSheetInternal(name, acbFile, awbFile, binder); + if (Application.isPlaying) { + CriAtom.instance.LoadAcbFileAsync(cueSheet, binder, acbFile, awbFile, loadAwbOnMemory); + } + return cueSheet; + } + + /** + * Adds a Cue Sheet (reading from memory) + * Cue Sheet name + * ACB data + * AWB file path + * Binder object for AWB (optional) + * Cue Sheet object + * + * Adds a Cue Sheet from the data and file path information specified in the arguments.
+ * It is possible to register multiple Cue Sheets at the same time.
+ *
+ * If a relative path is specified for the file path, the file is loaded relative to the StreamingAssets folder.
+ * The file is loaded using the specified path if an absolute path or URL is specified.
+ *
+ * When adding a Cue Sheet from the AWB file packed in the CPK file, + * specify the binder which bound the CPK in the awbBinder argument.
+ * The binder function cannot be used in ADX2LE.
+ *
+ */ + public static CriAtomCueSheet AddCueSheet(string name, byte[] acbData, string awbFile, CriFsBinder awbBinder = null) + { + #if CRIWARE_FORCE_LOAD_ASYNC + return CriAtom.AddCueSheetAsync(name, acbData, awbFile, awbBinder); + #else + CriAtomCueSheet cueSheet = CriAtom.instance.AddCueSheetInternal(name, "", awbFile, awbBinder); + if (Application.isPlaying) { + cueSheet.acb = CriAtom.instance.LoadAcbData(acbData, awbBinder, awbFile); + } + return cueSheet; + #endif + } + + /** + * Adds a Cue Sheet asynchronously (reading from memory) + * Cue Sheet name + * ACB data + * AWB file path + * Binder object for AWB (optional) + * Whether to load the AWB file on the memory (optional) + * Cue Sheet object + * + * Adds a Cue Sheet from the data and file path information specified in the arguments.
+ * It is possible to register multiple Cue Sheets at the same time.
+ *
+ * If a relative path is specified for the file path, the file is loaded relative to the StreamingAssets folder.
+ * The file is loaded using the specified path if an absolute path or URL is specified.
+ *
+ * When adding a Cue Sheet from the AWB file packed in the CPK file, + * specify the binder which bound the CPK in the awbBinder argument.
+ * The binder function cannot be used in ADX2LE.
+ *
+ * Loading is in progress while the CriAtomCueSheet::isLoading member of the returned Cue Sheet object is True.
+ * Be sure to check that it returns False before playing the Cue.
+ *
+ * If loadAwbOnMemory is set to False, only the header part of the AWB file is loaded on the memory and stream playback is performed.
+ * If loadAwbOnMemory is set to True, the entire AWB file is loaded into memory, effectively resulting in memory playback.
+ * In WebGL(Editor running), loadAwbOnMemory is forced to True for internal reasons.
+ *
+ */ + public static CriAtomCueSheet AddCueSheetAsync(string name, byte[] acbData, string awbFile, CriFsBinder awbBinder = null, bool loadAwbOnMemory = false) + { + #if UNITY_EDITOR && UNITY_WEBGL + loadAwbOnMemory = true; + #endif + CriAtomCueSheet cueSheet = CriAtom.instance.AddCueSheetInternal(name, "", awbFile, awbBinder); + if (Application.isPlaying) { + CriAtom.instance.LoadAcbDataAsync(cueSheet, acbData, awbBinder, awbFile, loadAwbOnMemory); + } + return cueSheet; + } + + /** + * Removes a Cue Sheet + * Cue Sheet name + * + * Removes the added Cue Sheet.
+ *
+ */ + public static void RemoveCueSheet(string name) + { + if (CriAtom.instance == null) { + return; + } + CriAtom.instance.RemoveCueSheetInternal(name); + } + + /** + * Checks the completion of loading a Cue Sheet. + * + * Checks the completion of loading all Cue Sheets.
+ *
+ */ + public static bool CueSheetsAreLoading { + get { + if (CriAtom.instance == null) { + return false; + } + foreach (var cueSheet in CriAtom.instance.cueSheets) { + if (cueSheet.IsLoading) { + return true; + } + } + return false; + } + } + + /** + * Gets the ACB object + * Cue Sheet name + * ACB object + * + * Gets the ACB object corresponding to the specified Cue Sheet.
+ *
+ */ + public static CriAtomExAcb GetAcb(string cueSheetName) + { + foreach (var cueSheet in CriAtom.instance.cueSheets) { + if (cueSheetName == cueSheet.name) { + return cueSheet.acb; + } + } + Debug.LogWarning("[CRIWARE] Cue sheet named \""+ cueSheetName + "\" is not loaded."); + return null; + } + + /** + * Sets the Category volume by specifying the Category name. + * Category name + * Volume + */ + public static void SetCategoryVolume(string name, float volume) + { + CriAtomExCategory.SetVolume(name, volume); + } + + /** + * Sets the Category volume by specifying the Category ID. + * Category ID + * Volume + */ + public static void SetCategoryVolume(int id, float volume) + { + CriAtomExCategory.SetVolume(id, volume); + } + + /** + * Gets the Category volume by specifying the Category name. + * Category name + * Volume + */ + public static float GetCategoryVolume(string name) + { + return CriAtomExCategory.GetVolume(name); + } + /** + * Gets the Category volume by specifying the Category ID. + * Category ID + * Volume + */ + public static float GetCategoryVolume(int id) + { + return CriAtomExCategory.GetVolume(id); + } + + /** + * Enables the acquisition of the bus information + * DSP bus name + * True: Enable acquisition. False: Disable acquisition. + */ + public static void SetBusAnalyzer(string busName, bool sw) + { + #if !UNITY_EDITOR && UNITY_PSP2 + // unsupported + #else + if (sw) { + CriAtomExAsr.AttachBusAnalyzer(busName, 50, 1000); + } else { + CriAtomExAsr.DetachBusAnalyzer(busName); + } + #endif + } + + /** + * Enables acquisition of all bus information. + * True: Enable acquisition. False: Disable acquisition. + */ + public static void SetBusAnalyzer(bool sw) + { + #if !UNITY_EDITOR && UNITY_PSP2 + // unsupported + #else + if (sw) { + CriAtomExAsr.AttachBusAnalyzer(50, 1000); + } else { + CriAtomExAsr.DetachBusAnalyzer(); + } + #endif + } + + /** + * Gets the bus information. + * DSP bus name + * DSP bus information + */ + public static CriAtomExAsr.BusAnalyzerInfo GetBusAnalyzerInfo(string busName) + { + CriAtomExAsr.BusAnalyzerInfo info; + #if !UNITY_EDITOR && UNITY_PSP2 + info = new CriAtomExAsr.BusAnalyzerInfo(null); + #else + CriAtomExAsr.GetBusAnalyzerInfo(busName, out info); + #endif + return info; + } + + /** + * \deprecated + * This is a deprecated API that will be removed. + * Please consider using CriAtom.GetBusAnalyzerInfo(string busName) instead. + */ + [System.Obsolete("Use CriAtom.GetBusAnalyzerInfo(string busName)")] + public static CriAtomExAsr.BusAnalyzerInfo GetBusAnalyzerInfo(int busId) + { + CriAtomExAsr.BusAnalyzerInfo info; + #if !UNITY_EDITOR && UNITY_PSP2 + info = new CriAtomExAsr.BusAnalyzerInfo(null); + #else + CriAtomExAsr.GetBusAnalyzerInfo(busId, out info); + #endif + return info; + } + + #endregion // Functions + + /* @cond DOXYGEN_IGNORE */ + #region Functions for internal use + + public void Setup() + { + if (CriAtom.instance != null && CriAtom.instance != this) { + var obj = CriAtom.instance.gameObject; + CriAtom.instance.Shutdown(); + CriAtomEx.UnregisterAcf(); + GameObject.Destroy(obj); + } + + CriAtom.instance = this; + + CriAtomPlugin.InitializeLibrary(); + + if (!String.IsNullOrEmpty(this.acfFile)) { + string acfPath = Path.Combine(CriWare.Common.streamingAssetsPath, this.acfFile); + CriAtomEx.RegisterAcf(null, acfPath); + } + + if (!String.IsNullOrEmpty(dspBusSetting)) { + AttachDspBusSetting(dspBusSetting); + } + + foreach (var cueSheet in this.cueSheets) { + cueSheet.acb = this.LoadAcbFile(null, cueSheet.acbFile, cueSheet.awbFile); + } + + if (this.dontDestroyOnLoad) { + GameObject.DontDestroyOnLoad(this.gameObject); + } + } + + public void Shutdown() + { + foreach (var cueSheet in this.cueSheets) { + if (cueSheet.acb != null) { + cueSheet.acb.Dispose(); + cueSheet.acb = null; + } + } + CriAtomPlugin.FinalizeLibrary(); + if (CriAtom.instance == this) { + CriAtom.instance = null; + } + } + + void Awake() + { + if (CriAtom.instance != null && CriAtom.instance != this) { + if (CriAtom.instance.acfFile != this.acfFile) { + var obj = CriAtom.instance.gameObject; + CriAtom.instance.Shutdown(); + CriAtomEx.UnregisterAcf(); + GameObject.Destroy(obj); + return; + } + if (CriAtom.instance.dspBusSetting != this.dspBusSetting) { + CriAtom.AttachDspBusSetting(this.dspBusSetting); + } + CriAtom.instance.MargeCueSheet(this.cueSheets, this.dontRemoveExistsCueSheet); + GameObject.Destroy(this.gameObject); + } + } + + protected override void OnEnable() + { + base.OnEnable(); + #if UNITY_EDITOR + if (CriAtomPlugin.previewCallback != null) { + CriAtomPlugin.previewCallback(); + } + #endif + if (CriAtom.instance != null) { + return; + } + + #if CRIWARE_FORCE_LOAD_ASYNC + this.SetupAsync(); + #else + this.Setup(); + #endif + } + + void OnDestroy() + { + if (this != CriAtom.instance) { + return; + } + if (beatsyncUserCbFunc != null) { + beatsyncUserCbFunc = null; + CriAtomPlugin.CRIWAREC739641B(IntPtr.Zero); + } + if (this.acfRegisterGCHandle.IsAllocated) { + CriAtomEx.UnregisterAcf(); + this.acfRegisterGCHandle.Free(); + } + this.Shutdown(); + } + + public override void CriInternalUpdate() { } + + public override void CriInternalLateUpdate() { } + + public CriAtomCueSheet GetCueSheetInternal(string name) + { + for (int i = 0; i < this.cueSheets.Length; i++) { + CriAtomCueSheet cueSheet = this.cueSheets[i]; + if (cueSheet.name == name) { + return cueSheet; + } + } + return null; + } + + public CriAtomCueSheet AddCueSheetInternal(string name, string acbFile, string awbFile, CriFsBinder binder) + { + var cueSheets = new CriAtomCueSheet[this.cueSheets.Length + 1]; + this.cueSheets.CopyTo(cueSheets, 0); + this.cueSheets = cueSheets; + + var cueSheet = new CriAtomCueSheet(); + this.cueSheets[this.cueSheets.Length - 1] = cueSheet; + if (String.IsNullOrEmpty(name)) { + cueSheet.name = Path.GetFileNameWithoutExtension(acbFile); + } else { + cueSheet.name = name; + } + cueSheet.acbFile = acbFile; + cueSheet.awbFile = awbFile; + return cueSheet; + } + + public void RemoveCueSheetInternal(string name) + { + int index = -1; + for (int i = 0; i < this.cueSheets.Length; i++) { + if (name == this.cueSheets[i].name) { + index = i; + } + } + if (index < 0) { + return; + } + + var cueSheet = this.cueSheets[index]; + if (cueSheet.acb != null) { + cueSheet.acb.Dispose(); + cueSheet.acb = null; + } + + var cueSheets = new CriAtomCueSheet[this.cueSheets.Length - 1]; + Array.Copy(this.cueSheets, 0, cueSheets, 0, index); + Array.Copy(this.cueSheets, index + 1, cueSheets, index, this.cueSheets.Length - index - 1); + this.cueSheets = cueSheets; + } + + public bool dontRemoveExistsCueSheet = false; + + /* + * newDontRemoveExistsCueSheet == false の場合、古いキューシートを登録解除して、新しいキューシートの登録を行う。 + * ただし同じキューシートの再登録は回避する + */ + private void MargeCueSheet(CriAtomCueSheet[] newCueSheets, bool newDontRemoveExistsCueSheet) + { + if (!newDontRemoveExistsCueSheet) { + for (int i = 0; i < this.cueSheets.Length; ) { + int index = Array.FindIndex(newCueSheets, sheet => sheet.name == this.cueSheets[i].name); + if (index < 0) { + CriAtom.RemoveCueSheet(this.cueSheets[i].name); + } else { + i++; + } + } + } + + foreach (var sheet1 in newCueSheets) { + var sheet2 = this.GetCueSheetInternal(sheet1.name); + if (sheet2 == null) { + CriAtom.AddCueSheet(null, sheet1.acbFile, sheet1.awbFile, null); + } + } + } + + private CriAtomExAcb LoadAcbFile(CriFsBinder binder, string acbFile, string awbFile) + { + if (String.IsNullOrEmpty(acbFile)) { + return null; + } + + string acbPath = acbFile; + if ((binder == null) && CriWare.Common.IsStreamingAssetsPath(acbPath)) { + acbPath = Path.Combine(CriWare.Common.streamingAssetsPath, acbPath); + } + + string awbPath = awbFile; + if (!String.IsNullOrEmpty(awbPath)) { + if ((binder == null) && CriWare.Common.IsStreamingAssetsPath(awbPath)) { + awbPath = Path.Combine(CriWare.Common.streamingAssetsPath, awbPath); + } + } + + return CriAtomExAcb.LoadAcbFile(binder, acbPath, awbPath); + } + + private CriAtomExAcb LoadAcbData(byte[] acbData, CriFsBinder binder, string awbFile) + { + if (acbData == null) { + return null; + } + + string awbPath = awbFile; + if (!String.IsNullOrEmpty(awbPath)) { + if ((binder == null) && CriWare.Common.IsStreamingAssetsPath(awbPath)) { + awbPath = Path.Combine(CriWare.Common.streamingAssetsPath, awbPath); + } + } + + return CriAtomExAcb.LoadAcbData(acbData, binder, awbPath); + } + +#if CRIWARE_FORCE_LOAD_ASYNC + private void SetupAsync() + { + CriAtom.instance = this; + + CriAtomPlugin.InitializeLibrary(); + + if (this.dontDestroyOnLoad) { + GameObject.DontDestroyOnLoad(this.gameObject); + } + + if (!String.IsNullOrEmpty(this.acfFile)) { + this.acfIsLoading = true; + StartCoroutine(RegisterAcfAsync(this.acfFile, this.dspBusSetting)); + } + + foreach (var cueSheet in this.cueSheets) { + #if UNITY_EDITOR + bool loadAwbOnMemory = true; + #else + bool loadAwbOnMemory = false; + #endif + StartCoroutine(LoadAcbFileCoroutine(cueSheet, null, cueSheet.acbFile, cueSheet.awbFile, loadAwbOnMemory)); + } + } + + private IEnumerator RegisterAcfAsync(string acfFile, string dspBusSetting) + { + #if UNITY_EDITOR + string acfPath = "file://" + CriWare.Common.streamingAssetsPath + "/" + acfFile; + #else + string acfPath = CriWare.Common.streamingAssetsPath + "/" + acfFile; + #endif + using (var req = new WWW(acfPath)) { + yield return req; + this.acfData = req.bytes; + } + /* + * If there is already an allocated ACF data, + * unregister and then release it. + */ + if (this.acfRegisterGCHandle.IsAllocated) { + CriAtomEx.UnregisterAcf(); + this.acfRegisterGCHandle.Free(); + } + this.acfRegisterGCHandle = GCHandle.Alloc(this.acfData, GCHandleType.Pinned); + CriAtomEx.RegisterAcf(this.acfRegisterGCHandle.AddrOfPinnedObject(), acfData.Length); + + if (!String.IsNullOrEmpty(dspBusSetting)) { + AttachDspBusSetting(dspBusSetting); + } + this.acfIsLoading = false; + } +#endif + + + private void LoadAcbFileAsync(CriAtomCueSheet cueSheet, CriFsBinder binder, string acbFile, string awbFile, bool loadAwbOnMemory) + { + if (String.IsNullOrEmpty(acbFile)) { + return; + } + + StartCoroutine(LoadAcbFileCoroutine(cueSheet, binder, acbFile, awbFile, loadAwbOnMemory)); + } + + private IEnumerator LoadAcbFileCoroutine(CriAtomCueSheet cueSheet, CriFsBinder binder, string acbPath, string awbPath, bool loadAwbOnMemory) + { + cueSheet.loaderStatus = CriAtomExAcbLoader.Status.Loading; + + if ((binder == null) && CriWare.Common.IsStreamingAssetsPath(acbPath)) { + acbPath = Path.Combine(CriWare.Common.streamingAssetsPath, acbPath); + } + + if (!String.IsNullOrEmpty(awbPath)) { + if ((binder == null) && CriWare.Common.IsStreamingAssetsPath(awbPath)) { + awbPath = Path.Combine(CriWare.Common.streamingAssetsPath, awbPath); + } + } + + while (this.acfIsLoading) { + yield return null; + } + + using (var asyncLoader = CriAtomExAcbLoader.LoadAcbFileAsync(binder, acbPath, awbPath, loadAwbOnMemory)) { + if (asyncLoader == null) { + cueSheet.loaderStatus = CriAtomExAcbLoader.Status.Error; + yield break; + } + + while (true) { + var status = asyncLoader.GetStatus(); + cueSheet.loaderStatus = status; + if (status == CriAtomExAcbLoader.Status.Complete) { + cueSheet.acb = asyncLoader.MoveAcb(); + break; + } else if (status == CriAtomExAcbLoader.Status.Error) { + break; + } + yield return null; + } + } + } + + private void LoadAcbDataAsync(CriAtomCueSheet cueSheet, byte[] acbData, CriFsBinder awbBinder, string awbFile, bool loadAwbOnMemory) + { + StartCoroutine(LoadAcbDataCoroutine(cueSheet, acbData, awbBinder, awbFile, loadAwbOnMemory)); + } + + private IEnumerator LoadAcbDataCoroutine(CriAtomCueSheet cueSheet, byte[] acbData, CriFsBinder awbBinder, string awbPath, bool loadAwbOnMemory) + { + cueSheet.loaderStatus = CriAtomExAcbLoader.Status.Loading; + + if (!String.IsNullOrEmpty(awbPath)) { + if ((awbBinder == null) && CriWare.Common.IsStreamingAssetsPath(awbPath)) { + awbPath = Path.Combine(CriWare.Common.streamingAssetsPath, awbPath); + } + } + + while (this.acfIsLoading) { + yield return null; + } + + using (var asyncLoader = CriAtomExAcbLoader.LoadAcbDataAsync(acbData, awbBinder, awbPath, loadAwbOnMemory)) { + if (asyncLoader == null) { + cueSheet.loaderStatus = CriAtomExAcbLoader.Status.Error; + yield break; + } + + while (true) { + var status = asyncLoader.GetStatus(); + cueSheet.loaderStatus = status; + if (status == CriAtomExAcbLoader.Status.Complete) { + cueSheet.acb = asyncLoader.MoveAcb(); + break; + } else if (status == CriAtomExAcbLoader.Status.Error) { + break; + } + yield return null; + } + } + } + + [AOT.MonoPInvokeCallback(typeof(CriAtomExSequencer.EventCbFunc))] + public static void SequenceEventCallbackFromNative(string eventString) + { + /* 本関数はアプリケーションメインスレッドの CriAtom.Update から呼び出される */ + if (eventUserCbFunc != null) { + eventUserCbFunc(eventString); + } + } + + [AOT.MonoPInvokeCallback(typeof(CriAtomExSequencer.EventCallback))] + private static void SequenceCallbackFromNative(ref CriAtomExSequencer.CriAtomExSequenceEventInfo criAtomExSequenceInfo) + { + /* 本関数はアプリケーションメインスレッドの CriAtom.Update から呼び出される */ + if (eventUserCallback != null) { + eventUserCallback(ref criAtomExSequenceInfo); + } + } + + [AOT.MonoPInvokeCallback(typeof(CriAtomExBeatSync.CbFunc))] + public static void BeatSyncCallbackFromNative(ref CriAtomExBeatSync.Info info) + { + /* 本関数はアプリケーションメインスレッドの CriAtom.Update から呼び出される */ + if (beatsyncUserCbFunc != null) { + beatsyncUserCbFunc(ref info); + } + } + + [AOT.MonoPInvokeCallback(typeof(CriAtomEx.CueLinkCbFunc))] + public static void CueLinkCallbackFromNative(ref CriAtomEx.CueLinkInfo info) + { + /* 本関数はアプリケーションメインスレッドの CriAtom.Update から呼び出される */ + if (cueLinkUserCbFunc != null) { + cueLinkUserCbFunc(ref info); + } + } + + /* プラグイン内部用API */ + public static void SetEventCallback(CriAtomExSequencer.EventCbFunc func, string separator) + { + /* ネイティブプラグインに関数ポインタを登録 */ + IntPtr ptr = IntPtr.Zero; + eventUserCbFunc = func; + if (func != null) { + CriAtomExSequencer.EventCbFunc delegateObject; + delegateObject = new CriAtomExSequencer.EventCbFunc(CriAtom.SequenceEventCallbackFromNative); + ptr = Marshal.GetFunctionPointerForDelegate(delegateObject); + } + CriAtomPlugin.CRIWARE61D452DC(ptr, separator); + } + + private static void RegisterEventCallbackChain(CriAtomExSequencer.EventCallback func) + { + /* Register callback function's pointer to native plugin side. */ + IntPtr ptr = IntPtr.Zero; + if (eventUserCallback == null) { + CriAtomExSequencer.EventCallback delegateObject; + delegateObject = new CriAtomExSequencer.EventCallback(CriAtom.SequenceCallbackFromNative); + ptr = Marshal.GetFunctionPointerForDelegate(delegateObject); + CriAtomPlugin.CRIWAREACA4DD5F(ptr); + } + eventUserCallback += func; + } + + private static void UnregisterEventCallbackChain(CriAtomExSequencer.EventCallback func) + { + eventUserCallback -= func; + if (eventUserCallback == null) { + CriAtomPlugin.CRIWAREACA4DD5F(IntPtr.Zero); + } + } + + public static void SetBeatSyncCallback(CriAtomExBeatSync.CbFunc func) + { + Debug.LogWarning("[CRIWARE] This function(CriAtom.SetBeatSyncCallback) is deprecated. Use CriAtomExBeatSync class."); + if (func == null) { + /* Only unregistered via CriAtomExBeatSync or CriAtom SetBeatSyncCallback(). */ + UnregisterBeatSyncCallbackChain(obsoleteBeatSyncFunc); + obsoleteBeatSyncFunc = null; + return; + } + if (obsoleteBeatSyncFunc != null) { + UnregisterBeatSyncCallbackChain(obsoleteBeatSyncFunc); + } + obsoleteBeatSyncFunc = func; + RegisterBeatSyncCallbackChain(obsoleteBeatSyncFunc); + } + + private static void RegisterBeatSyncCallbackChain(CriAtomExBeatSync.CbFunc func) + { + if (beatsyncUserCbFunc == null) { + CriAtomExBeatSync.CbFunc delegateObject; + delegateObject = new CriAtomExBeatSync.CbFunc(CriAtom.BeatSyncCallbackFromNative); + var ptr = Marshal.GetFunctionPointerForDelegate(delegateObject); + CriAtomPlugin.CRIWAREC739641B(ptr); + } + beatsyncUserCbFunc += func; + } + + private static void UnregisterBeatSyncCallbackChain(CriAtomExBeatSync.CbFunc func) + { + beatsyncUserCbFunc -= func; + if (beatsyncUserCbFunc == null) { + CriAtomPlugin.CRIWAREC739641B(IntPtr.Zero); + } + } + + private static void RegisterCueLinkCallbackChain(CriAtomEx.CueLinkCbFunc func) + { + if (cueLinkUserCbFunc == null) { + CriAtomEx.CueLinkCbFunc delegateObject; + delegateObject = new CriAtomEx.CueLinkCbFunc(CriAtom.CueLinkCallbackFromNative); + var ptr = Marshal.GetFunctionPointerForDelegate(delegateObject); + CriAtomPlugin.CRIWAREEF0CC849(ptr); + } + cueLinkUserCbFunc += func; + } + + private static void UnregisterCueLinkCallbackChain(CriAtomEx.CueLinkCbFunc func) + { + cueLinkUserCbFunc -= func; + if (cueLinkUserCbFunc == null) { + CriAtomPlugin.CRIWAREEF0CC849(IntPtr.Zero); + } + } + + #endregion + /* @endcond */ + +} + +} //namespace CriWare +/** @} */ +/* end of file */ diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/CriAtom.cs.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/CriAtom.cs.meta new file mode 100644 index 0000000..6556ece --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/CriAtom.cs.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 91f529aa944b914449d62b8c40f188fe +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: -11 + icon: {instanceID: 0} diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/CriAtomListener.cs b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/CriAtomListener.cs new file mode 100644 index 0000000..697e883 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/CriAtomListener.cs @@ -0,0 +1,230 @@ +/**************************************************************************** + * + * Copyright (c) 2011 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +using UnityEngine; +using System; +using System.Collections.Generic; + +/** + * \addtogroup CRIATOM_UNITY_COMPONENT + * @{ + */ + +namespace CriWare { + +/** + * A component that represents a 3D listener. + * + * Usually, it is used by attaching it to the GameObject object of the camera or main character. + * The current position is updated automatically, so no special operation or setting is required. + * + */ +[AddComponentMenu("CRIWARE/CRI Atom Listener")] +public class CriAtomListener : CriMonoBehaviour +{ + #region CRIWARE internals + public static void CreateDummyNativeListener() + { + if (dummyNativeListener == null) { + dummyNativeListener = new CriAtomEx3dListener(); + } + } + + public static void DestroyDummyNativeListener() + { + if (dummyNativeListener != null) { + dummyNativeListener.Dispose(); + dummyNativeListener = null; + } + } + #endregion + + #region Fields & Properties + /** + * This is the CriAtomEx3dListener used internally. + * + * If you want to control CriAtom3dListener directly, get CriAtom3dListener from this property. + * + */ + public CriAtomEx3dListener nativeListener { get; protected set; } + + [SerializeField] CriAtomRegion regionOnStart = null; + + /** + * Whether to make it an exclusive active listener in OnEnable + * + * If true, when OnEnable is called, this listener will be activated + * and all the other listeners will be deactivated. + * If false, it will become active without affecting other listeners. + * + */ + public bool activateListenerOnEnable = false; + + /** + * Whether the CriAtomListener is active + * + * An active CriAtomListener acts as a listener for CriAtomSource audio.
+ * If there are multiple CriAtomListeners, The 3D sound will be calculated
+ * using the active listener that is closest to the CriAtomSource.
+ *
+ */ + public bool isActive { + get { return _isActive; } + set { + if (_isActive == value) return; + _isActive = value; + if (value) + UpdatePosition(); + else { + /* Make the listener unactive by setting far position. */ + nativeListener.SetPosition(float.MaxValue, float.MaxValue, float.MaxValue); + nativeListener.Update(); + } + } + } + + /** + * Sets/gets 3D region of the sound source + */ + public CriAtomRegion region3d + { + get { return this.currentRegion; } + set { + if (this.currentRegion == value) { + return; + } + /* Remove the reference frome the current region */ + if (this.currentRegion != null) { + this.currentRegion.referringListeners.Remove(this); + } + CriAtomEx3dRegion regionHandle = (value == null) ? null : value.region3dHn; + if (this.nativeListener != null) { + this.nativeListener.Set3dRegion(regionHandle); + this.nativeListener.Update(); + this.currentRegion = value; + /* Seup a reference from a new region */ + if (this.currentRegion != null) { + this.currentRegion.referringListeners.Add(this); + } + } else { + Debug.LogError("[CRIWARE] Internal: CriAtomListener is not initialized correctly."); + this.currentRegion = null; + } + } + } + #endregion + + #region Internal Variables + static List listenersList = new List(); + + /* Dummy listenr used when CriAtomListenr is not exists. */ + static CriAtomEx3dListener dummyNativeListener; + + private Vector3 lastPosition; + private CriAtomRegion currentRegion = null; + private bool _isActive = true; + #endregion + + #region Functions + private void Awake() + { + if (!listenersList.Contains(this)) + listenersList.Add(this); + DestroyDummyNativeListener(); + nativeListener = new CriAtomEx3dListener(); + isActive = enabled; + } + + private void Start() + { + if (regionOnStart != null) { + region3d = this.regionOnStart; + } + } + + protected override void OnEnable() + { + base.OnEnable(); + ActivateListener(activateListenerOnEnable); + } + + protected override void OnDisable() + { + base.OnDisable(); + isActive = false; + } + + private void OnDestroy() + { + if (listenersList.Contains(this)) { + listenersList.Remove(this); + } + region3d = null; + nativeListener.Dispose(); + nativeListener = null; + } + +#if UNITY_EDITOR + private void OnDrawGizmos() { + if (this.enabled == false) { return; } + var criWareLightBlue = new Color(0.332f, 0.661f, 0.991f); + Gizmos.color = isActive || !Application.isPlaying ? criWareLightBlue : Color.gray; + Gizmos.DrawLine(this.transform.position, this.transform.position + this.transform.forward); + Gizmos.DrawLine(this.transform.position, this.transform.position + this.transform.up); + UnityEditor.Handles.color = isActive || !Application.isPlaying ? criWareLightBlue : Color.gray; + UnityEditor.Handles.ArrowHandleCap(1, this.transform.position + this.transform.forward, this.transform.rotation, 1f, EventType.Repaint); + UnityEditor.Handles.RectangleHandleCap(1, this.transform.position, this.transform.rotation * Quaternion.LookRotation(Vector3.up), 1f, EventType.Repaint); + } +#endif + + public override void CriInternalUpdate() { } + + public override void CriInternalLateUpdate() + { + if (isActive) + UpdatePosition(); + } + + void UpdatePosition() + { + Vector3 position = this.transform.position; + Vector3 velocity = (position - this.lastPosition) / Time.deltaTime; + Vector3 front = this.transform.forward; + Vector3 up = this.transform.up; + this.lastPosition = position; + if (nativeListener != null) { + nativeListener.SetPosition(position.x, position.y, position.z); + nativeListener.SetVelocity(velocity.x, velocity.y, velocity.z); + nativeListener.SetOrientation(front.x, front.y, front.z, up.x, up.y, up.z); + nativeListener.Update(); + } + } + #endregion + + /** + * Make it an active listener + * Whether to make this AtomListener the only active listener + * + * When it becomes an active listener, it acts as a 3D listener for CriWare.CriAtomSource . + * For compatibility with old plugins, when called with no arguments,
+ * only the CriAtomListener calling this method will be active.
+ *
+ */ + public void ActivateListener(bool exclusive = true) + { + if (exclusive) { + foreach (var listener in listenersList) { + if (listener == this) continue; + listener.isActive = false; + } + } + isActive = true; + } +} // end of class + +} //namespace CriWare +/** @} */ +/* end of file */ diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/CriAtomListener.cs.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/CriAtomListener.cs.meta new file mode 100644 index 0000000..9b220ac --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/CriAtomListener.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: ce7d42e042e4c9c4db4bde98b863e167 +timeCreated: 1433816077 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 54b14f2540d554f4c9bafa3501e6dc9f, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/CriAtomOutputDeviceObserver.cs b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/CriAtomOutputDeviceObserver.cs new file mode 100644 index 0000000..8d29db5 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/CriAtomOutputDeviceObserver.cs @@ -0,0 +1,291 @@ +/**************************************************************************** + * + * Copyright (c) CRI Middleware Co., Ltd. + * + ****************************************************************************/ +#if !UNITY_EDITOR && (UNITY_ANDROID || UNITY_IOS) +#define CRIWAREPLUGIN_SUPPORT_OUTPUTDEVICE_OBSERVER +#endif + +using System; +using System.Collections; +using System.Runtime.InteropServices; +using UnityEngine; + +/** + * \addtogroup CRIWARE_COMMON_CLASS + * @{ + */ + +namespace CriWare { + + +/** + * A component that monitors the connection status of audio output devices. + * + * Use it by adding it to any GameObject.
+ * You can monitor the connection status of the audio output device on your smartphone device and acquire the status externally.
+ * By registering a delegate, you can also receive callbacks when the connection status changes.
+ * To use this component, it is necessary to initialize the Atom library first.
+ * Currently, the functions of this component only work on smartphones (Android / iOS).
+ * Please wait for future updates for support for other platforms.
+ *
+ */ +public class CriAtomOutputDeviceObserver : CriMonoBehaviour +{ + /** + * Type of audio output device + * + * Types of device to which audio is output from the application. + * + * + */ + public enum OutputDeviceType { + BuiltinSpeaker, /**< Internal Speaker */ + WiredDevice, /**< Wired device (wired headset, etc.) */ + WirelessDevice, /**< Wireless device (Bluetooth headset, etc.) */ + } + + + /** + * Connection state change callback delegate type + * Output device connection status (false = disconnected, true = connected) + * Output device type + * + * This is the type of the callback function that is called when the connection status of the audio output device changes. + * + * + */ + public delegate void DeviceConnectionChangeCallback(bool isConnected, OutputDeviceType deviceType); + + + /** + * Connection state change callback delegate + * + * This is a callback function that is called when the connection status of the audio output device changes.
+ * Called from the application's main thread.
+ *
+ * + */ + public static event DeviceConnectionChangeCallback OnDeviceConnectionChanged { + add { + _onDeviceConnectionChanged += value; + if (instance) { + value(IsDeviceConnected, DeviceType); + } + } + remove { + _onDeviceConnectionChanged -= value; + } + } + + /** + * Gets device connection status + * Whether connected (false = disconnected, true = connected) + * + * Returns whether an audio output device is connected to the machine.
+ * Returns true if the output destination is a device other than the internal speaker.
+ *
+ */ + public static bool IsDeviceConnected { + get { + if (instance == null) { + return false; + } +#if !UNITY_EDITOR && UNITY_IOS + return UnsafeNativeMethods.criAtomUnity_IsOutputDeviceConnected_IOS(); +#elif !UNITY_EDITOR && UNITY_ANDROID + return instance.isConnected; +#else + return false; +#endif + } + } + + /** + * Gets the output device type + * Output device type + * + * Gets the type of the current audio output device. + * + */ + public static OutputDeviceType DeviceType { + get { + if (instance == null) { + return OutputDeviceType.BuiltinSpeaker; + } +#if !UNITY_EDITOR && UNITY_IOS + return UnsafeNativeMethods.criAtomUnity_GetOutputDeviceType_IOS(); +#elif !UNITY_EDITOR && UNITY_ANDROID + return instance.deviceType; +#else + return OutputDeviceType.BuiltinSpeaker; +#endif + } + } + + #region Internal Members + [SerializeField] bool dontDestroyOnLoad = false; + bool lastIsConnected = false; + bool isConnected = false; + OutputDeviceType lastDeviceType = OutputDeviceType.BuiltinSpeaker; + OutputDeviceType deviceType = OutputDeviceType.BuiltinSpeaker; + static CriAtomOutputDeviceObserver instance = null; + static event DeviceConnectionChangeCallback _onDeviceConnectionChanged = null; +#if !UNITY_EDITOR && UNITY_ANDROID + static UnityEngine.AndroidJavaObject checker = null; +#endif + #endregion + + #region Internal Functions + private void Awake() { + if (instance != null) { + Destroy(this); + return; + } + + if (!CriAtomPlugin.IsLibraryInitialized()) { + Debug.LogError("[CRIWARE] Atom library is not initialized. Cannot setup CriAtomExOutputDeviceObserver."); + Destroy(this); + return; + } + + instance = this; + +#if CRIWAREPLUGIN_SUPPORT_OUTPUTDEVICE_OBSERVER +#if !UNITY_EDITOR && UNITY_IOS + bool isStarted = UnsafeNativeMethods.criAtomUnity_StartOutputDeviceObserver_IOS(); + if (!isStarted) { + Debug.LogError("[CRIWARE] CriAtomOutputDeviceObserver cannot start while Atom library is not initialized."); + } +#elif !UNITY_EDITOR && UNITY_ANDROID + UnityEngine.AndroidJavaClass jc = new UnityEngine.AndroidJavaClass("com.unity3d.player.UnityPlayer"); + UnityEngine.AndroidJavaObject activity = jc.GetStatic("currentActivity"); + + if (checker == null) { + checker = new UnityEngine.AndroidJavaObject("com.crimw.crijavaclasses.CriOutputDeviceObserver", activity, this.gameObject.name, "CallbackFromObserver_ANDROID"); + } + if (checker == null) { + Debug.LogError("[CRIWARE] Cannot load CriOutputDeviceObserver class in library."); + } + checker.Call("Start", activity); + CheckOutputDevice_ANDROID(); +#endif + isConnected = lastIsConnected = IsDeviceConnected; + deviceType = lastDeviceType = DeviceType; + if (_onDeviceConnectionChanged != null) { + _onDeviceConnectionChanged(isConnected, deviceType); + } +#elif !UNITY_EDITOR + Debug.Log("[CRIWARE] CriAtomOutputDeviceObserver is not supported on this platform."); +#endif + if (this.dontDestroyOnLoad) { + GameObject.DontDestroyOnLoad(this.gameObject); + } + } + + + private void OnDestroy() { + if (instance != this) { + return; + } + instance = null; + +#if CRIWAREPLUGIN_SUPPORT_OUTPUTDEVICE_OBSERVER +#if !UNITY_EDITOR && UNITY_IOS + UnsafeNativeMethods.criAtomUnity_StopOutputDeviceObserver_IOS(); +#elif !UNITY_EDITOR && UNITY_ANDROID + UnityEngine.AndroidJavaClass jc = new UnityEngine.AndroidJavaClass("com.unity3d.player.UnityPlayer"); + UnityEngine.AndroidJavaObject activity = jc.GetStatic("currentActivity"); + if (activity != null && checker != null) { + checker.Call("Stop", activity); + } + checker = null; +#endif +#endif + } + + + public override void CriInternalUpdate() { + isConnected = IsDeviceConnected; + deviceType = DeviceType; + + if ((isConnected != lastIsConnected || + deviceType != lastDeviceType) && + _onDeviceConnectionChanged != null) { + _onDeviceConnectionChanged(isConnected, deviceType); + } + lastIsConnected = isConnected; + lastDeviceType = deviceType; + } + + + public override void CriInternalLateUpdate() { + } + +#if !UNITY_EDITOR && UNITY_ANDROID + /* [ANDROID] Callback from CriOutputDeviceObserver class */ + private void CallbackFromObserver_ANDROID(string message) { + if (message[0] == 'a') { + CheckOutputDevice_ANDROID(); + } else if (message[0] == 'b') { + StartCoroutine("CoroutineForCheck_ANDROID"); + } + } + + private void CheckOutputDevice_ANDROID() { + if (checker == null) { + return; + } + + UnityEngine.AndroidJavaClass jc = new UnityEngine.AndroidJavaClass("com.unity3d.player.UnityPlayer"); + UnityEngine.AndroidJavaObject activity = jc.GetStatic("currentActivity"); + int device = checker.Call("CheckOutputDeviceType", activity); + deviceType = (OutputDeviceType)device; + isConnected = (deviceType != OutputDeviceType.BuiltinSpeaker); + + } + + private IEnumerator CoroutineForCheck_ANDROID() { + const float waitSec = 2.0f; + float time = 0.0f; + while (time < waitSec) { + yield return null; + time += Time.deltaTime; + } + CheckOutputDevice_ANDROID(); + } + +#endif + #endregion + + #region Dll Import + private static class UnsafeNativeMethods + { +#if !CRIWARE_ENABLE_HEADLESS_MODE +#if !UNITY_EDITOR && UNITY_IOS + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + internal static extern bool criAtomUnity_StartOutputDeviceObserver_IOS(); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + internal static extern void criAtomUnity_StopOutputDeviceObserver_IOS(); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + internal static extern bool criAtomUnity_IsOutputDeviceConnected_IOS(); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + internal static extern OutputDeviceType criAtomUnity_GetOutputDeviceType_IOS(); +#endif +#else +#if !UNITY_EDITOR && UNITY_IOS + internal static bool criAtomUnity_StartOutputDeviceObserver_IOS() { return false; } + internal static void criAtomUnity_StopOutputDeviceObserver_IOS() { } + internal static bool criAtomUnity_IsOutputDeviceConnected_IOS() { return false; } + internal static OutputDeviceType criAtomUnity_GetOutputDeviceType_IOS() { return OutputDeviceType.BuiltinSpeaker; } +#endif +#endif + } + #endregion + +} // end of class + +} //namespace CriWare +/** @} */ +/* end of file */ diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/CriAtomOutputDeviceObserver.cs.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/CriAtomOutputDeviceObserver.cs.meta new file mode 100644 index 0000000..fb10dcc --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/CriAtomOutputDeviceObserver.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c9b37739fef8f4647acb0b94be4d34fc +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/CriAtomRegion.cs b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/CriAtomRegion.cs new file mode 100644 index 0000000..6d55473 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/CriAtomRegion.cs @@ -0,0 +1,111 @@ +/**************************************************************************** + * + * Copyright (c) 2020 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +using UnityEngine; +using System.Collections.Generic; + +/** + * \addtogroup CRIATOM_UNITY_COMPONENT + * @{ + */ + +namespace CriWare { + +/** + * 3D region component + * + * A component that groups 3D sound sources, 3D listeners and transceivers by space.
+ * Used by attaching to any GameObject.
+ * This can be used as an value of region3d in CriAtomSource, CriAtomListener and CriAtomTransceiver,
+ * or can be set as initial region setting.
+ * Only one of this component can be attached to a GameObject.
+ *
+ * + * + * + */ +[AddComponentMenu("CRIWARE/CRI Atom Region"), DisallowMultipleComponent] +public class CriAtomRegion : CriMonoBehaviour +{ + #region Fields & Properties + /** + * The CriAtomEx3dRegion used internally. + * + * If you want to control CriAtomEx3dRegion directly, get CriAtomEx3dRegion from this property. + * + */ + public CriAtomEx3dRegion region3dHn { get; protected set; } + #endregion + + #region Private Fields & Properties + internal List referringSources = new List(); + internal List referringListeners = new List(); + internal List referringTransceivers = new List(); + #endregion + + #region Methods + + private void Awake() + { + this.InternalInitialize(); + } + + protected override void OnEnable() + { + base.OnEnable(); + this.InitializeParameters(); + } + + private void OnDestroy() + { + this.InternalFinalize(); + } + + protected virtual void InternalInitialize() + { + CriAtomPlugin.InitializeLibrary(); + this.region3dHn = new CriAtomEx3dRegion(); + } + + protected virtual void InternalFinalize() + { + /* Clear references to this region */ + while (referringSources.Count > 0) { + referringSources[0].region3d = null; + } + referringSources.Clear(); + while (referringListeners.Count > 0) { + referringListeners[0].region3d = null; + } + referringListeners.Clear(); + while(referringTransceivers.Count > 0) { + referringTransceivers[0].region3d = null; + } + referringTransceivers.Clear(); + + region3dHn.Dispose(); + region3dHn = null; + CriAtomPlugin.FinalizeLibrary(); + } + + protected virtual void InitializeParameters() + { + if (this.region3dHn == null) { + Debug.LogError("[CRIWARE] Internal: CriAtomEx3dRegion is not created correctly.", this); + return; + } + } + + public override void CriInternalUpdate() { } + + public override void CriInternalLateUpdate() { } + + #endregion +} // end of class + +} //namespace CriWare +/** @} */ +/* end of file */ \ No newline at end of file diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/CriAtomRegion.cs.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/CriAtomRegion.cs.meta new file mode 100644 index 0000000..35fae52 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/CriAtomRegion.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f90e8bb5f5c39384c915cfdeb1ee0bbb +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/CriAtomServer.cs b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/CriAtomServer.cs new file mode 100644 index 0000000..1c8187f --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/CriAtomServer.cs @@ -0,0 +1,197 @@ +/**************************************************************************** + * + * Copyright (c) 2011 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +using UnityEngine; +using System; + +namespace CriWare { + +public class CriAtomServer : CriMonoBehaviour { + + #region Internal Fields + private static CriAtomServer _instance = null; +#if UNITY_EDITOR + private bool isApplicationPaused = false; + private bool isEditorPaused = false; +#endif + #endregion + + public System.Action onApplicationPausePreProcess; + public System.Action onApplicationPausePostProcess; + static public bool KeepPlayingSoundOnPause = true; + static public bool EnableAutoConsumePcmOutput = true; + +#if UNITY_EDITOR + private bool consumingPcmOutput = false; + private float consumeStartTime = 0.0f; + private ulong consumedSamples = 0; + private int samplingRate; + private int channels; + private float[][] buffer; +#endif + + public static CriAtomServer instance { + get { + CreateInstance(); + return _instance; + } + } + + public static void CreateInstance() { + if (_instance == null) { + CriWare.Common.managerObject.AddComponent(); + } + } + + public static void DestroyInstance() { + if (_instance != null) { + UnityEngine.GameObject.Destroy(_instance); + } + } + + void Awake() + { + /* インスタンスは常に1つしか生成されないことを保証する */ + if (_instance == null) { + _instance = this; + } else { + GameObject.Destroy(this); + } + } + + protected override void OnEnable() + { + base.OnEnable(); +#if UNITY_EDITOR +#if UNITY_2017_2_OR_NEWER + UnityEditor.EditorApplication.playModeStateChanged += OnPlayModeStateChanged; + UnityEditor.EditorApplication.pauseStateChanged += OnPauseStateChanged; +#else + UnityEditor.EditorApplication.playmodeStateChanged += OnPlaymodeStateChange; +#endif +#endif + } + + protected override void OnDisable() + { + base.OnDisable(); +#if UNITY_EDITOR +#if UNITY_2017_2_OR_NEWER + UnityEditor.EditorApplication.playModeStateChanged -= OnPlayModeStateChanged; + UnityEditor.EditorApplication.pauseStateChanged -= OnPauseStateChanged; +#else + UnityEditor.EditorApplication.playmodeStateChanged -= OnPlaymodeStateChange; +#endif +#endif + + if (_instance == this) { + _instance = null; + } + } + + public override void CriInternalUpdate() + { + CriAtomPlugin.ExecuteQueuedCueLinkCallbacks(); + CriAtomPlugin.ExecuteQueuedEventCallbacks(); + CriAtomPlugin.ExecuteQueuedBeatSyncCallbacks(); + + if (EnableAutoConsumePcmOutput) { + ConsumePcmOutput(); + } + } + + public override void CriInternalLateUpdate() { } + + private void ConsumePcmOutput() + { +#if UNITY_EDITOR + if (!CriAtomPlugin.IsInitializedForPcmOutput()) { + consumingPcmOutput = false; + return; + } + + if (buffer == null) { + channels = CriAtomPlugin.GetOutputChannels(); + samplingRate = CriAtomPlugin.GetOutputSamplingRate(); + buffer = new float[channels][]; + for (int i = 0; i < channels; i++) { + buffer[i] = new float[samplingRate]; + } + } + + if (!consumingPcmOutput) { + consumeStartTime = Time.time; + consumedSamples = 0; + consumingPcmOutput = true; + } + + int numToConsume = (int)(((Time.time - consumeStartTime) * samplingRate) - consumedSamples); + consumedSamples += (ulong)CriAtomExAsr.GetPcmOutput(channels, numToConsume, buffer); +#endif + } + +#if UNITY_EDITOR + private void OnPlaymodeStateChange() + { + bool paused = UnityEditor.EditorApplication.isPaused; + if (!isApplicationPaused && isEditorPaused != paused) { + ProcessApplicationPause(paused); + isEditorPaused = paused; + } + } + +#if UNITY_2017_2_OR_NEWER + private void OnPlayModeStateChanged(UnityEditor.PlayModeStateChange state) + { + OnPlaymodeStateChange(); + } + private void OnPauseStateChanged(UnityEditor.PauseState state) + { + OnPlaymodeStateChange(); + } +#endif + +#endif + + void OnApplicationPause(bool appPause) + { +#if UNITY_EDITOR + if (!isEditorPaused && isApplicationPaused != appPause) { + ProcessApplicationPause(appPause); + isApplicationPaused = appPause; + } +#else + ProcessApplicationPause(appPause); +#endif + } + + void ProcessApplicationPause(bool appPause) + { + if (onApplicationPausePreProcess != null) { + onApplicationPausePreProcess(appPause); + } +#if !UNITY_EDITOR && UNITY_IOS + if(appPause == false) { + CriAtomPlugin.CallOnApplicationResume_IOS(); + } +#endif + +#if UNITY_STANDALONE || UNITY_EDITOR + if (!KeepPlayingSoundOnPause) { + CriAtomPlugin.Pause(appPause); + } +#else +#if !UNITY_IOS + CriAtomPlugin.Pause(appPause); +#endif +#endif + if (onApplicationPausePostProcess != null) { + onApplicationPausePostProcess(appPause); + } + } +} + +} //namespace CriWare \ No newline at end of file diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/CriAtomServer.cs.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/CriAtomServer.cs.meta new file mode 100644 index 0000000..cbb5489 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/CriAtomServer.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 4ef410aed001b60468abcbb30b09687a +timeCreated: 1433816076 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/CriAtomSource.cs b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/CriAtomSource.cs new file mode 100644 index 0000000..9a06166 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/CriAtomSource.cs @@ -0,0 +1,130 @@ +/**************************************************************************** + * + * Copyright (c) 2011 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +using UnityEngine; +using System; +using System.Collections; + +/** + * \addtogroup CRIATOM_UNITY_COMPONENT + * @{ + */ + +namespace CriWare { + +/** + * A component that plays sound. + * + * Used by attaching to any GameObject.
+ * If the Cue to be played is set to do 3D Positioning, 3D playback is performed. + * In this case, it is necessary to attach CriWare.CriAtomListener to the camera or main character + * since the localization is calculated with the position of the GameObject to which CriWare.CriAtomListener is attached.
+ * Public variables are basically set on UnityEditor.
+ *
+ */ +[AddComponentMenu("CRIWARE/CRI Atom Source")] +public class CriAtomSource : CriAtomSourceBase +{ + #region Variables + [SerializeField] + private string _cueName = ""; + [SerializeField] + private string _cueSheet = ""; + #endregion + + #region Properties + /** + * Sets/gets the name of the Cue to be played. + * + * When you call the CriAtomSource::Play() function or + * when you play sound at the start of execution by setting the CriAtomSource::playOnStart property, + * the Cue set by this property is played. + * + */ + public string cueName { + get {return this._cueName;} + set {this._cueName = value;} + } + + /** + * Sets/gets the Cue Sheet name. + * + * The Cue specified in the CriAtomSource::Play function or CriAtomSource::CueName property + * is searched from the Cue Sheet set in this property. + * + */ + public string cueSheet { + get {return this._cueSheet;} + set {this._cueSheet = value;} + } + #endregion + + #region Functions + + /** + * Starts playing the Cue that is set. + * Playback ID + * + * The Cue to be played must be set in advance to the + * CriAtomSource::CueName property. + * + */ + public override CriAtomExPlayback Play() + { + return this.Play(this.cueName); + } + + protected override CriAtomExAcb GetAcb() + { + CriAtomExAcb acb = null; + if (!String.IsNullOrEmpty(this.cueSheet)) { + acb = CriAtom.GetAcb(this.cueSheet); + } + return acb; + } + + /** + * Starts playing the Cue that is set. + * + * You must set the CriAtomSource::playOnStart, CriAtomSource::CueName + * properties in advance. + * + */ + protected override void PlayOnStart() + { + if (this.playOnStart && !String.IsNullOrEmpty(this.cueName)) { + StartCoroutine(PlayAsync(this.cueName)); + } + } + + /** + * Asynchronously starts playing the Cue with the specified Cue name. + * Cue name + * Coroutine + * + * It is executed asynchronously by using the coroutine function of Unity. + * Call this function by specifying it as an argument of MonoBehaviour::StartCoroutine. + * + */ + private IEnumerator PlayAsync(string cueName) + { + CriAtomExAcb acb = null; + while (acb == null && !String.IsNullOrEmpty(this.cueSheet)) { + acb = CriAtom.GetAcb(this.cueSheet); + if (acb == null) { + yield return null; + } + } + this.player.SetCue(acb, cueName); + InternalPlayCue(); + } + + #endregion +} + +} //namespace CriWare +/** @} */ +/* end of file */ diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/CriAtomSource.cs.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/CriAtomSource.cs.meta new file mode 100644 index 0000000..84fd19b --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/CriAtomSource.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: d1e631c3b9947b54c823c6853a05529c +timeCreated: 1433816077 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: c7b655dd5eeac7b489f2ddd1304fb5f4, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/CriAtomSourceBase.cs b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/CriAtomSourceBase.cs new file mode 100644 index 0000000..fa0fe37 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/CriAtomSourceBase.cs @@ -0,0 +1,1059 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; + +namespace CriWare { + public abstract class CriAtomSourceBase : CriMonoBehaviour + { + #region Enumlators + /** + * A value indicating the playback status of CriAtomSource. + * + * Information can be obtained using the CriAtomSource::status property. + * + */ + public enum Status + { + Stop, /**< Stopped */ + Prep, /**< Preparing for playback */ + Playing, /**< Playing */ + PlayEnd, /**< Playback completed */ + Error /**< Error occurred */ + } + #endregion + + #region Variables + /** + * The CriAtomExPlayer used internally. + * + * If you want to control CriAtomExPlayer directly, get CriAtomExPlayer from this property. + * + */ + public CriAtomExPlayer player { protected set; get; } + + /** + * This is the CriAtomEx3dSource used internally. + * + * If you want to control CriAtomEx3dSource directly, please get the CriAtomEx3dSource handle from this property. + * + */ + public CriAtomEx3dSource source { protected set; get; } + + protected bool initialized = false; + protected Vector3 lastPosition; + protected bool hasValidPosition = false; + private CriAtomRegion currentRegion = null; + private CriAtomListener currentListener = null; + + [SerializeField] + private bool _playOnStart = false; + [SerializeField] + private CriAtomRegion _regionOnStart = null; + [SerializeField] + private CriAtomListener _listenerOnStart = null; + + // Parameters + [SerializeField] + private bool _use3dPositioning = true; + [SerializeField] + private bool _freezeOrientation = false; + [SerializeField] + private bool _loop = false; + [SerializeField] + private float _volume = 1.0f; + [SerializeField] + private float _pitch = 0.0f; + [SerializeField] + private bool _androidUseLowLatencyVoicePool = false; + [SerializeField] + private bool need_to_player_update_all = true; + [SerializeField] + private bool _use3dRandomization = false; + [SerializeField] + private uint _randomPositionListMaxLength = 0; + [SerializeField] + private CriAtomEx.Randomize3dConfig randomize3dConfig = new CriAtomEx.Randomize3dConfig(0); + #endregion + + #region Properties + + /** + * Sets/gets whether to play at the start of execution. + * + * If set to True, playback starts when starting the execution. + * The timing when playback starts is when the MonoBehaviour::Start function is called. + * Be sure to specify the Cue Sheet name when playing a Cue at the start of execution + * using this flag on a platform where asynchronous ACB loading is enabled such as WebGL.
+ * If not specified, the playback of Cue fails since the system cannot identify + * the Cue Sheet for which it should wait for loading.
+ *
+ */ + public bool playOnStart + { + get { return this._playOnStart; } + set { this._playOnStart = value; } + } + + /** + * Sets whether to use the 3D Positioning. + * + *
+ * By default, the use of 3D Positioning is enabled.
+ * This parameter can be switched at any time.
+ *
+ */ + public bool use3dPositioning + { + set + { + this._use3dPositioning = value; + if (this.player != null) + { + this.player.Set3dSource(this.use3dPositioning ? this.source : null); + this.SetNeedToPlayerUpdateAll(); + } + } + get { return this._use3dPositioning; } + } + + /** + * Sets whether to fix the orientation of the 3D sound source. + * + *
+ * By default, the orientation of the 3D sound source corresponds to the orientation of the GameObject.
+ * If this parameter is set to true, the direction of the sound source will be fixed to the current value.
+ *
+ */ + public bool freezeOrientation + { + get { return this._freezeOrientation; } + set { this._freezeOrientation = value; } + } + + /** + * Sets whether to use randomization of the position of the 3D sound source. + * + *
+ * By default, the randomization of a sound source position is disabled.
+ * This parameter can be switched at any time.
+ *
+ */ + public bool use3dRandomization + { + set + { + this._use3dRandomization = value; + if (this.source != null) + { + if (this._use3dRandomization) + { + this.source.SetRandomPositionConfig(this.randomize3dConfig); + } + else + { + this.source.SetRandomPositionConfig(null); + } + } + } + get { return this._use3dRandomization; } + } + + /** + * Sets the maximum number of elements that can be in the coordinates list used for position randomization of a 3D sound source + * + *
+ * By default, the maximum number of elements in the list is 0.
+ * This parameter can only be changed before the Awake method of the CriAtomSource is executed.
+ *
+ */ + public uint randomPositionListMaxLength + { + set + { + if (initialized) + { + Debug.LogError("[CRIWARE] Max length of random position list cannot be changed after initialization of the CriAtomSource.", this); + return; + } + this._randomPositionListMaxLength = value; + } + get + { + return this._randomPositionListMaxLength; + } + } + + /** + * Sets/gets 3D region of the sound source + * + * If the 3D Positioning is disabled, you cannot set the region. + * + */ + public CriAtomRegion region3d + { + get { return this.currentRegion; } + set + { + if (this.currentRegion == value) + { + return; + } + if (this._use3dPositioning == false) + { + Debug.LogWarning("[CRIWARE] Cannot set 3D Region on audio source with 3d positioning disabled."); + return; + } + /* Remove the reference frome the current region */ + if (this.currentRegion != null) + { + this.currentRegion.referringSources.Remove(this); + } + CriAtomEx3dRegion regionHandle = (value == null) ? null : value.region3dHn; + if (this.source != null) + { + this.source.Set3dRegion(regionHandle); + this.source.Update(); + this.currentRegion = value; + /* Seup a reference from a new region */ + if (this.currentRegion != null) + { + this.currentRegion.referringSources.Add(this); + } + } + else + { + Debug.LogError("[CRIWARE] Internal: 3D Positioning is not initialized correctly."); + this.currentRegion = null; + } + } + } + + /** + * Gets and sets the listener of the sound source + * + * The listener closest to the sound source will be used if no listener is specified. + * If the 3D Positioning is disabled, you cannot set the listener. + * + */ + public CriAtomListener listener + { + get { return currentListener; } + set + { + if (this._use3dPositioning == false) + { + Debug.LogWarning("[CRIWARE] Cannot set 3D Listener on audio source with 3d positioning disabled."); + return; + } + currentListener = value; + player.Set3dListener(value == null ? null : value.nativeListener); + } + } + + /** + * Sets the initial region. + * + * Set the region to be applied when Start is invoked.
+ * Applied only when 3D Positioning is enabled.
+ * It is not applied if empty (null).
+ *
+ */ + public CriAtomRegion regionOnStart + { + get { return this._regionOnStart; } + set { this._regionOnStart = value; } + } + + /** + * Sets the initial listener. + * + * Sets the listener to be applied when Start is executed.
+ * Applies only when 3D positioning is enabled.
+ * Does not apply if empty (null).
+ * The listener closest to the sound source will be used if no listener is specified. + *
+ */ + public CriAtomListener listenerOnStart + { + get { return _listenerOnStart; } + set { _listenerOnStart = value; } + } + + /** + * Switches on/off the loop playback + * Loop switch (True: loop mode, False: cancel loop mode) + * + * Switches the loop playback ON/OFF for the waveform data that does not have a loop point.
+ * By default, loop is OFF.
+ * When loop playback is turned ON, the playback does not end at the end of the sound, and the playback is repeated from the beginning.
+ * The setting in this function is applied to the waveform data.
+ * When this function is called for Sequence data, + * the individual waveform data in the Sequence data is played back in a loop.
+ *
+ * The specification by this function is valid only for waveform data that does not have loop points.
+ * When playing back waveform data with loop points, loop playback is performed + * according to the loop position of the waveform data regardless of the specification of this function.
+ *
+ * This function internally uses the seamless link playback feature.
+ * Therefore, if you use a format that does not support seamless linked playback (such as HCA-MX), + * some amount of silence is inserted at the loop position.
+ *
+ * This parameter is evaluated when the status of the CriAtomSource component is stopped + * and the CriAtomSource::Play function is called.
+ *
+ */ + public bool loop + { + set { this._loop = value; } + get { return this._loop; } + } + + /** + * Sets/gets the volume. + * + * Sets/gets the volume of the output sound.
+ * The volume value is a scale factor for the amplitude of the sound data (the unit is not decibel).
+ * For example, if you specify 1.0f, the original sound is played at its unmodified volume.
+ * If you specify 0.5f, the sound is played at the volume by halving the amplitude (-6dB) + * of the original waveform.
+ * If you specify 0.0f, the sound is muted (silent).
+ * The default value for volume is 1.0f.
+ * When playing a Cue, if this function is called when the volume is set on the data, + * the value set on the data and the setting in this function is multiplied and the result is applied.
+ * For example, if the volume on the data is 0.8f and the volume of CriAtomSource is 0.5f, + * the actual volume applied is 0.4f.
+ *
+ */ + public float volume + { + set + { + this._volume = value; + if (this.player != null) + { + this.player.SetVolume(this._volume); + this.SetNeedToPlayerUpdateAll(); + } + } + get { return this._volume; } + } + + /** + * Sets/gets the pitch. + * + * Sets/gets the pitch of the output sound.
+ * The pitch is specified in cents.
+ * One cent is 1/1200 of one octave. A semitone is 100 cents.
+ * For example, if you specify 100.0f, the pitch increases by a semitone. If you specify -100.0f, the pitch decreases by a semitone.
+ * The default pitch is 0.0f.
+ * When playing a Cue, if this function is called when the pitch is set on the data, + * the value set on the data and the setting in this function is added and the result is applied.
+ * For example, if the pitch on the data is -100.0f and the pitch of CriAtomSource is 200.0f, + * the actual pitch applied is 100.0f.
+ *
+ */ + public float pitch + { + set + { + this._pitch = value; + if (this.player != null) + { + this.player.SetPitch(this._pitch); + this.SetNeedToPlayerUpdateAll(); + } + } + get { return this._pitch; } + } + + /** + * Sets/gets the Panning 3D angle. + * + * Sets/gets the Panning 3D angle.
+ * The angle is specified in degrees.
+ * With front being 0 degree, you can set up to 180.0f in the right direction (clockwise) and -180.0f in the left direction (counterclockwise).
+ * For example, if you specify 45.0f, the localization will be 45 degrees to the front right. If you specify -45.0f, the localization will be 45 degree to the front left.
+ * When playing a Cue, if this function is called when the Panning 3D angle is set on the data, + * the value set on the data and the setting in this function is added and the result is applied.
+ * For example, if the Panning 3D angle on the data is 15.0f and the Panning 3D angle on CriAtomSource is 30.0f, + * the actual Panning 3D angle applied will be 45.0f. + *
+ * If the actual applied Panning 3D angle exceeds 180.0f, -360.0f is added to the value so that it is within the range.
+ * Similarly, if the actual applied volume value is less than -180.0f, +360.0f is add so that it is within the range.
+ * (Since the localization does not change even when +360.0f, or -360.0f is added, you can effectively set a value outside the range of -180.0f to 180.0f.)
+ *
+ */ + public float pan3dAngle + { + set + { + if (this.player != null) + { + this.player.SetPan3dAngle(value); + this.SetNeedToPlayerUpdateAll(); + } + } + get + { + return (this.player != null) ? + this.player.GetParameterFloat32(CriAtomEx.Parameter.Pan3dAngle) : 0.0f; + } + } + + /** + * Sets/gets the Panning 3D distance. + * + * Sets/gets the distance when doing the interior Panning with Panning 3D.
+ * The distance is specified in the range of -1.0f to 1.0f, with the listener position being 0.0f and the circumference of the speaker position being 1.0f.
+ * If you specify a negative value, the Panning 3D angle inverts 180 degrees and the localization is reversed.
+ * When playing a Cue, if this function is called when the Panning 3D distance is set on the data, + * the value set on the data and the setting in this function is multiplied and the result is applied.
+ * For example, if the Panning 3D distance on the data is 0.8f and the Panning 3D distance on CriAtomSource is 0.5f, + * the actual Panning 3D distance applied will be 0.4f. + *
+ * If the actual applied Panning 3D distance exceeds 1.0f, the value is clipped to 1.0f.
+ * Similarly, if the actual applied Panning 3D distance is smaller than -1.0f, the value is clipped to -1.0f.
+ *
+ */ + public float pan3dDistance + { + set + { + if (this.player != null) + { + this.player.SetPan3dInteriorDistance(value); + this.SetNeedToPlayerUpdateAll(); + } + } + get + { + return (this.player != null) ? + this.player.GetParameterFloat32(CriAtomEx.Parameter.Pan3dDistance) : 0.0f; + } + } + + /** + * Sets/gets the playback start position. + * + * Sets/gets the position to start playback. + * By setting the playback start position, you can play the sound data halfway.
+ * The playback start position is specified in milliseconds. For example, if you set 10000, + * the sound data to be played next is played from the position at 10 seconds.
+ * When playing a sound from the middle of the data, the play timing delays + * compared to when playing it from the beginning.
+ * This is because the system must analyze the header of the sound data, + * jump to the specified position, and rereads the data to start playback.
+ * Encrypted ADX data must be decrypted sequentially from the beginning of the data.
+ * Therefore, when playing encrypted ADX data from the middle, + * decryption of the data up to the seeking position will occur, + * causing the processing load to increase significantly.
+ *
+ * If a start position is specified before playing the sequence, + * waveform data placed before that position will not be played.
+ * (Individual waveforms within the sequence will not be played from the middle.)
+ *
+ */ + public int startTime + { + set + { + if (this.player != null) + { + this.player.SetStartTime(value); + this.SetNeedToPlayerUpdateAll(); + } + } + get + { + return (this.player != null) ? + this.player.GetParameterSint32(CriAtomEx.Parameter.StartTime) : 0; + } + } + + + /** + * Gets the playback time (in milliseconds). + * + * If the playback time can be acquired, this property indicates a value of 0 or bigger.
+ * This function indicates a negative value when the playback time cannot be get (when the Voice cannot be get).
+ * Indicates the time of the "last" sound played when multiple + * sounds are played by the same CriAtomSource component.
+ * If you need to check the playback time for multiple sounds, + * create as many CriAtomSource components as the number of sounds to play.
+ *
+ * The playback time indicated by this property is "the elapsed time from the start of playback".
+ * The time does not rewind depending on the playback position, + * even during loop playback or seamless linked playback.
+ *
+ * When the playback is paused using the CriAtomSource::Pause function, + * the playback time count-up also stops.
+ * (If you unpause the playback, the count-up resumes.) + *
+ * The return type is long, but currently there is no precision over 32bit.
+ * When performing control based on the playback time, it should be noted that the playback time becomes incorrect in about 24 days.
+ * (The playback time overflows and becomes a negative value when it exceeds 2147483647 milliseconds.)
+ *
+ * If the Voice being played is erased by the Voice control, + * the playback time count-up also stops at that point.
+ * In addition, if no Voice is allocated by the Voice control at the start of playback, + * this function does not return the correct time.
+ * (Negative value is returned.)
+ *
+ * Even if the sound data supply is temporarily interrupted due to a delay in reading the file etc., + * the playback time count-up is not interrupted.
+ * (The time progresses even if the playback is stopped due to the stop of data supply.)
+ * Therefore, when synchronizing sound with the source video based on the time acquired by this function, + * the synchronization may be greatly deviated each time a data supply shortage occurs.
+ *
+ */ + public long time + { + get + { + return (this.player != null) ? + this.player.GetTime() : 0; + } + } + + /** + * Gets the status. + * + * Gets the status of the CriAtomSource component.
+ * The status is one of following 5 values indicating the playback status of the CriAtomSource component.
+ * -# Stop + * -# Prep + * -# Playing + * -# Playend + * -# Error + * . + *
+ *
+ * When the CriAtomSource component is created, the status of the CriAtomSource component + * is Stop.
+ * When you start playback using the CriAtomSource.Play function etc., the status of the CriAtomSource component + * changes to Prep.
+ * (Prep is the status waiting for the data to be supplied or start of decoding.)
+ * When enough data is supplied for starting playback, the CriAtomSource component + * changes the status to Playing.
+ * If an error occurs during playback, CriAtomSource component + * changes the status to Error.
+ *
+ * By checking the status of CriAtomSource component and switching the processing depending on the status, + * it is possible to create a program linked to the sound playback status.
+ *
+ */ + public Status status + { + get + { + return (this.player != null) ? + (Status)this.player.GetStatus() : Status.Error; + } + } + + /** + * Sets/gets if the distance attenuation is enabled. + * + * Sets/gets whether to enable or disable the volume variation by distance attenuation.
+ * The default is enabled.
+ *
+ */ + public bool attenuationDistanceSetting + { + set + { + if (this.source != null) + { + source.SetAttenuationDistanceSetting(value); + source.Update(); + } + } + get + { + return (this.source != null) ? + source.GetAttenuationDistanceSetting() : false; + } + } + + /** + * Sets/gets whether to play sound from the low delay playback Voice Pool. + * + * If set to True, playback starts using the low latency playback Voice Pool. + * To enable this flag, it is necessary to set the number of low delay playback Voice Pools of CriWareInitializer. + * + */ + public bool androidUseLowLatencyVoicePool + { + get { return this._androidUseLowLatencyVoicePool; } + set { this._androidUseLowLatencyVoicePool = value; } + } + + #endregion + + #region Functions + + protected void SetNeedToPlayerUpdateAll() + { + this.need_to_player_update_all = true; + } + + protected virtual void InternalInitialize() + { + CriAtomPlugin.InitializeLibrary(); + this.player = new CriAtomExPlayer(); + this.source = new CriAtomEx3dSource(randomPositionListMaxLength: this.randomPositionListMaxLength); + this.initialized = true; + } + + protected virtual void InternalFinalize() + { + this.initialized = false; + this.region3d = null; + this.player.Dispose(); + this.player = null; + this.source.Dispose(); + this.source = null; + CriAtomPlugin.FinalizeLibrary(); + } + + void Awake() + { + this.InternalInitialize(); + } + + protected override void OnEnable() + { + base.OnEnable(); + this.hasValidPosition = false; + this.SetInitialParameters(); + this.SetNeedToPlayerUpdateAll(); + } + + void OnDestroy() + { + this.InternalFinalize(); + } + + protected bool SetInitialSourcePosition() + { + Vector3 position = this.transform.position; + this.lastPosition = position; + if (this.source != null) + { + this.source.SetPosition(position.x, position.y, position.z); + this.source.Update(); + return true; + } + else + { + return false; + } + } + + protected virtual void SetInitialParameters() + { + this.use3dPositioning = this.use3dPositioning; /* ここで必要に応じて3Dソースが設定される */ + this.use3dRandomization = this.use3dRandomization; + if (this.SetInitialSourcePosition() == false) + { + Debug.LogError("[ADX2][SetInitialParameters] source is null.", this); + } + + this.player.SetVolume(this._volume); + this.player.SetPitch(this._pitch); + } + + protected virtual void UpdatePosition() + { + Vector3 position = this.transform.position; + this.source.SetPosition(position.x, position.y, position.z); + if (this.hasValidPosition == true) + { + Vector3 velocity = (position - this.lastPosition) / Time.deltaTime; + this.source.SetVelocity(velocity.x, velocity.y, velocity.z); + } + if (this.freezeOrientation == false) + { + this.source.SetOrientation(this.transform.forward, this.transform.up); + } + this.source.Update(); + this.lastPosition = position; + this.hasValidPosition = true; + } + + void Start() + { + if (this.use3dPositioning && this.regionOnStart != null) + { + this.region3d = this.regionOnStart; + } + if (use3dPositioning && listenerOnStart != null) + listener = listenerOnStart; + this.PlayOnStart(); + } + + public override void CriInternalUpdate() { } + + public override void CriInternalLateUpdate() + { + if (this.use3dPositioning == true) + { + UpdatePosition(); + } + + if (this.need_to_player_update_all == true) + { + this.player.UpdateAll(); + this.need_to_player_update_all = false; + } + } + +#if UNITY_EDITOR + static private readonly Color c_CriWareLightBlue = new Color(0.332f, 0.661f, 0.991f); + static private readonly Color c_RandomizeGizmoColor = new Color(0.332f, 0.661f, 0.991f, 0.2f); + private Mesh randomize3dGizmoMesh = null; + private CriAtomEx.Randomize3dCalcType lastRandomizeTypeGizmo = CriAtomEx.Randomize3dCalcType.None; + private Quaternion currentGizmoRotation = Quaternion.identity; + private Quaternion lastGizmoRotation = Quaternion.identity; + + private void SetGizmoMesh(PrimitiveType meshType) + { + GameObject tempPrimitive = GameObject.CreatePrimitive(meshType); + this.randomize3dGizmoMesh = tempPrimitive.GetComponent().sharedMesh; + DestroyImmediate(tempPrimitive); + } + + public void OnDrawGizmos() + { + if (this.enabled == false) { return; } + var gizmoColor = (!Application.isPlaying || this.status == Status.Playing) ? c_CriWareLightBlue : Color.gray; + if (this.freezeOrientation == false) + { + currentGizmoRotation = transform.rotation; + lastGizmoRotation = currentGizmoRotation; + } + else if (Application.isPlaying) + { + currentGizmoRotation = lastGizmoRotation; + } + else + { + currentGizmoRotation = Quaternion.identity; + } + UnityEditor.Handles.color = gizmoColor; + UnityEditor.Handles.DrawLine(this.transform.position, this.transform.position + this.currentGizmoRotation * Vector3.forward); + UnityEditor.Handles.DrawLine(this.transform.position, this.transform.position + this.currentGizmoRotation * Vector3.up); + UnityEditor.Handles.ArrowHandleCap(1, this.transform.position + this.currentGizmoRotation * Vector3.forward, this.currentGizmoRotation, 1f, EventType.Repaint); + UnityEditor.Handles.CircleHandleCap(1, this.transform.position, this.currentGizmoRotation * Quaternion.LookRotation(Vector3.up), 1f, EventType.Repaint); + + if (UnityEditor.Selection.activeGameObject == this.gameObject) + { + bool needRefreshMesh = false; + if (lastRandomizeTypeGizmo != randomize3dConfig.CalculationType) + { + needRefreshMesh = true; + lastRandomizeTypeGizmo = randomize3dConfig.CalculationType; + } + if (use3dRandomization) + { + Gizmos.color = c_RandomizeGizmoColor; + Vector3 scale; + switch (randomize3dConfig.CalculationType) + { + case CriAtomEx.Randomize3dCalcType.Rectangle: + if (needRefreshMesh) { this.SetGizmoMesh(PrimitiveType.Quad); } + scale = new Vector3(randomize3dConfig.CalculationParameter1, randomize3dConfig.CalculationParameter2, 1f); + Gizmos.DrawWireMesh(randomize3dGizmoMesh, this.transform.position, this.currentGizmoRotation * Quaternion.LookRotation(Vector3.up), scale); + break; + case CriAtomEx.Randomize3dCalcType.Cuboid: + if (needRefreshMesh) { this.SetGizmoMesh(PrimitiveType.Cube); } + scale = new Vector3(randomize3dConfig.CalculationParameter1, randomize3dConfig.CalculationParameter3, randomize3dConfig.CalculationParameter2); + Gizmos.DrawWireMesh(randomize3dGizmoMesh, this.transform.position, this.currentGizmoRotation, scale); + break; + case CriAtomEx.Randomize3dCalcType.Circle: + if (needRefreshMesh) { this.SetGizmoMesh(PrimitiveType.Cylinder); } + scale = new Vector3(randomize3dConfig.CalculationParameter1 * 2f, 0, randomize3dConfig.CalculationParameter1 * 2f); + Gizmos.DrawWireMesh(randomize3dGizmoMesh, this.transform.position, this.currentGizmoRotation, scale); + break; + case CriAtomEx.Randomize3dCalcType.Cylinder: + if (needRefreshMesh) { this.SetGizmoMesh(PrimitiveType.Cylinder); } + scale = new Vector3(randomize3dConfig.CalculationParameter1 * 2f, randomize3dConfig.CalculationParameter2, randomize3dConfig.CalculationParameter1 * 2f); + Gizmos.DrawWireMesh(randomize3dGizmoMesh, this.transform.position, this.currentGizmoRotation, scale); + break; + case CriAtomEx.Randomize3dCalcType.Sphere: + if (needRefreshMesh) { this.SetGizmoMesh(PrimitiveType.Sphere); } + scale = new Vector3(randomize3dConfig.CalculationParameter1 * 2f, randomize3dConfig.CalculationParameter1 * 2f, randomize3dConfig.CalculationParameter1 * 2f); + Gizmos.DrawWireMesh(randomize3dGizmoMesh, this.transform.position, this.currentGizmoRotation, scale); + break; + default: + randomize3dGizmoMesh = null; + break; + } + } + } + } +#endif + + #region Abstract Functions + public abstract CriAtomExPlayback Play(); + protected abstract CriAtomExAcb GetAcb(); + protected abstract void PlayOnStart(); + #endregion + + #region PlaybackAndController + + /** + * Starts playing the Cue with the specified Cue name. + * Cue name + * Playback ID + * + * Plays the Cue with the name specified in this function, regardless of how the Cue is specified in the corresponding property. + * + */ + public CriAtomExPlayback Play(string cueName) + { + if (this.player == null) + return new CriAtomExPlayback(CriAtomExPlayback.invalidId); + + CriAtomExAcb acb = GetAcb(); + this.player.SetCue(acb, cueName); + return InternalPlayCue(); + } + + /** + * Starts playing the Cue with the specified Cue ID. + * Cue ID + * Playback ID + * + * Plays the Cue with the ID specified in this function, regardless of how the Cue is specified in the corresponding property. + * + */ + public CriAtomExPlayback Play(int cueId) + { + if (this.player == null) + return new CriAtomExPlayback(CriAtomExPlayback.invalidId); + + + CriAtomExAcb acb = GetAcb(); + this.player.SetCue(acb, cueId); + return InternalPlayCue(); + } + + protected CriAtomExPlayback InternalPlayCue() + { +#if !UNITY_EDITOR && UNITY_ANDROID + if (androidUseLowLatencyVoicePool) { + this.player.SetSoundRendererType(CriAtomEx.SoundRendererType.Native); + } else { + this.player.SetSoundRendererType(CriAtomEx.androidDefaultSoundRendererType); + } +#endif + if (this.hasValidPosition == false) + { + this.SetInitialSourcePosition(); + this.hasValidPosition = true; + } + if (this.status == Status.Stop) + { + this.player.Loop(this._loop); + } + return this.player.Start(); + } + + /** + * Stops playback. + * + * If this function is called for the CriAtomSource component that is playing sound, + * the CriAtomSource component stops playing (stops reading files or playback), + * and transitions to the Stop state.
+ * If this function is called for an CriAtomSource component that has already stopped + * (CriAtomSource component whose status is Playend or Error), the status + * of the CriAtomSource component is changed to Stop.
+ * If this function is called for the CriAtomSource component that is playing sound, the status + * may not change to Stop immediately.
+ * (It may take some time for it to change to Stop.)
+ *
+ */ + public void Stop() + { + if (this.player != null) + { + this.player.Stop(); + } + } + + /** + * Pauses/resumes. + * True: Pause, False: Resume + * + * Pauses/unpauses playback.
+ * When this function is called by specifying True in sw, + * the CriAtomSource component pauses the sound being played.
+ * When this function is called by specifying False in sw, + * the CriAtomSource component resumes the playback of paused sound.
+ *
+ */ + public void Pause(bool sw) + { + if (this.player == null) + return; + + if (sw == false) + { + this.player.Resume(CriAtomEx.ResumeMode.PausedPlayback); + } + else + { + this.player.Pause(); + } + } + + /** + * Gets the posing status. + * Pausing status + * + * Gets the ON/OFF status of the pause.
+ *
+ * + */ + public bool IsPaused() + { + return (this.player != null) ? this.player.IsPaused() : false; + } + + /** + * Set the Bus Send Level by specifying the bus name. + * + * When playing a Cue, if this function is called when the Bus Send Level is set on the data, + * the value set on the data and the setting in this function is multiplied and the result is applied.
+ * For example, if the Bus Send Level on the data is 0.8f and the Bus Send Level of the CriAtomSource is 0.5f, + * the Bus Send Level actually applied is 0.4f.
+ *
+ */ + public void SetBusSendLevel(string busName, float level) + { + if (this.player != null) + { + this.player.SetBusSendLevel(busName, level); + this.SetNeedToPlayerUpdateAll(); + } + } + + /** + * \deprecated + * This is a deprecated API that will be removed. + * Please consider using CriAtomSource.SetBusSendLevel(string, float) instead. + */ + [System.Obsolete("Use CriAtomSource.SetBusSendLevel(string, float)")] + public void SetBusSendLevel(int busId, float level) + { + if (this.player != null) + { + this.player.SetBusSendLevel(busId, level); + this.SetNeedToPlayerUpdateAll(); + } + } + + /** + * Set the Bus Send Level by specifying the bus name and offset. + * + * When playing a Cue, if this function is called when the Bus Send Level is set on the data, + * the value set on the data and the setting in this function is added and the result is applied.
+ * For example, if the Bus Send Level on the data is 0.2f and the Bus Send Level of the CriAtomSource is 0.5f, + * the Bus Send Level actually applied is 0.7f.
+ *
+ */ + public void SetBusSendLevelOffset(string busName, float levelOffset) + { + if (this.player != null) + { + this.player.SetBusSendLevelOffset(busName, levelOffset); + this.SetNeedToPlayerUpdateAll(); + } + } + + /** + * \deprecated + * This is a deprecated API that will be removed. + * Please consider using CriAtomSource.SetBusSendLevelOffset(string, float) instead. + */ + [System.Obsolete("Use CriAtomSource.SetBusSendLevelOffset(string, float)")] + public void SetBusSendLevelOffset(int busId, float levelOffset) + { + if (this.player != null) + { + this.player.SetBusSendLevelOffset(busId, levelOffset); + this.SetNeedToPlayerUpdateAll(); + } + } + + + /** + * Sets the AISAC control value by specifying the AISAC control name. + */ + public void SetAisacControl(string controlName, float value) + { + if (this.player != null) + { + this.player.SetAisacControl(controlName, value); + this.SetNeedToPlayerUpdateAll(); + } + } + + /** + * \deprecated + * This is a deprecated API that will be removed. + * Please consider using CriAtomSource.SetAisacControl instead. + */ + [System.Obsolete("Use CriAtomSource.SetAisacControl")] + public void SetAisac(string controlName, float value) + { + SetAisacControl(controlName, value); + } + + /** + * Sets the AISAC control value by specifying the AISAC control name. + */ + public void SetAisacControl(uint controlId, float value) + { + if (this.player != null) + { + this.player.SetAisacControl(controlId, value); + this.SetNeedToPlayerUpdateAll(); + } + } + + /** + * \deprecated + * This is a deprecated API that will be removed. + * Please consider using CriAtomSource.SetAisacControl instead. + */ + [System.Obsolete("Use CriAtomSource.SetAisacControl")] + public void SetAisac(uint controlId, float value) + { + SetAisacControl(controlId, value); + } + + /** + * Attach to the output data analysis module. + */ + public void AttachToAnalyzer(CriAtomExOutputAnalyzer analyzer) + { + if (this.player != null) + { + analyzer.AttachExPlayer(this.player); + } + } + + /** + * Detaches from the output data analysis module. + */ + public void DetachFromAnalyzer(CriAtomExOutputAnalyzer analyzer) + { + analyzer.DetachExPlayer(); + } + #endregion + + #endregion + } // end of class +} // namespace CriWare diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/CriAtomSourceBase.cs.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/CriAtomSourceBase.cs.meta new file mode 100644 index 0000000..0eaf10e --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/CriAtomSourceBase.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0c5921f941fbd144181ddb7e92b3c842 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/CriAtomTransceiver.cs b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/CriAtomTransceiver.cs new file mode 100644 index 0000000..ba5391c --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/CriAtomTransceiver.cs @@ -0,0 +1,267 @@ +/**************************************************************************** + * + * Copyright (c) 2020 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +using System; +using UnityEngine; + +/** + * \addtogroup CRIATOM_UNITY_COMPONENT + * @{ + */ + +namespace CriWare { + +/** + * Transceiver components + * + * A component which provides spacial audio connection feature. Audio with 3D positioning enabled is submixed and output from a single point.
+ * This component is used by attaching it to any GameObject.
+ * To enable the feature, it is necessary to set CriAtomRegion to the sound source, listener and transceiver.
+ * All transceiver parameters can be set in the Inspector
+ * or the member functions of embedded CriAtomEx3dTransceiver.
+ * All the information on position and orientation of the transceiver is taken from the attached GameObject.
+ * If "Use Dedicated Input" is enabled,
+ * position and orientation of the separately set GameObject are used for transceiver input.
+ * Only one of this component can be attached to a GameObject.
+ *
+ * + */ +[AddComponentMenu("CRIWARE/CRI Atom Transceiver"), DisallowMultipleComponent] +public class CriAtomTransceiver : CriMonoBehaviour +{ + #region Fields & Properties + /** + * The CriAtomEx3dTransceiver used internally. + * + * If you want to control CriAtomEx3dTransceiver directly, get CriAtomEx3dTransceiver from this property. + * + */ + public CriAtomEx3dTransceiver transceiverHn { get; protected set; } + /** Location of transceiver input (read only) */ + public Vector3 inputPos { get; private set; } + /** Forward vector of transceiver input (read only) */ + public Vector3 inputFront { get; private set; } + /** Upper vector of transceiver input (read only) */ + public Vector3 inputUp { get; private set; } + /** + * Sets/gets 3D region of the sound source + */ + public CriAtomRegion region3d + { + get { return this.currentRegion; } + set { + if (this.currentRegion == value) { + return; + } + /* Remove the reference frome the current region */ + if (this.currentRegion != null) { + this.currentRegion.referringTransceivers.Remove(this); + } + CriAtomEx3dRegion regionHandle = (value == null) ? null : value.region3dHn; + if (this.transceiverHn != null) { + this.transceiverHn.Set3dRegion(regionHandle); + this.transceiverHn.Update(); + this.currentRegion = value; + /* Seup a reference from a new region */ + if (this.currentRegion != null) { + this.currentRegion.referringTransceivers.Add(this); + } + } else { + Debug.LogError("[CRIWARE] Internal: The Transcevier is not initialized correctly."); + this.currentRegion = null; + } + } + } + + [SerializeField] private CriAtomRegion regionOnStart = null; + [SerializeField] private bool useDedicatedInput = false; + [SerializeField] private GameObject dedicatedInput = null; + [SerializeField, Range(0, 1f)] private float outputVolume = 1f; + [SerializeField] private float directAudioRadius = 0; + [SerializeField] private float crossFadeDistance = 10f; + [SerializeField, Range(0, 360f)] private float coneInsideAngle = 360f; + [SerializeField, Range(0, 360f)] private float coneOutsideAngle = 360f; + [SerializeField, Range(0, 1f)] private float coneOutsideVolume = 0f; + [SerializeField] private float transceiverRadius = 1f; + [SerializeField] private float interiorDistance = 3f; + [SerializeField] public float minAttenuation = 1f; + [SerializeField] public float maxAttenuation = 100f; + + [SerializeField] private string globalAisacName = string.Empty; + [SerializeField] private float maxAngleAisacDelta = 1f; + [SerializeField] private string distanceAisacControlId = string.Empty; + [SerializeField] private string listenerAzimuthAisacControlId = string.Empty; + [SerializeField] private string listenerElevationAisacControlId = string.Empty; + [SerializeField] private string outputAzimuthAisacControlId = string.Empty; + [SerializeField] private string outputElevationAisacControlId = string.Empty; + + [NonSerialized] public bool inspectorAisacSettingFoldout = false; + + private bool isInitialized = false; + private bool dedicatedInputNotSetWarned = false; + private CriAtomRegion currentRegion = null; + #endregion + + #region Methods + private void Awake() + { + this.InternalInitialize(); + } + + private void Start() + { + if (this.regionOnStart != null) { + this.region3d = this.regionOnStart; + } + } + + protected override void OnEnable() + { + base.OnEnable(); + this.InitializeParameters(); + } + + private void OnDestroy() + { + this.InternalFinalize(); + } + + protected virtual void InternalInitialize() + { + CriAtomPlugin.InitializeLibrary(); + this.transceiverHn = new CriAtomEx3dTransceiver(); + this.isInitialized = true; + } + + protected virtual void InternalFinalize() + { + this.isInitialized = false; + this.region3d = null; + this.transceiverHn.Dispose(); + this.transceiverHn = null; + CriAtomPlugin.FinalizeLibrary(); + } + + protected virtual void InitializeParameters() + { + if (this.transceiverHn != null) { + this.ApplyCurrentPosition(); + this.ApplyParameters(); + } else { + Debug.LogError("[CRIWARE] Internal: CriAtomEx3dTranceiver is not created correctly.", this); + } + } + + public override void CriInternalUpdate() { } + + public override void CriInternalLateUpdate() + { + this.ApplyCurrentPosition(); + } + + private void ApplyCurrentPosition() + { + if (this.isInitialized == false || this.transceiverHn == null) { return; } + + Vector3 position = this.transform.position; + Vector3 front = this.transform.forward; + Vector3 up = this.transform.up; + this.transceiverHn.SetOutputPosition(position); + this.transceiverHn.SetOutputOrientation(front, up); + + if (this.useDedicatedInput) { + if (this.dedicatedInput != null) { + var listenerTransform = this.dedicatedInput.transform; + this.inputPos = listenerTransform.position; + this.inputFront = listenerTransform.forward; + this.inputUp = listenerTransform.up; + } else { + if (dedicatedInputNotSetWarned == false) { + Debug.LogWarning("[CRIWARE] " + this.GetType().ToString() + " : dedicated input is not specified. The output object will also be used as input.", this); + this.dedicatedInputNotSetWarned = true; + } + this.inputPos = position; + this.inputFront = -front; + this.inputUp = up; + } + } else { + this.inputPos = position; + this.inputFront = -front; + this.inputUp = up; + } + this.transceiverHn.SetInputPosition(this.inputPos); + this.transceiverHn.SetInputOrientation(this.inputFront, this.inputUp); + + this.transceiverHn.Update(); + } + + private void ApplyParameters() + { + if (this.isInitialized == false || this.transceiverHn == null) { return; } + + this.transceiverHn.SetOutputVolume(this.outputVolume); + this.transceiverHn.SetInputCrossFadeField(this.directAudioRadius, this.crossFadeDistance); + this.transceiverHn.SetOutputConeParameter(this.coneInsideAngle, this.coneOutsideAngle, this.coneOutsideVolume); + this.transceiverHn.SetOutputInteriorPanField(this.transceiverRadius, this.interiorDistance); + this.transceiverHn.SetOutputMinMaxDistance(this.minAttenuation, this.maxAttenuation); + + if (string.IsNullOrEmpty(globalAisacName) == false) { + this.transceiverHn.AttachAisac(globalAisacName); + } + this.transceiverHn.SetMaxAngleAisacDelta(this.maxAngleAisacDelta); + TrySetAisacControlId(distanceAisacControlId, this.transceiverHn.SetDistanceAisacControlId); + TrySetAisacControlId(listenerAzimuthAisacControlId, this.transceiverHn.SetListenerBasedAzimuthAngleAisacControlId); + TrySetAisacControlId(listenerElevationAisacControlId, this.transceiverHn.SetListenerBasedElevationAngleAisacControlId); + TrySetAisacControlId(outputAzimuthAisacControlId, this.transceiverHn.SetTransceiverOutputBasedAzimuthAngleAisacControlId); + TrySetAisacControlId(outputElevationAisacControlId, this.transceiverHn.SetTransceiverOutputBasedElevationAngleAisacControlId); + + this.transceiverHn.Update(); + } + + private delegate void SetControlIdMethod(ushort id); + private void TrySetAisacControlId(string strId, SetControlIdMethod callback) + { + if (string.IsNullOrEmpty(strId) == false) { + ushort controlId; + if (ushort.TryParse(strId, out controlId)) { + callback.Invoke(controlId); + } else { + Debug.LogError("[CRIWARE] " + this.GetType().ToString() + " : invalid AISAC control ID.", this); + } + } + } + +#if UNITY_EDITOR + public void OnDrawGizmos() + { + if (this.enabled == false) { return; } + + Gizmos.color = Color.green; + Gizmos.DrawLine(this.transform.position, this.transform.position + this.transform.up); + if (UnityEditor.Selection.activeGameObject != this.gameObject) { + Gizmos.DrawLine(this.transform.position, this.transform.position + this.transform.forward); + UnityEditor.Handles.color = Color.green; + UnityEditor.Handles.ArrowHandleCap(0, this.transform.position + this.transform.forward, this.transform.rotation, 1f, EventType.Repaint); + UnityEditor.Handles.CircleHandleCap(0, this.transform.position, this.transform.rotation * Quaternion.LookRotation(Vector3.up), 1f, EventType.Repaint); + } + + if (this.useDedicatedInput && this.dedicatedInput != null) { + var transformTarget = this.dedicatedInput.transform; + Gizmos.color = Color.green; + Gizmos.DrawLine(transformTarget.position, transformTarget.position + transformTarget.forward); + Gizmos.DrawLine(transformTarget.position, transformTarget.position + transformTarget.up); + UnityEditor.Handles.color = Color.green; + UnityEditor.Handles.ArrowHandleCap(0, transformTarget.position + transformTarget.forward, transformTarget.rotation, 1f, EventType.Repaint); + UnityEditor.Handles.RectangleHandleCap(0, transformTarget.position, transformTarget.rotation * Quaternion.LookRotation(Vector3.up), 1f, EventType.Repaint); + } + } +#endif + #endregion +} // end of class + +} //namespace CriWare +/** @} */ +/* end of file */ diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/CriAtomTransceiver.cs.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/CriAtomTransceiver.cs.meta new file mode 100644 index 0000000..a9da9a6 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/CriAtomTransceiver.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c0f10afca132f5f40bd79b939ee6199c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {fileID: 2800000, guid: 092d44bfa808b4645826d36c43846fa4, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/Extension.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/Extension.meta new file mode 100644 index 0000000..049deb0 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/Extension.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: ae9fc3f8a6f8c4947a79f85929c29c78 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/Extension/CriAtomBehaviour.cs b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/Extension/CriAtomBehaviour.cs new file mode 100644 index 0000000..d325c4d --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/Extension/CriAtomBehaviour.cs @@ -0,0 +1,143 @@ +/**************************************************************************** + * + * Copyright (c) 2019 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +#if UNITY_2018_1_OR_NEWER && CRIWARE_TIMELINE_1_OR_NEWER + +using System; +using System.Threading; +using UnityEngine; +using UnityEngine.Playables; +using UnityEngine.Timeline; + +namespace CriWare { + +namespace CriTimeline.Atom +{ + public struct CriAtomClipPlayConfig { + readonly public CriAtomClipBase clip; + readonly public long startTimeMs; + readonly public double speedRate; + readonly public bool loop; + + public CriAtomClipPlayConfig( + CriAtomClipBase clip, + long startTimeMs, + double speedRate, + bool loop + ) { + this.clip = clip; + this.startTimeMs = startTimeMs; + this.speedRate = speedRate; + this.loop = loop; + } + } + + [Serializable] + public class CriAtomBehaviour : PlayableBehaviour { + [Range(0.0f, 1.0f)] + public float volume = 1f; + [Range(-1200.0f, 1200.0f)] + public float pitch = 0f; + [Range(0.0f, 1.0f)] + public float AISACValue = 0f; + + static private int cPreviewStopTimeMs = 500; + + private CriAtomExAcb m_acb = null; + private string m_lastCueSheetPath = null; + + public CriAtomExPlayback playback { get; private set; } + private bool _IsClipPlaying = false; + public bool IsClipPlaying { get { return _IsClipPlaying; } private set { _IsClipPlaying = value; } } + private double _CueLength = 0; + public double CueLength { get { return _CueLength; } private set { _CueLength = value; } } + + public override void OnGraphStop(Playable playable) { + base.OnGraphStop(playable); + + this.IsClipPlaying = false; + } + + public void Play(CriAtomSourceBase atomSource, CriAtomClipPlayConfig config) { + this.IsClipPlaying = true; + + if (atomSource == null) { + return; + } + + if (config.clip.AcbPath != m_lastCueSheetPath) { + m_acb = config.clip.GetAcb(); + } + if (m_acb != null) { + atomSource.player.SetCue(m_acb, config.clip.CueName); + this.CueLength = GetCueLengthSec(m_acb, config.clip.CueName); + m_lastCueSheetPath = config.clip.AcbPath; + + if (this.playback.status != CriAtomExPlayback.Status.Removed) { + this.playback.Stop(); + } + + if (this.CueLength > 0) { + atomSource.player.SetStartTime(config.startTimeMs); + atomSource.player.Loop(config.loop); + this.playback = atomSource.player.Start(); + } + } + } + + public void PreviewPlay(Guid trackId, bool instantStop, CriAtomClipPlayConfig config) { + this.IsClipPlaying = true; + + if (config.clip.AcbPath != m_lastCueSheetPath) { + m_acb = CriAtomTimelinePreviewer.Instance.GetAcb(config.clip.AcbPath, config.clip.AwbPath); + } + if (m_acb != null) { + CriAtomTimelinePreviewer.Instance.SetCue(trackId, m_acb, config.clip.CueName); + this.CueLength = GetCueLengthSec(m_acb, config.clip.CueName); + m_lastCueSheetPath = config.clip.AcbPath; + + if (this.playback.status != CriAtomExPlayback.Status.Removed) { + this.playback.Stop(); + } + + if (this.CueLength > 0) { + CriAtomTimelinePreviewer.Instance.SetStartTime(trackId, config.startTimeMs); + CriAtomTimelinePreviewer.Instance.SetLoop(trackId, config.loop); + this.playback = CriAtomTimelinePreviewer.Instance.Play(trackId); + if (instantStop) { + WaitAndStop(); + } + } + } + } + + private void WaitAndStop() { + var thread = new Thread(() => { + Thread.Sleep(cPreviewStopTimeMs); + this.Stop(true); + }); + thread.Start(); + } + + public void Stop(bool noReleaseTime = false) { + this.playback.Stop(noReleaseTime); + this.IsClipPlaying = false; + } + + private double GetCueLengthSec(CriAtomExAcb acb, string cueName) { + CriAtomEx.WaveformInfo waveInfo; + if (acb != null && acb.GetWaveFormInfo(cueName, out waveInfo) == true) { + return waveInfo.numSamples / (double)waveInfo.samplingRate; + } else { + return 0; + } + } + } +} + +} //namespace CriWare + +#endif \ No newline at end of file diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/Extension/CriAtomBehaviour.cs.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/Extension/CriAtomBehaviour.cs.meta new file mode 100644 index 0000000..bca3aa5 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/Extension/CriAtomBehaviour.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 545b20387c678bb41b7a880f91cb423c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/Extension/CriAtomClip.cs b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/Extension/CriAtomClip.cs new file mode 100644 index 0000000..c990876 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/Extension/CriAtomClip.cs @@ -0,0 +1,119 @@ +/**************************************************************************** + * + * Copyright (c) 2019 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +#if UNITY_2018_1_OR_NEWER && CRIWARE_TIMELINE_1_OR_NEWER + +using System; +using UnityEngine; +using UnityEngine.Playables; +using UnityEngine.Timeline; + +namespace CriWare { + +namespace CriTimeline.Atom +{ + public class CriAtomClip : CriAtomClipBase + { + public string cueSheet; + public string cueName; + + public override string CueName { + get { + return cueName; + } + } + + public override CriAtomExAcb GetAcb() => CriAtom.GetAcb(cueSheet); + + CriAtomCueSheet GetCueSheet() { +#if UNITY_EDITOR + var atom = (CriAtom)UnityEngine.Object.FindObjectOfType(typeof(CriAtom)); + if (atom == null) + { + Debug.LogWarning("[CRIWARE] Timeline Previewer: CriAtom not set in the scene"); + return null; + } + return atom.GetCueSheetInternal(cueSheet); +#else + return CriAtom.GetCueSheet(cueSheet); +#endif + } + + public override string AcbPath { + get { + var sheet = GetCueSheet(); + if (string.IsNullOrEmpty(sheet.acbFile)) + return null; + return System.IO.Path.Combine(CriWare.Common.streamingAssetsPath, sheet.acbFile); + } + } + + public override string AwbPath { + get + { + var sheet = GetCueSheet(); + if (string.IsNullOrEmpty(sheet.awbFile)) + return null; + return System.IO.Path.Combine(CriWare.Common.streamingAssetsPath, sheet.awbFile); + } + } + + public override void SetCueFromAtomSource(CriAtomSourceBase atomSource) { + if (!(atomSource is CriAtomSource)) return; + if (string.IsNullOrEmpty(cueSheet)) { + cueSheet = (atomSource as CriAtomSource).cueSheet; + } + if (string.IsNullOrEmpty(cueName)) { + cueName = (atomSource as CriAtomSource).cueName; + } + } + } + + public abstract class CriAtomClipBase : PlayableAsset, ITimelineClipAsset { + public bool stopWithoutRelease = false; + public bool muted = false; + public bool ignoreBlend = false; + public bool loopWithinClip = false; + public bool stopAtClipEnd = true; + + public CriAtomBehaviour templateBehaviour = new CriAtomBehaviour(); + + [SerializeField, HideInInspector] private double clipDuration = 0.0; + + public ClipCaps clipCaps { + get { return ClipCaps.Looping | ClipCaps.SpeedMultiplier | ClipCaps.Blending; } + } + + public override Playable CreatePlayable(PlayableGraph graph, GameObject owner) { + return ScriptPlayable.Create(graph, templateBehaviour); + } + + public void SetClipDuration(double clipDuration) { + this.clipDuration = clipDuration; + } + + public override double duration { + get { + return clipDuration > 0.0 ? clipDuration : 2.0; + } + } + +#region Abstracts + + public abstract string CueName { get; } + + public abstract CriAtomExAcb GetAcb(); + public abstract string AcbPath { get; } + public abstract string AwbPath { get; } + + public abstract void SetCueFromAtomSource(CriAtomSourceBase atomSource); + +#endregion + } +} + +} //namespace CriWare +#endif \ No newline at end of file diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/Extension/CriAtomClip.cs.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/Extension/CriAtomClip.cs.meta new file mode 100644 index 0000000..d27ffc6 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/Extension/CriAtomClip.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ec394b19c2203cb44aec13d50aa7361d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/Extension/CriAtomMixerBehaviour.cs b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/Extension/CriAtomMixerBehaviour.cs new file mode 100644 index 0000000..b557df4 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/Extension/CriAtomMixerBehaviour.cs @@ -0,0 +1,371 @@ +/**************************************************************************** + * + * Copyright (c) 2019 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +#if UNITY_2018_1_OR_NEWER && CRIWARE_TIMELINE_1_OR_NEWER + +using System; +using System.Collections.Generic; +using System.IO; +using UnityEngine; +using UnityEngine.Playables; +using UnityEngine.Timeline; + +namespace CriWare { + +namespace CriTimeline.Atom +{ + [Serializable] + public class CriAtomMixerBehaviour : PlayableBehaviour { + internal PlayableDirector m_Director; + internal IEnumerable m_Clips; + internal CriAtomSourceBase m_Bind; + internal string m_AisacControls; + internal bool m_StopOnWrapping; + internal bool m_StopAtGraphEnd; + + public Guid m_Guid { get; private set; } + + private const int cScratchTimeIntervalMs = 200; + private DateTime m_lastScrubTime; + private double m_lastDirectorTime = 0; + + public override void OnPlayableCreate(Playable playable) { + base.OnPlayableCreate(playable); + m_Guid = Guid.NewGuid(); + if (IsEditor) { + if (CriAtomPlugin.IsLibraryInitialized() == false) { + CriWareInitializer criInitializer = GameObject.FindObjectOfType(); + if (criInitializer != null) { + CriWareInitializer.InitializeAtom(criInitializer.atomConfig); + } else { + CriWareInitializer.InitializeAtom(new CriAtomConfig()); + Debug.Log("[CRIWARE] Timeline / Atom: Can't find CriWareInitializer component; Using default parameters in edit mode."); + } + } + } + m_lastDirectorTime = 0; + } + + public override void OnGraphStop(Playable playable) { + base.OnGraphStop(playable); + + if (IsEditor) { + if (CriAtomTimelinePreviewer.IsInitialized) { + CriAtomTimelinePreviewer.Instance.StopAllTracks(); + } + } else { + if (m_Bind != null && this.m_StopAtGraphEnd) { + m_Bind.Stop(); + } + } + m_lastDirectorTime = 0; + } + + public override void ProcessFrame(Playable playable, FrameData info, object playerData) { + if (playerData == null || m_Director.time == m_lastDirectorTime) { return; } + + bool wrapped = false; + if (m_Director.state == PlayState.Playing && m_Director.time < m_lastDirectorTime) { wrapped = true; } + m_lastDirectorTime = m_Director.time; + + int inputPort = 0; + foreach (var clip in m_Clips) { + ScriptPlayable inputPlayable = (ScriptPlayable)playable.GetInput(inputPort); + CriAtomBehaviour clipBehaviour = inputPlayable.GetBehaviour(); + CriAtomClipBase criAtomClip = clip.asset as CriAtomClipBase; + float inputWeight = criAtomClip.ignoreBlend ? 1f : playable.GetInputWeight(inputPort); + + if (clipBehaviour != null) { + if (m_StopOnWrapping && wrapped) { + if (clipBehaviour.IsClipPlaying) { + clipBehaviour.Stop(criAtomClip.stopWithoutRelease); + } + } + + if (m_Director.time >= clip.end || + m_Director.time <= clip.start) { + if (clipBehaviour.IsClipPlaying && criAtomClip.stopAtClipEnd) { + clipBehaviour.Stop(criAtomClip.stopWithoutRelease); + } + } else if (criAtomClip.muted == false) { + long seekTimeMs = (long)((m_Director.time - clip.start) * 1000.0); + bool isDirectorPaused = (m_Director.state == PlayState.Paused); + + var playConfig = new CriAtomClipPlayConfig( + criAtomClip, + seekTimeMs, + clip.timeScale, + criAtomClip.loopWithinClip + ); + + if (clipBehaviour.IsClipPlaying == false) { /* Entering clip for the first time */ + if (IsEditor == false) { + clipBehaviour.Play(m_Bind, playConfig); + } else { + clipBehaviour.PreviewPlay(m_Guid, isDirectorPaused, playConfig); + m_lastScrubTime = DateTime.Now; + } + criAtomClip.SetClipDuration(clipBehaviour.CueLength); + } else { + var now = DateTime.Now; + if (IsEditor == true && isDirectorPaused && + now - m_lastScrubTime > new TimeSpan(0, 0, 0, 0, cScratchTimeIntervalMs)) { /* Scrubing the track */ + clipBehaviour.Stop(true); + clipBehaviour.PreviewPlay(m_Guid, isDirectorPaused, playConfig); + m_lastScrubTime = now; + } + } + + if (IsEditor == true) { + CriAtomTimelinePreviewer.Instance.SetVolume(m_Guid, clipBehaviour.volume * inputWeight); + CriAtomTimelinePreviewer.Instance.SetPitch(m_Guid, clipBehaviour.pitch); + if (string.IsNullOrEmpty(m_AisacControls) == false) { + CriAtomTimelinePreviewer.Instance.SetAISAC(m_Guid, m_AisacControls, clipBehaviour.AISACValue); + } + CriAtomTimelinePreviewer.Instance.PlayerUpdateParameter(m_Guid, clipBehaviour.playback); + } else { + m_Bind.player.SetVolume(clipBehaviour.volume * inputWeight); + m_Bind.player.SetPitch(clipBehaviour.pitch); + if (string.IsNullOrEmpty(m_AisacControls) == false) { + m_Bind.player.SetAisacControl(m_AisacControls, clipBehaviour.AISACValue); + } + m_Bind.player.Update(clipBehaviour.playback); + } + } + } + + inputPort++; + } + } + + static private bool IsEditor { + get { +#if UNITY_EDITOR + if (UnityEditor.EditorApplication.isPlaying == false) { + return true; + } +#endif + return false; + } + } + } + + public class CriAtomTimelinePreviewer : IDisposable { + static private CriAtomTimelinePreviewer instance = null; + static public CriAtomTimelinePreviewer Instance { + get { + if (instance == null) { + instance = new CriAtomTimelinePreviewer(); +#if UNITY_EDITOR + UnityEditor.EditorApplication.playModeStateChanged += OnPlayModeStateChanged; +#endif + } + return instance; + } + } + static public void InstanceDispose() { + if (instance != null) { + instance.Dispose(); + instance = null; +#if UNITY_EDITOR + UnityEditor.EditorApplication.playModeStateChanged -= OnPlayModeStateChanged; +#endif + } + } + static public bool IsInitialized { + get { + if (instance == null) { + return false; + } + return true; + } + } + +#if UNITY_EDITOR + static void OnPlayModeStateChanged(UnityEditor.PlayModeStateChange change) + { + if (change == UnityEditor.PlayModeStateChange.EnteredEditMode) + InstanceDispose(); + } +#endif + + struct PlayerSource { + public readonly CriAtomExPlayer player; + public readonly CriAtomEx3dSource source3d; + + public PlayerSource(CriAtomEx3dListener listener) { + this.player = new CriAtomExPlayer(); + this.source3d = new CriAtomEx3dSource(); + this.source3d.SetPosition(0, 0, 0); + this.source3d.Update(); + this.player.Set3dSource(this.source3d); + this.player.Set3dListener(listener); + this.player.UpdateAll(); + } + } + + private CriAtom atom; + private string lastAcfFile = ""; + private Dictionary acbTable; + private Dictionary playerTable; /* preview player for each track */ + private CriAtomEx3dListener listener3d; + + public CriAtomTimelinePreviewer() { + this.acbTable = new Dictionary(); + this.playerTable = new Dictionary(); + + if (listener3d == null) { + listener3d = new CriAtomEx3dListener(); + listener3d.SetPosition(0, 0, 0); + listener3d.Update(); + } + } + + public CriAtomExPlayer GetPlayer(Guid trackId) { + if (this.playerTable.ContainsKey(trackId)) { + return this.playerTable[trackId].player; + } else { + PlayerSource playerSource = new PlayerSource(this.listener3d); + try { + this.playerTable.Add(trackId, playerSource); + } catch (Exception e) { /* impossible */ + Debug.LogError("[CRIWARE] Timeline Previewer: Failed adding preview player (" + e.Message + ")"); + } + return playerSource.player; /* return the created player anyway */ + } + } + + public void SetCue(Guid trackId, CriAtomExAcb acb, string cueName) { + if (acb != null && string.IsNullOrEmpty(cueName) == false) { + this.GetPlayer(trackId).SetCue(acb, cueName); + } else { + Debug.LogWarning("[CRIWARE] Timeline Previewer: insufficient ACB or cue name"); + } + } + + public CriAtomExAcb GetAcb(string acbPath, string awbPath) { + if (string.IsNullOrEmpty(acbPath)) { + Debug.LogWarning("[CRIWARE] Timeline Previewer: cuesheet path is vacant"); + return null; + } + + this.atom = (CriAtom)UnityEngine.Object.FindObjectOfType(typeof(CriAtom)); + if(this.atom != null) + { + if (lastAcfFile != this.atom.acfFile) { + CriAtomEx.UnregisterAcf(); + CriAtomEx.RegisterAcf(null, Path.Combine(CriWare.Common.streamingAssetsPath, atom.acfFile)); + lastAcfFile = this.atom.acfFile; + } + } + + if (this.acbTable.ContainsKey(acbPath)) { + return acbTable[acbPath]; + } else { + CriAtomExAcb acb = CriAtomExAcb.LoadAcbFile(null, acbPath, awbPath); + if (acb != null) { + try { + acbTable.Add(acbPath, acb); + } catch (Exception e) { + if (e is ArgumentException) { + /* impossible */ + Debug.LogWarning("[CRIWARE] Timeline Previewer: ACB already existing."); + } else { + Debug.LogWarning("[CRIWARE] Timeline Previewer: ACB Dictionary exception: " + e.Message); + } + } + } else { + Debug.LogWarning("[CRIWARE] Timeline Previewer: Failed loading ACB/AWB file."); + } + return acb; + } + } + + public CriAtomExPlayback Play(Guid trackId) { + return this.GetPlayer(trackId).Start(); + } + + public void StopTrack(Guid trackId, bool stopWithoutRelease = true) { + if (stopWithoutRelease) { + this.GetPlayer(trackId).StopWithoutReleaseTime(); + } else { + this.GetPlayer(trackId).Stop(); + } + } + + public void StopAllTracks(bool stopWithoutRelease = true) { + foreach (var elem in playerTable) { + if (stopWithoutRelease) { + elem.Value.player.StopWithoutReleaseTime(); + } else { + elem.Value.player.Stop(); + } + } + } + + public void SetStartTime(Guid trackId, long startTimeMs) { + this.GetPlayer(trackId).SetStartTime(startTimeMs); + } + + public void SetLoop(Guid trackId, bool sw) { + this.GetPlayer(trackId).Loop(sw); + } + + public void SetVolume(Guid trackId, float volume) { + this.GetPlayer(trackId).SetVolume(volume); + } + + public void SetPitch(Guid trackId, float pitch) { + this.GetPlayer(trackId).SetPitch(pitch); + } + + public void SetAISAC(Guid trackId, string controlName, float value) { + this.GetPlayer(trackId).SetAisacControl(controlName, value); + } + + public void PlayerUpdateParameter(Guid trackId, CriAtomExPlayback atomExPlayback) { + this.GetPlayer(trackId).Update(atomExPlayback); + } + + ~CriAtomTimelinePreviewer() { + this.Dispose(false); + } + + public void Dispose() { + this.Dispose(true); + GC.SuppressFinalize(this); + } + + private void Dispose(bool disposing) { + foreach (var elem in playerTable.Values) { + if (elem.player != null) { + elem.player.Stop(); + elem.player.Set3dListener(null); + elem.player.Set3dSource(null); + elem.player.Dispose(); + } + if (elem.source3d != null) { + elem.source3d.Dispose(); + } + } + playerTable.Clear(); + + foreach (var elem in acbTable.Values) { + elem.Dispose(); + } + acbTable.Clear(); + + if (listener3d != null) { + listener3d.Dispose(); + listener3d = null; + } + } + } +} + +} //namespace CriWare + +#endif \ No newline at end of file diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/Extension/CriAtomMixerBehaviour.cs.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/Extension/CriAtomMixerBehaviour.cs.meta new file mode 100644 index 0000000..7f895ad --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/Extension/CriAtomMixerBehaviour.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: beb68135fd7c2e249ad0f6557b13d1dd +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/Extension/CriAtomTrack.cs b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/Extension/CriAtomTrack.cs new file mode 100644 index 0000000..6e09c20 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/Extension/CriAtomTrack.cs @@ -0,0 +1,57 @@ +/**************************************************************************** + * + * Copyright (c) 2019 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +#if UNITY_2018_1_OR_NEWER && CRIWARE_TIMELINE_1_OR_NEWER + +using UnityEngine; +using UnityEngine.Playables; +using UnityEngine.Timeline; + +namespace CriWare { + +namespace CriTimeline.Atom +{ + [TrackColor(0.3317462f, 0.6611561f, 0.990566f)] + [TrackClipType(typeof(CriAtomClipBase))] + [TrackBindingType(typeof(CriAtomSourceBase))] + public class CriAtomTrack : TrackAsset { + public string m_AisacControls; + public bool m_StopOnWrapping = true; + public bool m_StopAtGraphEnd = true; +#if UNITY_EDITOR + public bool m_IsRenderMono = true; +#endif + + public override Playable CreateTrackMixer(PlayableGraph graph, GameObject owner, int inputCount) { + var mixerPlayable = ScriptPlayable.Create(graph, inputCount); + var mixerBehaviour = mixerPlayable.GetBehaviour(); + if (mixerBehaviour != null) { + mixerBehaviour.m_Director = owner.GetComponent(); + mixerBehaviour.m_Clips = this.GetClips(); + mixerBehaviour.m_Bind = mixerBehaviour.m_Director.GetGenericBinding(this) as CriAtomSourceBase; + + if(mixerBehaviour.m_Bind != null) { + CriAtomClipBase criAtomClip; + foreach (var clip in mixerBehaviour.m_Clips) { + criAtomClip = clip.asset as CriAtomClipBase; + + criAtomClip.SetCueFromAtomSource(mixerBehaviour.m_Bind); + + clip.displayName = criAtomClip.CueName; + } + } + mixerBehaviour.m_AisacControls = this.m_AisacControls; + mixerBehaviour.m_StopOnWrapping = this.m_StopOnWrapping; + mixerBehaviour.m_StopAtGraphEnd = this.m_StopAtGraphEnd; + } + return mixerPlayable; + } + } +} + +} //namespace CriWare + +#endif \ No newline at end of file diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/Extension/CriAtomTrack.cs.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/Extension/CriAtomTrack.cs.meta new file mode 100644 index 0000000..e699400 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/Extension/CriAtomTrack.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 57d76e8978fa3b442a107420348f6623 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses.meta new file mode 100644 index 0000000..27f6c96 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: e02c56df66bd95e489a903e5216a1455 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomEx.cs b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomEx.cs new file mode 100644 index 0000000..7cfa653 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomEx.cs @@ -0,0 +1,3283 @@ +/**************************************************************************** + * + * Copyright (c) 2011 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using System.Text; +using AisacControlId = System.UInt32; + +namespace CriWare { + +public class CriStructMemory : IDisposable +{ + public byte[] bytes { + get; private set; + } + public IntPtr ptr { + get { return gch.AddrOfPinnedObject(); } + } + GCHandle gch; + + public CriStructMemory() + { + this.bytes = new byte[Marshal.SizeOf(typeof(Type))]; + this.gch = GCHandle.Alloc(this.bytes, GCHandleType.Pinned); + } + + public CriStructMemory(int num) + { + this.bytes = new byte[Marshal.SizeOf(typeof(Type)) * num]; + this.gch = GCHandle.Alloc(this.bytes, GCHandleType.Pinned); + } + + public void Dispose() + { + this.gch.Free(); + } +} + +} //namespace CriWare + +/*========================================================================== + * CRI Atom Native Wrapper + *=========================================================================*/ +/** + * \addtogroup CRIATOM_NATIVE_WRAPPER + * @{ + */ + +namespace CriWare { + +/** + * Global class of the Atom library. + * + * A class that contains setting functions for the Atom library and variable types shared in the Atom library.
+ *
+ */ +public static class CriAtomEx +{ + /** + * Invalid value of the AISAC control ID + */ + public const AisacControlId InvalidAisacControlId = 0xffffffffu; + + /** + * Character code + * + * Indicates the character code (character encoding method). + * + */ + public enum CharacterEncoding : int + { + /** UTF-8 */ + Utf8, + /** Shift_JIS */ + Sjis, + } + + /** + * Sound renderer type + * + * Indicates the type of sound renderer created internally by CriWare.CriAtomExPlayer. + * + */ + public enum SoundRendererType { + Default = 0, + Native = 1, + Asr = 2, + Hw1 = 1, + Hw2 = 9, + Haptic = 3, + } + + /** + * Voice allocation method + * + * Data type used to specify the behavior of CriWare.CriAtomExPlayer when it allocates voices. + * + * + */ + public enum VoiceAllocationMethod { + Once, /**< Allocate a Voice only once */ + Retry, /**< Allocate a Voice repeatedly */ + } + + /** + * Biquad Filter type + * + * A data type that specifies the type of Biquad Filter.
+ * Used in the CriWare.CriAtomExPlayer::SetBiquadFilterParameters .
+ *
+ * + */ + public enum BiquadFilterType { + Off, /**< Filter disabled */ + LowPass, /**< Low pass filter */ + HighPass, /**< High pass filter */ + Notch, /**< Notch filter */ + LowShelf, /**< Low shelf filter */ + HighShelf, /**< High shelf filter */ + Peaking /**< Peaking filter */ + } + + /** + * Unpausing method + * + * A data type for specifying the target to unpause.
+ * Used as an argument to the CriWare.CriAtomExPlayer::Resume and + * CriWare.CriAtomExPlayback::Resume functions.
+ *
+ * + * + */ + public enum ResumeMode { + AllPlayback = 0, /**< Resumes playback regardless of how it was paused */ + PausedPlayback = 1, /**< Resumes playback only for the sound paused by the Pause function */ + PreparedPlayback = 2, /**< Starts playback of the sound prepared for playback using the Prepare function */ + } + + /** + * Panning type + * + * A data type for specifying how to perform the localization calculation.
+ * Used in the CriWare.CriAtomExPlayer::SetPanType .
+ *
+ * + */ + public enum PanType { + Unknown = -1, /**< Unknown panning type */ + Pan3d = 0, /**< Calculates the localization using Panning 3D */ + Pos3d, /**< Calculates the localization with the 3D Positioning */ + Auto, /**< + * Calculates the localization based on the 3D Positioning when the 3D sound source/3D lister is + * set to the AtomExPlayer, or on the pan 3D if not set. + */ + } + + /** + * Voice control method + * + * A data type used to specify the Voice control method for the sound played by the AtomExPlayer.
+ * Used in the CriWare.CriAtomExPlayer::SetVoiceControlMethod .
+ *
+ * + */ + public enum VoiceControlMethod { + PreferLast = 0, /**< Last-note priority */ + PreferFirst, /**< First-note priority */ + } + + /** + * Parameter ID + * + * The ID for specifying the parameter.
+ * Used in functions such as CriWare.CriAtomExPlayer::GetParameterFloat32 .
+ *
+ * + * + * + */ + public enum Parameter { + Volume = 0, /**< Volume */ + Pitch = 1, /**< Pitch */ + Pan3dAngle = 2, /**< Panning 3D angle */ + Pan3dDistance = 3, /**< Panning 3D distance */ + Pan3dVolume = 4, /**< Panning 3D volume */ + BusSendLevel0 = 9, /**< Bus Send Level 0 */ + BusSendLevel1 = 10, /**< Bus Send Level 1 */ + BusSendLevel2 = 11, /**< Bus Send Level 2 */ + BusSendLevel3 = 12, /**< Bus Send Level 3 */ + BusSendLevel4 = 13, /**< Bus Send Level 4 */ + BusSendLevel5 = 14, /**< Bus Send Level 5 */ + BusSendLevel6 = 15, /**< Bus Send Level 6 */ + BusSendLevel7 = 16, /**< Bus Send Level 7 */ + BandPassFilterCofLow = 17, /**< Low cutoff frequency of the BandPass Filter */ + BandPassFilterCofHigh = 18, /**< High cutoff frequency of the BandPass Filter */ + BiquadFilterType = 19, /**< Filter type of the Biquad Filter */ + BiquadFilterFreq = 20, /**< Biquad Filter frequency */ + BiquadFIlterQ = 21, /**< Q value of the Biquad Filter */ + BiquadFilterGain = 22, /**< Biquad Filter gain */ + EnvelopeAttackTime = 23, /**< Envelope Attack Time */ + EnvelopeHoldTime = 24, /**< Envelope hold time */ + EnvelopeDecayTime = 25, /**< Envelope Decay Time */ + EnvelopeReleaseTime = 26, /**< Envelope release time */ + EnvelopeSustainLevel = 27, /**< Envelope sustain level */ + StartTime = 28, /**< Playback start position */ + Priority = 31, /**< Voice Priority */ + } + + /** + * Speaker ID + * + * An ID for specifying the speaker that outputs sound.
+ * Used in the CriWare.CriAtomExPlayer::SetSendLevel .
+ *
+ * + */ + public enum Speaker { + FrontLeft = 0, /**< Front left speaker */ + FrontRight = 1, /**< Front right speaker */ + FrontCenter = 2, /**< Front center speaker */ + LowFrequency = 3, /**< LFE (≒ subwoofer) */ + SurroundLeft = 4, /**< Surround left speaker */ + SurroundRight = 5, /**< Surround right speaker */ + SurroundBackLeft = 6, /**< Surround back left speaker */ + SurroundBackRight = 7, /**< Surround back right speaker */ + } + + /** + * Format type + * + * A data type used to specify the sound format to be played by the AtomExPlayer.
+ * Used in the CriWare.CriAtomExPlayer::SetFormat .
+ *
+ * + */ + public enum Format : uint { + ADX = 0x00000001, /**< ADX */ + HCA = 0x00000003, /**< HCA */ + HCA_MX = 0x00000004, /**< HCA-MX */ + WAVE = 0x00000005, /**< Wave */ + RAW_PCM = 0x00000006, /**< RawPCM */ + } + + private enum SpeakerSystem : System.UInt32 { + Surround_5_1 = 0, + Surround_7_1 = 1, + } + + /** + * Output speaker angle (5.1ch) + * + * Sets the angle (arrangement) of the output speakers used
+ * when calculating Pan3D or 3D Positioning for virtual speakers.
+ *
+ * + * + */ + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + public struct SpeakerAngles6ch { + public float frontLeft; /**< Front left speaker */ + public float frontRight; /**< Front right speaker */ + public float frontCenter; /**< Front center speaker */ + public float lowFrequency; /**< LFE (≒ subwoofer) */ + public float surroundLeft; /**< Surround left speaker */ + public float surroundRight; /**< Surround right speaker */ + public static SpeakerAngles6ch Default(){ + return new SpeakerAngles6ch + { + frontLeft = -30.0f, + frontRight = 30.0f, + frontCenter = 0.0f, + lowFrequency = 0.0f, + surroundLeft = -120.0f, + surroundRight = 120.0f, + }; + } + } + + /** + * Output speaker angle (7.1ch) + * + * Sets the angle (arrangement) of the output speakers used
+ * when calculating Pan3D or 3D Positioning for virtual speakers.
+ *
+ * + * + */ + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + public struct SpeakerAngles8ch { + public float frontLeft; /**< Front left speaker */ + public float frontRight; /**< Front right speaker */ + public float frontCenter; /**< Front center speaker */ + public float lowFrequency; /**< LFE (≒ subwoofer) */ + public float surroundLeft; /**< Surround left speaker */ + public float surroundRight; /**< Surround right speaker */ + public float surroundBackLeft; /**< Surround back left speaker */ + public float surroundBackRight; /**< Surround back right speaker */ + public static SpeakerAngles8ch Default() { + return new SpeakerAngles8ch + { + frontLeft = -30.0f, + frontRight = 30.0f, + frontCenter = 0.0f, + lowFrequency = 0.0f, + surroundLeft = -110.0f, + surroundRight = 110.0f, + surroundBackLeft = -150.0f, + surroundBackRight = 150.0f, + }; + } + } + + /** + * Speaker angle setting (5.1ch) + * Output speaker angle + * + * Sets the angle (arrangement) of the output speakers used when calculating Pan 3D or 3D Positioning.
+ * Set the angle between -180 degrees and 180 degrees with the forward direction as 0 degrees.
+ * frontLeftとfrontRightの位置を入れ替えるような設定をした場合、意図しない挙動になる可能性があります。 + * Changing the lowFrequency angle does not change the Pan3D or 3D Positioning calculation results.
+ * The angle is set independently for each speaker system.
+ *
+ */ + public static void SetSpeakerAngle(SpeakerAngles6ch speakerAngle) { + criAtomEx_SetSpeakerAngleArray(SpeakerSystem.Surround_5_1, ref speakerAngle); + } + + /** + * Speaker angle setting (7.1ch) + * Output speaker angle + * + * Sets the angle (arrangement) of the output speakers used when calculating Pan 3D or 3D Positioning.
+ * Set the angle between -180 degrees and 180 degrees with the forward direction as 0 degrees.
+ * frontLeftとfrontRightの位置を入れ替えるような設定をした場合、意図しない挙動になる可能性があります。 + * Changing the lowFrequency angle does not change the Pan3D or 3D Positioning calculation results.
+ * The angle is set independently for each speaker system.
+ *
+ */ + public static void SetSpeakerAngle(SpeakerAngles8ch speakerAngle) { + criAtomEx_SetSpeakerAngleArray(SpeakerSystem.Surround_7_1, ref speakerAngle); + } + + /** + * Virtual speaker angle setting (5.1ch) + * Output speaker angle + * + * Sets the angle (arrangement) of the output speakers used
+ * when calculating Pan3D or 3D Positioning for virtual speakers.
+ * The setting in this function will not be applied to the Pan3D or 3D Positioning calculations
+ * unless the virtual speaker setting is enabled
+ * by calling the CriWare.CriAtomEx::ControlVirtualSpeakerSetting function.
+ *
+ */ + public static void SetVirtualSpeakerAngle(SpeakerAngles6ch speakerAngle) { + criAtomEx_SetVirtualSpeakerAngleArray(SpeakerSystem.Surround_5_1, ref speakerAngle); + } + + /** + * Virtual speaker angle setting (7.1ch) + * Output speaker angle + * + * Sets the angle (arrangement) of the output speakers used
+ * when calculating Pan3D or 3D Positioning for virtual speakers.
+ * The setting in this function will not be applied to the Pan3D or 3D Positioning calculations
+ * unless the virtual speaker setting is enabled
+ * by calling the CriWare.CriAtomEx::ControlVirtualSpeakerSetting function.
+ *
+ */ + public static void SetVirtualSpeakerAngle(SpeakerAngles8ch speakerAngle) { + criAtomEx_SetVirtualSpeakerAngleArray(SpeakerSystem.Surround_7_1, ref speakerAngle); + } + + /** + * Virtual speaker setting ON / OFF + * Switch (False = disable, True = enable) + * + * Turn On/Off the function that uses the virtual speaker settings when calculating Pan3D or 3D Positioning.
+ * When enabled, multi-channel sounds will be played from the virtual speaker angles
+ * set by the CriWare.CriAtomEx::SetVirtualSpeakerAngle function.
+ * The default state is "disabled".
+ * Also, if any voice is set to "enabled" during playback, the change will not be immediately reflected in the Pan3D or 3D Positioning calculations. + * The change will be applied from the playback of the next Voice.
+ *
+ */ + public static void ControlVirtualSpeakerSetting(bool sw) { + criAtomEx_ControlVirtualSpeakerSetting(sw); + } + + /** + * Audio data format information + * + * Audio data format information.
+ *
+ * + */ + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + public struct FormatInfo { + public Format format; /**< Format type */ + public int samplingRate; /**< Sampling frequency */ + public long numSamples; /**< Total number of samples */ + public long loopOffset; /**< Loop start sample */ + public long loopLength; /**< The number samples in the loop section */ + public int numChannels; /**< The number of channels */ + public uint reserved; /**< Reserved area */ + } + + /** + * A structure for getting the AISAC control information + * + * A structure for getting the AISAC control information.
+ * Passed to the CriWare.CriAtomExAcb::GetUsableAisacControl function as an argument.
+ *
+ * + */ + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + public struct AisacControlInfo { + [MarshalAs(UnmanagedType.LPStr)] + public readonly string name; /**< AISAC control name */ + public AisacControlId id; /**< AISAC control ID */ + + public AisacControlInfo(byte[] data, int startIndex) + { + if (IntPtr.Size == 4) { + this.name = Marshal.PtrToStringAnsi(new IntPtr(BitConverter.ToInt32(data, startIndex + 0))); + this.id = BitConverter.ToUInt32(data, startIndex + 4); + } else { + this.name = Marshal.PtrToStringAnsi(new IntPtr(BitConverter.ToInt64(data, startIndex + 0))); + this.id = BitConverter.ToUInt32(data, startIndex + 8); + } + } + } + + /** + * Gets the method used to calculate the random coordinates of a 3D sound source + * + * This is the definition of the method used to calculate the random coordinates of a 3D sound source.
+ *
+ * + */ + public enum Randomize3dCalcType : int + { + None = -1, /**< No settings */ + Rectangle = 0, /**< Rectangle */ + Cuboid = 1, /**< Cuboid */ + Circle = 2, /**< Circle */ + Cylinder = 3, /**< Cylinder */ + Sphere = 4, /**< Sphere */ + List = 6 /**< List of coordinates */ + } + + /** + * Definition of the parameters used to calculate coordinates for the randomization of the position of 3D sound sources + * + * Definition of the parameters that determine the calculation of a random position (i.e., shape indicating the coordinates space).
+ *
+ * + * + * + */ + public enum Randomize3dParamType + { + None, /**< Unused */ + Width, /**< Width */ + Depth, /**< Depth */ + Height, /**< Height */ + Radius /**< Radius */ + } + + static public readonly Dictionary randomize3dParamTable = new Dictionary() + { + { Randomize3dCalcType.None, new Randomize3dParamType[]{ Randomize3dParamType.None, Randomize3dParamType.None, Randomize3dParamType.None } }, + { Randomize3dCalcType.Rectangle, new Randomize3dParamType[]{ Randomize3dParamType.Width, Randomize3dParamType.Depth, Randomize3dParamType.None } }, + { Randomize3dCalcType.Cuboid, new Randomize3dParamType[]{ Randomize3dParamType.Width, Randomize3dParamType.Depth, Randomize3dParamType.Height } }, + { Randomize3dCalcType.Circle, new Randomize3dParamType[]{ Randomize3dParamType.Radius, Randomize3dParamType.None, Randomize3dParamType.None } }, + { Randomize3dCalcType.Cylinder, new Randomize3dParamType[]{ Randomize3dParamType.Radius, Randomize3dParamType.Height, Randomize3dParamType.None } }, + { Randomize3dCalcType.Sphere, new Randomize3dParamType[]{ Randomize3dParamType.Radius, Randomize3dParamType.None, Randomize3dParamType.None } }, + { Randomize3dCalcType.List, new Randomize3dParamType[]{ Randomize3dParamType.None, Randomize3dParamType.None, Randomize3dParamType.None } }, + }; + + /** + * Config structure used to randomize the positions of the 3D sound sources. + * + * This is the structure that contains the settings related to the randomization of the 3D sound source's position.
+ *
+ * + */ + [Serializable, StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + public struct Randomize3dConfig + { + /* static */ + public const int NumOfCalcParams = 3; + + /* fields */ + [UnityEngine.SerializeField] + private bool followsOriginalSource; /**< Whether to follow the position and orientation of the 3D sound source */ + [UnityEngine.SerializeField] + private Randomize3dCalcType calculationType; /**< Shape (calculation method of coordinates) */ + [UnityEngine.SerializeField, MarshalAs(UnmanagedType.ByValArray, SizeConst = NumOfCalcParams)] + private float[] calculationParameters; /**< Various parameters for the shape (coordinates calculation method) */ + + /* properties */ + /** Returns whether the position and orientation of the 3D sound source must be followed (read only) */ + public bool FollowsOriginalSource { get { return followsOriginalSource; } } + /** Gets the shape used for 3D sound source randomization (read only) */ + public Randomize3dCalcType CalculationType { get { return calculationType; } } + /** Gets Parameter 1 related to the shape used for 3D sound source randomization (read only) */ + public float CalculationParameter1 { get { return calculationParameters[0]; } } + /** Gets Parameter 2 related to the shape used for 3D sound source randomization (read only) */ + public float CalculationParameter2 { get { return calculationParameters[1]; } } + /** Gets Parameter 3 related to the shape used for 3D sound source randomization (read only) */ + public float CalculationParameter3 { get { return calculationParameters[2]; } } + + internal Randomize3dConfig(byte[] data, int startIndex) + { + this.followsOriginalSource = BitConverter.ToInt32(data, startIndex + 0) != 0; + this.calculationType = (Randomize3dCalcType)BitConverter.ToInt32(data, startIndex + 4); + this.calculationParameters = new float[NumOfCalcParams]; + for (int i = 0; i < NumOfCalcParams; ++i) { + calculationParameters[i] = BitConverter.ToSingle(data, startIndex + 8 + (4 * i)); + } + } + + /** Initializes the settings related to 3D sound source position randomization */ + public Randomize3dConfig(bool followsOriginalSource, Randomize3dCalcType calculationType, float param1 = 0, float param2 = 0, float param3 = 0) + { + this.followsOriginalSource = followsOriginalSource; + this.calculationType = calculationType; + this.calculationParameters = new float[NumOfCalcParams]; + this.calculationParameters[0] = param1; + this.calculationParameters[1] = param2; + this.calculationParameters[2] = param3; + } + + public Randomize3dConfig(int dummy) /* for initiating */ + { + followsOriginalSource = false; + calculationType = Randomize3dCalcType.Rectangle; + this.calculationParameters = new float[NumOfCalcParams]; + this.ClearCalcParams(); + } + + /** Sets all parameters to the specified values. Sets all parameters to 0 if no argument is passed */ + public void ClearCalcParams(float initVal = 0f) + { + for (int i = 0; i < NumOfCalcParams; ++i) { + calculationParameters[i] = initVal; + } + } + + /** Gets the value of a parameter by specifying the type */ + public bool GetParamByType(Randomize3dParamType paramType, ref float paramVal) + { + int index = Array.IndexOf(randomize3dParamTable[calculationType], paramType); + if (index < 0) { + UnityEngine.Debug.LogWarningFormat("[CRIWARE] Parameter {0} not available for 3d randomize calculation type {1}", paramType.ToString(), calculationType.ToString()); + return false; + } + paramVal = calculationParameters[index]; + return true; + } + + /** Sets the parameter by specifying the type */ + public bool SetParamByType(Randomize3dParamType paramType, float paramVal) + { + int index = Array.IndexOf(randomize3dParamTable[calculationType], paramType); + if (index < 0) { + UnityEngine.Debug.LogWarningFormat("[CRIWARE] Parameter {0} not available for 3d randomize calculation type {1}", paramType.ToString(), calculationType.ToString()); + return false; + } + calculationParameters[index] = paramVal; + return true; + } + } + + /** + * The 3D information of the Cue + * + * Waveform information is the 3D details of the Cue.
+ *
+ * + */ + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + public struct CuePos3dInfo + { + public float coneInsideAngle; /**< Cone internal angle */ + public float coneOutsideAngle; /**< Cone external angle */ + public float minAttenuationDistance; /**< Minimum attenuation distance */ + public float maxAttenuationDistance; /**< Maximum attenuation distance */ + public float sourceRadius; /**< Zero distance InteriorPan applicable distance */ + public float interiorDistance; /**< InteriorPan application boundary distance */ + public float dopplerFactor; /**< Doppler coefficient */ + public Randomize3dConfig randomPos; /**< Configuration information of the 3D sound source randomization */ + public AisacControlId distanceAisacControl; /**< Distance attenuation AISAC control */ + public AisacControlId listenerBaseAngleAisacControl; /**< Listener reference angle AISAC control */ + public AisacControlId sourceBaseAngleAisacControl; /**< Sound source reference angle AISAC control */ + public AisacControlId listenerBaseElevationAisacControl; /**< Listener reference elevation AISAC control */ + public AisacControlId sourceBaseElevationAisacControl; /**< Sound source reference elevation AISAC control */ + + public CuePos3dInfo(byte[] data, int startIndex) + { + this.coneInsideAngle = BitConverter.ToSingle(data, startIndex + 0); + this.coneOutsideAngle = BitConverter.ToSingle(data, startIndex + 4); + this.minAttenuationDistance = BitConverter.ToSingle(data, startIndex + 8); + this.maxAttenuationDistance = BitConverter.ToSingle(data, startIndex + 12); + this.sourceRadius = BitConverter.ToSingle(data, startIndex + 16); + this.interiorDistance = BitConverter.ToSingle(data, startIndex + 20); + this.dopplerFactor = BitConverter.ToSingle(data, startIndex + 24); + this.randomPos = new Randomize3dConfig(data, startIndex + 28); + this.distanceAisacControl = BitConverter.ToUInt32(data, startIndex + 48); + this.listenerBaseAngleAisacControl = BitConverter.ToUInt32(data, startIndex + 52); + this.sourceBaseAngleAisacControl = BitConverter.ToUInt32(data, startIndex + 56); + this.listenerBaseElevationAisacControl = BitConverter.ToUInt32(data, startIndex + 60); + this.sourceBaseElevationAisacControl = BitConverter.ToUInt32(data, startIndex + 64); + } + } + + /** + * Structure for acquiring game variable information + * + * This is the structure used to get information on a game variable.
+ * Pass it to the CriWare.CriAtomEx::GetGameVariableInfo function as an argument.
+ *
+ * + */ + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + public struct GameVariableInfo + { + [MarshalAs(UnmanagedType.LPStr)] + public readonly string name; /**< Game variable name */ + public uint id; /**< Game variable ID */ + public float gameValue; /**< Game variable value */ + + public GameVariableInfo(byte[] data, int startIndex) + { + if (IntPtr.Size == 4) { + this.name = Marshal.PtrToStringAnsi(new IntPtr(BitConverter.ToInt32(data, startIndex + 0))); + this.id = BitConverter.ToUInt32(data, startIndex + 4); + this.gameValue = BitConverter.ToSingle(data, startIndex + 8); + } else { + this.name = Marshal.PtrToStringAnsi(new IntPtr(BitConverter.ToInt64(data, startIndex + 0))); + this.id = BitConverter.ToUInt32(data, startIndex + 8); + this.gameValue = BitConverter.ToSingle(data, startIndex + 12); + } + } + + public GameVariableInfo(string name, uint id, float gameValue) + { + this.name = name; + this.id = id; + this.gameValue = gameValue; + } + } + + /** + * Cue type + * + */ + public enum CueType + { + Polyphonic, /**< Polyphonic */ + Sequential, /**< Sequential */ + Shuffle, /**< Shuffle playback */ + Random, /**< Random */ + RandomNoRepeat, /**< Random discontinued (randomly play sounds other than the one played previously) */ + SwitchGameVariable, /**< Switch playback (switches tracks to be played by referencing the game variable) */ + ComboSequential, /**< Combo Sequential (Sequential when consecutive combo is successful within the "combo time", and returns to "combo loopback" point when the end is reached) */ + SwitchSelector, /**< Selector */ + TrackTransitionBySelector, + } + + /** + * Cue information + * + * Detailed information of the Cue.
+ *
+ * + */ + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + public struct CueInfo + { + public int id; /**< Cue ID */ + public CueType type; /**< Type */ + [MarshalAs(UnmanagedType.LPStr)] + public readonly string name; /**< Cue name */ + [MarshalAs(UnmanagedType.LPStr)] + public readonly string userData; /**< User data */ + public long length; /**< Length (msec) */ + + /* 最大再生毎カテゴリ参照数:CRIATOMEXCATEGORY_MAX_CATEGORIES_PER_PLAYBACKは16 */ + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] + public ushort[] categories; /**< Category index */ + + public short numLimits; /**< Cue limit */ + public ushort numBlocks; /**< Number of Blocks */ + public ushort numTracks; /**< The number of tracks */ + public ushort numRelatedWaveForms; /**< The number of related waveforms */ + public byte priority; /**< Category Cue Priority */ + public byte headerVisibility; /**< Header publication flag */ + public byte ignore_player_parameter; /**< Player parameter invalidation flag */ + public byte probability; /**< Playback probability */ + public PanType panType; /**< Panning type */ + public CuePos3dInfo pos3dInfo; /**< 3D information */ + public GameVariableInfo gameVariableInfo; /**< Game variables */ + + public CueInfo(byte[] data, int startIndex) + { + if (IntPtr.Size == 4) { + this.id = BitConverter.ToInt32(data, startIndex + 0); + this.type = (CueType)BitConverter.ToInt32(data, startIndex + 4); + this.name = Marshal.PtrToStringAnsi(new IntPtr(BitConverter.ToInt32(data, startIndex + 8))); + this.userData = Marshal.PtrToStringAnsi(new IntPtr(BitConverter.ToInt32(data, startIndex + 12))); + this.length = BitConverter.ToInt64(data, startIndex + 16); + this.categories = new ushort[16]; + for (int i = 0; i < 16; ++i) { + categories[i] = BitConverter.ToUInt16(data, startIndex + 24 + (2 * i)); + } + this.numLimits = BitConverter.ToInt16(data, startIndex + 56); + this.numBlocks = BitConverter.ToUInt16(data, startIndex + 58); + this.numTracks = BitConverter.ToUInt16(data, startIndex + 60); + this.numRelatedWaveForms = BitConverter.ToUInt16(data, startIndex + 62); + this.priority = data[startIndex + 64]; + this.headerVisibility = data[startIndex + 65]; + this.ignore_player_parameter = data[startIndex + 66]; + this.probability = data[startIndex + 67]; + this.panType = (PanType)BitConverter.ToInt32(data, startIndex + 68); + this.pos3dInfo = new CuePos3dInfo(data, startIndex + 72); + this.gameVariableInfo = new GameVariableInfo(data, startIndex + 140); + } else { + this.id = BitConverter.ToInt32(data, startIndex + 0); + this.type = (CueType)BitConverter.ToInt32(data, startIndex + 4); + this.name = Marshal.PtrToStringAnsi(new IntPtr(BitConverter.ToInt64(data, startIndex + 8))); + this.userData = Marshal.PtrToStringAnsi(new IntPtr(BitConverter.ToInt64(data, startIndex + 16))); + this.length = BitConverter.ToInt64(data, startIndex + 24); + this.categories = new ushort[16]; + for (int i = 0; i < 16; ++i) { + categories[i] = BitConverter.ToUInt16(data, startIndex + 32 + (2 * i)); + } + this.numLimits = BitConverter.ToInt16(data, startIndex + 64); + this.numBlocks = BitConverter.ToUInt16(data, startIndex + 66); + this.numTracks = BitConverter.ToUInt16(data, startIndex + 68); + this.numRelatedWaveForms = BitConverter.ToUInt16(data, startIndex + 70); + this.priority = data[startIndex + 72]; + this.headerVisibility = data[startIndex + 73]; + this.ignore_player_parameter = data[startIndex + 74]; + this.probability = data[startIndex + 75]; + this.panType = (PanType)BitConverter.ToInt32(data, startIndex + 76); + this.pos3dInfo = new CuePos3dInfo(data, startIndex + 80); + /* padded by 4 bytes */ + this.gameVariableInfo = new GameVariableInfo(data, startIndex + 152); + } + } + } + + /** + * Sound waveform information + * + * Waveform information is a detailed information about the sound waveform played from each Cue.
+ *
+ * + */ + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + public struct WaveformInfo + { + public int waveId; /**< Waveform data ID */ + public uint format; /**< Format type */ + public int samplingRate; /**< Sampling frequency */ + public int numChannels; /**< The number of channels */ + public long numSamples; /**< Total number of samples */ + public bool streamingFlag; /**< Streaming flag */ + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)] + public uint[] reserved; /**< Reserved area */ + + public WaveformInfo(byte[] data, int startIndex) + { + this.waveId = BitConverter.ToInt32(data, startIndex + 0); + this.format = BitConverter.ToUInt32(data, startIndex + 4); + this.samplingRate = BitConverter.ToInt32(data, startIndex + 8); + this.numChannels = BitConverter.ToInt32(data, startIndex + 12); + this.numSamples = BitConverter.ToInt64(data, startIndex + 16); + this.streamingFlag = BitConverter.ToInt32(data, startIndex + 24) != 0; + this.reserved = new uint[1]; + for (int i = 0; i < 1; ++i) { + reserved[i] = BitConverter.ToUInt32(data, startIndex + 28 + (4 * i)); + } + } + } + + /** + * A structure for getting the AISAC information + * + * A structure for getting the AISAC information.
+ *
+ * + * + * + */ + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + public struct AisacInfo + { + [MarshalAs(UnmanagedType.LPStr)] + public readonly string name; /**< AISAC name */ + public bool defaultControlFlag; /**< Whether the default control value is set */ + public float defaultControlValue; /**< Default AISAC control value */ + public AisacControlId controlId; /**< ControlId */ + [MarshalAs(UnmanagedType.LPStr)] + public readonly string controlName; /**< ControlName */ + + public AisacInfo(byte[] data, int startIndex) + { + if (IntPtr.Size == 4) { + this.name = Marshal.PtrToStringAnsi(new IntPtr(BitConverter.ToInt32(data, startIndex + 0))); + this.defaultControlFlag = BitConverter.ToInt32(data, startIndex + 4) != 0; + this.defaultControlValue = BitConverter.ToSingle(data, startIndex + 8); + this.controlId = BitConverter.ToUInt32(data, startIndex + 12); + this.controlName = Marshal.PtrToStringAnsi(new IntPtr(BitConverter.ToInt32(data, startIndex + 16))); + } else { + this.name = Marshal.PtrToStringAnsi(new IntPtr(BitConverter.ToInt64(data, startIndex + 0))); + this.defaultControlFlag = BitConverter.ToInt32(data, startIndex + 8) != 0; + this.defaultControlValue = BitConverter.ToSingle(data, startIndex + 12); + this.controlId = BitConverter.ToUInt32(data, startIndex + 16); + this.controlName = Marshal.PtrToStringAnsi(new IntPtr(BitConverter.ToInt64(data, startIndex + 20))); + } + } + } + + /** + * Performance information + * + * A structure for getting the performance information.
+ * Used in the CriWare.CriAtomEx::GetPerformanceInfo .
+ *
+ * + */ + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + public struct PerformanceInfo + { + public uint serverProcessCount; /**< The number of server process executions */ + public uint lastServerTime; /**< Last measured server process time (in microseconds) */ + public uint maxServerTime; /**< Maximum server process time (in microseconds) */ + public uint averageServerTime; /**< Average server process time (in microseconds) */ + public uint lastServerInterval; /**< Last measured server process execution interval (in microseconds) */ + public uint maxServerInterval; /**< Maximum server process execution interval (in microseconds) */ + public uint averageServerInterval; /**< Average server process execution interval (in microseconds) */ + } + + /** + * Usage of various resources + * + * A structure indicating the usage status of various resources. + * + */ + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + public struct ResourceUsage + { + public uint useCount; /**< Current usage of the target resource */ + public uint limit; /**< Limit for target resources */ + } + + /** + * 3D vector structure + * + * A structure that represents the position, direction, etc. in 3D space. + * + */ + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + public struct NativeVector + { + public float x; + public float y; + public float z; + + public NativeVector(float x, float y, float z) { + this.x = x; + this.y = y; + this.z = z; + } + + public NativeVector(UnityEngine.Vector3 vector) { + this.x = vector.x; + this.y = vector.y; + this.z = vector.z; + } + } + + /** + * Information about the Cue Link callback + * + * A structure for retrieving information from Cue Link callbacks. + * + * + */ + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + public struct CueLinkInfo + { + public IntPtr nativePlayerHn; /**< Player handle */ + public uint basePlaybackId; /**< Playback ID of the link's source */ + public uint targetPlaybackId; /**< Playback ID of the link's target */ + public int cueLinkType; /**< Type of the Cue Link callback(0:static, 1:dynamic) */ + } + + /** + * Cue Link callback + * Information about the Cue Link callback + * + * This is the delegate type for Cue Link callbacks.
+ *
+ * + */ + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public delegate void CueLinkCbFunc(ref CueLinkInfo info); + + /** + * Registering Cue Link callbacks + * + * Registers a callback function that receives Cue Link information when processing a Cue Link + * during the Cue's playback.
+ * The registered callback function is executed when the application's main thread updates + * right after the callback event is processed.
+ *
+ */ + public static event CueLinkCbFunc OnCueLinkCallback { + add { + CriAtom.OnCueLinkCallback += value; + } + remove { + CriAtom.OnCueLinkCallback -= value; + } + } + + /** + * Registers the ACF file + * Binder + * File path of the ACF file + * + * Loads the ACF file and incorporates it into the library.
+ *
+ * + */ + public static void RegisterAcf(CriFsBinder binder, string acfPath) + { + IntPtr binderHandle = (binder != null) ? binder.nativeHandle : IntPtr.Zero; + criAtomEx_RegisterAcfFile(binderHandle, acfPath, IntPtr.Zero, 0); + } + + /** + * Registers the ACF data + * ACF data + * ACF data size + * + * Loads the ACF data placed on the memory and captures it to the library.
+ * The buffer address of the data to be passed as an argument should be fixed beforehand + * by the application so that it is not moved to the garbage collector.
+ * Also, release the memory lock after unregistering the ACF file or after finalizing the library.
+ *
+ * + */ + public static void RegisterAcf(IntPtr acfData, int dataSize) + { + criAtomEx_RegisterAcfData(acfData, dataSize, IntPtr.Zero, 0); + } + + /** + * \deprecated + * This is a deprecated API that will be removed. + * Please consider using CriAtomEx.RegisterAcf(IntPtr) instead. + */ + [Obsolete("Use RegisterAcf(IntPtr) instead")] + public static void RegisterAcf(byte[] acfData) { + criAtomEx_RegisterAcfData(acfData, acfData.Length, IntPtr.Zero, 0); + } + + /** + * Unregisters the ACF file + * + * Unregisters the ACF file.
+ *
+ * + */ + public static void UnregisterAcf() + { + criAtomEx_UnregisterAcf(); + } + + /** + * Gets the snapshot's name + * + * Gets the current snapshot name. Returns null if none was set.
+ *
+ */ + public static string GetAppliedDspBusSnapshotName() + { + string snapshotName = null; + IntPtr ptr = criAtomEx_GetAppliedDspBusSnapshotName(); + if (ptr == IntPtr.Zero) { + return null; + } + snapshotName = Marshal.PtrToStringAnsi(ptr); + return snapshotName; + } + + /** + * Attaching the DSP bus settings + * Name of the DSP bus setting + * + * Builds a DSP bus from the DSP bus settings and attaches it to the sound renderer.
+ * Before calling this function, you must register the ACF information + * using the CriAtomEx::RegisterAcf function
+ * : + * // ACFファイルの読み込みと登録 + * CriAtomEx.RegisterAcf("Sample.acf"); + * + * // DSPバス設定の適用 + * CriAtomEx.AttachDspBusSetting("DspBusSetting_0"); + * : + * + *
+ * This function is a return-on-complete function.
+ * Calling this function blocks the server processing of the Atom library for a while.
+ * If this function is called during sound playback, problems such as sound interruption may occur, + * so call this function at a timing when load fluctuations is accepted such as when switching scenes.
+ *
+ * + * + */ + public static void AttachDspBusSetting(string settingName) + { + criAtomEx_AttachDspBusSetting(settingName, IntPtr.Zero, 0); + } + + /** + * Detaches the DSP bus settings + * + * Detaches the DSP bus settings.
+ * This function is a return-on-complete function.
+ * Calling this function blocks the server processing of the Atom library for a while.
+ * If this function is called during sound playback, problems such as sound interruption may occur, + * so call this function at a timing when load fluctuations is accepted such as when switching scenes.
+ *
+ * + */ + public static void DetachDspBusSetting() + { + criAtomEx_DetachDspBusSetting(); + } + + /** + * Applies the DSP bus snapshot + * DSP bus snapshot name + * The time (in milliseconds) until the snapshot is fully reflected + * + * Applies a DSP bus snapshot.
+ * Calling this function changes the snapshot parameters. + * It takes time_ms milliseconds for the change to complete.
+ *
+ */ + public static void ApplyDspBusSnapshot(string snapshot_name, int time_ms) + { + criAtomEx_ApplyDspBusSnapshot(snapshot_name, time_ms); + } + + /** + * Gets the total number of game variables + * The total number of game variables + * + * Gets the total number of game variables registered in the ACF file.
+ * It is necessary to register the ACF file before calling this function.
+ * If the ACF file is not registered, -1 is returned.
+ *
+ */ + public static int GetNumGameVariables() + { + return criAtomEx_GetNumGameVariables(); + } + + /** + * Gets game variable information (index specified) + * Game variable index + * Game variable information + * Whether the information could be obtained + * + * Gets the game variable information from the game variable index.
+ * Returns False if there is no game variable with the specified index.
+ * It is necessary to register the ACF file before calling this function.
+ *
+ */ + public static bool GetGameVariableInfo(ushort index, out GameVariableInfo info) + { + using (var mem = new CriStructMemory()) { + bool result = criAtomEx_GetGameVariableInfo(index, mem.ptr); + info = new GameVariableInfo(mem.bytes, 0); + return result; + } + } + + /** + * Gets game variables + * Game variable ID + * Game variable value + * + * Gets the value of the game variable registered in the ACF file.
+ * It is necessary to register the ACF file before calling this function.
+ *
+ */ + public static float GetGameVariable(uint game_variable_id) + { + return criAtomEx_GetGameVariableById(game_variable_id); + } + + /** + * Gets game variables + * Game variable name + * Game variable value + * + * Gets the value of the game variable registered in the ACF file.
+ * It is necessary to register the ACF file before calling this function.
+ *
+ */ + public static float GetGameVariable(string game_variable_name) + { + return criAtomEx_GetGameVariableByName(game_variable_name); + } + + /** + * Sets game variables + * Game variable ID + * Game variable value + * + * Sets the value to the game variable registered in the ACF file.
+ * Acceptable values are between 0.0f and 1.0f.
+ * It is necessary to register the ACF file before calling this function.
+ *
+ */ + public static void SetGameVariable(uint game_variable_id, float game_variable_value) + { + criAtomEx_SetGameVariableById(game_variable_id, game_variable_value); + } + + /** + * Sets game variables + * Game variable name + * Game variable value + * + * Sets the value to the game variable registered in the ACF file.
+ * Acceptable values are between 0.0f and 1.0f.
+ * It is necessary to register the ACF file before calling this function.
+ *
+ */ + public static void SetGameVariable(string game_variable_name, float game_variable_value) + { + criAtomEx_SetGameVariableByName(game_variable_name, game_variable_value); + } + + /** + * Sets the random number seed + * Random number seed + * + * Sets the random number seed in the pseudo random number generator shared in entire CRI Atom library.
+ * By setting the random number seed, it is possible to add reproducibility to various random playback processes.
+ * If you want reproducibility in each AtomExPlayer, use the CriWare.CriAtomExPlayer::SetRandomSeed function. + *
+ * If you do not need reproducibility and want to change the random number seed for each execution, + * use the CriWare.CriAtomConfig::useRandomSeedWithTime property instead of this function. + *
+ * This function must be called before generating CriWare.CriAtomSource or CriWare.CriAtomExPlayer . + * Those created before setting the random number seed are not affected. + *
+ * + */ + public static void SetRandomSeed(uint seed) + { + criAtomEx_SetRandomSeed(seed); + } + + /** + * Resets the performance monitor + * + * Discards the measurement results up to now.
+ * The performance monitor starts collecting performance information immediately after + * initializing the library and accumulates the measurement results.
+ * If you do not want to include the previous measurement result in the future measurement, + * you need to call this function to discard the accumulated measurement.
+ *
+ * + */ + public static void ResetPerformanceMonitor() + { + criAtom_ResetPerformanceMonitor(); + } + + /** + * Gets the performance information + * + * Gets the performance information.
+ *
+ * + * + */ + public static void GetPerformanceInfo(out PerformanceInfo info) + { + criAtom_GetPerformanceInfo(out info); + } + + /** + * Sets the global reference label for a selector + * Selector index + * Label index + * + * Set the globally referenced label for the selector registered in the ACF file.
+ * It is necessary to register the ACF file before calling this function.
+ *
+ * + */ + public static void SetGlobalLabelToSelectorByIndex(ushort selector_index, ushort label_index) + { + criAtomExAcf_SetGlobalLabelToSelectorByIndex(selector_index, label_index); + } + + /** + * Sets the global reference label for a selector + * Selector name + * Label name + * + * Set the globally referenced label for the selector registered in the ACF file.
+ * It is necessary to register the ACF file before calling this function.
+ *
+ * + */ + public static void SetGlobalLabelToSelectorByName(string selector_name, string label_name) + { + criAtomExAcf_SetGlobalLabelToSelectorByName(selector_name, label_name); + } + + /** + * Prevents interruption to the server process + * + * Prevents the lock of interruption to server processing.
+ * The interruption to the server processing is prevented after this function is called until the CriWare.CriAtomEx::Unlock function is called.
+ * If you want to reliably call multiple APIs in the same audio frame, use this function to prevent interruption + * to the server processing and then call those functions.
+ *
+ * + */ + public static void Lock() + { + criAtomEx_Lock(); + } + + /** + * Allow interruption to the server process + * + * Do not prevent the interruption of the server processing (disable the effect of the CriWare.CriAtomEx::Lock function). + * + * + */ + public static void Unlock() + { + criAtomEx_Unlock(); + } + + /** + * [PC] Output device setting(by device ID) + * Device ID + * + * Sets the ID of the device to be used as Atom's audio output destination. + * + */ + public static void SetOutputAudioDevice_PC(string deviceId) + { +#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN + string audioDevice; + if (string.IsNullOrEmpty(deviceId) || deviceId.Contains("{")) { + audioDevice = deviceId; + } else { + audioDevice = "{0.0.0.00000000}.{" + deviceId + "}"; + } + criAtom_SetDeviceId_WASAPI(SoundRendererType.Native, audioDevice); +#endif + } + + /** + * [PC] Initializing the list of output devices + * + * Initializes the list of devices which can be used as Atom's audio output destination.
+ * After calling this function, the number of devices can be obtained from CriAtomEx::GetNumAudioDevices_PC, + * and the names of the devices from CriAtomEx::GetAudioDeviceName_PC.
+ *
+ * + * + */ + public static bool LoadAudioDeviceList_PC() + { +#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN + return criAtomUnity_LoadAudioDeviceList_PC(); +#else + return false; +#endif + } + + /** + * [PC] Getting the number of the output devices + * Amount of output devices + * + * Gets the number of devices that can be selected as the audio output destination from Atom.
+ * Please call this function after using + * CriAtomEx::LoadAudioDeviceList_PC function to initialize the device list inside the plugin. + * The maximum return value is 32.
+ *
+ * + */ + public static int GetNumAudioDevices_PC() + { +#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN + return criAtomUnity_GetNumAudioDevices_PC(); +#else + return 0; +#endif + } + + /** + * [PC] Getting the output device's name(by index) + * Device index + * Output device's name + * + * Gets the names of devices that can be selected as the audio output destination from Atom.
+ * Please call this function after using + * CriAtomEx::LoadAudioDeviceList_PC function to initialize the device list inside the plugin.
+ *
+ * + */ + public static string GetAudioDeviceName_PC(int index) + { +#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN + IntPtr ptr = criAtomUnity_GetAudioDeviceName_PC(index); + + if (ptr == IntPtr.Zero) { + return null; + } + + string ret = null; + try { + ret = Marshal.PtrToStringAnsi(ptr); + } catch (Exception) { + ret = null; + } + if (string.IsNullOrEmpty(ret)) { + try { + var array = new byte[1024]; + Marshal.Copy(ptr, array, 0, 1024); + var encoding = Encoding.GetEncoding("shift-jis"); + int deviceNameLength = 0; + for (int i = 0; i < array.Length; i++) { + if (array[i] == '\0') { + deviceNameLength = i; + break; + } + } + ret = encoding.GetString(array, 0, deviceNameLength); + } catch (Exception exception) { + if (exception is System.NotSupportedException) { + throw; + } + ret = null; + } + } + return ret; +#else + return null; +#endif + } + + /** + * [PC] Output device setting(by index) + * Device index + * + * Sets the device to be used as Atom's audio output destination.
+ * Please call this function after using + * CriAtomEx::LoadAudioDeviceList_PC function to initialize the device list inside the plugin.
+ *
+ * + */ + public static void SetOutputAudioDevice_PC(int index) + { +#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN + IntPtr id = criAtomUnity_GetAudioDeviceId_PC(index); + criAtom_SetDeviceId_WASAPI(SoundRendererType.Native, id); +#endif + } + + /* @cond excludele */ + /** + * [VITA] Specifies output volume + * + * Specify the final output volume (master volume) of the sound.
+ * The volume value specified in this function is multiplied to all the sounds played by the Atom library.
+ * The default volume is 1.0f.
+ * This function is an API dedicated VITA. + *
+ */ + public static void SetOutputVolume_VITA(float volume) + { + #if !UNITY_EDITOR && UNITY_PSP2 + criAtom_SetOutputVolume_VITA(volume); + #endif + } + + /** + * [VITA] Checks the BGM output right + * + * Checks the BGM output right.
+ * If True, it means that you have a right to output BGM, and that no other application is using the BGM port.
+ * If False, it means that you cannot acquire the BGM output right, and that another application is using the BGM port.
+ *
+ * After checking the BGM output right with this function, request the BGM output right or mute the BGM sound if necessary.
+ * This function is an API dedicated VITA. + *
+ */ + public static bool IsBgmPortAcquired_VITA() + { + #if !UNITY_EDITOR && UNITY_PSP2 + return criAtomUnity_IsBgmPortAcquired_VITA(); + #else + return true; + #endif + } + /* @endcond */ + + /** + * [iOS] Confirms stoppage of sound output + * + * Checks if the sound output is stopped.
+ * If True, the sound output is stopped.
+ * If this function returns True even if the application is not paused, + * the sound output is blocked by a system interrupt etc. that is not detected by the application.
+ * For synchronizing the application with the sound, check the sound output status + * using this function, and add pausing if necessary.
+ * This function is an API dedicated iOS. + *
+ */ + public static bool IsSoundStopped_IOS() + { + #if !UNITY_EDITOR && UNITY_IOS + return criAtomUnity_IsSoundStopped_IOS(); + #else + return false; + #endif + } + + /** + * [iOS] Enables AudioSession Restoration + * Whether to enable the restoration process + * + * Sets whether to automatically restore the audio after interruptions by other applications or the OS.
+ * When the audio output is performed exclusively (i.e. CriAtomConfig.iosOverrideIPodMusic is true), + * this setting will determine whether to resume the audio after interruptions from other applications.
+ * It is enabled by default, which means audio will immediately resume after an interruption.
+ * You can set the argument to false and call this function when you want to temporarily disable the audio restoration, + * when dealing with one of these situations: + * - When you want to support voice input when the user enters information
+ * - When you want to temporarily use a module that offers audio playback, other than CRIWARE (example: video playback by WebView)
+ * Make sure to call this function again with "true" for the argument once you are done, in order to avoid that + * the audio of the application does not resume.
+ * This function is an API dedicated iOS. + *
+ */ + public static void EnableAudioSessionRestoration_IOS(bool flag) + { + #if !UNITY_EDITOR && UNITY_IOS + criAtomUnity_EnableAudioSessionRestoration_IOS(flag); + #endif + } + +#if !UNITY_EDITOR && UNITY_ANDROID + public static SoundRendererType androidDefaultSoundRendererType = SoundRendererType.Default; +#endif + + #region DLL Import + #if !CRIWARE_ENABLE_HEADLESS_MODE + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool criAtomEx_RegisterAcfFile( + IntPtr binder, string path, IntPtr work, int workSize); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomEx_RegisterAcfData( + IntPtr acfData, int acfDataSize, IntPtr work, int workSize); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomEx_RegisterAcfData( + byte[] acfData, int acfDataSize, IntPtr work, int workSize); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomEx_UnregisterAcf(); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomEx_AttachDspBusSetting( + string settingName, IntPtr work, int workSize); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomEx_DetachDspBusSetting(); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomEx_ApplyDspBusSnapshot(string snapshot_name, int time_ms); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern IntPtr criAtomEx_GetAppliedDspBusSnapshotName(); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criAtomEx_GetNumGameVariables(); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool criAtomEx_GetGameVariableInfo(ushort index, IntPtr game_variable_info); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern float criAtomEx_GetGameVariableById(uint game_variable_id); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern float criAtomEx_GetGameVariableByName(string game_variable_name); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomEx_SetGameVariableById(uint game_variable_id, float game_variable_value); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomEx_SetGameVariableByName(string game_variable_name, float game_variable_value); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomEx_SetRandomSeed(uint seed); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomEx_Lock(); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomEx_Unlock(); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtom_ResetPerformanceMonitor(); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtom_GetPerformanceInfo(out PerformanceInfo info); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExAcf_SetGlobalLabelToSelectorByIndex(ushort selector_index, ushort label_index); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExAcf_SetGlobalLabelToSelectorByName(string selector_name, string label_name); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomEx_SetSpeakerAngleArray(SpeakerSystem speaker_system, ref SpeakerAngles6ch angle_array); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomEx_SetSpeakerAngleArray(SpeakerSystem speaker_system, ref SpeakerAngles8ch angle_array); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomEx_SetVirtualSpeakerAngleArray(SpeakerSystem speaker_system, ref SpeakerAngles6ch angle_array); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomEx_SetVirtualSpeakerAngleArray(SpeakerSystem speaker_system, ref SpeakerAngles8ch angle_array); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomEx_ControlVirtualSpeakerSetting(bool sw); + + #if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtom_SetDeviceId_WASAPI(SoundRendererType soundRendererType, [MarshalAs(UnmanagedType.LPWStr)]string deviceId); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtom_SetDeviceId_WASAPI(CriAtomEx.SoundRendererType type, IntPtr deviceId); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool criAtomUnity_LoadAudioDeviceList_PC(); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criAtomUnity_GetNumAudioDevices_PC(); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern IntPtr criAtomUnity_GetAudioDeviceName_PC(int index); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern IntPtr criAtomUnity_GetAudioDeviceId_PC(int index); + #endif + + #if !UNITY_EDITOR && UNITY_PSP2 + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtom_SetOutputVolume_VITA(float volume); + #endif + + #if !UNITY_EDITOR && UNITY_PSP2 + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool criAtomUnity_IsBgmPortAcquired_VITA(); + #endif + + #if !UNITY_EDITOR && UNITY_ANDROID + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + public static extern void criAtom_EnableSlLatencyCheck_ANDROID(bool sw); + #endif + + #if !UNITY_EDITOR && UNITY_ANDROID + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + public static extern int criAtom_GetSlBufferConsumptionLatency_ANDROID(); + #endif + + #if !UNITY_EDITOR && UNITY_IOS + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + public static extern bool criAtomUnity_IsSoundStopped_IOS(); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + public static extern void criAtomUnity_EnableAudioSessionRestoration_IOS(bool flag); + #endif + + #if !UNITY_EDITOR && UNITY_SWITCH + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + public static extern void criAtom_SetServerThreadAffinityMask_SWITCH(ulong mask); + #endif + #else + private static bool criAtomEx_RegisterAcfFile( + IntPtr binder, string path, IntPtr work, int workSize) { return true; } + private static void criAtomEx_RegisterAcfData( + IntPtr acfData, int acfDataSize, IntPtr work, int workSize) { } + private static void criAtomEx_RegisterAcfData( + byte[] acfData, int acfDataSize, IntPtr work, int workSize) { } + private static void criAtomEx_UnregisterAcf() { } + private static void criAtomEx_AttachDspBusSetting( + string settingName, IntPtr work, int workSize) { } + private static void criAtomEx_DetachDspBusSetting() { } + private static void criAtomEx_ApplyDspBusSnapshot(string snapshot_name, int time_ms) { } + private static IntPtr criAtomEx_GetAppliedDspBusSnapshotName() { return IntPtr.Zero; } + private static int criAtomEx_GetNumGameVariables() { return 0; } + private static bool criAtomEx_GetGameVariableInfo(ushort index, IntPtr game_variable_info) { return false; } + private static float criAtomEx_GetGameVariableById(uint game_variable_id) { return 0.0f; } + private static float criAtomEx_GetGameVariableByName(string game_variable_name) { return 0.0f; } + private static void criAtomEx_SetGameVariableById(uint game_variable_id, float game_variable_value) { } + private static void criAtomEx_SetGameVariableByName(string game_variable_name, float game_variable_value) { } + private static void criAtomEx_SetRandomSeed(uint seed) { } + private static void criAtomEx_Lock() { } + private static void criAtomEx_Unlock() { } + private static void criAtom_ResetPerformanceMonitor() { } + private static void criAtom_GetPerformanceInfo(out PerformanceInfo info) { info = new PerformanceInfo(); } + private static void criAtomExAcf_SetGlobalLabelToSelectorByIndex(ushort selector_index, ushort label_index) { } + private static void criAtomExAcf_SetGlobalLabelToSelectorByName(string selector_name, string label_name) { } + private static void criAtomEx_SetSpeakerAngleArray(SpeakerSystem speaker_system, ref SpeakerAngles6ch angle_array) { } + private static void criAtomEx_SetSpeakerAngleArray(SpeakerSystem speaker_system, ref SpeakerAngles8ch angle_array) { } + private static void criAtomEx_SetVirtualSpeakerAngleArray(SpeakerSystem speaker_system, ref SpeakerAngles6ch angle_array) { } + private static void criAtomEx_SetVirtualSpeakerAngleArray(SpeakerSystem speaker_system, ref SpeakerAngles8ch angle_array) { } + private static void criAtomEx_ControlVirtualSpeakerSetting(bool sw) { } + #if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN + private static void criAtom_SetDeviceId_WASAPI(SoundRendererType soundRendererType, string deviceId) { } + private static void criAtom_SetDeviceId_WASAPI(CriAtomEx.SoundRendererType type, IntPtr deviceId) { } + private static bool criAtomUnity_LoadAudioDeviceList_PC() { return false; } + private static int criAtomUnity_GetNumAudioDevices_PC() { return 0; } + private static IntPtr criAtomUnity_GetAudioDeviceName_PC(int index) { return IntPtr.Zero; } + private static IntPtr criAtomUnity_GetAudioDeviceId_PC(int index) { return IntPtr.Zero; } + #endif + #if !UNITY_EDITOR && UNITY_PSP2 + private static void criAtom_SetOutputVolume_VITA(float volume) { } + #endif + #if !UNITY_EDITOR && UNITY_PSP2 + private static bool criAtomUnity_IsBgmPortAcquired_VITA() { return false; } + #endif + #if !UNITY_EDITOR && UNITY_ANDROID + public static void criAtom_EnableSlLatencyCheck_ANDROID(bool sw) { } + #endif + #if !UNITY_EDITOR && UNITY_ANDROID + public static int criAtom_GetSlBufferConsumptionLatency_ANDROID() { return 0; } + #endif + #if !UNITY_EDITOR && UNITY_IOS + public static bool criAtomUnity_IsSoundStopped_IOS() { return false; } + public static void criAtomUnity_EnableAudioSessionRestoration_IOS(bool flag) { } + #endif + #if !UNITY_EDITOR && UNITY_SWITCH + public static void criAtom_SetServerThreadAffinityMask_SWITCH(ulong mask) { } + #endif + #endif + #endregion +} + +/** + * A class for controlling parameters for each Category. + * + * A class for controlling parameters for each Category.
+ *
+ */ +public static class CriAtomExCategory +{ + /** + * REACT type + * + * The type of REACT.
+ *
+ * + * + */ + public enum ReactType : int + { + Ducker = 0, /**< Ducker */ + AisacModulationTrigger, /**< AISAC modulation trigger */ + } + + /** + * Ducking target by REACT + * + * Ducking target type by REACT.
+ *
+ * + * + */ + public enum ReactDuckerTargetType : int + { + Volume = 0, /**< Volume ducker */ + AisacControlValue, /**< Ducker of the AISAC control value */ + } + + /** + * Ducking Curve Type by REACT + * + * Ducking Curve Type by REACT.
+ *
+ * + * + */ + public enum ReactDuckerCurveType : int + { + Linear = 0, /**< straight line */ + Square, /**< Slow transition */ + SquareReverse, /**< high speed change */ + SCurve, /**< S curve */ + FlatAtHalf, /**< Inverted S curve */ + } + + /** + * REACT fade parameter structure + * + * A structure for getting/setting the fade drive parameter information of REACT.
+ *
+ * + * + */ + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + public struct ReactFadeParameter + { + public ReactDuckerCurveType curveType; /**< Curve type */ + public float curveStrength; /**< Curve strength (0.0f - 2.0f) */ + public System.UInt16 fadeTimeMs; /**< Fading time (milliseconds) */ + } + + /** + * REACT hold type + * + * REACT hold type (for maintaining the decay time).
+ *
+ * + * + */ + public enum ReactHoldType + { + WhilePlaying, /**< Do holding while playing */ + FixedTime, /**< Hold for a fixed time */ + } + + /** + * Ducker parameter structure by REACT + * + * A structure for getting/setting the ducker driving parameter information by REACT.
+ *
+ * + * + */ + [StructLayout(LayoutKind.Explicit, CharSet = CharSet.Ansi)] + public struct ReactDuckerParameter + { + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + public struct Volume + { + public float level; /**< Attenuation volume level */ + } + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + public struct AisacControl + { + public AisacControlId id; /**< AISAC control ID */ + public float value; /**< AISAC control value */ + } + [StructLayout(LayoutKind.Explicit, CharSet = CharSet.Ansi)] + public struct Target + { + [FieldOffset(0)] + public Volume volume; + [FieldOffset(0)] + public AisacControl aisacControl; + } + [FieldOffset(0)] + public Target target; + [FieldOffset(8)] + public ReactDuckerTargetType targetType; /**< Target of the Ducker */ + [FieldOffset(12)] + public ReactFadeParameter entry; /**< Fading parameter when start to change */ + [FieldOffset(24)] + public ReactFadeParameter exit; /**< Fading parameter when finished changing */ + [FieldOffset(36)] + public ReactHoldType holdType; /**< Hold type */ + [FieldOffset(40)] + public System.UInt16 holdTimeMs; /**< Hold time (milliseconds) */ + } + + /** + * AISAC modulation trigger parameter structure + * + * A structure for setting/getting the driving parameter information for AISAC modulation trigger.
+ *
+ * + * + */ + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + public struct ReactAisacModulationParameter + { + private System.Int32 _enableDecrementAisacModulationKey; + public System.UInt32 decrementAisacModulationKey; /**< Decrement AISAC modulation key */ + private System.Int32 _enableIncrementAisacModulationKey; + public System.UInt32 incrementAisacModulationKey; /**< Increment AISAC modulation key */ + public bool enableDecrementAisacModulationKey /**< Whether the decrement AISAC modulation key is enabled */ + { + get {return _enableDecrementAisacModulationKey != 0 ? true : false;} + } + public bool enableIncrementAisacModulationKey /**< Whether the increment AISAC modulation key is enabled */ + { + get {return _enableIncrementAisacModulationKey != 0 ? true : false; } + } + } + + /** + * REACT drive parameter structure + * + * A structure for getting/setting the drive parameter information of REACT.
+ *
+ * + * + */ + [StructLayout(LayoutKind.Explicit, CharSet = CharSet.Ansi)] + public struct ReactParameter + { + [StructLayout(LayoutKind.Explicit, CharSet = CharSet.Ansi)] + public struct Parameter + { + [FieldOffset(0)] + public ReactDuckerParameter ducker; /**< Ducker parameters */ + [FieldOffset(0)] + public ReactAisacModulationParameter aisacModulation; /**< AISAC modulation trigger parameter */ + } + [FieldOffset(0)] + public Parameter parameter; + [FieldOffset(44)] + public ReactType type; /**< REACT type */ + [FieldOffset(48)] + public bool enablePausingCue; /**< Whether the paused Cue is applied or not */ + } + + /** + * Execution status of REACT + * + * This is the value indicating the execution status of REACT
+ *
+ * + */ + public enum ReactStatus + { + Stop = 0, /**< Stopped */ + FadeOut, /**< Execution starting */ + Hold, /**< Executing */ + FadeIn, /**< Execution ending */ + Error, /**< Error */ + } + + /** + * Sets volume for the Category by specifying the name + * Category name + * Volume value + * + * Sets the volume for the Category by specifying the name. + * + */ + public static void SetVolume(string name, float volume) + { + criAtomExCategory_SetVolumeByName(name, volume); + } + + /** + * Sets volume for the Category by specifying the ID + * Category ID + * Volume value + * + * Sets the volume for the Category by specifying the ID. + * + */ + public static void SetVolume(int id, float volume) + { + criAtomExCategory_SetVolumeById(id, volume); + } + + /** + * Gets the Category volume by specifying the name + * Category name + * Category volume + * + * Gets the volume value applied to the Category by specifying the name. + * + */ + public static float GetVolume(string name) + { + return criAtomExCategory_GetVolumeByName(name); + } + + /** + * Gets the Category volume by specifying the ID + * Category ID + * Category volume + * + * Gets the volume value applied to the Category by specifying the ID. + * + */ + public static float GetVolume(int id) + { + return criAtomExCategory_GetVolumeById(id); + } + + /** + * Sets the Category mute status by specifying the name + * Category name + * Mute status (False = unmute, True = mute) + * + * Sets the mute status of the Category by specifying the name. + * + */ + public static void Mute(string name, bool mute) + { + criAtomExCategory_MuteByName(name, mute); + } + + /** + * Sets the Category mute status by specifying the ID + * Category ID + * Mute status (False = unmute, True = mute) + * + * Sets the mute status of the Category by specifying the ID. + * + */ + public static void Mute(int id, bool mute) + { + criAtomExCategory_MuteById(id, mute); + } + + /** + * Gets the Category mute status by specifying the name + * Category name + * Mute status (False = not muted, True = muted) + * + * Gets the mute status of the Category by specifying the name. + * + */ + public static bool IsMuted(string name) + { + return criAtomExCategory_IsMutedByName(name); + } + + /** + * Gets the Category mute status by specifying the ID + * Category ID + * Mute status (False = not muted, True = muted) + * + * Gets the mute status of the Category by specifying the ID. + * + */ + public static bool IsMuted(int id) + { + return criAtomExCategory_IsMutedById(id); + } + + /** + * Sets the solo status of the Category by specifying the name + * Category name + * Solo status (False = un-solo, True = solo) + * The mute volume value applied to other Categories + * + * Set the Category solo status by specifying the name.
+ * The volume specified by muteVolume + * is applied to the Categories belonging to the same Category group.
+ *
+ */ + public static void Solo(string name, bool solo, float muteVolume) + { + criAtomExCategory_SoloByName(name, solo, muteVolume); + } + + /** + * Sets the solo status of the Category by specifying the ID + * Category ID + * Solo status (False = un-solo, True = solo) + * The mute volume value applied to other Categories + * + * Sets the solo status of the Category by specifying the ID.
+ * The volume specified by muteVolume + * is applied to the Categories belonging to the same Category group.
+ *
+ */ + public static void Solo(int id, bool solo, float muteVolume) + { + criAtomExCategory_SoloById(id, solo, muteVolume); + } + + /** + * Gets the solo status of the Category by specifying the name + * Category name + * Solo status (False = not solo, True = solo) + * + * Gets the solo status of the Category by specifying the name. + * + */ + public static bool IsSoloed(string name) + { + return criAtomExCategory_IsSoloedByName(name); + } + + /** + * Gets the solo status of the Category by specifying the ID + * Category ID + * Solo status (False = not solo, True = solo) + * + * Gets the solo status of the Category by specifying the ID. + * + */ + public static bool IsSoloed(int id) + { + return criAtomExCategory_IsSoloedById(id); + } + + /** + * Pauses/unpauses the Category by specifying the name + * Category name + * Switch (False = unpause, True = pause) + * + * Pauses/unpauses the Category by specifying the name.
+ * The specification is the same as the CriWare.CriAtomExCategory::Pause(int, bool) function, except that + * the Category is specified by the name.
+ *
+ * + */ + public static void Pause(string name, bool pause) + { + criAtomExCategory_PauseByName(name, pause); + } + + /** + * Pauses/unpauses the Category by specifying the ID + * Category ID + * Switch (False = unpause, True = pause) + * + * Pauses/unpauses the Category by specifying the ID.
+ * Pausing a Category is treated independently of pausing + * the AtomExPlayer or playback sound (pause with CriWare.CriAtomExPlayer::Pause or CriWare.CriAtomExPlayback::Pause function), + * and the final pause status of a sound is determined by considering these pause states.
+ * In other words, paused if either of them is paused, and unpaused if all of the are unpaused.
+ *
+ * + */ + public static void Pause(int id, bool pause) + { + criAtomExCategory_PauseById(id, pause); + } + + /** + * Gets the pause status of the Category by specifying the ID + * Category ID + * Paused status (False = not paused, True = paused) + * + * Gets the pause status of the Category by specifying the ID. + * + */ + public static bool IsPaused(string name) + { + return criAtomExCategory_IsPausedByName(name); + } + + /** + * Pauses/unpauses the Category by specifying the name + * Category name + * Paused status (False = not paused, True = paused) + * + * Gets the pause status of the Category by specifying the name. + * + */ + public static bool IsPaused(int id) + { + return criAtomExCategory_IsPausedById(id); + } + + /** + * Sets the AISAC control value for the Category by specifying the name + * Category name + * AISAC control name + * AISAC control value + * + * Sets the AISAC control value for the Category by specifying the name.
+ * The specification is the same as the CriWare.CriAtomExCategory::SetAisacControl function, except that + * the Category and AISAC control are specified by the name.
+ *
+ * + */ + public static void SetAisacControl(string name, string controlName, float value) + { + criAtomExCategory_SetAisacControlByName(name, controlName, value); + } + + /** + * \deprecated + * This is a deprecated API that will be removed. + * Please consider using CriAtomExCategory.SetAisacControl instead. + */ + [System.Obsolete("Use CriAtomExCategory.SetAisacControl")] + public static void SetAisac(string name, string controlName, float value) + { + SetAisacControl(name, controlName, value); + } + + /** + * Sets the AISAC control value for the Category by specifying the ID + * Category ID + * AISAC control ID + * AISAC control value + * + * Sets the AISAC control value for the Category by specifying the ID.
+ * For the AISACs set to a Cue or Track, + * the AISAC control value set to the Category is given priority + * over the AISAC control value setting to the player
+ * For the AISACs attached to the Category, + * only the AISACcontrol value set to the Category is always referenced.
+ *
+ * + */ + public static void SetAisacControl(int id, int controlId, float value) + { + criAtomExCategory_SetAisacControlById(id, (ushort)controlId, value); + } + + /** + * \deprecated + * This is a deprecated API that will be removed. + * Please consider using CriAtomExCategory.SetAisacControl instead. + */ + [System.Obsolete("Use CriAtomExCategory.SetAisacControl")] + public static void SetAisac(int id, int controlId, float value) + { + SetAisacControl(id, controlId, value); + } + + /** + * Sets the REACT drive parameter + * REACT name + * REACT drive parameter structure + * + * Sets the parameters that drive REACT.
+ * Parameters cannot be set while REACT is running (warning is issued).
+ * If you specify a REACT name that does not exist, an error callback is returned.
+ *
+ * + * + */ + public static void SetReactParameter(string name, ReactParameter parameter) + { + criAtomExCategory_SetReactParameter(name, ref parameter); + } + + /** + * Gets the REACT drive parameters + * REACT name + * REACT drive parameter structure + * + * Gets the current value of the parameter that drives REACT.
+ * If you specify a REACT name that does not exist, an error callback is called and CRI_False is returned.
+ * If you specify a REACT name that does not exist, an error callback is returned.
+ *
+ * + */ + public static bool GetReactParameter(string name, out ReactParameter parameter) + { + return criAtomExCategory_GetReactParameter(name, out parameter); + } + + /** + * Gets the AISAC information by specifying the ID + * Category ID + * Index of the attached AISAC + * A structure for getting the AISAC information + * + * Gets the information on the AISAC attached to the Category by specifying the ID.
+ * If you specify a Category that does not exist, or if you specify an invalid index, False is returned.
+ *
+ */ + public static bool GetAttachedAisacInfoById(uint id, int aisacAttachedIndex, out CriAtomEx.AisacInfo aisacInfo) + { + using (var mem = new CriStructMemory()) { + bool result = criAtomExCategory_GetAttachedAisacInfoById(id, aisacAttachedIndex, mem.ptr); + if (result) { + aisacInfo = new CriAtomEx.AisacInfo(mem.bytes, 0); + } else { + aisacInfo = new CriAtomEx.AisacInfo(); + } + return result; + } + } + + /** + * Gets the AISAC information by specifying the name + * Category name + * Index of the attached AISAC + * A structure for getting the AISAC information + * + * Gets the information on the AISAC attached to the Category by specifying the name.
+ * If you specify a Category that does not exist, or if you specify an invalid index, False is returned.
+ *
+ */ + public static bool GetAttachedAisacInfoByName(string name, int aisacAttachedIndex, out CriAtomEx.AisacInfo aisacInfo) + { + using (var mem = new CriStructMemory()) { + bool result = criAtomExCategory_GetAttachedAisacInfoByName(name, aisacAttachedIndex, mem.ptr); + if (result) { + aisacInfo = new CriAtomEx.AisacInfo(mem.bytes, 0); + } else { + aisacInfo = new CriAtomEx.AisacInfo(); + } + return result; + } + } + + + /** + * Gets the AISAC information by specifying the name + * Category name + * AISAC control name + * Current value of the AISAC control + * Was the current value acquired? (Acquired: true / Unable to acquire: false) + * \par説明: + * カテゴリにアタッチされているAISACコントロールの現在値を取得します。
+ * \attention + * 存在しないカテゴリを指定した場合や、無効なインデックスを指定した場合、falseが返ります。
+ */ + public static bool GetCurrentAisacControlValue(string categoryName, string aisacControlName, out float controlValue) { + return criAtomExCategory_GetCurrentAisacControlValueByName(categoryName, aisacControlName, out controlValue); + } + + /** + * Gets the execution status of REACT
+ * REACT name + * Execution status of REACT + * + * Gets the execution status of REACT
+ * If a non-existing REACT name is specified, an error callback will be triggered and ReactStatus.Error will be returned. + *
+ */ + public static ReactStatus GetReactStatus(string reactName) + { + return criAtomExCategory_GetReactStatus(reactName); + } + + #region DLL Import + #if !CRIWARE_ENABLE_HEADLESS_MODE + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExCategory_SetVolumeByName(string name, float volume); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern float criAtomExCategory_GetVolumeByName(string name); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExCategory_SetVolumeById(int id, float volume); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern float criAtomExCategory_GetVolumeById(int id); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExCategory_MuteById(int id, bool mute); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool criAtomExCategory_IsMutedById(int id); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExCategory_MuteByName(string name, bool mute); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool criAtomExCategory_IsMutedByName(string name); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExCategory_SoloById(int id, bool solo, float volume); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool criAtomExCategory_IsSoloedById(int id); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExCategory_SoloByName(string name, bool solo, float volume); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool criAtomExCategory_IsSoloedByName(string name); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExCategory_PauseById(int id, bool pause); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool criAtomExCategory_IsPausedById(int id); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExCategory_PauseByName(string name, bool pause); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool criAtomExCategory_IsPausedByName(string name); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExCategory_SetAisacControlById(int id, ushort controlId, float value); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExCategory_SetAisacControlByName(string name, string controlName, float value); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExCategory_SetReactParameter(string react_name, ref ReactParameter parameter); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool criAtomExCategory_GetReactParameter(string react_name, out ReactParameter parameter); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool criAtomExCategory_GetAttachedAisacInfoById(uint id, int aisacAttachedIndex, IntPtr aisacInfo); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool criAtomExCategory_GetAttachedAisacInfoByName(string name, int aisacAttachedIndex, IntPtr aisacInfo); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool criAtomExCategory_GetCurrentAisacControlValueByName(string category_name, string aisac_control_name, out float control_value); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern ReactStatus criAtomExCategory_GetReactStatus(string react_name); + + #else + private static void criAtomExCategory_SetVolumeByName(string name, float volume) { } + private static float criAtomExCategory_GetVolumeByName(string name) { return 1.0f; } + private static void criAtomExCategory_SetVolumeById(int id, float volume) { } + private static float criAtomExCategory_GetVolumeById(int id) { return 1.0f; } + private static void criAtomExCategory_MuteById(int id, bool mute) { } + private static bool criAtomExCategory_IsMutedById(int id) { return false; } + private static void criAtomExCategory_MuteByName(string name, bool mute) { } + private static bool criAtomExCategory_IsMutedByName(string name) { return false; } + private static void criAtomExCategory_SoloById(int id, bool solo, float volume) { } + private static bool criAtomExCategory_IsSoloedById(int id) { return false; } + private static void criAtomExCategory_SoloByName(string name, bool solo, float volume) { } + private static bool criAtomExCategory_IsSoloedByName(string name) { return false; } + private static void criAtomExCategory_PauseById(int id, bool pause) { } + private static bool criAtomExCategory_IsPausedById(int id) { return false; } + private static void criAtomExCategory_PauseByName(string name, bool pause) { } + private static bool criAtomExCategory_IsPausedByName(string name) { return false; } + private static void criAtomExCategory_SetAisacControlById(int id, ushort controlId, float value) { } + private static void criAtomExCategory_SetAisacControlByName(string name, string controlName, float value) { } + private static void criAtomExCategory_SetReactParameter(string name, ref ReactParameter parameter) { } + private static bool criAtomExCategory_GetReactParameter(string name, out ReactParameter parameter) { parameter = new ReactParameter(); + return false; } + private static bool criAtomExCategory_GetAttachedAisacInfoById(uint id, int aisacAttachedIndex, IntPtr aisacInfo) { return false; } + private static bool criAtomExCategory_GetAttachedAisacInfoByName(string name, int aisacAttachedIndex, IntPtr aisacInfo) { return false; } + private static bool criAtomExCategory_GetCurrentAisacControlValueByName(string category_name, string aisac_control_name, out float control_value) { control_value = 0.0f; return false;} + private static ReactStatus criAtomExCategory_GetReactStatus(string react_name) { return ReactStatus.Error; } + #endif + + #endregion +} + +/** + * A class for controlling the Sequence data. + * + * A class for using the Sequence data created on CRI Atom Craft.
+ *
+ */ +public static class CriAtomExSequencer +{ + /** + * Structure to get information about a sequence event + * + * This is the structure used to get information about a sequence event.
+ *
+ * + */ + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + public struct CriAtomExSequenceEventInfo { + public ulong position; + public IntPtr playerHn; + [MarshalAs(UnmanagedType.LPStr)] + public readonly string tag; + public uint playbackId; + private int type; + public uint id; + private uint reserved; + } + /** + * Sequence callback (string argument) + * Event parameter string + * + * A Sequence callback function type.
+ * The argument string contains the following information:
+ * -# Event position + * -# Event ID + * -# Playback ID + * -# Event type + * -# Event tag string + * . + * Each piece of information is concatenated and passed as one string with the specified delimiter character in between.
+ * Parse the required parameters from the string before use.
+ *
+ * + */ + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public delegate void EventCbFunc(string eventParamsString); + + /** + * Sequence callback + * >Event information structure + * + * Sequence callback function type.
+ * The structure passed as argument contains the following information:
+ * -# Event position + * -# Player handler pointer + * -# Data embedded string + * -# Playback ID + * -# Event type + * -# Data embedded value + * .
+ *
+ */ + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public delegate void EventCallback(ref CriAtomExSequenceEventInfo criAtomExSequenceInfo); + + /** + * Registers the Sequence event callback + * + * Registers a callback function to be executed by the callback marker synchronization embedded in the Cue.
+ * The registered callback function will be executed when the application main thread is updated + * immediately after processing the callback event.
+ *
+ */ + public static event EventCallback OnCallback { + add { + CriAtom.OnEventSequencerCallback += value; + } + remove { + CriAtom.OnEventSequencerCallback -= value; + } + } + + /** + * \deprecated + * 削除予定の非推奨APIです。 + * CriAtomExSequencer.OnCallback event の使用を検討してください。 + * Registering sequence event callbacks (for string argument delegates) + * Sequence callback function + * Event parameter delimiting string (up to 15 characters) + * + * Registers the callback function that receives the callback information embedded in the Sequence data.
+ * The registered callback function is called at the update timing of the application main thread + * immediately after processing the callback event.
+ * Only one callback function can be registered.
+ * If you do the registration multiple times, the callback function + * already registered is overwritten by the one registered later.
+ *
+ */ + [Obsolete("SetEventCallback is deprecated. Use CriAtomExSequencer.OnCallback event", false)] + public static void SetEventCallback(CriAtomExSequencer.EventCbFunc func, string separator = "\t") + { + /* MonoBehaviour側に登録 */ + CriAtom.SetEventCallback(func, separator); + } +} + +/** + * A class for using beat synchronization data. + * + * A class for using the beat synchronization data set on CRI Atom Craft.
+ *
+ */ +public static class CriAtomExBeatSync +{ + /** + * Beat synchronization position detection callback information + * + * A structure for getting information from the beat synchronization callback and beat synchronization information getting method.
+ *
+ * + * + */ + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + public struct Info { + public IntPtr playerHn; /**< Player handle */ + public uint playbackId; /**< Playback ID */ + public uint barCount; /**< The number of Measures */ + public uint beatCount; /**< The current count of beats */ + public float beatProgress; /**< Beat progress (0.0f to 1.0f) */ + public float bpm; /**< Tempo (beats/minute) */ + public int offset; /**< Sync offset (ms) */ + public uint numBeats; /**< The number of beats */ + } + + /** + * Beat synchronization callback + * Beat synchronization position detection information + * + * A beat synchronization callback function type.
+ *
+ * + */ + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public delegate void CbFunc(ref Info info); + + /** + * Registers the beat synchronization callback + * + * Registers the callback function that receives the beat synchronization position information embedded in the Cue.
+ * The registered callback function is called at the update timing of the application main thread + * immediately after processing the callback event.
+ *
+ */ + public static event CbFunc OnCallback { + add { + CriAtom.OnBeatSyncCallback += value; + } + remove { + CriAtom.OnBeatSyncCallback -= value; + } + } + + /** + * \deprecated + * 削除予定の非推奨APIです。 + * CriAtomExPlayer.OnBeatSyncCallback または CriAtomExBeatSync.OnCallback の使用を検討してください。 + * Registers the beat synchronization callback + * Callback function + * + * Registers the callback function that receives the beat synchronization position information embedded in the Cue.
+ * The registered callback function is called at the update timing of the application main thread + * immediately after processing the callback event.
+ * Only one callback function can be registered.
+ * If you do the registration multiple times, the callback function + * already registered is overwritten by the one registered later.
+ *
+ */ + [Obsolete("SetCallback is deprecated. Use OnBeatSyncCallback event", false)] + public static void SetCallback(CriAtomExBeatSync.CbFunc func) + { + /* MonoBehaviour側に登録 */ + CriAtom.SetBeatSyncCallback(func); + } +} + +/** + * A class that controls the bus output of the Atom sound renderer. + * + * In this class, you can change the volume or measure the level by operating the bus output of the Atom sound renderer.
+ *
+ */ +public class CriAtomExAsr +{ + [StructLayout(LayoutKind.Sequential)] + private struct BusAnalyzerConfig + { + public int interval; + public int peakHoldTime; + } + + /** + * Level measurement information + * + * A structure for acquiring the level measurement information of the DSP bus.
+ * Used in the CriAtomExAsr::GetBusAnalyzerInfo.
+ * Each level value is a scale factor for the amplitude of the sound data (the unit is not decibel).
+ * You can convert to decibel notation using the following code.
+ * dB = 10.0f * log10f(level);
+ *
+ * + */ + [StructLayout(LayoutKind.Sequential)] + public struct BusAnalyzerInfo + { + public int numChannels; /**< The number of effective channels */ + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] + public float[] rmsLevels; /**< RMS level */ + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] + public float[] peakLevels; /**< Peak level */ + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] + public float[] peakHoldLevels; /**< Peak hold level */ + + public BusAnalyzerInfo(byte[] data) + { + if (data != null) { + this.numChannels = BitConverter.ToInt32(data, 0); + this.rmsLevels = new float[8]; + for (int i = 0; i < 8; i++) { + this.rmsLevels[i] = BitConverter.ToSingle(data, 4 + i * 4); + } + this.peakLevels = new float[8]; + for (int i = 0; i < 8; i++) { + this.peakLevels[i] = BitConverter.ToSingle(data, 36 + i * 4); + } + this.peakHoldLevels = new float[8]; + for (int i = 0; i < 8; i++) { + this.peakHoldLevels[i] = BitConverter.ToSingle(data, 68 + i * 4); + } + } else { + this.numChannels = 0; + this.rmsLevels = new float[8]; + this.peakLevels = new float[8]; + this.peakHoldLevels = new float[8]; + } + } + } + + /** + * Adds the level measurement function + * DSP bus name + * Measurement interval (ms) + * Hold time of the peak hold level (ms) + * + * Adds the level measurement function to the DSP bus and starts the level measurement.
+ * After calling this function, you can get the RMS level (sound pressure), + * peak level (maximum amplitude), and peak hold level by calling the + * CriAtomExAsr::GetBusAnalyzerInfo function. + * In order to measure the level of multiple DSP buses, this function must be called for each DSP bus.
+ *
+ * + * + */ + public static void AttachBusAnalyzer(string busName, int interval, int peakHoldTime) + { + BusAnalyzerConfig config; + config.interval = interval; + config.peakHoldTime = peakHoldTime; + criAtomExAsr_AttachBusAnalyzerByName(busName, ref config); + } + + /** + * Adds the level measurement feature to all DSP buses + * Measurement interval (ms) + * Hold time of the peak hold level (ms) + * + * Adds the level measurement function to the DSP bus and starts the level measurement.
+ * After calling this function, you can get the RMS level (sound pressure), + * peak level (maximum amplitude), and peak hold level by calling the + * CriAtomExAsr::GetBusAnalyzerInfo function.
+ *
+ * + * + */ + public static void AttachBusAnalyzer(int interval, int peakHoldTime) + { + BusAnalyzerConfig config; + config.interval = interval; + config.peakHoldTime = peakHoldTime; + for (int i = 0; i < 8; i++) { + criAtomExAsr_AttachBusAnalyzer(i, ref config); + } + } + + /** + * Removes the level measurement function + * DSP bus name + * + * Removes the level measurement function from the specified DSP bus. + * + * + */ + public static void DetachBusAnalyzer(string busName) + { + criAtomExAsr_DetachBusAnalyzerByName(busName); + } + + /** + * Removes the level measurement feature from all DSP buses + * + * Removes the level measurement feature from all DSP buses. + * + * + */ + public static void DetachBusAnalyzer() + { + for (int i = 0; i < 8; i++) { + criAtomExAsr_DetachBusAnalyzer(i); + } + } + + /** + * Gets the level measurement result + * DSP bus name + * Level measurement result + * + * Gets the result of the level measurement function from the DSP bus. + * + * + */ + public static void GetBusAnalyzerInfo(string busName, out BusAnalyzerInfo info) + { + using (var mem = new CriStructMemory()) { + criAtomExAsr_GetBusAnalyzerInfoByName(busName, mem.ptr); + info = new BusAnalyzerInfo(mem.bytes); + } + } + + /** + * \deprecated + * This is a deprecated API that will be removed. + * Please consider using CriAtomExAsr.GetBusAnalyzerInfo(string busName, out BusAnalyzerInfo info) instead. + */ + [System.Obsolete("Use CriAtomExAsr.GetBusAnalyzerInfo(string busName, out BusAnalyzerInfo info)")] + public static void GetBusAnalyzerInfo(int busId, out BusAnalyzerInfo info) + { + using (var mem = new CriStructMemory()) { + criAtomExAsr_GetBusAnalyzerInfo(busId, mem.ptr); + info = new BusAnalyzerInfo(mem.bytes); + } + } + + /** + * Sets the volume of the DSP bus + * DSP bus name + * Volume value + * + * Sets the volume of the DSP bus.
+ * This is valid for the send destinations whose send type is post-volume or post-pan.
+ *
+ * For the volume value, specify a real value in the range of 0.0f to 1.0f.
+ * The volume value is a scale factor for the amplitude of the sound data (the unit is not decibel).
+ * For example, if you specify 1.0f, the original sound is played at its unmodified volume.
+ * If you specify 0.5f, the sound is played at the volume by halving the amplitude (-6dB) + * of the original waveform.
+ * If you specify 0.0f, the sound is muted (silent).
+ * The default volume is the value set on CRI Atom Craft.
+ *
+ */ + public static void SetBusVolume(string busName, float volume) + { + criAtomExAsr_SetBusVolumeByName(busName, volume); + } + + /** + * \deprecated + * This is a deprecated API that will be removed. + * Please consider using CriAtomExAsr.SetBusVolume(string busName, float volume) instead. + */ + [System.Obsolete("Use CriAtomExAsr.SetBusVolume(string busName, float volume)")] + public static void SetBusVolume(int busId, float volume) + { + criAtomExAsr_SetBusVolume(busId, volume); + } + + /** + * Sets the send level of the DSP bus + * DSP bus name + * Send destination DSP bus name + * Level value + * + * Sets the level for sending sound data to the send destination DSP bus.
+ *
+ * Specify a real value in the range of 0.0f to 1.0f for the level value.
+ * The level value is a scale factor for the amplitude of sound data (in decibels).
+ * For example, if you set it to 1.0f, the sound is played at its original level.
+ * If you specify 0.5f, the sound is played at the volume by halving the amplitude (-6dB) + * of the original waveform.
+ * If you specify 0.0f, the sound is muted (silent).
+ * The default level is the value set on CRI Atom Craft.
+ *
+ */ + public static void SetBusSendLevel(string busName, string sendTo, float level) + { + criAtomExAsr_SetBusSendLevelByName(busName, sendTo, level); + } + + /** + * \deprecated + * This is a deprecated API that will be removed. + * Please consider using CriAtomExAsr.SetBusSendLevel(string busName, string sendTo, float level) instead. + */ + [System.Obsolete("Use CriAtomExAsr.SetBusSendLevel(string busName, string sendTo, float level)")] + public static void SetBusSendLevel(int busId, int sendTo, float level) + { + criAtomExAsr_SetBusSendLevel(busId, sendTo, level); + } + + /** + * Sets the level matrix for the DSP bus + * DSP bus name + * The number of input channels + * The number of output channels + * An array of level values that represents the level matrix in one dimension + * + * Sets the level matrix of the DSP bus.
+ * Valid for the send destination whose send type is post-pan.
+ *
+ * The level matrix is a mechanism for specifying which speaker outputs + * the sound of each channel of the sound data at which volume.
+ * matrix is an array of [input_channels * output_channels].
+ * You set the level sent from the input channel ch_in to the output channel ch_out + * inmatrix[ch_in * output_channels + ch_out].
+ * The default of the level matrix is the identity matrix.
+ *
+ * Specify a real value in the range of 0.0f to 1.0f for the level value.
+ * The level value is a scale factor for the amplitude of sound data (in decibels).
+ * For example, if you set it to 1.0f, the sound is played at its original level.
+ * If you specify 0.5f, the sound is played at the volume by halving the amplitude (-6dB) + * of the original waveform.
+ * If you specify 0.0f, the sound is muted (silent).
+ *
+ */ + public static void SetBusMatrix(string busName, int inputChannels, int outputChannels, float[] matrix) + { + criAtomExAsr_SetBusMatrixByName(busName, inputChannels, outputChannels, matrix); + } + + /** + * \deprecated + * This is a deprecated API that will be removed. + * Please consider using CriAtomExAsr.SetBusMatrix(string busName, int inputChannels, int outputChannels, float[] matrix) instead. + */ + [System.Obsolete("Use CriAtomExAsr.SetBusMatrix(string busName, int inputChannels, int outputChannels, float[] matrix)")] + public static void SetBusMatrix(int busId, int inputChannels, int outputChannels, float[] matrix) + { + criAtomExAsr_SetBusMatrix(busId, inputChannels, outputChannels, matrix); + } + + /** + * DSP bus effect Bypass setting + * Bus name + * Effect name + * Bypass setting (True: bypass, False: not bypass) + * + * Sets the Bypass of the effect.
+ * Bypassed effects will be passed through during sound processing.
+ * Before bypassing an effect, a DSP bus setting must be attached + * before calling this function.
+ * Which effect is on which bus depends on the DSP bus settings you attached.
+ * The function fails if there is no effect with the specified ID on the specified bus.
+ * If you set Bypass while the sound is played, a noise may occur.
+ *
+ */ + public static void SetEffectBypass(string busName, string effectName, bool bypass) + { + criAtomExAsr_SetEffectBypass(busName, effectName, bypass); + } + + /** + * Sets the DSP bus effect operating parameter + * Bus name + * Effect name + * Effect run-time parameter index + * Effect run-time parameter settings + * + * Sets the operating parameters of the DSP bus effect.
+ *
+ * Which effect is on which bus depends on the DSP bus settings you attached.
+ * The function fails if there is no effect with the specified ID on the specified bus.
+ *
+ */ + public static void SetEffectParameter(string busName, string effectName, uint parameterIndex, float parameterValue) + { + criAtomExAsr_SetEffectParameter(busName, effectName, parameterIndex, parameterValue); + criAtomExAsr_UpdateEffectParameters(busName, effectName); + } + + /** + * Gets the DSP bus effect operating parameter + * Bus name + * Effect name + * Effect run-time parameter index + * + * Gets the operating parameter value of the DSP bus effect.
+ *
+ * Which effect is on which bus depends on the DSP bus settings you attached.
+ * The function fails if there is no effect with the specified ID on the specified bus.
+ *
+ */ + public static float GetEffectParameter(string busName, string effectName, uint parameterIndex) + { + return criAtomExAsr_GetEffectParameter(busName, effectName, parameterIndex); + } + + + /** + * Registers the user-defined effect interface + * Interface with version information for user-defined effects + * Was the registration successful? (True: registration successful, False: registration failed) + * + * Registers the user-defined effects interface with ASR.
+ * The effects for which the user-defined effects interface has been registered can be used when attaching the DSP bus settings.
+ * If the following conditions are met, the registration of the user-defined effects interface fails and an error callback is returned: + * - A user defined effect interface with the same effect name is already registered + * - It is different from the user-defined effects interface used by Atom + * - The maximum number of user-defined effect interface registrations is reached
+ * This API can be used only when registering an user-defined effect in CRI ADX2 Audio Effect Plugin SDK.
+ * Be sure to call this function after calling CriAtomPlugin::InitializeLibrary + * and before calling CriAtomEx::AttachDSPBusSetting.
+ * Once registered, the interface pointer continues to be referenced until CriAtomEx::DetachDSPBusSetting is called.
+ * If you want to unregister the interface while using the library, use CriAtomExAsr::UnregisterEffectInterface.
+ *
+ * + * + * + */ + static public bool RegisterEffectInterface(IntPtr afx_interface) + { + return criAtomExAsr_RegisterEffectInterface(afx_interface); + } + + /** + * Unregisters the user-defined effects interface + * Interface with version information for user-defined effects + * + * Unregister the user-defined effect interface.
+ * Unregistered effects will no longer be available when attaching the DSP bus settings.
+ * You cannot unregister a user-defined effect interface that has not been + * registered (error callback is returned).
+ * This API can be used only when unregistering an effect in CRI ADX2 Audio Effect Plugin SDK. + *
+ * + */ + static public void UnregisterEffectInterface(IntPtr afx_interface) + { + criAtomExAsr_UnregisterEffectInterface(afx_interface); + } + + /** + * Getting the volume of the Bus + * Bus name + * Volume value + * + * Gets the volume of the bus.
+ *
+ * The raw volume value will be returned.
+ * The default value of the volume is the value set in CRI Atom Craft.
+ *
+ */ + static public void GetBusVolume(string busName, out float volume) + { + criAtomExAsr_GetBusVolumeByName(busName, out volume); + } + + /** + * Gets the PCM output + * Number of channels to acquire + * Number of PCM samples to acquire + * Buffer for writing PCM samples + * Number of PCM samples acquired + * + * Gets the PCM samples output by Atom.
+ * This function is for execution in the Editor only.
+ * It works only if the user PCM output mode is enabled and initialized.
+ *
+ */ + static public int GetPcmOutput(int outputChannels, int outputSamples, float[][] buffer) + { + #if UNITY_EDITOR + GCHandle[] gchs = new GCHandle[outputChannels]; + IntPtr[] intPtrs = new IntPtr[outputChannels]; + for (int i = 0; i < outputChannels; i++) { + gchs[i] = GCHandle.Alloc(buffer[i], GCHandleType.Pinned); + intPtrs[i] = gchs[i].AddrOfPinnedObject(); + } + int ret = criAtomExAsr_GetPcmDataFloat32(outputChannels, outputSamples, intPtrs); + for (int i = 0; i < outputChannels; i++) { + gchs[i].Free(); + } + return ret; + #else + return 0; + #endif + } + + /** + * Gets the number of output PCM samples available + * Number of PCM output samples that can be acquired + * + * Gets the number of PCM samples that will be output from the available Atom.
+ * This function is for execution in the Editor only.
+ * It works only if the user PCM output mode is enabled and initialized.
+ *
+ */ + static public int GetNumBufferedPcmOutputSamples() + { + #if UNITY_EDITOR + return criAtomExAsr_GetNumBufferedSamples(); + #else + return 0; + #endif + } + + /** + * Sets the size of the buffer for the output of the PCM samples + * Size of the buffer containing the PCM samples output + * + * Sets the size of the buffer used by Atom for the PCM sample data.
A small size will reduce the latency of the output obtained via CriWare.CriAtomExAsr::GetPcmOutput . However, it may cause audio interruptions and other issues if the calling rate is insufficient.
+ * This function is for execution in the Editor only.
+ * It works only if the user PCM output mode is enabled and initialized.
+ *
+ */ + static public void SetPcmBufferSize(int numSamples) + { + #if UNITY_EDITOR + criAtomExAsr_SetPcmBufferSize(numSamples); + #endif + } + + #region DLL Import + #if !CRIWARE_ENABLE_HEADLESS_MODE + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExAsr_AttachBusAnalyzerByName( + string busName, ref BusAnalyzerConfig config); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExAsr_AttachBusAnalyzer( + int busNo, ref BusAnalyzerConfig config); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExAsr_DetachBusAnalyzerByName(string busName); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExAsr_DetachBusAnalyzer(int busNo); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExAsr_GetBusAnalyzerInfoByName( + string busName, IntPtr info); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExAsr_GetBusAnalyzerInfo( + int busNo, IntPtr info); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExAsr_SetBusVolumeByName( + string busName, float volume); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExAsr_SetBusVolume( + int busNo, float volume); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExAsr_SetBusSendLevelByName( + string busName, string sendtoName, float level); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExAsr_SetBusSendLevel( + int busNo, int sendtoNo, float level); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExAsr_SetBusMatrixByName( + string busName, + int inputChannels, + int outputChannels, + [MarshalAs(UnmanagedType.LPArray)] float[] matrix + ); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExAsr_SetBusMatrix( + int busNo, + int inputChannels, + int outputChannels, + [MarshalAs(UnmanagedType.LPArray)] float[] matrix + ); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExAsr_SetEffectBypass(string busName, string effectName, bool bypass); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExAsr_UpdateEffectParameters(string busName, string effectName); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExAsr_SetEffectParameter(string busName, string effectName, uint parameterIndex, float parameterValue); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern float criAtomExAsr_GetEffectParameter(string busName, string effectName, uint parameterIndex); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool criAtomExAsr_RegisterEffectInterface(IntPtr afx_interface); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExAsr_UnregisterEffectInterface(IntPtr afx_interface); + +#if UNITY_EDITOR + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criAtomExAsr_GetPcmDataFloat32(int outputChannels, int outputSamples, IntPtr[] samples); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criAtomExAsr_GetNumBufferedSamples(); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExAsr_SetPcmBufferSize(int numSamples); +#endif + + #else + private static void criAtomExAsr_AttachBusAnalyzerByName( + string busName, ref BusAnalyzerConfig config) { } + private static void criAtomExAsr_AttachBusAnalyzer( + int busNo, ref BusAnalyzerConfig config) { } + private static void criAtomExAsr_DetachBusAnalyzerByName(string busName) { } + private static void criAtomExAsr_DetachBusAnalyzer(int busNo) { } + private static void criAtomExAsr_GetBusAnalyzerInfoByName( + string busName, IntPtr info) { } + private static void criAtomExAsr_GetBusAnalyzerInfo(int busNo, IntPtr info) { } + private static void criAtomExAsr_SetBusVolumeByName(string busName, float volume) { } + private static void criAtomExAsr_SetBusVolume(int busNo, float volume) { } + private static void criAtomExAsr_SetBusSendLevelByName(string busName, string sendtoName, float level) { } + private static void criAtomExAsr_SetBusSendLevel(int busNo, int sendtoNo, float level) { } + private static void criAtomExAsr_SetBusMatrixByName( + string busName, + int inputChannels, + int outputChannels, + [MarshalAs(UnmanagedType.LPArray)] float[] matrix + ) { } + private static void criAtomExAsr_SetBusMatrix( + int busNo, + int inputChannels, + int outputChannels, + [MarshalAs(UnmanagedType.LPArray)] float[] matrix + ) { } + private static void criAtomExAsr_SetEffectBypass(string busName, string effectName, bool bypass) { } + private static void criAtomExAsr_UpdateEffectParameters(string busName, string effectName) { } + private static void criAtomExAsr_SetEffectParameter(string busName, string effectName, uint parameterIndex, float parameterValue) { } + private static float criAtomExAsr_GetEffectParameter(string busName, string effectName, uint parameterIndex) { return 0.0f; } + private static bool criAtomExAsr_RegisterEffectInterface(IntPtr afx_interface) { return true; } // fixme + private static void criAtomExAsr_UnregisterEffectInterface(IntPtr afx_interface) { } +#if UNITY_EDITOR + private static int criAtomExAsr_GetPcmDataFloat32(int outputChannels, int outputSamples, IntPtr[] samples) { return 0; } + private static int criAtomExAsr_GetNumBufferedSamples() { return 0; } + private static void criAtomExAsr_SetPcmBufferSize(int numSamples) { } +#endif + #endif + + #if !CRIWARE_ENABLE_HEADLESS_MODE && !UNITY_WEBGL + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExAsr_GetBusVolumeByName(string busName, out float volume); + #else + private static void criAtomExAsr_GetBusVolumeByName(string busName, out float volume) { volume = 0.0f; } + #endif + + #endregion +} + +/** + * A class for getting the estimated delay value for sound playback. + * + * In this class, you can change the volume or measure the level by operating the + * bus output of the Atom sound renderer.
+ *
+ */ +public static class CriAtomExLatencyEstimator +{ + /** + * Status + * + * A value that indicates the status of the delay estimation.
+ * It can get using the CriWare.CriAtomExLatencyEstimator::GetCurrentInfo function.
+ *
+ *
+ */ + public enum Status { + Stop, /**< Initial state/stopped state */ + Processing, /**< Estimating delay time */ + Done, /**< Delay time estimation completed */ + Error, /**< Error */ + } + + /** + * Status + * + * A structure that represents the information on delay estimation.
+ * It holds the execution status of the inference module and the latency (estimated value). The unit is millisecond. + * It can get using the CriWare.CriAtomExLatencyEstimator::GetCurrentInfo function.
+ *
+ *
+ */ + [StructLayout(LayoutKind.Sequential)] + public struct EstimatorInfo + { + public Status status; /**< Status of the delay estimation module */ + public uint estimated_latency; /**< The result of estimated latency (in milliseconds) */ + } + + /** + * Initialize the delay estimation process + * + * Call this function after initializing the plug-in. + * Starts the delay estimation process for sound playback.
+ *
+ * If you use the CriAtomExLatencyEstimator to obtain the sound delay estimation value, + * you must always do initialization using this function.
+ * If you could get the estimated value or if an error occurs, call the + * CriAtomExLatencyEstimator.Finalize function.
+ * Multiple calls to this function are allowed, but the number of calls is internally counted, + * and the actual initialization done only at the first call.
+ *
+ * + */ + public static void InitializeModule() + { + #if !UNITY_EDITOR && UNITY_ANDROID + criAtomLatencyEstimator_Initialize_ANDROID(); + #endif + } + + /** + * Terminates the delay estimation process + * + * Finishes the delay estimation for sound playback.
+ *
+ * When the delay estimation value is acquired, call this function to end the estimation process. + * Also, call this function if an error occurs or if you want to interrupt the estimation process.
+ * When the CriAtomExLatencyEstimator.InitializeModule function is called multiple times, the number of calls (reference count) + * is incremented internally. The termination process is not invoked until the reference count reaches 0, so when you performed initialization multiple times, + * call this function until the reference count becomes 0. + *
+ * + */ + public static void FinalizeModule() + { + #if !UNITY_EDITOR && UNITY_ANDROID + criAtomLatencyEstimator_Finalize_ANDROID(); + #endif + } + + /** + * Gets information on delay estimation + * + * Gets the current information on the delay estimation.
+ * The information that can be acquired is "delay estimator status" and "estimated delay time (ms)".
+ *
+ * The estimated_latency obtained when the status changes to Status.Done is the estimated value.
+ * Note that the estimated delay value cannot be obtained immediately. Before it changes from Status.Processsing to Status.Done, it takes + * tens to hundreds of milliseconds. (The time it takes depends on the Atom initialization settings and device) + *
+ * The value of estmated_latency when the status is not Status.Done is invalid. Make sure that the status is Status.Done + * before recording the value of estimated_latency.
+ *
+ * After calling this function to get the estimated value, call riAtomExLatencyEstimator.Finalize to finalize the process.
+ *
+ * + * + */ + public static CriAtomExLatencyEstimator.EstimatorInfo GetCurrentInfo() + { + #if !UNITY_EDITOR && UNITY_ANDROID + return criAtomLatencyEstimator_GetCurrentInfo_ANDROID(); + #else + EstimatorInfo info = new EstimatorInfo(); + info.status = CriAtomExLatencyEstimator.Status.Stop; + info.estimated_latency = 0; + return info; + #endif + } + + #region DLL Import + #if !UNITY_EDITOR && UNITY_ANDROID + #if !CRIWARE_ENABLE_HEADLESS_MODE + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomLatencyEstimator_Initialize_ANDROID(); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomLatencyEstimator_Finalize_ANDROID(); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern EstimatorInfo criAtomLatencyEstimator_GetCurrentInfo_ANDROID(); + #else + private static void criAtomLatencyEstimator_Initialize_ANDROID() { } + private static void criAtomLatencyEstimator_Finalize_ANDROID() { } + private static EstimatorInfo criAtomLatencyEstimator_GetCurrentInfo_ANDROID() + { + EstimatorInfo info = new EstimatorInfo(); + info.status = CriAtomExLatencyEstimator.Status.Stop; + info.estimated_latency = 0; + return info; + } + #endif + #endif + #endregion +} + +} //namespace CriWare +/** + * @} + */ + +/* --- end of file --- */ diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomEx.cs.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomEx.cs.meta new file mode 100644 index 0000000..b81530d --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomEx.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: d8e5372b33b3d1049aea96b60b8ab8d1 +timeCreated: 1433816077 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomEx3dListener.cs b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomEx3dListener.cs new file mode 100644 index 0000000..7126b20 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomEx3dListener.cs @@ -0,0 +1,477 @@ +/**************************************************************************** + * + * Copyright (c) 2011 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +#if !UNITY_WEBGL + #define CRIWARE_TRANSCEIVER_N_ELEVATIONANGLEAISAC_SUPPORT +#endif + +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using System.Text; + +/*========================================================================== + * CRI Atom Native Wrapper + *=========================================================================*/ +/** + * \addtogroup CRIATOM_NATIVE_WRAPPER + * @{ + */ + +namespace CriWare { + +/** + * 3D listener + * + * An object for handling the 3D listener.
+ * Used for 3D Positioning.
+ *
+ * You set the parameters and position information of the 3D listener through the 3D listener object.
+ *
+ */ +public class CriAtomEx3dListener : CriDisposable +{ + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + public struct Config { + public int reserved; + } + + /** + * Creates a 3D listener + * + * Creates a 3D listener object.
+ * The library must be initialized before calling this function.
+ *
+ */ + public CriAtomEx3dListener() + { + Config config = new Config(); + this.handle = criAtomEx3dListener_Create(ref config, IntPtr.Zero, 0); + CriDisposableObjectManager.Register(this, CriDisposableObjectManager.ModuleType.Atom); + } + + /** + * Discards the 3D listener object + * + * Discards a 3D listener object.
+ * When this function is called, all the resources allocated in the DLL when creating the 3D listener are released.
+ * If there are any sounds being played by an AtomExPlayer with the 3D listener object set, + * either stop those sounds or discard the AtomExPlayer before calling this function.
+ *
+ */ + public override void Dispose() + { + this.Dispose(true); + } + + private void Dispose(bool disposing) + { + CriDisposableObjectManager.Unregister(this); + + if (this.handle != IntPtr.Zero) { + criAtomEx3dListener_Destroy(this.handle); + this.handle = IntPtr.Zero; + } + + if (disposing) { + GC.SuppressFinalize(this); + } + } + + public IntPtr nativeHandle + { + get {return this.handle;} + } + + /** + * Updates the 3D listener + * + * Updates the 3D listener using the parameters set in the 3D listener.
+ * This function updates all the parameters set in the 3D listener. + * It is more efficient to change multiple parameters before performing update + * than to update using this function each time a parameter is changed.
+ * This function runs independently of the parameter update in the AtomExPlayer + * ( CriWare.CriAtomExPlayer::UpdateAll , CriWare.CriAtomExPlayer::Update ).
+ * When you change the parameter of the 3D listener, perform the update process using this function.
+ *
+ * + * : + * // リスナーの作成 + * CriAtomExListener listener = new CriAtomEx3dListener(); + * : + * // リスナー位置の設定 + * listener.SetPosition(0.0f, 0.0f, 1.0f); + * + * // リスナー速度の設定 + * listener.SetVelocity(1.0f, 0.0f, 0.0f); + * + * // 注意)この時点ではリスナーの位置や速度はまだ変更されていません。 + * + * // 変更の適用 + * listener.Update(); + * : + * + */ + public void Update() + { + if (this.handle != IntPtr.Zero) + criAtomEx3dListener_Update(this.handle); + } + + /** + * Initializes 3D sound source parameters + * + * Clears the parameters set in the 3D listener and restores the initial values.
+ * To actually apply the cleared parameters, you need to call the CriWare.CriAtomEx3dListener::Update function. + *
+ */ + public void ResetParameters() + { + if (this.handle != IntPtr.Zero) + criAtomEx3dListener_ResetParameters(this.handle); + } + + /** + * Sets the position of the 3D listener + * X coordinate + * Y coordinate + * Z coordinate + * + * Sets the position of the 3D listener.
+ * The position is used for calculating the distance attenuation and localization.
+ * The position is specified as a 3D vector.
+ * The unit of the position is determined by the distance factor + * of the 3D listener(set using the CriWare.CriAtomEx3dListener::SetDistanceFactor function).
+ * The default is (0.0f, 0.0f, 0.0f).
+ * Since the position cannot be set on the data, the value set using this function is always used.
+ * To actually apply the set parameters, you need to call the CriWare.CriAtomEx3dListener::Update function. + *
+ * + */ + public void SetPosition(float x, float y, float z) + { + if (this.handle == IntPtr.Zero) + return; + + CriAtomEx.NativeVector position; + position.x = x; + position.y = y; + position.z = z; + criAtomEx3dListener_SetPosition(this.handle, ref position); + } + + /** + * Sets the velocity of the 3D listener + * Velocity along X axis + * Velocity along Y axis + * Velocity along Z axis + * + * Sets the velocity of the 3D listener.
+ * The velocity is used to calculate the Doppler effect.
+ * The velocity is specified as a 3D vector.
+ * The unit of velocity is the distance traveled per second.
+ * The unit of the distance is determined by the distance factor + * of the 3D listener (set using the CriWare.CriAtomEx3dListener::SetDistanceFactor function).
+ * The default is (0.0f, 0.0f, 0.0f).
+ * Since the velocity cannot be set on the data, the value set using this function is always used.
+ * To actually apply the set parameters, you need to call the CriWare.CriAtomEx3dListener::Update function. + *
+ * + */ + public void SetVelocity(float x, float y, float z) + { + if (this.handle == IntPtr.Zero) + return; + + CriAtomEx.NativeVector velocity; + velocity.x = x; + velocity.y = y; + velocity.z = z; + criAtomEx3dListener_SetVelocity(this.handle, ref velocity); + } + + /** + * Sets the orientation of the 3D listener + * Value of the forward vector in the X direction + * Value of the forward vector in the Y direction + * Value of the forward vector in the Z direction + * Value of the upper vector in the X direction + * Value of the upper vector in the Y direction + * Value of the upper vector in the Z direction + * + * Sets the orientation of the 3D listener using the forward and upward vectors.
+ * The orientation is specified using a 3D vector.
+ * The orientation vector that is set is normalized inside the library before being used.
+ * The default values are as follows:
+ * - Forward vector: (0.0f, 0.0f, 1.0f) + * - Upward vector: (0.0f, 1.0f, 0.0f) + * . + * As you cannot set the orientation of the listener on the data, the setting in this function is always used.
+ * To actually apply the set parameters, you need to call the CriWare.CriAtomEx3dListener::Update function. + *
+ * + */ + public void SetOrientation(float fx, float fy, float fz, float ux, float uy, float uz) + { + if (this.handle == IntPtr.Zero) + return; + + CriAtomEx.NativeVector front, top; + front.x = fx; + front.y = fy; + front.z = fz; + top.x = ux; + top.y = uy; + top.z = uz; + criAtomEx3dListener_SetOrientation(this.handle, ref front, ref top); + } + + /** + * \deprecated + * 削除予定の非推奨APIです。 + * CriWareErrorHandler.OnCallback event の使用を検討してください。 + * Sets the distance factor of the 3D listener + * Distance factor + * + * Sets the distance factor of the 3D listener.
+ * This factor is used to calculate the Doppler effect.
+ * For example, if you set distance_factor to 0.1f, the speed 1.0f is treated as 10 meters.
+ * Possible value for distanceFactor is 0 or a value greater than 0.0f. + * The default is 1.0f.
+ * As you cannot set the distance factor of the listener on the data, the setting in this function is always used.
+ * To actually apply the set parameters, you need to call the CriWare.CriAtomEx3dListener::Update function. + *
+ * + */ + [Obsolete("Use SetDopplerMultiplier instead")] + public void SetDistanceFactor(float distanceFactor) + { + if (this.handle == IntPtr.Zero) + return; + + if (distanceFactor < 0f) { + UnityEngine.Debug.LogError("[CRIWARE] Invalid value for distanceFactor. Value >= 0f required."); + } else if (distanceFactor == 0f) { + criAtomEx3dListener_SetDopplerMultiplier(this.handle, 0f); + } else { + criAtomEx3dListener_SetDopplerMultiplier(this.handle, 1.0f / distanceFactor); + } + } + + /** + * Sets the Doppler scale factor of the 3D listener + * Doppler scale factor + * + * Sets the Doppler scale factor of the 3D listener. This scale factor is used to calculate the Doppler effect.
+ * For example, if you set dopplerMultiplier to 10.0f, the Doppler effect will be 10 times more intense than usual.
+ * Possible value for dopplerMultiplier is 0 or a value greater than 0.0f. + * The default is 1.0f.
+ * As you cannot set the Doppler scale value to the listener on the data, the setting in this function is always used.
+ * To actually apply the set parameters, you need to call the CriWare.CriAtomEx3dListener::Update function. + *
+ * + */ + public void SetDopplerMultiplier(float dopplerMultiplier) + { + if (this.handle == IntPtr.Zero) + return; + + if (dopplerMultiplier < 0f) { + UnityEngine.Debug.LogError("[CRIWARE] Invalid value for dopplerMultiplier. Value >= 0f required."); + return; + } + + criAtomEx3dListener_SetDopplerMultiplier(this.handle, dopplerMultiplier); + } + + /** + * Sets the focus point of the 3D listener + * + * Set the focus point of the 3D listener.
+ * When performing the 3D Positioning, + * by setting the focus point, the listener's position and the focus point are connected by a straight line, + * and the microphone can be moved on that line.
+ * For example, by keeping the listener synchronized with the camera and setting the focus point on the position of the main character, + * you can flexibly express/adjust objective and subjective representation depending on the situation.
+ * Unlike the real-world microphone, the microphone that can be moved between the listener's position and the focus point + * has separate distance sensor (for distance attenuation calculation) and orientation sensor (for localization calculation).
+ * By operating these independently, a representation is possible such as + * "I want to focus on the main character, so the distance attenuation should be based on the character position." + * or "I want to match the localization with the screen, so the localization calculation should be based on the camera position"
+ * The default is (0.0f, 0.0f, 0.0f). In situations where the focus level of the distance sensor or orientation sensor is not set, + * it is not necessary to set the focus point. + * In that case, all the 3D Positioning calculations are done based on the listener position as usual.
+ * To actually apply the set parameters, you need to call the CriWare.CriAtomEx3dListener::Update function. + *
+ * + * + * + */ + public void SetFocusPoint(float x, float y, float z) + { + if (this.handle == IntPtr.Zero) + return; + + CriAtomEx.NativeVector focus; + focus.x = x; + focus.y = y; + focus.z = z; + criAtomEx3dListener_SetFocusPoint(this.handle, ref focus); + } + + /** + * Sets the distance sensor focus level + * Distance sensor focus level + * + * Sets the focus level of the distance sensor.
+ * The distance sensor represents the position that is the basis of the distance attenuation calculation among the 3D Positioning calculations. + * It is treated as a microphone that ignores localization and senses only the degree of distance attenuation.
+ * The focus level indicates how close the sensor (microphone) can be to the focus point. + * The sensor (microphone) can be moved on a straight line connecting the listener position and the focus point, + * with 0.0f being the listener position and 1.0f being the same position as the focus point.
+ * For example, by setting the focus level of the distance sensor to 1.0f and the focus level of the direction sensor to 0.0f, + * distance attenuation is applied based on the focus point, and localization is determined based on the listener position.
+ * The default is 0.0f. In the situation where the focus level of the distance sensor or direction sensor is not set, + * all 3D Positioning calculations are done based on the listener position as before.
+ * To actually apply the set parameters, you need to call the CriWare.CriAtomEx3dListener::Update function. + *
+ * + * + * + */ + public void SetDistanceFocusLevel(float distanceFocusLevel) + { + if (this.handle != IntPtr.Zero) + criAtomEx3dListener_SetDistanceFocusLevel(this.handle, distanceFocusLevel); + } + + /** + * Sets the focus level the direction sensor + * The focus level the direction sensor + * + * Sets the focus level of the direction sensor.
+ * The direction sensor represents the position that serves as the reference for localization calculation in the 3D Positioning calculation. + * It is treated as a microphone that ignores distance attenuation and senses only localization.
+ * For the orientation of the direction sensor, the orientation of the listener (set by the SetOrientation function) is used as is.
+ * The focus level indicates how close the sensor (microphone) can be to the focus point. + * The sensor (microphone) can be moved on a straight line connecting the listener position and the focus point, + * with 0.0f being the listener position and 1.0f being the same position as the focus point.
+ * For example, by setting the focus level of the distance sensor to 1.0f and the focus level of the direction sensor to 0.0f, + * distance attenuation is applied based on the focus point, and localization is determined based on the listener position.
+ * The default is 0.0f. In the situation where the focus level of the distance sensor or direction sensor is not set, + * all 3D Positioning calculations are done based on the listener position as before.
+ * To actually apply the set parameters, you need to call the CriWare.CriAtomEx3dListener::Update function. + *
+ * + * + * + */ + public void SetDirectionFocusLevel(float directionFocusLevel) + { + if (this.handle != IntPtr.Zero) + criAtomEx3dListener_SetDirectionFocusLevel(this.handle, directionFocusLevel); + } + + /** + * Sets the 3D region + * + * Sets the 3D region to the 3D listener. + * If the regions set to the 3D sound source and 3D listener set to the same ExPlayer are different,
+ * and if there is no 3D Transceiver that has the same region as the 3D sound source, the sound is muted.
+ * To actually apply the set parameters, you need to call the CriWare.CriAtomEx3dListener::Update function.
+ *
+ * + * + */ + public void Set3dRegion(CriAtomEx3dRegion region3d) + { + if (this.handle == IntPtr.Zero) + return; + + IntPtr region3dHandle = (region3d == null) ? IntPtr.Zero : region3d.nativeHandle; + criAtomEx3dListener_Set3dRegionHn(this.handle, region3dHandle); + } + + #region Internal Members + + ~CriAtomEx3dListener() + { + this.Dispose(false); + } + + private IntPtr handle = IntPtr.Zero; + + #endregion + + #region DLL Import + +#if !CRIWARE_ENABLE_HEADLESS_MODE + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern IntPtr criAtomEx3dListener_Create(ref Config config, IntPtr work, int work_size); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomEx3dListener_Destroy(IntPtr ex_3d_listener); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomEx3dListener_Update(IntPtr ex_3d_listener); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomEx3dListener_ResetParameters(IntPtr ex_3d_listener); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomEx3dListener_SetPosition(IntPtr ex_3d_listener, ref CriAtomEx.NativeVector position); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomEx3dListener_SetVelocity(IntPtr ex_3d_listener, ref CriAtomEx.NativeVector velocity); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomEx3dListener_SetOrientation(IntPtr ex_3d_listener, ref CriAtomEx.NativeVector front, ref CriAtomEx.NativeVector top); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomEx3dListener_SetDistanceFactor(IntPtr ex_3d_listener, float distance_factor); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomEx3dListener_SetDopplerMultiplier(IntPtr ex_3d_listener, float doppler_multiplier); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomEx3dListener_SetFocusPoint(IntPtr ex_3d_listener, ref CriAtomEx.NativeVector focus_point); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomEx3dListener_SetDistanceFocusLevel(IntPtr ex_3d_listener, float distance_focus_level); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomEx3dListener_SetDirectionFocusLevel(IntPtr ex_3d_listener, float direction_focus_level); +#else + private static IntPtr criAtomEx3dListener_Create(ref Config config, IntPtr work, int work_size) { return IntPtr.Zero; } + private static void criAtomEx3dListener_Destroy(IntPtr ex_3d_listener) { } + private static void criAtomEx3dListener_Update(IntPtr ex_3d_listener) { } + private static void criAtomEx3dListener_ResetParameters(IntPtr ex_3d_listener) { } + private static void criAtomEx3dListener_SetPosition(IntPtr ex_3d_listener, ref CriAtomEx.NativeVector position) { } + private static void criAtomEx3dListener_SetVelocity(IntPtr ex_3d_listener, ref CriAtomEx.NativeVector velocity) { } + private static void criAtomEx3dListener_SetOrientation(IntPtr ex_3d_listener, ref CriAtomEx.NativeVector front, ref CriAtomEx.NativeVector top) { } + private static void criAtomEx3dListener_SetDistanceFactor(IntPtr ex_3d_listener, float distance_factor) { } + private static void criAtomEx3dListener_SetDopplerMultiplier(IntPtr ex_3d_listener, float doppler_multiplier) { } + private static void criAtomEx3dListener_SetFocusPoint(IntPtr ex_3d_listener, ref CriAtomEx.NativeVector focus_point) { } + private static void criAtomEx3dListener_SetDistanceFocusLevel(IntPtr ex_3d_listener, float distance_focus_level) { } + private static void criAtomEx3dListener_SetDirectionFocusLevel(IntPtr ex_3d_listener, float direction_focus_level) { } +#endif + +#if !CRIWARE_ENABLE_HEADLESS_MODE && CRIWARE_TRANSCEIVER_N_ELEVATIONANGLEAISAC_SUPPORT + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomEx3dListener_Set3dRegionHn(IntPtr ex_3d_listener, IntPtr ex_3d_region); +#else + private static void criAtomEx3dListener_Set3dRegionHn(IntPtr ex_3d_listener, IntPtr ex_3d_region) { } +#endif + + #endregion +} + +} //namespace CriWare +/** + * @} + */ + +/* --- end of file --- */ diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomEx3dListener.cs.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomEx3dListener.cs.meta new file mode 100644 index 0000000..2360fbf --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomEx3dListener.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 3e467ebe1db55bf459a3171036fef5ce +timeCreated: 1433816076 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomEx3dSource.cs b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomEx3dSource.cs new file mode 100644 index 0000000..6109971 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomEx3dSource.cs @@ -0,0 +1,703 @@ +/**************************************************************************** + * + * Copyright (c) 2011 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +#if !UNITY_WEBGL + #define CRIWARE_TRANSCEIVER_N_ELEVATIONANGLEAISAC_SUPPORT +#endif + +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using System.Text; +using UnityEngine; + +/*========================================================================== + * CRI Atom Native Wrapper + *=========================================================================*/ +/** + * \addtogroup CRIATOM_NATIVE_WRAPPER + * @{ + */ + +namespace CriWare { + +/** + * 3D sound source object + * + * An object for handling the 3D sound source.
+ * Used for 3D Positioning.
+ *
+ * You set the parameters and position information of the 3D sound source through the 3D sound source object.
+ *
+ */ +public class CriAtomEx3dSource : CriDisposable +{ + /** + * Structure for 3D sound source configuration + * + * This is the structure that contains the settings related to the initialization of the 3D sound source.
+ *
+ */ + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + public struct Config { + public bool enableVoicePriorityDecay; /**< Whether to enable voice priority attenuation according to distance */ + public uint randomPositionListMaxLength; /**< Gets the maximum number of elements that can be in the coordinates list used for position randomization of a 3D sound source */ + + public Config(bool enableVoicePriorityDecay, uint randomPositionListMaxLength) { + this.enableVoicePriorityDecay = enableVoicePriorityDecay; + this.randomPositionListMaxLength = randomPositionListMaxLength; + } + } + + private uint currentRandomPositionListMaxLength = 0; + + /** + * Creates a 3D sound source object + * Enables voice priority attenuation according to the distance + * Gets the maximum number of elements that can be in the coordinates list used for position randomization of a 3D sound source + * + * Create a 3D sound source object based on the config for creating a 3D sound source object.
+ * The library must be initialized before calling this function.
+ *
+ */ + public CriAtomEx3dSource(bool enableVoicePriorityDecay = false, uint randomPositionListMaxLength = 0) + { + Config config = new Config(enableVoicePriorityDecay, randomPositionListMaxLength); + this.handle = criAtomEx3dSource_Create(ref config, IntPtr.Zero, 0); + CriDisposableObjectManager.Register(this, CriDisposableObjectManager.ModuleType.Atom); + this.currentRandomPositionListMaxLength = randomPositionListMaxLength; + } + + /** + * Discards a 3D sound source object + * + * Discards a 3D source object.
+ * When this function is called, all the resources allocated in the DLL when creating the 3D sound source object are released.
+ * If there are any sounds being played by an AtomExPlayer with the 3D sound source object set, + * either stop those sounds or discard the AtomExPlayer before calling this function.
+ *
+ */ + public override void Dispose() + { + this.Dispose(true); + } + + private void Dispose(bool disposing) + { + CriDisposableObjectManager.Unregister(this); + + if (this.handle != IntPtr.Zero) { + criAtomEx3dSource_Destroy(this.handle); + this.handle = IntPtr.Zero; + } + + if (disposing) { + GC.SuppressFinalize(this); + } + } + + public IntPtr nativeHandle + { + get {return this.handle;} + } + + /** + * Updates the 3D sound source + * + * Updates the 3D sound source using the parameters set to the 3D sound source.
+ * This function updates all the parameters set to the 3D sound source.
+ * It is more efficient to change multiple parameters before performing update + * than to update using this function each time a parameter is changed.
+ * This function runs independently of the parameter update in the AtomExPlayer + * ( CriWare.CriAtomExPlayer::UpdateAll , CriAtomExPlayer::Update ).
+ * When you change the parameter of the 3D sound source, perform the update process using this function.
+ *
+ * + * : + * // 音源の作成 + * CriAtomEx3dSource source = new CriAtomEx3dSource(); + * : + * // 音源の位置を設定 + * source.SetPosition(0.0f, 0.0f, 1.0f); + * + * // 音源の速度を設定 + * source.SetVelocity(1.0f, 0.0f, 0.0f); + * + * // 注意)この時点では音源の位置や速度はまだ変更されていません。 + * + * // 変更の適用 + * source.Update(); + * : + * + */ + public void Update() + { + criAtomEx3dSource_Update(this.handle); + } + + /** + * Initializes 3D sound source parameters + * + * Clears the parameters set to the 3D sound source and restores the initial values.
+ * To actually apply the cleared parameters, you need to call the CriWare.CriAtomEx3dSource::Update function. + *
+ * + */ + public void ResetParameters() + { + criAtomEx3dSource_ResetParameters(this.handle); + } + + /** + * Sets the position of the 3D sound source + * X coordinate + * Y coordinate + * Z coordinate + * + * Sets the position of the 3D sound source.
+ * The position is used for calculating the distance attenuation and localization.
+ * The position is specified as a 3D vector.
+ * The unit of the position is determined by the distance factor + * of the 3D listener (set using the CriWare.CriAtomEx3dListener::SetDistanceFactor function).
+ * The default is (0.0f, 0.0f, 0.0f).
+ * Since the position cannot be set on the data, the value set using this function is always used.
+ * To actually apply the set parameters, you need to call the CriWare.CriAtomEx3dSource::Update function. + *
+ * + */ + public void SetPosition(float x, float y, float z) + { + CriAtomEx.NativeVector position; + position.x = x; + position.y = y; + position.z = z; + criAtomEx3dSource_SetPosition(this.handle, ref position); + } + + /** + * Sets the velocity of the 3D sound source + * Velocity along X axis + * Velocity along Y axis + * Velocity along Z axis + * + * Sets the velocity of the 3D sound source.
+ * The velocity is used to calculate the Doppler effect.
+ * The velocity is specified as a 3D vector.
+ * The unit of velocity is the distance traveled per second.
+ * The unit of the distance is determined by the distance factor + * of the 3D listener (set using the CriWare.CriAtomEx3dListener::SetDistanceFactor function). + * The default is (0.0f, 0.0f, 0.0f).
+ * Since the velocity cannot be set on the data, the value set using this function is always used.
+ * To actually apply the set parameters, you need to call the CriWare.CriAtomEx3dSource::Update function. + *
+ * + */ + public void SetVelocity(float x, float y, float z) + { + CriAtomEx.NativeVector velocity; + velocity.x = x; + velocity.y = y; + velocity.z = z; + criAtomEx3dSource_SetVelocity(this.handle, ref velocity); + } + + /** + * Sets the orientation of the 3D sound source + * Forward vector + * Upper vector + * + * Sets the orientation of the 3D sound source.
+ * The orientation is determined by a sound cone.
+ * The sound cone represents the direction in which the sound is emitted from the sound source. It is used to express the directivity of the sound.
+ * The orientation of the sound cone is specified by a 3D vector. The orientation vector is then normalized and used by the library internally.
+ * Since the direction of the sound cone cannot be set on the data side, calling this function is necessary to set the orientation.
+ * The default values are as follows.
+ * - Forward vector: (0.0f, 0.0f, 1.0f)
+ * - Upper vector: (0.0f, 1.0f, 0.0f)
+ * If you set the orientation of the sound cone, the upper vector is ignored and only the forward vector is used.
+ * Also, if you are using Ambisonics playback, Ambisonics will rotate according to the orientation specified by this function and the orientation of the listener.
+ * You must call the CriWare.CriAtomEx3dSource::Update function to actually apply the parameters you have set.
+ * Please note that sound cones cannot be applied to Ambisonics.
+ *
+ * + * + */ + public void SetOrientation(Vector3 front, Vector3 top) + { + CriAtomEx.NativeVector src_front; + src_front.x = front.x; + src_front.y = front.y; + src_front.z = front.z; + CriAtomEx.NativeVector src_top; + src_top.x = top.x; + src_top.y = top.y; + src_top.z = top.z; + criAtomEx3dSource_SetOrientation(this.handle, ref src_front, ref src_top); + } + + + /** + * \deprecated + * 削除予定の非推奨APIです。 + * CriAtomEx3dSource.SetOrientationの使用を検討してください。 + * Sets the orientation of the sound cone of the 3D sound source + * Value in X direction + * Value in Y direction + * Value in Z direction + * + * Sets the orientation of the sound cone of the 3D sound source.
+ * The sound cone represents the direction in which sound is emitted from a sound source and is used to express the directionality of the sound.
+ * The orientation of the sound cone is specified using a 3D vector.
+ * The orientation vector that is set is normalized inside the library before being used.
+ * The default is (0.0f, 0.0f, -1.0f).
+ * As you cannot set the orientation of the sound cone on the data, the setting in this function is always used.
+ * To actually apply the set parameters, you need to call the CriWare.CriAtomEx3dSource::Update function. + *
+ * + * + */ + [Obsolete("Use CriAtomEx3dSource.SetOrientation instead")] + public void SetConeOrientation(float x, float y, float z) + { + CriAtomEx.NativeVector coneOrientation; + coneOrientation.x = x; + coneOrientation.y = y; + coneOrientation.z = z; + criAtomEx3dSource_SetConeOrientation(this.handle, ref coneOrientation); + } + + /** + * Sets the sound cone parameters of the 3D sound source + * Sound cone inside angle + * Sound cone outside angle + * Sound cone outside volume + * + * Sets the sound cone parameters of the 3D sound source.
+ * The sound cone represents the direction in which sound is emitted from a sound source and is used to express the directionality of the sound.
+ * The sound cone consists of inner cone and outer cone. The inside angle represents the angle of the inner cone, + * the outside angle represents the angle of the outer cone, and the outside volume represents the volume + * beyond the outer cone angle.
+ * At angles smaller than the inner cone angle, no attenuation is applied by the cone. + * In the direction between the inner and outer cones, the sound is gradually attenuated to the outside volume.
+ * The inside and outside angles are specified within the range of 0.0f to 360.0f.
+ * The outside volume is specifies as a scale factor for the amplitude within the range of 0.0f to 1.0f (the unit is not decibel).
+ * The default values when initializing the library are as follows, and no attenuation is applied by the cone.
+ * - Inside angle: 360.0f + * - Outside angle: 360.0f + * - Outside volume: 0.0f + * . + * If this function is called when the sound cone parameters are set on the data, the following settings are applied:
+ * - Inside angle: Addition + * - Outside angle: Addition + * - Outside volume: Multiplication + * .
+ * To actually apply the set parameters, you need to call the CriWare.CriAtomEx3dSource::Update function. + *
+ * + */ + public void SetConeParameter(float insideAngle, float outsideAngle, float outsideVolume) + { + criAtomEx3dSource_SetConeParameter(this.handle, insideAngle, outsideAngle, outsideVolume); + } + + /** + * Sets the minimum/maximum distances of the 3D sound source + * Minimum distance + * Maximum distance + * + * Sets the minimum/maximum distances of the 3D sound source.
+ * The minimum distance represents the distance at which the volume cannot be increased any further.
+ * The maximum distance is the distance with the lowest volume.
+ * The unit of the distance is determined by the distance factor + * of the 3D listener (set using the CriWare.CriAtomEx3dListener::SetDistanceFactor function).
+ * The default values when the library is initialized are as follows:
+ * - Minimum distance: 0.0f + * - Maximum distance: 0.0f + * . + * When this function is called when the minimum/maximum distances are set on the data, + * the values on the data are overridden (ignored).
+ * To actually apply the set parameters, you need to call the CriWare.CriAtomEx3dSource::Update function. + *
+ * + */ + public void SetMinMaxDistance(float minDistance, float maxDistance) + { + criAtomEx3dSource_SetMinMaxAttenuationDistance(this.handle, minDistance, maxDistance); + } + + /** + * Sets the interior Panning boundary distance of the 3D sound source + * 3D sound source radius + * Interior distance + * + * Sets the interior Panning boundary distance of the 3D sound source.
+ * The radius of the 3D sound source is the radius when the 3D sound source is considered as a sphere.
+ * Interior distance is the distance from the radius of the 3D sound source to which the interior Panning is applied.
+ * Within the radius of the 3D sound source, interior Panning is applied, but since the interior distance is treated as 0.0, + * the sound is played back from all speakers at the same volume.
+ * Within the interior distance, interior Panning is applied.
+ * Outside the interior distance, interior Panning is not applied and the sound is played from 1 + * or 2 speakers closest to the sound source position.
+ * By default, the 3D sound source radius is set to 0.0f, and interior distance is set to 0.0f (depending on the minimum distance of the 3D sound source).
+ * To actually apply the set parameters, you need to call the CriWare.CriAtomEx3dSource::Update function. + *
+ * + * + */ + public void SetInteriorPanField(float sourceRadius, float interiorDistance) + { + criAtomEx3dSource_SetInteriorPanField(this.handle, sourceRadius, interiorDistance); + } + + /** + * Sets the Doppler coefficient of the 3D sound source + * Doppler coefficient + * + * Set the Doppler coefficient of the 3D sound source.
+ * The Doppler coefficient specifies the scale factor for exaggerating the Doppler effect + * calculated when the sound velocity of 340m/s.
+ * For example, if you specify 2.0f, the pitch is multiplied by 2 if the velocity of the sound is 340m/s.
+ * If you specify 0.0f, the Doppler effect is disabled.
+ * The default value when the library is initialized is 0.0f.
+ * When this function is called when the Doppler coefficient is set on the data, + * the value on the data is overridden (ignored).
+ * To actually apply the set parameters, you need to call the CriWare.CriAtomEx3dSource::Update function. + *
+ * + */ + public void SetDopplerFactor(float dopplerFactor) + { + criAtomEx3dSource_SetDopplerFactor(this.handle, dopplerFactor); + } + + /** + * Sets the volume of the 3D sound source + * Volume + * + * Sets the volume of the 3D sound source.
+ * The volume of the 3D sound source affects only the volume related to localization (L,R,SL,SR), + * and does not affect the output level of LFE or the center.
+ * For the volume value, specify a real value in the range of 0.0f to 1.0f.
+ * The volume value is a scale factor for the amplitude of the sound data (the unit is not decibel).
+ * For example, if you specify 1.0f, the original sound is played at its unmodified volume.
+ * If you specify 0.5f, the sound is played at the volume by halving the amplitude (-6dB) + * of the original waveform.
+ * If you specify 0.0f, the sound is muted (silent).
+ * The default value when the library is initialized is 1.0f.
+ * When this function is called when the volume of the 3D sound source is set on the data, + * the value on the data is multiplied by this value.
+ * To actually apply the set parameters, you need to call the CriWare.CriAtomEx3dSource::Update function. + *
+ * + */ + public void SetVolume(float volume) + { + criAtomEx3dSource_SetVolume(this.handle, volume); + } + + /** + * Sets the maximum amount of change in angle AISAC control value + * Maximum amount of change in angle AISAC control value + * + * Sets the maximum amount of change when the AISAC control value is changed by the angle AISAC.
+ * By changing the maximum amount of change to a lower value, the change of the AISAC control value by + * angle AISAC can be made smooth even if the relative angle between the sound source and the listener changes abruptly.
+ * For example, if (0.5f / 30.0f) is set, the change takes place over 30 frames + * when the angle changes from 0° to 180°.
+ * The default value is 1.0f (no limit).
+ * Since this parameter cannot be set on the data, the value set using this function is always used.
+ * To actually apply the set parameters, + * you need to call the CriWare.CriAtomEx3dSource::Update function.
+ * The maximum amount of change set by this function is applied + * only to the change of the angle AISAC control value calculated based on the localization angle. It does not affect the localization angle itself.
+ *
+ * + */ + public void SetMaxAngleAisacDelta(float maxDelta) + { + criAtomEx3dSource_SetMaxAngleAisacDelta(this.handle, maxDelta); + } + + /** + * Sets the distance attenuation + * Whether to enable the distance attenuation (True: enable, False: disable) + * + * Sets whether to enable or disable the volume variation by distance attenuation.
+ * The default is True (enabled).
+ * To actually apply the set parameters, you need to call the CriWare.CriAtomEx3dSource::Update function.
+ *
+ * + * + */ + public void SetAttenuationDistanceSetting(bool flag) + { + criAtomEx3dSource_SetAttenuationDistanceSetting(this.handle, flag); + } + + /** + * Gets distance attenuation settings + * Distance attenuation setting (True: enable, False: disable) + * + * Gets whether the volume variation by distance attenuation is enabled or disabled.
+ * The default is True (enabled).
+ *
+ * + */ + public bool GetAttenuationDistanceSetting() + { + return criAtomEx3dSource_GetAttenuationDistanceSetting(this.handle); + } + + /** + * Settings related to position randomization of 3D sound sources + * Config structure (nullable) used to randomize the positions of the 3D sound sources. + * + * Assigns the randomized position to the 3D sound source handle. + * Once this function is executed, the position of the voice will change randomly according to the original position information and settings.
+ * You can clear the settings by specifying null for the argument config.
+ * You must call the CriWare.CriAtomEx3dSource::Update function to actually apply the parameters you have set.
+ * This function does not affect the audio currently being played.
+ * The new parameters will be applied from the next audio playback.
+ *
+ * + */ + public void SetRandomPositionConfig(CriAtomEx.Randomize3dConfig? config) + { + if (config.HasValue) { + if (config.Value.CalculationType == CriAtomEx.Randomize3dCalcType.None) { + criAtomEx3dSource_SetRandomPositionConfig(this.handle, IntPtr.Zero); + } else { + var tempConfig = config.Value; + criAtomEx3dSource_SetRandomPositionConfig(this.handle, ref tempConfig); + } + } else { + criAtomEx3dSource_SetRandomPositionConfig(this.handle, IntPtr.Zero); + } + } + + /** + * Sets the list of coordinates to be used to randomize the position of a 3D sound source + * Position coordinates list + * + * Specifies a list of possible coordinates.
+ * When the randomization of the 3D sound source's position is enabled, the coordinates will be randomly picked from that list.
+ * This parameter is referenced only when CriWare.CriAtomEx::Randomize3dCalcType::List
+ * is set as the calculation method for the coordinates.
+ * If any other calculation method is set, this parameter will be ignored.
+ * You must call the CriWare.CriAtomEx3dSource::Update function to actually apply the parameters you have set.
+ * The area passed to this function will no longer be referenced after the execution of the
+ * CriWare.CriAtomEx3dSource::SetRandomPositionList function is completed.
+ * Instead, the list of the coordinates will be saved internally.
+ * Therefore, setting a list whose length exceeds
+ * CriWare.CriAtomEx3dSource::Config::randomPositionListMaxLength will result in an error.
+ *
+ * + * + */ + public void SetRandomPositionList(Vector3[] positionList) + { + if (this.currentRandomPositionListMaxLength == 0) { + Debug.LogError("[CRIWARE] The maxmium amount of random positions is set to 0. List will not be set."); + return; + } + if (positionList.Length > this.currentRandomPositionListMaxLength) { + Debug.LogError("[CRIWARE] Input list of positions is longer than maxmium length setting. List will not be set."); + return; + } + + CriAtomEx.NativeVector[] nativeList = new CriAtomEx.NativeVector[positionList.Length]; + for(int i = 0; i < positionList.Length; ++i) { + nativeList[i] = new CriAtomEx.NativeVector(positionList[i]); + } + criAtomEx3dSource_SetRandomPositionList(this.handle, nativeList, (uint)positionList.Length); + } + + /** + * Sets the 3D region + * + * Set the 3D regions to the 3D sound source. + * If the regions set to the 3D sound source and 3D listener set to the same ExPlayer are different,
+ * and if there is no 3D Transceiver that has the same region as the 3D sound source, the sound is muted.
+ * To actually apply the set parameters, you need to call the CriWare.CriAtomEx3dSource::Update function.
+ *
+ * + * + */ + public void Set3dRegion(CriAtomEx3dRegion region3d) + { + IntPtr region3dHandle = (region3d == null) ? IntPtr.Zero : region3d.nativeHandle; + criAtomEx3dSource_Set3dRegionHn(this.handle, region3dHandle); + } + + /** + * Sets the listener reference elevation AISAC control setting ID + * Listener reference elevation AISAC control ID + * + * Specifies the AISAC control ID linked to the elevation of the sound source seen from the listener.
+ * The listener reference elevation AISAC control ID set on the data is overridden by this function.
+ * To actually apply the set parameters, you need to call the CriWare.CriAtomEx3dSource::Update function. + *
+ * + */ + public void SetListenerBasedElevationAngleAisacControlId(ushort aisacControlId) + { + criAtomEx3dSource_SetListenerBasedElevationAngleAisacControlId(this.handle, aisacControlId); + } + + /** + * Sets the sound source reference azimuth AISAC control ID + * Sound source reference azimuth AISAC control ID + * + * Specifies the AISAC control ID linked to the azimuth of the listener as seen from the sound source.
+ * The sound source reference azimuth AISAC control ID set on the data is overridden by this function.
+ * To actually apply the set parameters, you need to call the CriWare.CriAtomEx3dSource::Update function. + *
+ * + */ + public void SetSourceBasedElevationAngleAisacControlId(ushort aisacControlId) + { + criAtomEx3dSource_SetSourceBasedElevationAngleAisacControlId(this.handle, aisacControlId); + } + + /** + * Sets the Distance AISAC Control ID + * Sound source reference azimuth AISAC control ID + * + * Specifies the AISAC control ID to be linked to the distance attenuation between the minimum and maximum distances.
+ * If an AISAC control ID is set with this function, the default distance attenuation is disabled.
+ * The distance AISAC control ID set on the data side is overridden by this function.
+ * To actually apply parameter changes, it is necessary to call the CriAtomEx3dSource.Update function.
+ * When this function is executed, any previous changes due to the AISAC control ID set to the 3D sound source will be invalidated,
+ * while the parameters changes previously applied to the audio being played will stay unchanged.
+ * Therefore, it is recommended to execute this function when no audio associated with the specified 3D sound source is being played.
+ *
+ * + */ + public void SetDistanceAisacControlId(ushort aisacControlId) + { + criAtomEx3dSource_SetDistanceAisacControlId(this.handle, aisacControlId); + } + + #region Internal Members + + ~CriAtomEx3dSource() + { + this.Dispose(false); + } + + private IntPtr handle = IntPtr.Zero; + + #endregion + + #region DLL Import + +#if !CRIWARE_ENABLE_HEADLESS_MODE + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern IntPtr criAtomEx3dSource_Create(ref Config config, IntPtr work, int work_size); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomEx3dSource_Destroy(IntPtr ex_3d_source); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomEx3dSource_Update(IntPtr ex_3d_source); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomEx3dSource_ResetParameters(IntPtr ex_3d_source); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomEx3dSource_SetPosition(IntPtr ex_3d_source, ref CriAtomEx.NativeVector position); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomEx3dSource_SetVelocity(IntPtr ex_3d_source, ref CriAtomEx.NativeVector velocity); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomEx3dSource_SetOrientation(IntPtr ex_3d_source, ref CriAtomEx.NativeVector front, ref CriAtomEx.NativeVector top); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomEx3dSource_SetConeOrientation(IntPtr ex_3d_source, ref CriAtomEx.NativeVector cone_orient); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomEx3dSource_SetConeParameter(IntPtr ex_3d_source, float inside_angle, float outside_angle, float outside_volume); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomEx3dSource_SetMinMaxAttenuationDistance(IntPtr ex_3d_source, float min_distance, float max_distance); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomEx3dSource_SetInteriorPanField(IntPtr ex_3d_source, float source_radius, float interior_distance); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomEx3dSource_SetDopplerFactor(IntPtr ex_3d_source, float doppler_factor); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomEx3dSource_SetVolume(IntPtr ex_3d_source, float volume); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomEx3dSource_SetMaxAngleAisacDelta(IntPtr ex_3d_source, float max_delta); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomEx3dSource_SetAttenuationDistanceSetting(IntPtr ex_3d_source, bool flag); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool criAtomEx3dSource_GetAttenuationDistanceSetting(IntPtr ex_3d_source); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomEx3dSource_SetRandomPositionConfig(IntPtr ex_3d_source, ref CriAtomEx.Randomize3dConfig config); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomEx3dSource_SetRandomPositionConfig(IntPtr ex_3d_source, IntPtr config); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomEx3dSource_SetRandomPositionList(IntPtr ex_3d_source, CriAtomEx.NativeVector[] position_list, uint length); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomEx3dSource_SetDistanceAisacControlId(IntPtr ex_3d_source, ushort aisac_control_id); +#else + private static IntPtr criAtomEx3dSource_Create(ref Config config, IntPtr work, int work_size) { return IntPtr.Zero; } + private static void criAtomEx3dSource_Destroy(IntPtr ex_3d_source) { } + private static void criAtomEx3dSource_Update(IntPtr ex_3d_source) { } + private static void criAtomEx3dSource_ResetParameters(IntPtr ex_3d_source) { } + private static void criAtomEx3dSource_SetPosition(IntPtr ex_3d_source, ref CriAtomEx.NativeVector position) { } + private static void criAtomEx3dSource_SetVelocity(IntPtr ex_3d_source, ref CriAtomEx.NativeVector velocity) { } + private static void criAtomEx3dSource_SetOrientation(IntPtr ex_3d_source, ref CriAtomEx.NativeVector front, ref CriAtomEx.NativeVector top) { } + private static void criAtomEx3dSource_SetConeOrientation(IntPtr ex_3d_source, ref CriAtomEx.NativeVector cone_orient) { } + private static void criAtomEx3dSource_SetConeParameter(IntPtr ex_3d_source, float inside_angle, float outside_angle, float outside_volume) { } + private static void criAtomEx3dSource_SetMinMaxAttenuationDistance(IntPtr ex_3d_source, float min_distance, float max_distance) { } + private static void criAtomEx3dSource_SetInteriorPanField(IntPtr ex_3d_source, float source_radius, float interior_distance) { } + private static void criAtomEx3dSource_SetDopplerFactor(IntPtr ex_3d_source, float doppler_factor) { } + private static void criAtomEx3dSource_SetVolume(IntPtr ex_3d_source, float volume) { } + private static void criAtomEx3dSource_SetMaxAngleAisacDelta(IntPtr ex_3d_source, float max_delta) { } + private static void criAtomEx3dSource_SetAttenuationDistanceSetting(IntPtr ex_3d_source, bool flag) { } + private static bool criAtomEx3dSource_GetAttenuationDistanceSetting(IntPtr ex_3d_source) { return false; } + private static void criAtomEx3dSource_SetRandomPositionConfig(IntPtr ex_3d_source, ref CriAtomEx.Randomize3dConfig config) { } + private static void criAtomEx3dSource_SetRandomPositionConfig(IntPtr ex_3d_source, IntPtr config) { } + private static void criAtomEx3dSource_SetRandomPositionList(IntPtr ex_3d_source, CriAtomEx.NativeVector[] position_list, uint length) { } + private static void criAtomEx3dSource_SetDistanceAisacControlId(IntPtr ex_3d_source, ushort aisac_control_id) { } +#endif + +#if !CRIWARE_ENABLE_HEADLESS_MODE && CRIWARE_TRANSCEIVER_N_ELEVATIONANGLEAISAC_SUPPORT + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomEx3dSource_Set3dRegionHn(IntPtr ex_3d_source, IntPtr ex_3d_region); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomEx3dSource_SetListenerBasedElevationAngleAisacControlId(IntPtr ex_3d_source, ushort aisac_control_id); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomEx3dSource_SetSourceBasedElevationAngleAisacControlId(IntPtr ex_3d_source, ushort aisac_control_id); +#else + private static void criAtomEx3dSource_Set3dRegionHn(IntPtr ex_3d_source, IntPtr ex_3d_region) { } + private static void criAtomEx3dSource_SetListenerBasedElevationAngleAisacControlId(IntPtr ex_3d_source, ushort aisac_control_id) { } + private static void criAtomEx3dSource_SetSourceBasedElevationAngleAisacControlId(IntPtr ex_3d_source, ushort aisac_control_id) { } +#endif + + #endregion +} + +} //namespace CriWare +/** + * @} + */ + +/* --- end of file --- */ diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomEx3dSource.cs.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomEx3dSource.cs.meta new file mode 100644 index 0000000..f270611 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomEx3dSource.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: e1fe1761e05a5a041ad9ccc3046d2019 +timeCreated: 1433816077 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomEx3dTransceiver.cs b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomEx3dTransceiver.cs new file mode 100644 index 0000000..5455460 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomEx3dTransceiver.cs @@ -0,0 +1,671 @@ +/**************************************************************************** + * + * Copyright (c) 2020 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +#if !UNITY_WEBGL + #define CRIWARE_TRANSCEIVER_N_ELEVATIONANGLEAISAC_SUPPORT +#endif + +using System; +using System.Runtime.InteropServices; +using UnityEngine; + +/*========================================================================== + * CRI Atom Native Wrapper + *=========================================================================*/ +/** + * \addtogroup CRIATOM_NATIVE_WRAPPER + * @{ + */ + +namespace CriWare { + +/** + * 3D Transceiver object + * + * An object for handling the 3D Transceivers.
+ *
+ * You set the parameters or location information of the 3D Transceiver through this object.
+ *
+ */ +public class CriAtomEx3dTransceiver : CriDisposable +{ + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + public struct Config + { + public int reserved; + } + + /** + * Creates a 3D Transceiver object + * + * Creates a 3D Transceiver.
+ * The library must be initialized before calling this function.
+ *
+ */ + public CriAtomEx3dTransceiver() + { + Config config = new Config(); + this.handle = UnsafeNativeMethods.criAtomEx3dTransceiver_Create(ref config, IntPtr.Zero, 0); + CriDisposableObjectManager.Register(this, CriDisposableObjectManager.ModuleType.Atom); + } + + /** + * Discards a 3D Transceiver object + * + * Discards the 3D Transceiver object.
+ * When this function is called, all the resources allocated in the DLL when creating the 3D Transceiver object are released,
+ * and the 3D Transceiver is disabled.
+ *
+ */ + public override void Dispose() + { + this.Dispose(true); + } + + private void Dispose(bool disposing) + { + CriDisposableObjectManager.Unregister(this); + + if (this.handle != IntPtr.Zero) { + UnsafeNativeMethods.criAtomEx3dTransceiver_Destroy(this.handle); + this.handle = IntPtr.Zero; + } + + if (disposing) { + GC.SuppressFinalize(this); + } + } + + public IntPtr nativeHandle + { + get { return this.handle; } + } + + /** + * Updates the 3D Transceiver + * + * Updates the 3D Transceiver using the parameters set for the 3D Transceiver.
+ * This function updates all the parameters set in the 3D Transceiver.
+ * It is more efficient to change multiple parameters before performing update + * than to update using this function each time a parameter is changed.
+ * This function runs independently of the parameter update in the AtomExPlayer + * ( CriWare.CriAtomExPlayer::UpdateAll , CriAtomExPlayer::Update ).
+ * If you change the parameters of the 3D transceiver, perform the update process using this function.
+ *
+ * + * : + * // トランシーバーの作成 + * CriAtomEx3dTransceiver transceiver = new CriAtomEx3dTransceiver(); + * : + * // トランシーバーの入力位置を設定 + * transceiver.SetInputPosition(Vector3.zero); + * + * // トランシーバーの出力位置を設定 + * transceiver.SetOutputPosition(Vector3.zero); + * + * // 注意)この時点ではトランシーバーの位置はまだ変更されていません。 + * + * // 変更の適用 + * transceiver.Update(); + * : + * + */ + public void Update() + { + UnsafeNativeMethods.criAtomEx3dTransceiver_Update(this.handle); + } + + /** + * Sets the position of the 3D Transceiver input + * Input position vector + * + * Sets the position of the 3D Transceiver input.
+ * The position is used for calculating the distance attenuation and localization.
+ * The position is specified as a 3D vector.
+ * The default is (0.0f, 0.0f, 0.0f).
+ * To actually apply the set parameters, you need to call the CriWare.CriAtomEx3dTransceiver::Update function. + *
+ * + */ + public void SetInputPosition(Vector3 position) + { + CriAtomEx.NativeVector pos = new CriAtomEx.NativeVector(position); + UnsafeNativeMethods.criAtomEx3dTransceiver_SetInputPosition(this.handle, ref pos); + } + + /** + * Sets the position of the 3D Transceiver output + * Output position vector + * + * Sets the position of the 3D Transceiver output.
+ * The position is used for calculating the distance attenuation and localization.
+ * The position is specified as a 3D vector.
+ * The default is (0.0f, 0.0f, 0.0f).
+ * To actually apply the set parameters, you need to call the CriWare.CriAtomEx3dTransceiver::Update function. + *
+ * + */ + public void SetOutputPosition(Vector3 position) + { + CriAtomEx.NativeVector pos = new CriAtomEx.NativeVector(position); + UnsafeNativeMethods.criAtomEx3dTransceiver_SetOutputPosition(this.handle, ref pos); + } + + /** + * Sets the orientation of the 3D Transceiver input + * Forward vector + * Upper vector + * + * Sets the orientation of the 3D Transceiver using the forward and upward vectors.
+ * The orientation is specified using a 3D vector. The orientation vector that is set is normalized inside the library before being used.
+ * The default values are as follows:
+ * - Forward vector: (0.0f, 0.0f, 1.0f) + * - Upward vector: (0.0f, 1.0f, 0.0f)
+ * To actually apply the set parameters, you need to call the CriWare.CriAtomEx3dTransceiver::Update function. + *
+ * + */ + public void SetInputOrientation(Vector3 front, Vector3 top) + { + CriAtomEx.NativeVector orient_front = new CriAtomEx.NativeVector(front); + CriAtomEx.NativeVector orient_top = new CriAtomEx.NativeVector(top); + UnsafeNativeMethods.criAtomEx3dTransceiver_SetInputOrientation(this.handle, ref orient_front, ref orient_top); + } + + /** + * Sets the orientation of the 3D Transceiver output + * Forward vector + * Upper vector + * + * Sets the orientation of the 3D Transceiver using the forward and upward vectors.
+ * The orientation is specified using a 3D vector. The orientation vector that is set is normalized inside the library before being used.
+ * The default values are as follows:
+ * - Forward vector: (0.0f, 0.0f, 1.0f) + * - Upward vector: (0.0f, 1.0f, 0.0f)
+ * To actually apply the set parameters, you need to call the CriWare.CriAtomEx3dTransceiver::Update function. + *
+ * + */ + public void SetOutputOrientation(Vector3 front, Vector3 top) + { + CriAtomEx.NativeVector orient_front = new CriAtomEx.NativeVector(front); + CriAtomEx.NativeVector orient_top = new CriAtomEx.NativeVector(top); + UnsafeNativeMethods.criAtomEx3dTransceiver_SetOutputOrientation(this.handle, ref orient_front, ref orient_top); + } + + /** + * Sets the sound cone parameters for the 3D Transceiver output + * Sound cone inside angle + * Sound cone outside angle + * Sound cone outside volume + * + * Sets the sound cone parameters for the 3D Transceiver output.
+ * The sound cone represents the direction in which the sound is emitted from the transceiver and is used to express the directionality of the sound.
+ * The sound cone consists of inner cone and outer cone. The inside angle represents the angle of the inner cone, + * the outside angle represents the angle of the outer cone, and the outside volume represents the volume + * beyond the outer cone angle.
+ * At angles smaller than the inner cone angle, no attenuation is applied by the cone. + * In the direction between the inner and outer cones, the sound is gradually attenuated to the outside volume.
+ * The inside and outside angles are specified within the range of 0.0f to 360.0f.
+ * The outside volume is specifies as a scale factor for the amplitude within the range of 0.0f to 1.0f (the unit is not decibel).
+ * The default values when initializing the library are as follows, and no attenuation is applied by the cone.
+ * - Inside angle: 360.0f + * - Outside angle: 360.0f + * - Outside volume: 0.0f + * .
+ * To actually apply the set parameters, you need to call the CriWare.CriAtomEx3dTransceiver::Update function. + *
+ * + */ + public void SetOutputConeParameter(float insideAngle, float outsideAngle, float outsideVolume) + { + UnsafeNativeMethods.criAtomEx3dTransceiver_SetOutputConeParameter(this.handle, insideAngle, outsideAngle, outsideVolume); + } + + /** + * Sets the minimum/maximum distance of the 3D Transceiver output + * Minimum distance + * Maximum distance + * + * Sets the minimum/maximum distance of the 3D Transceiver output.
+ * The minimum distance represents the distance at which the volume cannot be increased any further.
+ * The maximum distance is the distance with the lowest volume.
+ * The default values when the library is initialized are as follows:
+ * - Minimum distance: 0.0f + * - Maximum distance: 0.0f + * . + * When this function is called when the minimum/maximum distances are set on the data, + * the values on the data are overridden (ignored).
+ * To actually apply the set parameters, you need to call the CriWare.CriAtomEx3dTransceiver::Update function. + *
+ * + */ + public void SetOutputMinMaxDistance(float minDistance, float maxDistance) + { + UnsafeNativeMethods.criAtomEx3dTransceiver_SetOutputMinMaxAttenuationDistance(this.handle, minDistance, maxDistance); + } + + /** + * Sets the interior Panning boundary distance for the 3D Transceiver output + * Radius of the 3D Transceiver output + * Interior distance + * + * Sets the interior Panning boundary distance for the 3D Transceiver output.
+ * The radius of the 3D Transceiver output is the radius when the 3D Transceiver output is considered as a sphere.
+ * Interior distance is the distance from the radius of the 3D sound source to which the interior Panning is applied.
+ * Within the radius of the 3D Transceiver output, interior Panning is applied, but since the interior distance is treated as 0.0, + * the sound is played back from all speakers at the same volume.
+ * Within the interior distance, interior Panning is applied.
+ * Outside the interior distance, interior Panning is not applied and the sound is played from 1 or 2 speakers + * closest to the 3D Transceiver output position.
+ * The default values when the library is initialized are as follows:
+ * - 3D Transceiver radius: 0.0f + * - Interior distance: 0.0f (depends on the minimum distance of the 3D Transceiver) + * .
+ * To actually apply the set parameters, you need to call the CriWare.CriAtomEx3dTransceiver::Update function. + *
+ * + * + */ + public void SetOutputInteriorPanField(float radius, float interiorDistance) + { + UnsafeNativeMethods.criAtomEx3dTransceiver_SetOutputInteriorPanField(this.handle, radius, interiorDistance); + } + + /** + * Sets the cross-fade boundary distance of the 3D Transceiver input + * Radius of direct sound area + * Cross-fade distance + * + * Sets the cross-fade boundary distance of the 3D Transceiver input.
+ * Within the radius of the direct sound area, the sound from the 3D Transceiver output is not played, and only the sound from the 3D sound source is played.
+ * The cross-fade distance is the distance from the direct sound area where the cross-fade of the 3D Transceiver output and the sound from the 3D source is applied.
+ * In the direct sound area, the sound from the sound source =1 and the sound from the 3D Transceiver is =0, + * so the sound from the 3D Transceiver output is inaudible and only the sound from the sound source is played.
+ * Within the cross-fade distance, the cross0fade is applied depending on the position of the listener.
+ * Outside the cross-fade distance, the sound from the 3D sound source is not heard, only the sound from the 3D Transceiver output is heard. + * The default values when the library is initialized are as follows:
+ * - Radius of direct sound area: 0.0f + * - Cross-fade distance: 0.0f + * .
+ * To actually apply the set parameters, you need to call the CriWare.CriAtomEx3dTransceiver::Update function. + *
+ * + * + */ + public void SetInputCrossFadeField(float directAudioRadius, float crossfadeDistance) + { + UnsafeNativeMethods.criAtomEx3dTransceiver_SetInputCrossFadeField(this.handle, directAudioRadius, crossfadeDistance); + } + + /** + * Sets the 3D Transceiver output volume + * Volume + * + * Sets the volume of the 3D Transceiver output.
+ * The volume of the 3D Transceiver output affects only the volume related to localization (L,R,SL,SR), + * and does not affect the output level of LFE or the center.
+ * For the volume value, specify a real value in the range of 0.0f to 1.0f.
+ * The volume value is a scale factor for the amplitude of the sound data (the unit is not decibel).
+ * For example, if you specify 1.0f, the original sound is played at its unmodified volume.
+ * If you specify 0.5f, the sound is played at the volume by halving the amplitude (-6dB) + * of the original waveform.
+ * If you specify 0.0f, the sound is muted (silent).
+ * The default value when the library is initialized is 1.0f.
+ * To actually apply the set parameters, you need to call the CriWare.CriAtomEx3dTransceiver::Update function. + *
+ * + */ + public void SetOutputVolume(float volume) + { + UnsafeNativeMethods.criAtomEx3dTransceiver_SetOutputVolume(this.handle, volume); + } + + /** + * Attach AISAC to the 3D Transceiver + * Global AISAC name to attach + * + * Attach AISAC to the 3D Transceiver. + * By attaching AISAC, you can get AISAC effect even if you didn't set AISAC + * for the Cue or the Track.
+ *
+ * If attaching AISAC failed, CriWareErrorHandler calls the error callback.
+ * Check the error message for the reason why the attaching AISAC failed.
+ * Only the global ACF included in the global settings (AISAC file) can be attached.
+ * To get the effect of AISAC , it is necessary to set the appropriate AISAC control value + * in the same way as the AISAC set for Cues or Tracks.
+ * Even if "an AISAC to change AISAC control value" is set for the Cue or Track, + * the applied AISAC control value does not affect the AISAC attached to the 3Dtransceiver.
+ * Currently, it does not support the AISAC attachment of control type + * "Automodulation" or "Random".
+ * Currently, the maximum number of AISACs that can be attached to a 3D Transceiver is fixed to 8.
+ *
+ * + */ + public void AttachAisac(string globalAisacName) + { + UnsafeNativeMethods.criAtomEx3dTransceiver_AttachAisac(this.handle, globalAisacName); + } + + /** + * Detach AISAC from the 3D Transceiver + * Global AISAC name to detach + * + * Detach (remove) AISAC from the 3D Transceiver.
+ *
+ * If detaching AISAC fails, CriWareErrorHandler calls the error callback.
+ * Check the error message for the reason why detaching AISAC failed.
+ *
+ * + */ + public void DetachAisac(string globalAisacName) + { + UnsafeNativeMethods.criAtomEx3dTransceiver_DetachAisac(this.handle, globalAisacName); + } + + /** + * Sets the maximum amount of change in angle AISAC control value + * Maximum amount of change in angle AISAC control value + * + * Sets the maximum amount of change when the AISAC control value is changed by the angle AISAC.
+ * By changing the maximum amount of change to a lower value, the change of the AISAC control value by + * angle AISAC can be made smooth even if the relative angle between 3D the transceiver and the listener changes abruptly.
+ * For example, if (0.5f / 30.0f) is set, the change takes place over 30 frames + * when the angle changes from 0° to 180°.
+ * The default value is 1.0f (no limit). + * Since this parameter cannot be set on the data, the value set using this function is always used.
+ * To actually apply the set parameters, + * you need to call the CriWare.CriAtomEx3dTransceiver::Update function.
+ * The maximum amount of change set by this function is applied + * only to the change of the angle AISAC control value calculated based on the localization angle. + * It does not affect the localization angle itself.
+ *
+ * + */ + public void SetMaxAngleAisacDelta(float maxDelta) + { + UnsafeNativeMethods.criAtomEx3dTransceiver_SetMaxAngleAisacDelta(this.handle, maxDelta); + } + + /** + * Sets the Distance AISAC Control ID + * Distance AISAC Control ID + * + * Specifies the AISAC control ID that is linked to the distance attenuation between the minimum distance and the maximum distance.
+ * If the AISAC control ID is set by this function, the default distance attenuation becomes invalid.
+ * To actually apply the set parameters, you need to call the CriWare.CriAtomEx3dTransceiver::Update function.
+ *
+ * + */ + public void SetDistanceAisacControlId(ushort aisacControlId) + { + UnsafeNativeMethods.criAtomEx3dTransceiver_SetDistanceAisacControlId(this.handle, aisacControlId); + } + + /** + * Sets the listener reference azimuth AISAC control setting ID + * Listener reference azimuth AISAC control ID + * + * Specifies the AISAC control ID linked to the azimuth of the 3D Transceiver seen from the listener.
+ * To actually apply the set parameters, you need to call the CriWare.CriAtomEx3dTransceiver::Update function.
+ *
+ * + */ + public void SetListenerBasedAzimuthAngleAisacControlId(ushort aisacControlId) + { + UnsafeNativeMethods.criAtomEx3dTransceiver_SetListenerBasedAzimuthAngleAisacControlId(this.handle, aisacControlId); + } + + /** + * Sets the listener reference elevation AISAC control setting ID + * Listener reference elevation AISAC control ID + * + * Specifies the AISAC control ID linked to the elevation of the 3D Transceiver seen from the listener.
+ * To actually apply the set parameters, you need to call the CriWare.CriAtomEx3dTransceiver::Update function.
+ *
+ * + */ + public void SetListenerBasedElevationAngleAisacControlId(ushort aisacControlId) + { + UnsafeNativeMethods.criAtomEx3dTransceiver_SetListenerBasedElevationAngleAisacControlId(this.handle, aisacControlId); + } + + /** + * Sets the 3D Transceiver output reference azimuth AISAC control ID + * 3D Transceiver reference azimuth AISAC control ID + * + * Specify the AISAC control ID linked to the azimuth of listener as seen from the position of the 3D Transceiver output.
+ * To actually apply the set parameters, you need to call the CriWare.CriAtomEx3dTransceiver::Update function.
+ *
+ * + */ + public void SetTransceiverOutputBasedAzimuthAngleAisacControlId(ushort aisacControlId) + { + UnsafeNativeMethods.criAtomEx3dTransceiver_SetTransceiverOutputBasedAzimuthAngleAisacControlId(this.handle, aisacControlId); + } + + /** + * Sets the 3D Transceiver output reference elevation AISAC control ID + * 3D Transceiver reference elevation AISAC control ID + * + * Specify the AISAC control ID linked to the elevation of listener as seen from the position of the 3D Transceiver output.
+ * To actually apply the set parameters, you need to call the CriWare.CriAtomEx3dTransceiver::Update function.
+ *
+ * + */ + public void SetTransceiverOutputBasedElevationAngleAisacControlId(ushort aisacControlId) + { + UnsafeNativeMethods.criAtomEx3dTransceiver_SetTransceiverOutputBasedElevationAngleAisacControlId(this.handle, aisacControlId); + } + + /** + * Sets the 3D region + * + * Set the 3D regions to the 3D sound source. + * If the regions set to the 3D sound source and 3D listener set to the same ExPlayer are different,
+ * and if there is no 3D Transceiver that has the same region as the 3D sound source, the sound is muted.
+ * To actually apply the set parameters, you need to call the CriWare.CriAtomEx3dSource::Update function.
+ *
+ * + * + */ + public void Set3dRegion(CriAtomEx3dRegion region3d) + { + IntPtr region3dHandle = (region3d == null) ? IntPtr.Zero : region3d.nativeHandle; + UnsafeNativeMethods.criAtomEx3dTransceiver_Set3dRegionHn(this.handle, region3dHandle); + } + + #region Internal Members + ~CriAtomEx3dTransceiver() + { + this.Dispose(false); + } + + private IntPtr handle = IntPtr.Zero; + #endregion + + #region Dll Import + private static class UnsafeNativeMethods + { +#if !CRIWARE_ENABLE_HEADLESS_MODE && CRIWARE_TRANSCEIVER_N_ELEVATIONANGLEAISAC_SUPPORT + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + internal static extern IntPtr criAtomEx3dTransceiver_Create(ref Config config, IntPtr work, int work_size); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + internal static extern void criAtomEx3dTransceiver_Destroy(IntPtr ex_3d_transceiver); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + internal static extern void criAtomEx3dTransceiver_Update(IntPtr ex_3d_transceiver); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + internal static extern void criAtomEx3dTransceiver_SetInputPosition(IntPtr ex_3d_transceiver, ref CriAtomEx.NativeVector position); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + internal static extern void criAtomEx3dTransceiver_SetOutputPosition(IntPtr ex_3d_transceiver, ref CriAtomEx.NativeVector position); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + internal static extern void criAtomEx3dTransceiver_SetInputOrientation(IntPtr ex_3d_transceiver, ref CriAtomEx.NativeVector front, ref CriAtomEx.NativeVector top); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + internal static extern void criAtomEx3dTransceiver_SetOutputOrientation(IntPtr ex_3d_transceiver, ref CriAtomEx.NativeVector front, ref CriAtomEx.NativeVector top); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + internal static extern void criAtomEx3dTransceiver_SetOutputConeParameter(IntPtr ex_3d_transceiver, float inside_angle, float outside_angle, float outside_volume); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + internal static extern void criAtomEx3dTransceiver_SetOutputMinMaxAttenuationDistance(IntPtr ex_3d_transceiver, float min_attenuation_distance, float max_attenuation_distance); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + internal static extern void criAtomEx3dTransceiver_SetOutputInteriorPanField(IntPtr ex_3d_transceiver, float transceiver_radius, float interior_distance); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + internal static extern void criAtomEx3dTransceiver_SetInputCrossFadeField(IntPtr ex_3d_transceiver, float direct_audio_radius, float crossfade_distance); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + internal static extern void criAtomEx3dTransceiver_SetOutputVolume(IntPtr ex_3d_transceiver, float volume); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + internal static extern void criAtomEx3dTransceiver_AttachAisac(IntPtr ex_3d_transceiver, string global_aisac_name); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + internal static extern void criAtomEx3dTransceiver_DetachAisac(IntPtr ex_3d_transceiver, string global_aisac_name); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + internal static extern void criAtomEx3dTransceiver_SetMaxAngleAisacDelta(IntPtr ex_3d_transceiver, float max_delta); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + internal static extern void criAtomEx3dTransceiver_SetDistanceAisacControlId(IntPtr ex_3d_transceiver, ushort aisac_control_id); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + internal static extern void criAtomEx3dTransceiver_SetListenerBasedAzimuthAngleAisacControlId(IntPtr ex_3d_transceiver, ushort aisac_control_id); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + internal static extern void criAtomEx3dTransceiver_SetListenerBasedElevationAngleAisacControlId(IntPtr ex_3d_transceiver, ushort aisac_control_id); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + internal static extern void criAtomEx3dTransceiver_SetTransceiverOutputBasedAzimuthAngleAisacControlId(IntPtr ex_3d_transceiver, ushort aisac_control_id); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + internal static extern void criAtomEx3dTransceiver_SetTransceiverOutputBasedElevationAngleAisacControlId(IntPtr ex_3d_transceiver, ushort aisac_control_id); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + internal static extern void criAtomEx3dTransceiver_Set3dRegionHn(IntPtr ex_3d_transceiver, IntPtr ex_3d_region); +#else + internal static IntPtr criAtomEx3dTransceiver_Create(ref Config config, IntPtr work, int work_size) { return IntPtr.Zero; } + internal static void criAtomEx3dTransceiver_Destroy(IntPtr ex_3d_transceiver) { } + internal static void criAtomEx3dTransceiver_Update(IntPtr ex_3d_transceiver) { } + internal static void criAtomEx3dTransceiver_SetInputPosition(IntPtr ex_3d_transceiver, ref CriAtomEx.NativeVector position) { } + internal static void criAtomEx3dTransceiver_SetOutputPosition(IntPtr ex_3d_transceiver, ref CriAtomEx.NativeVector position) { } + internal static void criAtomEx3dTransceiver_SetInputOrientation(IntPtr ex_3d_transceiver, ref CriAtomEx.NativeVector front, ref CriAtomEx.NativeVector top) { } + internal static void criAtomEx3dTransceiver_SetOutputOrientation(IntPtr ex_3d_transceiver, ref CriAtomEx.NativeVector front, ref CriAtomEx.NativeVector top) { } + internal static void criAtomEx3dTransceiver_SetOutputConeParameter(IntPtr ex_3d_transceiver, float inside_angle, float outside_angle, float outside_volume) { } + internal static void criAtomEx3dTransceiver_SetOutputMinMaxAttenuationDistance(IntPtr ex_3d_transceiver, float min_attenuation_distance, float max_attenuation_distance) { } + internal static void criAtomEx3dTransceiver_SetOutputInteriorPanField(IntPtr ex_3d_transceiver, float transceiver_radius, float interior_distance) { } + internal static void criAtomEx3dTransceiver_SetInputCrossFadeField(IntPtr ex_3d_transceiver, float direct_audio_radius, float crossfade_distance) { } + internal static void criAtomEx3dTransceiver_SetOutputVolume(IntPtr ex_3d_transceiver, float volume) { } + internal static void criAtomEx3dTransceiver_AttachAisac(IntPtr ex_3d_transceiver, string global_aisac_name) { } + internal static void criAtomEx3dTransceiver_DetachAisac(IntPtr ex_3d_transceiver, string global_aisac_name) { } + internal static void criAtomEx3dTransceiver_SetMaxAngleAisacDelta(IntPtr ex_3d_transceiver, float max_delta) { } + internal static void criAtomEx3dTransceiver_SetDistanceAisacControlId(IntPtr ex_3d_transceiver, ushort aisac_control_id) { } + internal static void criAtomEx3dTransceiver_SetListenerBasedAzimuthAngleAisacControlId(IntPtr ex_3d_transceiver, ushort aisac_control_id) { } + internal static void criAtomEx3dTransceiver_SetListenerBasedElevationAngleAisacControlId(IntPtr ex_3d_transceiver, ushort aisac_control_id) { } + internal static void criAtomEx3dTransceiver_SetTransceiverOutputBasedAzimuthAngleAisacControlId(IntPtr ex_3d_transceiver, ushort aisac_control_id) { } + internal static void criAtomEx3dTransceiver_SetTransceiverOutputBasedElevationAngleAisacControlId(IntPtr ex_3d_transceiver, ushort aisac_control_id) { } + internal static void criAtomEx3dTransceiver_Set3dRegionHn(IntPtr ex_3d_transceiver, IntPtr ex_3d_region) { } +#endif + } + #endregion +} + + +/** + * 3D region object + * + * An object for handling the 3D region. + * + */ +public class CriAtomEx3dRegion : CriDisposable +{ + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + public struct Config + { + public int reserved; + } + + /** + * Creates a 3D region object + * + * Creates a 3D region object.
+ * The library must be initialized before calling this function.
+ *
+ */ + public CriAtomEx3dRegion() + { + Config config = new Config(); + this.handle = UnsafeNativeMethods.criAtomEx3dRegion_Create(ref config, IntPtr.Zero, 0); + CriDisposableObjectManager.Register(this, CriDisposableObjectManager.ModuleType.Atom); + } + + /** + * Discards a 3D region object + * + * Discards a 3D region object.
+ * When this function is called, all the resources allocated in the DLL when creating the 3D region object are released,
+ * and the 3D region object is disabled.
+ *
+ */ + public override void Dispose() + { + this.Dispose(true); + } + + private void Dispose(bool disposing) + { + CriDisposableObjectManager.Unregister(this); + + if (this.handle != IntPtr.Zero) { + UnsafeNativeMethods.criAtomEx3dRegion_Destroy(this.handle); + this.handle = IntPtr.Zero; + } + + if (disposing) { + GC.SuppressFinalize(this); + } + } + + ~CriAtomEx3dRegion() + { + this.Dispose(false); + } + + public IntPtr nativeHandle + { + get { return this.handle; } + } + + private IntPtr handle = IntPtr.Zero; + + private static class UnsafeNativeMethods + { +#if !CRIWARE_ENABLE_HEADLESS_MODE && CRIWARE_TRANSCEIVER_N_ELEVATIONANGLEAISAC_SUPPORT + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + internal static extern IntPtr criAtomEx3dRegion_Create(ref Config config, IntPtr work, int work_size); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + internal static extern void criAtomEx3dRegion_Destroy(IntPtr ex_3d_region); +#else + internal static IntPtr criAtomEx3dRegion_Create(ref Config config, IntPtr work, int work_size) { return IntPtr.Zero; } + internal static void criAtomEx3dRegion_Destroy(IntPtr ex_3d_region) { } +#endif + } +} // end of class + +} //namespace CriWare +/** + * @} + */ + +/* --- end of file --- */ diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomEx3dTransceiver.cs.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomEx3dTransceiver.cs.meta new file mode 100644 index 0000000..84985b5 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomEx3dTransceiver.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 249329d1a1f411b4c8f2fed9c870952b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExAcb.cs b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExAcb.cs new file mode 100644 index 0000000..c424843 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExAcb.cs @@ -0,0 +1,985 @@ +/**************************************************************************** + * + * Copyright (c) 2011 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using System.Text; +using UnityEngine; + +/*========================================================================== + * CRI Atom Native Wrapper + *=========================================================================*/ +/** + * \addtogroup CRIATOM_NATIVE_WRAPPER + * @{ + */ + +namespace CriWare { + +/** + * ACB and AWB data + * + * A class that manages the Cue information.
+ * Loads or unloads ACB or AWB, or gets the Cue information etc.
+ *
+ */ +public class CriAtomExAcb : CriDisposable +{ + public IntPtr nativeHandle {get {return this.handle;} } + + public bool isAvailable {get {return this.handle != IntPtr.Zero;} } + + /** + * Loads the ACB file + * Binder object + * Path of the ACB file + * Path of the AWB file + * CriAtomExAcb object + * + * Loads the ACB file and import the information required for Cue playback.
+ *
+ * Specify the path of the ACB file for on-memory playback in the second argument acbPath, + * and the path of the AWB file for stream playback in the third argument awbPath.
+ * (When loading ACB data for on-memory playback only, + * the value set in awbPath is ignored.)
+ *
+ * When the ACB file and the AWB file are packed in one CPK file, + * you need to specify the CriFsBinder object that binds the CPK file as the first argument ( binder ).
+ *
+ * Loading the ACB file returns an CriAtomExAcb object ( CriWare.CriAtomExAcb ) + * for accessing the ACB data.
+ * You can play the Cue in the ACB file by + * specifying the ACB handle and the Cue name to be played + * using the CriWare.CriAtomExPlayer::SetCue function for the AtomExPlayer.
+ *
+ * This function will return null as a return value + * if the ACB file cannot be loaded due to a read error.
+ * The library must be initialized before calling this function.
+ *
+ * The ACB handle internally allocates a binder ( CriFsBinder ).
+ * When loading an ACB file, + * it is necessary to initialize the library using the settings which allow binder for the number of ACB files can be allocated.
+ *
+ * This function is a return-on-complete function.
+ * The time it takes to load an ACB file varies depending on the platform.
+ * If this function is called at a timing when the screen needs to be updated such as in a game loop, + * the process is blocked in the unit of milliseconds, resulting in dropped frames.
+ * Load the ACB file at a timing when load fluctuations is accepted + * such as when switching scenes.
+ *
+ * + */ + public static CriAtomExAcb LoadAcbFile(CriFsBinder binder, string acbPath, string awbPath) + { + /* バージョン番号が不正なライブラリではキューシートをロードしない */ + /* 備考)不正に差し替えられたsoファイルを使用している可能性あり。 */ + bool isCorrectVersion = CriWare.Common.CheckBinaryVersionCompatibility(); + if (isCorrectVersion == false) { + return null; + } + + IntPtr binderHandle = (binder != null) ? binder.nativeHandle : IntPtr.Zero; + IntPtr handle = criAtomExAcb_LoadAcbFile( + binderHandle, acbPath, binderHandle, awbPath, IntPtr.Zero, 0); + if (handle == IntPtr.Zero) { + return null; + } + return new CriAtomExAcb(handle, null); + } + + /** + * Loads the ACB data + * Byte array of the ACB data + * Binder object for AWB + * Path of the AWB file + * CriAtomExAcb object + * + * Loads the ACB data placed on the memory and captures the information required for Cue playback.
+ *
+ * Specify the path of the AWB file for stream playback in the second argument awbPath.
+ * (When loading ACB data for on-memory playback only, + * the value set in awbPath is ignored.)
+ *
+ * When the AWB file is packed in a CPK file, + * you need to specify the CriFsBinder object that binds the CPK file as the second argument ( binder ).
+ *
+ * Loading the ACB data returns an CriAtomExAcb object ( CriWare.CriAtomExAcb ) + * for accessing the ACB data.
+ * You can play the Cue in the ACB file by specifying the ACB handle + * and the Cue name to be played using the + * CriWare.CriAtomExPlayer::SetCue function for the AtomExPlayer.
+ *
+ * This function will return null as a return value + * if the ACB file cannot be loaded due to a read error.
+ * The library must be initialized before calling this function.
+ *
+ * The ACB handle internally allocates a binder ( CriFsBinder ).
+ * When loading an ACB file, + * it is necessary to initialize the library using the settings which allow binder for the number of ACB files can be allocated.
+ *
+ * This function is a return-on-complete function.
+ * The time it takes to load an ACB file varies depending on the platform.
+ * If this function is called at a timing when the screen needs to be updated such as in a game loop, + * the process is blocked in the unit of milliseconds, resulting in dropped frames.
+ * Load the ACB file at a timing when load fluctuations is accepted + * such as when switching scenes.
+ *
+ * + */ + public static CriAtomExAcb LoadAcbData(byte[] acbData, CriFsBinder awbBinder, string awbPath) + { + /* バージョン番号が不正なライブラリではキューシートをロードしない */ + /* 備考)不正に差し替えられたsoファイルを使用している可能性あり。 */ + bool isCorrectVersion = CriWare.Common.CheckBinaryVersionCompatibility(); + if (isCorrectVersion == false) { + return null; + } + + IntPtr binderHandle = (awbBinder != null) ? awbBinder.nativeHandle : IntPtr.Zero; + GCHandle gch = GCHandle.Alloc(acbData, GCHandleType.Pinned); + IntPtr handle = criAtomExAcb_LoadAcbData( + gch.AddrOfPinnedObject(), acbData.Length, binderHandle, awbPath, IntPtr.Zero, 0); + if (handle == IntPtr.Zero) { + return null; + } + return new CriAtomExAcb(handle, gch); + } + + /** + * Unloads the ACB file + * + * Unloads the loaded ACB file.
+ * Calling this function will + * stop all Cues that reference the ACB file to be unloaded.
+ * (After this function is called, the work area used to create the + * ACB handle or the area where the ACB data was placed is not referenced.)
+ * When this function is called, the library performs a search to check + * if there are any Atom players referencing the ACB data to be discarded.
+ * Therefore, if you create/discard an Atom player in the different thread while this function is running, + * serious problems such as access violation or deadlock may be triggered.
+ *
+ * + * + */ + public override void Dispose() + { + this.Dispose(true); + GC.SuppressFinalize(this); + } + + private void Dispose(bool disposing) + { + CriDisposableObjectManager.Unregister(this); + + if (this.isAvailable) { + criAtomExAcb_Release(this.handle); + this.handle = IntPtr.Zero; + } + + if (disposing && this.dataHandle.IsAllocated) { + this.dataHandle.Free(); + } + } + + /** + * Checks the existence of the Cue (Cue name specified) + * Cue name + * Whether the Cue exists (exists: True, does not exist: False) + * + * Gets whether the Cue with the specified name exists.
+ * Returns True if it exists.
+ *
+ */ + public bool Exists(string cueName) + { + return criAtomExAcb_ExistsName(this.handle, cueName); + } + + /** + * Checking the existence of the Cue (Cue ID specified) + * Cue ID + * Whether the Cue exists (exists: True, does not exist: False) + * + * Gets whether the Cue with the specified ID exists.
+ * Returns True if it exists.
+ *
+ */ + public bool Exists(int cueId) + { + return criAtomExAcb_ExistsId(this.handle, cueId); + } + + /** + * Gets Cue information (Cue name specified) + * Cue name + * Cue information + * Whether the acquisition was successful (success: True, failure: False) + * + * Gets the Cue information by specifying the Cue name.
+ * Returns False if there is no Cue with the specified name.
+ *
+ * + */ + public bool GetCueInfo(string cueName, out CriAtomEx.CueInfo info) + { + using (var mem = new CriStructMemory()) { + bool result = criAtomExAcb_GetCueInfoByName(this.handle, cueName, mem.ptr); + info = new CriAtomEx.CueInfo(mem.bytes, 0); + return result; + } + } + + /** + * Gets Cue information (Cue ID specified) + * Cue ID + * Cue information + * Whether the acquisition was successful (success: True, failure: False) + * + * Gets the Cue information by specifying the Cue ID.
+ * Returns False if there is no Cue with the specified ID.
+ *
+ * + */ + public bool GetCueInfo(int cueId, out CriAtomEx.CueInfo info) + { + using (var mem = new CriStructMemory()) { + bool result = criAtomExAcb_GetCueInfoById(this.handle, cueId, mem.ptr); + info = new CriAtomEx.CueInfo(mem.bytes, 0); + return result; + } + } + + /** + * Gets Cue information (Cue index specified) + * Cue index + * Cue information + * Whether the acquisition was successful (success: True, failure: False) + * + * Gets the Cue information by specifying the Cue index.
+ * Returns False if there is no Cue with the specified index.
+ *
+ * + */ + public bool GetCueInfoByIndex(int index, out CriAtomEx.CueInfo info) + { + using (var mem = new CriStructMemory()) { + bool result = criAtomExAcb_GetCueInfoByIndex(this.handle, index, mem.ptr); + info = new CriAtomEx.CueInfo(mem.bytes, 0); + return result; + } + } + + + /** + * Gets all Cue information + * Cues information array + * + * Gets all Cue information contained in the Acb file.
+ *
+ * + */ + public CriAtomEx.CueInfo[] GetCueInfoList() + { + int numCues = criAtomExAcb_GetNumCues(this.handle); + var infoList = new CriAtomEx.CueInfo[numCues]; + for (int i = 0; i < numCues; i++) { + this.GetCueInfoByIndex(i, out infoList[i]); + } + return infoList; + } + + /** + * Gets sound waveform information (Cue name specified) + * Cue name + * Sound waveform information + * Whether the acquisition was successful (success: True, failure: False) + * + * Gets the information on the sound waveform played by a Cue by specifying the Cue name.
+ * If there are multiple sound waveforms played by that Cue, + * the information of the sound waveform played first in the first Track is obtained.
+ * Returns false if there is no Cue with the specified name.
+ *
+ */ + public bool GetWaveFormInfo(string cueName, out CriAtomEx.WaveformInfo info) + { + using (var mem = new CriStructMemory()) { + bool result = criAtomExAcb_GetWaveformInfoByName(this.handle, cueName, mem.ptr); + info = new CriAtomEx.WaveformInfo(mem.bytes, 0); + return result; + } + } + + /** + * Gets the sound waveform information (Cue ID specified) + * Cue ID + * Sound waveform information + * Whether the acquisition was successful (success: True, failure: False) + * + * Gets the information on the sound waveform played by a Cue by specify the Cue ID.
+ * If there are multiple sound waveforms played by that Cue, + * the information of the sound waveform played first in the first Track is obtained. + * Returns False if there is no Cue with the specified ID.
+ *
+ */ + public bool GetWaveFormInfo(int cueId, out CriAtomEx.WaveformInfo info) + { + using (var mem = new CriStructMemory()) { + bool result = criAtomExAcb_GetWaveformInfoById(this.handle, cueId, mem.ptr); + info = new CriAtomEx.WaveformInfo(mem.bytes, 0); + return result; + } + } + + /** + * Gets the number of Voices of the Cue for which Cue limit is set (Cue name specified) + * Cue name + * The number of Voices (-1 is returned when a Cue with no Cue limit is specified) + * + * Gets the number of Voices of the Cue with a Cue limit by specifying the Cue name.
+ * Returns -1 if there is no Cue with the specified name, or if the specified Cue has no Cue limit.
+ *
+ */ + public int GetNumCuePlaying(string name) + { + return criAtomExAcb_GetNumCuePlayingCountByName(this.handle, name); + } + + /** + * Gets the number of Voices of the Cue for which Cue limit is set (Cue ID specified) + * Cue ID + * The number of Voices (-1 is returned when a Cue with no Cue limit is specified) + * + * Gets the number of Voices of the Cue with a Cue limit by specifying the Cue ID.
+ * Returns -1 if there is no Cue with the specified ID, or if the specified Cue has no Cue limit.
+ *
+ */ + public int GetNumCuePlaying(int id) + { + return criAtomExAcb_GetNumCuePlayingCountById(this.handle, id); + } + + /** + * Gets the Block index (Cue name specified) + * Cue name + * Block name + * Block index + * + * Get the Block index from the Cue name and the Block name.
+ * Returns 0xFFFFFFFF if there is no Cue with the specified name + * or the Block name.
+ *
+ */ + public int GetBlockIndex(string cueName, string blockName) + { + return criAtomExAcb_GetBlockIndexByName(this.handle, cueName, blockName); + } + + /** + * Gets Block index (Cue ID specified) + * Cue ID + * Block name + * Block index + * + * Gets the Block index from the Cue ID and the Block name.
+ * Returns 0xFFFFFFFF if there is no Cue with the specified ID + * or the Block name.
+ *
+ */ + public int GetBlockIndex(int cueId, string blockName) + { + return criAtomExAcb_GetBlockIndexById(this.handle, cueId, blockName); + } + + /** + * Gets the number of AISAC Controls that can be controlled by a Cue (Cue name specified) + * Cue name + * The number of AISAC Controls + * + * Gets the number of AISAC Controls that can be controlled by the Cue by specifying the Cue name.
+ * Returns -1 if there is no Cue with the specified name.
+ *
+ * + */ + public int GetNumUsableAisacControls(string cueName) + { + return criAtomExAcb_GetNumUsableAisacControlsByName(this.handle, cueName); + } + + /** + * Gets the number of AISAC Controls that can be controlled by a Cue (Cue ID specified) + * Cue ID + * The number of AISAC Controls + * + * Gets the number of AISAC Controls that can be controlled by the Cue by specifying the Cue ID.
+ * Returns -1 if there is no Cue with the specified ID.
+ *
+ * + */ + public int GetNumUsableAisacControls(int cueId) + { + return criAtomExAcb_GetNumUsableAisacControlsById(this.handle, cueId); + } + + /** + * Gets the AISAC Controls that can be controlled by a Cue (Cue name specified) + * Cue name + * AISAC Control index + * AISAC Control information + * Whether the acquisition was successful (success: True, failure: False) + * + * Gets the AISAC Control information by specifying the Cue name and the AISAC Control index.
+ * Returns False if there is no Cue with the specified name.
+ *
+ * + */ + public bool GetUsableAisacControl(string cueName, int index, out CriAtomEx.AisacControlInfo info) + { + using (var mem = new CriStructMemory()) { + bool result = criAtomExAcb_GetUsableAisacControlByName(this.handle, cueName, (ushort)index, mem.ptr); + info = new CriAtomEx.AisacControlInfo(mem.bytes, 0); + return result; + } + } + + /** + * Gets the AISAC Controls that can be controlled by a Cue (Cue ID specified) + * Cue ID + * AISAC Control index + * AISAC Control information + * Whether the acquisition was successful (success: True, failure: False) + * + * Gets the AISAC Control information by specifying the Cue ID and the AISAC Control index.
+ * Returns False if there is no Cue with the specified ID.
+ *
+ * + */ + public bool GetUsableAisacControl(int cueId, int index, out CriAtomEx.AisacControlInfo info) + { + using (var mem = new CriStructMemory()) { + bool result = criAtomExAcb_GetUsableAisacControlById(this.handle, cueId, (ushort)index, mem.ptr); + info = new CriAtomEx.AisacControlInfo(mem.bytes, 0); + return result; + } + } + + public CriAtomEx.AisacControlInfo[] GetUsableAisacControlList(string cueName) + { + int numControls = GetNumUsableAisacControls(cueName); + var infoList = new CriAtomEx.AisacControlInfo[numControls]; + for (int i = 0; i < numControls; i++) { + this.GetUsableAisacControl(cueName, i, out infoList[i]); + } + return infoList; + } + + public CriAtomEx.AisacControlInfo[] GetUsableAisacControlList(int cueId) + { + int numControls = GetNumUsableAisacControls(cueId); + var infoList = new CriAtomEx.AisacControlInfo[numControls]; + for (int i = 0; i < numControls; i++) { + this.GetUsableAisacControl(cueId, i, out infoList[i]); + } + return infoList; + } + + /** + * Resets the Cue type state (Cue name specified) + * Cue name + * + * Resets the Cue type state by specifying the Cue name.
+ * Only the state of the specified Cue is reset. The status of the sub synth contained in the Cue or Cue link destinations + * is not reset. + * The Cue type state is a mechanism that manages the previously played Track as a state + * when playing a Cue other than the Polyphonic type Cue
+ * This function resets the state management area to the state immediately after ACB loading.
+ *
+ */ + public void ResetCueTypeState(string cueName) + { + criAtomExAcb_ResetCueTypeStateByName(this.handle, cueName); + } + + /** + * Resets the Cue type state (Cue ID specified) + * Cue name + * + * Resets the Cue type state by specifying the Cue name.
+ * Only the state of the specified Cue is reset. The status of the sub synth contained in the Cue or Cue link destinations + * is not reset. + * The Cue type state is a mechanism that manages the previously played Track as a state + * when playing a Cue other than the Polyphonic type Cue
+ * This function resets the state management area to the state immediately after ACB loading.
+ *
+ */ + public void ResetCueTypeState(int cueId) + { + criAtomExAcb_ResetCueTypeStateById(this.handle, cueId); + } + + /** + * Attaches the AWB file for streaming + * Handle of the binder containing the AWB files + * Path of the AWB file + * AWB name + * + * Attaches an AWB file for the stream to the ACB handle. + * For the first argument awb_binder and the second argument awb_path, + * specify the AWB file for stream playback.
+ * The third argument awb_name is used to specify the slot to which the AWB is attached. + * Therefore, if you changed the AWB name output by AtomCraft (the base file name without extension), + * specify the original AWB name.
+ * An error callback is called when the attachment of the AWB file fails.
+ * The reason for the failure can be determined from the error callback message.
+ * When the AWB is attached, the binder ( CriFsBinderHn ) and loader ( CriFsLoaderHn ) are + * allocated inside the library.
+ * If you want to attach additional AWB files, you need to initialize the Atom library (or the CRI File System library) + * using the settings which allow the allocation of additional binders and loaders.
+ *
+ */ + public void AttachAwbFile(CriFsBinder awb_binder, string awb_path, string awb_name) + { + if (this.isAvailable) { + IntPtr binderHandle = (awb_binder != null) ? awb_binder.nativeHandle : IntPtr.Zero; + criAtomExAcb_AttachAwbFile(this.handle, binderHandle, awb_path, awb_name, IntPtr.Zero, 0); + } + } + + /** + * Detaches the AWB file for streaming + * AWB name + * + * Detaches the AWB file for the stream attached to the ACB handle. + * For the first argument awb_name, specify the same AWB name as that specified when attaching the AWB.
+ *
+ */ + public void DetachAwbFile(string awb_name) + { + if (this.isAvailable) { + criAtomExAcb_DetachAwbFile(this.handle, awb_name); + } + } + + /** + * Gets the immediate release state of the ACB handle + * Status of ACB (True = instant release possible, False = there are players playing) + * + * Checks if the ACB handle can be released immediately.
+ * Calling the CriWare.CriAtomExAcb::Dispose at the timing when this function returns false + * and will stop the player referencing the ACB handle.
+ * (For the ACB handle for stream playback, the process may block for a long time + * in the CriWare.CriAtomExAcb::Dispose function because it waits for the completion of file read.)
+ *
+ */ + public bool IsReadyToRelease() + { + if (this.isAvailable) { + bool result = criAtomExAcb_IsReadyToRelease(this.handle); + return result; + } else { + return false; + } + } + + /* @cond excludele */ + /** + * Gets the loading progress + * + * Gets the load status of the AAC data included in ACB on WebGLplatform. + * A value between 0.0f and 1.0f is returned. Loading is finished if 1.0f is returned. + * + */ + public float GetLoadProgress() + { +#if !UNITY_EDITOR && UNITY_WEBGL + return criAtomExAcb_GetLoadProgress(this.handle); +#else + return 1.0f; +#endif + } + /* @endcond */ + + /* @cond notpublic */ + /** + * Sets the decryption key + * Decryption key + * Nonce (be sure to specify 0) + * + * Specifies the decryption key to decrypt the ACB data.
+ * It is possible to use different decryption keys for each ACB handle + * by calling this function after loading the ACB file.
+ * (The decryption key specified using this function is used for the relevant ACB file + * ignoring the setting by the decryptor.)
+ *
+ */ + public void Decrypt(ulong key, ulong nonce) + { + if (this.isAvailable) { + CriAtomPlugin.DecryptAcb(this.handle, key, nonce); + } + } + /* @endcond */ + + #region Internal Members + + internal CriAtomExAcb(IntPtr handle, GCHandle? dataHandle) + { + this.handle = handle; + if (dataHandle.HasValue) { + this.dataHandle = dataHandle.Value; + } + CriDisposableObjectManager.Register(this, CriDisposableObjectManager.ModuleType.Atom); + } + + ~CriAtomExAcb() + { + this.Dispose(false); + } + + private IntPtr handle = IntPtr.Zero; + private GCHandle dataHandle; + #endregion + + #region DLL Import + #if !CRIWARE_ENABLE_HEADLESS_MODE + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern IntPtr criAtomExAcb_LoadAcbFile(IntPtr acb_binder, string acb_path, + IntPtr awb_binder, string awb_path, IntPtr work, int work_size); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern IntPtr criAtomExAcb_LoadAcbData(IntPtr acb_data, int acb_data_size, + IntPtr awb_binder, string awb_path, IntPtr work, int work_size); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExAcb_Release(IntPtr acb_hn); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criAtomExAcb_GetNumCues(IntPtr acb_hn); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool criAtomExAcb_ExistsId(IntPtr acb_hn, int id); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool criAtomExAcb_ExistsName(IntPtr acb_hn, string name); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criAtomExAcb_GetNumUsableAisacControlsById(IntPtr acb_hn, int id); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criAtomExAcb_GetNumUsableAisacControlsByName(IntPtr acb_hn, string name); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool criAtomExAcb_GetUsableAisacControlById( + IntPtr acb_hn, int id, ushort index, IntPtr info); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool criAtomExAcb_GetUsableAisacControlByName( + IntPtr acb_hn, string name, ushort index, IntPtr info); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool criAtomExAcb_GetWaveformInfoById( + IntPtr acb_hn, int id, IntPtr waveform_info); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool criAtomExAcb_GetWaveformInfoByName( + IntPtr acb_hn, string name, IntPtr waveform_info); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool criAtomExAcb_GetCueInfoByName(IntPtr acb_hn, string name, IntPtr info); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool criAtomExAcb_GetCueInfoById(IntPtr acb_hn, int id, IntPtr info); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool criAtomExAcb_GetCueInfoByIndex(IntPtr acb_hn, int index, IntPtr info); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criAtomExAcb_GetNumCuePlayingCountByName(IntPtr acb_hn, string name); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criAtomExAcb_GetNumCuePlayingCountById(IntPtr acb_hn, int id); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criAtomExAcb_GetBlockIndexById(IntPtr acb_hn, int id, string block_name); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criAtomExAcb_GetBlockIndexByName(IntPtr acb_hn, string name, string block_name); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExAcb_ResetCueTypeStateByName(IntPtr acb_hn, string name); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExAcb_ResetCueTypeStateById(IntPtr acb_hn, int id); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExAcb_AttachAwbFile(IntPtr acb_hn, IntPtr awb_binder, + string awb_path, string awb_name, IntPtr work, int work_size); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExAcb_DetachAwbFile(IntPtr acb_hn, string awb_name); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool criAtomExAcb_IsReadyToRelease(IntPtr acb_hn); + + /* @cond excludele */ + #if !UNITY_EDITOR && UNITY_WEBGL + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern float criAtomExAcb_GetLoadProgress(IntPtr acb_hn); + #endif + /* @endcond */ + #else + private static IntPtr criAtomExAcb_LoadAcbFile(IntPtr acb_binder, string acb_path, + IntPtr awb_binder, string awb_path, IntPtr work, int work_size) { return new IntPtr(1); } + private static IntPtr criAtomExAcb_LoadAcbData(IntPtr acb_data, int acb_data_size, + IntPtr awb_binder, string awb_path, IntPtr work, int work_size) { return new IntPtr(1); } + private static void criAtomExAcb_Release(IntPtr acb_hn) { } + private static int criAtomExAcb_GetNumCues(IntPtr acb_hn) { return 0; } + private static bool criAtomExAcb_ExistsId(IntPtr acb_hn, int id) { return false; } + private static bool criAtomExAcb_ExistsName(IntPtr acb_hn, string name) { return false; } + private static int criAtomExAcb_GetNumUsableAisacControlsById(IntPtr acb_hn, int id) { return 0; } + private static int criAtomExAcb_GetNumUsableAisacControlsByName(IntPtr acb_hn, string name) { return 0; } + private static bool criAtomExAcb_GetUsableAisacControlById( + IntPtr acb_hn, int id, ushort index, IntPtr info) { return false; } + private static bool criAtomExAcb_GetUsableAisacControlByName( + IntPtr acb_hn, string name, ushort index, IntPtr info) { return false; } + private static bool criAtomExAcb_GetWaveformInfoById( + IntPtr acb_hn, int id, IntPtr waveform_info) { return false; } + private static bool criAtomExAcb_GetWaveformInfoByName( + IntPtr acb_hn, string name, IntPtr waveform_info) { return false; } + private static bool criAtomExAcb_GetCueInfoByName(IntPtr acb_hn, string name, IntPtr info) { return false; } + private static bool criAtomExAcb_GetCueInfoById(IntPtr acb_hn, int id, IntPtr info) { return false; } + private static bool criAtomExAcb_GetCueInfoByIndex(IntPtr acb_hn, int index, IntPtr info) { return false; } + private static int criAtomExAcb_GetNumCuePlayingCountByName(IntPtr acb_hn, string name) { return 0; } + private static int criAtomExAcb_GetNumCuePlayingCountById(IntPtr acb_hn, int id) { return 0; } + private static int criAtomExAcb_GetBlockIndexById(IntPtr acb_hn, int id, string block_name) { return -1; } + private static int criAtomExAcb_GetBlockIndexByName(IntPtr acb_hn, string name, string block_name) { return -1; } + private static void criAtomExAcb_ResetCueTypeStateByName(IntPtr acb_hn, string name) { } + private static void criAtomExAcb_ResetCueTypeStateById(IntPtr acb_hn, int id) { } + private static void criAtomExAcb_AttachAwbFile(IntPtr acb_hn, IntPtr awb_binder, + string awb_path, string awb_name, IntPtr work, int work_size) { } + private static void criAtomExAcb_DetachAwbFile(IntPtr acb_hn, string awb_name) { } + private static bool criAtomExAcb_IsReadyToRelease(IntPtr acb_hn) { return false; } + /* @cond excludele */ + #if !UNITY_EDITOR && UNITY_WEBGL + private static float criAtomExAcb_GetLoadProgress(IntPtr acb_hn) { return 1.0f; } + #endif + /* @endcond */ + #endif + #endregion +} + +/** + * Asynchronous loader of ACB and AWB data + * + * A class for loading the ACB or AWB files asynchronously.
+ *
+ */ +public class CriAtomExAcbLoader : CriDisposable +{ + /** + * Status + * + * The status of the asynchronous loader.
+ *
+ */ + public enum Status + { + Stop, + Loading, + Complete, + Error + } + + /** + * Asynchronous loading of the ACB file + * Binder object + * Path of the ACB file + * Path of the AWB file + * Whether to load the AWB file on the memory (optional) + * CriAtomExAcbLoader object + * + * Starts the asynchronous loading of the ACB file.
+ * You should call CriWare.CriAtomExAcbLoader::GetStatus for the return value to check the loading status. + * If the status changes to Complete, you can get the CriWare.CriAtomExAcb object using CriWare.CriAtomExAcbLoader::MoveAcb .
+ *
+ */ + public static CriAtomExAcbLoader LoadAcbFileAsync(CriFsBinder binder, string acbPath, string awbPath, bool loadAwbOnMemory = false) + { + /* バージョン番号が不正なライブラリではキューシートをロードしない */ + /* 備考)不正に差し替えられたsoファイルを使用している可能性あり。 */ + bool isCorrectVersion = CriWare.Common.CheckBinaryVersionCompatibility(); + if (isCorrectVersion == false) { + return null; + } + + IntPtr binderHandle = (binder != null) ? binder.nativeHandle : IntPtr.Zero; + LoaderConfig config = new LoaderConfig(); + config.shouldLoadAwbOnMemory = loadAwbOnMemory; + IntPtr handle = criAtomExAcbLoader_Create(ref config); + if (handle == IntPtr.Zero) { return null; } + bool result = criAtomExAcbLoader_LoadAcbFileAsync(handle, binderHandle, acbPath, binderHandle, awbPath); + if (result == false) { return null; } + return new CriAtomExAcbLoader(handle, null); + } + + /** + * Asynchronous loading of the ACB data + * Byte array of the ACB data + * Binder object for AWB + * Path of the AWB file + * Whether to load the AWB file on the memory (optional) + * CriAtomExAcbLoader object + * + * Starts asynchronous loading of the ACB data.
+ * You should call CriWare.CriAtomExAcbLoader::GetStatus for the return value to check the loading status. + * If the status changes to Complete, you can get CriWare.CriAtomExAcb using CriWare.CriAtomExAcbLoader::MoveAcb .
+ *
+ */ + public static CriAtomExAcbLoader LoadAcbDataAsync(byte[] acbData, CriFsBinder awbBinder, string awbPath, bool loadAwbOnMemory = false) + { + /* バージョン番号が不正なライブラリではキューシートをロードしない */ + /* 備考)不正に差し替えられたsoファイルを使用している可能性あり。 */ + bool isCorrectVersion = CriWare.Common.CheckBinaryVersionCompatibility(); + if (isCorrectVersion == false) { + return null; + } + + IntPtr binderHandle = (awbBinder != null) ? awbBinder.nativeHandle : IntPtr.Zero; + LoaderConfig config = new LoaderConfig(); + config.shouldLoadAwbOnMemory = loadAwbOnMemory; + IntPtr handle = criAtomExAcbLoader_Create(ref config); + if (handle == IntPtr.Zero) { return null; } + GCHandle dataHandle = GCHandle.Alloc(acbData, GCHandleType.Pinned); + bool result = criAtomExAcbLoader_LoadAcbDataAsync(handle, dataHandle.AddrOfPinnedObject(), acbData.Length, binderHandle, awbPath); + if (result == false) { return null; } + return new CriAtomExAcbLoader(handle, dataHandle); + } + + /** + * Gets the status + * Asynchronous loader loading status + * + * Gets the status of the asynchronous loader.
+ * When the return value of this function changes to Complete, you can get CriWare.CriAtomExAcb using CriWare.CriAtomExAcbLoader::MoveAcb .
+ *
+ */ + public Status GetStatus() + { + return criAtomExAcbLoader_GetStatus(this.handle); + } + + /** + * Gets the ACB data + * CriAtomExAcb object + * + * Gets the ACB data loaded asynchronously.
+ * Call this function after the return value of CriWare.CriAtomExAcbLoader::GetStatus changes to Complete.
+ *
+ */ + public CriAtomExAcb MoveAcb() + { + IntPtr movedAcbHandle = criAtomExAcbLoader_MoveAcbHandle(this.handle); + if (movedAcbHandle != IntPtr.Zero) { + CriAtomExAcb movedAcb = new CriAtomExAcb(movedAcbHandle, this.gch); + this.gch = null; + return movedAcb; + } + return null; + } + + /** + * Discards an asynchronous loader + * + * Discard an asynchronous loader.
+ *
+ */ + public override void Dispose() + { + this.Dispose(true); + GC.SuppressFinalize(this); + } + + private void Dispose(bool disposing) + { + CriDisposableObjectManager.Unregister(this); + + if (this.handle != IntPtr.Zero) { + criAtomExAcbLoader_Destroy(this.handle); + this.handle = IntPtr.Zero; + } + + if (disposing && this.gch.HasValue && this.gch.Value.IsAllocated) { + this.gch.Value.Free(); + } + } + + #region Internal Members + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + private struct LoaderConfig + { + public bool shouldLoadAwbOnMemory; + } + + private IntPtr handle = IntPtr.Zero; + private GCHandle? gch; + + private CriAtomExAcbLoader(IntPtr handle, GCHandle? dataHandle) + { + this.handle = handle; + if (dataHandle.HasValue) { + this.gch = dataHandle.Value; + } + CriDisposableObjectManager.Register(this, CriDisposableObjectManager.ModuleType.Atom); + } + + ~CriAtomExAcbLoader() + { + this.Dispose(false); + } + #endregion + + #region DLL Import + #if !CRIWARE_ENABLE_HEADLESS_MODE + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern IntPtr criAtomExAcbLoader_Create([In] ref LoaderConfig config); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExAcbLoader_Destroy(IntPtr acb_loader); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool criAtomExAcbLoader_LoadAcbFileAsync(IntPtr acb_loader, IntPtr acb_binder, string acb_path, IntPtr awb_binder, string awb_path); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool criAtomExAcbLoader_LoadAcbDataAsync(IntPtr acb_loader, IntPtr acb_data, int acb_size, IntPtr awb_binder, string awb_path); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern Status criAtomExAcbLoader_GetStatus(IntPtr acb_loader); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool criAtomExAcbLoader_WaitForCompletion(IntPtr acb_loader); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern IntPtr criAtomExAcbLoader_MoveAcbHandle(IntPtr acb_loader); + #else + private static IntPtr criAtomExAcbLoader_Create([In] ref LoaderConfig config) { return new IntPtr(1); } + private static void criAtomExAcbLoader_Destroy(IntPtr acb_loader) { } + private static bool criAtomExAcbLoader_LoadAcbFileAsync(IntPtr acb_loader, IntPtr acb_binder, string acb_path, IntPtr awb_binder, string awb_path) + { return false; } + private static bool criAtomExAcbLoader_LoadAcbDataAsync(IntPtr acb_loader, IntPtr acb_data, int acb_size, IntPtr awb_binder, string awb_path) + { return false; } + private static Status criAtomExAcbLoader_GetStatus(IntPtr acb_loader) { return Status.Complete; } + private static bool criAtomExAcbLoader_WaitForCompletion(IntPtr acb_loader) { return true; } + private static IntPtr criAtomExAcbLoader_MoveAcbHandle(IntPtr acb_loader) { return IntPtr.Zero; } + #endif + #endregion +} + +} //namespace CriWare +/** + * @} + */ + +/* --- end of file --- */ diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExAcb.cs.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExAcb.cs.meta new file mode 100644 index 0000000..a574310 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExAcb.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: d481d21ea5191b64fb163c81e68da255 +timeCreated: 1433816077 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExAcf.cs b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExAcf.cs new file mode 100644 index 0000000..3618b45 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExAcf.cs @@ -0,0 +1,1268 @@ +/**************************************************************************** + * + * Copyright (c) 2019 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +using System; +using System.Runtime.InteropServices; +using UnityEngine; + +/*========================================================================== + * CRI Atom Native Wrapper + *=========================================================================*/ +/** + * \addtogroup CRIATOM_NATIVE_WRAPPER + * @{ + */ + +namespace CriWare { + +/** + * ACF data + * + * A class which manages the project settings set on CRI Atom Craft.
+ * Acquires various information described in the ACF file.
+ *
+ */ +public class CriAtomExAcf +{ + #region Native Struct Definition + + /** + * A structure for getting the DSP bus setting information + * + * A structure for getting the DSP bus setting information.
+ * Passed to the CriAtomExAcf::GetDSPSettingInformation function as an argument.
+ *
+ * + */ + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + public struct AcfDspSettingInfo + { + [MarshalAs(UnmanagedType.LPStr)] + public string name; /**< Setting name */ + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 64)] + public ushort[] busIndexes; /**< DSP bus index array */ + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 64)] + public ushort[] extendBusIndexes; /**< DSP extended bus index array */ + public ushort snapshotStartIndex; /**< Snapshot start index */ + public byte numBuses; /**< The number of effective DSP buses */ + public byte numExtendBuses; /**< The number of effective extended DSP buses */ + public ushort numSnapshots; /**< The number of snapshots */ + public ushort snapshotWorkSize; /**< Snapshot start index */ + public ushort numMixerAisacs; /**< Number of mixer AISACs */ + public ushort mixerAisacStartIndex; /**< Mixer AISAC start index */ + + public AcfDspSettingInfo(byte[] data, int startIndex) + { + if (IntPtr.Size == 4) + { + this.name = Marshal.PtrToStringAnsi(new IntPtr(BitConverter.ToInt32(data, startIndex + 0))); + this.busIndexes = new ushort[64]; + for (int i = 0; i < 64; ++i) + { + busIndexes[i] = BitConverter.ToUInt16(data, startIndex + 4 + (2 * i)); + } + this.extendBusIndexes = new ushort[64]; + for (int i = 0; i < 64; ++i) + { + extendBusIndexes[i] = BitConverter.ToUInt16(data, startIndex + 132 + (2 * i)); + } + this.snapshotStartIndex = BitConverter.ToUInt16(data, startIndex + 260); + this.numBuses = data[startIndex + 262]; + this.numExtendBuses = data[startIndex + 263]; + this.numSnapshots = BitConverter.ToUInt16(data, startIndex + 264); + this.snapshotWorkSize = BitConverter.ToUInt16(data, startIndex + 266); + this.numMixerAisacs = BitConverter.ToUInt16(data, startIndex + 268); + this.mixerAisacStartIndex = BitConverter.ToUInt16(data, startIndex + 270); + } + else + { + this.name = Marshal.PtrToStringAnsi(new IntPtr(BitConverter.ToInt64(data, startIndex + 0))); + this.busIndexes = new ushort[64]; + for (int i = 0; i < 64; ++i) + { + busIndexes[i] = BitConverter.ToUInt16(data, startIndex + 8 + (2 * i)); + } + this.extendBusIndexes = new ushort[64]; + for (int i = 0; i < 64; ++i) + { + extendBusIndexes[i] = BitConverter.ToUInt16(data, startIndex + 136 + (2 * i)); + } + this.snapshotStartIndex = BitConverter.ToUInt16(data, startIndex + 264); + this.numBuses = data[startIndex + 265]; + this.numExtendBuses = data[startIndex + 266]; + this.numSnapshots = BitConverter.ToUInt16(data, startIndex + 268); + this.snapshotWorkSize = BitConverter.ToUInt16(data, startIndex + 270); + this.numMixerAisacs = BitConverter.ToUInt16(data, startIndex + 272); + this.mixerAisacStartIndex = BitConverter.ToUInt16(data, startIndex + 274); + } + } + } + + /** + * A structure for getting the DSP bus setting snapshot information + * + * A structure for getting the snapshot information of the DSP bus settings.
+ * Passed to the CriAtomExAcf::GetDSPSettingSnapshotInformation function as an argument.
+ *
+ * + */ + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + public struct AcfDspSettingSnapshotInfo + { + [MarshalAs(UnmanagedType.LPStr)] + public string name; /**< Snapshot name */ + public byte numBuses; /**< The number of effective DSP buses */ + public byte numExtendBuses; /**< The number of effective extended DSP buses */ + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)] + public byte[] reserved; /**< Reserved area */ + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 64)] + public ushort[] busIndexes; /**< DSP bus index array */ + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 64)] + public ushort[] extendBusIndexes; /**< DSP extended bus index array */ + + public AcfDspSettingSnapshotInfo(byte[] data, int startIndex) + { + if (IntPtr.Size == 4) + { + this.name = Marshal.PtrToStringAnsi(new IntPtr(BitConverter.ToInt32(data, startIndex + 0))); + this.numBuses = data[startIndex + 4]; + this.numExtendBuses = data[startIndex + 5]; + this.reserved = new byte[2]; + for (int i = 0; i < 2; ++i) + { + reserved[i] = data[startIndex + 6 + i]; + } + this.busIndexes = new ushort[64]; + for (int i = 0; i < 64; ++i) + { + busIndexes[i] = BitConverter.ToUInt16(data, startIndex + 8 + (2 * i)); + } + this.extendBusIndexes = new ushort[64]; + for (int i = 0; i < 64; ++i) + { + extendBusIndexes[i] = BitConverter.ToUInt16(data, startIndex + 136 + (2 * i)); + } + } + else + { + this.name = Marshal.PtrToStringAnsi(new IntPtr(BitConverter.ToInt64(data, startIndex + 0))); + this.numBuses = data[startIndex + 8]; + this.numExtendBuses = data[startIndex + 9]; + this.reserved = new byte[2]; + for (int i = 0; i < 2; ++i) + { + reserved[i] = data[startIndex + 10 + i]; + } + this.busIndexes = new ushort[64]; + for (int i = 0; i < 64; ++i) + { + busIndexes[i] = BitConverter.ToUInt16(data, startIndex + 12 + (2 * i)); + } + this.extendBusIndexes = new ushort[64]; + for (int i = 0; i < 64; ++i) + { + extendBusIndexes[i] = BitConverter.ToUInt16(data, startIndex + 140 + (2 * i)); + } + } + } + } + + /** + * A structure for getting the DSP bus setting information + * + * A structure for getting the DSP bus setting information.
+ * Passed to the CriAtomExAcf::GetDSPBusInformation function as an argument.
+ *
+ * + */ + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + public struct AcfDspBusInfo + { + [MarshalAs(UnmanagedType.LPStr)] + public string name; /**< Name */ + public float volume; /**< Volume */ + public float pan3dVolume; /**< Pan3D volume */ + public float pan3dAngle; /**< Pan3D Angle */ + public float pan3dDistance; /**< Pan3D interior distance */ + public float pan3dSpread; /**< Pan3D spread */ + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] + public ushort[] fxIndexes; /**< DSP FX index array */ + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 64)] + public ushort[] busLinkIndexes; /**< DSP bus link index array */ + public ushort busNo; /**< DSP bus number in setting */ + public byte numFxes; /**< The number of DSP FXs */ + public byte numBusLinks; /**< Number of DSP bus links */ + + public AcfDspBusInfo(byte[] data, int startIndex) + { + if (IntPtr.Size == 4) + { + this.name = Marshal.PtrToStringAnsi(new IntPtr(BitConverter.ToInt32(data, startIndex + 0))); + this.volume = BitConverter.ToSingle(data, startIndex + 4); + this.pan3dVolume = BitConverter.ToSingle(data, startIndex + 8); + this.pan3dAngle = BitConverter.ToSingle(data, startIndex + 12); + this.pan3dDistance = BitConverter.ToSingle(data, startIndex + 16); + this.pan3dSpread = BitConverter.ToSingle(data, startIndex + 20); + this.fxIndexes = new ushort[8]; + for (int i = 0; i < 8; ++i) + { + fxIndexes[i] = BitConverter.ToUInt16(data, startIndex + 24 + (2 * i)); + } + this.busLinkIndexes = new ushort[64]; + for (int i = 0; i < 64; ++i) + { + busLinkIndexes[i] = BitConverter.ToUInt16(data, startIndex + 40 + (2 * i)); + } + this.busNo = BitConverter.ToUInt16(data, startIndex + 168); + this.numFxes = data[startIndex + 169]; + this.numBusLinks = data[startIndex + 170]; + } + else + { + this.name = Marshal.PtrToStringAnsi(new IntPtr(BitConverter.ToInt64(data, startIndex + 0))); + this.volume = BitConverter.ToSingle(data, startIndex + 8); + this.pan3dVolume = BitConverter.ToSingle(data, startIndex + 12); + this.pan3dAngle = BitConverter.ToSingle(data, startIndex + 16); + this.pan3dDistance = BitConverter.ToSingle(data, startIndex + 20); + this.pan3dSpread = BitConverter.ToSingle(data, startIndex + 24); + this.fxIndexes = new ushort[8]; + for (int i = 0; i < 8; ++i) + { + fxIndexes[i] = BitConverter.ToUInt16(data, startIndex + 28 + (2 * i)); + } + this.busLinkIndexes = new ushort[64]; + for (int i = 0; i < 64; ++i) + { + busLinkIndexes[i] = BitConverter.ToUInt16(data, startIndex + 44 + (2 * i)); + } + this.busNo = BitConverter.ToUInt16(data, startIndex + 172); + this.numFxes = data[startIndex + 173]; + this.numBusLinks = data[startIndex + 174]; + } + } + } + + /** + * DSP bus link type + * + */ + public enum AcfDspBusLinkType : uint + { + preVolume = 0, /**< Pre-volume type */ + postVolume, /**< Post volume type */ + postPan, /**< Post Panning type */ + } + + /** + * A structure for getting the DSP bus link information + * + * A structure for getting the DSP bus link information.
+ * Passed to the CriAtomExAcf::GetDSPBusLinkInformation function as an argument.
+ *
+ * + */ + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + public struct AcfDspBusLinkInfo + { + public AcfDspBusLinkType type; /**< Type */ + public float sendLevel; /**< Send level */ + public ushort busNo; /**< DSP bus number in the destination setting */ + public ushort busId; /**< DSP bus ID in the destination setting */ + + public AcfDspBusLinkInfo(byte[] data, int startIndex) + { + { + this.type = (AcfDspBusLinkType)Enum.ToObject(typeof(AcfDspBusLinkType), BitConverter.ToUInt32(data, startIndex + 0)); + this.sendLevel = BitConverter.ToSingle(data, startIndex + 4); + this.busNo = BitConverter.ToUInt16(data, startIndex + 8); + this.busId = BitConverter.ToUInt16(data, startIndex + 10); + } + } + } + + /** + * A structure for getting the Category information + * + * A structure for getting the Category information.
+ * Passed to the CriAtomExAcf::GetCategoryInfo function as an argument.
+ *
+ * + */ + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + public struct CategoryInfo + { + public uint groupNo; /**< Group number */ + public uint id; /**< Category ID */ + [MarshalAs(UnmanagedType.LPStr)] + public string name; /**< Category name */ + public uint numCueLimits; /**< Cue limit count */ + public float volume; /**< Volume */ + + public CategoryInfo(byte[] data, int startIndex) + { + if (IntPtr.Size == 4) + { + this.groupNo = BitConverter.ToUInt16(data, startIndex + 0); + this.id = BitConverter.ToUInt16(data, startIndex + 4); + this.name = Marshal.PtrToStringAnsi(new IntPtr(BitConverter.ToInt32(data, startIndex + 8))); + this.numCueLimits = BitConverter.ToUInt16(data, startIndex + 12); + this.volume = BitConverter.ToSingle(data, startIndex + 16); + } + else + { + this.groupNo = BitConverter.ToUInt16(data, startIndex + 0); + this.id = BitConverter.ToUInt16(data, startIndex + 4); + this.name = Marshal.PtrToStringAnsi(new IntPtr(BitConverter.ToInt64(data, startIndex + 8))); + this.numCueLimits = BitConverter.ToUInt16(data, startIndex + 16); + this.volume = BitConverter.ToSingle(data, startIndex + 20); + } + } + } + + /** + * AISAC type + * + */ + public enum AcfAisacType : uint + { + normal = 0, /**< Normal type */ + autoModulation, /**< Auto modulation type */ + } + + /** + * A structure for getting the AISAC information + * + * A structure for acquiring Global AISAC information.
+ * Can be used as an argument of the CriAtomExAcf::GetGlobalAisacInfo function.
+ *
+ * + */ + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + public struct GlobalAisacInfo + { + [MarshalAs(UnmanagedType.LPStr)] + public string name; /**< Global AISAC name */ + public ushort index; /**< Data index */ + public ushort numGraphs; /**< Number of graphs */ + public AcfAisacType type; /**< AISAC type */ + public float randomRange; /**< Random range */ + public ushort controlId; /**< Control Id */ + public ushort dummy; /**< Unused */ + + public GlobalAisacInfo(byte[] data, int startIndex) + { + if (IntPtr.Size == 4) + { + this.name = Marshal.PtrToStringAnsi(new IntPtr(BitConverter.ToInt32(data, startIndex + 0))); + this.index = BitConverter.ToUInt16(data, startIndex + 4); + this.numGraphs = BitConverter.ToUInt16(data, startIndex + 6); + this.type = (AcfAisacType)Enum.ToObject(typeof(AcfAisacType), BitConverter.ToUInt32(data, startIndex + 8)); + this.randomRange = BitConverter.ToSingle(data, startIndex + 12); + this.controlId = BitConverter.ToUInt16(data, startIndex + 16); + this.dummy = BitConverter.ToUInt16(data, startIndex + 18); + } + else + { + this.name = Marshal.PtrToStringAnsi(new IntPtr(BitConverter.ToInt64(data, startIndex + 0))); + this.index = BitConverter.ToUInt16(data, startIndex + 8); + this.numGraphs = BitConverter.ToUInt16(data, startIndex + 10); + this.type = (AcfAisacType)Enum.ToObject(typeof(AcfAisacType), BitConverter.ToUInt32(data, startIndex + 12)); + this.randomRange = BitConverter.ToSingle(data, startIndex + 16); + this.controlId = BitConverter.ToUInt16(data, startIndex + 20); + this.dummy = BitConverter.ToUInt16(data, startIndex + 22); + } + } + } + + /** + * AISAC graph type + * + */ + public enum AisacGraphType : int + { + none = 0, /**< Unused */ + volume, /**< Volume */ + pitch, /**< Pitch */ + bandpassHigh, /**< High cutoff frequency of the BandPass Filter */ + bandpassLow, /**< Low cutoff frequency of the BandPass Filter */ + biquadFreq, /**< Biquad Filter frequency */ + biquadQ, /**< Q value of the Biquad Filter */ + busSend0, /**< Bus Send Level 0 */ + busSend1, /**< Bus Send Level 1 */ + busSend2, /**< Bus Send Level 2 */ + busSend3, /**< Bus Send Level 3 */ + busSend4, /**< Bus Send Level 4 */ + busSend5, /**< Bus Send Level 5 */ + busSend6, /**< Bus Send Level 6 */ + busSend7, /**< Bus Send Level 7 */ + pan3dAngel, /**< Panning 3D angle */ + pan3dVolume, /**< Panning 3D volume */ + pan3dInteriorDistance, /**< Panning 3D distance */ + pan3dCenter, /**< Not used in ACB Ver.0.11.00 and later. */ + pan3dLfe, /**< Not used in ACB Ver.0.11.00 and later. */ + aisac0, /**< AISAC control ID 0 */ + aisac1, /**< AISAC control ID 1 */ + aisac2, /**< AISAC control ID 2 */ + aisac3, /**< AISAC control ID 3 */ + aisac4, /**< AISAC control ID 4 */ + aisac5, /**< AISAC control ID 5 */ + aisac6, /**< AISAC control ID 6 */ + aisac7, /**< AISAC control ID 7 */ + aisac8, /**< AISAC control ID 8 */ + aisac9, /**< AISAC control ID 9 */ + aisac10, /**< AISAC control ID 10 */ + aisac11, /**< AISAC control ID 11 */ + aisac12, /**< AISAC control ID 12 */ + aisac13, /**< AISAC control ID 13 */ + aisac14, /**< AISAC control ID 14 */ + aisac15, /**< AISAC control ID 15 */ + priority, /**< Voice Priority */ + preDelayTime, /**< Pre-delay */ + biquadGain, /**< Biquad Filter gain */ + pan3dMixdownCenter, /**< Panning 3D center level */ + pan3dMixdownLfe, /**< Panning 3D LFE level */ + egAttack, /**< Envelope Attack */ + egRelease, /**< Envelope Release */ + playbackRatio, /**< Sequence playback ratio */ + drySendL, /**< L ch dry send */ + drySendR, /**< R ch dry send */ + drySendCenter, /**< Center ch dry send */ + drySendLfe, /**< LFE ch dry send */ + drySendSl, /**< Surround L ch dry send */ + drySendSr, /**< Surround R ch dry send */ + drySendEx1, /**< Ex1 ch dry send */ + drySendEx2, /**< Ex2 ch dry send */ + panSpread, /**< Panning spread */ + } + + /** + * A structure for getting the AISAC Graph information + * + * A structure for getting the Global AISAC Graph information.
+ * Passed to the CriWare.CriAtomExAcf::GetGlobalAisacGraphInfo function as an argument.
+ *
+ * + */ + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + public struct AisacGraphInfo + { + public AisacGraphType type; /**< Graph type */ + + public AisacGraphInfo(byte[] data, int startIndex) + { + this.type = (AisacGraphType)Enum.ToObject(typeof(AisacGraphType), BitConverter.ToInt32(data, startIndex + 0)); + } + } + + /** + * Character code + * + * Indicates the character code (character encoding method).
+ *
+ * + */ + public enum CharacterEncoding : uint + { + utf8 = 0, /**< UTF-8 */ + sjis = 1, /**< Shift_JIS */ + } + + /** + * ACF information + * + * Detailed information of the ACF data.
+ * Passed to the CriWare.CriAtomExAcf::GetAcfInfo function as an argument.
+ *
+ * + */ + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + public struct AcfInfo + { + [MarshalAs(UnmanagedType.LPStr)] + public string name; /**< Name */ + public uint size; /**< Size */ + public uint version; /**< ACB version */ + public CharacterEncoding characterEncoding; /**< Character code */ + public int numDspSettings; /**< The number of DSP settings */ + public int numCategories; /**< The number of Categories */ + public int numCategoriesPerPlayback; /**< The number of Category references per playback */ + public int numReacts; /**< The number of REACTs */ + public int numAisacControls; /**< The number of AISAC controls */ + public int numGlobalAisacs; /**< The number of global AISACs */ + public int numGameVariables; /**< The number of game variables */ + public int maxBusesOfDspBusSettings; /**< Maximum number of buses in the DSP setting */ + public int numBuses; /**< The number of buses */ + public int numVoiceLimitGroups; /**< The number of Voice limit groups */ + public int numOutputPorts; /**< Number of output ports */ + + public AcfInfo(byte[] data, int startIndex) + { + if (IntPtr.Size == 4) + { + this.name = Marshal.PtrToStringAnsi(new IntPtr(BitConverter.ToInt32(data, startIndex + 0))); + this.size = BitConverter.ToUInt32(data, startIndex + 4); + this.version = BitConverter.ToUInt32(data, startIndex + 8); + this.characterEncoding = (CharacterEncoding)Enum.ToObject(typeof(CharacterEncoding), BitConverter.ToUInt32(data, startIndex + 12)); + this.numDspSettings = BitConverter.ToInt32(data, startIndex + 16); + this.numCategories = BitConverter.ToInt32(data, startIndex + 20); + this.numCategoriesPerPlayback = BitConverter.ToInt32(data, startIndex + 24); + this.numReacts = BitConverter.ToInt32(data, startIndex + 28); + this.numAisacControls = BitConverter.ToInt32(data, startIndex + 32); + this.numGlobalAisacs = BitConverter.ToInt32(data, startIndex + 36); + this.numGameVariables = BitConverter.ToInt32(data, startIndex + 40); + this.maxBusesOfDspBusSettings = BitConverter.ToInt32(data, startIndex + 44); + this.numBuses = BitConverter.ToInt32(data, startIndex + 48); + this.numVoiceLimitGroups = BitConverter.ToInt32(data, startIndex + 52); + this.numOutputPorts = BitConverter.ToInt32(data, startIndex + 56); + } + else + { + this.name = Marshal.PtrToStringAnsi(new IntPtr(BitConverter.ToInt64(data, startIndex + 0))); + this.size = BitConverter.ToUInt32(data, startIndex + 8); + this.version = BitConverter.ToUInt32(data, startIndex + 12); + this.characterEncoding = (CharacterEncoding)Enum.ToObject(typeof(CharacterEncoding), BitConverter.ToUInt32(data, startIndex + 16)); + this.numDspSettings = BitConverter.ToInt32(data, startIndex + 20); + this.numCategories = BitConverter.ToInt32(data, startIndex + 24); + this.numCategoriesPerPlayback = BitConverter.ToInt32(data, startIndex + 28); + this.numReacts = BitConverter.ToInt32(data, startIndex + 32); + this.numAisacControls = BitConverter.ToInt32(data, startIndex + 36); + this.numGlobalAisacs = BitConverter.ToInt32(data, startIndex + 40); + this.numGameVariables = BitConverter.ToInt32(data, startIndex + 44); + this.maxBusesOfDspBusSettings = BitConverter.ToInt32(data, startIndex + 48); + this.numBuses = BitConverter.ToInt32(data, startIndex + 52); + this.numVoiceLimitGroups = BitConverter.ToInt32(data, startIndex + 56); + this.numOutputPorts = BitConverter.ToInt32(data, startIndex + 60); + } + } + } + + /** + * A structure for getting the selector information + * + * A structure to get the selector information.
+ * Passed to the CriAtomExAcf::GetSelectorInfo function as an argument.
+ *
+ * + */ + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + public struct SelectorInfo + { + [MarshalAs(UnmanagedType.LPStr)] + public string name; /**< Selector name */ + public ushort index; /**< Data index */ + public ushort numLabels; /**< The number of labels */ + public ushort globalLabelIndex; /**< Global reference label index */ + + public SelectorInfo(byte[] data, int startIndex) + { + if (IntPtr.Size == 4) + { + this.name = Marshal.PtrToStringAnsi(new IntPtr(BitConverter.ToInt32(data, startIndex + 0))); + this.index = BitConverter.ToUInt16(data, startIndex + 4); + this.numLabels = BitConverter.ToUInt16(data, startIndex + 6); + this.globalLabelIndex = BitConverter.ToUInt16(data, startIndex + 8); + } + else + { + this.name = Marshal.PtrToStringAnsi(new IntPtr(BitConverter.ToInt64(data, startIndex + 0))); + this.index = BitConverter.ToUInt16(data, startIndex + 8); + this.numLabels = BitConverter.ToUInt16(data, startIndex + 10); + this.globalLabelIndex = BitConverter.ToUInt16(data, startIndex + 12); + } + } + } + + /** + * A structure for getting the Selector Label information + * + * A a structure for getting the Selector Label information.
+ * Passed to the CriWare.CriAtomExAcf::GetSelectorLabelInfo function as an argument.
+ *
+ * + */ + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + public struct SelectorLabelInfo + { + [MarshalAs(UnmanagedType.LPStr)] + public string selectorName; /**< Selector name */ + [MarshalAs(UnmanagedType.LPStr)] + public string labelName; /**< Selector Label name */ + + public SelectorLabelInfo(byte[] data, int startIndex) + { + if (IntPtr.Size == 4) + { + this.selectorName = Marshal.PtrToStringAnsi(new IntPtr(BitConverter.ToInt32(data, startIndex + 0))); + this.labelName = Marshal.PtrToStringAnsi(new IntPtr(BitConverter.ToInt32(data, startIndex + 4))); + } + else + { + this.selectorName = Marshal.PtrToStringAnsi(new IntPtr(BitConverter.ToInt64(data, startIndex + 0))); + this.labelName = Marshal.PtrToStringAnsi(new IntPtr(BitConverter.ToInt64(data, startIndex + 8))); + } + } + } + #endregion + + #region Exported API + /** + * Gets the number of AISAC controls + * The number of AISAC controls + * + * Gets the number of AISAC controls contained in the registered ACF.
+ * Returns -1 if no ACF file is registered.
+ *
+ */ + public static int GetNumAisacControls() + { + return criAtomExAcf_GetNumAisacControls(); + } + + /** + * Gets the AISAC control information + * AISAC control index + * AISAC control information + * Whether the information can be acquired. (Could be acquired: True / could not be acquired: False) + * + * Gets the AISAC control information from the AISAC control index.
+ * Returns False if there is no AISAC control with the specified index.
+ *
+ */ + public static bool GetAisacControlInfo(ushort index, out CriAtomEx.AisacControlInfo info) + { + using (var mem = new CriStructMemory()) + { + bool result = criAtomExAcf_GetAisacControlInfo(index, mem.ptr); + info = new CriAtomEx.AisacControlInfo(mem.bytes, 0); + return result; + } + } + + /** + * Gets the number of DSP bus settings + * The number of DSP bus settings + * + * Gets the number of DSP bus settings included in the ACF data registered with the library.
+ * This function returns -1 when ACF data is not registered.
+ *
+ */ + public static int GetNumDspSettings() + { + return criAtomExAcf_GetNumDspSettings(); + } + + /** + * Acquiring the DSP bus setting (from the specified ACF data) + * ACF data pointer + * ACF data size + * The number of DSP bus settings + * + * Gets the number of DSP bus settings contained in the specified ACF data.
+ * This function can be called before the ACF data is registered.
+ *
+ */ + public static int GetNumDspSettings(IntPtr acfData, int size) + { + return criAtomExAcf_GetNumDspSettingsFromAcfData(acfData, size); + } + + /** + * Acquiring the DSP bus setting's name + * DSP bus setting index + * DSP bus setting name + * + * Obtains the DSP bus setting name from the ACF data registered with the library.
+ * Returns null if no ACF data is registered or the DSP bus setting with the specified index does not exist.
+ *
+ */ + public static string GetDspSettingNameByIndex(ushort index) + { + var ptr = criAtomExAcf_GetDspSettingNameByIndex(index); + if (ptr == IntPtr.Zero) return null; + return Marshal.PtrToStringAnsi(ptr); + } + + /** + * Acquiring the DSP bus setting's name (from the specified ACF data) + * ACF data pointer + * ACF data size + * DSP bus setting index + * DSP bus setting name + * + * Obtains the DSP bus setting name from the ACF data registered with the library.
+ * This function can be called before the ACF data is registered.
+ *
+ */ + public static string GetDspSettingNameByIndex(IntPtr acfData, int size, ushort index) + { + var ptr = criAtomExAcf_GetDspSettingNameByIndexFromAcfData(acfData, size, index); + if (ptr == IntPtr.Zero) return null; + return Marshal.PtrToStringAnsi(ptr); + } + + /** + * Gets the DSP bus setting information + * Setting name + * Setting information + * Whether the information can be acquired. (Could be acquired: True / could not be acquired: False) + * + * Gets the setting information by specifying the setting name.
+ * Returns false if there is no DSP setting with the specified setting name.
+ *
+ */ + public static bool GetDspSettingInformation(string name, out AcfDspSettingInfo info) + { + using (var mem = new CriStructMemory()) + { + bool result = criAtomExAcf_GetDspSettingInformation(name, mem.ptr); + info = new AcfDspSettingInfo(mem.bytes, 0); + return result; + } + } + + /** + * Gets the DSP bus setting snapshot information + * Snapshot index + * Snapshot information + * Whether the information can be acquired. (Could be acquired: True / could not be acquired: False) + * + * Gets the snapshot information by specifying the snapshot index.
+ * Returns FALSE if there is no snapshot with the specified setting name.
+ * For the snapshot index, calculate an appropriate value based on the snapshotStartIndex and numSnapshots members + * in the CriAtomExAcf::AcfDspSettingInfo structure of the parent DSP bus setting information.
+ *
+ */ + public static bool GetDspSettingSnapshotInformation(ushort index, out AcfDspSettingSnapshotInfo info) + { + using (var mem = new CriStructMemory()) + { + bool result = criAtomExAcf_GetDspSettingSnapshotInformation(index, mem.ptr); + info = new AcfDspSettingSnapshotInfo(mem.bytes, 0); + return result; + } + } + + /** + * Gets the DSP bus + * Bus index + * Bus information + * Whether the information can be acquired. (Could be acquired: True / could not be acquired: False) + * + * Gets the DSP bus information by specifying the index.
+ * Returns False if there is no DSP bus with the specified index name.
+ *
+ */ + public static bool GetDspBusInformation(ushort index, out AcfDspBusInfo info) + { + using (var mem = new CriStructMemory()) + { + bool result = criAtomExAcf_GetDspBusInformation(index, mem.ptr); + info = new AcfDspBusInfo(mem.bytes, 0); + return result; + } + } + + /** + * Gets the DSP bus link + * DSP bus link index + * DSP bus link information + * Whether the information can be acquired. (Could be acquired: True / could not be acquired: False) + * + * Gets the bus link information by specifying the index.
+ * Returns False if there is no DSP bus link with the specified index name.
+ *
+ */ + public static bool GetDspBusLinkInformation(ushort index, out AcfDspBusLinkInfo info) + { + using (var mem = new CriStructMemory()) + { + bool result = criAtomExAcf_GetDspBusLinkInformation(index, mem.ptr); + info = new AcfDspBusLinkInfo(mem.bytes, 0); + return result; + } + } + + /** + * Gets the number of Categories + * The number of Categories + * + * Gets the number of Categories contained in the registered ACF. + * + */ + public static int GetNumCategories() + { + return criAtomExAcf_GetNumCategories(); + } + + /** + * Gets the number of Category references per playback + * The number of Category references per playback + * + * Gets the number of Category references by playback contained in the registered ACF. + * + */ + public static int GetNumCategoriesPerPlayback() + { + return criAtomExAcf_GetNumCategoriesPerPlayback(); + } + + /** + * Gets the Category information (index specified) + * Category index + * Category information + * Whether the information can be acquired. (Could be acquired: True / could not be acquired: False) + * + * Gets the Category information from the Category index.
+ * Returns False if there is no Category with the specified index.
+ *
+ */ + public static bool GetCategoryInfoByIndex(ushort index, out CategoryInfo info) + { + using (var mem = new CriStructMemory()) + { + bool result = criAtomExAcf_GetCategoryInfo(index, mem.ptr); + info = new CategoryInfo(mem.bytes, 0); + return result; + } + } + + /** + * Gets the Category information (Category name specified) + * Specify Category name + * Category information + * Whether the information can be acquired. (Could be acquired: True / could not be acquired: False) + * + * Gets Category information from the Category name.
+ * Returns False if there is no Category with the specified Category name.
+ *
+ */ + public static bool GetCategoryInfoByName(string name, out CategoryInfo info) + { + using (var mem = new CriStructMemory()) + { + bool result = criAtomExAcf_GetCategoryInfoByName(name, mem.ptr); + info = new CategoryInfo(mem.bytes, 0); + return result; + } + } + + /** + * Gets the Category information (Category ID specified) + * Category ID + * Category information + * Whether the information can be acquired. (Could be acquired: True / could not be acquired: False) + * + * Gets the Category information from the Category ID.
+ * Returns False if there is no category with the specified category ID.
+ *
+ */ + public static bool GetCategoryInfoById(uint id, out CategoryInfo info) + { + using (var mem = new CriStructMemory()) + { + bool result = criAtomExAcf_GetCategoryInfoById(id, mem.ptr); + info = new CategoryInfo(mem.bytes, 0); + return result; + } + } + + /** + * Gets the number of Global AISACs + * The number of Global AISACs + * + * Gets the number of Global AISAC contained in the registered ACF. + * + */ + public static int GetNumGlobalAisacs() + { + return criAtomExAcf_GetNumGlobalAisacs(); + } + + /** + * Gets the Global AISAC information (index specified) + * Global AISAC index + * Global AISAC information + * Whether the information can be acquired. (Could be acquired: True / could not be acquired: False) + * + * Gets AISAC information from the Global AISAC index.
+ * Returns False if there is no Global AISAC with the specified index.
+ *
+ */ + public static bool GetGlobalAisacInfoByIndex(ushort index, out GlobalAisacInfo info) + { + using (var mem = new CriStructMemory()) + { + bool result = criAtomExAcf_GetGlobalAisacInfo(index, mem.ptr); + info = new GlobalAisacInfo(mem.bytes, 0); + return result; + } + } + + /** + * Gets the Global AISAC information (name specified) + * Global AISAC name + * Global AISAC information + * Whether the information can be acquired. (Could be acquired: True / could not be acquired: False) + * + * Gets the AISAC information from the Global AISAC name
+ * Returns False if there is no Global AISAC with the specified name.
+ *
+ */ + public static bool GetGlobalAisacInfoByName(string name, out GlobalAisacInfo info) + { + using (var mem = new CriStructMemory()) + { + bool result = criAtomExAcf_GetGlobalAisacInfoByName(name, mem.ptr); + info = new GlobalAisacInfo(mem.bytes, 0); + return result; + } + } + + /** + * Gets the Global AISAC Graph information + * Global AISAC information + * Global AISAC graph index + * AISAC graph information + * Whether the information can be acquired. (Could be acquired: True / could not be acquired: False) + * + * Gets the graph information from the Global AISAC information and graph index.
+ * Returns False if there is no Global AISAC with the specified index.
+ *
+ */ + public static bool GetGlobalAisacGraphInfo(GlobalAisacInfo aisacInfo, ushort graphIndex, out AisacGraphInfo graphInfo) + { + bool result = false; + IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(GlobalAisacInfo))); + Marshal.StructureToPtr(aisacInfo, ptr, false); + using (var mem = new CriStructMemory()) + { + result = criAtomExAcf_GetGlobalAisacGraphInfo(ptr, graphIndex, mem.ptr); + graphInfo = new AisacGraphInfo(mem.bytes, 0); + } + Marshal.FreeHGlobal(ptr); + return result; + } + + /** + * Gets the Global AISAC value + * Global AISAC information + * AISAC control value + * Graph type + * AISAC value + * Whether the information can be acquired. (Could be acquired: True / could not be acquired: False) + * + * Gets the AISAC value by specifying Global AISAC information, control value and graph type.
+ * Returns False if there is no Global AISAC with the specified index or there is no graph.
+ *
+ */ + public static bool GetGlobalAisacValue(GlobalAisacInfo aisacInfo, float control, AisacGraphType type, out float value) + { + IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(GlobalAisacInfo))); + Marshal.StructureToPtr(aisacInfo, ptr, false); + bool result = criAtomExAcf_GetGlobalAisacValue(ptr, control, type, out value); + Marshal.FreeHGlobal(ptr); + return result; + } + + /** + * Gets the ACF information + * ACF information + * Whether the information can be acquired. (Could be acquired: True / could not be acquired: False) + * + * Gets various information on the ACF data registered with the library.
+ * Returns False if acquisition of the ACF information failed.
+ *
+ */ + public static bool GetAcfInfo(out AcfInfo acfInfo) + { + using (var mem = new CriStructMemory()) + { + bool result = criAtomExAcf_GetAcfInfo(mem.ptr); + acfInfo = new AcfInfo(mem.bytes, 0); + return result; + } + } + + /** + * Gets the number of selectors + * The number of selectors + * + * Gets the number of selectors contained in the registered ACF. + * + */ + public static int GetNumSelectors() + { + return criAtomExAcf_GetNumSelectors(); + } + + /** + * Gets the selector information (index specified) + * Selector index + * Selector information + * Whether the information can be acquired. (Could be acquired: True / could not be acquired: False) + * + * Gets the selector information from the selector index.
+ * Returns False if there is no selector with the specified index.
+ *
+ */ + public static bool GetSelectorInfoByIndex(ushort index, out SelectorInfo info) + { + using (var mem = new CriStructMemory()) + { + bool result = criAtomExAcf_GetSelectorInfoByIndex(index, mem.ptr); + info = new SelectorInfo(mem.bytes, 0); + return result; + } + } + + /** + * Gets the selector information (name specified) + * Selector name + * Selector information + * Whether the information can be acquired. (Could be acquired: True / could not be acquired: False) + * + * Get the selector information from the selector name.
+ * Returns False if there is no selector with the specified name.
+ *
+ */ + public static bool GetSelectorInfoByName(string name, out SelectorInfo info) + { + using (var mem = new CriStructMemory()) + { + bool result = criAtomExAcf_GetSelectorInfoByName(name, mem.ptr); + info = new SelectorInfo(mem.bytes, 0); + return result; + } + } + + /** + * Gets the Selector Label information + * Selector information + * Label index + * Selector Label information + * Whether the information can be acquired. (Could be acquired: True / could not be acquired: False) + * + * Gets the Selector Label information from the selector information and Selector Label index.
+ * Returns False if there is no Selector Label with the specified index.
+ *
+ */ + public static bool GetSelectorLabelInfo(SelectorInfo selectorInfo, ushort labelIndex, out SelectorLabelInfo info) + { + bool result = false; + IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(SelectorInfo))); + Marshal.StructureToPtr(selectorInfo, ptr, false); + using (var mem = new CriStructMemory()) + { + result = criAtomExAcf_GetSelectorLabelInfo(ptr, labelIndex, mem.ptr); + info = new SelectorLabelInfo(mem.bytes, 0); + } + Marshal.FreeHGlobal(ptr); + return result; + } + + /** + * Gets the number of buses + * The number of buses + * + * Gets the number of buses contained in the registered ACF. + * + */ + public static int GetNumBuses() + { + return criAtomExAcf_GetNumBuses(); + } + + /** + * Gets the maximum number of buses in the DSP bus settings + * Maximum number of buses in the DSP bus settings + * + * Gets the maximum number of buses in the DSP bus settings contained in the registered ACF. + * + */ + public static int GetMaxBusesOfDspBusSettings() + { + return criAtomExAcf_GetMaxBusesOfDspBusSettings(); + } + + /** + * Gets the bus name in ACF + * Bus name + * Bus name in ACF + * + * Gets the string in the ACF for the specified bus name.
+ * Returns NULL if you specify a bus name that does not exist.
+ *
+ */ + public static string FindBusName(string busName) + { + return criAtomExAcf_FindBusName(busName); + } + #endregion + + #region DLL Import +#if !CRIWARE_ENABLE_HEADLESS_MODE + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criAtomExAcf_GetNumAisacControls(); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool criAtomExAcf_GetAisacControlInfo(ushort index, IntPtr info); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern uint criAtomExAcf_GetAisacControlIdByName(string name); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern string criAtomExAcf_GetAisacControlNameById(uint id); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criAtomExAcf_GetNumDspSettings(); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criAtomExAcf_GetNumDspSettingsFromAcfData(IntPtr acf_data, int acf_data_size); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern IntPtr criAtomExAcf_GetDspSettingNameByIndex(ushort index); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern IntPtr criAtomExAcf_GetDspSettingNameByIndexFromAcfData(IntPtr acf_data, int acf_data_size, ushort index); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool criAtomExAcf_GetDspSettingInformation(string name, IntPtr info); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool criAtomExAcf_GetDspSettingSnapshotInformation(ushort index, IntPtr info); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool criAtomExAcf_GetDspBusInformation(ushort index, IntPtr info); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criAtomExAcf_GetDspFxType(ushort index); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern string criAtomExAcf_GetDspFxName(ushort index); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool criAtomExAcf_GetDspFxParameters(ushort index, IntPtr parameters, int size); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool criAtomExAcf_GetDspBusLinkInformation(ushort index, IntPtr info); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criAtomExAcf_GetNumCategoriesFromAcfData(IntPtr acf_data, int acf_data_size); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criAtomExAcf_GetNumCategories(); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criAtomExAcf_GetNumCategoriesPerPlaybackFromAcfData(IntPtr acf_data, int acf_data_size); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criAtomExAcf_GetNumCategoriesPerPlayback(); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool criAtomExAcf_GetCategoryInfo(ushort index, IntPtr info); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool criAtomExAcf_GetCategoryInfoByName(string name, IntPtr info); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool criAtomExAcf_GetCategoryInfoById(uint id, IntPtr info); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criAtomExAcf_GetNumGlobalAisacs(); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool criAtomExAcf_GetGlobalAisacInfo(ushort index, IntPtr info); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool criAtomExAcf_GetGlobalAisacInfoByName(string name, IntPtr info); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool criAtomExAcf_GetGlobalAisacGraphInfo(IntPtr aisac_info, ushort graph_index, IntPtr graph_info); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool criAtomExAcf_GetGlobalAisacValue(IntPtr aisac_info, float control, AisacGraphType type, out float value); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool criAtomExAcf_GetAcfInfo(IntPtr acf_info); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool criAtomExAcf_GetAcfInfoFromAcfData(IntPtr acf_data, int acf_data_size, IntPtr acf_info); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criAtomExAcf_GetNumSelectors(); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool criAtomExAcf_GetSelectorInfoByIndex(ushort index, IntPtr info); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool criAtomExAcf_GetSelectorInfoByName(string name, IntPtr info); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool criAtomExAcf_GetSelectorLabelInfo(IntPtr selector_info, ushort label_index, IntPtr info); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criAtomExAcf_GetNumBusesFromAcfData(IntPtr acf_data, int acf_data_size); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criAtomExAcf_GetNumBuses(); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criAtomExAcf_GetMaxBusesOfDspBusSettingsFromAcfData(IntPtr acf_data, int acf_data_size); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criAtomExAcf_GetMaxBusesOfDspBusSettings(); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern string criAtomExAcf_FindBusName(string bus_name); +#else + private static int criAtomExAcf_GetNumAisacControls() { return 0; } + private static bool criAtomExAcf_GetAisacControlInfo(ushort index, IntPtr info) { return false; } + private static uint criAtomExAcf_GetAisacControlIdByName(string name) { return 0; } + private static string criAtomExAcf_GetAisacControlNameById(uint id) { return null; } + private static int criAtomExAcf_GetNumDspSettings() { return 0; } + private static int criAtomExAcf_GetNumDspSettingsFromAcfData(IntPtr acf_data, int acf_data_size) { return 0; } + private static IntPtr criAtomExAcf_GetDspSettingNameByIndex(ushort index) { return IntPtr.Zero; } + private static IntPtr criAtomExAcf_GetDspSettingNameByIndexFromAcfData(IntPtr acf_data, int acf_data_size, ushort index) { return IntPtr.Zero; } + private static bool criAtomExAcf_GetDspSettingInformation(string name, IntPtr info) { return false; } + private static bool criAtomExAcf_GetDspSettingSnapshotInformation(ushort index, IntPtr info) { return false; } + private static bool criAtomExAcf_GetDspBusInformation(ushort index, IntPtr info) { return false; } + private static int criAtomExAcf_GetDspFxType(ushort index) { return 0; } + private static string criAtomExAcf_GetDspFxName(ushort index) { return null; } + private static bool criAtomExAcf_GetDspFxParameters(ushort index, IntPtr parameters, int size) { return false; } + private static bool criAtomExAcf_GetDspBusLinkInformation(ushort index, IntPtr info) { return false; } + private static int criAtomExAcf_GetNumCategoriesFromAcfData(IntPtr acf_data, int acf_data_size) { return 0; } + private static int criAtomExAcf_GetNumCategories() { return 0; } + private static int criAtomExAcf_GetNumCategoriesPerPlaybackFromAcfData(IntPtr acf_data, int acf_data_size) { return 0; } + private static int criAtomExAcf_GetNumCategoriesPerPlayback() { return 0; } + private static bool criAtomExAcf_GetCategoryInfo(ushort index, IntPtr info) { return false; } + private static bool criAtomExAcf_GetCategoryInfoByName(string name, IntPtr info) { return false; } + private static bool criAtomExAcf_GetCategoryInfoById(uint id, IntPtr info) { return false; } + private static int criAtomExAcf_GetNumGlobalAisacs() { return 0; } + private static bool criAtomExAcf_GetGlobalAisacInfo(ushort index, IntPtr info) { return false; } + private static bool criAtomExAcf_GetGlobalAisacInfoByName(string name, IntPtr info) { return false; } + private static bool criAtomExAcf_GetGlobalAisacGraphInfo(IntPtr aisac_info, ushort graph_index, IntPtr graph_info) { return false; } + private static bool criAtomExAcf_GetGlobalAisacValue(IntPtr aisac_info, float control, AisacGraphType type, out float value) { value = 0.0f; return false; } + private static bool criAtomExAcf_GetAcfInfo(IntPtr acf_info) { return false; } + private static bool criAtomExAcf_GetAcfInfoFromAcfData(IntPtr acf_data, int acf_data_size, IntPtr acf_info) { return false; } + private static int criAtomExAcf_GetNumSelectors() { return 0; } + private static bool criAtomExAcf_GetSelectorInfoByIndex(ushort index, IntPtr info) { return false; } + private static bool criAtomExAcf_GetSelectorInfoByName(string name, IntPtr info) { return false; } + private static bool criAtomExAcf_GetSelectorLabelInfo(IntPtr selector_info, ushort label_index, IntPtr info) { return false; } + private static int criAtomExAcf_GetNumBusesFromAcfData(IntPtr acf_data, int acf_data_size) { return 0; } + private static int criAtomExAcf_GetNumBuses() { return 0; } + private static int criAtomExAcf_GetMaxBusesOfDspBusSettingsFromAcfData(IntPtr acf_data, int acf_data_size) { return 0; } + private static int criAtomExAcf_GetMaxBusesOfDspBusSettings() { return 0; } + private static string criAtomExAcf_FindBusName(string bus_name) { return null; } +#endif + #endregion +} + +} //namespace CriWare +/** + * @} + */ + +/* --- end of file --- */ diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExAcf.cs.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExAcf.cs.meta new file mode 100644 index 0000000..08fef0b --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExAcf.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2ad20d2283b01d347b187547bbc5bfcf +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExAsrRack.cs b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExAsrRack.cs new file mode 100644 index 0000000..1e1f8a9 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExAsrRack.cs @@ -0,0 +1,506 @@ +/**************************************************************************** + * + * Copyright (c) 2016 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +/*--------------------------- + * Asr Support Defines + *---------------------------*/ +#if !UNITY_PSP2 +#define CRIWARE_SUPPORT_ASR +#endif + +using System; +using System.Runtime.InteropServices; + +/*========================================================================== + * CRI Atom Native Wrapper + *=========================================================================*/ +/** + * \addtogroup CRIATOM_NATIVE_WRAPPER + * @{ + */ + +namespace CriWare { + +/** + * ASR Rack + */ +public partial class CriAtomExAsrRack : CriDisposable +{ + #region Data Types + /** + * A config structure for creating an ASR Rack + * + * A structure for specifying the behavior of CriAtomExAsrRack.
+ * You pass this structure as an argument when creating a module (the CriWare.CriAtomExAsrRack::CriAtomExAsrRack function).
+ * Please change the default configuration obtained from CriWare.CriAtomExAsrRack::defaultConfig when needed.
+ *
+ * + * + */ + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + public struct Config + { + /** + * Frequency of server process + * + * Specifies the frequency of running the server process + * Set the same value as the one set to CriAtomConfig::serverFrequency for CriWareInitializer. + * + */ + public float serverFrequency; + + /** + * The number of buses + * + * Specifies the number of buses that ASR creates.
+ * The bus is responsible for mixing sounds and managing the DSPeffects.
+ *
+ */ + public int numBuses; + + /** + * The number of output channels + * + * Specifies the number of output channels of the ASR Rack.
+ * Specify 6ch or more channels when using pan 3D or 3D Positioning features.
+ *
+ */ + public int outputChannels; + + /** + * Output sampling rate + * + * Specifies the output and processing sampling rate of the ASR Rack.
+ * Normally, specify the sampling rate of the sound device on the target machine.
+ * Lowering it lowers the processing load but lowers the sound quality. + *
+ */ + public int outputSamplingRate; + + /** + * Sound renderer type + * + * Specifies the type of the output destination sound renderer of the ASR Rack.
+ * If you specify CriAtomEx.SoundRendererType.Native for soundRendererType, + * the sound data is transferred to each platform's default output.
+ *
+ */ + public CriAtomEx.SoundRendererType soundRendererType; + + /** + * Destination ASR Rack ID + * + * Specifies the ASR Rack ID of the ASR Rack's output destination.
+ * Valid only when you specify CriAtomEx.SoundRendererType.Asr for soundRendererType.
+ *
+ */ + public int outputRackId; + + /** + * Pointer to platform-specific parameters + * + * Specifies a pointer to platform-specific parameters.
+ * When using it as the argument to the CriAtomExAsrRack::CriAtomExAsrRack function, + * specify IntPtr.Zero because it is overwritten by the second argument PlatformContext.
+ *
+ */ + public IntPtr context; + } + + /** + * A platform-specific config structure for creating an ASR Rack + * + * A structure for specifying the behavior of CriAtomExAsrRack.
+ * You pass this structure as an argument when creating a module (the CriWare.CriAtomExAsrRack::CriAtomExAsrRack function).
+ * For details, refer to the platform-specific manual.
+ *
+ * + */ + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + public struct PlatformConfig + { + #if !UNITY_EDITOR && UNITY_PS4 + public int userId; + public CriWarePS4.AudioPortType portType; + public CriWarePS4.AudioPortAttribute portAttr; + #elif !UNITY_EDITOR && UNITY_SWITCH + public UInt32 npadId; + #else + public byte reserved; + #endif + } + + /** + * Performance information + * + * A structure for getting the performance information.
+ * Used in the CriWare.CriAtomExAsrRack::GetPerformanceInfo and CriWare.CriAtomExAsrRack::GetPerformanceInfoByRackId methods.
+ *
+ * + * + */ + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + public struct PerformanceInfo + { + public UInt32 processCount; /**< Number of signal generation processes */ + public UInt32 lastProcessTime; /**< Latest processing time (in microseconds) */ + public UInt32 maxProcessTime; /**< Maximum processing time (in microseconds) */ + public UInt32 averageProcessTime; /**< Average processing time (in microseconds) */ + public UInt32 lastProcessInterval; /**< Latest processing interval (in microseconds) */ + public UInt32 maxProcessInterval; /**< Maximum processing interval (in microseconds) */ + public UInt32 averageProcessInterval; /**< Average processing interval (in microseconds) */ + public UInt32 lastProcessSamples; /**< Latest number of samples generated in a single processing */ + public UInt32 maxProcessSamples; /**< Maximum number of samples generated in a single processing */ + public UInt32 averageProcessSamples; /**< Average number of samples generated in a single processing */ + } + #endregion + + /** + * Creating an ASR Rack + * Config structure + * Platform-specific parameter structure + * ASR Rack + * + * Creates an ASR Rack.
+ * Be sure to discard the ASR Rack created by this function using the Dispose function.
+ *
+ */ + public CriAtomExAsrRack(Config config, PlatformConfig platformConfig) + { + #if CRIWARE_SUPPORT_ASR + this._rackId = CRIWAREB4A7C956(ref config, ref platformConfig); + if (config.context != IntPtr.Zero) { + Marshal.FreeHGlobal(config.context); + } + if (this._rackId == -1) { + throw new Exception("CriAtomExAsrRack() failed."); + } + + CriDisposableObjectManager.Register(this, CriDisposableObjectManager.ModuleType.Atom); + #else + this._rackId = -1; + #endif + } + + /** + * Attaching the DSP bus settings + * Name of the DSP bus setting + * + * Build DSP buses from the DSP bus settings and attach them to the ASR Rack.
+ * To execute this function, it is necessary to register the ACF information with + * the CriAtomEx::RegisterAcf function in advance.
+ * This function is a return-on-complete function.
+ * Calling this function blocks the server processing of the Atom library for a while.
+ * If this function is called during sound playback, problems such as sound interruption may occur, + * so call this function at a timing when load fluctuations is accepted such as when switching scenes.
+ *
+ * + * + */ + public void AttachDspBusSetting(string settingName) + { + criAtomExAsrRack_AttachDspBusSetting(this.rackId, settingName, IntPtr.Zero, 0); + } + + /** + * Detaches the DSP bus settings + * + * Detaches the DSP bus settings.
+ * This function is a return-on-complete function.
+ * Calling this function blocks the server processing of the Atom library for a while.
+ * If this function is called during sound playback, problems such as sound interruption may occur, + * so call this function at a timing when load fluctuations is accepted such as when switching scenes.
+ *
+ * + */ + public void DetachDspBusSetting() + { + criAtomExAsrRack_DetachDspBusSetting(this.rackId); + } + + /** + * Applies the DSP bus snapshot + * DSP bus snapshot name + * The time (in milliseconds) until the snapshot is fully reflected + * + * Applies the DSP bus snapshot to the ASR Rack.
+ * When this function is called, the parameter values progressively change to + * the values saved in the snapshot. + * It takes timeMs milliseconds to complete the change.
+ *
+ */ + public void ApplyDspBusSnapshot(string snapshotName, int timeMs) + { + criAtomExAsrRack_ApplyDspBusSnapshot(this.rackId, snapshotName, timeMs); + } + + /** + * Gets the snapshot's name + * Rack ID + * Snapshot name + * + * Gets the current snapshot name. Returns null if none was set.
+ *
+ */ + public static string GetAppliedDspBusSnapshotName(int rackId) + { + string snapshotName; + IntPtr ptr = criAtomExAsrRack_GetAppliedDspBusSnapshotName(rackId); + if (ptr == IntPtr.Zero) { + return null; + } + snapshotName = Marshal.PtrToStringAnsi(ptr); + return snapshotName; + } + + /** + * Gets the snapshot's name + * Snapshot name + * + * Gets the current snapshot name. Returns null if none was set.
+ *
+ */ + public string GetAppliedDspBusSnapshotName() + { + string snapshotName; + IntPtr ptr = criAtomExAsrRack_GetAppliedDspBusSnapshotName(this.rackId); + if (ptr == IntPtr.Zero) { + return null; + } + snapshotName = Marshal.PtrToStringAnsi(ptr); + return snapshotName; + } + + /** + * Gets the performance information for the ASR rack + * ASR Rack performance information + * + * Gets performance information from the current ASR Rack instance.
+ *
+ * + * + */ + public PerformanceInfo GetPerformanceInfo() + { + PerformanceInfo info = new PerformanceInfo(); + if(this._rackId < 0) { + UnityEngine.Debug.LogError("[CRIWARE] This ASR Rack is not initialized."); + return info; + } + + criAtomExAsrRack_GetPerformanceInfo(this._rackId, out info); + return info; + } + + /** + * Gets the performance information for the ASR rack + * Rack ID + * ASR Rack performance information + * + * Gets performance information for the ASR Rack with the specified ID.
+ * If no Rack ID is specified, performance information for the default ASR Rack (created + * during the initialization of the library) will be returned.
+ * If an invalid Rack ID is specified, all the members of the structure returned will be set to 0.
+ *
+ * + * + */ + public static PerformanceInfo GetPerformanceInfoByRackId(int rackId = CriAtomExAsrRack.defaultRackId) + { + PerformanceInfo info = new PerformanceInfo(); + criAtomExAsrRack_GetPerformanceInfo(rackId, out info); + return info; + } + + /** + * Resets the performance measurements for the ASR rack + * + * Resets the performance measurement of the current ASR Rack instance.
+ *
+ * + * + */ + public void ResetPerformanceMonitor() + { + criAtomExAsrRack_ResetPerformanceMonitor(this._rackId); + } + + /** + * Resets the performance measurements for the ASR rack + * Rack ID + * + * Resets the performance measurement of the ASR Rack with the specified ID.
+ * If no Rack ID is specified, the performance information of the default ASR Rack + * (created during the initialization of the library) will be reset.
+ *
+ * + * + */ + public static void ResetPerformanceMonitorByRackId(int rackId = CriAtomExAsrRack.defaultRackId) + { + criAtomExAsrRack_ResetPerformanceMonitor(rackId); + } + + /** + * Setting the AISAC control value by name + * Rack ID + * AISAC control name + * AISAC control value + * + * Sets the AISAC control value by name. + * + */ + public static void SetAisacControl(int rackId, string controlName, float value) + { + criAtomExAsrRack_SetAisacControlByName(rackId, controlName, value); + } + + /** + * Setting AISAC control value by specifying an ID + * Rack ID + * AISAC control ID + * AISAC control value + * + * Sets the AISAC control value by specifying an ID. + * + */ + public static void SetAisacControl(int rackId, int controlId, float value) + { + criAtomExAsrRack_SetAisacControlById(rackId, (ushort)controlId, value); + } + + /** + * Discards an ASR Rack + * + * Discards an ASR Rack. + * + */ + public override void Dispose() + { + #if CRIWARE_SUPPORT_ASR + CriDisposableObjectManager.Unregister(this); + + if (this._rackId != -1) { + criAtomExAsrRack_Destroy(this._rackId); + this._rackId = -1; + } + #endif + GC.SuppressFinalize(this); + } + + public int rackId { + get { return this._rackId; } + } + + #region Static Properties + /** + * Default configuration + * + * Default config. + * Change the default configuration obtained using this property + * + * + */ + public static Config defaultConfig { + get { + Config config; + config.serverFrequency = 60.0f; + config.numBuses = 8; + config.soundRendererType = CriAtomEx.SoundRendererType.Native; + config.outputRackId = 0; + config.context = System.IntPtr.Zero; + #if !UNITY_EDITOR && UNITY_PS4 + config.outputChannels = 8; + config.outputSamplingRate = 48000; + #elif !UNITY_EDITOR && UNITY_IOS || UNITY_ANDROID + config.outputChannels = 2; + config.outputSamplingRate = 44100; + #elif !UNITY_EDITOR && UNITY_PSP2 + config.outputChannels = 2; + config.outputSamplingRate = 48000; + #else + config.outputChannels = 6; + config.outputSamplingRate = 48000; + #endif + return config; + } + } + + /** + * Default ASR Rack ID + * + * Default ASR Rack ID. + * When returning to normal output or discarding the generated ASR Rack, use this constant + * for each player to specify the ASR Rack ID. + * + * + * + */ + public const int defaultRackId = 0; + + #endregion + + + #region internal members + ~CriAtomExAsrRack() + { + this.Dispose(); + } + + private int _rackId = -1; + #endregion + + #region DLL Import + #if CRIWARE_SUPPORT_ASR + + #if !CRIWARE_ENABLE_HEADLESS_MODE + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int CRIWAREB4A7C956([In] ref Config config, [In] ref PlatformConfig platformConfig); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExAsrRack_Destroy(Int32 rackId); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExAsrRack_AttachDspBusSetting(Int32 rackId, string setting, IntPtr work, Int32 workSize); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExAsrRack_DetachDspBusSetting(Int32 rackId); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern IntPtr criAtomExAsrRack_GetAppliedDspBusSnapshotName(int rackId); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExAsrRack_ApplyDspBusSnapshot(Int32 rackId, string snapshotName, Int32 timeMs); + #else + private static int CRIWAREB4A7C956([In] ref Config config, [In] ref PlatformConfig platformConfig) { return 0; } + private static void criAtomExAsrRack_Destroy(Int32 rackId) { } + private static void criAtomExAsrRack_AttachDspBusSetting(Int32 rackId, string setting, IntPtr work, Int32 workSize) { } + private static void criAtomExAsrRack_DetachDspBusSetting(Int32 rackId) { } + private static void criAtomExAsrRack_ApplyDspBusSnapshot(Int32 rackId, string snapshotName, Int32 timeMs) { } + private static IntPtr criAtomExAsrRack_GetAppliedDspBusSnapshotName(int rackId) { return IntPtr.Zero; } + #endif + + #if !CRIWARE_ENABLE_HEADLESS_MODE && !UNITY_WEBGL + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExAsrRack_GetPerformanceInfo(Int32 rackId, out PerformanceInfo perfInfo); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExAsrRack_ResetPerformanceMonitor(Int32 rackId); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExAsrRack_SetAisacControlById(Int32 rackId, ushort controlId, float value); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExAsrRack_SetAisacControlByName(Int32 rackId, string controlName, float value); + #else + private static void criAtomExAsrRack_GetPerformanceInfo(Int32 rackId, out PerformanceInfo perfInfo) { perfInfo = new PerformanceInfo(); } + private static void criAtomExAsrRack_ResetPerformanceMonitor(Int32 rackId) { } + private static void criAtomExAsrRack_SetAisacControlById(Int32 rackId, ushort controlId, float value) { } + private static void criAtomExAsrRack_SetAisacControlByName(Int32 rackId, string controlName, float value) { } + #endif + + #endif + #endregion +} + +} //namespace CriWare +/** + * @} + */ + +/* --- end of file --- */ diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExAsrRack.cs.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExAsrRack.cs.meta new file mode 100644 index 0000000..d404d70 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExAsrRack.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: f7655a4f183e17243bacc3625bae3104 +timeCreated: 1478751988 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExAuxIn.cs b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExAuxIn.cs new file mode 100644 index 0000000..e5f85af --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExAuxIn.cs @@ -0,0 +1,390 @@ +/**************************************************************************** + * + * Copyright (c) 2018 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +#if (UNITY_EDITOR && !UNITY_EDITOR_LINUX) || UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX || UNITY_ANDROID || UNITY_IOS +#define CRIWAREPLUGIN_SUPPORT_AUXIN +#pragma warning disable 0414 +#endif + +using System; +using System.Runtime.InteropServices; +using UnityEngine; + +/*========================================================================== + * CRI Atom Native Wrapper + *=========================================================================*/ +/** + * \addtogroup CRIATOM_NATIVE_WRAPPER + * @{ + */ + +namespace CriWare { + +/** + * AuxIn for reading external sound + * + * AuxIn can send the sound data external to ADX2 to the DSP bus of ADX2.
+ * Controls the start of playing back input data, gets status, writes input data etc.
+ *
+ */ +public class CriAtomExAuxIn : CriDisposable +{ + /** + * A config structure for creating an AuxIn + * + * A structure for specifying the behavior for creating an AuxIn handle for capturing sound.
+ * Specify it as an argument at the time of creation.
+ *
+ * The created AuxIn handle reserves as many internal resources as necessary, + * depending on the settings specified in this structure when the handle is created.
+ * The size of the work area required for the player varies according to the parameters specified in this structure.
+ *
+ */ + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + public struct Config + { + /** + * Maximum number of output channels + * + * Specifies the number of sound channels to be played by the AtomIn player.
+ * The created AuxIn can play sound data that is "equal to or less than" + * the number of channels specified with max_channels.
+ * The relationship between the value specified as the maximum number of output channels + * and the data that can be played back by the created AuxIn is as follows:
+ * |Maximum number of output channels (specified value) | Data that can be played by the created AuxIn | + * |-------------------------------|-------------------------------| + * |1 | Mono | + * |2 | Mono, stereo | + * |6 | Mono, stereo, 5.1ch | + * |8 | Mono, stereo, 5.1ch, 7.1ch | + *
+ * For platforms that use hardware resources when outputting sound, it is + * possible to reduce the consumption of hardware resources by reducing the number + * of output channels.
+ * Data exceeding the specified maximum number of output channels cannot be played.
+ * For example, if the maximum number of output channels is set to 1, the created AuxIn + * cannot play stereo sound.
+ * (It will not be downmixed to monaural and output.)
+ *
+ */ + public int maxChannels; + + /** + * Maximum sampling rate + * + * Specifies the sampling rate of the sound played by the AuxIn.
+ * The created AuxIn can play sound data that is "equal to or less than" + * the sampling rate specified with max_sampling_rate.
+ *
+ * By lowering the maximum sampling rate, it is possible to reduce the size of the work memory + * required when creating AuxIn. + * Data that exceeds the specified maximum sampling rate cannot be played.
+ * For example, if the maximum sampling rate is set to 24000, the created AuxIn + * cannot play sound with 48000Hz.
+ * (It is not down-sampled and output.)
+ *
+ */ + public int maxSamplingRate; + + /** + * Sound renderer type + * + * Specifies the type of the sound renderer to be used by AuxIn.
+ * When set to CriAtomEx.SoundRendererType.Native, + * the sound data is sent to the sound output of each platform.
+ * When set to CriAtomEx.SoundRendererType.Asr, + * the sound data is sent to ASR (Atom Sound Renderer).
+ * (The destination of ASR is specified separately when ASR is initialized.)
+ *
+ */ + public CriAtomEx.SoundRendererType soundRendererType; + + public static Config Default { + get { + Config config = new Config(); + config.maxChannels = 2; + config.maxSamplingRate = 48000; + config.soundRendererType = CriAtomEx.SoundRendererType.Asr; + return config; + } + } + } + + #region Error Messages + private const string errorInvalidHandle = "[CRIWARE] Invalid native handle of CriAtomExAuxIn."; + #endregion + + #region Internal Members +#if CRIWAREPLUGIN_SUPPORT_AUXIN + private IntPtr handle = IntPtr.Zero; + private CriAudioReadStream inputReadStream; +#endif + #endregion + + /** + * Creates an AuxIn + * A config structure for creating an AuxIn + * AtomAuxIn handle + * + * Creates an AuxIn for capturing sound.
+ * AuxIn can send the sound data external to ADX2 to the DSP bus of ADX2.
+ *
+ * To start playing a sound, call the CriWare.CriAtomExAuxIn::Start function.
+ * You pass the sound to be captured to AuxIn through the callback function + * specified to CriWare.CriAtomExAuxIn::SetInputReadStream .
+ * This function is a return-on-complete function. The time it takes depends on the platform.
+ * Create/discard microphone at a timing when load fluctuations is accepted + * such as when switching scenes.
+ *
+ * + */ + public CriAtomExAuxIn(Config? config = null) + { +#if CRIWAREPLUGIN_SUPPORT_AUXIN + CriDisposableObjectManager.Register(this, CriDisposableObjectManager.ModuleType.Atom); + Config internalConfig = (config.HasValue) ? config.Value : Config.Default; + this.handle = criAtomAuxIn_Create(ref internalConfig, IntPtr.Zero, 0); +#else + Debug.LogError("[CRIWARE] CriAtomExAuxIn does not support this platform."); +#endif + } + + ~CriAtomExAuxIn(){ + Dispose(); + } + + /** + * Discards an AuxIn + * + * Discard an AuxIn.
+ * This function is a return-on-complete function. The time it takes depends on the platform.
+ * Create/discard microphone at a timing when load fluctuations is accepted + * such as when switching scenes.
+ *
+ * + */ + public override void Dispose() + { +#if CRIWAREPLUGIN_SUPPORT_AUXIN + if (this.handle != IntPtr.Zero) { + criAtomAuxIn_Destroy(this.handle); + this.handle = IntPtr.Zero; + } + GC.SuppressFinalize(this); + CriDisposableObjectManager.Unregister(this); +#endif + } + + /** + * Starts the playback of AuxIn + * + * Starts the playback of AuxIn.
+ *
+ * + */ + public void Start() + { +#if CRIWAREPLUGIN_SUPPORT_AUXIN + Debug.Assert(this.handle != IntPtr.Zero, errorInvalidHandle); + criAtomAuxIn_Start(this.handle); +#endif + } + + /** + * Stops the playback of AuxIn + * + * Stops the playback of AuxIn.
+ *
+ * + */ + public void Stop() + { +#if CRIWAREPLUGIN_SUPPORT_AUXIN + if (this.handle == IntPtr.Zero) { + return; + } + criAtomAuxIn_Stop(this.handle); +#endif + } + + /** + * Set the format + * The number of channels + * Sampling frequency + * + * Sets the format of the sound to be played.
+ * It must be set before calling CriWare.CriAtomExAuxIn::Start .
+ *
+ * + */ + public void SetFormat(int numChannels, int samplingRate) + { +#if CRIWAREPLUGIN_SUPPORT_AUXIN + criAtomAuxIn_SetFormat(this.handle, numChannels, samplingRate); +#endif + } + + /** + * Gets the format + * The number of channels + * Sampling frequency + * + * Gets the format information set by CriWare.CriAtomExAuxIn::SetFormat .
+ *
+ * + */ + public void GetFormat(out int numChannels, out int samplingRate) + { +#if CRIWAREPLUGIN_SUPPORT_AUXIN + criAtomAuxIn_GetFormat(this.handle, out numChannels, out samplingRate); +#else + numChannels = 0; + samplingRate = 0; +#endif + } + + /** + * Volume setting + * Volume value + * + * Sets the volume of the AuxIn sound.
+ *
+ * The volume value is a scale factor for the amplitude of the sound data (the unit is not decibel).
+ * For example, if you specify 1.0f, the original sound is played at its unmodified volume.
+ * If you specify 0.5f, the sound is played at the volume by halving the amplitude (-6dB) + * of the original waveform.
+ * If you specify 0.0f, the sound is muted (silent).
+ *
+ */ + public void SetVolume(float volume) + { +#if CRIWAREPLUGIN_SUPPORT_AUXIN + criAtomAuxIn_SetVolume(this.handle, volume); +#endif + } + + /** + * Sets the frequency adjustment ratio + * Frequency adjustment ratio (0.25f to 4.0f) + * + * Sets the sound frequency adjustment ratio of AuxIn.
+ * The frequency adjustment ratio is the ratio of the sound data frequency to the playback frequency and is equivalent to the playback speed multiplication factor.
+ * If the frequency ratio exceeds 1.0f, the sound data is played faster than the original sound, + * and if the frequency ratio is less than 1.0f, the sound data is played slower than the original sound.
+ *
+ * The frequency ratio also affects the pitch of the sound.
+ * For example, if the sound is played with the frequency ratio of 1.0f, the sound data is played back at the pitch of the original sound, + * but if the frequency ratio is changed to 2.0f, the pitch goes up by one octave.
+ * (Because the playback speed is doubled.)
+ * If the frequency ratio higher than 1.0f is set, the sound data to be played is + * consumed faster than usual, so it is necessary to supply the sound data faster.
+ * When setting the frequency ratio higher than 1.0f, set the maximum sampling rate + * specified when creating the AuxIn considering the frequency ratio.
+ * (You must set maxSamplingRate in CriWare.CriAtomExAuxIn::Config structure + * when creating AuxIn to a value calculated with + * "sampling rate of original sound x frequency ratio")
+ *
+ */ + public void SetFrequencyRatio(float frequencyRatio) + { +#if CRIWAREPLUGIN_SUPPORT_AUXIN + criAtomAuxIn_SetFrequencyRatio(this.handle, frequencyRatio); +#endif + } + + /** + * Sets the Bus Send Level + * Bus name + * Level value(0.0f~1.0f) + * + * Sets the Bus Send Level of the AuxIn sound.
+ * The Bus Send Level is a mechanism for specifying how much sound should be sent to which bus.
+ *
+ * For the second argument, specify the bus name in the DSP bus setting.
+ * The third argument specifies the level (volume) when sending.
+ *
+ * If the bus specified by the bus name as the second argument does not exist in the DSP bus settings being applied, the setting is treated as invalid.
+ * The range and handling of the send level values are the same as for volume. Refer to the CriWare.CriAtomExAuxIn::SetVolume function.
+ *
+ */ + public void SetBusSendLevel(string busName, float level) + { +#if CRIWAREPLUGIN_SUPPORT_AUXIN + criAtomAuxIn_SetBusSendLevelByName(this.handle, busName, level); +#endif + } + + /** + * Sets the read stream + * Read stream + * + * Sets the read stream in the input direction of AuxIn.
+ * The callback function is called from a separate thread on most platforms, + * so the callee must be implemented as thread-safe.
+ *
+ */ + public void SetInputReadStream(CriAudioReadStream stream) + { +#if CRIWAREPLUGIN_SUPPORT_AUXIN + this.inputReadStream = stream; + criAtomAuxIn_SetInputReadStream(this.handle, stream.callbackFunction, stream.callbackPointer); +#endif + } + + #region DLL Import +#if CRIWAREPLUGIN_SUPPORT_AUXIN + #if !CRIWARE_ENABLE_HEADLESS_MODE + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern IntPtr criAtomAuxIn_Create([In] ref Config config, IntPtr work, int work_size); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomAuxIn_Destroy(IntPtr aux_in); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomAuxIn_Start(IntPtr aux_in); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomAuxIn_Stop(IntPtr aux_in); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomAuxIn_SetVolume(IntPtr aux_in, float volume); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomAuxIn_SetFrequencyRatio(IntPtr aux_in, float ratio); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomAuxIn_SetBusSendLevelByName(IntPtr aux_in, string bus_name, float level); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomAuxIn_SetFormat(IntPtr aux_in, int num_channels, int sampling_rate); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomAuxIn_GetFormat(IntPtr aux_in, out int num_channels, out int sampling_rate); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomAuxIn_SetInputReadStream(IntPtr aux_in, IntPtr stream_cbfunc, IntPtr stream_ptr); + #else + private static IntPtr criAtomAuxIn_Create([In] ref Config config, IntPtr work, int work_size) { return new IntPtr(1); } + private static void criAtomAuxIn_Destroy(IntPtr aux_in) { } + private static void criAtomAuxIn_Start(IntPtr aux_in) { } + private static void criAtomAuxIn_Stop(IntPtr aux_in) { } + private static void criAtomAuxIn_SetVolume(IntPtr aux_in, float volume) { } + private static void criAtomAuxIn_SetFrequencyRatio(IntPtr aux_in, float ratio) { } + private static void criAtomAuxIn_SetBusSendLevelByName(IntPtr aux_in, string bus_name, float level) { } + private static void criAtomAuxIn_SetFormat(IntPtr aux_in, int num_channels, int sampling_rate) { } + private static void criAtomAuxIn_GetFormat(IntPtr aux_in, out int num_channels, out int sampling_rate) { num_channels = sampling_rate = 0; } + private static void criAtomAuxIn_SetInputReadStream(IntPtr aux_in, IntPtr stream_cbfunc, IntPtr stream_ptr) { } + #endif +#endif + #endregion +} + +} //namespace CriWare +/** + * @} + */ + +/* --- end of file --- */ diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExAuxIn.cs.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExAuxIn.cs.meta new file mode 100644 index 0000000..7eb799e --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExAuxIn.cs.meta @@ -0,0 +1,13 @@ +fileFormatVersion: 2 +guid: e7faa56a121b65b4aba19899d381e0ec +timeCreated: 1532400114 +licenseType: Free +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExMic.cs b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExMic.cs new file mode 100644 index 0000000..716c72e --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExMic.cs @@ -0,0 +1,1098 @@ +/**************************************************************************** + * + * Copyright (c) 2018 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +#if (UNITY_EDITOR && !UNITY_EDITOR_LINUX) || UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX || UNITY_ANDROID || UNITY_IOS +#define CRIWAREPLUGIN_SUPPORT_MIC +#endif + +using System; +using System.Runtime.InteropServices; +using UnityEngine; + +/*========================================================================== + * CRI Atom Native Wrapper + *=========================================================================*/ +/** + * \addtogroup CRIATOM_NATIVE_WRAPPER + * @{ + */ + +namespace CriWare { + +/** + * Microphone for capturing sound + * + * A class for capturing input from a physical microphone or sound device.
+ * Performs control such as starting input, getting status and getting data.
+ * You can also get the information about the sound input device using CriWare.CriAtomExMic::GetDevices .
+ *
+ */ +public class CriAtomExMic : CriDisposable +{ + /** + * Microphone device information structure + * + * A structure for sound input device information.
+ * The device information is acquired from CriWare.CriAtomExMic::GetDevices .
+ *
+ */ + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + public struct DeviceInfo + { + /** + * Device ID + * + * A string which indicates the identifier of the platform audio input device.
+ *
+ */ + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1024)] + public string deviceId; + /** + * Device name + * + * Name information for the platform audio input device.
+ *
+ */ + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1024)] + public string deviceName; + /** + * Device flag + * + * A flag that is referenced when creating an audio input device.
+ *
+ */ + public uint deviceFlags; + /** + * Maximum number of channels + * + * Maximum number of channels supported.
+ *
+ */ + public int maxChannels; + /** + * Maximum sampling frequency + * + * Maximum supported sampling frequency.
+ *
+ */ + public int maxSamplingRate; + } + + /** + * A config structure for creating an AtomEx microphone + * + * A structure for specifying the behavior for creating an AtomEx microphone.
+ * It is specified as an argument of the CriWare.CriAtomExMic::Create function.
+ *
+ * + */ + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + public struct Config + { + /** + * Device ID + * + * A string which indicates the identifier of the platform audio input device.
+ * Specify CRIATOMMIC_DEFAULT_DEVICE_ID if you don't want to specify one.
+ *
+ * + * + */ + [MarshalAs(UnmanagedType.LPStr)] + public string deviceId; + /** + * Creation flag + * + * A flag that is referenced when creating an audio input device.
+ *
+ */ + public uint flags; + /** + * The number of channels + * + * The number of channels required for audio input. The default is 1.
+ * The creation fails if you specify an unsupported number of channels.
+ *
+ * + */ + public int numChannels; + /** + * Sampling rate + * + * The sampling frequency required for audio input. The default is 44100.
+ * The creation fails if you specify a non-supported sampling frequency.
+ *
+ * + */ + public int samplingRate; + /** + * Frame size (number of samples) + * + * The number of samples indicating the size of 1 frame. The default is 256.
+ * This is the processing unit of the effect for which CriWare.CriAtomExMic::AttachEffect was called.
+ *
+ */ + public uint frameSize; + /** + * Buffer size (ms) + * + * The size of the buffer maintained internally. The default is 50msec.
+ * This is the processing unit of the effect for which CriWare.CriAtomExMic::AttachEffect was called.
+ *
+ */ + public uint bufferingTime; + /** + * Platform context + * + * It is not used at this time.
+ *
+ */ + public IntPtr context; + + /** + * Default setting + * + * The default setting for the config structure.
+ *
+ */ + public static Config Default { + get { + Config config = new Config(); + config.deviceId = null; + config.flags = 0; + config.numChannels = 1; + config.samplingRate = 44100; + config.frameSize = 256; + config.bufferingTime = 50; + return config; + } + } + } + + /** + * Microphone effect + * + * A class for the effect applied to the input sound of the microphone.
+ * Returned by CriWare.CriAtomExMic::AttachEffect .
+ *
+ * + * + */ + public class Effect + { + public IntPtr handle { get; private set; } + public IntPtr afxInstance { get; private set; } + + public Effect(IntPtr handle, IntPtr afxInstance) + { + this.handle = handle; + this.afxInstance = afxInstance; + } + } + + #region Error Messages + private const string errorInvalidHandle = "[CRIWARE] Invalid native handle of CriAtomMic."; + private const string errorInvalidBufferLength = "[CRIWARE] Invalid buffer length for CriAtomMic.ReadData."; + private const string errorInvalidNumBuffers = "[CRIWARE] Number of buffers are not same with channels of CriAtomMic."; + private const string errorAlreadyInitialized = "[CRIWARE] CriAtomMic module is already initialized."; + private const string errorNotInitialized = "[CRIWARE] CriAtomMic module is not initialized."; + #endregion + + public static bool isInitialized { get; private set; } + + /** + * Initializes the CriAtomMic module + * + * Initializes the CriAtomMic module.
+ * In order to use the function of the module, you must call this function.
+ * (You can use the features of the module after calling this function and before calling the CriWare.CriAtomExMic::FinalizeModule function.)
+ * After calling this function, be sure to call the corresponding CriWare.CriAtomExMic::FinalizeModule function.
+ * In addition, this function cannot be called again until the CriWare.CriAtomExMic::FinalizeModule function is called.
+ *
+ * + */ + public static void InitializeModule() + { + _initializationCount++; + if (_initializationCount > 1) { + return; + } + +#if CRIWAREPLUGIN_SUPPORT_MIC + if (isInitialized) { + Debug.LogError(errorAlreadyInitialized); + return; + } + criAtomMicUnity_Initialize(); + isInitialized = true; +#else + Debug.LogError("[CRIWARE] CriAtomExMic does not support this platform."); +#endif + } + + /** + * Terminates the CriAtomMic module + * + * Terminates the CriAtomMic module.
+ *
+ * + */ + public static void FinalizeModule() + { + _initializationCount--; + if (_initializationCount > 0) { + return; + } else if (_initializationCount < 0) { + _initializationCount = 0; + } + +#if CRIWAREPLUGIN_SUPPORT_MIC + if (!isInitialized) { + Debug.LogError(errorNotInitialized); + return; + } + CriDisposableObjectManager.CallOnModuleFinalization(CriDisposableObjectManager.ModuleType.AtomMic); + criAtomMicUnity_Finalize(); + isInitialized = false; +#endif + } + + /** + * [iOS] Sets the output category of the microphone input + * Enable or disable the setting (True: enable, False: disable) + * + * Set the category (AVAudioSessionCategory) to use the microphone on iOS.
+ *
+ * The processing performed by calling this function will also be performed within CriWare.CriAtomExMic::InitializeModule and + * CriWare.CriAtomExMic::FinalizeModule .
+ * Therefore, it is usually not neccessary to call this function directly.
+ * This function should only be used when the AVAudioSessionCategory setting needs to be changed, + * in order to use an external microphone input module other than the regular CriAtomExMic module.
+ *
+ * + * + */ + public static void SetupOutputCategoryForMic_IOS(bool enable) + { +#if !UNITY_EDITOR && UNITY_IOS + criAtomUnity_SetMicEnabled_IOS(enable); +#endif + } + + /** + * Gets the microphone device + * Microphone device array + * + * Gets information on the microphone device.
+ *
+ * + */ + public static DeviceInfo[] GetDevices() + { +#if CRIWAREPLUGIN_SUPPORT_MIC + if (!isInitialized) { + Debug.LogError(errorNotInitialized); + return null; + } + + int numDevices = criAtomMic_GetNumDevices(); + var devices = new DeviceInfo[numDevices]; + for (int i = 0; i < numDevices; i++) { + criAtomMic_GetDevice(i, out devices[i]); + } + return devices; +#else + return null; +#endif + } + + /** + * Gets the number of microphone devices + * The number of microphone devices + * + * Gets the number of microphone devices connected to the terminal.
+ *
+ * + */ + public static int GetNumDevices() + { +#if CRIWAREPLUGIN_SUPPORT_MIC + return criAtomMic_GetNumDevices(); +#else + return 0; +#endif + } + + /** + * Gets the default microphone device + * Microphone device structure + * + * Gets the information about the default microphone device.
+ *
+ * + */ + public static DeviceInfo? GetDefaultDevice() + { +#if CRIWAREPLUGIN_SUPPORT_MIC + if (!isInitialized) { + Debug.LogError(errorNotInitialized); + return null; + } + + var device = new DeviceInfo(); + bool result = criAtomMic_GetDefaultDevice(out device); + if (result) { + return device; + } +#endif + return null; + } + + /** + * Gets the format support status + * Config information + * True: supported, False: not supported + * + * Gets whether the specified format in the config information is supported.
+ *
+ * + */ + public static bool IsFormatSupported(Config config) + { +#if CRIWAREPLUGIN_SUPPORT_MIC + return criAtomMic_IsFormatSupported(ref config); +#else + return false; +#endif + } + + #region Internal Members + private IntPtr handle = IntPtr.Zero; + private IntPtr[] bufferPointers = null; + private GCHandle[] gcHandles = null; +#if CRIWAREPLUGIN_SUPPORT_MIC + private CriAudioWriteStream outputWriteStream = null; +#endif + + private static int _initializationCount = 0; + #endregion + + /** + * Creates an AtomEx microphone + * Config information + * AtomEx microphone + * + * Creates a microphone instance for capturing sound.
+ *
+ * Calling the CriWare.CriAtomExMic::Create function creates an AtomEx microphone + * and an instance ( CriAtomExMic ) for controlling the microphone is returned.
+ *
+ * This function returns null if it failed to open the sound input device. + *
+ * To actually start sound input, call the CriWare.CriAtomExMic::Start function.
+ * Use the CriWare.CriAtomExMic::ReadData function for getting the captured sound data.
+ *
+ * + */ + public static CriAtomExMic Create(Config? config = null) + { +#if CRIWAREPLUGIN_SUPPORT_MIC + if (!isInitialized) { + Debug.LogError(errorNotInitialized); + return null; + } + + Config internalConfig = (config.HasValue) ? config.Value : Config.Default; + IntPtr handle = criAtomMic_Create(ref internalConfig, IntPtr.Zero, 0); + if (handle == IntPtr.Zero) { + Debug.LogWarning("Failed to open audio input device."); + return null; + } + return new CriAtomExMic(handle); +#else + return null; +#endif + } + + private CriAtomExMic(IntPtr handle) + { +#if CRIWAREPLUGIN_SUPPORT_MIC + this.handle = handle; + int numChannels = this.GetNumChannels(); + this.bufferPointers = new IntPtr[numChannels]; + this.gcHandles = new GCHandle[numChannels]; + + CriDisposableObjectManager.Register(this, CriDisposableObjectManager.ModuleType.AtomMic); +#endif + } + + ~CriAtomExMic(){ + Dispose(); + } + + /** + * Discards the microphone + * + * Discard the microphone for capturing sound.
+ * This function is a return-on-complete function. The time it takes depends on the platform.
+ * If this function is called at a timing when the screen needs to be updated such as in a game loop, + * the process is blocked in the unit of milliseconds, resulting in dropped frames.
+ * Create/discard microphone at a timing when load fluctuations is accepted + * such as when switching scenes.
+ *
+ * + */ + public override void Dispose() + { + this.Dispose(true); + GC.SuppressFinalize(this); + } + + private void Dispose(bool disposing) + { +#if CRIWAREPLUGIN_SUPPORT_MIC + CriDisposableObjectManager.Unregister(this); + + if (this.handle != IntPtr.Zero) { + criAtomMic_Destroy(this.handle); + this.handle = IntPtr.Zero; + } +#endif + } + + /** + * Starts microphone sound capturing + * + * Starts capturing sounds by the microphone.
+ *
+ * + * + */ + public void Start() + { +#if CRIWAREPLUGIN_SUPPORT_MIC + Debug.Assert(this.handle != IntPtr.Zero, errorInvalidHandle); + criAtomMic_Start(this.handle); +#endif + } + + /** + * Stops the microphone sound capturing + * + * Stops capturing sound by the microphone.
+ *
+ * + * + */ + public void Stop() + { +#if CRIWAREPLUGIN_SUPPORT_MIC + Debug.Assert(this.handle != IntPtr.Zero, errorInvalidHandle); + criAtomMic_Stop(this.handle); +#endif + } + + /** + * Gets the number of microphone channels + * The number of channels + * + * Gets the number of microphone channels.
+ *
+ */ + public int GetNumChannels() + { +#if CRIWAREPLUGIN_SUPPORT_MIC + Debug.Assert(this.handle != IntPtr.Zero, errorInvalidHandle); + return criAtomMic_GetNumChannels(this.handle); +#else + return 0; +#endif + } + + /** + * Gets the microphone sampling frequency + * Sampling frequency + * + * Gets the sampling frequency of the microphone.
+ *
+ */ + public int GetSamplingRate() + { +#if CRIWAREPLUGIN_SUPPORT_MIC + Debug.Assert(this.handle != IntPtr.Zero, errorInvalidHandle); + return criAtomMic_GetSamplingRate(this.handle); +#else + return 0; +#endif + } + + /** + * Gets the number of samples of buffered data + * The number of samples buffered + * + * Gets the number of microphone input data samples existing in the internal buffer.
+ *
+ */ + public uint GetNumBufferedSamples() + { +#if CRIWAREPLUGIN_SUPPORT_MIC + Debug.Assert(this.handle != IntPtr.Zero, errorInvalidHandle); + return criAtomMic_GetNumBufferedSamples(this.handle); +#else + return 0; +#endif + } + + /** + * \deprecated + * This is a deprecated API that will be removed. + * Please consider using CriAtomExMic.GetNumBufferedSamples instead. + */ + [System.Obsolete("Use CriAtomExMic.GetNumBufferedSamples")] + public uint GetNumBufferredSamples() + { + return GetNumBufferedSamples(); + } + + /** + * Gets the microphone availability + * Whether it is available (True: available, False: not available) + * + * Checks the status of the audio input device to see if it is available.
+ *
+ */ + public bool IsAvailable() + { +#if CRIWAREPLUGIN_SUPPORT_MIC + return this.handle != IntPtr.Zero ? criAtomMic_IsAvailable(this.handle) : false; +#else + return false; +#endif + } + + /** + * Reads the microphone input data (monaural) + * Data buffer + * The number of samples that could be acquired + * + * Gets the data input to the microphone.
+ * If this function is not called regularly and the internal buffer becomes full, + * the data that cannot be fed to the buffer is discarded.
+ * This function is valid only when you call CriWare.CriAtomExMic::Start by setting the number of + * channels to 1.
+ * Otherwise, the assertion fails.
+ *
+ */ + public uint ReadData(float[] bufferMono) + { +#if CRIWAREPLUGIN_SUPPORT_MIC + return ReadData(bufferMono, (uint)bufferMono.Length); +#else + return 0; +#endif + } + + /** + * Reads the microphone input data (monaural) + * Data buffer + * The number of samples to read + * The number of samples that could be acquired + * + * Gets the data input to the microphone.
+ * If this function is not called regularly and the internal buffer becomes full, + * the data that cannot be fed to the buffer is discarded.
+ * This function is valid only when you call CriWare.CriAtomExMic::Start by setting the number of + * channels to 1.
+ * Otherwise, the assertion fails.
+ *
+ */ + public uint ReadData(float[] bufferMono, uint numToRead) + { +#if CRIWAREPLUGIN_SUPPORT_MIC + Debug.Assert(this.handle != IntPtr.Zero, errorInvalidHandle); + Debug.Assert(this.bufferPointers.Length == 1, errorInvalidNumBuffers); + Debug.Assert(bufferMono.Length >= numToRead && numToRead > 0, errorInvalidBufferLength); + + if (this.outputWriteStream != null) { + return 0; + } + + var gch = GCHandle.Alloc(bufferMono, GCHandleType.Pinned); + this.bufferPointers[0] = gch.AddrOfPinnedObject(); + + uint result = InternalReadDataFromBufferPointers(numToRead); + InternalClearBuffers(); + return result; +#else + return 0; +#endif + } + + /** + * Reads the microphone input data (stereo) + * Data buffer (L channel) + * Data buffer (R channel) + * The number of samples that could be acquired + * + * Gets the data input to the microphone.
+ * If this function is not called regularly and the internal buffer becomes full, + * the data that cannot be fed to the buffer is discarded.
+ * This function is valid only when you call CriWare.CriAtomExMic::Start by setting the number of + * channels to 2.
+ * Otherwise, the assertion fails.
+ * In addition, make sure that each data buffer has the same array length.
+ *
+ */ + public uint ReadData(float[] bufferL, float[] bufferR) + { +#if CRIWAREPLUGIN_SUPPORT_MIC + Debug.Assert(bufferL.Length == bufferR.Length, errorInvalidBufferLength); + + return ReadData(bufferL, bufferR, (uint)bufferL.Length); +#else + return 0; +#endif + } + + /** + * Reads the microphone input data (stereo) + * Data buffer (L channel) + * Data buffer (R channel) + * The number of samples to read + * The number of samples that could be acquired + * + * Gets the data input to the microphone.
+ * If this function is not called regularly and the internal buffer becomes full, + * the data that cannot be fed to the buffer is discarded.
+ * This function is valid only when you call CriWare.CriAtomExMic::Start by setting the number of + * channels to 2.
+ * Otherwise, the assertion fails.
+ * In addition, make sure that array size of all data buffers is equal to or larger than numToRead.
+ *
+ */ + public uint ReadData(float[] bufferL, float[] bufferR, uint numToRead) + { +#if CRIWAREPLUGIN_SUPPORT_MIC + Debug.Assert(this.handle != IntPtr.Zero, errorInvalidHandle); + Debug.Assert(this.bufferPointers.Length == 2, errorInvalidNumBuffers); + Debug.Assert(bufferL.Length >= numToRead && bufferR.Length >= numToRead, errorInvalidBufferLength); + + if (this.outputWriteStream != null) { + return 0; + } + + this.gcHandles[0] = GCHandle.Alloc(bufferL, GCHandleType.Pinned); + this.gcHandles[1] = GCHandle.Alloc(bufferR, GCHandleType.Pinned); + for (int i = 0; i < this.bufferPointers.Length; i++) { + this.bufferPointers[i] = this.gcHandles[i].AddrOfPinnedObject(); + } + for (int i = 2; i < this.bufferPointers.Length; i++) { + this.bufferPointers[i] = IntPtr.Zero; + } + + uint result = InternalReadDataFromBufferPointers(numToRead); + InternalClearBuffers(); + + return result; +#else + return 0; +#endif + } + + /** + * Reads the microphone input data (multi-channel) + * Data buffer array + * The number of samples that could be acquired + * + * Gets the data input to the microphone.
+ * If this function is not called regularly and the internal buffer becomes full, + * the data that cannot be fed to the buffer is discarded.
+ * The length of the data buffer array passed to this function must be equal to or larger than + * the number of CriAtomExMic::Config channels passed to CriAtomExMic::Start .
+ * Otherwise, the assertion fails.
+ * In addition, make sure that array size of all data buffers is equal to or larger than numToRead.
+ *
+ */ + public uint ReadData(float[][] buffers) + { +#if CRIWAREPLUGIN_SUPPORT_MIC + Debug.Assert(buffers != null); + Debug.Assert(buffers.Length >= this.bufferPointers.Length, errorInvalidNumBuffers); + + int bufferLength = buffers[0].Length; + for (int i = 1; i < this.bufferPointers.Length; i++) { + Debug.Assert(buffers[i].Length == bufferLength, errorInvalidNumBuffers); + } + + return ReadData(buffers, (uint)bufferLength); +#else + return 0; +#endif + } + + /** + * Reads the microphone input data (multi-channel) + * Data buffer array + * The number of samples to read + * The number of samples that could be acquired + * + * Gets the data input to the microphone.
+ * If this function is not called regularly and the internal buffer becomes full, + * the data that cannot be fed to the buffer is discarded.
+ * The length of the data buffer array passed to this function must be equal to the + * number of CriAtomExMic::Config channels passed to CriWare.CriAtomExMic::Start .
+ * Otherwise, the assertion fails.
+ * In addition, make sure that array size of each data buffer is equal to or larger than numToRead.
+ *
+ */ + public uint ReadData(float[][] buffers, uint numToRead) + { +#if CRIWAREPLUGIN_SUPPORT_MIC + Debug.Assert(this.handle != IntPtr.Zero, errorInvalidHandle); + Debug.Assert(buffers != null); + Debug.Assert(buffers.Length >= this.bufferPointers.Length); + Debug.Assert(numToRead > 0); + + for (int i = 0; i < this.bufferPointers.Length; i++) { + Debug.Assert(buffers[i].Length >= numToRead); + } + + if (this.outputWriteStream != null) { + return 0; + } + + for (int i = 0; i < this.bufferPointers.Length; i++) { + this.gcHandles[i] = GCHandle.Alloc(buffers[i], GCHandleType.Pinned); + this.bufferPointers[i] = this.gcHandles[i].AddrOfPinnedObject(); + } + + uint result = InternalReadDataFromBufferPointers(numToRead); + InternalClearBuffers(); + + return result; +#else + return 0; +#endif + } + + /** + * Sets the light stream + * Light stream + * + * Sets the output light stream to the microphone.
+ * The light stream callback function is called when microphone captures input.
+ * The callback function is called from a separate thread on most platforms, + * so the callee must be implemented as thread-safe.
+ *
+ */ + public void SetOutputWriteStream(CriAudioWriteStream stream) + { +#if CRIWAREPLUGIN_SUPPORT_MIC + Debug.Assert(this.handle != IntPtr.Zero, errorInvalidHandle); + this.outputWriteStream = stream; + if (stream != null) { + criAtomMic_SetOutputWriteStream(this.handle, stream.callbackFunction, stream.callbackPointer); + } else { + criAtomMic_SetOutputWriteStream(this.handle, IntPtr.Zero, IntPtr.Zero); + } +#endif + } + + /** + * Gets the read stream + * Read stream callback function + * + * Gets the read stream of the microphone in the output direction.
+ * When calling the read stream callback function, it is necessary to specify the AtomEx microphone handle as the first argument.
+ * If the read stream callback function is not called regularly and the internal buffer becomes full, + * the data that cannot be fed to the buffer is discarded.
+ *
+ */ + public CriAudioReadStream GetOutputReadStream() + { +#if CRIWAREPLUGIN_SUPPORT_MIC + Debug.Assert(this.handle != IntPtr.Zero, errorInvalidHandle); + return new CriAudioReadStream(criAtomMic_GetOutputReadStream(), this.handle); +#else + return null; +#endif + } + + /** + * Adds an effect + * CriAfx interface + * Config parameter array for creating CriAfx + * Microphone effect + * + * Adds an effect to the microphone.
+ * The effect you add must be created using the CriAfx interface.
+ *
+ * If this function is called while the microphone is operating, the effect is suddenly activated, + * which may cause noise in the sound.
+ *
+ */ + public Effect AttachEffect(IntPtr afxInterface, float[] configParameters) + { +#if CRIWAREPLUGIN_SUPPORT_MIC + Debug.Assert(this.handle != IntPtr.Zero, errorInvalidHandle); + IntPtr effectHandle = criAtomMic_AttachEffect(this.handle, afxInterface, + configParameters, (uint)configParameters.Length, IntPtr.Zero, 0); + if (effectHandle == IntPtr.Zero) { + return null; + } + return new Effect(effectHandle, criAtomMic_GetEffectInstance(this.handle, effectHandle)); +#else + return null; +#endif + } + + /** + * Removes an effect + * Microphone effect + * + * Removes a microphone effect.
+ *
+ * If this function is called while the microphone is operating, the effect is suddenly deactivated, + * which may cause noise in the sound.
+ *
+ * + */ + public void DetachEffect(Effect effect) + { +#if CRIWAREPLUGIN_SUPPORT_MIC + Debug.Assert(this.handle != IntPtr.Zero, errorInvalidHandle); + criAtomMic_DetachEffect(this.handle, effect.handle); +#endif + } + + /** + * Sets effect parameters + * Microphone effect + * Parameter index + * Parameter value + * + * Sets parameters to the microphone effect.
+ * This sets the corresponding parameter value by specifying its index.
+ *
+ * Parameters are not reflected to the effect just by calling this function, + * so it is necessary to finally call criAtomMic_UpdateEffectParameters to reflect the parameters.
+ *
+ * + */ + public void SetEffectParameter(Effect effect, int parameterIndex, float parameterValue) + { +#if CRIWAREPLUGIN_SUPPORT_MIC + Debug.Assert(this.handle != IntPtr.Zero, errorInvalidHandle); + criAtomMic_SetEffectParameter(this.handle, effect.handle, (uint)parameterIndex, parameterValue); +#endif + } + + /** + * Gets effect parameters + * Microphone effect + * Parameter index + * Parameter value + * + * Gets microphone effect parameters.
+ * By specifying a parameter index, the value of the corresponding parameter is returned.
+ *
+ */ + public float GetEffectParameter(Effect effect, int parameterIndex) + { +#if CRIWAREPLUGIN_SUPPORT_MIC + Debug.Assert(this.handle != IntPtr.Zero, errorInvalidHandle); + return criAtomMic_GetEffectParameter(this.handle, effect.handle, (uint)parameterIndex); +#else + return 0.0f; +#endif + } + + /** + * Effect Bypass setting + * Microphone effect + * Bypass setting + * + * Specifies that the microphone effects be bypassed.
+ * If you specify True for Bypass, the effects are deactivated.
+ *
+ */ + public void SetEffectBypass(Effect effect, bool bypass) + { +#if CRIWAREPLUGIN_SUPPORT_MIC + Debug.Assert(this.handle != IntPtr.Zero, errorInvalidHandle); + criAtomMic_SetEffectBypass(this.handle, effect.handle, bypass); +#endif + } + + /** + * Sets effect parameters + * Microphone effect + * + * Sets parameters to the microphone effect.
+ * This sets the corresponding parameter value by specifying its index.
+ *
+ * Parameters are not reflected to the effect just by calling this function, + * so it is necessary to finally call criAtomMic_UpdateEffectParameters to reflect the parameters.
+ *
+ * + */ + public void UpdateEffectParameters(Effect effect) + { +#if CRIWAREPLUGIN_SUPPORT_MIC + Debug.Assert(this.handle != IntPtr.Zero, errorInvalidHandle); + criAtomMic_UpdateEffectParameters(this.handle, effect.handle); +#endif + } + + private uint InternalReadDataFromBufferPointers(uint numToRead) + { +#if CRIWAREPLUGIN_SUPPORT_MIC + return criAtomMic_ReadData(this.handle, this.bufferPointers, numToRead); +#else + return 0; +#endif + } + + private void InternalClearBuffers() + { + for (int i = 0; i < bufferPointers.Length; i++) { + if (this.gcHandles[i].IsAllocated) { + this.gcHandles[i].Free(); + } + this.bufferPointers[i] = IntPtr.Zero; + } + } + + #region DLL Import +#if CRIWAREPLUGIN_SUPPORT_MIC + #if !CRIWARE_ENABLE_HEADLESS_MODE + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomMicUnity_Initialize(); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomMicUnity_Finalize(); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criAtomMic_GetNumDevices(); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool criAtomMic_GetDevice(int index, out DeviceInfo info); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool criAtomMic_GetDefaultDevice(out DeviceInfo info); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool criAtomMic_IsFormatSupported([In] ref Config config); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern IntPtr criAtomMic_Create([In] ref Config config, IntPtr work, int work_size); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomMic_Destroy(IntPtr mic); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomMic_Start(IntPtr mic); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomMic_Stop(IntPtr mic); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criAtomMic_GetNumChannels(IntPtr mic); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criAtomMic_GetSamplingRate(IntPtr mic); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern uint criAtomMic_GetNumBufferedSamples(IntPtr mic); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool criAtomMic_IsAvailable(IntPtr mic); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern uint criAtomMic_ReadData(IntPtr mic, IntPtr[] data, uint num_samples); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomMic_SetOutputWriteStream(IntPtr mic, IntPtr stream_cbfunc, IntPtr stream_ptr); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern IntPtr criAtomMic_GetOutputReadStream(); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criAtomMic_CalculateWorkSizeForEffect(IntPtr mic, + IntPtr afx_interface, float[] config_parameters, uint num_config_parameters); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern IntPtr criAtomMic_AttachEffect(IntPtr mic, + IntPtr afx_interface, float[] config_parameters, uint num_config_parameters, + IntPtr work, int work_size); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomMic_DetachEffect(IntPtr mic, IntPtr effect); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern IntPtr criAtomMic_GetEffectInstance(IntPtr mic, IntPtr effect); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomMic_SetEffectBypass(IntPtr mic, IntPtr effect, bool bypass); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomMic_SetEffectParameter(IntPtr mic, IntPtr effect, + uint parameter_index, float parameter_value); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern float criAtomMic_GetEffectParameter(IntPtr mic, IntPtr effect, uint parameter_index); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomMic_UpdateEffectParameters(IntPtr mic, IntPtr effect); + +#if !UNITY_EDITOR && UNITY_IOS + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomUnity_SetMicEnabled_IOS(bool enabled); +#endif + #else + private static void criAtomMicUnity_Initialize() { } + private static void criAtomMicUnity_Finalize() { } + private static int criAtomMic_GetNumDevices() { return 0; } + private static bool criAtomMic_GetDevice(int index, out DeviceInfo info) { info = new DeviceInfo(); return false; } + private static bool criAtomMic_GetDefaultDevice(out DeviceInfo info) { info = new DeviceInfo(); return false; } + private static bool criAtomMic_IsFormatSupported([In] ref Config config) { return false; } + private static IntPtr criAtomMic_Create([In] ref Config config, IntPtr work, int work_size) { return IntPtr.Zero; } + private static void criAtomMic_Destroy(IntPtr mic) { } + private static void criAtomMic_Start(IntPtr mic) { } + private static void criAtomMic_Stop(IntPtr mic) { } + private static int criAtomMic_GetNumChannels(IntPtr mic) { return 0; } + private static int criAtomMic_GetSamplingRate(IntPtr mic) { return 0; } + private static uint criAtomMic_GetNumBufferedSamples(IntPtr mic) { return 0u; } + private static bool criAtomMic_IsAvailable(IntPtr mic) { return false; } + private static uint criAtomMic_ReadData(IntPtr mic, IntPtr[] data, uint num_samples) { return 0u; } + private static void criAtomMic_SetOutputWriteStream(IntPtr mic, IntPtr stream_cbfunc, IntPtr stream_ptr) { } + private static IntPtr criAtomMic_GetOutputReadStream() { return IntPtr.Zero; } + private static int criAtomMic_CalculateWorkSizeForEffect(IntPtr mic, + IntPtr afx_interface, float[] config_parameters, uint num_config_parameters) { return 0; } + private static IntPtr criAtomMic_AttachEffect(IntPtr mic, + IntPtr afx_interface, float[] config_parameters, uint num_config_parameters, + IntPtr work, int work_size) { return IntPtr.Zero; } + private static void criAtomMic_DetachEffect(IntPtr mic, IntPtr effect) { } + private static IntPtr criAtomMic_GetEffectInstance(IntPtr mic, IntPtr effect) { return IntPtr.Zero; } + private static void criAtomMic_SetEffectBypass(IntPtr mic, IntPtr effect, bool bypass) { } + private static void criAtomMic_SetEffectParameter(IntPtr mic, IntPtr effect, + uint parameter_index, float parameter_value) { } + private static float criAtomMic_GetEffectParameter(IntPtr mic, IntPtr effect, uint parameter_index) { return 0.0f; } + private static void criAtomMic_UpdateEffectParameters(IntPtr mic, IntPtr effect) { } +#if !UNITY_EDITOR && UNITY_IOS + private static void criAtomUnity_SetMicEnabled_IOS(bool enabled) { } +#endif + #endif +#endif + #endregion +} + +} //namespace CriWare +/** + * @} + */ + +/* --- end of file --- */ diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExMic.cs.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExMic.cs.meta new file mode 100644 index 0000000..568e071 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExMic.cs.meta @@ -0,0 +1,13 @@ +fileFormatVersion: 2 +guid: b6543470795d67749bfccdbcedb1a0b2 +timeCreated: 1528091287 +licenseType: Free +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExOutputAnalyzer.cs b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExOutputAnalyzer.cs new file mode 100644 index 0000000..450e318 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExOutputAnalyzer.cs @@ -0,0 +1,581 @@ +/**************************************************************************** + * + * Copyright (c) 2018 CRI Middleware Co., Ltd. + * + ****************************************************************************/ +using UnityEngine; +using System; +using System.Runtime.InteropServices; + +/*========================================================================== + * CRI Atom Native Wrapper + *=========================================================================*/ +/** + * \addtogroup CRIATOM_NATIVE_WRAPPER + * @{ + */ + +namespace CriWare { + +/** + * Sound output data analysis module (for each player/source/bus) + * + * Performs sound output analysis for each CriAtomSource/CriAtomExPlayer or for each bus.
+ * Provides features such as Level Meter.
+ * When attached to CriAtomSource/CriAtomExPlayer, analysis is not possible + * when HCA-MX or platform-specific sound compression codec is used.
+ * Use HCA or ADX codecs.
+ *
+ */ + +public class CriAtomExOutputAnalyzer : CriDisposable +{ + public IntPtr nativeHandle {get {return this.handle;} } + + /** + * Maximum number of spectrum analyzer bands + * + * Maximum number of bands that the spectrum analyzer can output. + * + */ + public const int MaximumSpectrumBands = 512; + + /** + * Waveform acquisition callback + * + * A callback for acquiring the output waveform data.
+ *
+ */ + public delegate void PcmCaptureCallback(float[] dataL, float[] dataR, int numChannels, int numData); + + /** + * Sound output data analysis module config structure + * + * A config specified when creating the analysis module.
+ *
+ * + */ + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + public struct Config + { + /** + * Whether to enable the Level Meter + * + * Enables the Level Meter. + * + */ + public bool enableLevelmeter; + + /** + * Whether to enable the spectrum analyzer + * + * Enables the spectrum analyzer. + * When using the function, specify True in this flag and + * set numSpectrumAnalyzerBands to a positive number equal to or + * smaller than MaximumSpectrumBands. + * + */ + public bool enableSpectrumAnalyzer; + + /** + * Whether to enable acquisition of the waveform data + * + * Enables the acquisition of output data. + * When using the function, specify True in this flag and + * set numCapturedPcmSamples to a positive number. + * + */ + public bool enablePcmCapture; + + /** + * Whether to enable the waveform data acquisition callback + * + * Enables the callback for acquiring the output data.
+ * When using the function, specify True in this flag and + * call ExecutePcmCaptureCallback regularly in MonoBehaviour.Update etc.
+ *
+ */ + public bool enablePcmCaptureCallback; + + /** + * The number of spectrum analyzer bands + */ + public int numSpectrumAnalyzerBands; + + /** + * The number of waveform data samples acquired at one time + */ + public int numCapturedPcmSamples; + }; + + /** + * Creates a sound output data analysis module + * Sound output data analysis module + * + * Create an output Voice data analysis module.
+ * Use the analysis module you created by attaching it to a CriAtomSource, CriAtomExPlayer, or bus.
+ * Perform analysis of the level meter etc. on the attached audio output.
+ * // 解析モジュールの作成例 + * + * // コンフィグでSpectrumAnalyzerを有効にし、バンド数を指定 + * CriAtomExOutputAnalyzer.Config config = new CriAtomExOutputAnalyzer.Config(); + * config.enableSpectrumAnalyzer = true; + * config.numSpectrumAnalyzerBands = 16; + * + * // 出力データ解析モジュールを作成 + * this.analyzer = new CriAtomExOutputAnalyzer(config); + * + *
+ * Only one CriAtomSource/CriAtomExPlayer/ bus can be attached to the analysis module.
+ * If you want to reuse the analysis module, detach it.
+ * Unmanaged resources are reserved when creating a sound output data analysis module.
+ * When you no longer need the analysis module, be sure to call the CriAtomExOutputAnalyzer.Dispose method.
+ *
+ */ + public CriAtomExOutputAnalyzer(Config config) + { + InitializeWithConfig(config); + CriDisposableObjectManager.Register(this, CriDisposableObjectManager.ModuleType.Atom); + } + + /** + * Discards the output data analysis module + * + * Discards the output data analysis module.
+ * At the time of calling this function, all the resources allocated in the plug-in when creating the output data analysis module are released.
+ * To prevent memory leak, call this method when the output data analysis module is no longer required.
+ * This function is a return-on-complete function.
+ * If there are any attached AtomExPlayers, they are detached in this function.
+ * Note that the sounds being played by the target AtomExPlayers are forcibly stopped.
+ *
+ * + */ + public override void Dispose() + { + this.Dispose(true); + } + + protected void Dispose(bool disposing) + { + CriDisposableObjectManager.Unregister(this); + + if (this.handle != IntPtr.Zero) { + /* アタッチ済みのプレーヤがあればデタッチ */ + this.DetachExPlayer(); + this.DetachDspBus(); + + /* ネイティブリソースの破棄 */ + criAtomExOutputAnalyzer_Destroy(this.handle); + this.handle = IntPtr.Zero; + } + + if (disposing) { + GC.SuppressFinalize(this); + } + } + + /** + * Attaching the AtomExPlayer + * Whether the attach was successful (success: True, failure: False) + * + * Attaches the AtomExPlayer that analyzes the output data.
+ * It is not possible to attach multiple AtomExPlayers. + * If you attach another AtomExPlayer while one is attached, the attached AtomExPlayer is detached.
+ *
+ * To attach CriAtomSource, use CriAtomSource::AttachToOutputAnalyzer.
+ * Attachment must be done before starting playback. Attachment fails after starting playback.
+ *
+ * If you discard the AtomExPlayer attached using this function before detaching it, + * an access violation occurs at the time of detachment.
+ * Be sure to first detach the AtomExPlayer before discarding it.
+ *
+ * + * + */ + public bool AttachExPlayer(CriAtomExPlayer player) + { + if (player == null || !player.isAvailable || + this.handle == IntPtr.Zero) { + return false; + } + + /* アタッチ済みならデタッチ */ + this.DetachExPlayer(); + this.DetachDspBus(); + + /* プレーヤの状態をチェック */ + CriAtomExPlayer.Status status = player.GetStatus(); + if (status != CriAtomExPlayer.Status.Stop) { + return false; + } + + criAtomExOutputAnalyzer_AttachExPlayer(this.handle, player.nativeHandle); + this.player = player; + + return true; + } + + /** + * Detaches the AtomExPlayer + * + * Detaches the AtomExPlayer that analyzes the output data.
+ * After detaching, the subsequent analysis will not be done.
+ * If this function is called while the player already attached is playing a sound, + * the playback is forcibly stopped before detaching.
+ *
+ * An access violation occurs if the attached AtomExPlayer has already been discarded.
+ * Be sure to call this function or CriAtomExOutputAnalyzer::Dispose before + * discarding the AtomExPlayer.
+ *
+ * + * + */ + public void DetachExPlayer() + { + if (this.player == null || !this.player.isAvailable || + this.handle == IntPtr.Zero) { + return; + } + + CriAtomExPlayer.Status status = this.player.GetStatus(); + if (status != CriAtomExPlayer.Status.Stop) { + /* 音声再生中にデタッチは行えないため、強制的に停止 */ + Debug.LogWarning("[CRIWARE] Warning: CriAtomExPlayer is forced to stop for detaching CriAtomExOutputAnalyzer."); + this.player.StopWithoutReleaseTime(); + } + + criAtomExOutputAnalyzer_DetachExPlayer(this.handle, this.player.nativeHandle); + this.player = null; + } + + /** + * Attaching the DSP bus + * Whether the attach was successful (success: True, failure: False) + * + * Attach a DSP bus for output data analysis.
+ * It is not possible to attach multiple DSP buses. + * If you attach another DSP bus while one is attached, the attached DSP bus is detached.
+ *
+ * + */ + public bool AttachDspBus(string busName) + { + if (busName == null || this.handle == IntPtr.Zero) { + return false; + } + + /* アタッチ済みのプレーヤがあればデタッチ */ + this.DetachExPlayer(); + this.DetachDspBus(); + + #if !UNITY_PSP2 + criAtomExOutputAnalyzer_AttachDspBusByName(this.handle, busName); + this.busName = busName; + return true; + #else + Debug.LogError("[CRIWARE] Error: CriAtomExOutputAnalyzer cannot be attached to bus on this platform."); + return false; + #endif + } + + /** + * Detaches the DSP bus + * + * Detach a DSP bus for output data analysis.
+ * After detaching, the subsequent analysis will not be done.
+ *
+ * + * + */ + public void DetachDspBus() + { + if (this.busName == null || this.handle == IntPtr.Zero) { + return; + } + + criAtomExOutputAnalyzer_DetachDspBusByName(this.handle, busName); + this.busName = null; + } + + /** + * Gets the RMS level of sound output being attached + * Channel number + * RMS level + * + * Gets the RMS level of sound output being attached.
+ * When using this function, create a module setting enableLevelmeter to True in Config.
+ *
+ * + * + */ + public float GetRms(int channel) + { + if ((this.player == null && this.busName == null) + || this.handle == IntPtr.Zero) { + return 0.0f; + } + + /* プレーヤが再生状態でなければレベルを落とす */ + if (this.player != null && + this.player.GetStatus() != CriAtomExPlayer.Status.Playing && + this.player.GetStatus() != CriAtomExPlayer.Status.Prep) { + return 0.0f; + } + + return criAtomExOutputAnalyzer_GetRms(this.handle, channel); + } + + /** + * Gets the spectrum analysis result + * Analysis result (amplitude of each band) + * + * Gets the amplitude for each band analyzed by the spectrum analyzer.
+ * The number of elements in the array is the number of bands specified when the module was created.
+ * When using this function, create a module setting enableSpectrumAnalyzer to True and a numSpectrumAnalyzerBands to + * a positive number equal to or smaller than MaximumSpectrumBands in Config. + * If you want to display the analysis result like a commercial spectrum analyzer, + * you need to convert the value returned by this function into a decibel value.
+ *
+ * + * // 例:スペクトル解析結果を取得するコンポーネント + * public class SpectrumLevelMeter : MonoBehaviour { + * private CriAtomExOutputAnalyzer analyzer; + * void Start() { + * // 引数 config については省略。モジュールの作成時に指定したバンド数は 8 とする + * this.analyzer = new CriAtomExOutputAnalyzer(config); + * // CriAtomExPlayer のアタッチについては省略 + * } + * + * void Update() { + * // 音声再生中の実行 + * float[] levels = new float[8]; + * analyzer.GetSpectrumLevels (ref levels); + * // levelsの0帯域目の振幅値をデシベル値に変換 + * float db = 20.0f * Mathf.Log10(levels[0]); + * Debug.Log (db); + * } + * } + * + * + * + */ + public void GetSpectrumLevels(ref float[] levels) + { + if ((this.player == null && this.busName == null) || this.handle == IntPtr.Zero) { + return; + } + + if (levels == null || levels.Length < numBands) { + levels = new float[numBands]; + } + + IntPtr ret = criAtomExOutputAnalyzer_GetSpectrumLevels(this.handle); + Marshal.Copy(ret, levels, 0, numBands); + } + + /** + * Gets the waveform data of the sound output being attached + * Output data + * Channel + * + * Gets the waveform data of the sound output being attached.
+ * When using this function, create a module by setting enablePcmCapture to True + * and a numCapturedPcmSamples to a positive number in Config.
+ * If the argument array is not long enough, it is allocated in the function.
+ * To avoid unnecessary GC, pass an array with a length longer than + * the number of data samples specified in the initialization config as an argument. + * Currently, the only channels that can be acquired are L/R. For ch, specify 0 or 1.
+ *
+ * + * + */ + public void GetPcmData(ref float[] data, int ch) + { + if ((this.player == null && this.busName == null) || this.handle == IntPtr.Zero) { + return; + } + + if (data == null || data.Length < numCapturedPcmSamples) { + data = new float[numCapturedPcmSamples]; + } + + IntPtr ret = criAtomExOutputAnalyzer_GetPcmData(this.handle, ch); + if (ret != IntPtr.Zero) { + Marshal.Copy(ret, data, 0, numCapturedPcmSamples); + } + } + + /** + * Registers the waveform data acquisition callback + * + * Register the callback for acquiring output data.
+ * When using callback for acquiring the waveform data, register the callback using this function + * before calling ExecutePcmCaptureCallback.
+ *
+ */ + public void SetPcmCaptureCallback(PcmCaptureCallback callback) + { + this.userPcmCaptureCallback = callback; + } + + /** + * Calls the waveform data acquisition callback + * + * Call the callback for acquiring the output data.
+ * When this function is called, the callback is called multiple times with the output difference data + * from the last execution as an argument.
+ * When using a callback for getting the waveform data, call this function regularly.
+ * If this function is not called for a long time, there may be a loss of acquired waveform data.
+ *
+ */ + public void ExecutePcmCaptureCallback() + { + #if !(!UNITY_EDITOR && UNITY_WEBGL) + if (CriAtomExOutputAnalyzer.InternalCallbackFunctionPointer == IntPtr.Zero) { + CriAtomExOutputAnalyzer.DelegateObject = new InternalPcmCaptureCallback(CriAtomExOutputAnalyzer.Callback); + CriAtomExOutputAnalyzer.InternalCallbackFunctionPointer = Marshal.GetFunctionPointerForDelegate(CriAtomExOutputAnalyzer.DelegateObject); + } + + CriAtomExOutputAnalyzer.UserPcmCaptureCallback = this.userPcmCaptureCallback; + CriAtomExOutputAnalyzer.DataL = this.dataL; + CriAtomExOutputAnalyzer.DataR = this.dataR; + + criAtomExOutputAnalyzer_ExecuteQueuedPcmCapturerCallbacks(this.handle, CriAtomExOutputAnalyzer.InternalCallbackFunctionPointer); + + CriAtomExOutputAnalyzer.UserPcmCaptureCallback = null; + CriAtomExOutputAnalyzer.DataL = null; + CriAtomExOutputAnalyzer.DataR = null; + #endif + } + + /** + * \deprecated + * This is a deprecated API that will be removed. + * Please consider using SetPcmCaptureCallback(PcmCaptureCallback) and ExecutePcmCaptureCallback() instead. + */ + [System.Obsolete("Use SetPcmCaptureCallback(PcmCaptureCallback) and ExecutePcmCaptureCallback()")] + public void ExecutePcmCaptureCallback(PcmCaptureCallback callback) + { + this.userPcmCaptureCallback = callback; + ExecutePcmCaptureCallback(); + } + + #region Internal Members + protected CriAtomExOutputAnalyzer() { + CriDisposableObjectManager.Register(this, CriDisposableObjectManager.ModuleType.Atom); + } + + ~CriAtomExOutputAnalyzer() + { + this.Dispose(false); + } + + protected void InitializeWithConfig(Config config) { + /* ネイティブリソースの作成 */ + this.handle = criAtomExOutputAnalyzer_Create(ref config); + if (this.handle == IntPtr.Zero) { + throw new Exception("criAtomExOutputAnalyzer_Create() failed."); + } + + /* コンフィグ指定の記憶 */ + { + this.numBands = config.numSpectrumAnalyzerBands; + this.numCapturedPcmSamples = config.numCapturedPcmSamples; + if (config.enablePcmCaptureCallback) { + #if !UNITY_EDITOR && UNITY_WEBGL + Debug.LogError("[CRIWARE] PCM capture callback is not supported for this platform."); + #else + if (this.dataL == null) { + this.dataL = new float[pcmCapturerNumMaxData]; + this.dataR = new float[pcmCapturerNumMaxData]; + } + #endif + } + } + } + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + protected delegate void InternalPcmCaptureCallback(IntPtr dataL, IntPtr dataR, int numChannels, int numData); + + protected IntPtr handle = IntPtr.Zero; + protected CriAtomExPlayer player = null; + protected string busName = null; + protected int numBands = 8; + protected int numCapturedPcmSamples = 4096; + protected PcmCaptureCallback userPcmCaptureCallback = null; + protected float [] dataL, dataR; + protected const int pcmCapturerNumMaxData = 512; + + [AOT.MonoPInvokeCallback(typeof(InternalPcmCaptureCallback))] + private static void Callback(IntPtr ptrL, IntPtr ptrR, int numChannels, int numData) + { + if (DataL == null) + return; + + Marshal.Copy(ptrL, DataL, 0, numData); + if (numChannels > 1) { + Marshal.Copy(ptrR, DataR, 0, numData); + } + if (UserPcmCaptureCallback != null) { + UserPcmCaptureCallback(DataL, DataR, numChannels, numData); + } + } + + protected static IntPtr InternalCallbackFunctionPointer = IntPtr.Zero; + protected static InternalPcmCaptureCallback DelegateObject; + protected static float [] DataL, DataR; + protected static PcmCaptureCallback UserPcmCaptureCallback = null; + #endregion + + #region DLL Import + #if !CRIWARE_ENABLE_HEADLESS_MODE + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + protected static extern IntPtr criAtomExOutputAnalyzer_Create([In] ref Config config); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + protected static extern void criAtomExOutputAnalyzer_Destroy(IntPtr analyzer); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + protected static extern void criAtomExOutputAnalyzer_AttachExPlayer(IntPtr analyzer, IntPtr player); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + protected static extern void criAtomExOutputAnalyzer_DetachExPlayer(IntPtr analyzer, IntPtr player); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + protected static extern void criAtomExOutputAnalyzer_AttachDspBusByName(IntPtr analyzer, string busName); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + protected static extern void criAtomExOutputAnalyzer_DetachDspBusByName(IntPtr analyzer, string busName); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + protected static extern float criAtomExOutputAnalyzer_GetRms(IntPtr analyzer, int channel); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + protected static extern IntPtr criAtomExOutputAnalyzer_GetSpectrumLevels(IntPtr analyzer); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + protected static extern IntPtr criAtomExOutputAnalyzer_GetPcmData(IntPtr analyzer, int ch); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + protected static extern void criAtomExOutputAnalyzer_ExecuteQueuedPcmCapturerCallbacks(IntPtr analyzer, IntPtr callback); + #else + protected static IntPtr criAtomExOutputAnalyzer_Create([In] ref Config config) { return new IntPtr(1); } + protected static void criAtomExOutputAnalyzer_Destroy(IntPtr analyzer) { } + protected static void criAtomExOutputAnalyzer_AttachExPlayer(IntPtr analyzer, IntPtr player) { } + protected static void criAtomExOutputAnalyzer_DetachExPlayer(IntPtr analyzer, IntPtr player) { } + protected static void criAtomExOutputAnalyzer_AttachDspBusByName(IntPtr analyzer, string busName) { } + protected static void criAtomExOutputAnalyzer_DetachDspBusByName(IntPtr analyzer, string busName) { } + protected static float criAtomExOutputAnalyzer_GetRms(IntPtr analyzer, int channel) { return 0.0f; } + protected static IntPtr criAtomExOutputAnalyzer_GetSpectrumLevels(IntPtr analyzer) { return IntPtr.Zero; } + protected static IntPtr criAtomExOutputAnalyzer_GetPcmData(IntPtr analyzer, int ch) { return IntPtr.Zero; } + protected static void criAtomExOutputAnalyzer_ExecuteQueuedPcmCapturerCallbacks(IntPtr analyzer, IntPtr callback) { } + #endif + #endregion +} + +} //namespace CriWare +/** + * @} + */ + +/* --- end of file --- */ diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExOutputAnalyzer.cs.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExOutputAnalyzer.cs.meta new file mode 100644 index 0000000..e6cedf6 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExOutputAnalyzer.cs.meta @@ -0,0 +1,13 @@ +fileFormatVersion: 2 +guid: d04eda20a599a66478363693fbf6bd79 +timeCreated: 1516758629 +licenseType: Pro +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExPlayback.cs b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExPlayback.cs new file mode 100644 index 0000000..1e17180 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExPlayback.cs @@ -0,0 +1,618 @@ +/**************************************************************************** + * + * Copyright (c) 2011 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using System.Text; + +/*========================================================================== + * CRI Atom Native Wrapper + *=========================================================================*/ +/** + * \addtogroup CRIATOM_NATIVE_WRAPPER + * @{ + */ + +namespace CriWare { + +/** + * Playback sound object + * + * The object returned when the CriWare.CriAtomExPlayer::Start function is executed.
+ * This object is used to change parameters or acquire the status of each voice (instead of the whole player) played by the CriWare.CriAtomExPlayer::Start function.
+ *
+ * + */ +public struct CriAtomExPlayback +{ + /** + * Playback status + * + * Status of the sound that has been played on the AtomExPlayer.
+ * It can be obtained by using the CriWare.CriAtomExPlayback::GetStatus function.
+ *
+ * The playback status usually changes in the following order.
+ * -# Prep + * -# Playing + * -# Removed + * .
+ * Status indicates the status of the sound that was played + * ( CriWare.CriAtomExPlayer::Start function was called) by the AtomExPlayer + * instead of the status of the player.
+ *
+ * The sound resource being played is discarded when the playback is stopped.
+ * Therefore, the status of the playback sound changes to Removed in the following cases.
+ * - When playback is complete. + * - When the sound being played is stopped using the Stop function. + * - When a Voice being played is stolen by a high priority playback request. + * - When an error occurred during playback. + * .
+ *
+ * + * + * + */ + public enum Status { + Prep = 1, /**< Preparing for playback */ + Playing, /**< Playing */ + Removed /**< Removed */ + } + + /** + * Playback Track information + * + * A structure to get the Track information of the Cue being played.
+ *
+ * + */ + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + public struct TrackInfo { + public uint id; /**< Playback ID */ + public CriAtomEx.CueType sequenceType; /**< Parent Sequence type */ + public IntPtr playerHn; /**< Player handle */ + public ushort trackNo; /**< Track number */ + public ushort reserved; /**< Reserved area */ + } + + public CriAtomExPlayback(uint id) + : this() + { + this.id = id; + #if CRIWARE_ENABLE_HEADLESS_MODE + this._dummyStatus = Status.Prep; + #endif + } + + /** + * Stops the playback sound + * Whether to ignore release time + * (False = perform release process, True = ignore release time and stop immediately) + * + * Stops for each played sound.
+ * By using this function, it is possible to pause the sound played + * for each individual sound on the player.
+ * If you want to stop all the sounds played back by the AtomExPlayer, + * use the CriWare.CriAtomExPlayer::Stop function instead of this function.
+ * (The CriWare.CriAtomExPlayer::Stop function stops all the sounds being played by the player.)
+ * When the playback sound is stopped using this function, the status of the sound being played changes to Removed.
+ * Since the Voice resource is also discarded when stopped, it will not be possible to acquire information + * from the playback object that changed to Removed state.
+ *
+ * + * + */ + public void Stop(bool ignoresReleaseTime) + { + if (CriAtomPlugin.IsLibraryInitialized() == false) { return; } + + if (ignoresReleaseTime == false) { + criAtomExPlayback_Stop(this.id); + } else { + criAtomExPlayback_StopWithoutReleaseTime(this.id); + } + } + + /** + * Pauses playback sound + * + * Pauses for each played sound.
+ *
+ * By using this function, it is possible to pause the sound played + * for each individual sound on the player.
+ * If you want to pause all the sounds played back by the player, + * use the CriWare.CriAtomExPlayer::Pause function instead of this function.
+ *
+ * + * + * + */ + public void Pause() + { + criAtomExPlayback_Pause(this.id, true); + } + + /** + * Unpauses the playback sound + * Unpausing target + * + * Unpauses for each played sound.
+ * When this function is called by specifying PausedPlayback in the argument (mode), + * the playback of the sound paused by the user using + * the CriWare.CriAtomExPlayer::Pause function (or the CriWare.CriAtomExPlayback::Pause function) is resumed.
+ * When this function is called by specifying PreparedPlayback in the argument (mode), + * the playback of the sound prepared by the user using the CriWare.CriAtomExPlayer::Prepare starts.
+ * If the player paused by the CriWare.CriAtomExPlayer::Pause function is prepared for playback with the CriWare.CriAtomExPlayer::Prepare function, + * the playback will not start until the unpausing processing triggered by both PausedPlayback and PreparedPlayback is completed.
+ *
+ * To always start playback, even if the player is processed by the CriWare.CriAtomExPlayer::Pause or CriWare.CriAtomExPlayer::Prepare functions, + * please call this function with the "mode" argument set to "AllPlayback".
+ *
+ * + * + * + */ + public void Resume(CriAtomEx.ResumeMode mode) + { + criAtomExPlayback_Resume(this.id, mode); + } + + /** + * Gets pausing status of the playback sound + * Whether the playback is paused (False = not paused, True = paused) + * + * Returns whether or not the sound being played is paused.
+ *
+ * + */ + public bool IsPaused() + { + return criAtomExPlayback_IsPaused(this.id); + } + + /** + * Gets the playback sound format information + * Format information + * Whether the information can be acquired (True = could be acquired, False = could not be acquired) + * + * Gets information about the format of the audio played by the CriWare.CriAtomExPlayer::Start function.
+ *
+ * If the format information can be obtained, this function returns true.
+ * If the specified voice has already been removed, this function returns false.
+ * When playing a Cue that contains multiple sound data, the information on + * the first sound data found is returned.
+ * This function can get the format information only during sound playback.
+ * If the Voice is deleted by Voice control during playback preparation or after the playback, + * acquisition of format information fails.
+ *
+ * + * + */ + public bool GetFormatInfo(out CriAtomEx.FormatInfo info) + { + return criAtomExPlayback_GetFormatInfo(this.id, out info); + } + + /** + * Gets the playback status + * Playback status + * + * Gets the status of the audio played by the CriWare.CriAtomExPlayer::Start function.
+ * This function returns the playing status of an individual voice + * (unlike the CriWare.CriAtomExPlayer::GetStatus function which returns the status of the AtomExPlayer).
+ *
+ * The Voice resource associated with the audio being played will be disposed in the following cases:
+ * - The playback is complete. + * - The audio being played is stopped by the Stop function. + * - The Voice used has been reclaimed by another playback request of higher priority. + * - An error occured during playback. + * . + * Therefore, regardless of whether the playback was explicitly stopped by using the CriWare.CriAtomExPlayback::Stop function + * or for other reasons, the status of the playback will transit to "Removed".
+ * (To detect an error, check the status of the AtomExPlayer + * with the CriWare.CriAtomExPlayer::GetStatus function instead of using this function.)
+ *
+ * + * + * + */ + public Status GetStatus() + { + return criAtomExPlayback_GetStatus(this.id); + } + + /** + * Gets the playback time + * Playback time (in milliseconds) + * + * Obtains the playback time of the audio played by the CriWare.CriAtomExPlayer::Start function.
+ *
+ * If the playback time can be obtained, this function returns a value greater than 0.
+ * If the specified voice has already been removed, this function returns a negative value.
+ * The playback time returned by this function is "the elapsed time from the start of playback".
+ * The time does not rewind depending on the playback position, + * even during loop playback or seamless linked playback.
+ *
+ * When the playback is paused using the CriWare.CriAtomExPlayer::Pause function, + * the playback time count-up also stops.
+ * (If you unpause the playback, the count-up resumes.) + *
+ * The accuracy of the time that can be obtained by this function depends on the frequency of the server processing.
+ * (The time is updated for each server process.)
+ * If you need to get more accurate time, use the + * CriWare.CriAtomExPlayback::GetNumPlayedSamples function instead of this function + * to get the number of samples played.
+ * The return type is long, but currently there is no precision over 32bit.
+ * When performing control based on the playback time, it should be noted that the playback time becomes incorrect in about 24 days.
+ * (The playback time overflows and becomes a negative value when it exceeds 2147483647 milliseconds.)
+ *
+ * This function can get the time only during sound playback.
+ * (Unlike the CriWare.CriAtomExPlayer::GetTime function, this function can get the time + * for each sound being played, but it cannot get the playback end time.)
+ * Getting the playback time fails after the playback ends + * or when the Voice is erased by the Voice control.
+ * (Negative value is returned.)
+ *
+ * If the sound data supply is temporarily interrupted due to device read retry processing, etc., + * the count-up of the playback time is not interrupted.
+ * (The time progresses even if the playback is stopped due to the stop of data supply.)
+ * Therefore, when synchronizing sound with the source video based on the time acquired by this function, + * the synchronization may be greatly deviated each time a read retry occurs.
+ * If it is necessary to strictly synchronize the waveform data and video, + * use the CriWare.CriAtomExPlayback::GetNumPlayedSamples function instead of this function + * to synchronize with the number of played samples.
+ *
+ * + * + * + */ + public long GetTime() + { + return criAtomExPlayback_GetTime(this.id); + } + + /** + * Gets the playback time synchronized with sound + * Playback time (in milliseconds) + * + * Obtains the playback time of the audio played by the CriWare.CriAtomExPlayer::Start function.
+ *
+ * If the playback time can be obtained, this function returns a value greater than 0.
+ * If the specified voice has already been removed, this function returns a negative value.
+ * The playback time synchronized with the audio can be obtained with this function + * (unlike the CriWare.CriAtomExPlayback::GetTime function which returns the "elapsed time since the start of the playback").
+ * If the audio data supply is interrupted and the playback is stopped due to trying to re-read the data etc., the playback time will stop being incremented.
+ * Use this function to obtain the playback time in cases you need to perform processing that is strictly synchronized with the audio being played.
+ * However, the time will not reset according to the playback position during loop playback or seamlessly concatenated playback.
+ * In addition, the playback time cannot correctly be acquired for sequence Cues that have gaps between waveforms, or block sequence Cues that switch waveforms when playing.
+ *
+ * When pausing the playback with the CriWare.CriAtomExPlayer::Pause function, the playback time incrementation will also be paused.
+ * (It will resume once the playback is unpaused.)
+ *
+ * To get the playback time using this function, use the CriWare.CriAtomExPlayer::CriAtomExPlayer(bool) function and set the argument to true to enable the audio synchronization timer when creating a player. + *
+ * The return type is long, but currently there is no precision over 32bit.
+ * When performing control based on the playback time, it should be noted that the playback time becomes incorrect in about 24 days.
+ * (The playback time overflows and becomes a negative value when it exceeds 2147483647 milliseconds.)
+ *
+ * This function can get the time only during sound playback.
+ * (Unlike the CriWare.CriAtomExPlayer::GetTime function, this function can get the time + * for each sound being played, but it cannot get the playback end time.)
+ * Getting the playback time fails after the playback ends + * or when the Voice is erased by the Voice control.
+ * (Negative value is returned.)
+ *
+ * This function calculates the time internally, so the processing load + * may be a problem depending on the platform. In addition, it returns the updated time with each call, + * even within the same frame of the application.
+ * Although it depends on how the playback time is used by the application, + * basically use this function to get the time only once per frame.
+ *
+ *
+ * + * + * + * + */ + public long GetTimeSyncedWithAudio() + { + return criAtomExPlayback_GetTimeSyncedWithAudio(this.id); + } + + /** + * Gets the number of playback samples + * The number of played samples + * Sampling rate + * Whether the sample count can be acquired (True = could be acquired, False = could not be acquired) + * + * Returns the number of samples + * and the sampling rate of the audio played by the CriWare.CriAtomExPlayer::Start function.
+ *
+ * If the number of samples can be obtained, this function returns true.
+ * If the specified voice has already been removed, this function returns false.
+ * (In the event of an error, numSamples and samplingRate will be negative values.)
+ * The accuracy of the number of samples played depends on the + * sound library in the platform SDK.
+ * (The accuracy of the number of samples played depends on the platform.)
+ *
+ * When playing a Cue that contains multiple sound data, the information + * on the first sound data found is returned.
+ * If the sound data supply is interrupted due to device read retry processing, etc., + * the count-up of the number of playback samples stops.
+ * (The count-up restarts when the data supply is resumed.)
+ *
+ * This function can get the number of playback samples only while the sound is being played.
+ * Getting the number of playback samples fails after the playback ends + * or when the Voice is erased by the Voice control.
+ *
+ * + */ + public bool GetNumPlayedSamples(out long numSamples, out int samplingRate) + { + return criAtomExPlayback_GetNumPlayedSamples(this.id, out numSamples, out samplingRate); + } + + /** + * Gets the Sequence playback position + * Sequence playback position (in milliseconds) + * + * Gets the sequence playback position in the audio played by the CriWare.CriAtomExPlayer::Start function.
+ *
+ * If the playback position can be obtained, this function returns a value greater than 0.
+ * If the specified sequence has already been removed, etc., this function returns a negative value.
+ * The playback time returned by this function is the "playback position on the Sequence data".
+ * When a Sequence loop or Block transition was performed, the rewound value is returned.
+ *
+ * The Sequencer does not run if you performed non-Cue-specified playback. For playback other than Cue playback, + * this function returns a negative value.
+ *
+ * When the playback is paused using the CriWare.CriAtomExPlayer::Pause function, the playback position also stops being updated.
+ * (If you unpause, the update resumes.) + *
+ * The accuracy of the time that can be obtained by this function depends on the frequency of the server processing.
+ * (The time is updated for each server process.)
+ * The return type is long, but currently there is no precision over 32bit.
+ * When performing control based on the playback position, it should be noted that + * the playback position becomes incorrect in about 24 days for the data that has no settings such as Sequence loops.
+ * (The playback position overflows and becomes a negative value when it exceeds 2147483647 milliseconds.)
+ *
+ * This function can get the position only during sound playback.
+ * After the end of playback, or when the Sequence was erased by Voice control, + * acquisition of the playback position fails.
+ * (Negative value is returned.)
+ *
+ * + */ + public long GetSequencePosition() + { + return criAtomExPlayback_GetSequencePosition(this.id); + } + + /** + * Gets the current Block index of the playback sound + * Current Block index + * + * Get the current block index in the block sequence + * played by the CriWare.CriAtomExPlayer::Start function.
+ * Returns 0xFFFFFFFF if the data being played by the playback ID is not a Block Sequence.
+ *
+ * + * + * + */ + public int GetCurrentBlockIndex() + { + return criAtomExPlayback_GetCurrentBlockIndex(this.id); + } + + /** + * Gets the playback Track information + * Playback Track information + * Whether the acquisition succeeded + * + * Acquires the track information of the Cue played by the CriWare.CriAtomExPlayer::Start function.
+ * Only the track information that is directly contained within the Cue can be acquired, i.e., information about sub-sequences or Cue links cannot be obtained.
+ * An attempt to get the Track information fails if the following data is being played.
+ * - Data other than Cue is being played. (Since there is no Track information)
+ * - The Cue being played is a Polyphonic type or a selector-referenced switch type. + * (Since there may be multiple Track information)
+ * - The Cue being played is a Track Transition type. (Since the playback Track changes by transition)
+ *
+ * + */ + public bool GetTrackInfo(out TrackInfo info) + { + return criAtomExPlayback_GetPlaybackTrackInfo(this.id, out info); + } + + /** + * Gets beat synchronization information + * Beat synchronization information + * Whether the acquisition succeeded + * + * Acquires the beat synchronization information of the Cue played by the CriWare.CriAtomExPlayer::Start function.
+ * The current BPM, measure count, beat count, and beat progress percentage (from 0.0 to 1.0) can be obtained.
+ * The Cue itself must have beat sync information set.
+ * Information cannot be acquired for Cues started with from a Cue link or a Start Action.
+ * An attempt to get the beat synchronization information fails if the following data is being played.
+ * - Data other than Cue is being played. (Since there is not beat synchronization information)
+ * - A Cue without beat synchronization information is being played.
+ * - A Cue with beat synchronization information is being played "indirectly". + * (Being played with Cue link or start action)
+ *
+ * + */ + public bool GetBeatSyncInfo(out CriAtomExBeatSync.Info info) + { + return criAtomExPlayback_GetBeatSyncInfo(this.id, out info); + } + + /** + * Block transition of playback sound + * Block index + * + * Block transition is performed for each played sound.
+ * When this function is executed, if the Voice with the specified ID is a block sequence, + * It transitions the block according to the specified block sequence setting.
+ * Use the CriWare.CriAtomExPlayer::SetFirstBlockIndex function to specify the playback start Block, + * and use the CriWare.CriAtomExPlayback::GetCurrentBlockIndex function to get the Block index during playback. + *
+ * + * + */ + public void SetNextBlockIndex(int index) + { + criAtomExPlayback_SetNextBlockIndex(this.id, index); + } + + /** + * Beat synchronization offset setting + * Offset time (ms) + * Whether the offset has been successfully set + * + * Sets the beat sync offset for the Cue being played.
+ * The Cue must have beat-sync information set.
+ * It is not possible to get information for a Cue that is started by a Cue link or a Start Action.
+ * If any of the following data is being played back, the beat sync offset setting will fail.
+ * - Data other than a Cue is being played back (since beat-synchronization information does not exist).
+ * - A Cue without synchronization information is being played back. + * - A Cue with beat-synchronization information is being "indirectly" played. (playback started by a Cue link or a Start Action).
+ *
+ */ + public bool SetBeatSyncOffset(short timeMs) + { + return criAtomExPlayback_SetBeatSyncOffset(this.id, timeMs); + } + + public uint id + { + get; + private set; + } + + public Status status + { + get { + return this.GetStatus(); + } + } + + public long time + { + get { + return this.GetTime(); + } + } + + public long timeSyncedWithAudio + { + get { + return this.GetTimeSyncedWithAudio(); + } + } + + public const uint invalidId = 0xFFFFFFFF; + + /* Old APIs */ + public void Stop() { + if (CriAtomPlugin.IsLibraryInitialized() == false) { return; } + criAtomExPlayback_Stop(this.id); + } + public void StopWithoutReleaseTime() { + if (CriAtomPlugin.IsLibraryInitialized() == false) { return; } + criAtomExPlayback_StopWithoutReleaseTime(this.id); + } + public void Pause(bool sw) { criAtomExPlayback_Pause(this.id, sw); } + + + #region DLL Import + #if !CRIWARE_ENABLE_HEADLESS_MODE + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayback_Stop(uint id); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayback_StopWithoutReleaseTime(uint id); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayback_Pause(uint id, bool sw); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayback_Resume(uint id, CriAtomEx.ResumeMode mode); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool criAtomExPlayback_IsPaused(uint id); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern Status criAtomExPlayback_GetStatus(uint id); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool criAtomExPlayback_GetFormatInfo( + uint id, out CriAtomEx.FormatInfo info); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern long criAtomExPlayback_GetTime(uint id); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern long criAtomExPlayback_GetTimeSyncedWithAudio(uint id); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool criAtomExPlayback_GetNumPlayedSamples( + uint id, out long num_samples, out int sampling_rate); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern long criAtomExPlayback_GetSequencePosition(uint id); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayback_SetNextBlockIndex(uint id, int index); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criAtomExPlayback_GetCurrentBlockIndex(uint id); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool criAtomExPlayback_GetPlaybackTrackInfo(uint id, out TrackInfo info); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool criAtomExPlayback_GetBeatSyncInfo(uint id, out CriAtomExBeatSync.Info info); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool criAtomExPlayback_SetBeatSyncOffset(uint id, short timeMs); + #else + private Status _dummyStatus; + private bool _dummyPaused; + private void criAtomExPlayback_Stop(uint id) { _dummyStatus = Status.Removed; } + private void criAtomExPlayback_StopWithoutReleaseTime(uint id) { _dummyStatus = Status.Removed; } + private void criAtomExPlayback_Pause(uint id, bool sw) { _dummyPaused = sw; } + private static void criAtomExPlayback_Resume(uint id, CriAtomEx.ResumeMode mode) { } + private bool criAtomExPlayback_IsPaused(uint id) { return _dummyPaused; } + private Status criAtomExPlayback_GetStatus(uint id) + { + if (_dummyStatus != Status.Removed) { + _dummyStatus = _dummyStatus + 1; + } + return _dummyStatus; + } + private static bool criAtomExPlayback_GetFormatInfo( + uint id, out CriAtomEx.FormatInfo info) { info = new CriAtomEx.FormatInfo(); return false; } + private static long criAtomExPlayback_GetTime(uint id) { return 0; } + private static long criAtomExPlayback_GetTimeSyncedWithAudio(uint id) { return 0; } + private static bool criAtomExPlayback_GetNumPlayedSamples( + uint id, out long num_samples, out int sampling_rate) { num_samples = sampling_rate = 0; return false; } + private static long criAtomExPlayback_GetSequencePosition(uint id) { return 0; } + private static void criAtomExPlayback_SetNextBlockIndex(uint id, int index) { } + private static int criAtomExPlayback_GetCurrentBlockIndex(uint id) { return -1; } + private static bool criAtomExPlayback_GetPlaybackTrackInfo(uint id, out TrackInfo info) { info = new TrackInfo(); return false; } + private static bool criAtomExPlayback_GetBeatSyncInfo(uint id, out CriAtomExBeatSync.Info info) { info = new CriAtomExBeatSync.Info(); return false; } + private static bool criAtomExPlayback_SetBeatSyncOffset(uint id, short timeMs) { return false; } + #endif + #endregion +} + +} //namespace CriWare +/** + * @} + */ + +/* --- end of file --- */ diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExPlayback.cs.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExPlayback.cs.meta new file mode 100644 index 0000000..c1ab68e --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExPlayback.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: e94ea530306be467d9356d8e8d193037 +timeCreated: 1480484327 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExPlayer.cs b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExPlayer.cs new file mode 100644 index 0000000..11e524c --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExPlayer.cs @@ -0,0 +1,3927 @@ +/**************************************************************************** + * + * Copyright (c) 2011 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using System.Text; + +/*========================================================================== + * CRI Atom Native Wrapper + *=========================================================================*/ +/** + * \addtogroup CRIATOM_NATIVE_WRAPPER + * @{ + */ + +namespace CriWare { + +/** + * AtomExPlayer + * + * A player class used for sound playback control.
+ * Performs control such as setting data, starting playback and getting status.
+ *
+ */ +public class CriAtomExPlayer : CriDisposable +{ + public IntPtr nativeHandle {get {return this.handle;} } + public bool isAvailable {get {return this.handle != IntPtr.Zero;} } + private event CriAtomExBeatSync.CbFunc _onBeatSyncCallback = null; + + /** + * Registers the Sequence event callback + * + * Registers a callback function to be executed when the callback marker embedded in a Cue is reached (during playback on the player).
+ * The registered callback function is executed when the application's main thread is updated, immediately after processing the callback event.
+ *
+ */ + public event CriAtomExBeatSync.CbFunc OnBeatSyncCallback { + add { + if (_onBeatSyncCallback == null) { + CriAtom.OnBeatSyncCallback += OnBeatSyncCallbackChainInternal; + } + _onBeatSyncCallback += value; + } + remove { + _onBeatSyncCallback -= value; + if (_onBeatSyncCallback == null) { + CriAtom.OnBeatSyncCallback -= OnBeatSyncCallbackChainInternal; + } + } + } + + private event CriAtomExSequencer.EventCallback _onSequenceCallback = null; + + /** + * Registers the beat synchronization callback + * + * Register a callback function that receives the beat sync position information embedded in the Cue being played by the player.
+ * The registered callback function is executed when the application's main thread is updated, immediately after processing the callback event.
+ *
+ */ + public event CriAtomExSequencer.EventCallback OnSequenceCallback + { + add { + if (_onSequenceCallback == null) { + CriAtomExSequencer.OnCallback += OnSequenceCallbackChainInternal; + } + _onSequenceCallback += value; + } + remove { + _onSequenceCallback -= value; + if (_onSequenceCallback == null) { + CriAtomExSequencer.OnCallback -= OnSequenceCallbackChainInternal; + } + } + } + + private bool hasExistingNativeHandle = false; + private IntPtr entryPoolHandle = IntPtr.Zero; + private int _entryPoolCapacity = 0; + private int max_path = 0; + + /** + * Player status + * + * A value indicating the playback status of the AtomExPlayer.
+ * It can get using the CriWare.CriAtomExPlayer::GetStatus function.
+ *
+ * The playback status usually changes in the following order.
+ * -# Stop + * -# Prep + * -# Playing + * -# PlayEnd + * . + * The status immediately after creating the AtomExPlayer is Stop.
+ * When you set the data using the CriWare.CriAtomExPlayer::SetCue function etc., + * and call the CriWare.CriAtomExPlayer::Start function, the status changes to playback preparation state ( Prep ) to prepare playback.
+ * When enough data is supplied and the playback is ready, the status changes to ( Playing ) + * and the sound output starts.
+ * When all the data set was played back, the status changes to + * playback completed ( PlayEnd ).
+ * One AtomExPlayer can play multiple sounds.
+ * If you call the CriWare.CriAtomExPlayer::Start function for the AtomExPlayer being played, + * the two sounds are played back at the same time.
+ * If the CriWare.CriAtomExPlayer::Stop function is called during playback, + * all sounds currently being played in the AtomExPlayer are stopped and the status returns to Stop.
+ * (Depending on the timing of calling the CriWare.CriAtomExPlayer::Stop function, + * it may take some time to change to Stop.)
+ *
+ * When the CriWare.CriAtomExPlayer::Start function is called multiple times for one AtomExPlayer, + * the status changes to Prep if at least one sound is being prepared.
+ * (The status does not change to Playing until all the sounds + * are playing.)
+ * If you call the CriWare.CriAtomExPlayer::Start function again for the player + * in Playing state, the status temporarily returns to Prep.
+ *
+ * If invalid data is read during playback or file access fails, + * the status changes to Error.
+ * If an error occurs in a sound while playing multiple sounds, the player status + * changes to Error regardless of the status of other sounds.
+ *
+ * + * + * + */ + public enum Status { + Stop = 0, /**< Stopped */ + Prep, /**< Preparing for playback */ + Playing, /**< Playing */ + PlayEnd, /**< Playback completed */ + Error, /**< Error occurred */ + } + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + private struct Config { + public CriAtomEx.VoiceAllocationMethod voiceAllocationMethod; + public int maxPathStrings; + public int maxPath; + public int maxAisacs; + public bool updatesTime; + public bool enableAudioSyncedTimer; + } + + /** + * Creates an AtomExPlayer + * AtomExPlayer + * + * Creates an AtomExPlayer.
+ *
+ * The steps for playing back the sound data using the created AtomExPlayer are as follows:
+ * -# Use the CriWare.CriAtomExPlayer::SetCue function to set the data to be played in the AtomExPlayer.
+ * -# Call the CriWare.CriAtomExPlayer::Start function to start playback.
+ * The library must be initialized before calling this function.
+ *
+ * When playing back a sound file that is not packed by specifying + * it in the CriWare.CriAtomExPlayer::SetFile function, + * CriWare.CriAtomExPlayer::CriAtomExPlayer(int, int) function must be used instead of this function.
+ *
+ * This function is a return-on-complete function.
+ * The time it takes for creating the AtomExPlayer depends on the platform.
+ * If this function is called at a timing when the screen needs to be updated such as in a game loop, + * the process is blocked in the unit of milliseconds, resulting in dropped frames.
+ * Create/discard AtomExPlayers at a timing when load fluctuations is accepted + * such as when switching scenes.
+ *
+ * + * + * + * + * + * + */ + public CriAtomExPlayer() : this(0, 0, false, IntPtr.Zero) + { + } + + /** + * Creates an AtomExPlayer (for single file playback) + * Maximum path string length + * The number of files that can be played simultaneously + * AtomExPlayer + * + * Create an AtomExPlayer for single file playback.
+ * The basic specification is the same as the CriWare.CriAtomExPlayer::CriAtomExPlayer() function, + * except that a single file can be played.
+ * The AtomExPlayer created by this function + * allocates maxPathxmaxPathStrings memory areas for single file playback.
+ * This area is not used when playing back ACB or AWB files.
+ * When the CriWare.CriAtomExPlayer::SetFile function is not used, it is possible to + * save memory usage by using the CriWare.CriAtomExPlayer::CriAtomExPlayer() + * function instead of this function.
+ *
+ * + */ + public CriAtomExPlayer(int maxPath, int maxPathStrings) : this(maxPath, maxPathStrings, false, IntPtr.Zero) + { + } + + /** + * Creates an AtomExPlayer (using sound synchronization timer) + * Sound synchronization timer enabled flag + * AtomExPlayer + * + * Create an AtomExPlayer which supports sound synchronization.
+ * The basic specification is the same as the CriWare.CriAtomExPlayer::CriAtomExPlayer() function + * except that the playback time synchronized with the sound can be obtained.
+ * For the sound played using the AtomExPlayer created by specifying true for + * the argument of this function, the time is updated in sync with the number + * of played samples
+ * When the CriWare.CriAtomExPlayback::GetTimeSyncedWithAudio function is not used, + * it is possible to suppress the increase in load by specifying false + * in the argument of this function or by using CriWare.CriAtomExPlayer::CriAtomExPlayer() + * instead of this function.
+ * For the AtomExPlayer created by specifying true for the argument of this function, + * the playback pitch cannot be changed using the CriWare.CriAtomExPlayer::SetPitch function.
+ *
+ * + * + */ + public CriAtomExPlayer(bool enableAudioSyncedTimer) : this(0, 0, enableAudioSyncedTimer, IntPtr.Zero) + { + } + + /** + * Creates an AtomExPlayer (single file playback, using sound synchronization timer) + * Maximum path string length + * The number of files that can be played simultaneously + * Sound synchronization timer enabled flag + * AtomExPlayer + * + * Create an AtomExPlayer for single file playback.
+ * By specifying the flag to enableAudioSyncedTimer, it is possible to get + * the playback time synchronized with the sound.
+ * Basic specification is the same as the CriWare.CriAtomExPlayer::CriAtomExPlayer() function.
+ *
+ * + * + * + */ + public CriAtomExPlayer(int maxPath, int maxPathStrings, bool enableAudioSyncedTimer) : this(maxPath, maxPathStrings, enableAudioSyncedTimer, IntPtr.Zero) + { + } + + public CriAtomExPlayer(IntPtr existingNativeHandle) : this(0, 0, false, existingNativeHandle) + { + } + + public CriAtomExPlayer(int maxPath, int maxPathStrings, bool enableAudioSyncedTimer, IntPtr existingNativeHandle) + { + /* ライブラリの初期化 */ + if (!CriAtomPlugin.IsLibraryInitialized()) { + throw new Exception("CriAtomPlugin is not initialized."); + } + + /* ハンドルの作成 */ + Config config; + config.voiceAllocationMethod = CriAtomEx.VoiceAllocationMethod.Once; + config.maxPath = maxPath; + config.maxPathStrings = maxPathStrings; + config.enableAudioSyncedTimer = enableAudioSyncedTimer; + /* デフォルト値 */ + config.maxAisacs = 8; + config.updatesTime = true; + + /* 既存の (外部で作成された) CriAtomExPlayerHn を渡されたか? */ + hasExistingNativeHandle = (existingNativeHandle != IntPtr.Zero); + if (hasExistingNativeHandle) { + this.handle = existingNativeHandle; + } else { + /* CriAtomExPlayerHn を新規作成する */ + this.handle = criAtomExPlayer_Create(ref config, IntPtr.Zero, 0); + this.max_path = config.maxPath; + } + + CriDisposableObjectManager.Register(this, CriDisposableObjectManager.ModuleType.Atom); + } + + + + /** + * Discards an AtomExPlayer + * + * Discards the AtomExPlayer.
+ * When this function is called, all the resources allocated in the DLL when creating the AtomExPlayer are released.
+ * This function is a return-on-complete function.
+ * If you try to discard an AtomExPlayer that is playing sound, this function waits for + * the playback to be stopped and then releases the resources.
+ * (If the playback is from a file, it also waits for the completion of reading.)
+ * Therefore, the process may be blocked in this function for a long time (for several frames).
+ * Create/discard AtomExPlayers at a timing when load fluctuations is accepted + * such as when switching scenes.
+ *
+ * + */ + public override void Dispose() + { + CriDisposableObjectManager.Unregister(this); + if (this.entryPoolHandle != IntPtr.Zero) { + this.StopWithoutReleaseTime(); + CRIWARE7A36FD14(this.entryPoolHandle); + } + this.entryPoolHandle = IntPtr.Zero; + this._entryPoolCapacity = 0; + if (hasExistingNativeHandle == false && isAvailable) { + /* CriAtomExPlayerHn を新規作成した場合 */ + /* ハンドルの削除 */ + criAtomExPlayer_Destroy(this.handle); + } + if (_onBeatSyncCallback != null) { + _onBeatSyncCallback = null; + CriAtom.OnBeatSyncCallback -= OnBeatSyncCallbackChainInternal; + } + this.handle = IntPtr.Zero; + GC.SuppressFinalize(this); + } + + /** + * Sets the sound data (Cue name specified) + * ACB object + * Cue name + * + * Associates the Cue name with the AtomExPlayer.
+ * After specifying the Cue name using this function, when you start the playback + * using the CriWare.CriAtomExPlayer::Start function, the specified Cue is played.
+ * When specifying the Cue to play with the CriWare.CriAtomExPlayer::SetCue function, the parameters set by the following functions are ignored:
+ * - CriWare.CriAtomExPlayer::SetFormat + * - CriWare.CriAtomExPlayer::SetNumChannels + * - CriWare.CriAtomExPlayer::SetSamplingRate + * . + * (The audio format, number of channels, sampling rate, etc. are automatically set based on the information in the ACB file.)
+ *
+ * + * : + * // プレーヤの作成 + * CriAtomExPlayer player = new CriAtomExPlayer(); + * + * // ACFファイルの登録 + * CriAtomEx.RegisterAcf(null, "sample.acf"); + * + * // ACBファイルのロード + * CriAtomExAcb acb = CriAtomExAcb.LoadAcbFile(null, "sample.acb", "sample.awb"); + * + * // 再生するキューの名前を指定 + * player.SetCue(acb, "gun_shot"); + * + * // セットされた音声データを再生 + * player.Start(); + * : + * Once set, the information on the data is + * retained in the AtomExPlayer until other data is set.
+ * Therefore, when playing the same data many times, + * it is not necessary to reset the data for each playback.
+ * (You can call the CriWare.CriAtomExPlayer::Start function repeatedly.)
+ * + */ + public void SetCue(CriAtomExAcb acb, string name) + { + criAtomExPlayer_SetCueName(this.handle, + (acb != null) ? acb.nativeHandle : IntPtr.Zero, name); + } + + /** + * Sets the sound data (Cue ID specified) + * ACB object + * Cue ID + * + * Associates the Cue ID with the AtomExPlayer.
+ * After specifying the Cue ID using this function, when you start the playback + * using the CriWare.CriAtomExPlayer::Start function, the specified Cue is played.
+ * When specifying the Cue to play with the CriWare.CriAtomExPlayer::SetCue function, the parameters set by the following functions are ignored:
+ * - CriWare.CriAtomExPlayer::SetFormat + * - CriWare.CriAtomExPlayer::SetNumChannels + * - CriWare.CriAtomExPlayer::SetSamplingRate + * . + * (The audio format, number of channels, sampling rate, etc. are automatically set based on the information in the ACB file.)
+ *
+ * + * : + * // プレーヤの作成 + * CriAtomExPlayer player = new CriAtomExPlayer(); + * + * // ACFファイルの登録 + * CriAtomEx.RegisterAcf(null, "sample.acf"); + * + * // ACBファイルのロード + * CriAtomExAcb acb = CriAtomExAcb.LoadAcbFile(null, "sample.acb", "sample.awb"); + * + * // 再生するキューのIDを指定 + * player.SetCue(acb, 100); + * + * // セットされた音声データを再生 + * player.Start(); + * : + * Once set, the information on the data is + * retained in the AtomExPlayer until other data is set.
+ * Therefore, when playing the same data many times, + * it is not necessary to reset the data for each playback.
+ * (You can call the CriWare.CriAtomExPlayer::Start function repeatedly.)
+ * + */ + public void SetCue(CriAtomExAcb acb, int id) + { + criAtomExPlayer_SetCueId(this.handle, + (acb != null) ? acb.nativeHandle : IntPtr.Zero, id); + } + + /** + * Sets the sound data (Cue index specified) + * ACB object + * Cue index + * + * Associates the Cue index with the AtomExPlayer.
+ * After specifying the Cue index using this function, when you start the playback + * using the CriWare.CriAtomExPlayer::Start function, the specified Cue is played.
+ * When specifying the Cue to play with the CriWare.CriAtomExPlayer::SetCueIndex function, the parameters set by the following functions are ignored:
+ * - CriWare.CriAtomExPlayer::SetFormat + * - CriWare.CriAtomExPlayer::SetNumChannels + * - CriWare.CriAtomExPlayer::SetSamplingRate + * . + * (The audio format, number of channels, sampling rate, etc. are automatically set based on the information in the ACB file.)
+ *
+ * This function can be used to set the audio to play on a player without specifying the Cue name or the Cue ID.
+ * (This function can be used for debugging purposes, + * since the contents in the ACB file can be played without specifying a Cue name or Cue ID.)
+ *
+ * + * : + * // プレーヤの作成 + * CriAtomExPlayer player = new CriAtomExPlayer(); + * + * // ACFファイルの登録 + * CriAtomEx.RegisterAcf(null, "sample.acf"); + * + * // ACBファイルのロード + * CriAtomExAcb acb = CriAtomExAcb.LoadAcbFile(null, "sample.acb", "sample.awb"); + * + * // 再生するキューのインデックスを指定 + * player.SetCueIndex(acb, 300); + * + * // セットされた音声データを再生 + * player.Start(); + * : + * Once set, the information on the data is + * retained in the AtomExPlayer until other data is set.
+ * Therefore, when playing the same data many times, + * it is not necessary to reset the data for each playback.
+ * (You can call the CriWare.CriAtomExPlayer::Start function repeatedly.)
+ * + */ + public void SetCueIndex(CriAtomExAcb acb, int index) + { + criAtomExPlayer_SetCueIndex(this.handle, + (acb != null) ? acb.nativeHandle : IntPtr.Zero, index); + } + + /** + * Sets the sound data (CPK content ID specified) + * Binder + * Content ID + * + * Associates the content with the AtomExPlayer.
+ * Used to play the content file in the CPK file by specifying the ID + * using the CRI File System library.
+ * By specifying the binder and content ID for the player + * using this function and calling the CriWare.CriAtomExPlayer::Start function, + * the specified content file is streamed.
+ * Note that the file is not loaded when this function is called.
+ * Loading of the file starts after calling the CriWare.CriAtomExPlayer::Start function.
+ * When specifying the audio data to play with the CriWare.CriAtomExPlayer::SetContentId function, + * it is necessary to provide information about the data by calling the following functions:
+ * - CriWare.CriAtomExPlayer::SetFormat + * - CriWare.CriAtomExPlayer::SetNumChannels + * - CriWare.CriAtomExPlayer::SetSamplingRate + * .
+ *
+ * + * : + * // プレーヤの作成 + * CriAtomExPlayer player = new CriAtomExPlayer(); + * + * // バインダの作成 + * CriFsBinder binder = new CriFsBinder(); + * + * // CPKファイルのバインドを開始 + * CriFsBindRequest bindRequest = CriFsUtility.BindCpk(binder, "sample.cpk"); + * + * // バインドの完了を待つ + * yield return bindRequest.WaitForDone(this); + * + * // 音声ファイルをセット + * // sample.cpk内の1番のコンテンツをセット + * player.SetContentId(binder, 1); + * + * // 再生する音声データのフォーマットを指定 + * player.SetFormat(CriAtomEx.Format.ADX); + * player.SetNumChannels(2); + * player.SetSamplingRate(44100); + * + * // セットされた音声データを再生 + * plaeyr.Start(); + * : + * Once set, the information on the file is + * retained in the AtomExPlayer until other data is set.
+ * Therefore, when playing the same data many times, + * it is not necessary to reset the data for each playback.
+ * (You can call the CriWare.CriAtomExPlayer::Start function repeatedly.)
+ * + * + * + * + */ + public void SetContentId(CriFsBinder binder, int contentId) + { + criAtomExPlayer_SetContentId(this.handle, + (binder != null) ? binder.nativeHandle : IntPtr.Zero, contentId); + } + + /** + * Sets the sound data (file name specified) + * Binder object + * File path + * + * Associates the sound file with the AtomExPlayer.
+ * After specifying a file using this function, the file is streamed + * by calling the CriWare.CriAtomExPlayer::Start function to start playback.
+ * Note that the file is not loaded when this function is called.
+ * Loading of the file starts after calling the CriWare.CriAtomExPlayer::Start function.
+ * When using this function, it is necessary to create an AtomExPlayer for single file playback.
+ * Specifically, CriWare.CriAtomExPlayer::CriAtomExPlayer(int, int) must be used + * instead of CriWare.CriAtomExPlayer::CriAtomExPlayer().
+ *
+ * When setting the sound data using the CriWare.CriAtomExPlayer::SetFile function, + * it is necessary to separately specify the information of the sound data to be played using the following functions.
+ * - CriWare.CriAtomExPlayer::SetFormat + * - CriWare.CriAtomExPlayer::SetNumChannels + * - CriWare.CriAtomExPlayer::SetSamplingRate
+ *
+ * + * : + * // プレーヤの作成 + * CriAtomExPlayer player = new CriAtomExPlayer(); + * + * // 音声ファイルをセット + * player.SetFile(null, "sample.hca"); + * + * // 再生する音声データのフォーマットを指定 + * player.SetFormat(CriAtomEx.Format.HCA); + * player.SetNumChannels(2); + * player.SetSamplingRate(48000); + * + * // セットされた音声データを再生 + * player.Start(); + * : + * Once set, the information on the file is + * retained in the AtomExPlayer until other data is set.
+ * Therefore, when playing the same data many times, + * it is not necessary to reset the data for each playback.
+ * (You can call the CriWare.CriAtomExPlayer::Start function repeatedly.)
+ * + * + * + * + * + */ + public void SetFile(CriFsBinder binder, string path) + { + criAtomExPlayer_SetFile(this.handle, + (binder != null) ? binder.nativeHandle : IntPtr.Zero, path); + } + + /** + * Sets the sound data (on-memory byte array specified) + * Byte array + * Buffer size + * + * Associates the sound data placed on the memory with the AtomExPlayer.
+ * After specifying the memory address and size using this function, when you start playback + * using the CriWare.CriAtomExPlayer::Start function, the specified data is played.
+ * When using this function, it is necessary to create an AtomExPlayer for single file playback.
+ * Specifically, CriWare.CriAtomExPlayer::CriAtomExPlayer(int, int) must be used + * instead of CriWare.CriAtomExPlayer::CriAtomExPlayer().
+ *
+ * When setting the sound data using the CriWare.CriAtomExPlayer::SetData function, + * it is necessary to separately specify the information of the sound data to be played using the following functions.
+ * - CriWare.CriAtomExPlayer::SetFormat + * - CriWare.CriAtomExPlayer::SetNumChannels + * - CriWare.CriAtomExPlayer::SetSamplingRate
+ * The buffer address passed to SetData should be fixed beforehand by the application + * so that it is not moved by the garbage collector.
+ *
+ * + * : + * // プレーヤの作成 + * CriAtomExPlayer player = new CriAtomExPlayer(); + * + * // 音声ファイルをセット + * player.SetData(null, buffer, size); + * + * // 再生する音声データのフォーマットを指定 + * player.SetFormat(CriAtomEx.Format.HCA); + * player.SetNumChannels(2); + * player.SetSamplingRate(48000); + * + * // セットされた音声データを再生 + * player.Start(); + * : + * Once set, the information on the file is + * retained in the AtomExPlayer until other data is set.
+ * Therefore, when playing the same data many times, + * it is not necessary to reset the data for each playback.
+ * (You can call the CriWare.CriAtomExPlayer::Start function repeatedly.)
+ * + * + * + * + * + */ + public void SetData(byte[] buffer, int size) + { + criAtomExPlayer_SetData(this.handle, + buffer, size); + } + + /** + * Sets the sound data (on-memory buffer address specified) + * Buffer address + * Buffer size + * + * For details, refer to CriWare.CriAtomExPlayer::SetData(byte[], int) . + * + * + */ + public void SetData(IntPtr buffer, int size) { + criAtomExPlayer_SetData(this.handle, + buffer, size); + } + + /** + * Specifies the format + * Format + * + * Specifies the sound format to be played by the AtomExPlayer.
+ * When the sound is played using the CriWare.CriAtomExPlayer::Start function, the AtomExPlayer + * gets a Voice that can play the data with the format specified by this function from the Voice Pool.
+ * The default before calling the function is the ADX format.
+ * This function needs to be set only when playing sound without using the ACB file.
+ * When playing a Cue, the format is automatically acquired from the Cue Sheet, + * so it is not necessary to call this function separately.
+ *
+ */ + public void SetFormat(CriAtomEx.Format format) + { + criAtomExPlayer_SetFormat(this.handle, format); + } + + /** + * Specifies the number of channels + * The number of channels + * + * Specifies the number of sound channels to be played by the AtomExPlayer.
+ * When the sound is played using the CriWare.CriAtomExPlayer::Start function, the AtomExPlayer + * gets a Voice that can play the data with the channel count specified by this function from the Voice Pool.
+ * The default before calling the function is 2 channels.
+ * This function needs to be set only when playing sound without using the ACB file.
+ * When playing a Cue, the format is automatically acquired from the Cue Sheet, + * so it is not necessary to call this function separately.
+ *
+ */ + public void SetNumChannels(int numChannels) + { + criAtomExPlayer_SetNumChannels(this.handle, numChannels); + } + + /** + * Specifies the sampling rate + * Sampling rate + * + * Specifies the sampling rate of the sound played by the AtomExPlayer.
+ * When the sound is played using the CriWare.CriAtomExPlayer::Start function, the AtomExPlayer + * gets a Voice that can play the data with the sampling rate specified by this function from the Voice Pool.
+ * The default before calling the function is 32000Hz.
+ * This function needs to be set only when playing sound without using the ACB file.
+ * When playing a Cue, the format is automatically acquired from the Cue Sheet, + * so it is not necessary to call this function separately.
+ *
+ */ + public void SetSamplingRate(int samplingRate) + { + criAtomExPlayer_SetSamplingRate(this.handle, samplingRate); + } + + /** + * Creates an entry pool for concatenated playback + * The number of data that can be input + * Whether to stop if the entry pool is empty + * + * Create an entry pool for concatenated playback using CriWare.CriAtomExPlayer::EntryData etc.
+ * Calling this function puts the player in linked playback mode.
+ * If the stopOnEmpty flag is set to false, even if the data supplied by the CriWare.CriAtomExPlayer::SetData + * or CriWare.CriAtomExPlayer::EntryData reached its end, the player stays in playback state and waits for the next data input.
+ * If set to true, the player stops playback when the supplied data is exhausted, + * so make sure to feed data with a margin.
+ *
+ * + */ + public void PrepareEntryPool(int capacity, bool stopOnEmpty) + { + if (this.entryPoolHandle != IntPtr.Zero) { + CRIWARE7A36FD14(this.entryPoolHandle); + this._entryPoolCapacity = 0; + this.entryPoolHandle = IntPtr.Zero; + } + + if (capacity <= 0) + return; + + this.entryPoolHandle = CRIWAREFDE24A32(this.handle, capacity, this.max_path, stopOnEmpty); + if (this.entryPoolHandle != IntPtr.Zero) { + this._entryPoolCapacity = capacity; + } + } + + /** + * The number of concatenated playback data entries + * Number of entries + * + * Gets the number of entries entered for concatenated playback. + * + * + * + */ + public int GetNumEntries() + { + if (this.entryPoolHandle == IntPtr.Zero) { + return 0; + } + return CRIWARE3AE79C16(this.entryPoolHandle); + } + + /** + * Number of entries consumed by the playback process + * Number of entries + * + * Gets the number of entries consumed by the playback process when fetching concatenated playback data to the player.
+ * This number will increase each time an entry is consumed during playback, and it will be reset when CriAtomExPlayer::Start is called.
+ * It does not increase if the same entry is being played in a loop.
+ *
+ * + * + */ + public int GetNumConsumedEntries() + { + if (this.entryPoolHandle == IntPtr.Zero) { + return 0; + } + return CRIWAREE3B3AD44(this.entryPoolHandle); + } + + /** + * The number of concatenated playback data that can be input + */ + public int entryPoolCapacity { get { return _entryPoolCapacity; } } + + + /** + * Inputs the data for linked playback (file name specified) + * Binder object + * File path + * Whether to repeat playback when the next data is not entered + * Whether the data was successfully entered. + * + * Inputs a sound file for linked playback.
+ * When performing linked playback, set the start data using the CriWare.CriAtomExPlayer::SetData function etc. + * start playback, then input additional playback data using this function.
+ *
+ * + * + * + */ + public bool EntryFile(CriFsBinder binder, string path, bool repeat) + { + if (this.entryPoolHandle == IntPtr.Zero) { + return false; + } + return CRIWAREB64C6C94(this.entryPoolHandle, + (binder != null) ? binder.nativeHandle : IntPtr.Zero, + path, + repeat, + this.max_path); + } + + /** + * Inputs the data for linked playback (CPK content ID specified) + * Binder object + * Content ID + * Whether to repeat playback when the next data is not entered + * Whether the data was successfully entered. + * + * Enter the content for linked playback.
+ * Used to play the content file in the CPK file by specifying the ID + * using the CRI File System library.
+ * When performing linked playback, set the start data using the CriWare.CriAtomExPlayer::SetData function etc. + * start playback, then input additional playback data using this function.
+ *
+ * + * + * + */ + public bool EntryContentId(CriFsBinder binder, int contentId, bool repeat) + { + if (this.entryPoolHandle == IntPtr.Zero) { + return false; + } + return CRIWARE591013B5(this.entryPoolHandle, + (binder != null) ? binder.nativeHandle : IntPtr.Zero, + contentId, + repeat); + } + + /** + * Enters the concatenated playback data (on-memory byte array specified) + * On-memory byte array + * Buffer size + * Whether to repeat playback when the next data is not entered + * Whether the data was successfully entered. + * + * Inputs the data for linked playback.
+ * When performing linked playback, set the start data using the CriWare.CriAtomExPlayer::SetData function etc. + * start playback, then input data using this function.
+ *
+ * + * + * + */ + public bool EntryData(byte[] buffer, int size, bool repeat) + { + if (this.entryPoolHandle == IntPtr.Zero) { + return false; + } + return CRIWARE94039BDE(this.entryPoolHandle, buffer, size, repeat); + } + + /** + * Enters the concatenated playback data (on-memory buffer address specified) + * Buffer address + * Buffer size + * Whether to repeat playback when the next data is not entered + * Whether the data was successfully entered. + * + * Inputs the data for linked playback.
+ * When performing linked playback, set the start data using the CriWare.CriAtomExPlayer::SetData function etc. + * start playback, then input data using this function.
+ *
+ * + */ + public bool EntryData(IntPtr buffer, int size, bool repeat) + { + if (this.entryPoolHandle == IntPtr.Zero) { + return false; + } + return CRIWARE94039BDE(this.entryPoolHandle, buffer, size, repeat); + } + + /** + * Inputs the data for linked playback (Cue name specified) + * ACB handle + * Cue name + * Whether to repeat playback when the next data is not entered + * Whether the data was successfully entered. + * + * Inputs the data for linked playback.
+ * When performing linked playback, set the start data using the CriWare.CriAtomExPlayer::SetData function etc. + * start playback, then input data using this function.
+ *
+ * + */ + public bool EntryCue(CriAtomExAcb acb, string name, bool repeat) + { + if (this.entryPoolHandle == IntPtr.Zero) { + return false; + } + return CRIWAREEF1A65AD(this.entryPoolHandle, + (acb != null) ? acb.nativeHandle : IntPtr.Zero, name, repeat); + } + + /** + * Starts playback + * CriAtomExPlayback object + * + * Starts playing the sound data.
+ * Before calling this function, it is necessary to set the sound data to be played + * to the AtomExPlayer in advance using the functions such as CriWare.CriAtomExPlayer::SetCue .
+ * For example, when playing a Cue, it is necessary to set the sound data + * as follows using the CriWare.CriAtomExPlayer::SetCue function in advance, + * before calling this function.
+ * : + * // ACFファイルの登録 + * CriAtomEx.RegisterAcf(null, "sample.acf"); + * + * // ACBファイルのロード + * CriAtomExAcb acb = CriAtomExAcb.LoadAcbFile(null, "sample.acb", "sample.awb"); + * + * // プレーヤの作成 + * CriAtomExPlayer player = new CriAtomExPlayer(); + * + * // 再生するキューの名前を指定 + * player.SetCue(acb, "gun_shot"); + * + * // セットされた音声データを再生 + * player.Start(); + * : + * + * 本関数実行後、再生の進み具合(発音が開始されたか、再生が完了したか等) + * がどうなっているかは、ステータスを取得することで確認が可能です。
+ * ステータスの取得には、 CriWare.CriAtomExPlayer::GetStatus 関数を使用します。
+ * CriWare.CriAtomExPlayer::GetStatus 関数は以下の5通りのステータスを返します。
-# Stop + * -# Prep + * -# Playing + * -# PlayEnd + * -# Error + * . + * When you create an AtomExPlayer, the AtomExPlayer's status is Stop.
+ * By calling this function after setting the sound data to be played, + * the status of the AtomExPlayer changes to ready ( Prep ).
+ * (Prep is the status waiting for the data to be supplied or start of decoding.)
+ * When enough data is supplied for starting playback, the AtomExPlayer changes the status to + * Playing and starts to output sound.
+ * When all the set data have been played back, AtomExPlayer + * changes its status to PlayEnd.
+ * If an error occurs during playback, AtomExPlayer + * changes the status to Error.
+ *
+ * By checking the status of AtomExPlayer and switching the processing depending on the status, + * it is possible to create a program linked to the sound playback status.
+ * For example, if you want to wait for the completion of sound playback before proceeding, use the following code. + * : + * // プレーヤの作成 + * CriAtomExPlayer player = new CriAtomExPlayer(); + * + * // 再生するキューの名前を指定 + * player.SetCue(acb, "gun_shot"); + * + * // セットされた音声データを再生 + * player.Start(); + * + * // 再生完了待ち + * while (player.GetStatus() != CriAtomExPlayer.Status.PlayEnd) { + * yield return null; + * } + * : + * + *
+ *
+ * + * + */ + public CriAtomExPlayback Start() + { + if (this.entryPoolHandle != IntPtr.Zero) { + CRIWARE6BE60787(this.entryPoolHandle); + } + return new CriAtomExPlayback(criAtomExPlayer_Start(this.handle)); + } + + /** + * Prepare for playback + * CriAtomExPlayback object + * + * Prepares for playing sound data.
+ * Before calling this function, it is necessary to set the sound data to be played + * to the AtomExPlayer in advance using the functions such as CriWare.CriAtomExPlayer::SetData .
+ *
+ * When this function is called, the sound playback starts in the paused state.
+ * When the function is called, the resources required for sound playback are allocated + * and the data starts to be buffered (reading the streamed file), + * but the sound is not played after finished buffering.
+ * (It stands by in paused state even if it is ready to be played.)
+ *
+ * In the case of playing only one sound, this function behaves the same as the code below.
+ * : + * // プレーヤをポーズ状態に設定 + * player.Pause(); + * + * // 音声の再生を開始 + * CriAtomExPlayback playback = player.Start(); + * : + * + *
+ * 本関数で再生準備を行った音声を発音するには、 + * 本関数が返すCriAtomExPlaybackオブジェクトに対し、 + * CriWare.CriAtomExPlayback::Resume を実行する必要があります。
+ *
+ * In streaming playback, there is a time lag after starting playback using + * the CriWare.CriAtomExPlayer::Start function before the sound playback actually starts.
+ * (Because it takes time to buffer the sound data.)
+ *
+ * By performing the following operations, it is possible to control the timing of sound playback + * even for sound in stream playback. + * -# Call the CriWare.CriAtomExPlayer::Prepare function to start preparation. + * -# Check the status of the CriAtomExPlayback obtained acquired in step 1. using the CriWare.CriAtomExPlayback::GetStatus function. + * -# When the status becomes Playing, unpause the playback using the CriWare.CriAtomExPlayback::Resume function. + * -# After unpausing, the sound starts at the next server processing timing. + * . + * The specific code is as follows.
+ * : + * // プレーヤの作成 + * CriAtomExPlayer player = new CriAtomExPlayer(); + * + * // 再生するキューの名前を指定 + * player.SetCue(acb, "gun_shot"); + * + * // セットされた音声データの再生準備を開始 + * CriAtomExPlayback playback = player.Prepare(); + * + * // 再生準備完了待ち + * while (playback.GetStatus() != CriAtomExPlayback.Status.Playing) { + * yield return null; + * } + * + * // ポーズを解除 + * playback.Resume(CriAtomEx.ResumeMode.PreparedPlayback); + * : + * + *
+ * If PausedPlayback is specified when unpausing, + * both the pausing for preparing playback by this function and the + * pausing by the CriWare.CriAtomExPlayer::Pause function are canceled.
+ * If you want to play the sound prepared for playback using this function + * while stopping the sound paused by the CriWare.CriAtomExPlayer::Pause function, + * specify PreparedPlayback when unpausing.
+ *
+ * + * + */ + public CriAtomExPlayback Prepare() + { + return new CriAtomExPlayback(criAtomExPlayer_Prepare(this.handle)); + } + + /** + * Stop playing + * Whether to ignore release time + * (False = perform release process, True = ignore release time and stop immediately) + * + * Issues a request to stop playback.
+ * If this function is called for the AtomExPlayer that is playing sound, + * the AtomExPlayer stops playing (stops reading files or playback), + * and transitions to the Stop state.
+ *
+ * If the argument is set to True, + * the release time is ignored and the sound is stopped immediately, + * even if the sound being played has an envelope release time.
+ * If this function is called for an AtomExPlayer that has already stopped (AtomExPlayer + * whose status is PlayEnd or Error), the status of the AtomExPlayer is changed to Stop. + * If this function is called for the AtomExPlayer that is playing sound, + * the status may not change to Stop immediately.
+ * (It may take some time for it to change to Stop.)
+ *
+ * + * + */ + public void Stop(bool ignoresReleaseTime) + { + if (!this.isAvailable) { + return; + } + + if (ignoresReleaseTime == false) { + criAtomExPlayer_Stop(this.handle); + } else { + criAtomExPlayer_StopWithoutReleaseTime(this.handle); + } + if (this.entryPoolHandle != IntPtr.Zero) { + CRIWAREF051667D(this.entryPoolHandle); + } + } + + /** + * Pause + * + * Pauses playback.
+ * In the default state (state immediately after creating the player), the player is not paused.
+ * When this function is called, "all" the sounds being played by the player are paused.
+ * Use the CriWare.CriAtomExPlayback::Pause function to pause + * each sound being played separately.
+ *
+ * + * + * + */ + public void Pause() + { + criAtomExPlayer_Pause(this.handle, true); + } + + /** + * Cancels the pausing + * Unpausing target + * + * Cancels the suspended state.
+ *
+ * When this function is called by specifying PausedPlayback in the argument (mode), + * the playback of the sound paused by the user using the CriWare.CriAtomExPlayer::Pause function + * (or the CriWare.CriAtomExPlayback::Pause function) is resumed.
+ * When this function is called by specifying PreparedPlayback in the argument (mode), + * the playback of the sound prepared by the user using the CriWare.CriAtomExPlayer::Prepare starts.
+ * If the player paused by the CriWare.CriAtomExPlayer::Pause function is prepared for playback with the CriWare.CriAtomExPlayer::Prepare function, + * the playback will not start until the unpausing processing triggered by both PausedPlayback and PreparedPlayback is completed.
+ *
+ * To always start playback, even if the player is processed by the CriWare.CriAtomExPlayer::Pause or CriWare.CriAtomExPlayer::Prepare functions, + * please call this function with the "mode" argument set to "AllPlayback".
+ * When this function is called, "all" the sounds being played by the player + * are unpaused.
+ * Use the CriWare.CriAtomExPlayback::Resume function to unpause + * each sound being played separately.
+ *
+ * + * + */ + public void Resume(CriAtomEx.ResumeMode mode) + { + criAtomExPlayer_Resume(this.handle, mode); + } + + /** + * Gets the pausing status + * Whether the playback is paused (False = not paused, True = paused) + * + * Returns whether the player is paused.
+ * This function returns true only when "all sounds are paused".
+ * After calling the CriWare.CriAtomExPlayer::Pause function, if the sounds were unpaused by specifying the playback ID + * (the CriWare.CriAtomExPlayback::Pause function was called), this function returns + * false.
+ *
+ * This function does not distinguish between the sounds paused by the + * CriWare.CriAtomExPlayer::Pause function and the those paused by the CriWare.CriAtomExPlayer::Prepare function.
+ * (Regardless of the pausing method, it only determines whether all the Voices are paused.)
+ *
+ * + * + */ + public bool IsPaused() + { + return criAtomExPlayer_IsPaused(this.handle); + } + + /** + * Sets the volume + * Volume value + * + * Specify the output sound volume.
+ * After setting the volume using this function, when you start the playback + * using the CriWare.CriAtomExPlayer::Start function, the sound is played with the specified volume.
+ * It is also possible to update the volume of the sound already played by calling + * the CriWare.CriAtomExPlayer::Update or CriWare.CriAtomExPlayer::UpdateAll function after setting the volume.
+ *
+ * The volume value is a scale factor for the amplitude of the sound data (the unit is not decibel).
+ * For example, if you specify 1.0f, the original sound is played at its unmodified volume.
+ * If you specify 0.5f, the sound is played at the volume by halving the amplitude (-6dB) + * of the original waveform.
+ * If you specify 0.0f, the sound is muted (silent).
+ * The default value for volume is 1.0f.
+ * You can set the volume value to 0.0f or higher.
+ * If you set a value higher than 1.0f, the waveform data may be played + * at a louder volume than the original Material depending on the platform.
+ * If you specify a volume value lower than 0.0f, the value is clipped to 0.0f.
+ * (Even if you set a negative volume value, + * the phase of the waveform data is not inverted.)
+ *
+ * When playing a Cue, if this function is called when the volume is set on the data, + * the value set on the data and the setting in this function is multiplied and the result is applied.
+ * For example, if the volume on the data is 0.8f and the volume of the AtomExPlayer is 0.5f, + * the volume actually applied is 0.4f.
+ *
+ * If you want to set it in decibel, convert it with the following formula before setting it.
+ * volume = Math.Pow(10.0f, db_vol / 20.0f); + * + * ※db_volがデシベル値、volumeがボリューム値です。 + *
+ * When specifying a volume larger than 1.0f, note the followings:
+ * - Behavior may differ depending on the platform. + * - Clipping sound may be heard. + * . + *
+ * Even if a volume value exceeding 1.0f is set in this function, + * whether the sound is played back at a volume higher than the original waveform data + * depends on the platform and the sound compression codec type.
+ * Therefore, it is recommended that you do not use volume values higher than 1.0f + * when adjusting volume for multi-platform titles.
+ * (If you specify a volume value higher than 1.0f, the sound may be played back at a different volume + * depending on the model even if the same waveform data is played back.)
+ *
+ * Even on models in which volume can be raised, + * there is a limit to the volume that can be output by hardware, + * so noise may occur due to clicking sound.
+ *
+ * + * : + * // プレーヤの作成 + * CriAtomExPlayer player = new CriAtomExPlayer(); + * : + * // ボリュームの設定 + * player.SetVolume(0.5f); + * + * // 再生の開始 + * // 備考)ボリュームはプレーヤに設定された値(=0.5f)で再生される。 + * CriAtomExPlayback playback = player.Start(); + * : + * // ボリュームの変更 + * // 注意)この時点では再生中の音声のボリュームは変更されない。 + * player.SetVolume(0.3f); + * + * // プレーヤに設定されたボリュームを再生中の音声にも反映 + * player.Update(playback); + * : + * + * + * + * + */ + public void SetVolume(float volume) + { + criAtomExPlayer_SetVolume(this.handle, volume); + } + + /** + * Sets the pitch + * Pitch (in cents) + * + * Specifies the pitch of the output sound.
+ * After setting the pitch using this function, when you start the playback + * using the CriWare.CriAtomExPlayer::Start function, the sound is played with the specified pitch.
+ * It is possible to update the pitch of the sound already played by calling + * the CriWare.CriAtomExPlayer::Update or CriWare.CriAtomExPlayer::UpdateAll function after setting the pitch.
+ *
+ * The pitch is specified in cents.
+ * One cent is 1/1200 of one octave. A semitone is 100 cents.
+ * For example, if you specify 100.0f, the pitch increases by a semitone. If you specify -100.0f, + * the pitch decreases by a semitone.
+ * The default pitch is 0.0f.
+ * When playing a Cue, if this function is called when the pitch is set on the data, + * the value set on the data and the setting in this function is added and the result is applied.
+ * For example, if the pitch on the data is -100.0f and the pitch of the AtomExPlayer is 200.0f, + * the actual pitch applied is 100.0f. + *
+ * If you want to set the frequency ratio of the sampling rate, convert it with the following formula before setting it.
+ * pitch = 1200.0 * Math.Log(freq_ratio, 2.0); + * + * ※freq_ratioが周波数比率、pitchがピッチの値です。 + *
+ * The pitch of the sound data encoded for HCA-MX cannot be changed.
+ * (The pitch does not change even if you call this function.)
+ * For the sound whose pitch you want to change, encode it with a different codec such as ADX or HCA.
+ *
+ * The maximum pitch that can be set depends on the sampling rate of the sound data and the maximum sampling rate of the Voice Pool.
+ * For example, if the sampling rate of the sound data is 24kHz and the maximum sampling rate of the Voice Pool is 48kHz, + * the maximum pitch that can be set is 1200(double frequency ratio).
+ *
+ * Since the pitch is implemented by increasing or decreasing the playback sampling rate, + * changing the pitch also changes the playback speed along with the pitch.
+ *
+ * + * : + * // プレーヤの作成 + * CriAtomExPlayer player = new CriAtomExPlayer(); + * : + * // ピッチの設定 + * player.SetPitch(100.0f); + * + * // 再生の開始 + * // 備考)ピッチはプレーヤに設定された値(=100セント)で再生される。 + * CriAtomExPlayback playback = player.Start(); + * : + * // ピッチの変更 + * // 注意)この時点では再生中の音声のピッチは変更されない。 + * player.SetPitch(-200.0f); + * + * // プレーヤに設定されたピッチを再生中の音声にも反映 + * player.Update(playback); + * : + * + * + * + * + */ + public void SetPitch(float pitch) + { + criAtomExPlayer_SetPitch(this.handle, pitch); + } + + /** + * Sequence playback ratio setting + * Sequence playback ratio + * + * Sets the playback ratio of the player's playing sequence.
+ * Playback ratio can be set between 0.0f ~ 2.0f.
+ * If the input value is outside the range, the lower or upper limit will be set.
+ * After specifying playback ratio with this function, start with CriWare.CriAtomExPlayer::Start + * to play back at the specified ratio. + * If you want to change the playback ratio during the playback, + * please call CriWare.CriAtomExPlayer::Update or CriWare.CriAtomExPlayer::UpdateAll function.
+ * The value set by this function is applied only when playing a sequence type Cue.
+ * It cannot be used for the playback ratio of waveform data in a sequence.
+ * If you want to change the playback ratio of waveform, use the time stretch function.
+ *
+ * + * + */ + public void SetPlaybackRatio(float ratio) + { + criAtomExPlayer_SetPlaybackRatio(this.handle, ratio); + } + + /** + * Sets the Panning 3D angle + * Panning 3D angle (-180.0f to 180.0f: in degrees) + * + * Specifies the Panning 3D angle.
+ * After setting the Panning 3D angle using this function, when you start the playback using the CriWare.CriAtomExPlayer::Start function, + * the sound is played back using the specified Panning 3D angle.
+ * In addition, by calling the CriWare.CriAtomExPlayer::Update and CriWare.CriAtomExPlayer::UpdateAll functions after setting, + * you can update the Panning 3D angle of the sound already played.
+ *
+ * The angle is specified in degrees.
+ * With front being 0 degree, you can set up to 180.0f in the right direction (clockwise) and -180.0f in the left direction (counterclockwise).
+ * For example, if you specify 45.0f, the localization will be 45 degrees to the front right. If you specify -45.0f, the localization will be 45 degree to the front left.
+ * When playing a Cue, if this function is called when the Panning 3D angle is set on the data, + * the value set on the data and the setting in this function is added and the result is applied.
+ * For example, if the Panning 3D angle on the data is 15.0f and the Panning 3D angle on the AtomExPlayer is 30.0f, + * the actual Panning 3D angle applied will be 45.0f. + *
+ * If the actual applied Panning 3D angle exceeds 180.0f, -360.0f is added to the value so that it is within the range.
+ * Similarly, if the actual applied volume value is less than -180.0f, +360.0f is add so that it is within the range.
+ * (Since the localization does not change even when +360.0f, or -360.0f is added, you can effectively set a value outside the range of -180.0f to 180.0f.)
+ *
+ * + * : + * // プレーヤの作成 + * CriAtomExPlayer player = new CriAtomExPlayer(); + * : + * // パンニング3D角度の設定 + * player.SetPan3dAngle(45.0f); + * + * // 再生の開始 + * // 備考)パンニング3D角度はプレーヤに設定された値(=45.0f)で再生される。 + * CriAtomExPlayback playback = player.Start(); + * : + * // パンニング3D角度の変更 + * // 注意)この時点では再生中の音声のパンニング3D角度は変更されない。 + * player.SetPan3dAngle(-45.0f); + * + * // プレーヤに設定されたパンニング3D角度を再生中の音声にも反映 + * player.Update(playback); + * : + * + * + * + * + */ + public void SetPan3dAngle(float angle) + { + criAtomExPlayer_SetPan3dAngle(this.handle, angle); + } + + /** + * Sets the Panning 3D distance + * Panning 3D distance (-1.0f to 1.0f) + * + * Specifies the distance for doing interior Panning in Panning 3D.
+ * After setting the Panning 3D distance using this function, when you start the playback using the CriWare.CriAtomExPlayer::Start function, + * the sound is played back using the specified Panning 3D distance.
+ * In addition, by calling the CriWare.CriAtomExPlayer::Update and CriWare.CriAtomExPlayer::UpdateAll functions after setting, + * you can update the Panning 3D distance of the sound already played.
+ *
+ * The distance is specified in the range of -1.0f to 1.0f, with the listener position being 0.0f and the circumference of the speaker position being 1.0f.
+ * If you specify a negative value, the Panning 3D angle inverts 180 degrees and the localization is reversed.
+ * When playing a Cue, if this function is called when the Panning 3D distance is set on the data, + * the value set on the data and the setting in this function is multiplied and the result is applied.
+ * For example, if the Panning 3D distance on the data is 0.8f and the Panning 3D distance on the AtomExPlayer is 0.5f, + * the actual Panning 3D distance applied will be 0.4f. + *
+ * If the actual applied Panning 3D distance exceeds 1.0f, the value is clipped to 1.0f.
+ * Similarly, if the actual applied Panning 3D distance is smaller than -1.0f, the value is clipped to -1.0f.
+ *
+ * + * : + * // プレーヤの作成 + * CriAtomExPlayer player = new CriAtomExPlayer(); + * : + * // パンニング3D距離の設定 + * player.SetPan3dInteriorDistance(0.5f); + * + * // 再生の開始 + * // 備考)パンニング3D距離はプレーヤに設定された値(=0.5f)で再生される。 + * CriAtomExPlayback playback = player.Start(); + * : + * // パンニング3D距離の変更 + * // 注意)この時点では再生中の音声のパンニング3D距離は変更されない。 + * // 備考)以下の処理はパン3D角度を180度反転するのと等価 + * player.SetPan3dInteriorDistance(-0.5f); + * + * // プレーヤに設定されたパンニング3D距離を再生中の音声にも反映 + * player.Update(playback); + * : + * + * + * + * + */ + public void SetPan3dInteriorDistance(float distance) + { + criAtomExPlayer_SetPan3dInteriorDistance(this.handle, distance); + } + + /** + * Sets the Panning 3D volume + * Panning 3D volume (0.0f to 1.0f) + * + * Specifies the volume of the Panning 3D.
+ * After setting the Panning 3D volume using this function, when you start the playback using the CriWare.CriAtomExPlayer::Start function, + * the sound is played back using the specified Panning 3D volume.
+ * In addition, by calling the CriWare.CriAtomExPlayer::Update and CriWare.CriAtomExPlayer::UpdateAll functions after setting, + * you can update the Panning 3D volume of the sound already played.
+ *
+ * The Panning 3D volume is used when controlling the + * Panning 3D component and the output level to the center/LFE separately.
+ * For example, when outputting a sound from LFE using the send level at a fixed volume, + * and Panning is controlled by Panning 3D. + *
+ * The range and handling of the value are the same as for normal volume. Refer to the CriWare.CriAtomExPlayer::SetVolume function.
+ *
+ * + * : + * // プレーヤの作成 + * CriAtomExPlayer player = new CriAtomExPlayer(); + * : + * // パンニング3Dボリュームの設定 + * player.SetPan3dVolume(0.8f); + * + * // 再生の開始 + * // 備考)パンニング3Dボリュームはプレーヤに設定された値(=0.5f)で再生される。 + * CriAtomExPlayback playback = player.Start(); + * : + * // パンニング3Dボリュームの変更 + * // 注意)この時点では再生中の音声のパンニング3Dボリュームは変更されない。 + * player.SetPan3dVolume(0.7f); + * + * // プレーヤに設定されたパンニング3Dボリュームを再生中の音声にも反映 + * player.Update(playback); + * : + * + * + * + * + * + */ + public void SetPan3dVolume(float volume) + { + criAtomExPlayer_SetPan3dVolume(this.handle, volume); + } + + /** + * Sets the Panning type + * Panning type + * + * Specifies Panning type.
+ * After setting the Panning type using this function, when you start the playback using the CriWare.CriAtomExPlayer::Start function, + * the sound is played back using the specified Panning type.
+ * In addition, by calling the CriWare.CriAtomExPlayer::Update and CriWare.CriAtomExPlayer::UpdateAll functions after setting, + * you can update the Panning type of the sound already played.
+ * When playing a Cue, if this function is called, the Panning type set on the + * data is overridden (the setting on the data is ignored).
+ * Normally, it is not necessary to call this function because the Panning type is set on the data.
+ * To enable 3D Positioning when playing back sound without using an ACB file, + * set Pos3d using this function. + *
+ * An Error will occur if CriAtomEx.PanType.Unknown is specified when executing.
+ *
+ * + * + * + * + */ + public void SetPanType(CriAtomEx.PanType panType) + { + criAtomExPlayer_SetPanType(this.handle, panType); + } + + /** + * Sets the send level + * Channel number + * Speaker ID + * Send level value (0.0f to 1.0f) + * + * Specifies the send level.
+ * The send level is a mechanism for specifying which speaker outputs + * the sound of each channel of the sound data at which volume.
+ * After setting the send level using this function, when you start the playback using the CriWare.CriAtomExPlayer::Start function, + * the sound is played back using the specified send level.
+ * In addition, by calling the CriWare.CriAtomExPlayer::Update and CriWare.CriAtomExPlayer::UpdateAll functions after setting, + * you can update the send level of the sound already played.
+ *
+ * The first argument, the channel number, specifies the "channel number of the sound data".
+ * The second argument, the speaker ID, specifies which speaker outputs the data of the specified channel number, + * and the third argument specifies the level (volume) when sending data.
+ * For example, if you want to output the sound data of channel 0 from + * the right speaker with full volume (1.0f), specify as follows: + * player.SetSendLevel(0, CriAtomEx.Speaker.FrontRight, 1.0f); + * + *
+ * センドレベル値の範囲や扱いは、ボリュームと同等です。 CriWare.CriAtomExPlayer::SetVolume 関数を参照してください。
+ *
+ *
+ * There are two types of send level settings: "automatic setting" and "manual setting".
+ * Immediately after creating the AtomExPlayer, or when + * the parameters are cleared using the CriWare.CriAtomExPlayer::ResetParameters function, the send level setting becomes "automatic setting".
+ * But when this function is called, the send level setting becomes "manual setting".
+ * (The user must control the send level to each speaker and perform Panning.)
+ *
+ * In the "automatic setting", the AtomExPlayer routes sound as follows:
+ *
+ * [When playing mono sound]
+ * The sound from channel 0 is output from the left and right speakers at the volume of about 0.7f (-3dB).
+ *
+ * [When playing stereo sound]
+ * The sound from channel 0 is output from the left speaker, + * and the sound from channel 1 is output from the right speaker.
+ *
+ * [When playing 4ch sound]
+ * The sound from channel 0 is output from the left speaker, the sound from channel 1 is output from the right speaker, + * the sound from channel 2 is output from the surround left speaker, + * and the sound from channel 3 is output from the surround right speaker.
+ *
+ * [When playing 5.1ch sound]
+ * The sound from channel 0 is output from the left speaker, the sound from channel 1 is output from the right speaker, + * the sound from channel 2 is output from the center speaker, the sound from channel 3 is output from LFE, + * the sound from channel 4 is output from the surround left speaker, + * and the sound from channel 5 is output from the surround right speaker.
+ *
+ * [When playing 7.1ch sound]
+ * The sound from channel 0 is output from the left speaker, the sound from channel 1 is output from the right speaker, + * the sound from channel 2 is output from the center speaker, the sound from channel 3 is output from LFE, + * the sound from channel 4 is output from the surround left speaker, + * and the sound from channel 5 is output from the surround right speaker.
+ * The sound from channel 6 is output from the surround back left speaker, + * and the sound from channel 7 is output from the surround back right speaker.
+ *
+ * On the other hand, when "manual setting" is selected using this function, the sound is output + * with the specified send level setting regardless of the number of channels in the sound data.
+ * (It is necessary to switch the send level setting appropriately according to the number of channels in the sound data.)
+ *
+ * If you want to clear the send level specified previously and return to the "automatic setting" routing, + * call the CriWare.CriAtomExPlayer::ResetParameters function.
+ *
+ * This parameter cannot be set on the data, so the setting in this function is always applied.
+ * Sound is not output for channels for which the send level is not set.
+ * For example, if the sound data to be played is stereo, but the send level is set + * only for one of the channels, the sound of the channel for which the send level + * is not set is muted.
+ * When controlling the send level, be sure to set the send level for all channels + * you want to output.
+ *
+ * + * CriSint32 ch = 0; // channel number 0 + * CriAtomEx.Speaker spk = CriAtomEx.Speaker.FrontCenter; + * CriFloat32 level = 1.0f; + * // Set send level(ch0 to center) + * player.SetSendLevel(ch, spk, level); + * // Start playback + * CriAtomExPlayback playback = player.Start(); + * : + * // Change send level + * level = 0.7f; + * player.SetSendLevel(ch, spk, level); + * player.Update(playback); + * + * + * + * + * + */ + public void SetSendLevel(int channel, CriAtomEx.Speaker id, float level) + { + criAtomExPlayer_SetSendLevel(this.handle, channel, id, level); + } + + /** + * Sets the parameters of the Biquad Filter + * Filter type + * Normalized frequency (0.0f to 1.0f) + * Gain (decibels) + * Q value + * + * Specifies various parameters of the Biquad Filter.
+ * After setting the parameters using this function, when you start the playback using the CriWare.CriAtomExPlayer::Start function, + * the Biquad Filter is activated using the specified parameters.
+ * In addition, by calling the CriWare.CriAtomExPlayer::Update and CriWare.CriAtomExPlayer::UpdateAll functions after setting, + * you can update the Biquad Filter parameters for the sound already played.
+ *
+ * The normalized frequency is a value obtained by normalizing 24Hz to 24000Hz on the logarithmic axis to 0.0f to 1.0f.
+ * The gain is specified in decibels.
+ * Gain is valid only when the filter type is either of the following types.
+ * - LowShelf : Low shelf filter + * - HighShelf : High shelf filter + * - Peaking : Peaking filter + * .
+ * - type
+ * Overwrites the value set in the data. + * - frequency
+ * Added to the value set in the data. + * - gain
+ * The value set in the data is multiplied. + * - q
+ * Added to the value set in the data. + * . + *
+ * If the normalization cutoff frequency which is actually applied exceeds 1.0f, the value is clipped to 1.0f.
+ * Similarly, if the normalization cutoff frequency actually applied is less than 0.0f, the value is clipped to 0.0f.
+ * The Biquad Filter is not applied to the sound data encoded for HCA-MX.
+ * If you want to use the Biquad Filter for a sound, encode it with a different codec such as ADX or HCA.
+ *
+ * + * : + * // プレーヤの作成 + * CriAtomExPlayer player = new CriAtomExPlayer(); + * : + * // フィルタのパラメータを設定 + * CriAtomEx.BiquadFilterType type = CriAtomEx.BiquadFilterType.LowPass; + * float frequency = 0.5f; + * float gain = 1.0f; + * float q = 3.0f; + * player.SetBiquadFilterParameters(type, frequency, gain, q); + * + * // 再生の開始 + * CriAtomExPlayback playback = player.Start(); + * : + * // パラメータの変更 + * // 注意)この時点では再生中の音声のパラメータは変更されない。 + * frequency = 0.7f; + * player.SetBiquadFilterParameters(type, frequency, gain, q); + * + * // プレーヤに設定されたパラメータを再生中の音声にも反映 + * player.Update(playback); + * : + * + * + * + * + */ + public void SetBiquadFilterParameters( + CriAtomEx.BiquadFilterType type, float frequency, float gain, float q) + { + criAtomExPlayer_SetBiquadFilterParameters(this.handle, type, frequency, gain, q); + } + + /** + * Sets BandPass Filter parameters + * Normalized low frequency cutoff frequency (0.0f to 1.0f) + * Normalized high frequency cutoff frequency (0.0f to 1.0f) + * + * Specifies the cutoff frequency of the BandPass Filter.
+ * After setting the cutoff frequency using this function, when you start the playback using the CriWare.CriAtomExPlayer::Start function, + * the BandPass Filter is activated using the specified cutoff frequency.
+ * In addition, by calling the CriWare.CriAtomExPlayer::Update and CriWare.CriAtomExPlayer::UpdateAll functions after setting, + * you can update the cutoff frequency of the BandPass Filter for the sound already played.
+ *
+ * The normalized cutoff frequency is a value obtained by normalizing 24Hz to 24000Hz on the logarithmic axis to 0.0f to 1.0f.
+ * For example, if the normalized low cutoff frequency is specified as 0.0f and the normalized high cutoff frequency as 1.0f, + * the BandPass Filter will pass the entire range, and the higher the normalized low cutoff frequency, + * or the lower the normalized high cutoff frequency, the narrower the passband.
+ * When playing a Cue, if the function is called when the bandpass filter parameter is set on the data, + * the settings will be as follows. + * - cofLow
+ * The value set on the data is multiplied after calculating "cofLowRev = 1.0f - cofLow", + * and the result of calculating "cofLow = 1.0f - cofLowRev" is applied.
+ * In other words, 0.0f is considered as "the filter is opened most to the low frequency side", and the degree of opening is multiplied and applied. + * - cofHigh
+ * The value set in the data is multiplied and applied.
+ * In other words, 1.0f is considered as "the filter is opened most to the high frequency side", and the degree of opening is multiplied and applied. + * . + *
+ * If the normalization cutoff frequency which is actually applied exceeds 1.0f, the value is clipped to 1.0f.
+ * Similarly, if the normalization cutoff frequency actually applied is less than 0.0f, the value is clipped to 0.0f.
+ *
+ * + * : + * // プレーヤの作成 + * CriAtomExPlayer player = new CriAtomExPlayer(); + * : + * // フィルタのパラメータを設定 + * float cof_low = 0.0f; + * float cof_high = 0.3f; + * player.SetBandpassFilterParameter(cof_low, cof_high); + * + * // 再生の開始 + * CriAtomExPlayback playback = player.Start(); + * : + * // パラメータの変更 + * // 注意)この時点では再生中の音声のパラメータは変更されない。 + * cof_low = 0.7f; + * cof_high = 1.0f; + * player.SetBandpassFilterParameter(cof_low, cof_high); + * + * // プレーヤに設定されたパラメータを再生中の音声にも反映 + * player.Update(playback); + * : + * + * + * + * + */ + public void SetBandpassFilterParameters(float cofLow, float cofHigh) + { + criAtomExPlayer_SetBandpassFilterParameters(this.handle, cofLow, cofHigh); + } + + /** + * Sets the Bus Send Level (bus name specified) + * Bus name + * Send level value (0.0f to 1.0f) + * + * Specifies the Bus Send Level.
+ * The Bus Send Level is a mechanism for specifying how much sound should be sent to which bus.
+ * After setting the Bus Send Level using this function, when you start the playback using the CriWare.CriAtomExPlayer::Start function, + * the sound is played back using the specified Bus Send Level.
+ * In addition, by calling the CriWare.CriAtomExPlayer::Update and CriWare.CriAtomExPlayer::UpdateAll functions after setting, + * you can update the Bus Send Level of the sound already played.
+ *
+ * The first argument, the bus ID, specifies the "channel number of the sound data".
+ * The third argument specifies the level (volume) when sending.
+ *
+ * The range and handling of the send level values are the same as for volume. Refer to CriWare.CriAtomExPlayer::SetVolume function.
+ * By calling this function multiple times, you can send sound to multiple buses.
+ *
+ * + * : + * // プレーヤの作成 + * CriAtomExPlayer player = new CriAtomExPlayer(); + * : + * // バスセンドレベルを設定 + * int bus_id = 1; // ex. reverb, etc... + * float level = 0.3f; + * player.SetBusSendLevel(bus_id, level); + * + * // 再生の開始 + * CriAtomExPlayback playback = player.Start(); + * : + * // パラメータの変更 + * // 注意)この時点では再生中の音声のパラメータは変更されない。 + * level = 0.5f; + * player.SetBusSendLevel(bus_id, level); + * + * // プレーヤに設定されたパラメータを再生中の音声にも反映 + * player.Update(playback); + * : + * + * + * + * + * + */ + public void SetBusSendLevel(string busName, float level) + { + criAtomExPlayer_SetBusSendLevelByName(this.handle, busName, level); + } + + /** + * Obtaining the bus send level (specifying the bus name) + * Bus name + * Send level value (0.0f to 1.0f) + * Whether obtained or not (Obtained: TRUE / Unable to obtain: FALSE) + * + * Gets the specific bus send level set for the player.
+ * In the following cases, the acquisition of the bus send level will fail.
+ * - A bus with the specified name does not exist in the current DSP bus configuration. + * - The send level has not been set for the bus specified by the player.
+ *
+ * + */ + public bool GetBusSendLevel(string busName, out float level) + { + return criAtomExPlayer_GetBusSendLevelByName(this.handle, busName, out level); + } + + /** + * \deprecated + * This is a deprecated API that will be removed. + * Please consider using CriAtomExPlayer.SetBusSendLevel(string busName, float level) instead. + */ + [System.Obsolete("Use CriAtomExPlayer.SetBusSendLevel(string busName, float level)")] + public void SetBusSendLevel(int busId, float level) + { + criAtomExPlayer_SetBusSendLevel(this.handle, busId, level); + } + + + /** + * Sets the Bus Send Level by offset (bus name specified) + * Bus name + * Send level value (0.0f to 1.0f) + * + * Specifies the Bus Send Level as an offset.
+ * When playing a Cue, if this function is called when the Bus Send Level is set on the data, + * the value set on the data and the setting in this function is added and the result is applied.
+ * Other specifications are the same as the CriWare.CriAtomExPlayer::SetBusSendLevel function.
+ * By calling the CriWare.CriAtomExPlayer::SetBusSendLevel function with a level of 0.0f and setting an offset value with this function,
+ * it is possible to set an arbitrary value (the offset value) as the send level, ignoring the value specified on the data side. (Overwrite setting)
+ *
+ * + */ + public void SetBusSendLevelOffset(string busName, float levelOffset) + { + criAtomExPlayer_SetBusSendLevelOffsetByName(this.handle, busName, levelOffset); + } + + /** + * Obtaining the offset of the bus send level (specifying the bus name) + * Bus name + * Send level offset value (0.0f to 1.0f) + * Whether obtained or not (Obtained: TRUE / Unable to obtain: FALSE) + * + * Gets the offset for a particular bus send level set on the player.
+ * In the following cases, the acquisition of the bus send level will fail.
+ * - A bus with the specified name does not exist in the current DSP bus configuration. + * - The send level has not been set for the bus specified by the player.
+ *
+ * + */ + public bool GetBusSendLevelOffset(string busName, out float level) + { + return criAtomExPlayer_GetBusSendLevelOffsetByName(this.handle, busName, out level); + } + + /** + * \deprecated + * This is a deprecated API that will be removed. + * Please consider using CriAtomExPlayer.SetBusSendLevelOffset(int busId, float levelOffset) instead. + */ + [System.Obsolete("Use CriAtomExPlayer.SetBusSendLevelOffset(int busId, float levelOffset)")] + public void SetBusSendLevelOffset(int busId, float levelOffset) + { + criAtomExPlayer_SetBusSendLevelOffset(this.handle, busId, levelOffset); + } + + /** + * Attaches AISAC to the player + * Global AISAC name to attach + * + * Attaches AISAC to the player. + * By attaching AISAC, you can get AISAC effect even if you didn't set AISAC for the Cue or the Track.
+ * After the AISAC is attached using this function, when the playback is started using the CriWare.CriAtomExPlayer::Start function , + * various parameters are applied considering the attached AISAC.
+ * After attachment, by calling the CriWare.CriAtomExPlayer::Update or CriWare.CriAtomExPlayer::UpdateAll function, + * you can apply various parameter settings by the attached AISAC to the sound already played.
+ * Only the global ACF included in the global settings (AISAC file) can be attached.
+ * To get the effect of AISAC , it is necessary to set the appropriate AISAC control value + * in the same way as the AISAC set for Cues or Tracks. + *
+ * This parameter is cleared using the CriWare.CriAtomExPlayer::ResetParameters function.
+ * Even if "an AISAC to change AISAC control value" is set for the Cue or Track, + * the applied AISAC control value does not affect the AISAC attached to the player. + * Currently, it does not support the AISAC attachment of control type "Automodulation" or "Random".
+ * Currently, the maximum number of AISACs that can be attached to a player is fixed to 8.
+ *
+ */ + public void AttachAisac(string globalAisacName) + { + criAtomExPlayer_AttachAisac(this.handle, globalAisacName); + } + + /** + * Separates AISAC from the player + * Global AISAC name to detach + * + * Detach (separate) AISAC from the player.
+ * After detaching AISAC using this function, when you start the playback using + * the CriWare.CriAtomExPlayer::Start function, the detached AISAC has no effect.
+ * After detachment, by calling the CriWare.CriAtomExPlayer::Update or CriWare.CriAtomExPlayer::UpdateAll function, + * the detached AISAC has no effect on the sound already played.
+ *
+ */ + public void DetachAisac(string globalAisacName) + { + criAtomExPlayer_DetachAisac(this.handle, globalAisacName); + } + + + /** + * Sets the AISAC control value (specifying the control name) + * Control name + * Control value (0.0f to 1.0f) + * + * Specifies the AISAC control value by specifying the control name.
+ * Up to eight AISAC control values can be set for one player.
+ * After setting the AISAC control value using this function, when you start the playback using the CriWare.CriAtomExPlayer::Start function, + * the sound is played back using the specified AISAC control value.
+ * In addition, by calling the CriWare.CriAtomExPlayer::Update and CriWare.CriAtomExPlayer::UpdateAll functions after setting, + * you can update the AISAC control value of the sound already played.
+ *
+ * The AISAC control value is handled in the same way as in the CriWare.CriAtomExPlayer::SetAisacControl function.
+ *
+ * + * : + * // プレーヤの作成 + * CriAtomExPlayer player = new CriAtomExPlayer(); + * : + * // AISACコントロール値の設定 + * float control_value = 0.5f; + * player.SetAisacControl("Any", control_value); + * + * // 再生の開始 + * CriAtomExPlayback playback = player.Start(); + * : + * // パラメータの変更 + * // 注意)この時点では再生中の音声のパラメータは変更されない。 + * control_value = 0.3f; + * player.SetAisacControl("Any", control_value); + * + * // プレーヤに設定されたパラメータを再生中の音声にも反映 + * player.Update(playback); + * : + * + * + * + * + * + */ + public void SetAisacControl(string controlName, float value) + { + criAtomExPlayer_SetAisacControlByName(this.handle, controlName, value); + } + + /** + * \deprecated + * This is a deprecated API that will be removed. + * Please consider using CriAtomExPlayer.SetAisacControl instead. + */ + [System.Obsolete("Use CriAtomExPlayer.SetAisacControl")] + public void SetAisac(string controlName, float value) + { + SetAisacControl(controlName, value); + } + + /** + * Sets the AISAC control value (specifying the control ID) + * Control ID + * Control value (0.0f to 1.0f) + * + * Specifies the AISAC control value by specifying the control ID.
+ * Up to eight AISAC control values can be set for one player.
+ * After setting the AISAC control value using this function, when you start the playback using the CriWare.CriAtomExPlayer::Start function, + * the sound is played back using the specified AISAC control value.
+ * In addition, by calling the CriWare.CriAtomExPlayer::Update and CriWare.CriAtomExPlayer::UpdateAll functions after setting, + * you can update the AISAC control value of the sound already played.
+ *
+ * Specify a real value in the range of 0.0f to 1.0f for the AISAC control value.
+ * The behavior changes as follows depending on the control type of AISAC. + * - Off + * - If the AISAC control value is not set using this function, the AISAC is not activated. + * . + * - Automatic modulation + * - The AISAC control value changes automatically over time without being affected by the setting in this function. + * . + * - Random + * - With the AISAC control value set by this function etc. as the median value, + * the final AISAC control value is determined by randomizing it with the random width set to the data. + * - The randomization is done only by applying parameters when starting playback, + * and the AISAC control value cannot be changed for the sound being played. + * - If the AISAC control value is not set when starting playback, + * randomization is done using 0.0f as the median value. + * . + * . + *
+ * + * : + * // プレーヤの作成 + * CriAtomExPlayer player = new CriAtomExPlayer(); + * : + * // AISACコントロール値の設定 + * CriAtomExAisacControlId control_id = 0; + * float control_value = 0.5f; + * player.SetAisacControl(control_id, control_value); + * + * // 再生の開始 + * CriAtomExPlayback playback = player.Start(); + * : + * // パラメータの変更 + * // 注意)この時点では再生中の音声のパラメータは変更されない。 + * control_value = 0.3f; + * player.SetAisacControl(control_id, control_value); + * + * // プレーヤに設定されたパラメータを再生中の音声にも反映 + * player.Update(playback); + * : + * + * + * + * + * + */ + public void SetAisacControl(uint controlId, float value) + { + criAtomExPlayer_SetAisacControlById(this.handle, (ushort)controlId, value); + } + + /** + * \deprecated + * This is a deprecated API that will be removed. + * Please consider using CriAtomExPlayer.SetAisacControl instead. + */ + [System.Obsolete("Use SetAisacControl")] + public void SetAisac(uint controlId, float value) + { + criAtomExPlayer_SetAisacControlById(this.handle, (ushort)controlId, value); + } + + /** + * Gets information on AISAC attached to the player + * Index of the attached AISAC + * A structure for getting the AISAC information + * + * Gets information on AISAC attached to the player.
+ * Returns False if you specify an invalid index.
+ *
+ */ + public bool GetAttachedAisacInfo(int aisacAttachedIndex, out CriAtomEx.AisacInfo aisacInfo) + { + using (var mem = new CriStructMemory()) { + bool result = criAtomExPlayer_GetAttachedAisacInfo(this.handle, aisacAttachedIndex, mem.ptr); + if (result) { + aisacInfo = new CriAtomEx.AisacInfo(mem.bytes, 0); + } else { + aisacInfo = new CriAtomEx.AisacInfo(); + } + return result; + } + } + + /** + * Sets a 3D sound source object + * CriAtomEx3dSource object + * + * Set the 3D sound source object to realize the 3D Positioning.
+ * By setting the 3D listener object and the 3D sound source object, + * localization, volume, pitch, etc. are automatically applied based on the positional relationship between the 3D listener object and 3D sound source object.
+ * After setting the 3D sound source object using this function, if you start playback using the CriWare.CriAtomExPlayer::Start function, + * the 3D sound source object that has been set will be referenced for playback.
+ * In addition, by calling the CriWare.CriAtomExPlayer::Update and CriWare.CriAtomExPlayer::UpdateAll functions after setting, + * you can change the 3D sound source object referenced by the already played sound.
+ * If source is set to null, the 3D sound source object already set is cleared.
+ * To change or update the parameters of the 3D sound source object, use the functions of the 3D sound source object + * instead of the functions of the AtomExPlayer.
+ * By default, 3D Positioning calculations are done in the left-handed coordinate system.
+ *
+ *
+ * + * : + * // リスナの作成 + * CriAtomEx3dListener listener = new CriAtomEx3dListener(); + * + * // ソースの作成 + * CriAtomEx3dSource source = new CriAtomEx3dSource(); + * + * // プレーヤの作成 + * CriAtomExPlayer player = new CriAtomExPlayer(); + * + * // ソース、リスナをプレーヤに設定 + * player.Set3dListener(listener); + * player.Set3dSource(source); + * : + * // 音源の位置を初期化 + * source.SetPosition(0.0f, 0.0f, 0.0f); + * source.Update(); + * : + * // 再生の開始 + * CriAtomExPlayback playback = player.Start(); + * : + * // 音源の位置を変更 + * source.SetPosition(10.0f, 0.0f, 0.0f); + * source.Update(); + * : + * + * + * + * + */ + public void Set3dSource(CriAtomEx3dSource source) + { + criAtomExPlayer_Set3dSourceHn(this.handle, (source == null) ? IntPtr.Zero : source.nativeHandle); + } + + /** + * Sets the 3D listener object + * 3D listener object + * + * Sets the 3D listener object for realizing the 3D Positioning.
+ * By setting the 3D listener object and the 3D sound source object, + * localization, volume, pitch, etc. are automatically applied based on the positional relationship between the 3D listener and 3D sound source.
+ * After setting the 3D listener object using this function, if you start playback using the CriWare.CriAtomExPlayer::Start function, + * the 3D listener object that has been set will be referenced for playback.
+ * In addition, by calling the CriWare.CriAtomExPlayer::Update and CriWare.CriAtomExPlayer::UpdateAll functions after setting, + * you can change the 3D listener object referenced by the already played sound.
+ * If listener is set to null, the 3D listener object already set is cleared.
+ * To change or update the parameters of the 3D listener object, use the functions of the 3D listener object + * instead of the functions of the AtomExPlayer.
+ * By default, 3D Positioning calculations are done in the left-handed coordinate system.
+ *
+ *
+ * + * : + * // リスナの作成 + * CriAtomEx3dListener listener = new CriAtomEx3dListener(); + * + * // ソースの作成 + * CriAtomEx3dSource source = new CriAtomEx3dSource(); + * + * // プレーヤの作成 + * CriAtomExPlayer player = new CriAtomExPlayer(); + * + * // ソース、リスナをプレーヤに設定 + * player.Set3dListener(listener); + * player.Set3dSource(source); + * : + * // 音源の位置を初期化 + * source.SetPosition(0.0f, 0.0f, 0.0f); + * source.Update(); + * : + * // 再生の開始 + * CriAtomExPlayback playback = player.Start(); + * : + * // リスナの位置を変更 + * listener.SetPosition(-10.0f, 0.0f, 0.0f); + * listener.Update(); + * : + * + * + * + * + */ + public void Set3dListener(CriAtomEx3dListener listener) + { + criAtomExPlayer_Set3dListenerHn(this.handle, ((listener == null) ? IntPtr.Zero : listener.nativeHandle)); + } + + /** + * Specifies the playback start position + * Playback start position (in milliseconds) + * + * Specifies the position to start playing the sound played by the AtomExPlayer.
+ * If you want to play the sound data from the middle, you need to specify the playback start position + * using this function before starting playback.
+ *
+ * The playback start position is specified in milliseconds.
+ * For example, if you set start_time_ms to 10000 and call this function, + * the sound data to be played next will be played from the position of 10 seconds.
+ * When playing a sound from the middle of the data, the play timing delays + * compared to when playing it from the beginning.
+ * This is because the system must analyze the header of the sound data, + * jump to the specified position, and rereads the data to start playback.
+ * A 64bit value can be set for startTimeMs, but currently it is not possible to + * specify a playback time exceeding 32bit value.
+ *
+ * The encrypted ADX data must be sequentially decrypted from the beginning of the data.
+ * Therefore, if the encrypted ADX data is played back from the middle, + * decryption must be done up to the seek position when starting playback, + * which may result in a significant load.
+ *
+ * When the Sequence is played back specifying the playback start position, + * the waveform data placed before the specified position is not played.
+ * (Individual waveforms in the Sequence are not played from the middle.)
+ *
+ */ + public void SetStartTime(long startTimeMs) + { + criAtomExPlayer_SetStartTime(this.handle, startTimeMs); + } + + /** + * Sets the playback start Block (Block index specified) + * Block index + * + * Associates the playback start Block index with the AtomExPlayer.
+ * After specifying the playback start Block index with this function, when the Block Sequence Cue + * is started using the CriWare.CriAtomExPlayer::Start function, playback starts from the specified Block.
+ * The default Block index of the AtomExPlayers is 0.
+ * If the Cue set in the player at the start of playback by the CriWare.CriAtomExPlayer::Start function + * is not a Block sequence, the value set by this function is not used.
+ * If there is no Block corresponding to the specified index, playback starts from the first Block.
+ * At this time, a warning is issued indicating that there is no Block at the specified index.
+ * Use the CriWare.CriAtomExPlayback::SetNextBlockIndex function to move Block after starting playback, + * and use the CriWare.CriAtomExPlayback::GetCurrentBlockIndex function to get the Block index during playback. + *
+ * + * : + * // プレーヤの作成 + * CriAtomExPlayer player = new CriAtomExPlayer(); + * : + * // 音声データをセット + * player.SetCue(acb, 300); + * + * // 開始ブロックをセット + * player.SetFirstBlockIndex(1); + * + * // セットされた音声データを再生 + * player.Start(); + * : + * + * + * + * + */ + public void SetFirstBlockIndex(int index) + { + criAtomExPlayer_SetFirstBlockIndex(this.handle, index); + } + + /** + * Sets the selector information + * Selector name + * Label name + * + * Assigns the Selector name and Label name to the player. Up to 8 can be assigned to each player.
+ * If a Cue that has Selector Labels assigned to its tracks is played, only the track that matches the Selector Label + * specified with this function will be played.
+ * Call CriWare.CriAtomExPlayer::UnsetSelectorLabel to unassign a specific label from the player.
+ * Call CriWare.CriAtomExPlayer::ClearSelectorLabels to unassign all labels.
+ * Call CriWare.CriAtomExPlayer::ResetParameters to remove all the player's settings, including label information.
+ *
+ * + * + * + */ + public void SetSelectorLabel(string selector, string label) + { + criAtomExPlayer_SetSelectorLabel(this.handle, selector, label); + } + + /** + * Removes the selector information that is set. + * Selector name + * + * Removes the information related to a selector name from the player, as well as any label names associated with it.
+ * After removal, you can call CriWare.CriAtomExPlayer::Update or CriWare.CriAtomExPlayer::UpdateAll , + * to also remove the selector information from voices that are already playing. However, the voices themselves will not stop.
+ *
+ * + * + */ + public void UnsetSelectorLabel(string selector) + { + criAtomExPlayer_UnsetSelectorLabel(this.handle, selector); + } + + /** + * Deletes all selector information + * + * Delete all selector name and label name information set in the player.
+ * Also, after deleting, by calling CriWare.CriAtomExPlayer::Update or CriWare.CriAtomExPlayer::UpdateAll , + * you can delete the selector information for the sound that is already being played, but the sound does not stop.
+ *
+ * + */ + public void ClearSelectorLabels() + { + criAtomExPlayer_ClearSelectorLabels(this.handle); + } + + /** + * Sets the Category (ID specified) + * Category ID + * + * Sets the Category by specifying the Category ID.
+ * To remove the configured Category information, the CriWare.CriAtomExPlayer::UnsetCategory function.
+ * When playing a Cue, if this function is called, the Category setting set on the + * data is overridden (the setting on the data is ignored).
+ * The Category information set by this function is cleared when ACF is registered and unregistered.
+ * The default Category is available when ACF is not registered.
+ * Make the Category settings before starting playback. If you update the Category settings for the sound being played, + * the playback count of the Category may be incorrect.
+ *
+ * + * + */ + public void SetCategory(int categoryId) + { + criAtomExPlayer_SetCategoryById(this.handle, (uint)categoryId); + } + + /** + * Sets Category (Category name specified) + * Category name + * + * Set the Category by specifying the Category name.
+ * To remove the configured Category information, the CriWare.CriAtomExPlayer::UnsetCategory function.
+ * The basic specification is the same as the CriWare.CriAtomExPlayer::SetCategory(int) function, except that the Category is specified by name. + *
+ * + * + */ + public void SetCategory(string categoryName) + { + criAtomExPlayer_SetCategoryByName(this.handle, categoryName); + } + + /** + * Removes Category + * + * Deletes the Category information set in the player handle.
+ *
+ * + */ + public void UnsetCategory() + { + criAtomExPlayer_UnsetCategory(this.handle); + } + + /** + * Sets the Cue priority + * Cue priority + * + * Sets the Cue priority to the AtomExPlayer.
+ * After setting the Cue priority using this function, when a sound is played using the CriWare.CriAtomExPlayer::Start function, + * the sound is played with the Cue priority set in this function.
+ * The default before calling the function is 0.
+ * When the AtomExPlayer plays a Cue, if the category to which the Cue belongs has already reached + * its Voice count limit, Voice control is done based on the priority.
+ * Specifically, if the AtomExPlayer's play request has higher priority than that of the Cue being played, + * the AtomExPlayer stops the Cue being played and starts playing the requested Cue.
+ * (The sound being played is stopped and another sound is played.)
+ * Conversely, if the AtomExPlayer's playback request is lower than the priority of the Cue currently being played, + * the AtomExPlayer's playback request is rejected.
+ * (The requested Cue will not be played.)
+ * When the playback request of the AtomExPlayer is equal to the priority of the Cue currently being played, + * the AtomExPlayer controls the Voice with the last-arrival priority.
+ *
+ * + * + */ + public void SetCuePriority(int priority) + { + criAtomExPlayer_SetCuePriority(this.handle, priority); + } + + /** + * Sets the Voice Priority + * Voice Priority (-255 to 255) + * + * Sets the Voice Priority to the AtomExPlayer.
+ * After setting the priority using this function, when a sound is played using the CriWare.CriAtomExPlayer::Start function, + * the sound is played with the priority set in this function.
+ * In addition, by calling the CriWare.CriAtomExPlayer::Update and CriWare.CriAtomExPlayer::UpdateAll functions after setting, + * you can update the priority of the sound already played.
+ *
+ * For Voice Priority, specify an integer in the range of -255 to 255.
+ * If you set a value outside the range, it will be clipped to fit the range.
+ * The default before calling the function is 0.
+ * When the AtomExPlayer tries to play waveform data, + * if the number of Voices in the Voice limit group to which the waveform data belongs has reached the upper limit, + * or if all the Voices in the Voice Pool are in use, + * the Voices are controlled based on the priority.
+ * (The Voice Priority is used to determine whether to play the specified waveform data.)
+ *
+ * Specifically, if the priority of the waveform data to be played is + * higher than that of the waveform data currently being played in the Voice, + * the AtomExPlayer steals the Voice being played and starts playing the requested waveform data.
+ * (The sound being played is stopped and another sound is played.)
+ *
+ * Conversely, if the priority of the waveform data to be played is + * lower than that of the waveform data currently being played in the Voice, + * the AtomExPlayer does not play the requested waveform data.
+ * (The requested sound is not played, and the sound being played continues to be played.)
+ *
+ * If the priority of the waveform data to be played is the same as + * that of the waveform data currently being played in the Voice, + * the AtomExPlayer performs the following control according to the + * Voice control method (first-priority or last-priority).
+ * - When in the first-priority mode, the priority is given to the waveform data being played, and the requested waveform data is not played. + * - When in the last-priority mode, the priority is given to the requested waveform data and the Voice is stolen. + * . + *
+ * When playing a Cue, if this function is called when the Voice Priority is set on the data, + * the sum of the value set on the data and the setting in this function is applied.
+ * For example, if the priority of the data is 255 and the priority of the AtomExPlayer is 45, + * the priority actually applied is 300.
+ * The range of values that can be set using this function is -255 to 255, but since the calculation inside the library + * is done within the range of int, the result of adding the values on data may exceed the range of -255 to 255.
+ * This function controls the Voice Priority set in the waveform data.
+ * Note that it does not affect the Category Cue Priority set for the Cue + * on Atom Craft.
+ *
+ * + * + * + * + */ + public void SetVoicePriority(int priority) + { + criAtomExPlayer_SetVoicePriority(this.handle, priority); + } + + /** + * Specifies the Voice control method + * Voice control method + * + * Sets the Voice control method to the AtomExPlayer.
+ * After setting the Voice control method using this function, when you play a sound using the CriWare.CriAtomExPlayer::Start function, + * the control method specified by this function is applied to the waveform data played by the player.
+ * The default before calling the function is last-priority ( PreferLast ).
+ * When the AtomExPlayer tries to play waveform data, + * if the number of Voices in the Voice limit group to which the waveform data belongs has reached the upper limit, + * or if all the Voices in the Voice Pool are in use, + * the Voices are controlled based on the Voice Priority.
+ *
+ * The Voice control method set by this function is considered in the Voice control + * when the priority of the waveform data to be played back is + * the same as that of the waveform data being played back.
+ * (For details on the Voice control by Voice Priority, + * see the Description of the CriWare.CriAtomExPlayer::SetVoicePriority function.)
+ * Currently, even if a Voice control method is specified using this function, + * the Voice control method set on the authoring tool is applied preferentially when playing a Cue.
+ *
+ * + * + * + */ + public void SetVoiceControlMethod(CriAtomEx.VoiceControlMethod method) + { + criAtomExPlayer_SetVoiceControlMethod(this.handle, method); + } + + /** + * Set the pre-delay time + * Pre-delay time (0.0f to 2000.0f) + * + * Sets the pre-delay time.
+ * After setting the pre-delay time using this function, when you start the playback using the CriWare.CriAtomExPlayer::Start function, + * the system waits for the pre-delay time before playback.
+ *
+ * For the pre-delay time, specify a real value in the range of 0.0f to 10000.0f. The unit is ms (millisecond).
+ * The default for pre-delay time is 0.0f.
+ * When playing a Cue, if this function is called when the pre-delay time is set on the data, + * the value set on the data and the setting in this function is added and the result is applied.
+ * It cannot be updated using CriWare.CriAtomExPlayer::Update or CriWare.CriAtomExPlayer::UpdateAll function during playback.
+ *
+ * Pre-delay is not applied to the sound data encoded for HCA-MX.
+ * If you want to use the envelope, encode the data using another codec such as ADX or HCA.
+ *
+ * + */ + public void SetPreDelayTime(float time) + { + criAtomExPlayer_SetPreDelayTime(this.handle, time); + } + + /** + * Sets the Envelope Attack Time + * Attack time (0.0f to 2000.0f) + * + * Sets the attack time of the envelope.
+ * After setting the attack time using this function, when you start the playback using the CriWare.CriAtomExPlayer::Start function, + * the sound is played back using the specified attack time.
+ *
+ * For the attack time, specify a real value from 0.0f to 2000.0f. The unit is ms (millisecond).
+ * The default attack time is 0.0f.
+ * When playing a Cue, if this function is called when the attack time is set on the data, + * the value set on the data is overridden (the setting on the data is ignored).
+ * It cannot be updated using CriWare.CriAtomExPlayer::Update or CriWare.CriAtomExPlayer::UpdateAll function during playback.
+ *
+ * The envelope is not applied to the sound data encoded for HCA-MX.
+ * If you want to use the envelope, encode the data using another codec such as ADX or HCA.
+ *
+ * + * : + * // プレーヤの作成 + * CriAtomExPlayer player = new CriAtomExPlayer(); + * : + * // エンベロープの設定 + * player.SetEnvelopeAttackTime(10.0f); + * + * // 再生の開始 + * CriAtomExPlayback playback = player.Start(); + * : + * + * + */ + public void SetEnvelopeAttackTime(float time) + { + criAtomExPlayer_SetEnvelopeAttackTime(this.handle, time); + } + + /** + * Sets the envelope hold time + * Hold time (0.0f to 2000.0f) + * + * Sets the hold time of the envelope.
+ * After setting the hold time using this function, when you start the playback using the CriWare.CriAtomExPlayer::Start function, + * the sound is played back using the specified hold time.
+ *
+ * For the hold time, specify a real value in the range of 0.0f to 2000.0f. The unit is ms (millisecond).
+ * The default hold time is 0.0f.
+ * When playing a Cue, if this function is called when the hold time is set on the data, + * the value set on the data is overridden (the setting on the data is ignored).
+ * It cannot be updated using CriWare.CriAtomExPlayer::Update or CriWare.CriAtomExPlayer::UpdateAll function + * during playback.
+ *
+ * Envelope is not applied to the sound data encoded for HCA-MX.
+ * If you want to use envelope, encode the data using another codec such as ADX or HCA.
+ *
+ * + * : + * // プレーヤの作成 + * CriAtomExPlayer player = new CriAtomExPlayer(); + * : + * // エンベロープの設定 + * player.SetEnvelopeHoldTime(player, 20.0f); + * + * // 再生の開始 + * CriAtomExPlayback playback = player.Start(); + * : + * + * + */ + public void SetEnvelopeHoldTime(float time) + { + criAtomExPlayer_SetEnvelopeHoldTime(this.handle, time); + } + + /** + * Sets the envelope decay time + * Decay time (0.0f to 2000.0f) + * + * Sets the decay time of the envelope.
+ * After setting the decay time using this function, when you start the playback using the CriWare.CriAtomExPlayer::Start function, + * the sound is played back using the specified decay time.
+ *
+ * For the decay time, specify a real value in the range of 0.0f to 2000.0f. The unit is ms (millisecond).
+ * The default decay time is 0.0f.
+ * When playing a Cue, if this function is called when the decay time is set on the data, + * the value set on the data is overridden (the setting on the data is ignored).
+ * It cannot be updated using CriWare.CriAtomExPlayer::Update or CriWare.CriAtomExPlayer::UpdateAll function + * during playback.
+ *
+ * Envelope is not applied to the sound data encoded for HCA-MX.
+ * If you want to use envelope, encode the data using another codec such as ADX or HCA.
+ *
+ * + * : + * // プレーヤの作成 + * CriAtomExPlayer player = new CriAtomExPlayer(); + * : + * // エンベロープの設定 + * player.SetEnvelopeDecayTime(player, 10.0f); + * + * // 再生の開始 + * CriAtomExPlayback playback = player.Start(); + * : + * + * + */ + public void SetEnvelopeDecayTime(float time) + { + criAtomExPlayer_SetEnvelopeDecayTime(this.handle, time); + } + + /** + * Sets the envelope release time + * Release time (0.0f to 10000.0f) + * + * Sets the release time of the envelope.
+ * After setting the release time using this function, when you start the playback using the CriWare.CriAtomExPlayer::Start function, + * the sound is played back using the specified release time.
+ *
+ * For the release time, specify a real value in the range of 0.0f to 10000.0f. The unit is ms (millisecond).
+ * The default release time value is 0.0f.
+ * When playing a Cue, if this function is called when the release time is set on the data, + * the value set on the data is overridden (the setting on the data is ignored).
+ * It cannot be updated using CriWare.CriAtomExPlayer::Update or CriWare.CriAtomExPlayer::UpdateAll function + * during playback.
+ *
+ * Envelope is not applied to the sound data encoded for HCA-MX.
+ * If you want to use envelope, encode the data using another codec such as ADX or HCA.
+ *
+ * + * : + * // プレーヤの作成 + * CriAtomExPlayer player = new CriAtomExPlayer(); + * : + * // エンベロープの設定 + * player.SetEnvelopeReleaseTime(player, 3000.0f); + * + * // 再生の開始 + * CriAtomExPlayback playback = player.Start(); + * : + * + * + */ + public void SetEnvelopeReleaseTime(float time) + { + criAtomExPlayer_SetEnvelopeReleaseTime(this.handle, time); + } + + /** + * Sets the envelope sustain level + * Sustain level (0.0f to 2000.0f) + * + * Sets the sustain level of the envelope.
+ * After setting the sustain level using this function, when you start the playback using the CriWare.CriAtomExPlayer::Start function, + * the sound is played back using the specified sustain level.
+ *
+ * Specify a real value in the range of 0.0f to 1.0f for the sustain level.
+ * The default sustain level is 0.0f.
+ * When playing a Cue, if this function is called when the sustain level is set on the data, + * the value set on the data is overridden (the setting on the data is ignored).
+ * It cannot be updated using CriWare.CriAtomExPlayer::Update or CriWare.CriAtomExPlayer::UpdateAll function + * during playback.
+ *
+ * Envelope is not applied to the sound data encoded for HCA-MX.
+ * If you want to use envelope, encode the data using another codec such as ADX or HCA.
+ *
+ * + * : + * // プレーヤの作成 + * CriAtomExPlayer player = new CriAtomExPlayer(); + * : + * // エンベロープの設定 + * player.SetEnvelopeSustainLevel(0.5f); + * + * // 再生の開始 + * CriAtomExPlayback playback = player.Start(); + * : + * + * + */ + public void SetEnvelopeSustainLevel(float level) + { + criAtomExPlayer_SetEnvelopeSustainLevel(this.handle, level); + } + + /** + * Attach a fader to a player + * + * Attach a fader to a player and turn the + * CriAtomExPlayer into a player dedicated to crossfade.
+ * (Some functions of conventional CriAtomExPlayer such as simultaneous playback of multiple sounds will not be available.)
+ *
+ * The player to which the fader is attached by this function performs + * the following control every time the sound playback is started (every time the + * CriWare.CriAtomExPlayer::Start or CriWare.CriAtomExPlayer::Prepare function is called).
+ * - Forcibly stops sounds being faded out if any. + * - Fades out the sound currently being played (or faded in). + * - Fades in the sound newly started to be played. + * . + *
+ * The following controls are performed when stopping playback (when the + * CriWare.CriAtomExPlayer::Stop function is called).
+ * - Forcibly stops sounds being faded out if any. + * - Fades out the sound currently being played (or faded in).
+ * If the player to attach the fader is playing sounds, all the sounds being played by the player + * stops when this function is called.
+ *
+ * Each time the function CriWare.CriAtomExPlayer::Start or CriWare.CriAtomExPlayer::Stop + * is called for the player a fader is attached to, + * the fader does the following control for the sound being played by the player.
+ *
+ * -# If there are any sounds already faded out, it stops it immediately. + * -# If there are any sounds being faded in (or sounds being played), + * it fades out the sounds from the current volume over the time + * specified in the CriWare.CriAtomExPlayer::SetFadeOutTime function. + * -# When the CriWare.CriAtomExPlayer::Start function is called, + * the fader starts playing the sound data set to the player at volume 0, + * and fades it in over the time specified in the CriWare.CriAtomExPlayer::SetFadeInTime function. + * . + *
+ * (When the CriWare.CriAtomExPlayer::Prepare function is used instead of the + * CriWare.CriAtomExPlayer::Start function, the above control is performed when unpaused.)
+ * When this function is called, the play/stop operation for CriAtomExPlayer changes significantly.
+ * (The behavior changes significantly before/after attaching a fader.)
+ * Specifically, the number of Voices that can be played simultaneously is limited to 1 (2 only during crossfading), + * and the control using CriWare.CriAtomExPlayback will not be available.
+ *
+ * This function is necessary only when you want to perform crossfading.
+ * Use envelope or Tween for Fade-in/out of only one sound.
+ *
+ * Due to the operational specifications of the fader, the Fade-in/out process is + * only applicable to the past two sound playbacks.
+ * Sound played before that is forcibly stopped when the + * CriWare.CriAtomExPlayer::Start or CriWare.CriAtomExPlayer::Stop function is called.
+ * Unintended noise may occur at the timing of forced stop, so be careful that + * the number of simultaneous playbacks does not exceed 3 sounds.
+ *
+ * Fade-in/out works only for the "operation on the AtomExPlayer".
+ * If you call the CriWare.CriAtomExPlayback::Stop function for the playback ID + * obtained by calling CriWare.CriAtomExPlayer::Start function, Fade-out is not activated.
+ * (Fader settings are ignored and the playback stops immediately.)
+ *
+ * + */ + public void AttachFader() + { + criAtomExPlayer_AttachFader(this.handle, IntPtr.Zero, IntPtr.Zero, 0); + } + + /** + * Remove a fader from a player + * + * Detaches (remove) the fader from the player.
+ * Fade-in/out process is no longer performed on the player whose fader is detached using this function.
+ * If the player to detach the fader is playing sounds, all the sounds being played by the player + * stops when this function is called.
+ *
+ * + */ + public void DetachFader() + { + criAtomExPlayer_DetachFader(this.handle); + } + + /** + * Sets the Fade-out time + * Fade out time (in milliseconds) + * + * Specifies the Fade-out time for players with faders attached.
+ * The next time a sound is played back (when the CriWare.CriAtomExPlayer::Start function is called), + * the sound being played is faded out over the time set in this function.
+ *
+ * The default for Fade-out time is 500 milliseconds.
+ * If the Fade-out time is set, CriAtomExPlayer stops the playback in the following order:
+ *
+ * -# Lowers the volume of the sound to 0 over the specified time. + * -# Continues the playback until delay time elapses with volume set to 0. + * -# Stops the playback after the delay time elapses. + * . + *
+ * The volume control during Fade-out is performed before the sound playback is stopped.
+ * Therefore, the envelope release time preset in the waveform data is ignored.
+ * (Strictly speaking, the envelope release process is applied after the volume reaches 0.)
+ *
+ * The behavior differs in the case where the second argument ( ms ) + * is set to 0 from the case where it is set to -1 as follows:
+ *
+ * - When 0 is specified: The volume is immediately lowered to 0 and the sound is stopped. + * - When -1 is specified: The sound is stopped without changing the volume. + * . + *
+ * If you want to enable the envelope release process preset in the waveform + * without performing Fade-out process when stopping playback, + * specify -1 for the second argument ( ms ).
+ * By specifying -1, volume control by Fade-out process will not be done, + * so after calling the CriWare.CriAtomExPlayer::Stop function, normal stopping process is done.
+ * (If the envelope release is set to the waveform data, the release process is performed.)
+ * Before calling this function, you need to attach faders to the player + * in advance using the CriWare.CriAtomExPlayer::AttachFader function.
+ *
+ * The value set by this function does not affect the sounds that being played.
+ * The fade time set by this function is applied when the CriWare.CriAtomExPlayer::Start + * or CriWare.CriAtomExPlayer::Stop function is called after calling this function.
+ * (For the sound that is being faded out, it is not possible to change + * Fade-out time afterward using this function.)
+ *
+ * + * + */ + public void SetFadeOutTime(int ms) + { + criAtomExPlayer_SetFadeOutTime(this.handle, ms); + } + + /** + * Sets the Fade-in time + * Fade-in time (in millisecond) + * + * Specifies the Fade-in time for players with faders attached.
+ * The next time a sound is played back (when the CriWare.CriAtomExPlayer::Start function is called), + * it is newly faded in over the time set in this function.
+ *
+ * The default for Fade-in time is 0 second.
+ * Therefore, if this function is not used, Fade-in does not occur, + * and the playback of the sound starts immediately at full volume.
+ * Before calling this function, you need to attach faders to the player + * in advance using the CriWare.CriAtomExPlayer::AttachFader function.
+ *
+ * The value set by this function does not affect the sounds that being played.
+ * The fade time set by this function is applied when the CriWare.CriAtomExPlayer::Start function + * is called after calling this function.
+ * (For the sound that is being faded in, it is not possible to change + * Fade-in time afterward using this function.)
+ *
+ * + * + */ + public void SetFadeInTime(int ms) + { + criAtomExPlayer_SetFadeInTime(this.handle, ms); + } + + /** + * Sets the Fade-in start offset + * Fade-in start offset (in millisecond) + * + * Specifies the Fade-in start offset for players with faders attached.
+ * By using this function, the timing to start the Fade-in can be advanced or delayed + * for any time with respect to the Fade-out.
+ * For example, if you set the Fade-out time to 5 seconds and the Fade-in start offset to 5 seconds, + * you can fade in the next sound immediately after the Fade-out completes in 5 seconds.
+ * Conversely, if you set the Fade-in time to 5 seconds and the Fade-in start offset to -5 seconds, + * it is possible to start the Fade-out of the sound being played immediately after the Fade-in completes in 5 seconds.
+ *
+ * The default Fade-in start offset is 0 second.
+ * (Fade-in and Fade-out start at the same time.)
+ * The Fade-in starts when the sound to be faded in is ready to be played back.
+ * Therefore, even if the Fade-in start offset is set to 0 second, if it takes time + * to buffer the Fade-in sound, (such as in stream playback), + * it may take some time before the Fade-out starts.
+ * (This parameter is a relative value for adjusting the timing of Fade-in and Fade-out.)
+ * Before calling this function, you need to attach faders to the player + * in advance using the CriWare.CriAtomExPlayer::AttachFader function.
+ *
+ * The value set by this function does not affect the sounds that being played.
+ * The fade time set by this function is applied when the CriWare.CriAtomExPlayer::Start + * or CriWare.CriAtomExPlayer::Stop function is called after calling this function.
+ * (For a Voice that has already started fading, + * the fading timing cannot be changed later with this function.)
+ *
+ * + * + */ + public void SetFadeInStartOffset(int ms) + { + criAtomExPlayer_SetFadeInStartOffset(this.handle, ms); + } + + /** + * Sets the delay time after Fade-out + * Delay time after Fade-out (in milliseconds) + * + * You can set the delay time before discarding the Voice after the Fade-out completes.
+ * By using this function, you can set the timing when the Voice that was faded out is discarded.
+ *
+ * The default delay time is 500 milliseconds.
+ * (The Voices playing a Fade-out sound are discarded 500 milliseconds after the volume is set to 0.)
+ * It is not necessary to use this function except on platforms where the Voice is stopped + * before the sound is stopped before finishing Fade-out.
+ * Before calling this function, you need to attach faders to the player + * in advance using the CriWare.CriAtomExPlayer::AttachFader function.
+ *
+ * The value set by this function does not affect the sounds that are being played.
+ * The fade time set by this function is applied when the CriWare.CriAtomExPlayer::Start + * or CriWare.CriAtomExPlayer::Stop function is called after calling this function.
+ * (For the sound that is being faded out, it is not possible to change + * delay time after Fade-out afterward using this function.)
+ *
+ * The timing when volume control and Voice stop are reflected depends on the platform.
+ * Therefore, if 0 is specified in this function, the Voice may be stopped before the volume change + * takes effect depending on the platform.
+ *
+ * + */ + public void SetFadeOutEndDelay(int ms) + { + criAtomExPlayer_SetFadeOutEndDelay(this.handle, ms); + } + + /** + * Gets whether the fading is in process + * Whether the fading is in progress + * + * Gets whether the fading process is in progress.
+ * This function returns True during the following processing period.
+ * - Waiting for synchronization for starting crossfade. + * - During Fade-in/Fade-out process (while changing volume). + * - During the delay period after completing Fade-out.
+ *
+ */ + public bool IsFading() + { + return criAtomExPlayer_IsFading(this.handle); + } + + /** + * Initializes the fader parameters + * + * Clears various parameters set in the fader and returns them to the initial values.
+ * Before calling this function, you need to attach faders to the player + * in advance using the CriAtomExPlayer::AttachFader function.
+ *
+ * Clearing the fader parameter using this function does not affect the sound that is being played.
+ * The fader parameters cleared by this function is applied when the CriAtomExPlayer::Start + * or CriAtomExPlayer::Stop function is called after calling this function.
+ * (For a Voice that has already started fading, the + * fader parameters cleared by this function cannot be changed)
+ *
+ */ + public void ResetFaderParameters() + { + criAtomExPlayer_ResetFaderParameters(this.handle); + } + + /** + * Specifies the group number + * + * Specifies from which Voice limit group the Voice is taken when playing.
+ *
+ * If group_no is set to -1, the player will not be restricted by the Voice limit group.
+ * (If there are any free Voices or Voices with a lower priority,
+ * the Voice is taken regardless of Voice Limit group.)
+ * When playback starts and all the Voices in the specified Voice limit group are in use, + * whether or not the sound is played is determined by the Voice Priority control.
+ * (For details on the Voice control by Voice Priority, + * see the Description of the CriWare.CriAtomExPlayer::SetVoicePriority function.
+ *
+ * When playing a Cue, if this function is called, the Voice limit group setting
+ * set on the data is overridden (the setting on the data is ignored).
+ * However, if -1 is specified for group_no, the Voice limit group set on data is referenced.
+ *
+ *
+ */ + public void SetGroupNumber(int group_no) + { + criAtomExPlayer_SetGroupNumber(this.handle, group_no); + } + + /** + * Updates the playback parameters (by CriAtomExPlayback object) + * CriAtomExPlayback object + * + * Updates the parameters of the CriAtomExPlayback object using the playback parameters + * set in the AtomExPlayer (including the AISAC control values).
+ * The CriAtomExPlayer object used for parameter update must be + * the player that generated the CriAtomExPlayback object.
+ *
+ * + * : + * // プレーヤの作成 + * CriAtomExPlayer player = new CriAtomExPlayer(); + * : + * // 再生の開始 + * CriAtomExPlayback playback = player.Start(); + * : + * // ボリュームの変更 + * // 注意)この時点では再生中の音声のパラメータは変更されない。 + * player.SetVolume(volume); + * + * // プレーヤに設定されたパラメータを再生中の音声にも反映 + * player.Update(playback); + * : + * + * + */ + public void Update(CriAtomExPlayback playback) + { + criAtomExPlayer_Update(this.handle, playback.id); + } + + /** + * Updates the playback parameters (for all sounds being played) + * + * Updates the playback parameters for all sounds being played by this AtomExPlayer + * using the playback parameters set in the AtomExPlayer (including the AISAC control values).
+ *
+ * + * : + * // プレーヤの作成 + * CriAtomExPlayer player = new CriAtomExPlayer(); + * : + * // 再生の開始 + * CriAtomExPlayback playback = player.Start(); + * : + * // ボリュームの変更 + * // 注意)この時点では再生中の音声のパラメータは変更されない。 + * player.SetVolume(volume); + * + * // プレーヤに設定されたパラメータを再生中の全ての音声に反映 + * player.UpdateAll(); + * : + * + * + */ + public void UpdateAll() + { + criAtomExPlayer_UpdateAll(this.handle); + } + + /** + * Initializes the playback parameters + * + * Resets the playback parameters (including AISAC control values) set in the AtomExPlayer + * to the initial state (unset state).
+ * After calling this function, if you start playback using the CriWare.CriAtomExPlayer::Start function, the sound is played using the default playback parameters.
+ * Even if the CriWare.CriAtomExPlayer::Update or CriWare.CriAtomExPlayer::UpdateAll function is called after calling this function, + * the parameters of the sound already being played does not return to the initial values.
+ * If you want to change the parameters of the sound that is already being played, + * call the CriWare.CriAtomExPlayer::SetVolume function explicitly.
+ *
+ * The following parameters are reset by this function.
+ * - Parameters defined in CriWare.CriAtomEx::Parameter + * - AISAC control value (set by the CriWare.CriAtomExPlayer::SetAisacControl function) + * - Cue priority (set by the CriWare.CriAtomExPlayer::SetCuePriority function) + * - 3D sound source handle (set by the CriWare.CriAtomExPlayer::Set3dSource function) + * - 3D listener handle (set by the CriWare.CriAtomExPlayer::Set3dListener function) + * - Category setting (set by the CriWare.CriAtomExPlayer::SetCategory function) + * - Playback starting Block (set by the CriWare.CriAtomExPlayer::SetFirstBlockIndex function) + * . + * Note that this function does not reset the parameters (position etc.) held by the 3D sound source handle or 3D listener handle itself. + * It only resets "What handle is set on the AtomExPlayer". + * If you want to reset the parameters of these handles themselves, + * call the parameter reset function of each handle.
+ *
+ * + * : + * // プレーヤの作成 + * CriAtomExPlayer player = new CriAtomExPlayer(); + * : + * // ボリュームの変更 + * player.SetVolume(0.5f); + * + * // 音声を再生 + * // 備考)ここで再生された音声は0.5fのボリュームで出力される。 + * CriAtomExPlayback playback1 = player.Start(); + * + * // プレーヤに設定されたパラメータをリセット + * // 備考)プレーヤのボリューム設定がデフォルト値(1.0f)に戻される。 + * player.ResetParameters(); + * + * // 別の音を再生 + * // 備考)ここで再生された音声は1.0fのボリュームで出力される。 + * CriAtomExPlayback playback2 = player.Start(); + * : + * + * + * + */ + public void ResetParameters() + { + criAtomExPlayer_ResetParameters(this.handle); + } + + /** + * Gets the playback time + * Playback time (in milliseconds) + * + * Gets the playback time of the sound that was played last by the AtomExPlayer.
+ *
+ * This function returns a value of 0 or greater if the playback time can be obtained.
+ * This function returns a negative value when the playback time cannot be obtained (when the Voice cannot be obtained).
+ * When multiple sounds are played in a player and this function is called, + * this function returns the time of the "last" played sound.
+ * If you need to check the playback time for multiple sounds, + * create as many players as the number of sounds to play, or + * use the CriWare.CriAtomExPlayback::GetTime function.
+ *
+ * The playback time returned by this function is "the elapsed time from the start of playback".
+ * The time does not rewind depending on the playback position, + * even during loop playback or seamless linked playback.
+ *
+ * When the playback is paused using the CriWare.CriAtomExPlayer::Pause function, + * the playback time count-up also stops.
+ * (If you unpause the playback, the count-up resumes.) + *
+ * The accuracy of the time that can be obtained by this function depends on the frequency of the server processing.
+ * (The time is updated for each server process.)
+ * If you need to get more accurate time, use the + * CriWare.CriAtomExPlayback::GetNumPlayedSamples function instead of + * this function to get the number of samples played.
+ * The return type is long, but currently there is no precision over 32bit.
+ * When performing control based on the playback time, it should be noted that the playback time becomes incorrect in about 24 days.
+ * (The playback time overflows and becomes a negative value when it exceeds 2147483647 milliseconds.)
+ *
+ * If the sound being played is erased by the Voice control, + * the playback time count-up also stops at that point.
+ * In addition, if Voice couldn't be allocated by the Voice control at the start of playback, + * this function does not return the correct time.
+ * (Negative value is returned.)
+ *
+ * Even if the sound data supply is temporarily interrupted due to read retry etc. on the drive, + * the playback time count-up is not interrupted.
+ * (The time progresses even if the playback is stopped due to the stop of data supply.)
+ * Therefore, when synchronizing sound with the source video based on the time acquired by this function, + * the synchronization may be greatly deviated each time a read retry occurs.
+ * If it is necessary to strictly synchronize the waveform data and video, + * use the CriWare.CriAtomExPlayback::GetNumPlayedSamples function instead of this function + * to synchronize with the number of played samples.
+ *
+ * + * + */ + public long GetTime() + { + return criAtomExPlayer_GetTime(this.handle); + } + + /** + * Gets the status + * Status + * + * Gets the status of the AtomExPlayer.
+ * The status is one of following 5 values of type CriWare.CriAtomExPlayer::Status + * indicating the playback status of the AtomExPlayer.
+ * -# Stop + * -# Prep + * -# Playing + * -# PlayEnd + * -# Error + * . + * When you create an AtomExPlayer, the AtomExPlayer's status is Stop.
+ * By calling the CriWare.CriAtomExPlayer::Start function after setting the sound data to be played, + * the status of the AtomExPlayer changes to ready ( Prep ).
+ * (Prep is the status waiting for the data to be supplied or start of decoding.)
+ * When enough data is supplied for starting playback, the AtomExPlayer changes the status to + * Playing and starts to output sound.
+ * When all the set data have been played back, the AtomExPlayer changes the status to + * PlayEnd.
+ * If an error occurs during playback, the AtomExPlayer changes the status to + * Error.
+ *
+ * By checking the status of AtomExPlayer and switching the processing depending on the status, + * it is possible to create a program linked to the sound playback status.
+ * For example, if you want to wait for the completion of sound playback before proceeding, use the following code. + * : + * // プレーヤの作成 + * CriAtomExPlayer player = new CriAtomExPlayer(); + * : + * // 音声データをセット + * player.SetCue(acb, cueId); + * + * // セットされた音声データを再生 + * player.Start(); + * + * // 再生完了待ち + * while (player.GetStatus() != CriAtomExPlayer.Status.PlayEnd) { + * yield return null; + * } + * : + * + *
+ *
+ * + */ + public Status GetStatus() + { + return criAtomExPlayer_GetStatus(this.handle); + } + + /** + * Gets parameters (floating point numbers) + * Parameter ID + * Parameter setting + * + * Gets the values of various parameters set in the AtomExPlayer.
+ * The value is obtained as a floating point number.
+ *
+ * + * + * + */ + public float GetParameterFloat32(CriAtomEx.Parameter id) + { + return criAtomExPlayer_GetParameterFloat32(this.handle, id); + } + + /** + * Gets parameters (unsigned integer) + * Parameter ID + * Parameter setting + * + * Gets the values of various parameters set in the AtomExPlayer.
+ * The value is obtained as an unsigned integer.
+ *
+ * + * + * + */ + public uint GetParameterUint32(CriAtomEx.Parameter id) + { + return criAtomExPlayer_GetParameterUint32(this.handle, id); + } + + /** + * Gets parameters (signed integer) + * Parameter ID + * Parameter setting + * + * Gets the values of various parameters set in the AtomExPlayer.
+ * The value is obtained as a signed integer.
+ *
+ * + * + * + */ + public int GetParameterSint32(CriAtomEx.Parameter id) + { + return criAtomExPlayer_GetParameterSint32(this.handle, id); + } + + /** + * Sets the output sound renderer type + * Output destination sound renderer type + * + * Sets the type of sound renderer used to play the AtomExPlayer.
+ * If you start playback after making this setting, a playable Voice is acquired from the Voice Pool + * created with the specified sound renderer type.
+ * The sound renderer type can be set for each Cue playback unit.
+ *
+ * + */ + public void SetSoundRendererType(CriAtomEx.SoundRendererType type) + { + criAtomExPlayer_SetSoundRendererType(this.handle, type); + } + + /** + * Sets the random number seed + * Random number seed + * + * Sets the random number seed in the pseudo random number generator in the AtomExPlayer.
+ * By setting the random number seed, it is possible to add reproducibility to various random playback processes.
+ *
+ *
+ * + */ + public void SetRandomSeed(uint seed) + { + criAtomExPlayer_SetRandomSeed(this.handle, seed); + } + + /** + * Switches on/off the loop playback + * Loop switch (True: loop mode, False: cancel loop mode) + * + * Switches the loop playback ON/OFF for the waveform data that does not have a loop point.
+ * By default, loop is OFF.
+ * When loop playback is turned ON, the playback does not end at the end of the sound, and the playback is repeated from the beginning.
+ * The setting in this function is applied to the waveform data.
+ * When this function is called for Sequence data, + * the individual waveform data in the Sequence data is played back in a loop.
+ *
+ * The specification by this function is valid only for waveform data that does not have loop points.
+ * When playing back waveform data with loop points, loop playback is performed + * according to the loop position of the waveform data regardless of the specification of this function.
+ *
+ * This function internally uses the seamless link playback feature.
+ * Therefore, if you use an format that does not support seamless linked playback (such as HCA-MX), + * some amount of silence is inserted at the loop position.
+ *
+ * You can change the loop switch only before starting playback.
+ * You cannot change the loop switch for the player that is playing sound.
+ *
+ */ + public void Loop(bool sw) + { + if (sw) + { + /*(-1) JP<ループ回数制限なし */ + /*(-2) JP<ループ情報を無視 */ + /*(-3) JP<強制ループ再生 */ + criAtomExPlayer_LimitLoopCount(this.handle, -3); + }else + { + ushort CRIATOMPARAMETER2_ID_LOOP_COUNT = CriAtomPlugin.GetLoopCountParameterId(); + IntPtr player_parameter = criAtomExPlayer_GetPlayerParameter(this.handle); + criAtomExPlayerParameter_RemoveParameter(player_parameter, CRIATOMPARAMETER2_ID_LOOP_COUNT); + } + } + + /** + * Specification of ASR Rack ID + * ASR Rack ID + * + * Specifies the Voice destination ASR Rack ID.
+ * This function is effective only when ASR is used as the sound renderer type of the Voice.
+ * (When using other Voices, the setting in this function is ignored.)
+ *
+ * The ASR Rack ID must be set before starting playback.
+ * The ASR Rack ID cannot be changed later for the sound already being played.
+ *
+ * The setting in this function is not applied to the sound data encoded for HCA-MX.
+ *
+ */ + public void SetAsrRackId(int asr_rack_id) + { + criAtomExPlayer_SetAsrRackId(this.handle, asr_rack_id); + } + + /** + * Sets the Voice Pool identifier + * Voice Pool identifier + * + * Specifies from which Voice Pool the Voice is taken when playing.
+ * When this function is called, the player will get Voices only from the Voice Pool that matches + * the specified Voice Pool identifier.
+ *
+ * + * + */ + public void SetVoicePoolIdentifier(uint identifier) + { + criAtomExPlayer_SetVoicePoolIdentifier(this.handle, identifier); + } + + /** + * Sets the DSP time stretch ratio + * Stretch ratio + * + * Sets the scale factor for the playback time of the DSP time stretch.
+ * The value obtained by multiplying the playback time of the original data by ratio is the playback time of the stretch result.
+ * Acceptable value is between 0.5f to 2.0f.
+ * The value to be set is not the playback speed but the scale factor for the "playback time".
+ * When specifying the stretch rate by the playback speed, set the reciprocal of the playback speed scale factor.
+ *
+ * + * + */ + public void SetDspTimeStretchRatio(float ratio) + { + SetDspParameter((int)TimeStretchParameterId.Ratio, ratio); + } + + /** + * Sets the pitch shift amount of the DSP pitch shifter + * Pitch shift amount + * + * Sets the pitch shift amount of the DSP pitch shifter.
+ * The unit is cents.
+ * Acceptable value is between -2400 to 2400.
+ * 1200 means 2 times and -1200 means 1/2 times pitch shift compared to the original sound.
+ *
+ * + * + */ + public void SetDspPitchShifterPitch(float pitch) + { + float value = pitch / 4800.0f + 0.5f; + SetDspParameter((int)PitchShifterParameterId.Pitch, value); + } + + /** + * Sets the DSP parameter + * Parameter ID + * Parameter value + * + * Sets the parameters of the DSP attached to the Voice. + * + * + * + * + */ + public void SetDspParameter(int id, float value) + { + criAtomExPlayer_SetDspParameter(this.handle, id, value); + } + + public void SetSequencePrepareTime(uint ms) + { + criAtomExPlayer_SetSequencePrepareTime(this.handle, ms); + } + + /** + * Parameters for time stretch + * + * The parameter specified for the time stretch DSP. + * + * + * + */ + public enum TimeStretchParameterId : int { + Ratio = 0, /**< Stretch ratio */ + FrameTime = 1, /**< Frame time */ + Quality = 2 /**< Processing quality */ + } + + /** + * Parameters for pitch shifter + * + * The parameter specified for the pitch shifter DSP. + * + * + * + */ + public enum PitchShifterParameterId : int { + Pitch = 0, /**< Pitch */ + Formant = 1, /**< Formant */ + Mode = 2 /**< Pitch shift mode */ + } + + /** + * Attaches an AtomExTween + * + * Simple parameter animation is possible by attaching AtomExTween to the player.
+ * If you want to apply the AtomExTween animation to the audio that started playing before the attachment,
+ * You need to call CriAtomExPlayer.Update or CriAtomExPlayer.UpdateAll .
+ *
+ * AtomExTween Object + * + */ + public void AttachTween(CriAtomExTween tween) + { + criAtomExPlayer_AttachTween(this.handle, tween.nativeHandle); + } + + /** + * Detaches an AtomExTween + * AtomExTween Object + * + */ + public void DetachTween(CriAtomExTween tween) + { + criAtomExPlayer_DetachTween(this.handle, tween.nativeHandle); + } + + /** + * Detaches all AtomExTween + * + */ + public void DetachTweenAll() + { + criAtomExPlayer_DetachTweenAll(this.handle); + } + + /* Old APIs */ + public void Stop() { + if (this.isAvailable) { + criAtomExPlayer_Stop(this.handle); + CRIWAREF051667D(this.entryPoolHandle); + } + } + public void StopWithoutReleaseTime() { + if (this.isAvailable) { + criAtomExPlayer_StopWithoutReleaseTime(this.handle); + CRIWAREF051667D(this.entryPoolHandle); + } + } + public void Pause(bool sw) { criAtomExPlayer_Pause(this.handle, sw); } + + #region Internal Members + + ~CriAtomExPlayer() + { + this.Dispose(); + } + + private IntPtr handle = IntPtr.Zero; + + private void OnBeatSyncCallbackChainInternal(ref CriAtomExBeatSync.Info info) + { + if (info.playerHn != this.nativeHandle) { + return; + } + _onBeatSyncCallback(ref info); + } + + private void OnSequenceCallbackChainInternal(ref CriAtomExSequencer.CriAtomExSequenceEventInfo info) + { + if (info.playerHn != this.nativeHandle) { + return; + } + _onSequenceCallback(ref info); + } + + #endregion + + #region DLL Import + #if !CRIWARE_ENABLE_HEADLESS_MODE + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern IntPtr criAtomExPlayer_Create(ref Config config, IntPtr work, int work_size); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_Destroy(IntPtr player); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_SetCueId( + IntPtr player, IntPtr acb_hn, int id); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_SetCueName( + IntPtr player, IntPtr acb_hn, string cue_name); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_SetCueIndex( + IntPtr player, IntPtr acb_hn, int index); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_SetFile( + IntPtr player, IntPtr binder, string path); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_SetData( + IntPtr player, byte[] buffer, int size); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_SetData( + IntPtr player, IntPtr buffer, int size); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_SetContentId( + IntPtr player, IntPtr binder, int id); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_SetVoicePoolIdentifier( + IntPtr player, uint identifier); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern uint criAtomExPlayer_Start(IntPtr player); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern uint criAtomExPlayer_Prepare(IntPtr player); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_Stop(IntPtr player); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_StopWithoutReleaseTime(IntPtr player); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_Pause(IntPtr player, bool sw); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_Resume(IntPtr player, CriAtomEx.ResumeMode mode); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool criAtomExPlayer_IsPaused(IntPtr player); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern Status criAtomExPlayer_GetStatus(IntPtr player); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern long criAtomExPlayer_GetTime(IntPtr player); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_SetFormat(IntPtr player, CriAtomEx.Format format); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_SetNumChannels(IntPtr player, int num_channels); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_SetSamplingRate(IntPtr player, int sampling_rate); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern IntPtr CRIWAREFDE24A32(IntPtr player, int capacity, int max_path, bool stopOnEmpty); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void CRIWARE7A36FD14(IntPtr pool); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int CRIWARE3AE79C16(IntPtr pool); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int CRIWAREE3B3AD44(IntPtr pool); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void CRIWARE6BE60787(IntPtr pool); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool CRIWAREB64C6C94(IntPtr pool, IntPtr binder, string path, bool repeat, int max_path); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool CRIWARE591013B5(IntPtr pool, IntPtr binder, int id, bool repeat); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool CRIWARE94039BDE(IntPtr pool, byte[] buffer, int size, bool repeat); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool CRIWARE94039BDE(IntPtr pool, IntPtr buffer, int size, bool repeat); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool CRIWAREEF1A65AD(IntPtr pool, IntPtr acbhn, string name, bool repeat); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void CRIWAREF051667D(IntPtr pool); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_SetStartTime( + IntPtr player, long start_time_ms); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_SetSequencePrepareTime( + IntPtr player, uint seq_prep_time_ms); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_LimitLoopCount(IntPtr player, int count); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_Update(IntPtr player, uint id); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_UpdateAll(IntPtr player); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_ResetParameters(IntPtr player); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern float criAtomExPlayer_GetParameterFloat32(IntPtr player, CriAtomEx.Parameter id); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern uint criAtomExPlayer_GetParameterUint32(IntPtr player, CriAtomEx.Parameter id); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criAtomExPlayer_GetParameterSint32(IntPtr player, CriAtomEx.Parameter id); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern IntPtr criAtomExPlayer_GetPlayerParameter(IntPtr player); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayerParameter_RemoveParameter(IntPtr player_parameter, System.UInt16 id); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_SetVolume(IntPtr player, float volume); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_SetPitch(IntPtr player, float pitch); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_SetPlaybackRatio(IntPtr player, float playback_ratio); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_SetPan3dAngle(IntPtr player, float pan3d_angle); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_SetPan3dInteriorDistance( + IntPtr player, float pan3d_interior_distance); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_SetPan3dVolume(IntPtr player, float pan3d_volume); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_SetPanType(IntPtr player, CriAtomEx.PanType panType); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_SetSendLevel(IntPtr player, int channel, CriAtomEx.Speaker id, float level); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_SetBusSendLevel( + IntPtr player, int bus_id, float level); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_SetBusSendLevelByName( + IntPtr player, string bus_name, float level); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool criAtomExPlayer_GetBusSendLevelByName( + IntPtr player, string bus_name, out float level); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_SetBusSendLevelOffset( + IntPtr player, int bus_id, float level_offset); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_SetBusSendLevelOffsetByName( + IntPtr player, string bus_name, float level_offset); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool criAtomExPlayer_GetBusSendLevelOffsetByName( + IntPtr player, string bus_name, out float level_offset); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_SetBandpassFilterParameters( + IntPtr player, float cof_low, float cof_high); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_SetBiquadFilterParameters( + IntPtr player, CriAtomEx.BiquadFilterType type, float frequency, float gain, float q); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_SetVoicePriority( + IntPtr player, int priority); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_SetVoiceControlMethod( + IntPtr player, CriAtomEx.VoiceControlMethod method); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_SetAisacControlById( + IntPtr player, ushort control_id, float control_value); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_SetAisacControlByName( + IntPtr player, string control_name, float control_value); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_Set3dSourceHn( + IntPtr player, IntPtr source); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_Set3dListenerHn( + IntPtr player, IntPtr listener); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_SetCategoryById( + IntPtr player, uint category_id); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_SetCategoryByName( + IntPtr player, string category_name); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_UnsetCategory(IntPtr player); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_SetCuePriority( + IntPtr player, int cue_priority); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_SetPreDelayTime( + IntPtr player, float predelay_time_ms); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_SetEnvelopeAttackTime( + IntPtr player, float attack_time_ms); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_SetEnvelopeHoldTime( + IntPtr player, float hold_time_ms); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_SetEnvelopeDecayTime( + IntPtr player, float decay_time_ms); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_SetEnvelopeReleaseTime( + IntPtr player, float release_time_ms); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_SetEnvelopeSustainLevel( + IntPtr player, float susutain_level); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_AttachFader( + IntPtr player, IntPtr config, IntPtr work, int work_size); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_AttachAisac( + IntPtr player, string globalAisacName); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_DetachAisac( + IntPtr player, string globalAisacName); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_DetachFader(IntPtr player); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_SetFadeOutTime(IntPtr player, int ms); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_SetFadeInTime(IntPtr player, int ms ); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_SetFadeInStartOffset(IntPtr player, int ms); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_SetFadeOutEndDelay(IntPtr player, int ms); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool criAtomExPlayer_IsFading(IntPtr player); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_ResetFaderParameters(IntPtr player); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_SetGroupNumber(IntPtr player, int group_no); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool criAtomExPlayer_GetAttachedAisacInfo( + IntPtr player, int aisac_attached_index, IntPtr aisac_info); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_SetFirstBlockIndex(IntPtr player, int index); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_SetSelectorLabel(IntPtr player, string selector, string label); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_UnsetSelectorLabel(IntPtr player, string selector); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_ClearSelectorLabels(IntPtr player); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_SetSoundRendererType(IntPtr player, CriAtomEx.SoundRendererType type); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_SetRandomSeed(IntPtr player, uint seed); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void CRIWARE77262FAC(IntPtr player, bool sw); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_SetAsrRackId(IntPtr player, int asr_rack_id); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_SetDspParameter(IntPtr player, int id, float value); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_AttachTween(IntPtr player, IntPtr tween); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_DetachTween(IntPtr player, IntPtr tween); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExPlayer_DetachTweenAll(IntPtr player); +#else + private Status _dummyStatus = Status.Stop; + private bool _dummyPaused = false; + private bool _dummyLoop = false; + private static IntPtr criAtomExPlayer_Create(ref Config config, IntPtr work, int work_size) { return IntPtr.Zero; } + private static void criAtomExPlayer_Destroy(IntPtr player) { } + private static void criAtomExPlayer_SetCueId(IntPtr player, IntPtr acb_hn, int id) { } + private static void criAtomExPlayer_SetCueName(IntPtr player, IntPtr acb_hn, string cue_name) { } + private static void criAtomExPlayer_SetCueIndex(IntPtr player, IntPtr acb_hn, int index) { } + private static void criAtomExPlayer_SetFile(IntPtr player, IntPtr binder, string path) { } + private static void criAtomExPlayer_SetData(IntPtr player, byte[] buffer, int size) { } + private static void criAtomExPlayer_SetData(IntPtr player, IntPtr buffer, int size) { } + private static void criAtomExPlayer_SetContentId(IntPtr player, IntPtr binder, int id) { } + private static void criAtomExPlayer_SetVoicePoolIdentifier(IntPtr player, uint identifier) { } + private uint criAtomExPlayer_Start(IntPtr player) { _dummyStatus = Status.Prep; _dummyPaused = false; return 0u; } + private uint criAtomExPlayer_Prepare(IntPtr player) { _dummyStatus = Status.Prep; return 0u; } + private void criAtomExPlayer_Stop(IntPtr player) { _dummyStatus = Status.Stop; } + private void criAtomExPlayer_StopWithoutReleaseTime(IntPtr player) { _dummyStatus = Status.Stop; } + private void criAtomExPlayer_Pause(IntPtr player, bool sw) { _dummyPaused = false; } + private static void criAtomExPlayer_Resume(IntPtr player, CriAtomEx.ResumeMode mode) { } + private bool criAtomExPlayer_IsPaused(IntPtr player) { return _dummyPaused; } + private Status criAtomExPlayer_GetStatus(IntPtr player) { + Status ret = _dummyStatus; + if (!_dummyPaused && _dummyStatus != Status.PlayEnd && _dummyStatus != Status.Stop) { + _dummyStatus = _dummyStatus == Status.Prep ? Status.Playing : + !(_dummyPaused || _dummyLoop) ? Status.PlayEnd : Status.Playing; + } + return ret; + } + private static long criAtomExPlayer_GetTime(IntPtr player) { return 0; } + private static void criAtomExPlayer_SetFormat(IntPtr player, CriAtomEx.Format format) { } + private static void criAtomExPlayer_SetNumChannels(IntPtr player, int num_channels) { } + private static void criAtomExPlayer_SetSamplingRate(IntPtr player, int sampling_rate) { } + private static IntPtr CRIWAREFDE24A32(IntPtr player, int capacity, int max_path, bool stopOnEmpty) { return new IntPtr(1); } + private static void CRIWARE7A36FD14(IntPtr pool) { } + private static int CRIWARE3AE79C16(IntPtr pool) { return 0; } + private static int CRIWAREE3B3AD44(IntPtr pool) { return 0; } + private static void CRIWARE6BE60787(IntPtr pool) { } + private static bool CRIWAREB64C6C94(IntPtr pool, IntPtr binder, string path, bool repeat, int max_path) { return true; } + private static bool CRIWARE591013B5(IntPtr pool, IntPtr binder, int id, bool repeat) { return true; } + private static bool CRIWARE94039BDE(IntPtr pool, byte[] buffer, int size, bool repeat) { return true; } + private static bool CRIWARE94039BDE(IntPtr pool, IntPtr buffer, int size, bool repeat) { return true; } + private static bool CRIWAREEF1A65AD(IntPtr pool, IntPtr acbhn, string name, bool repeat) { return true; } + private static void CRIWAREF051667D(IntPtr pool) { } + private static void criAtomExPlayer_SetStartTime(IntPtr player, long start_time_ms) { } + private static void criAtomExPlayer_SetSequencePrepareTime(IntPtr player, uint seq_prep_time_ms) { } + private void criAtomExPlayer_LimitLoopCount(IntPtr player, int count) { _dummyLoop = (count == -3); } + private static void criAtomExPlayer_Update(IntPtr player, uint id) { } + private static void criAtomExPlayer_UpdateAll(IntPtr player) { } + private static void criAtomExPlayer_ResetParameters(IntPtr player) { } + private static float criAtomExPlayer_GetParameterFloat32(IntPtr player, CriAtomEx.Parameter id) { return 0.0f; } + private static uint criAtomExPlayer_GetParameterUint32(IntPtr player, CriAtomEx.Parameter id) { return 0u; } + private static int criAtomExPlayer_GetParameterSint32(IntPtr player, CriAtomEx.Parameter id) { return 0; } + private static IntPtr criAtomExPlayer_GetPlayerParameter(IntPtr player) { return IntPtr.Zero; } + private void criAtomExPlayerParameter_RemoveParameter(IntPtr player_parameter, System.UInt16 id) { _dummyLoop = false; } + private static void criAtomExPlayer_SetVolume(IntPtr player, float volume) { } + private static void criAtomExPlayer_SetPitch(IntPtr player, float pitch) { } + private static void criAtomExPlayer_SetPlaybackRatio(IntPtr player, float playback_ratio) { } + private static void criAtomExPlayer_SetPan3dAngle(IntPtr player, float pan3d_angle) { } + private static void criAtomExPlayer_SetPan3dInteriorDistance( + IntPtr player, float pan3d_interior_distance) { } + private static void criAtomExPlayer_SetPan3dVolume(IntPtr player, float pan3d_volume) { } + private static void criAtomExPlayer_SetPanType(IntPtr player, CriAtomEx.PanType panType) { } + private static void criAtomExPlayer_SetSendLevel(IntPtr player, int channel, CriAtomEx.Speaker id, float level) { } + private static void criAtomExPlayer_SetBusSendLevel(IntPtr player, int bus_id, float level) { } + private static void criAtomExPlayer_SetBusSendLevelByName(IntPtr player, string bus_name, float level) { } + private static bool criAtomExPlayer_GetBusSendLevelByName(IntPtr player, string bus_name, out float level) { level = 0.0f; return false; } + private static void criAtomExPlayer_SetBusSendLevelOffset(IntPtr player, int bus_id, float level_offset) { } + private static void criAtomExPlayer_SetBusSendLevelOffsetByName(IntPtr player, string bus_name, float level_offset) { } + private static bool criAtomExPlayer_GetBusSendLevelOffsetByName(IntPtr player, string bus_name, out float level_offset) { level_offset = 0.0f; return false; } + private static void criAtomExPlayer_SetBandpassFilterParameters(IntPtr player, float cof_low, float cof_high) { } + private static void criAtomExPlayer_SetBiquadFilterParameters( + IntPtr player, CriAtomEx.BiquadFilterType type, float frequency, float gain, float q) { } + private static void criAtomExPlayer_SetVoicePriority(IntPtr player, int priority) { } + private static void criAtomExPlayer_SetVoiceControlMethod(IntPtr player, CriAtomEx.VoiceControlMethod method) { } + private static void criAtomExPlayer_AttachAisac(IntPtr player, string globalAisacName) { } + private static void criAtomExPlayer_DetachAisac(IntPtr player, string globalAisacName) { } + private static void criAtomExPlayer_SetAisacControlById(IntPtr player, ushort control_id, float control_value) { } + private static void criAtomExPlayer_SetAisacControlByName(IntPtr player, string control_name, float control_value) { } + private static void criAtomExPlayer_Set3dSourceHn(IntPtr player, IntPtr source) { } + private static void criAtomExPlayer_Set3dListenerHn(IntPtr player, IntPtr listener) { } + private static void criAtomExPlayer_SetCategoryById(IntPtr player, uint category_id) { } + private static void criAtomExPlayer_SetCategoryByName(IntPtr player, string category_name) { } + private static void criAtomExPlayer_UnsetCategory(IntPtr player) { } + private static void criAtomExPlayer_SetCuePriority(IntPtr player, int cue_priority) { } + private static void criAtomExPlayer_SetPreDelayTime(IntPtr player, float predelay_time_ms) { } + private static void criAtomExPlayer_SetEnvelopeAttackTime(IntPtr player, float attack_time_ms) { } + private static void criAtomExPlayer_SetEnvelopeHoldTime(IntPtr player, float hold_time_ms) { } + private static void criAtomExPlayer_SetEnvelopeDecayTime(IntPtr player, float decay_time_ms) { } + private static void criAtomExPlayer_SetEnvelopeReleaseTime(IntPtr player, float release_time_ms) { } + private static void criAtomExPlayer_SetEnvelopeSustainLevel(IntPtr player, float susutain_level) { } + private static void criAtomExPlayer_AttachFader(IntPtr player, IntPtr config, IntPtr work, int work_size) { } + private static void criAtomExPlayer_DetachFader(IntPtr player) { } + private static void criAtomExPlayer_SetFadeOutTime(IntPtr player, int ms) { } + private static void criAtomExPlayer_SetFadeInTime(IntPtr player, int ms ) { } + private static void criAtomExPlayer_SetFadeInStartOffset(IntPtr player, int ms) { } + private static void criAtomExPlayer_SetFadeOutEndDelay(IntPtr player, int ms) { } + private static bool criAtomExPlayer_IsFading(IntPtr player) { return false; } + private static void criAtomExPlayer_ResetFaderParameters(IntPtr player) { } + private static void criAtomExPlayer_SetGroupNumber(IntPtr player, int group_no) { } + private static bool criAtomExPlayer_GetAttachedAisacInfo( + IntPtr player, int aisac_attached_index, IntPtr aisac_info) { return false; } + private static void criAtomExPlayer_SetFirstBlockIndex(IntPtr player, int index) { } + private static void criAtomExPlayer_SetSelectorLabel(IntPtr player, string selector, string label) { } + private static void criAtomExPlayer_UnsetSelectorLabel(IntPtr player, string selector) { } + private static void criAtomExPlayer_ClearSelectorLabels(IntPtr player) { } + private static void criAtomExPlayer_SetSoundRendererType(IntPtr player, CriAtomEx.SoundRendererType type) { } + private static void criAtomExPlayer_SetRandomSeed(IntPtr player, uint seed) { } + private void CRIWARE77262FAC(IntPtr player, bool sw) { _dummyLoop = sw; } + private static void criAtomExPlayer_SetAsrRackId(IntPtr player, int asr_rack_id) { } + private static void criAtomExPlayer_SetDspParameter(IntPtr player, int id, float value) { } + + private static void criAtomExPlayer_AttachTween(IntPtr player, IntPtr tween){} + private static void criAtomExPlayer_DetachTween(IntPtr player, IntPtr tween){} + private static void criAtomExPlayer_DetachTweenAll(IntPtr player){} +#endif + #endregion +} + +} //namespace CriWare +/** + * @} + */ + +/* --- end of file --- */ diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExPlayer.cs.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExPlayer.cs.meta new file mode 100644 index 0000000..6fa6d5e --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExPlayer.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: a1b232ca3bdd6774ea6810c96f984b71 +timeCreated: 1433816076 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExPlayerOutputAnalyzer.cs b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExPlayerOutputAnalyzer.cs new file mode 100644 index 0000000..89cfa7f --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExPlayerOutputAnalyzer.cs @@ -0,0 +1,122 @@ +/**************************************************************************** + * + * Copyright (c) 2018 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +/*========================================================================== + * CRI Atom Native Wrapper + *=========================================================================*/ +/** + * \addtogroup CRIATOM_NATIVE_WRAPPER + * @{ + */ + +namespace CriWare { + +/** + * \deprecated + * 削除予定の非推奨APIです。 + * CriAtomExOutputAnalyzerクラスの使用を検討してください。 + * Sound output data analysis module (for each player/source) + * + * Performs sound output analysis for each CriAtomSource/CriAtomExPlayer.
+ * Provides features such as Level Meter.
+ * This class is discontinued in the future. Use CriAtomExOutputAnalyzer .
+ * Analysis is not possible when using HCA-MX or a platform-specific sound compression codec.
+ * Use HCA or ADX codecs.
+ *
+*/ +[System.Obsolete("Use CriAtomExOutputAnalyzer")] +public class CriAtomExPlayerOutputAnalyzer : CriAtomExOutputAnalyzer +{ + /** + * Analysis processing type + * + * A value indicating the type of analysis specified when creating the analysis module. + * + * + */ + public enum Type { + LevelMeter = 0, /**< Level Meter (RMS level measurement) */ + SpectrumAnalyzer = 1, /**< Spectrum analyzer */ + PcmCapture = 2, /**< Gets the waveform data */ + } + + /** + * Sound output data analysis module config structure + * + * A config specified when creating the analysis module.
+ * num_spectrum_analyzer_bands: The number of spectrum analyzer bands
+ * num_stored_output_data: The number of output data samples to be recorded
+ *
+ * + */ + public new struct Config { + public int num_spectrum_analyzer_bands; + public int num_stored_output_data; + + public Config(int num_spectrum_analyzer_bands = 8, int num_stored_output_data = 4096) + { + this.num_spectrum_analyzer_bands = num_spectrum_analyzer_bands; + this.num_stored_output_data = num_stored_output_data; + } + } + + /** + * Creates a sound output data analysis module + * Sound output data analysis module + * + * Creates an output sound data analysis module for CriAtomSource/CriAtomExPlayer.
+ * You use the analysis module you created by attaching it to CriAtomSource or CriAtomExPlayer.
+ * You perform analysis on the attached sound output such as a Level Meter.
+ * Only one CriAtomSource/CriAtomExPlayer can be attached to the analysis module.
+ * If you want to reuse the analysis module, detach it.
+ * This class is discontinued in the future. Use CriAtomExOutputAnalyzer .
+ * Unmanaged resources are reserved when creating a sound output data analysis module.
+ * When you no longer need the analysis module, be sure to call the CriAtomExPlayerOutputAnalyzer.Dispose method.
+ *
+ */ + public CriAtomExPlayerOutputAnalyzer(Type[] types, Config[] configs = null) + : base() + { + CriAtomExOutputAnalyzer.Config config = new CriAtomExOutputAnalyzer.Config(); + for (int i = 0; i < types.Length; i++) { + switch (types[i]) { + case Type.LevelMeter: + { + config.enableLevelmeter = true; + break; + } + case Type.SpectrumAnalyzer: + { + config.enableSpectrumAnalyzer = true; + if (configs != null && configs.Length > i) { + config.numSpectrumAnalyzerBands = configs[i].num_spectrum_analyzer_bands; + } else { + config.numSpectrumAnalyzerBands = 8; + } + break; + } + case Type.PcmCapture: + { + config.enablePcmCapture = true; + if (configs != null && configs.Length > i) { + config.numCapturedPcmSamples = configs[i].num_stored_output_data; + } else { + config.numCapturedPcmSamples = 4096; + } + break; + } + } + } + this.InitializeWithConfig(config); + } +} + +} //namespace CriWare +/** + * @} + */ + +/* --- end of file --- */ diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExPlayerOutputAnalyzer.cs.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExPlayerOutputAnalyzer.cs.meta new file mode 100644 index 0000000..d217cd8 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExPlayerOutputAnalyzer.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 0149ad38d1a97c441a27a52fe291bc4e +timeCreated: 1433816076 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExSoundObject.cs b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExSoundObject.cs new file mode 100644 index 0000000..2976827 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExSoundObject.cs @@ -0,0 +1,192 @@ +/**************************************************************************** + * + * Copyright (c) 2017 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; + +/*========================================================================== + * CRI Atom Native Wrapper + *=========================================================================*/ +/** + * \addtogroup CRIATOM_NATIVE_WRAPPER + * @{ + */ + +namespace CriWare { + +/** + * AtomEx sound object + * + * A sound object class.
+ * You can control sounds in a batch for the registered players by associating with + * "object", "space", "situation" etc. in the application.
+ *
+ */ +public class CriAtomExSoundObject : CriDisposable +{ + public IntPtr nativeHandle {get {return this.handle;} } + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + private struct Config { + public bool enableVoiceLimitScope; + public bool enableCategoryCueLimitScope; + } + + /** + * Creates a sound object + * Whether to activate the Voice limit scope + * Whether to enable the Category Cue limit scope + * Sound object + * + * Creates a sound object.
+ * If enableVoiceLimitScope is set to True, the Voice count is controlled by + * the Voice limit group by counting the number of Voices for the sound played back + * from the Ex player associated with this sound object only inside this + * sound object.
+ * If enableCategoryCueLimit is set to True, the playback count is controlled + * by counting the number of Category playbacks for the Cue played back from the + * Ex player associated with this sound object only inside this sound object.
+ *
+ * + */ + public CriAtomExSoundObject(bool enableVoiceLimitScope, bool enableCategoryCueLimitScope) + { + if (!CriAtomPlugin.IsLibraryInitialized()) { + throw new Exception("CriAtomPlugin is not initialized."); + } + + Config config; + config.enableVoiceLimitScope = enableVoiceLimitScope; + config. enableCategoryCueLimitScope = enableCategoryCueLimitScope; + + this.handle = criAtomExSoundObject_Create(ref config, IntPtr.Zero, 0); + + CriDisposableObjectManager.Register(this, CriDisposableObjectManager.ModuleType.Atom); + } + + /** + * Discards a sound object + * + * Discards a sound object.
+ * When this function is called, all the resources allocated in the DLL + * when creating the sound object are released.
+ *
+ * + */ + public override void Dispose() + { + CriDisposableObjectManager.Unregister(this); + if (this.handle != IntPtr.Zero) { + criAtomExSoundObject_Destroy(this.handle); + this.handle = IntPtr.Zero; + } + GC.SuppressFinalize(this); + } + + /** + * Adds an AtomExPlayer + * AtomExPlayer + * + * Adds an AtomExPlayer to the sound object.
+ * The added AtomExPlayer is associated with the sound object and will be + * affected by the sound object as follows:
+ * - Limitation on the number of Voices and the range affected by the event function (scope)
+ * - Playback control (Stop, Pause etc.)
+ * - Parameter control
+ * If you want to delete the added AtomExPlayer from the sound object, + * call the CriAtomExSoundObject::DeletePlayer function.
+ * Call this function when the AtomExPlayer you are trying to add is not playing sound.
+ * If an AtomExPlayer that is playing sound is specified, playback is stopped when adding.
+ *
+ * + * + * + */ + public void AddPlayer(CriAtomExPlayer player) + { + criAtomExSoundObject_AddPlayer(this.handle, player.nativeHandle); + } + + /** + * Removes an AtomExPlayer + * Native handle of the AtomExPlayer + * + * Removes the AtomExPlayer from the sound object.
+ * The removed AtomExPlayer is no longer associated with the sound object + * and is no longer affected by the sound object.
+ * Call this function when the AtomExPlayer you are trying to delete is not playing sound.
+ * If an AtomExPlayer that is playing sound is specified, playback is stopped when deleting.
+ *
+ * + * + * + */ + public void DeletePlayer(CriAtomExPlayer player) + { + criAtomExSoundObject_DeletePlayer(this.handle, player.nativeHandle); + } + + /** + * Removes all AtomExPlayers + * + * Removes all the AtomExPlayers associated with the sound object.
+ * The removed AtomExPlayer is no longer associated with the sound object and is no longer + * affected by the sound object.
+ * Call this function when the AtomExPlayer you are trying to delete is not playing sound.
+ * If an AtomExPlayer that is playing sound is specified, playback is stopped when deleting.
+ *
+ * + * + */ + public void DeleteAllPlayers() + { + criAtomExSoundObject_DeleteAllPlayers(this.handle); + } + + #region Internal Members + + ~CriAtomExSoundObject() + { + this.Dispose(); + } + + private IntPtr handle = IntPtr.Zero; + + #endregion + + #region DLL Import + #if !CRIWARE_ENABLE_HEADLESS_MODE + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern IntPtr criAtomExSoundObject_Create(ref Config config, IntPtr work, int work_size); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExSoundObject_Destroy(IntPtr soundObject); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExSoundObject_AddPlayer(IntPtr soundObject, IntPtr player); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExSoundObject_DeletePlayer(IntPtr soundObject, IntPtr player); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExSoundObject_DeleteAllPlayers(IntPtr soundObject); + #else + private static IntPtr criAtomExSoundObject_Create(ref Config config, IntPtr work, int work_size) { return IntPtr.Zero; } + private static void criAtomExSoundObject_Destroy(IntPtr soundObject) { } + private static void criAtomExSoundObject_AddPlayer(IntPtr soundObject, IntPtr player) { } + private static void criAtomExSoundObject_DeletePlayer(IntPtr soundObject, IntPtr player) { } + private static void criAtomExSoundObject_DeleteAllPlayers(IntPtr soundObject) { } + #endif + #endregion +} + +} //namespace CriWare +/** + * @} + */ + +/* --- end of file --- */ diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExSoundObject.cs.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExSoundObject.cs.meta new file mode 100644 index 0000000..35349a4 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExSoundObject.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: cb9d7f6ed0fe0f44da742fbfe48c40ec +timeCreated: 1494479176 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExTween.cs b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExTween.cs new file mode 100644 index 0000000..e96459d --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExTween.cs @@ -0,0 +1,264 @@ +/**************************************************************************** + * + * Copyright (c) 2020 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +using System.Runtime.InteropServices; +using System; + +/*========================================================================== + * CRI Atom Native Wrapper + *=========================================================================*/ + +/** + * \addtogroup CRIATOM_NATIVE_WRAPPER + * @{ + */ + +namespace CriWare { + +/** + * AtomExTween Class + * + * Runs the animation of the parameters by attaching to the player. + * + * + * + * + */ +public class CriAtomExTween : CriDisposable +{ + internal IntPtr nativeHandle { get { return this.handle; } } + + /** + * Type of Tween parameter + */ + public enum ParameterType : System.Int32 + { + /** + * Manipulation of basic parameters such as volume and pitch + * + */ + Basic, + /** + * Manipulating the AISAC control value + */ + Aisac + } + + [StructLayout(LayoutKind.Sequential)] + struct Config + { + public Target target; + public ParameterType parameterType; + [StructLayout(LayoutKind.Explicit)] + public struct Target + { + [FieldOffset(0)] + public CriAtomEx.Parameter parameterId; + [FieldOffset(0)] + public UInt32 aisacIds; + } + } + + /** + * Creates an AtomExTween + * AtomExTween Object + * + * The AtomExTween created by this constructor operates on the volume. + * + */ + public CriAtomExTween() : this(CriAtomEx.Parameter.Volume) { } + + /** + * Creates an AtomExTween (control of basic parameters) + * AtomExTween Object + * Parameter ID + * + */ + public CriAtomExTween(CriAtomEx.Parameter parameterId) : this(ParameterType.Basic, (UInt32)parameterId) { } + + /** + * Creates an AtomExTween (AISAC control) + * AtomExTween Object + * AISAC control ID + */ + public CriAtomExTween(uint aisacId) : this(ParameterType.Aisac, aisacId) { } + + public CriAtomExTween(ParameterType parameterType, UInt32 targetId) + { + /* Initialize Library */ + if (!CriAtomPlugin.IsLibraryInitialized()) + throw new Exception("CriAtomPlugin is not initialized."); + /* aplly config */ + Config config = new Config(); + config.parameterType = parameterType; + config.target.parameterId = (CriAtomEx.Parameter)targetId; + /* create instance */ + handle = criAtomExTween_Create(ref config, IntPtr.Zero, 0); + + CriDisposableObjectManager.Register(this, CriDisposableObjectManager.ModuleType.Atom); + } + + /** + * Destroys the AtomExTween + * + * A reference to the destroyed AtomExTween will occur if this function is excuted
+ * while the AtomExPlayer with the AtomExTween attached is playing audio.
+ * Be sure to execute this function after detaching from the AtomExPlayer.
+ *
+ */ + public override void Dispose() + { + Dispose(true); + } + + /** + * Gets the current values of the parameters of AtomExTween + * The current value of the parameter + */ + public float Value + { + get + { + return criAtomExTween_GetValue(handle); + } + } + + /** + * Gets whether it is changing currently + * Whether the parameter is changing + */ + public bool IsActive + { + get + { + return criAtomExTween_IsActive(handle); + } + } + + /** + * Changes the parameter from the current value to the specified one + * + * Changes the parameter from the current value when called to the specified value over the specified time.
+ * The change curve type is linear.
+ *
+ * Time required for the change (milliseconds) + * The final value after the change + */ + public void MoveTo(ushort durationMs, float value) + { + criAtomExTween_MoveTo(handle, durationMs, value); + } + + /** + * Changes the parameter from the specified value to the current one + * + * Changes the parameter from the specified value to the current value when called over the specified time.
+ * The change curve type is linear.
+ *
+ * Time required for the change (milliseconds) + * The initial value before the change + */ + public void MoveFrom(ushort durationMs, float value) + { + criAtomExTween_MoveFrom(handle, durationMs, value); + } + + /** + * Stops the AtomExTween + * + * Stops the time change of parameters caused by AtomExTween.
+ * The value of the parameter will be its value when stopped.
+ *
+ */ + public void Stop() + { + criAtomExTween_Stop(handle); + } + + /** + * Resets the AtomExTween + * + * Stops the AtomExTween and resets the parameters to their initial values. + * For basic parameters: Initial value of each parameter
+ * For AISAC control values: 0.0
+ *
+ */ + public void Reset() + { + criAtomExTween_Reset(handle); + } + + #region Internal + + ~CriAtomExTween() + { + Dispose(false); + } + + protected virtual void Dispose(bool disposing) + { + CriDisposableObjectManager.Unregister(this); + + if (handle != IntPtr.Zero) + { + criAtomExTween_Destroy(handle); + handle = IntPtr.Zero; + } + + if(disposing) + { + GC.SuppressFinalize(this); + } + } + + IntPtr handle = IntPtr.Zero; + + #endregion + + #region DLL Import +#if !CRIWARE_ENABLE_HEADLESS_MODE + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern IntPtr criAtomExTween_Create(ref Config config, IntPtr work, int work_size); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExTween_Destroy(IntPtr tween); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern Single criAtomExTween_GetValue(IntPtr tween); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExTween_MoveTo(IntPtr tween, UInt16 time_ms, Single value); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExTween_MoveFrom(IntPtr tween, UInt16 time_ms, Single value); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExTween_Stop(IntPtr tween); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExTween_Reset(IntPtr tween); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool criAtomExTween_IsActive(IntPtr tween); +#else + private static IntPtr criAtomExTween_Create(ref Config config, IntPtr work, int work_size) { return IntPtr.Zero; } + private static void criAtomExTween_Destroy(IntPtr tween) { } + private static Single criAtomExTween_GetValue(IntPtr tween) { return 0f; } + private static void criAtomExTween_MoveTo(IntPtr tween, UInt16 time_ms, Single value) { } + private static void criAtomExTween_MoveFrom(IntPtr tween, UInt16 time_ms, Single value) { } + private static void criAtomExTween_Stop(IntPtr tween) { } + private static void criAtomExTween_Reset(IntPtr tween) { } + private static bool criAtomExTween_IsActive(IntPtr tween) { return false; } +#endif + #endregion +} + +} //namespace CriWare +/** + * @} + */ + +/* --- end of file --- */ diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExTween.cs.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExTween.cs.meta new file mode 100644 index 0000000..4ab5859 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExTween.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 37abea4bc599d6d4f8f05e5f7c931644 +timeCreated: 1593511140 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExVoicePool.cs b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExVoicePool.cs new file mode 100644 index 0000000..2b0afd7 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExVoicePool.cs @@ -0,0 +1,568 @@ +/**************************************************************************** + * + * Copyright (c) 2011 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +#if !UNITY_WEBGL + #define CRIATOMEX_SUPPORT_INSERTION_DSP + #define CRIATOMEX_SUPPORT_STANDARD_VOICE_POOL + #define CRIATOMEX_SUPPORT_RAW_PCM_VOICE_POOL +#endif +#if !(UNITY_WEBGL || UNITY_STADIA) + #define CRIATOMEX_SUPPORT_WAVE_VOICE_POOL +#endif + +using System; +using System.Runtime.InteropServices; + +/*========================================================================== + * CRI Atom Native Wrapper + *=========================================================================*/ +/** + * \addtogroup CRIATOM_NATIVE_WRAPPER + * @{ + */ + +namespace CriWare { + +/** + * A class for controlling the Voice Pool. + * + * A class for controlling the Voice Pool.
+ *
+ */ +public abstract class CriAtomExVoicePool : CriDisposable +{ + /* @cond DOXYGEN_IGNORE */ + public const int StandardMemoryAsrVoicePoolId = 0; /**< Standard memory playback Voice Pool ID by ASR */ + public const int StandardStreamingAsrVoicePoolId = 1; /**< Standard streaming playback Voice Pool ID by ASR */ + public const int StandardMemoryNsrVoicePoolId = 2; /**< Standard memory playback Voice Pool ID by NSR */ + public const int StandardStreamingNsrVoicePoolId = 3; /**< Standard streaming playback Voice Pool ID by NSR */ + /* @endcond */ + + /** + * The ID to access the Voice Pool created inside the plug-in + * + */ + public enum VoicePoolId + { + /* 機種共通のボイスプールID */ +#if UNITY_EDITOR || UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX || UNITY_ANDROID || UNITY_IOS || UNITY_TVOS || UNITY_PS3 || UNITY_PS4 || UNITY_PS5 || UNITY_WINRT || UNITY_XBOXONE || UNITY_GAMECORE_XBOXONE || UNITY_GAMECORE_SCARLETT || UNITY_WEBGL || UNITY_SWITCH || UNITY_STADIA || UNITY_STANDALONE_LINUX + StandardMemory = StandardMemoryAsrVoicePoolId, /**< Model standard memory playback Voice Pool ID */ + StandardStreaming = StandardStreamingAsrVoicePoolId, /**< Model standard streaming playback Voice Pool ID */ +#elif UNITY_PSP2 + StandardMemory = StandardMemoryNsrVoicePoolId, /**< Model standard memory playback Voice Pool ID */ + StandardStreaming = StandardStreamingNsrVoicePoolId, /**< Model standard streaming playback Voice Pool ID */ +#else + #error unsupported platform +#endif + HcaMxMemory = 4, /**< HCA-MX memory playback Voice Pool ID */ + HcaMxStreaming = 5, /**< A Voice Pool ID for HCA-MX streaming playback */ + + /* 機種固有のボイスプールID */ +#if UNITY_EDITOR || UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX || UNITY_IOS || UNITY_TVOS || UNITY_PS3 || UNITY_WINRT || UNITY_XBOXONE || UNITY_GAMECORE_XBOXONE || UNITY_GAMECORE_SCARLETT || UNITY_WEBGL || UNITY_SWITCH || UNITY_STADIA || UNITY_STANDALONE_LINUX +#elif UNITY_ANDROID + LowLatencyMemory = StandardMemoryNsrVoicePoolId, /**< [Android] Low latency memory playback Voice Pool ID */ + LowLatencyStreaming = StandardStreamingNsrVoicePoolId, /**< [Android] Low latency streaming playback Voice Pool ID */ + /* @cond excludele */ +#elif UNITY_PSP2 + Atrac9Memory = 6, /**< [VITA] ATRAC9 memory playback Voice Pool ID */ + Atrac9Streaming = 7, /**< [VITA] ATRAC9 streaming playback Voice Pool ID */ +#elif UNITY_PS4 || UNITY_PS5 + Atrac9Memory = 6, /**< [PS4] ATRAC9 memory playback Voice Pool ID */ + Atrac9Streaming = 7, /**< [PS4] ATRAC9 streaming playback Voice Pool ID */ + Audio3dMemory = 8, /**< [PS4] Audio3D memory playback Voice Pool ID */ + Audio3dStreaming = 9, /**< [PS4] Audio3D streaming playback Voice Pool ID */ + /* @endcond */ +#else +#error unsupported platform +#endif + } + + /** + * Pitch shifter DSP operation mode + * + * Specifies the pitch shift processing method (algorithm). + * + * + * + */ + public enum PitchShifterMode : int { + Music = 0, + Vocal = 1, + SoundEffect = 2, + Speech = 3 + }; + + /** + * Structure for representing the usage of Voices in the Voice Pool + * + */ + public struct UsedVoicesInfo + { + public int numUsedVoices; /**< The number of Voices in use */ + public int numPoolVoices; /**< The number of Voices in the Voice Pool */ + } + + /** + * Gets the usage of Voices in the Voice Pool + * Voice Pool ID + * Voice usage + * + * Gets the Voice usage of the specified Voice Pool. + * Use this function only for debugging purposes. + * + * + * + */ + static public UsedVoicesInfo GetNumUsedVoices(VoicePoolId voicePoolId) + { + UsedVoicesInfo info; + CRIWARE3042ECD3((int)voicePoolId, out info.numUsedVoices, out info.numPoolVoices); + return info; + } + + + public IntPtr nativeHandle {get {return this._handle;} } + public uint identifier {get {return this._identifier;} } + public int numVoices {get {return this._numVoices; } } + public int maxChannels {get {return this._maxChannels; } } + public int maxSamplingRate {get {return this._maxSamplingRate; } } + + /** + * Discards the Voice Pool + * + * Discards the Voice Pool object.
+ * Be sure to discard the created object using this API. Otherwise, a resource leak occurs.
+ *
+ */ + public override void Dispose() + { + CriDisposableObjectManager.Unregister(this); + if (this._handle != IntPtr.Zero) { + CriAtomExVoicePool.criAtomExVoicePool_Free(this._handle); + this._handle = IntPtr.Zero; + } + GC.SuppressFinalize(this); + } + + /** + * Gets the usage of Voices in the Voice Pool + * Voice usage + * + * Gets the Voice usage. + * Use this function only for debugging purposes. + * + * + */ + public UsedVoicesInfo GetNumUsedVoices() + { + UsedVoicesInfo info; + if (this._handle != IntPtr.Zero) { + criAtomExVoicePool_GetNumUsedVoices(this._handle, out info.numUsedVoices, out info.numPoolVoices); + } else { + info = new UsedVoicesInfo(); + } + return info; + } + +#if CRIATOMEX_SUPPORT_INSERTION_DSP + /** + * Attaches the time stretch DSP + * + * Adds a time stretch DSP to the Voice Pool. + * This function is a return-on-complete function.
+ * Calling this function blocks the server processing of the Atom library for a while.
+ * If this function is called during sound playback, problems such as sound interruption may occur, + * so call this function at a timing when load fluctuations is accepted such as when switching scenes.
+ *
+ * + */ + public void AttachDspTimeStretch() + { + if (this._handle == IntPtr.Zero) + return; + + ExTimeStretchConfig config; + config.numDsp = this._numVoices; + config.maxChannels = this._maxChannels; + config.maxSamplingRate = this._maxSamplingRate; + config.config.reserved = 0; + criAtomExVoicePool_AttachDspTimeStretch(this._handle, ref config, IntPtr.Zero, 0); + } + + /** + * Attaches the pitch shifter DSP + * Pitch shift mode + * Window size + * The number of overlaps + * + * Adds a pitch shifter DSP to the Voice Pool. + * This function is a return-on-complete function.
+ * Calling this function blocks the server processing of the Atom library for a while.
+ * If this function is called during sound playback, problems such as sound interruption may occur, + * so call this function at a timing when load fluctuations is accepted such as when switching scenes.
+ *
+ * + */ + public void AttachDspPitchShifter(PitchShifterMode mode = PitchShifterMode.Music, int windosSize = 1024, int overlapTimes = 4) + { + if (this._handle == IntPtr.Zero) + return; + + ExPitchShifterConfig config; + config.numDsp = this._numVoices; + config.maxChannels = this._maxChannels; + config.maxSamplingRate = this._maxSamplingRate; + config.config.mode = (int)mode; + config.config.windowSize = windosSize; + config.config.overlapTimes = overlapTimes; + criAtomExVoicePool_AttachDspPitchShifter(this._handle, ref config, IntPtr.Zero, 0); + } + + /** + * Detaches DSP + * + * Removes the DSP added to the Voice Pool. + * This function is a return-on-complete function.
+ * Calling this function blocks the server processing of the Atom library for a while.
+ * If this function is called during sound playback, problems such as sound interruption may occur, + * so call this function at a timing when load fluctuations is accepted such as when switching scenes.
+ *
+ * + * + */ + public void DetachDsp() + { + if (this._handle == IntPtr.Zero) + return; + + criAtomExVoicePool_DetachDsp(this._handle); + } +#endif + + #region Internal Members + + ~CriAtomExVoicePool() + { + Dispose(); + } + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + protected struct PlayerConfig + { + public int maxChannels; + public int maxSamplingRate; + public bool streamingFlag; + public int soundRendererType; + public int decodeLatency; + private IntPtr context; + } + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + protected struct VoicePoolConfig + { + public uint identifier; + public int numVoices; + public PlayerConfig playerConfig; + } + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + private struct PitchShifterConfig { + public int mode; + public int windowSize; + public int overlapTimes; + } + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + private struct ExPitchShifterConfig { + public int numDsp; + public int maxChannels; + public int maxSamplingRate; + public PitchShifterConfig config; + } + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + private struct TimeStretchConfig { + public int reserved; + } + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + private struct ExTimeStretchConfig { + public int numDsp; + public int maxChannels; + public int maxSamplingRate; + public TimeStretchConfig config; + } + + protected IntPtr _handle = IntPtr.Zero; + protected uint _identifier = 0; + protected int _numVoices = 0; + protected int _maxChannels = 0; + protected int _maxSamplingRate = 0; + + #endregion + + #region DLL Import + #if !CRIWARE_ENABLE_HEADLESS_MODE + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void CRIWARE3042ECD3(int voice_pool_id, out int num_used_voices, out int num_pool_voices); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExVoicePool_GetNumUsedVoices(IntPtr pool, out int num_used_voices, out int num_pool_voices); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + public static extern void criAtomExVoicePool_Free(IntPtr pool); + + #if CRIATOMEX_SUPPORT_INSERTION_DSP + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExVoicePool_AttachDspTimeStretch(IntPtr pool, ref ExTimeStretchConfig config, IntPtr work, int work_size) ; + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExVoicePool_AttachDspPitchShifter(IntPtr pool, ref ExPitchShifterConfig config, IntPtr work, int work_size) ; + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExVoicePool_DetachDsp(IntPtr pool); + #endif + #else + private static void CRIWARE3042ECD3(int voice_pool_id, out int num_used_voices, out int num_pool_voices) + { num_used_voices = num_pool_voices = 0; } + private static void criAtomExVoicePool_GetNumUsedVoices(IntPtr pool, out int num_used_voices, out int num_pool_voices) + { num_used_voices = num_pool_voices = 0; } + public static void criAtomExVoicePool_Free(IntPtr pool) { } + #if CRIATOMEX_SUPPORT_INSERTION_DSP + private static void criAtomExVoicePool_AttachDspTimeStretch(IntPtr pool, ref ExTimeStretchConfig config, IntPtr work, int work_size) { } + private static void criAtomExVoicePool_AttachDspPitchShifter(IntPtr pool, ref ExPitchShifterConfig config, IntPtr work, int work_size) { } + private static void criAtomExVoicePool_DetachDsp(IntPtr pool) { } + #endif + #endif + #endregion +} + +#if CRIATOMEX_SUPPORT_STANDARD_VOICE_POOL + +/** + * Standard Voice Pool + */ +public class CriAtomExStandardVoicePool: CriAtomExVoicePool +{ + /** + * Creates an additional standard Voice Pool + * The number of Voices + * Maximum number of channels + * Maximum sampling rate + * Streaming playback flag + * Voice Pool identifier + * Standard Voice Pool + * + * Creates an additional standard Voice Pool.
+ * If you want to play a sound with six or more channels, create a Voice Pool using this API.
+ * If false is specified for streamingFlag, a voice pool for in-memory playback will be created.
+ * If you specify true for streamingFlag, the created voice pool will be capable of streaming playback in addition to in-memory playback.
+ * maxSamplingRate specifies the maximum sampling rate of the materials in the Cue to be played, which uses the voice pool being created.
+ * If the audio pitch is expected to change, please select a maximum sampling rate based on the highest pitch.
+ * If you want to use the time-stretch feature, you need to double the maximum sampling rate.
+ * Be sure to call the Dispose function to destroy the object after the playback is complete.
+ * If you want to explicitly set a particular CriAtomExPlayer to get voices from the created voice pool,
+ * please create the voice pool with a non-zero identifier (0 is the default identifier),
+ * and call the CriAtomExPlayer::SetVoicePoolIdentifier function.
+ *
+ * + */ + public CriAtomExStandardVoicePool(int numVoices, int maxChannels, int maxSamplingRate, bool streamingFlag, uint identifier = 0) + { + this._identifier = identifier; + this._numVoices = numVoices; + this._maxChannels = maxChannels; + this._maxSamplingRate = maxSamplingRate; + + VoicePoolConfig config = new VoicePoolConfig(); + config.identifier = identifier; + config.numVoices = numVoices; + config.playerConfig.maxChannels = maxChannels; + config.playerConfig.maxSamplingRate = maxSamplingRate; + config.playerConfig.streamingFlag = streamingFlag; + config.playerConfig.soundRendererType = (int)CriAtomEx.SoundRendererType.Asr; + config.playerConfig.decodeLatency = 0; + this._handle = criAtomExVoicePool_AllocateStandardVoicePool(ref config, IntPtr.Zero, 0); + if (this._handle == IntPtr.Zero) { + throw new Exception("CriAtomExStandardVoicePool() failed."); + } + + CriDisposableObjectManager.Register(this, CriDisposableObjectManager.ModuleType.Atom); + } + + #region DLL Import + #if !CRIWARE_ENABLE_HEADLESS_MODE + [DllImport(CriWare.Common.pluginName)] + private static extern IntPtr criAtomExVoicePool_AllocateStandardVoicePool(ref VoicePoolConfig config, IntPtr work, int work_size); + #else + private static IntPtr criAtomExVoicePool_AllocateStandardVoicePool(ref VoicePoolConfig config, IntPtr work, int work_size) { return new IntPtr(1); } + #endif + #endregion +} + +#endif + +#if CRIATOMEX_SUPPORT_WAVE_VOICE_POOL + +/** + * Wave Voice Pool + */ +public class CriAtomExWaveVoicePool: CriAtomExVoicePool +{ + /** + * Creates a Wave Voice Pool + * The number of Voices + * Maximum number of channels + * Maximum sampling rate + * Streaming playback flag + * Voice Pool identifier + * Wave Voice Pool + * + * Calling this function pools the Voices that can be played by Wave.
+ * When you play Wave data (or a Cue that contains Wave data) in the AtomExPlayer, + * the AtomExPlayer gets the Voice from the created Wave Voice Pool and plays it.
+ * After playing, be sure to discard the object using the Dispose function.
+ * If you want to explicitly set a specific CriAtomExPlayer to get a Voice from the created Voice Pool, + * create a Voice with a specifying non-zero value as identifier, and call the CriAtomExPlayer::SetVoicePoolIdentifier + * function.
+ *
+ * + */ + public CriAtomExWaveVoicePool(int numVoices, int maxChannels, int maxSamplingRate, bool streamingFlag, uint identifier = 0) + { + this._identifier = identifier; + this._numVoices = numVoices; + this._maxChannels = maxChannels; + this._maxSamplingRate = maxSamplingRate; + + VoicePoolConfig config = new VoicePoolConfig(); + config.identifier = identifier; + config.numVoices = numVoices; + config.playerConfig.maxChannels = maxChannels; + config.playerConfig.maxSamplingRate = maxSamplingRate; + config.playerConfig.streamingFlag = streamingFlag; + config.playerConfig.soundRendererType = (int)CriAtomEx.SoundRendererType.Asr; + config.playerConfig.decodeLatency = 0; + this._handle = criAtomExVoicePool_AllocateWaveVoicePool(ref config, IntPtr.Zero, 0); + if (this._handle == IntPtr.Zero) { + throw new Exception("CriAtomExWaveVoicePool() failed."); + } + + CriDisposableObjectManager.Register(this, CriDisposableObjectManager.ModuleType.Atom); + } + + #region DLL Import + #if !CRIWARE_ENABLE_HEADLESS_MODE + [DllImport(CriWare.Common.pluginName)] + private static extern IntPtr criAtomExVoicePool_AllocateWaveVoicePool(ref VoicePoolConfig config, IntPtr work, int work_size); + #else + private static IntPtr criAtomExVoicePool_AllocateWaveVoicePool(ref VoicePoolConfig config, IntPtr work, int work_size) { return new IntPtr(1); } + #endif + #endregion +} + +#endif + +#if CRIATOMEX_SUPPORT_RAW_PCM_VOICE_POOL + +/** + * RawPCM Voice Pool + */ +public class CriAtomExRawPcmVoicePool: CriAtomExVoicePool +{ + /** + * RawPCM format + * + * The data format to be played back using the RawPCM Voice Pool. + * + * + */ + public enum RawPcmFormat { + Sint16 = 0, + Float32 = 1 + } + + /** + * Creates an RawPCM Voice Pool + * The number of Voices + * Maximum number of channels + * Maximum sampling rate + * RawPCM format + * Voice Pool identifier + * RawPCM Voice Pool + * + * Calling this function pools the Voices that can be played by RawPCM.
+ * When you play RawPCM data (or a Cue that contains RawPCM data) in the AtomExPlayer, + * the AtomExPlayer gets the Voice from the created RawPCM Voice Pool and plays it.
+ * After playing, be sure to discard the object using the Dispose function.
+ * If you want to explicitly set a specific CriAtomExPlayer to get a Voice from the created Voice Pool, + * create a Voice with a specifying non-zero value as identifier, and call the CriAtomExPlayer::SetVoicePoolIdentifier + * function.
+ * Currently, it is not possible to change the format of a RawPCM Voice Pool once created.
+ * Make sure to create it by specifying the format that matches the data to be played.
+ * Even if the number of channels or and sampling rate is specified for CriWare.CriAtomExPlayer , + * playback is done based on the format set to the Voice Pool.
+ *
+ * + */ + public CriAtomExRawPcmVoicePool(int numVoices, int maxChannels, int maxSamplingRate, RawPcmFormat format, uint identifier = 0) + { + this._identifier = identifier; + this._numVoices = numVoices; + this._maxChannels = maxChannels; + this._maxSamplingRate = maxSamplingRate; + + RawPcmVoicePoolConfig config = new RawPcmVoicePoolConfig(); + config.identifier = identifier; + config.numVoices = numVoices; + config.playerConfig.maxChannels = maxChannels; + config.playerConfig.maxSamplingRate = maxSamplingRate; + config.playerConfig.format = format; + config.playerConfig.soundRendererType = (int)CriAtomEx.SoundRendererType.Asr; + config.playerConfig.decodeLatency = 0; + this._handle = criAtomExVoicePool_AllocateRawPcmVoicePool(ref config, IntPtr.Zero, 0); + if (this._handle == IntPtr.Zero) { + throw new Exception("CriAtomExRawPcmVoicePool() failed."); + } + + CriDisposableObjectManager.Register(this, CriDisposableObjectManager.ModuleType.Atom); + } + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + protected struct RawPcmPlayerConfig { + public RawPcmFormat format; + public int maxChannels; + public int maxSamplingRate; + public int soundRendererType; + public int decodeLatency; + private IntPtr context; + } + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + protected struct RawPcmVoicePoolConfig { + public uint identifier; + public int numVoices; + public RawPcmPlayerConfig playerConfig; + } + + #region DLL Import +#if !CRIWARE_ENABLE_HEADLESS_MODE + [DllImport(CriWare.Common.pluginName)] + private static extern IntPtr criAtomExVoicePool_AllocateRawPcmVoicePool(ref RawPcmVoicePoolConfig config, IntPtr work, int work_size); +#else + private static IntPtr criAtomExVoicePool_AllocateRawPcmVoicePool(ref RawPcmVoicePoolConfig config, IntPtr work, int work_size) { return new IntPtr(1); } +#endif + #endregion +} + +#endif + +} //namespace CriWare +/** + * @} + */ + +/* --- end of file --- */ diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExVoicePool.cs.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExVoicePool.cs.meta new file mode 100644 index 0000000..516b1d8 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAtom/NativeClasses/CriAtomExVoicePool.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: a3de78eb9875bb14cab1f26493ba76a0 +timeCreated: 1433816076 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAudioStream.cs b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAudioStream.cs new file mode 100644 index 0000000..a2f5a80 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAudioStream.cs @@ -0,0 +1,82 @@ +using System; +using System.Runtime.InteropServices; + +namespace CriWare { + +public class CriAudioReadStream +{ + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private delegate uint InternalDelegate(IntPtr cbobj, IntPtr data, uint numSamples); + private InternalDelegate internalDelegate; + + public delegate uint Delegate(float[][] buffer, uint numSamples); + + public IntPtr callbackFunction { get; private set; } + public IntPtr callbackPointer { get; private set; } + + public CriAudioReadStream(IntPtr callbackFunction, IntPtr callbackPointer) + { + this.callbackFunction = callbackFunction; + this.callbackPointer = callbackPointer; + } + + public CriAudioReadStream(Delegate callback, int numChannels, int bufferSize = 256) + { + float[][] buffer = new float[numChannels][]; + for (int channel = 0; channel < numChannels; channel++) { + buffer[channel] = new float[bufferSize]; + } + + this.internalDelegate = (IntPtr cbobj, IntPtr data, uint numSamples) => { + if (numSamples > bufferSize) { + numSamples = (uint)bufferSize; + } + numSamples = callback(buffer, numSamples); + for (int channel = 0; channel < numChannels; channel++) { + Marshal.Copy(buffer[channel], 0, Marshal.ReadIntPtr(data, IntPtr.Size * channel), (int)numSamples); + } + return numSamples; + }; + this.callbackFunction = Marshal.GetFunctionPointerForDelegate(this.internalDelegate); + } +} + +public class CriAudioWriteStream +{ + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private delegate uint InternalDelegate(IntPtr cbobj, IntPtr data, uint numSamples); + private InternalDelegate internalDelegate; + + public delegate uint Delegate(float[][] buffer, uint numSamples); + + public IntPtr callbackFunction { get; private set; } + public IntPtr callbackPointer { get; private set; } + + public CriAudioWriteStream(IntPtr callbackFunction, IntPtr callbackPointer) + { + this.callbackFunction = callbackFunction; + this.callbackPointer = callbackPointer; + } + + public CriAudioWriteStream(Delegate callback, int numChannels, int bufferSize = 256) + { + float[][] buffer = new float[numChannels][]; + for (int channel = 0; channel < numChannels; channel++) { + buffer[channel] = new float[bufferSize]; + } + + this.internalDelegate = (IntPtr cbobj, IntPtr data, uint numSamples) => { + if (numSamples > bufferSize) { + numSamples = (uint)bufferSize; + } + for (int channel = 0; channel < numChannels; channel++) { + Marshal.Copy(Marshal.ReadIntPtr(data, IntPtr.Size * channel), buffer[channel], 0, (int)numSamples); + } + numSamples = callback(buffer, numSamples); + return numSamples; + }; + this.callbackFunction = Marshal.GetFunctionPointerForDelegate(this.internalDelegate); + } +} + +} //namespace CriWare \ No newline at end of file diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAudioStream.cs.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAudioStream.cs.meta new file mode 100644 index 0000000..2fc1887 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriAudioStream.cs.meta @@ -0,0 +1,13 @@ +fileFormatVersion: 2 +guid: 7511b720d4a91e0498f5dd6a331065d4 +timeCreated: 1532495291 +licenseType: Free +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriFs.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriFs.meta new file mode 100644 index 0000000..4c81035 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriFs.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 8f2461adc118100409a12f6a2da7aec0 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriFs/CriFs.cs b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriFs/CriFs.cs new file mode 100644 index 0000000..a41f151 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriFs/CriFs.cs @@ -0,0 +1,2760 @@ +/**************************************************************************** + * + * Copyright (c) 2011 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +#pragma warning disable 0414 + +using UnityEngine; +using System; +using System.Runtime.InteropServices; +using System.Runtime.CompilerServices; +using System.Collections; +using System.Collections.Generic; + +/*========================================================================== + * CRI File System Native Wrapper + *=========================================================================*/ +/** + * \addtogroup CRIFS_NATIVE_WRAPPER + * @{ + */ + +namespace CriWare { + +/** + * A module for loading files into memory. + * + * A module for loading files into memory.
+ * By combining with CriWare.CriFsBinder , the content in the CPK file can also be read.
+ *
+ * + */ +public class CriFsLoader : CriDisposable +{ + /** + * A value indicating the loader status. + * + */ + public enum Status + { + Stop, /**< Stopped */ + Loading, /**< Loading */ + Complete, /**< Loading complete */ + Error /**< Error occurred */ + } + + public CriFsLoader() + { + if (!CriFsPlugin.IsLibraryInitialized()) { + throw new Exception("CriFsPlugin is not initialized."); + } + + /* ハンドルの作成 */ + this.handle = IntPtr.Zero; + criFsLoader_Create(out this.handle); + if (this.handle == IntPtr.Zero) { + throw new Exception("criFsLoader_Create() failed."); + } + + CriDisposableObjectManager.Register(this, CriDisposableObjectManager.ModuleType.Fs); + } + + /** + * Discards the loader. + * + * If you discard the loader during the loading process, + * the process may be blocked in this function for a long time.
+ *
+ */ + public override void Dispose() + { + this.Dispose(true); + GC.SuppressFinalize(this); + } + + private void Dispose(bool disposing) + { + CriDisposableObjectManager.Unregister(this); + + /* ハンドルの有無をチェック */ + if (this.handle != IntPtr.Zero) { + /* ハンドルの破棄 */ + criFsLoader_Destroy(this.handle); + this.handle = IntPtr.Zero; + } + + if (disposing) { + if (this.dstGch.IsAllocated) { + this.dstGch.Free(); + } + if (this.srcGch.IsAllocated) { + this.srcGch.Free(); + } + } + } + + /** + * Starts loading data. + * Binder + * File path name + * Offset from the beginning of the file (in bytes) + * Load request size (in bytes) + * Load destination buffer + * + * Starts reading data with the specified binder and file name.
+ * Read loadSize bytes from offset fileOffset in the file.
+ * This function returns immediately.
+ * To get the load completion status, use the CriWare.CriFsLoader::GetStatus function.
+ *
+ * + */ + public void Load(CriFsBinder binder, string path, long fileOffset, long loadSize, byte[] buffer) + { + this.dstGch = GCHandle.Alloc(buffer, GCHandleType.Pinned); + + #if !UNITY_EDITOR && UNITY_PSP2 + criFsLoader_LoadWorkaroundForVITA(this.handle, + (binder != null) ? binder.nativeHandle : IntPtr.Zero, fileOffset, + path, loadSize, this.dstGch.AddrOfPinnedObject(), buffer.Length); + #else + criFsLoader_Load(this.handle, + (binder != null) ? binder.nativeHandle : IntPtr.Zero, path, + fileOffset, loadSize, this.dstGch.AddrOfPinnedObject(), buffer.Length); + #endif + } + + /** + * Starts loading data. + * Binder + * File ID + * Offset from the beginning of the file (in bytes) + * Load request size (in bytes) + * Load destination buffer + * + * Starts reading data with the specified binder and file ID.
+ * Read loadSize bytes from offset fileOffset in the file.
+ * This function returns immediately.
+ * To get the load completion status, use the CriWare.CriFsLoader::GetStatus function.
+ *
+ * + */ + public void LoadById(CriFsBinder binder, int id, long fileOffset, long loadSize, byte[] buffer) + { + this.dstGch = GCHandle.Alloc(buffer, GCHandleType.Pinned); + criFsLoader_LoadById(this.handle, + (binder != null) ? binder.nativeHandle : IntPtr.Zero, id, + fileOffset, loadSize, this.dstGch.AddrOfPinnedObject(), buffer.Length); + } + + /** + * Loads the compressed data into memory without expanding it. + * Binder + * File path name + * Offset from the beginning of the file (in bytes) + * Load request size (in bytes) + * Load destination buffer + * + * Starts reading data with the specified binder and file name.
+ * Read loadSize bytes from offset fileOffset in the file.
+ * Unlike the CriWare.CriFsLoader::Load function, even if the data is compressed, it will load the data in memory without expanding it.
+ * This function returns immediately.
+ * To get the load completion status, use the CriWare.CriFsLoader::GetStatus function.
+ *
+ * + * + * + */ + public void LoadWithoutDecompression(CriFsBinder binder, string path, long fileOffset, long loadSize, byte[] buffer) + { + this.dstGch = GCHandle.Alloc(buffer, GCHandleType.Pinned); + criFsLoader_LoadWithoutDecompression(this.handle, + (binder != null) ? binder.nativeHandle : IntPtr.Zero, path, + fileOffset, loadSize, this.dstGch.AddrOfPinnedObject(), buffer.Length); + } + + /** + * Loads the compressed data into memory without expanding it. + * Binder + * File ID + * Offset from the beginning of the file (in bytes) + * Load request size (in bytes) + * Load destination buffer + * + * Starts reading data with the specified binder and file ID.
+ * Read loadSize bytes from offset fileOffset in the file.
+ * Unlike the CriWare.CriFsLoader::Load function, even if the data is compressed, it will load the data in memory without expanding it.
+ * This function returns immediately.
+ * To get the load completion status, use the CriWare.CriFsLoader::GetStatus function.
+ *
+ * + * + * + */ + public void LoadWithoutDecompressionById(CriFsBinder binder, int id, long fileOffset, long loadSize, byte[] buffer) + { + this.dstGch = GCHandle.Alloc(buffer, GCHandleType.Pinned); + criFsLoader_LoadWithoutDecompressionById(this.handle, + (binder != null) ? binder.nativeHandle : IntPtr.Zero, id, + fileOffset, loadSize, this.dstGch.AddrOfPinnedObject(), buffer.Length); + } + + /** + * Starts decompressing the compressed data place on the memory. + * Compressed data size (in bytes) + * The buffer containing the compressed data + * Size of the expansion destination buffer (in bytes) + * Expansion destination buffer + * + * Expands the compressed data placed on the memory to another memory area.
+ * This function returns immediately.
+ * To get the load completion status, use the criFsLoader_GetStatus function.
+ * If the input data is not compressed, this function copies the input data to the output address as is.
+ * This function supports only CRI proprietary software compression codec.
+ * This function cannot be used to expand the data when using a hardware decoder or + * when using a platform-specific codec.
+ *
+ * + * + * + */ + public void DecompressData(long srcSize, byte[] srcBuffer, long dstSize, byte[] dstBuffer) + { + this.srcGch = GCHandle.Alloc(srcBuffer, GCHandleType.Pinned); + this.dstGch = GCHandle.Alloc(dstBuffer, GCHandleType.Pinned); + criFsLoader_DecompressData(this.handle, this.srcGch.AddrOfPinnedObject(), srcSize, this.dstGch.AddrOfPinnedObject(), dstSize); + } + + /** + * Stops the loading process. + * + * Stops the loading process.
+ *
+ * This function returns immediately.
+ * To get the stopping status, use the CriWare.CriFsLoader::GetStatus function.
+ * Even if this function is called, data transfer to the buffer may continue + * until the loader status CriWare.CriFsLoader::Status changes to Stop.
+ *
+ * + */ + public void Stop() + { + if (this.handle != IntPtr.Zero) { + criFsLoader_Stop(this.handle); + } + } + + /** + * Gets the loader status. + * Status + * + * Gets the loader status.
+ *
+ * + */ + public Status GetStatus() + { + Status status = Status.Stop; + if (this.handle != IntPtr.Zero) { + criFsLoader_GetStatus(this.handle, out status); + } + if (status != Status.Loading) { + if (this.dstGch.IsAllocated) { + this.dstGch.Free(); + } + if (this.srcGch.IsAllocated) { + this.srcGch.Free(); + } + } + return status; + } + + /** + * Sets the unit read size + * Unit read size + * + * Sets the read unit size. + * When processing a read request with large size, CriFsLoader divides it into multiple reads with smaller size and repeats the reads.
+ * It is possible to change the read unit size by using this function.
+ * Cancellation of read request or interrupt of high priority read processing, etc. are processed only at the unit read size boundary.
+ * Therefore, setting a smaller unit size improves the response of I/O processing.
+ * Conversely, if you set a large unit size, the speed of reading files improves.
+ *
+ * + */ + public void SetReadUnitSize(int unit_size) + { + if (this.handle != IntPtr.Zero) { + criFsLoader_SetReadUnitSize(this.handle, unit_size); + } + } + + #region Internal Member + private IntPtr handle; + private GCHandle dstGch; + private GCHandle srcGch; + + ~CriFsLoader() + { + this.Dispose(false); + } + #endregion + + #region DLL Import + #if !CRIWARE_ENABLE_HEADLESS_MODE + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criFsLoader_Create(out IntPtr loader); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criFsLoader_Destroy(IntPtr loader); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criFsLoader_Load(IntPtr loader, IntPtr binder, string path, long offset, long load_size, IntPtr buffer, long buffer_size); + +#if !UNITY_EDITOR && UNITY_PSP2 + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criFsLoader_LoadWorkaroundForVITA(IntPtr loader, IntPtr binder, long offset, string path, long load_size, IntPtr buffer, long buffer_size); +#endif + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criFsLoader_LoadById(IntPtr loader, IntPtr binder, int id, long offset, long load_size, IntPtr buffer, long buffer_size); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criFsLoader_Stop(IntPtr loader); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criFsLoader_GetStatus(IntPtr loader, out Status status); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criFsLoader_SetReadUnitSize(IntPtr loader, long unit_size); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criFsLoader_LoadWithoutDecompression(IntPtr loader, IntPtr binder, string path, long offset, long load_size, IntPtr buffer, long buffer_size); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criFsLoader_LoadWithoutDecompressionById(IntPtr loader, IntPtr binder, int id, long offset, long load_size, IntPtr buffer, long buffer_size); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criFsLoader_DecompressData(IntPtr loader, IntPtr src, long src_size, IntPtr dst, long dst_size); + + #else + private static int criFsLoader_Create(out IntPtr loader) { loader = new IntPtr(1); return 0; } + private static int criFsLoader_Destroy(IntPtr loader) { return 0; } + private static int criFsLoader_Load(IntPtr loader, IntPtr binder, string path, long offset, long load_size, IntPtr buffer, long buffer_size) + { return 0; } +#if !UNITY_EDITOR && UNITY_PSP2 + private static int criFsLoader_LoadWorkaroundForVITA(IntPtr loader, IntPtr binder, long offset, string path, long load_size, IntPtr buffer, long buffer_size) + { return 0; } +#endif + private static int criFsLoader_LoadById(IntPtr loader, IntPtr binder, int id, long offset, long load_size, IntPtr buffer, long buffer_size) + { return 0; } + private static int criFsLoader_Stop(IntPtr loader) { return 0; } + private static int criFsLoader_GetStatus(IntPtr loader, out Status status) { status = Status.Complete; return 0; } + private static int criFsLoader_SetReadUnitSize(IntPtr loader, long unit_size) { return 0; } + private static int criFsLoader_LoadWithoutDecompression(IntPtr loader, IntPtr binder, string path, long offset, long load_size, IntPtr buffer, long buffer_size) + { return 0; } + private static int criFsLoader_LoadWithoutDecompressionById(IntPtr loader, IntPtr binder, int id, long offset, long load_size, IntPtr buffer, long buffer_size) + { return 0; } + private static int criFsLoader_DecompressData(IntPtr loader, IntPtr src, long src_size, IntPtr dst, long dst_size) + { return 0; } + #endif + + #endregion +} + +/** + * A module for installing files. + * + * A module for installing files.
+ * Used to install content on the server to the local storage.
+ * If the network connection times out, CriFsInstaller retries infinitely. + * However, an error occurs and it doesn't retry in the following cases. + * - Network connection timed out while checking the existence of the installation source file + * - The installation source file did not exist + * This class does not determine when to abort the infinite retry.
+ * It is up to the application implementation to decide when to stop infinite retry.
+ * For example, interruption by the following steps is possible. + * -# Get the installation progress using the CriWare.CriFsInstaller::GetProgress function. + * -# After a certain period of time, get the installation progress again. + * -# If the values obtained in step 1. and step 2. are the same, stop the installation using the CriWare.CriFsInstaller::Stop function.
+ *
+ */ +public class CriFsInstaller : CriDisposable +{ + /** + * A value indicating the installer status. + * + */ + public enum Status + { + Stop, /**< Stopped */ + Busy, /**< Installation in progress */ + Complete, /**< Installation complete */ + Error /**< Error occurred */ + } + + private byte[] installBuffer = null; + private GCHandle installBufferGch; + + public CriFsInstaller() + { + if (!CriFsPlugin.IsLibraryInitialized()) { + throw new Exception("CriFsPlugin is not initialized."); + } + + /* ハンドルの作成 */ + this.handle = IntPtr.Zero; + #pragma warning disable 162 + if (CriWare.Common.supportsCriFsInstaller == true) { + criFsInstaller_Create(out this.handle, CopyPolicy.Always); + if (this.handle == IntPtr.Zero) { + throw new Exception("criFsInstaller_Create() failed."); + } else { + CriDisposableObjectManager.Register(this, CriDisposableObjectManager.ModuleType.Fs); + } + } else { + throw new Exception("CriFsInstaller is not supported on this platform"); + } + #pragma warning restore 162 + } + + /** + * Discards the installer. + * + * If you discard the installer during the installation process, + * the process may be blocked in this function for a long time.
+ *
+ */ + public override void Dispose() + { + this.Dispose(true); + GC.SuppressFinalize(this); + } + + private void Dispose(bool disposing) + { + CriDisposableObjectManager.Unregister(this); + + /* ハンドルの破棄 */ + if (this.handle != IntPtr.Zero) { + criFsInstaller_Destroy(this.handle); + this.handle = IntPtr.Zero; + } + + if (disposing) { + /* コピーバッファを解放 */ + if (this.installBuffer != null) { + this.installBufferGch.Free(); + this.installBuffer = null; + } + } + } + + + /** + * Copies the file. + * Binder + * Copy source file path name + * Copy destination file path name + * Install buffer size + * + * Starts copying files.
+ *
+ * This function returns immediately.
+ * To get the copy completion status, use the CriWare.CriFsInstaller::GetStatus function.
+ *
+ * + */ + public void Copy(CriFsBinder binder, string srcPath, string dstPath, int installBufferSize) + { + string copySrcPath = srcPath; + if (copySrcPath.StartsWith("http:") || copySrcPath.StartsWith("https:")) { + /* HTTP I/Oを使用したインストールはセカンダリ HTTP I/O デバイスを使用する */ + copySrcPath = "net2:" + copySrcPath; + } + if (installBufferSize > 0) { + this.installBuffer = new byte[installBufferSize]; + this.installBufferGch = GCHandle.Alloc(this.installBuffer, GCHandleType.Pinned); + criFsInstaller_Copy(this.handle, + (binder != null) ? binder.nativeHandle : IntPtr.Zero, + copySrcPath, dstPath, this.installBufferGch.AddrOfPinnedObject(), this.installBuffer.Length); + } + else { + criFsInstaller_Copy(this.handle, + (binder != null) ? binder.nativeHandle : IntPtr.Zero, + copySrcPath, dstPath, IntPtr.Zero, 0); + } + } + + /** + * Stops the installation process. + * + * Stops the processing.
+ *
+ * This function returns immediately.
+ * Use the CriWare.CriFsInstaller::GetStatus function to get the stop completion status.
+ *
+ * + */ + public void Stop() + { + if (this.handle != IntPtr.Zero) { + criFsInstaller_Stop(this.handle); + } + } + + /** + * Gets the status of the installer. + * Status + * + */ + public Status GetStatus() + { + Status status = Status.Stop; + if (this.handle != IntPtr.Zero) { + criFsInstaller_GetStatus(this.handle, out status); + } + return status; + } + + /** + * Gets the progress of the installation process. + * Progress status + * + * Gets the progress of the process.
+ * It is a 32-bit floating point number in the range from 0.0 to 1.0.
+ *
+ */ + public float GetProgress() + { + float progress = 0.0f; + if(this.handle != IntPtr.Zero) { + criFsInstaller_GetProgress(this.handle, out progress); + } + return progress; + } + + /** + * Periodic execution function + * + * Proceed with the installation process. It should be run regularly.
+ *
+ */ + public static void ExecuteMain() + { + criFsInstaller_ExecuteMain(); + } + + #region Internal Member + IntPtr handle; + enum CopyPolicy + { + Always + } + + ~CriFsInstaller() + { + this.Dispose(false); + } + #endregion + + #region DLL Import + #if !CRIWARE_ENABLE_HEADLESS_MODE + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criFsInstaller_ExecuteMain(); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criFsInstaller_Create(out IntPtr installer, CopyPolicy option); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criFsInstaller_Destroy(IntPtr installer); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criFsInstaller_Copy(IntPtr installer, IntPtr binder, + string src_path, string dst_path, IntPtr buffer, long buffer_size); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criFsInstaller_Stop(IntPtr installer); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criFsInstaller_GetStatus(IntPtr installer, out Status status); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criFsInstaller_GetProgress(IntPtr installer, out float progress); + + #else + private static void criFsInstaller_ExecuteMain() { } + private static int criFsInstaller_Create(out IntPtr installer, CopyPolicy option) { installer = new IntPtr(1); return 0; } + private static int criFsInstaller_Destroy(IntPtr installer) { return 0; } + private static int criFsInstaller_Copy(IntPtr installer, IntPtr binder, + string src_path, string dst_path, IntPtr buffer, long buffer_size) { return 0; } + private static int criFsInstaller_Stop(IntPtr installer) { return 0; } + private static int criFsInstaller_GetStatus(IntPtr installer, out Status status) { status = Status.Complete; return 0; } + private static int criFsInstaller_GetProgress(IntPtr installer, out float progress) { progress = 1.0f; return 0; } + #endif + + #endregion +} + +/** + * A module for accessing the content in a CPK file. + * + * CriFsBinder (binder) is a database module to handle files efficiently.
+ * By binding the CPK file or directory to the binder, + * the content information in the CPK file or directory can be acquired.
+ *
+ */ +public class CriFsBinder : CriDisposable +{ + /** + * A value that indicates the status of the binder. + * + */ + public enum Status + { + None, /**< Stopped */ + Analyze, /**< Binding in progress */ + Complete, /**< Binding completed */ + Unbind, /**< Unbinding in progress */ + Removed, /**< Unbinding complete */ + Invalid, /**< Binding disabled */ + Error /**< Binding failed */ + } + + /** + * Content file information structure + * + * Output information of the CriWare.CriFsBinder::GetContentsFileInfo function.
+ * Information relative to the access of the content of the retrieved CPK file is stored.
+ *
+ * + * + */ + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + public struct ContentsFileInfo { + [MarshalAs(UnmanagedType.LPStr)] + public readonly string directory; /**< Directory name */ + [MarshalAs(UnmanagedType.LPStr)] + public readonly string fileName; /**< File name */ + public uint readSize; /**< Read size (file size) */ + public uint extractSize; /**< Expanded size (same as readSize for uncompressed data) */ + public ulong offset; /**< Offset from the beginning of the CPK file */ + public int fileId; /**< File ID */ + [MarshalAs(UnmanagedType.LPStr)] + string userStr; /**< User string (not supported) */ + + public ContentsFileInfo(byte[] data, int startIndex) + { + if (IntPtr.Size == 4) { + this.directory = Marshal.PtrToStringAnsi(new IntPtr(BitConverter.ToInt32(data, startIndex + 0))); + this.fileName = Marshal.PtrToStringAnsi(new IntPtr(BitConverter.ToInt32(data, startIndex + 4))); + this.readSize = BitConverter.ToUInt32(data, startIndex + 8); + this.extractSize = BitConverter.ToUInt32(data, startIndex + 12); + this.offset = BitConverter.ToUInt64(data, startIndex + 16); + this.fileId = BitConverter.ToInt32(data, startIndex + 24); + this.userStr = null; + } else { + this.directory = Marshal.PtrToStringAnsi(new IntPtr(BitConverter.ToInt64(data, startIndex + 0))); + this.fileName = Marshal.PtrToStringAnsi(new IntPtr(BitConverter.ToInt64(data, startIndex + 8))); + this.readSize = BitConverter.ToUInt32(data, startIndex + 16); + this.extractSize = BitConverter.ToUInt32(data, startIndex + 20); + this.offset = BitConverter.ToUInt64(data, startIndex + 24); + this.fileId = BitConverter.ToInt32(data, startIndex + 32); + this.userStr = null; + } + } + } + + public CriFsBinder() + { + if (!CriFsPlugin.IsLibraryInitialized()) { + throw new Exception("CriFsPlugin is not initialized."); + } + + /* ハンドルの作成 */ + this.handle = IntPtr.Zero; + criFsBinder_Create(out this.handle); + if (this.handle == IntPtr.Zero) { + throw new Exception("criFsBinder_Create() failed."); + } + CriDisposableObjectManager.Register(this, CriDisposableObjectManager.ModuleType.Fs); + } + + /** + * Discard the binder. + * + * If you discard the binder during the binding process or discard the binder without performing the Unbind process, + * the process may be blocked in this function for a long time.
+ *
+ */ + public override void Dispose() + { + this.Dispose(true); + GC.SuppressFinalize(this); + } + + private void Dispose(bool disposing) + { + CriDisposableObjectManager.Unregister(this); + + /* ハンドルの破棄 */ + if (this.handle != IntPtr.Zero) { + criFsBinder_Destroy(this.handle); + this.handle = IntPtr.Zero; + } + } + + /** + * Binds the CPK file. + * A binder to access the CPK file to bind + * Path name of the CPK file to bind + * Bind ID + * + * To use the CPK file, you need to bind the CPK file.
+ * This function binds the CPK file to the binder and returns the bind ID.
+ *
+ * For srcBinder, specify the binder to search for the CPK file.
+ * If srcBinder is set to null, the default device is used.
+ *
+ * If the bind cannot be started, 0 is returned as the bind ID.
+ * If a value other than 0 is returned as the bind ID, internal resources are allocated.
+ * So be sure to unbind the bind ID that is no longer required.
+ * (The CPK file being bound is kept open.)
+ *
+ * This function returns immediately.
+ * Immediately after returning from this function, CPK binding is not completed yet, + * so you cannot access the CPK content file.
+ * CPK will be available after the bound state becomes + * Complete.
+ * You can get the binding status using the CriWare.CriFsBinder::GetStatus function.
+ *
+ * + * + */ + public uint BindCpk(CriFsBinder srcBinder, string path) + { + uint bindId = 0u; + if (this.handle != IntPtr.Zero) { + criFsBinder_BindCpk(this.handle, + (srcBinder != null) ? srcBinder.nativeHandle : IntPtr.Zero, + path, IntPtr.Zero, 0, out bindId); + } + return bindId; + } + + /** + * Binds the directory path. + * The binder to access the directory to be bound + * Path name of the directory to be bound + * + * Binds the directory pathname.
+ * Specify the directory name to bind with an absolute path.
+ *
+ * The system does not check whether the directory exists at the time of binding.
+ * Only the directory path is retained in the binder; + * it does not open the files in the specified directory.
+ * Therefore, unless the bind fails, the bind status of the bind ID is Complete + * when this function returns.
+ *
+ * If the bind cannot be started, 0 is returned as the bind ID.
+ * If a value other than 0 is returned as the bind ID, internal resources are allocated.
+ * So be sure to unbind the bind ID that is no longer required.
+ * This function is a debug function for development support.
+ * If you use this function, the following problems may occur.
+ * - Functions CriWare.CriFsLoader::Load or CriWare.CriFsBinder::GetFileSize may block for a long time.
+ * - When accessing files in the bound directory, stream playback of sound or movie is interrupted.
+ * Be careful not to use this function in the application when final release.
+ * (Convert the data in the directory to a CPK file and bind it using the CriWare.CriFsBinder::BindCpk function, + * or bind all the files in the directory using the CriWare.CriFsBinder::BindFile function.)
+ *
+ * + * + * + * + */ + public uint BindDirectory(CriFsBinder srcBinder, string path) + { + uint bindId = 0u; + if (this.handle != IntPtr.Zero) { + criFsBinder_BindDirectory(this.handle, + (srcBinder != null) ? srcBinder.nativeHandle : IntPtr.Zero, + path, IntPtr.Zero, 0, out bindId); + } + return bindId; + } + + /** + * Binds the file. + * The binder to access the file to be bound + * The path name of the file to be bound + * Bind ID + * + * Binds a file and returns the bind ID.
+ * (Searches and finds the file specified by path from the binder srcBinder.)
+ * If srcBinder is set to null, the default device is used.
+ *
+ * If the bind cannot be started, 0 is returned as the bind ID.
+ * If a value other than 0 is returned as the bind ID, internal resources are allocated.
+ * So be sure to unbind the bind ID that is no longer required.
+ * (The CPK file being bound is kept open.)
+ *
+ * This function returns immediately.
+ * Immediately after returning from this function, file binding is not completed yet, + * so you cannot access the files using the bind ID.
+ * The files will be available after the bound status of + * the bind ID becomes Complete.
+ * You can get the binding status using the CriWare.CriFsBinder::GetStatus function.
+ *
+ * + * + */ + public uint BindFile(CriFsBinder srcBinder, string path) + { + uint bindId = 0u; + + criFsBinder_BindFile(this.handle, + (srcBinder != null) ? srcBinder.nativeHandle : IntPtr.Zero, + path, IntPtr.Zero, 0, out bindId); + return bindId; + } + + /** + * Bind a part of the file so that the part can be treated as a virtual file. + * The binder to access the file to be bound + * The path name of the file to be bound + * Data start position (bytes) + * Data size (bytes) + * Section name + * Bind ID + * + * Binds a part of the file and returns the bind ID.
+ * (Searches and finds the file specified by path from the binder srcBinder.)
+ * If srcBinder is set to null, the default device is used.
+ *
+ * If the bind cannot be started, 0 is returned as the bind ID.
+ * If a value other than 0 is returned as the bind ID, internal resources are allocated.
+ * So be sure to unbind the bind ID that is no longer required.
+ * (The CPK file being bound is kept open.)
+ * (Specify the section name in the path when loading.)
+ *
+ * This function returns immediately.
+ * Immediately after returning from this function, file binding is not completed yet, + * so you cannot access the files using the bind ID.
+ * The files will be available after the bound status of + * the bind ID becomes Complete.
+ * You can get the binding status using the CriWare.CriFsBinder::GetStatus function.
+ *
+ * + * + */ + public uint BindFileSection(CriFsBinder srcBinder, string path, ulong offset, int size, string sectionName) + { + uint bindId = 0u; + if (this.handle != IntPtr.Zero) { + criFsBinder_BindFileSection(this.handle, + (srcBinder != null) ? srcBinder.nativeHandle : IntPtr.Zero, path, + offset, size, sectionName, + IntPtr.Zero, 0, out bindId); + } + return bindId; + } + + /** + * Unbinds the bound content. + * Bind ID + * + * Unbind the bound content.
+ * Specify which content to unbind in the bind ID.
+ * This function is a return-on-complete function.
+ * It closes files as necessary, so it may take several milliseconds + * depending on the execution environment.
+ *
+ * Other bind IDs that depend on the bind ID to be unbound are + * also unbound at the same time (implicit unbinding).
+ * For example, the bind IDs that are binding the content files of the CPK bind ID + * are unbound implicitly when the referencing CPK bind ID is unbound.
+ *
+ * + * + */ + public static void Unbind(uint bindId) + { + if (CriFsPlugin.IsLibraryInitialized()) { + criFsBinder_Unbind(bindId); + } + } + + /** + * Gets the binder status. + * Status + * + */ + public static Status GetStatus(uint bindId) + { + Status status = Status.Removed; + if (CriFsPlugin.IsLibraryInitialized()) { + criFsBinder_GetStatus(bindId, out status); + } + return status; + } + + /** + * Gets the file size. + * Full path of the file + * File size + * + * Gets the file size of the specified file.
+ * Bind IDs whose binding status is Complete are searched.
+ *
+ * If the specified file does not exist, a negative value is returned.
+ * If directories are bound by the CriWare.CriFsBinder::BindDirectory function, + * processing may be blocked for a long time within this function. + *
+ * + */ + public long GetFileSize(string path) + { + long size = -1; + if (this.handle != IntPtr.Zero) { + int err; + err = criFsBinder_GetFileSize(this.handle, path, out size); + if (err != 0) { + return (-1); + } + } + return size; + } + + /** + * Gets the file size. + * File ID + * File size + * + * Gets the file size.
+ * The CPK file with ID information needs to be bound.
+ * Bind IDs whose binding status is Complete are searched.
+ *
+ * If the specified file does not exist, a negative value is returned.
+ *
+ * + */ + public long GetFileSize(int id) + { + long size = -1; + if (this.handle != IntPtr.Zero) { + int err; + err = criFsBinder_GetFileSizeById(this.handle, id, out size); + if (err != 0) { + return (-1); + } + } + return size; + } + + /** + * Gets the CPK content file information. + * Full path of the file + * Content file information + * Whether the acquisition succeeded + * + * Gets the information on the file with the specified file name from the CPK file with ID+ file name information.
+ * The CPK that contains the specified file must be the CPK with ID+ file name information.
+ * If there are multiple files with the same name in the specified binder handle, + * the CPK containing the first file found will be selected.
+ *
+ * + */ + public bool GetContentsFileInfo(string path, out ContentsFileInfo info) + { + using (var mem = new CriStructMemory()) { + int err = criFsBinder_GetContentsFileInfo(this.handle, path, mem.ptr); + info = new CriFsBinder.ContentsFileInfo(mem.bytes, 0); + return (err == 0); + } + } + + /** + * Gets the CPK content file information. + * File ID + * Content file information + * Whether the acquisition succeeded + * + * Gets the information on the file with the specified file ID from the CPK file with ID+ file name information.
+ * The CPK that contains the specified file must be the CPK with ID+ file name information.
+ * If there are multiple files with the same ID in the specified binder handle, + * the CPK containing the first file found will be selected.
+ *
+ * + */ + public bool GetContentsFileInfo(int id, out ContentsFileInfo info) + { + using (var mem = new CriStructMemory()) { + int err = criFsBinder_GetContentsFileInfoById(this.handle, id, mem.ptr); + info = new CriFsBinder.ContentsFileInfo(mem.bytes, 0); + return (err == 0); + } + } + + /** + * Gets the CPK content file information. + * Bind ID + * Start index of the content file from which information is obtained + * The number of content files from which information is obtained + * Content file information array + * Whether the acquisition succeeded + * + * Gets the information for the specified number of files from the specified index from the CPK file with ID+ file name information.
+ * The index is assigned starting from 0 to the content file when creating the CPK.
+ * The maximum value that can be specified for index and numFiles is the total number of files that can be acquired using CriWare.CriFsBinder::GetNumContentsFiles .
+ *
+ * + * + */ + public static bool GetContentsFileInfoByIndex(uint bindId, int index, int numFiles, out ContentsFileInfo[] info) + { + if (index < 0 || numFiles <= 0) { + throw new Exception("Invalid parameters."); + } + + info = new ContentsFileInfo[numFiles]; + using (var mem = new CriStructMemory(numFiles)) { + int err = criFsBinder_GetContentsFileInfoByIndex(bindId, index, mem.ptr, numFiles); + for (int i = 0; i < numFiles; i++) { + info[i] = new CriFsBinder.ContentsFileInfo(mem.bytes, i * Marshal.SizeOf(typeof(CriFsBinder.ContentsFileInfo))); + } + return (err == 0); + } + } + + /** + * Gets the total number of CPK content files. + * Bind ID + * The number of content files + * + * Gets the total number of included files from the CPK file with ID+ file name information.
+ * The return value of this function is the maximum number of content files for obtaining information + * that can be specified in the CriWare.CriFsBinder::GetContentsFileInfoByIndex function for the same bind ID.
+ *
+ * + */ + public static int GetNumContentsFiles(uint bindId) + { + return CRIWAREB3558960(bindId); + } + + /** + * Sets the search priority for a bind ID. + * Bind ID + * Priority + * + * Sets the search priority in the binder for the bind ID.
+ * The lowest priority is 0, and the higher the value, the higher the search priority.
+ * For bind IDs with the same priority, the one bound first is found first.
+ * If no priority is set, the default priority is 0.
+ * Bind IDs whose binding status is Complete are searched.
+ *
+ */ + public static void SetPriority(uint bindId, int priority) + { + if (CriFsPlugin.IsLibraryInitialized()) { + criFsBinder_SetPriority(bindId, priority); + } + } + + public IntPtr nativeHandle { + get { return this.handle; } + } + + #region Internal Member + private IntPtr handle; + + ~CriFsBinder() + { + this.Dispose(false); + } + #endregion + + #region DLL Import + #if !CRIWARE_ENABLE_HEADLESS_MODE + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern uint criFsBinder_Create(out IntPtr binder); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern uint criFsBinder_Destroy(IntPtr binder); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern uint criFsBinder_BindCpk(IntPtr binder, + IntPtr srcBinder, string path, IntPtr work, int worksize, out uint bindId); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern uint criFsBinder_BindDirectory(IntPtr binder, + IntPtr srcBinder, string path, IntPtr work, int worksize, out uint bindId); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern uint criFsBinder_BindFile(IntPtr binder, + IntPtr srcBinder, string path, IntPtr work, int worksize, out uint bindId); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern uint criFsBinder_BindFileSection(IntPtr binder, + IntPtr srcBinder, string path, ulong offset, int size, string sectionName, + IntPtr work, int worksize, out uint bindId); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criFsBinder_Unbind(uint bindId); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criFsBinder_GetStatus(uint bindId, out Status status); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criFsBinder_GetFileSize(IntPtr binder, string path, out long size); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criFsBinder_GetFileSizeById(IntPtr binder, int id, out long size); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criFsBinder_SetPriority(uint bindId, int priority); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criFsBinder_GetContentsFileInfo(IntPtr binder, string path, IntPtr info); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criFsBinder_GetContentsFileInfoById(IntPtr binder, int id, IntPtr info); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criFsBinder_GetContentsFileInfoByIndex(uint id, int index, IntPtr info, int num); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int CRIWAREB3558960(uint id); + + #else + private static uint criFsBinder_Create(out IntPtr binder) { binder = new IntPtr(1); return 0u; } + private static uint criFsBinder_Destroy(IntPtr binder) { return 0u; } + private static uint criFsBinder_BindCpk(IntPtr binder, + IntPtr srcBinder, string path, IntPtr work, int worksize, out uint bindId) { bindId = 0u; return 0u; } + private static uint criFsBinder_BindDirectory(IntPtr binder, + IntPtr srcBinder, string path, IntPtr work, int worksize, out uint bindId) { bindId = 0u; return 0u; } + private static uint criFsBinder_BindFile(IntPtr binder, + IntPtr srcBinder, string path, IntPtr work, int worksize, out uint bindId) { bindId = 0u; return 0u; } + private static uint criFsBinder_BindFileSection(IntPtr binder, + IntPtr srcBinder, string path, ulong offset, int size, string sectionName, + IntPtr work, int worksize, out uint bindId) { bindId = 0u; return 0u; } + private static int criFsBinder_Unbind(uint bindId) { return 0; } + private static int criFsBinder_GetStatus(uint bindId, out Status status) { status = Status.Complete; return 0; } + private static int criFsBinder_GetFileSize(IntPtr binder, string path, out long size) { size = 0; return 0; } + private static int criFsBinder_GetFileSizeById(IntPtr binder, int id, out long size) { size = 0; return 0; } + private static int criFsBinder_SetPriority(uint bindId, int priority) { return 0; } + private static int criFsBinder_GetContentsFileInfo(IntPtr binder, string path, IntPtr info) { return 0; } + private static int criFsBinder_GetContentsFileInfoById(IntPtr binder, int id, IntPtr info) { return 0; } + private static int criFsBinder_GetContentsFileInfoByIndex(uint id, int index, IntPtr info, int num) { return 0; } + private static int CRIWAREB3558960(uint id) { return 0; } + #endif + + #endregion +} + +} //namespace CriWare +/** + * @} + */ + + +/*========================================================================== + * CRI File System Unity Component + *=========================================================================*/ +/** + * \addtogroup CRIFS_UNITY_COMPONENT + * @{ + */ + +namespace CriWare { + +/** + * A module for checking the progress or getting the result of the asynchronous process. + * + * This module is used to check the progress from - or obtain the results of - the asynchronous processing.
+ * When the asynchronous processing is completed, the value of "isDone" will be set to true.
+ * If an error occured during the asynchronous processing, information about the error will be stored in "error".
+ *
+ */ +public class CriFsRequest : CriDisposable +{ + public delegate void DoneDelegate(CriFsRequest request); + + /** + * Delegate when processing is complete. + * + * This parameter is used to determine whether asynchronous processing has completed.
+ * During asynchronous processing, the value of isDone is false.
+ * Once asynchronous processing is complete, the value of isDone is true.
+ *
+ */ + public DoneDelegate doneDelegate { get; protected set; } + + /** + * Whether the processing is complete. + * + * This parameter is used to determine whether asynchronous processing has completed.
+ * During asynchronous processing, the value of isDone is false.
+ * Once asynchronous processing is complete, the value of isDone is true.
+ *
+ */ + public bool isDone { get; private set; } + + /** + * Error information. + * + * A parameter to check whether an error occurred during asynchronous process.
+ * If the asynchronous process completes successfully, the value of error is null.
+ * If an error occurs during asynchronous process, the error information is stored.
+ *
+ */ + public string error { get; protected set; } + + /** + * Discard information. + * + * A parameter to check if the request was discarded.
+ *
+ */ + public bool isDisposed { get; protected set; } + + + public override void Dispose() + { + if (!this.isDisposed) { + this.Dispose(true); + this.isDisposed = true; + System.GC.SuppressFinalize(this); + } + } + + /** + * Stops the asynchronous process. + * + * Stops the asynchronous process.
+ *
+ */ + virtual public void Stop() + { + } + + /** + * Waits for the completion of asynchronous process. + * + * Suspend the execution of coroutine until asynchronous process is complete.
+ *
+ * This function can be used only in the yield statement in the coroutine.
+ * Specifically, it should be used in the following format.
+ * : + * // 非同期処理の開始 + * CriFsRequest request = CriFsUtility.? + * + * // 非同期処理の完了まで待機 + * yield return request.WaitForDone(this); + * : + * + *
+ *
+ */ + public YieldInstruction WaitForDone(MonoBehaviour mb) + { + return mb.StartCoroutine(CheckDone()); + } + + #region Internal Methods + virtual protected void Dispose(bool disposing) + { + } + + virtual public void Update() + { + } + + protected void Done() + { + this.isDone = true; + if (this.doneDelegate != null) { + this.doneDelegate(this); + } + } + + IEnumerator CheckDone() + { + while (!this.isDone) { + yield return null; + } + } + + ~CriFsRequest() + { + if (!this.isDisposed) { + this.Dispose(false); + this.isDisposed = true; + } + } + #endregion +} + +/** + * A module for checking the progress or getting the result of the loading process. + * + * A module for checking the progress or getting the result of the loading process.
+ * It is returned as the return value of the CriWare.CriFsUtility::LoadFile function.
+ *
+ * The value of isDone becomes true when the loading process completes.
+ * Load result is stored in bytes.
+ * If an error occurs during the loading process, the error information is stored in error.
+ *
+ * + */ +public class CriFsLoadFileRequest : CriFsRequest +{ + /** + * The path to the file to be loaded. + * + * The path to the file to be loaded.
+ * The path specified when calling the CriWare.CriFsUtility::LoadFile function is stored.
+ *
+ * + */ + public string path { get; private set; } + + /** + * A buffer that stores load result. + * + * A buffer that stores the load result.
+ * If the loading process is stopped using the CriWare.CriFsLoadFileRequest::Stop function + * or if an error occurs during loading, the value is null.
+ *
+ */ + public byte[] bytes { get; private set; } + + #region Internal Methods + + public CriFsLoadFileRequest(CriFsBinder srcBinder, string path, CriFsRequest.DoneDelegate doneDelegate, int readUnitSize) + { + /* パスの保存 */ + this.path = path; + + /* 完了コールバック指定 */ + this.doneDelegate = doneDelegate; + + /* readUnitSizeの保存 */ + this.readUnitSize = readUnitSize; + + /* ファイルのバインド要求 */ + if (srcBinder == null) { + this.newBinder = new CriFsBinder(); + this.refBinder = this.newBinder; + this.bindId = this.newBinder.BindFile(srcBinder, path); + this.phase = Phase.Bind; + } else { + this.newBinder = null; + this.refBinder = srcBinder; + this.fileSize = srcBinder.GetFileSize(path); + if (this.fileSize < 0) { + this.phase = Phase.Error; + } else { + this.phase = Phase.Load; + } + } + + CriDisposableObjectManager.Register(this, CriDisposableObjectManager.ModuleType.Fs); + } + + override protected void Dispose(bool disposing) + { + CriDisposableObjectManager.Unregister(this); + + /* ローダの破棄 */ + if (this.loader != null) { + this.loader.Dispose(); + this.loader = null; + } + + /* バインダの破棄 */ + if (this.newBinder != null) { + this.newBinder.Dispose(); + this.newBinder = null; + } + + /* メモリの解放 */ + this.bytes = null; + } + + public override void Stop() + { + /* ローダに停止要求を発行 */ + if (this.phase == Phase.Load) { + if (this.loader != null) { + this.loader.Stop(); + } + } + } + + public override void Update() + { + if (this.phase == Phase.Bind) { + this.UpdateBinder(); + } + if (this.phase == Phase.Load) { + this.UpdateLoader(); + } + if (this.phase == Phase.Error) { + this.OnError(); + } + } + + private void UpdateBinder() + { + /* バインダのステータスをチェック */ + CriFsBinder.Status binderStatus = CriFsBinder.GetStatus(this.bindId); + if (binderStatus == CriFsBinder.Status.Analyze) { + /* バインド中は何もしない */ + return; + } + + switch (binderStatus) { + /* バインド完了 */ + case CriFsBinder.Status.Complete: + this.fileSize = this.refBinder.GetFileSize(this.path); + break; + + /* 上記以外はエラー扱い */ + default: + this.fileSize = -1; + break; + } + + /* エラーチェック */ + if (this.fileSize < 0) { + /* エラー状態に遷移してそっちで後始末 */ + this.phase = Phase.Error; + return; + } + + /* フェーズの更新 */ + this.phase = Phase.Load; + } + + private void UpdateLoader() + { + /* ローダが確保済みかどうかチェック */ + if (this.loader == null) { + /* ロード要求の発行 */ + this.loader = new CriFsLoader(); + this.loader.SetReadUnitSize(readUnitSize); + this.bytes = new byte[this.fileSize]; + this.loader.Load(this.refBinder, this.path, 0, this.fileSize, this.bytes); + } + + /* ローダのステータスをチェック */ + CriFsLoader.Status loaderStatus = this.loader.GetStatus(); + if (loaderStatus == CriFsLoader.Status.Loading) { + /* ロード中は何もしない */ + return; + } + + /* エラーチェック */ + switch (loaderStatus) { + case CriFsLoader.Status.Stop: + this.bytes = null; + break; + + case CriFsLoader.Status.Error: + /* エラーに遷移 */ + this.phase = Phase.Error; + return; + + default: + break; + } + + /* フェーズの更新 */ + this.phase = Phase.Done; + + /* ローダの破棄 */ + this.loader.Dispose(); + this.loader = null; + + /* バインダの破棄 */ + if (this.newBinder != null) { + this.newBinder.Dispose(); + this.newBinder = null; + } + + /* 処理の完了を通知 */ + this.Done(); + } + + private void OnError() + { + this.bytes = null; + this.error = "Error occurred."; + this.refBinder = null; + /* バインダの破棄 */ + if (this.newBinder != null) { + this.newBinder.Dispose(); + this.newBinder = null; + } + /* ローダの破棄 */ + if (this.loader != null) { + this.loader.Dispose(); + this.loader = null; + } + this.phase = Phase.Done; + this.Done(); + + return; + } + + #endregion + + #region Internal Fields + + private enum Phase + { + Stop, + Bind, + Load, + Done, + Error + }; + + private Phase phase = Phase.Stop; + private CriFsBinder refBinder = null; + private CriFsBinder newBinder = null; + private uint bindId = 0; + private CriFsLoader loader = null; + private int readUnitSize = 0; + private long fileSize = 0; + + #endregion +} + +/** + * A module for checking the progress of Asset Bundle processing and acquiring the result of Asset Bundle processing. + * + * A module for checking the progress of Asset Bundle processing and acquiring the result of Asset Bundle processing.
+ * It is returned as the return value of the CriWare.CriFsUtility::LoadAssetBundle function.
+ *
+ * The value of isDone becomes true when the Asset Bundle process completes.
+ * Asset Bundle result is stored in assetBundle.
+ * If an error occurs during the Asset Bundle process, the error information is stored in error.
+ *
+ * + */ +public class CriFsLoadAssetBundleRequest : CriFsRequest +{ + /** + * The path to the Asset Bundle file to be loaded. + * + * The path to the Asset Bundle file to be loaded.
+ * The path specified when calling the CriWare.CriFsUtility::LoadAssetBundle function is stored.
+ *
+ * + */ + public string path { get; private set; } + + /** + * The Asset Bundle that is the result of loading. + * + * An instance of Asset Bundle that stores the loading result.
+ * If the loading process is stopped using the CriWare.CriFsLoadFileRequest::Stop function + * or if an error occurs during loading, the value is null.
+ *
+ */ + public AssetBundle assetBundle { get; private set; } + + #region Internal Methods + + public CriFsLoadAssetBundleRequest(CriFsBinder binder, string path, int readUnitSize) + { + this.path = path; + this.loadFileReq = CriFsUtility.LoadFile(binder, path, readUnitSize); + CriDisposableObjectManager.Register(this, CriDisposableObjectManager.ModuleType.Fs); + } + + override public void Update() + { + if (this.loadFileReq != null) { + if (this.loadFileReq.isDone) { + if (this.loadFileReq.error != null) { + this.error = "Error occurred."; + this.Done(); + } else { +#if UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7 || UNITY_5_0 || UNITY_5_1 || UNITY_5_2 + this.assetBundleReq = AssetBundle.CreateFromMemory(this.loadFileReq.bytes); +#else + this.assetBundleReq = AssetBundle.LoadFromMemoryAsync(this.loadFileReq.bytes); +#endif + } + this.loadFileReq.Dispose(); + this.loadFileReq = null; + } + } else if (this.assetBundleReq != null) { + if (this.assetBundleReq.isDone) { + this.assetBundle = this.assetBundleReq.assetBundle; + this.Done(); + } + } else { + this.Done(); + } + } + + override protected void Dispose(bool disposing) + { + CriDisposableObjectManager.Unregister(this); + + /* ローダの破棄 */ + if (this.loadFileReq != null) { + this.loadFileReq.Dispose(); + this.loadFileReq = null; + } + } + + #endregion + + #region Internal Fields + + private CriFsLoadFileRequest loadFileReq; + private AssetBundleCreateRequest assetBundleReq; + + #endregion +} + +/** + * A module for checking the progress or getting the result of the installation process. + * + * A module for checking the progress or getting the result of the installation process.
+ * It is returned as the return value of the CriWare.CriFsUtility::Install function.
+ *
+ * The value of isDone becomes true when the installation process completes.
+ * If an error occurs during the installation process, the error information is stored in the error.
+ * This function retries infinitely unless you explicitly call CriWare.CriFsInstallRequest::Stop .
+ * When performing timeout handling, monitor the value of CriWare.CriFsInstallRequest::progress , and if the value does not change + * even after sufficient time, stop the installation process using CriWare.CriFsInstallRequest::Stop etc.
+ *
+ * + */ +public class CriFsInstallRequest : CriFsRequest +{ + /** + * Installation source file path. + * + * The file path of the installation source.
+ * The path specified when calling the CriWare.CriFsUtility::Install function is stored.
+ *
+ * + */ + public string sourcePath { get; protected set; } + + /** + * Installation destination file path. + * + * The file path of the installation destination.
+ * The path specified when calling the CriWare.CriFsUtility::Install function is stored.
+ *
+ * + */ + public string destinationPath { get; protected set; } + + /** + * The progress of the installation process. + * Progress status + * + * Gets the progress of the process.
+ * Progress is a 32 bit floating point number in the range of 0.0 to 1.0.
+ *
+ * When the process is stopped using the CriWare.CriFsInstallRequest::Stop function, the progress at the time of the stop is saved.
+ * If an error occurs during the installation process, the value is negative.
+ * The value is updated when the buffer of size CriWareInitializer.fileSystemConfig.installBufferSize + * is filled.
+ * If the size of the installation buffer is too large, the value is updated less frequently, + * even though the installation is advancing.
+ * Be careful about the size of the installation buffer when performing timeout processing etc.
+ *
+ */ + public float progress { get; protected set; } +} + + +public class CriFsInstallRequestLegacy : CriFsInstallRequest +{ + /** + * Stops the installation process. + * + * Stops the processing.
+ *
+ * This function returns immediately.
+ * It may take up to 20 seconds until the installation process stops after calling this function.
+ * When the installation process stops, the CriWare.CriFsInstallRequest::WaitForDone function running as a coroutine returns.
+ *
+ */ + public override void Stop() + { + if (this.installer != null) { + this.installer.Stop(); + } + } + + #region Internal Methods + + public CriFsInstallRequestLegacy(CriFsBinder srcBinder, string srcPath, string dstPath, CriFsRequest.DoneDelegate doneDelegate, int installBufferSize) + { + this.sourcePath = srcPath; + this.destinationPath = dstPath; + this.doneDelegate = doneDelegate; + this.progress = 0.0f; + this.installer = new CriFsInstaller(); + this.installer.Copy(srcBinder, srcPath, dstPath, installBufferSize); + CriDisposableObjectManager.Register(this, CriDisposableObjectManager.ModuleType.Fs); + } + + override public void Update() + { + /* インストーラの有無をチェック */ + if (this.installer == null) { + return; + } + + /* 進捗状況の更新 */ + this.progress = this.installer.GetProgress(); + + /* ステータスのチェック */ + CriFsInstaller.Status status = this.installer.GetStatus(); + if (status == CriFsInstaller.Status.Busy) { + return; + } + + /* エラーチェック */ + if (status == CriFsInstaller.Status.Error) { + this.progress = -1.0f; + this.error = "Error occurred."; + } + + /* インストーラの破棄 */ + this.installer.Dispose(); + this.installer = null; + + /* 処理の完了を通知 */ + this.Done(); + } + + #endregion + + #region Internal Fields + + private CriFsInstaller installer; + + override protected void Dispose(bool disposing) + { + CriDisposableObjectManager.Unregister(this); + + if (this.installer != null) { + this.installer.Dispose(); + this.installer = null; + } + } + + #endregion +} + + +/** + * A module for checking the progress or getting the result of the installation process. + * + * A module for checking the progress or getting the result of the installation process.
+ * It is returned as the return value of the CriWare.CriFsUtility::WebInstall function.
+ *
+ * The value of isDone becomes true when the installation process completes.
+ * If an error occurs during the installation process, the error information is stored in error.
+ *
+ * + */ +public class CriFsWebInstallRequest : CriFsInstallRequest +{ + /** + * Stops the installation process. + * + * Stops the processing.
+ *
+ * This function returns immediately.
+ * It may take up to 20 seconds until the installation process stops after calling this function.
+ * When the installation process stops, the CriWare.CriFsWebInstallRequest::WaitForDone + * function running as a coroutine returns.
+ *
+ */ + public override void Stop() + { + if (this.installer != null) { + this.installer.Stop(); + } + } + + public bool GetCRC32(out uint ret_val){ + ret_val = crc32; + return crc32_set; + } + + #region Internal Methods + + public CriFsWebInstallRequest(string srcPath, string dstPath, CriFsRequest.DoneDelegate doneDelegate) + { + this.sourcePath = srcPath; + this.destinationPath = dstPath; + this.doneDelegate = doneDelegate; + this.progress = 0.0f; + this.installer = new CriFsWebInstaller(); + System.IO.File.Delete(dstPath); + this.installer.Copy(srcPath, dstPath); + CriDisposableObjectManager.Register(this, CriDisposableObjectManager.ModuleType.Fs); + } + + override public void Update() + { + /* インストーラの有無をチェック */ + if (this.installer == null) { + return; + } + + var statusInfo = this.installer.GetStatusInfo(); + + /* 進捗状況の更新 */ + this.progress = (float)statusInfo.receivedSize / ((statusInfo.contentsSize > 0) ? statusInfo.contentsSize : 1); + + /* ステータスのチェック */ + if (statusInfo.status != CriFsWebInstaller.Status.Busy) { + /* エラーチェック */ + if (statusInfo.status == CriFsWebInstaller.Status.Error) { + this.progress = -1.0f; + this.error = "[CriFsWebInstallerError]" + statusInfo.error.ToString(); + } + + /* CRCを取得する */ + if (CriFsWebInstaller.isCrcEnabled && statusInfo.status == CriFsWebInstaller.Status.Complete) { + this.crc32_set = this.installer.GetCRC32(out this.crc32); + } + + /* インストーラの破棄 */ + this.installer.Dispose(); + this.installer = null; + + /* 処理の完了を通知 */ + this.Done(); + } + } + + #endregion + + #region Internal Fields + + private CriFsWebInstaller installer; + private uint crc32 = 0; + private bool crc32_set = false; + + override protected void Dispose(bool disposing) + { + CriDisposableObjectManager.Unregister(this); + + if (this.installer != null) { + this.installer.Dispose(); + this.installer = null; + } + } + + #endregion +} + +/** + * A module for checking the progress or getting the result of the binding process. + * + * This module is used to check the progress and obtain the result of the binding process,
+ * which is returned by the CriFsUtility::BindCpk function.
+ *
+ * Once the binding process is completed, the value of isDone becomes true.
+ * If an error occurs during the binding process, the error information will be stored in the "error" argument.
+ *
+ * + */ +public class CriFsBindRequest : CriFsRequest +{ + public enum BindType + { + Cpk, + Directory, + File + } + + /** + * The path of the file to be bound. + * + * The path of the file to bind.
+ * The path specified when calling the CriWare.CriFsUtility::BindCpk function etc. is stored.
+ *
+ * + * + * + */ + public string path { get; private set; } + + /** + * The ID which identifies the binding process. + * + * The ID which identifies the binding process.
+ * It is used to release only a specific binding after multi-binding.
+ *
+ * + */ + public uint bindId { get; private set; } + + public CriFsBindRequest(BindType type, CriFsBinder targetBinder, CriFsBinder srcBinder, string path) + { + /* パスの保存 */ + this.path = path; + + /* バインド種別のチェック */ + switch (type) { + case BindType.Cpk: + this.bindId = targetBinder.BindCpk(srcBinder, path); + break; + + case BindType.Directory: + this.bindId = targetBinder.BindDirectory(srcBinder, path); + break; + + case BindType.File: + this.bindId = targetBinder.BindFile(srcBinder, path); + break; + + default: + throw new Exception("Invalid bind type."); + } + + CriDisposableObjectManager.Register(this, CriDisposableObjectManager.ModuleType.Fs); + } + + public override void Stop() + { + } + + override public void Update() + { + /* バインド処理中かどうかチェック */ + if (this.isDone) { + /* バインド処理中以外は何もしない */ + return; + } + + /* ステータスのチェック */ + CriFsBinder.Status status = CriFsBinder.GetStatus(this.bindId); + if (status == CriFsBinder.Status.Analyze) { + return; + } + + /* エラーチェック */ + if (status == CriFsBinder.Status.Error) { + this.error = "Error occurred."; + } + + /* 完了の通知 */ + this.Done(); + } + + override protected void Dispose(bool disposing) + { + CriDisposableObjectManager.Unregister(this); + } +} + +/** + * A utility class for easily binding CPK files or loading files. + * + * A utility class for easily binding CPK files or loading files.
+ *
+ */ +public static class CriFsUtility +{ + /** + * The default read unit size for each loading request. + * + * The default for the last argument of each load request.
+ *
+ * + * + * + */ + public const int DefaultReadUnitSize = (1024 * 1024); // 1.0 Mb + + /** + * Starts loading the file. + * File path + * Read unit size of the CriFsLoader used internal + * CriFsLoadFileRequest + * + * Starts reading the specified file.
+ *
+ * This function returns immediately.
+ * You should check CriWare.CriFsLoadFileRequest::isDone to check the completion of the loading.
+ * If an error occurs during the loading process, the error information is stored in CriWare.CriFsLoadFileRequest::error .
+ * When loading the data in the CPK file, + * it is necessary to use CriWare.CriFsUtility::LoadFile instead of this function + * to specify the binder from which to load the data.
+ *
+ * You can also load the file from network by specifying a URL in the path.
+ * // crimot.comからFMPRO_Intro_e.txtをダウンロード + * CriFsLoadFileRequest request = CriFsUtility.LoadFile( + * "http://crimot.com/sdk/sampledata/crifilesystem/FMPRO_Intro_e.txt"); + * + *
+ *
+ * The code to load a file using the CriWare.CriFsUtility::LoadFile function is as follows.
+ * IEnumerator UserLoadFile(string path) + * { + * // ファイルの読み込みを開始 + * CriFsLoadFileRequest request = CriFsUtility.LoadFile(path); + * + * // 読み込み完了を待つ + * yield return request.WaitForDone(this); + * + * // エラーチェック + * if (request.error != null) { + * // エラー発生時の処理 + * … + * yield break; + * } + * + * // 備考)ロードされたファイルの内容は request.bytes 内に格納されています。 + * } + * + *
To load data under the StreamingAssets folder, + * concatenate CriWare::Common::streamingAssetsPath with the file path. + * string path = Path.Combine(CriWare.Common.streamingAssetsPath, "sample_text.txt"); + * CriFsLoadFileRequest request = CriFsUtility.LoadFile(path); + *
+ * + * + */ + public static CriFsLoadFileRequest LoadFile(string path, int readUnitSize = DefaultReadUnitSize) + { + return CriFsServer.instance.LoadFile(null, path, null, readUnitSize); + } + public static CriFsLoadFileRequest LoadFile(string path, CriFsRequest.DoneDelegate doneDelegate, int readUnitSize = DefaultReadUnitSize) + { + return CriFsServer.instance.LoadFile(null, path, doneDelegate, readUnitSize); + } + + /** + * Starts loading the file. + * Binder + * File path + * Read unit size of the CriFsLoader used internal + * CriFsLoadFileRequest + * + * Begins loading the bound file.
+ *
+ * This function returns immediately.
+ * You should check CriWare.CriFsLoadFileRequest::isDone to check the completion of the loading.
+ * If an error occurs during the loading process, the error information is stored in CriWare.CriFsLoadFileRequest::error .
+ * Same as the CriWare.CriFsUtility::LoadFile function, except that the binder is specified as the first argument.
+ *
+ * + * + */ + public static CriFsLoadFileRequest LoadFile(CriFsBinder binder, string path, int readUnitSize = DefaultReadUnitSize) + { + return CriFsServer.instance.LoadFile(binder, path, null, readUnitSize); + } + + /** + * Starts loading the Asset Bundle file. + * File path + * Read unit size of the CriFsLoader used internal + * CriFsLoadAssetBundleRequest + * + * Starts loading the specified Asset Bundle file.
+ *
+ * This function returns immediately.
+ * You should check CriWare.CriFsLoadAssetBundleRequest::isDone to check the completion of the loading.
+ * If an error occurs during the loading process, the error information is stored in CriWare.CriFsLoadFileRequest::error .
+ * When loading the asset data in the CPK file, + * it is necessary to use CriWare.CriFsUtility::LoadAssetBundle instead of this function + * to specify the binder from which to load the data.
+ *
+ * You can also load the file from network by specifying a URL in the path.
+ * // crimot.comからCharaMomo.unity3dをダウンロード + * CriFsLoadFileRequest request = CriFsUtility.LoadAssetBundle( + * "http://crimot.com/sdk/sampledata/crifilesystem/CharaMomo.unity3d"); + * + *
+ *
+ * The code to load an asset bundle using the CriWare.CriFsUtility::LoadAssetBundle function is as follows.
+ * IEnumerator UserLoadAssetBundle(string path) + * { + * // アセットバンドルの読み込みを開始 + * CriFsLoadAssetBundleRequest request = CriFsUtility.LoadAssetBundle(path); + * + * // 読み込み完了を待つ + * yield return request.WaitForDone(this); + * + * // エラーチェック + * if (request.error != null) { + * // エラー発生時の処理 + * … + * yield break; + * } + * + * // インスタンスの作成 + * var obj = GameObject.Instantiate(request.assetBundle.mainAsset, + * new Vector3(0.0f, 0.0f, 0.0f), Quaternion.identity); + * : + * } + * + *
To load data under the StreamingAssets folder, + * concatenate CriWare::Common::streamingAssetsPath with the file path. + * string path = Path.Combine(CriWare.Common.streamingAssetsPath, "sample.assetbundle"); + * CriFsLoadAssetBundleRequest request = CriFsUtility.LoadAssetBundle(path); + *
+ * + * + */ + public static CriFsLoadAssetBundleRequest LoadAssetBundle(string path, int readUnitSize = DefaultReadUnitSize) + { + return CriFsUtility.LoadAssetBundle(null, path, readUnitSize); + } + + /** + * Starts loading the Asset Bundle file. + * Binder + * File path + * Read unit size of the CriFsLoader used internal + * CriFsLoadAssetBundleRequest + * + * Begins loading the bound Asset Bundle file.
+ *
+ * This function returns immediately.
+ * You should check CriWare.CriFsLoadAssetBundleRequest::isDone to check the completion of the loading.
+ * If an error occurs during the loading process, the error information is stored in CriWare.CriFsLoadFileRequest::error .
+ * Same as the CriWare.CriFsUtility::LoadAssetBundle function, except that the binder is specified as the first argument.
+ *
+ * + * + */ + public static CriFsLoadAssetBundleRequest LoadAssetBundle(CriFsBinder binder, string path, int readUnitSize = DefaultReadUnitSize) + { + return CriFsServer.instance.LoadAssetBundle(binder, path, readUnitSize); + } + + /** + * Starts installing files. + * Installation source file path + * Installation destination file path + * CriFsInstallRequest + * + * Starts the installation of the specified file.
+ * Specify the installation source file path in srcPath and the installation destination file path in dstPath.
+ *
+ * This function returns immediately.
+ * You should use CriWare.CriFsInstallRequest::isDone to check the completion of the installation.
+ * If an error occurs during the installation process, the error information is stored in CriWare.CriFsInstallRequest::error .
+ *
+ * When specifying data under the StreamingAssets folder as the installation source, + * prepend CriWare::Common::streamingAssetsPath to the file path.
+ * You can also load the file from network by specifying a URL in the path.
+ * Create a folder in advance and call this API since an error occurs if the installation destination does not exist.
+ *
+ * The code to install files using the CriWare.CriFsUtility::Install function is as follows.
+ * private IEnumerator UserInstallFile(string url, string path) + * { + * // インストールの開始 + * CriFsInstallRequest request = CriFsUtility.Install(url, path); + * + * // インストール完了待ち + * yield return request.WaitForDone(this); + * + * // エラーチェック + * if (request.error != null) { + * // エラー発生時の処理 + * … + * yield break; + * } + * : + * } + * + *
+ * + */ + public static CriFsInstallRequest Install(string srcPath, string dstPath) + { + return CriFsUtility.Install(null, srcPath, dstPath, null); + } + public static CriFsInstallRequest Install(string srcPath, string dstPath, CriFsRequest.DoneDelegate doneDeleagate) + { + return CriFsUtility.Install(null, srcPath, dstPath, doneDeleagate); + } + + /** + * Starts installing files. + * Installation source binder + * Installation source file path + * Installation destination file path + * CriFsInstallRequest + * + * Start the installation of bound files.
+ * Specify the installation source file path in srcPath and the installation destination file path in dstPath.
+ *
+ * This function returns immediately.
+ * You should check CriWare.CriFsInstallRequest::isDone to check the completion of the installation.
+ * If an error occurs during the installation process, the error information is stored in CriWare.CriFsInstallRequest::error .
+ * Same as the CriWare.CriFsUtility::Install(string, string) function, except that the binder is specified as the first argument.
+ * (This function is used only when writing the contents in the CPK file as a file.)
+ *
+ * + * + */ + public static CriFsInstallRequest Install(CriFsBinder srcBinder, string srcPath, string dstPath) + { + return CriFsServer.instance.Install(srcBinder, srcPath, dstPath, null); + } + public static CriFsInstallRequest Install(CriFsBinder srcBinder, string srcPath, string dstPath, CriFsRequest.DoneDelegate doneDeleagate) + { + return CriFsServer.instance.Install(srcBinder, srcPath, dstPath, doneDeleagate); + } + + + /** + * Starts installing files. + * Installation source file path (URL) + * Installation destination file path + * Asynchronous process completion callback + * CriFsWebInstallRequest + * + * Starts installing files.
+ * Specify the installation source file path (URL) in srcPath and the installation destination file path in dstPath.
+ *
+ * This function returns immediately.
+ * You should check CriWare.CriFsWebInstallRequest::isDone to check the completion of the installation.
+ * If an error occurs during the installation process, the error information is stored in CriWare.CriFsWebInstallRequest::error .
+ * On iOS, this function works on iOS7 or later. + *
+ * + */ + public static CriFsInstallRequest WebInstall(string srcPath, string dstPath, CriFsRequest.DoneDelegate doneDeleagate) + { + return CriFsServer.instance.WebInstall(srcPath, dstPath, doneDeleagate); + } + + + /** + * Start binding the CPK file. + * Binder to be bound + * CPK file path + * CriFsBindRequest + * + * Start binding the CPK file.
+ *
+ * This function returns immediately.
+ * You should check CriWare.CriFsBindRequest::isDone to check the completion of the binding.
+ * If an error occurs during the binding process, the error information is stored in CriWare.CriFsBindRequest::error .
+ *
+ * When binding the data under the StreamingAssets folder, prepend CriWare::Common::streamingAssetsPath + * to the file path.
+ * If you want to use the multi-bind function or bind the CPK data in the CPK file, + * you must call CriWare.CriFsUtility::BindCpk(CriFsBinder, CriFsBinder, string) + * instead of this function.
+ *
+ * It is also possible to bind the CPK file on the network by specifying a URL in the path.
+ * // crimot.comのsample.cpkをバインド + * CriFsLoadFileRequest request = CriFsUtility.LoadFile( + * "http://crimot.com/sdk/sampledata/crifilesystem/sample.cpk"); + * + *
+ * CPK content information is acquired only at the time of binding.
+ * Therefore, when you bind a CPK file on the network, + * even if the file is updated on the server side, the update cannot be detected on the client side.
+ * (There may be an unintended access to the updated CPK file.)
+ *
+ * This sample code shows how to load the content in the CPK file using the CriWare.CriFsUtility::BindCpk and CriWare.CriFsUtility::LoadFile functions.
+ * private CriFsBinder binder = null; // バインダ + * private uint bindId = 0; // バインドID + * + * void OnEnable() + * { + * // バインダの作成 + * this.binder = new CriFsBinder(); + * } + * + * void OnDisable() + * { + * // アンバインド処理の実行 + * if (this.bindId > 0) { + * CriFsBinder.Unbind(this.bindId); + * this.bindId = 0; + * } + * + * // バインダの破棄 + * this.binder.Dispose(); + * this.binder = null; + * } + * + * IEnumerator UserLoadFileFromCpk(string cpk_path, string content_path) + * { + * // CPKファイルのバインドを開始 + * CriFsBindRequest bind_request = CriFsUtility.BindCpk(this.binder, cpk_path); + * + * // バインドの完了を待つ + * yield return bind_request.WaitForDone(this); + * + * // エラーチェック + * if (bind_request.error != null) { + * // エラー発生時の処理 + * … + * yield break; + * } + * + * // CPK内のコンテンツの読み込みを開始 + * CriFsLoadFileRequest load_request = CriFsUtility.LoadFile(this.binder, content_path); + * + * // 読み込み完了を待つ + * yield return load_request.WaitForDone(this); + * + * // エラーチェック + * if (load_request.error != null) { + * // エラー発生時の処理 + * … + * yield break; + * } + * + * // 備考)ロードされたファイルの内容は request.bytes 内に格納されています。 + * } + * + *
+ * + * + */ + public static CriFsBindRequest BindCpk(CriFsBinder targetBinder, string srcPath) + { + return CriFsUtility.BindCpk(targetBinder, null, srcPath); + } + + /** + * Start binding the CPK file. + * Binder to be bound + * A binder to access the CPK file to bind + * CPK file path + * CriFsBindRequest + * + * Start binding the CPK file.
+ * In addition to CriWare.CriFsUtility::BindCpk(CriFsBinder, string) , + * you can specify the binder to access to the sub CPK in the CPK file.
+ *
+ * This function returns immediately.
+ * You should check CriWare.CriFsBindRequest::isDone to check the completion of the binding.
+ * If an error occurs during the binding process, the error information is stored in CriWare.CriFsBindRequest::error .
+ *
+ * + * + */ + public static CriFsBindRequest BindCpk(CriFsBinder targetBinder, CriFsBinder srcBinder, string srcPath) + { + return CriFsServer.instance.BindCpk(targetBinder, srcBinder, srcPath); + } + + /** + * Starts binding the directory path. + * Binder to be bound + * Path name of the directory to be bound + * + * Binds the directory pathname.
+ *
+ * This function returns immediately.
+ * You should check CriWare.CriFsBindRequest::isDone to check the completion of the binding.
+ * If an error occurs during the binding process, the error information is stored in CriWare.CriFsBindRequest::error .
+ *
+ * When binding the directory under the StreamingAssets folder, prepend CriWare::Common::streamingAssetsPath + * to the file path.
+ * The system does not check whether the directory exists at the time of binding.
+ * Only the directory path is retained in the binder; + * it does not open the files in the specified directory.
+ * This function is a debug function for development support.
+ * If you use this function, the following problems may occur.
+ * - Functions CriWare.CriFsLoader::Load or CriWare.CriFsBinder::GetFileSize may block for a long time.
+ * - When accessing files in the bound directory, stream playback of sound or movie is interrupted.
+ * Be careful not to use this function in the application when final release.
+ * (Convert the data in the directory to a CPK file and bind it using the CriWare.CriFsUtility::BindCpk function, + * or bind all the files in the directory using the CriWare.CriFsUtility::BindFile function.)
+ *
+ * + * + * + */ + public static CriFsBindRequest BindDirectory(CriFsBinder targetBinder, string srcPath) + { + return CriFsServer.instance.BindDirectory(targetBinder, null, srcPath); + } + + /** + * Starts binding the directory path. + * Binder to be bound + * The binder to access the directory to be bound + * CPK file path + * CriFsBindRequest + * + * Begins binding the directory path.
+ * In addition to CriWare.CriFsUtility::BindDirectory(CriFsBinder, string), + * you can specify the binder to access the directory in the CPK file.
+ *
+ * This function returns immediately.
+ * You should check CriWare.CriFsBindRequest::isDone to check the completion of the binding.
+ * If an error occurs during the binding process, the error information is stored in CriWare.CriFsBindRequest::error .
+ *
+ * + * + */ + public static CriFsBindRequest BindDirectory(CriFsBinder targetBinder, CriFsBinder srcBinder, string srcPath) + { + return CriFsServer.instance.BindDirectory(targetBinder, srcBinder, srcPath); + } + + /** + * Binds the file. + * Binder to be bound + * The path name of the file to be bound + * Bind ID + * + * Starts binding the file.
+ *
+ * This function returns immediately.
+ * You should check CriWare.CriFsBindRequest::isDone to check the completion of the binding.
+ * If an error occurs during the binding process, the error information is stored in CriWare.CriFsBindRequest::error .
+ *
+ * When binding the files under the StreamingAssets folder, prepend CriWare::Common::streamingAssetsPath + * to the file path.
+ * This function is used when you want to get only the file size without loading the file.
+ * It is possible to get the file size asynchronously by calling the + * CriWare.CriFsBinder::GetFileSize function after binding the file.
+ *
+ * This sample code shows how to get the file size using the CriWare.CriFsUtility::BindFile and CriWare.CriFsBinder::GetFileSize functions.
+ * IEnumerator UserGetFileSize(string path, out long fileSize) + * { + * // ファイルのバインドを開始 + * CriFsBindRequest bind_request = CriFsUtility.BindFile(path); + * + * // バインドの完了を待つ + * yield return bind_request.WaitForDone(this); + * + * // エラーチェック + * if (bind_request.error != null) { + * // エラー発生時の処理 + * … + * yield break; + * } + * + * // ファイルサイズの取得 + * fileSize = bind_request.binder.GetFileSize(); + * } + * + *
+ * + * + */ + public static CriFsBindRequest BindFile(CriFsBinder targetBinder, string srcPath) + { + return CriFsServer.instance.BindFile(targetBinder, null, srcPath); + } + + /** + * Starts binding files. + * Binder to be bound + * The binder to access the file to be bound + * File path + * CriFsBindRequest + * + * Starts binding files.
+ * In addition to CriWare.CriFsUtility::BindFile(CriFsBinder, string), + * you can specify the binder to access to the files in the CPK file.
+ *
+ * This function returns immediately.
+ * You should check CriWare.CriFsBindRequest::isDone to check the completion of the binding.
+ * If an error occurs during the binding process, the error information is stored in CriWare.CriFsBindRequest::error .
+ *
+ * + * + */ + public static CriFsBindRequest BindFile(CriFsBinder targetBinder, CriFsBinder srcBinder, string srcPath) + { + return CriFsServer.instance.BindFile(targetBinder, srcBinder, srcPath); + } + + /** + * Specifies the User-Agent string used in HTTP requests. + * User-Agent character + * + * Specifies the User-Agent string used in HTTP requests.
+ * If not specified, the version character of the lower file system module is specified.
+ * Specify the User-Agent string using up to 255 characters ((255 bytes).
+ *
+ */ + public static void SetUserAgentString(string userAgentString) + { + /* User-Agent文字列を指定 */ + CRIWARE7BCABE2D(userAgentString); + } + + /** + * Specifies the proxy server used for HTTP requests. + * Proxy server address + * Proxy server port number + * + * Specifies the proxy server address to be used for HTTP request of HTTP I/O.
+ * Specify proxyPath using up to 256 characters.
+ *
+ */ + public static void SetProxyServer(string proxyPath, UInt16 proxyPort) + { + /* プロキシ設定 */ + CRIWARE0E8F8E33(proxyPath, proxyPort); + } + + /** + * Specifies the path separator + * A list of characters used as a separator + * + * Changes the character that the CRI File System library interprets as a separator.
+ * By default, the three characters ",", "\\t", and "\\n" are treated as a separator.
+ * For filter, specify a string that contains a list of characters to be used as a separator.
+ * For example, if you specify "@+-*", four types of characters "@", "+", "-", and "*" are + * treated as a separator.
+ * If you specify an empty string ("") for filter, the separator will be disabled. + * If you specify null, the setting returns to the default.
+ * If you pass the path including the separator specified in this function to the plug-in function, + * it is treated as an invalid path internally and the path after the separator is invalid.
+ * When handling the path including ",", "\\t" or "\\n" in the application, it is necessary to + * change it to a separator in advance using this function.
+ *
+ */ + public static void SetPathSeparator(string filter) + { + CRIWARE2F1D5BBC(filter); + } + + #region DLL Import + #if !CRIWARE_ENABLE_HEADLESS_MODE + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool CRIWARE7BCABE2D(string userAgentString); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool CRIWARE0E8F8E33(string proxyPath, UInt16 proxyPort); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool CRIWARE2F1D5BBC(string filter); + #else + private static bool CRIWARE7BCABE2D(string userAgentString) { return true; } + private static bool CRIWARE0E8F8E33(string proxyPath, UInt16 proxyPort) { return true; } + private static bool CRIWARE2F1D5BBC(string filter) {return true; } + #endif + #endregion +} + +/** + * @} + */ + +/*========================================================================== + * CRI Fs Unity Integration + *=========================================================================*/ + +/** + * \addtogroup CRIFS_UNITY_INTEGRATION + * @{ + */ + +/** + * Global class in the CRIFs library. + * + * Class that contains the initialization function of the CRI File System library and the definitions of the types used within the library.
+ *
+ */ +public static class CriFsPlugin +{ + /* 初期化カウンタ */ + private static int initializationCount = 0; + + private static bool isConfigured = false; + + public static int defaultInstallBufferSize = (4 * 1024 * 1024); // 4.0 Mb + public static int installBufferSize = defaultInstallBufferSize; + + public static bool isInitialized { get { return initializationCount > 0; } } + + public static void SetConfigParameters( + int num_loaders, int num_binders, int num_installers, int argInstallBufferSize, int max_path, bool minimize_file_descriptor_usage, bool enable_crc_check) + { + CriFsPlugin.CRIWARE57ED305B( + num_loaders, num_binders, num_installers, max_path, minimize_file_descriptor_usage, enable_crc_check); + installBufferSize = argInstallBufferSize; + + CriFsPlugin.isConfigured = true; + } + + public static void SetReadDeviceEnabled(int deviceId, bool enabled) + { + if (deviceId == 0 && enabled == false) { + Debug.LogError("[CRIWARE] Read Device 0 should never be disabled."); + return; + } + + criFs_SetReadDeviceEnabled(deviceId, enabled); + } + + public static void SetConfigAdditionalParameters_ANDROID( + int device_read_bps) + { +#if !UNITY_EDITOR && UNITY_ANDROID + CriFsPlugin.criFsUnity_SetConfigAdditionalParameters_ANDROID(device_read_bps); +#endif + } + + public static void SetMemoryFileSystemThreadPriorityExperimentalAndroid(int prio) + { +#if !UNITY_EDITOR && UNITY_ANDROID + CriFsPlugin.criFsUnity_SetMemoryFileSystemThreadPriority_ANDROID(prio); +#endif + } + + public static void SetDataDecompressionThreadPriorityExperimentalAndroid(int prio) + { +#if !UNITY_EDITOR && UNITY_ANDROID + CriFsPlugin.criFsUnity_SetDataDecompressionThreadPriority_ANDROID(prio); +#endif + } + + public static void InitializeLibrary() + { + /* 初期化カウンタの更新 */ + CriFsPlugin.initializationCount++; + if (CriFsPlugin.initializationCount != 1) { + return; + } + + /* シーン実行前に初期化済みの場合は終了させる */ + if (CriFsPlugin.IsLibraryInitialized() == true) { + CriFsPlugin.FinalizeLibrary(); + CriFsPlugin.initializationCount = 1; + } + + /* 初期化パラメータが設定済みかどうかを確認 */ + if (CriFsPlugin.isConfigured == false) { + Debug.Log("[CRIWARE] FileSystem initialization parameters are not configured. " + + "Initializes FileSystem by default parameters."); + } + + /* ライブラリの初期化 */ + CriFsPlugin.CRIWARE51EC119C(); + } + + public static bool IsLibraryInitialized() + { + /* ライブラリが初期化済みかチェック */ + return CRIWARE2F4B4F68(); + } + + public static void FinalizeLibrary() + { + /* 初期化カウンタの更新 */ + CriFsPlugin.initializationCount--; + if (CriFsPlugin.initializationCount < 0) { + CriFsPlugin.initializationCount = 0; + if (CriFsPlugin.IsLibraryInitialized() == false) { + return; + } + } + if (CriFsPlugin.initializationCount != 0) { + return; + } + + /* CriFsServerのインスタンスが存在すれば破棄 */ + CriFsServer.DestroyInstance(); + + /* パラメータを初期値に戻す */ + installBufferSize = defaultInstallBufferSize; + + /* 未破棄のDisposableを破棄 */ + CriDisposableObjectManager.CallOnModuleFinalization(CriDisposableObjectManager.ModuleType.Fs); + + /* ライブラリの終了 */ + CriFsPlugin.CRIWARE74CAAF39(); + } + + #region DLL Import + #if !CRIWARE_ENABLE_HEADLESS_MODE + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void CRIWARE57ED305B( + int num_loaders, int num_binders, int num_installers, int max_path, bool minimize_file_descriptor_usage, bool enable_crc_check); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void CRIWARE51EC119C(); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + public static extern bool CRIWARE2F4B4F68(); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void CRIWARE74CAAF39(); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + public static extern uint CRIWARE4A9B2613(); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + public static extern UInt32 criFsLoader_GetRetryCount(); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + public static extern Int32 criFs_GetNumBinds(ref int cur, ref int max, ref int limit); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + public static extern Int32 criFs_GetNumUsedLoaders(ref int cur, ref int max, ref int limit); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + public static extern Int32 criFs_GetNumUsedInstallers(ref int cur, ref int max, ref int limit); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern Int32 criFs_SetReadDeviceEnabled(int device_id, bool enabled); + + #if !UNITY_EDITOR && UNITY_ANDROID + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criFsUnity_SetConfigAdditionalParameters_ANDROID(int device_read_bps); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + public static extern void criFsUnity_SetMemoryFileSystemThreadPriority_ANDROID(int prio); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + public static extern void criFsUnity_SetDataDecompressionThreadPriority_ANDROID(int prio); + #endif + #else + private static bool _dummyInitialized = false; + private static void CRIWARE57ED305B( + int num_loaders, int num_binders, int num_installers, int max_path, bool minimize_file_descriptor_usage, bool enable_crc_check) { } + private static void CRIWARE51EC119C() { _dummyInitialized = true; } + public static bool CRIWARE2F4B4F68() { return _dummyInitialized; } + private static void CRIWARE74CAAF39() { _dummyInitialized = false; } + public static uint CRIWARE4A9B2613() { return 0u; } + public static UInt32 criFsLoader_GetRetryCount() { return 0u; } + public static Int32 criFs_GetNumBinds(ref int cur, ref int max, ref int limit) { return 0; } + public static Int32 criFs_GetNumUsedLoaders(ref int cur, ref int max, ref int limit) { return 0; } + public static Int32 criFs_GetNumUsedInstallers(ref int cur, ref int max, ref int limit) { return 0; } + private static Int32 criFs_SetReadDeviceEnabled(int device_id, bool enabled) { return 0; } + #if !UNITY_EDITOR && UNITY_ANDROID + private static void criFsUnity_SetConfigAdditionalParameters_ANDROID(int device_read_bps) { } + public static void criFsUnity_SetMemoryFileSystemThreadPriority_ANDROID(int prio) { } + public static void criFsUnity_SetDataDecompressionThreadPriority_ANDROID(int prio) { } + #endif + #endif + #endregion +} + +} //namespace CriWare +/** + * @} + */ + +/* --- end of file --- */ diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriFs/CriFs.cs.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriFs/CriFs.cs.meta new file mode 100644 index 0000000..b3aefd5 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriFs/CriFs.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 6c8ef3c4627959146923079a82f3079f +timeCreated: 1433816076 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriFs/CriFsServer.cs b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriFs/CriFsServer.cs new file mode 100644 index 0000000..b567564 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriFs/CriFsServer.cs @@ -0,0 +1,154 @@ +/**************************************************************************** + * + * Copyright (c) 2011 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +using UnityEngine; +using System.Collections.Generic; + +namespace CriWare { + +public class CriFsServer : CriMonoBehaviour +{ + #region Internal Fields + private static CriFsServer _instance = null; + private List requestList = null; + + static public CriFsServer instance + { + get { + CreateInstance(); + return _instance; + } + } + #endregion + + public int installBufferSize { get; private set; } + + #region Internal Methods + public static void CreateInstance() + { + if (_instance == null) { + CriWare.Common.managerObject.AddComponent(); + _instance.installBufferSize = CriFsPlugin.installBufferSize; + } + } + + public static void DestroyInstance() + { + if (_instance != null) { + UnityEngine.GameObject.Destroy(_instance); + } + } + + void Awake() + { + if (_instance == null) { + _instance = this; + this.requestList = new List(); + /* 高速化のため、ダミーを追加してListの内部配列の自動確保を促す + * 追加による自動確保が目的なのでダミーはすぐに削除する */ + CriFsRequest dummy = new CriFsRequest(); + this.requestList.Add(dummy); + this.requestList.RemoveAt(0); + } else { + GameObject.Destroy(this); + } + } + + void OnDestroy() + { + if (_instance == this) { + foreach (var reqest in this.requestList) { + reqest.Dispose(); + } + _instance = null; + } + } + + public override void CriInternalUpdate() + { + #pragma warning disable 162 + if (CriWare.Common.supportsCriFsInstaller == true) { + CriFsInstaller.ExecuteMain(); + if (CriFsWebInstaller.isInitialized) { + CriFsWebInstaller.ExecuteMain(); + } + } + #pragma warning restore 162 + + for (int i=0;iA module which performs installation to the local storage by HTTP.
+ * + * Used to install content on the Web server to the local storage. + * On iOS, this function works on iOS7 or later. + * Before creating an instance of CriWare.CriFsWebInstaller, the module must be initialized by calling the CriWare.CriFsWebInstaller::InitializeModule method. + * + */ +public class CriFsWebInstaller : CriDisposable +{ + #region Data Types + /** + * Status + * + */ + public enum Status : int + { + Stop, /**< Stopped */ + Busy, /**< Processing in progress */ + Complete, /**< Completed */ + Error, /**< Error */ + } + + /** + * Error type + * + * Indicates the error type of the installer handle.
+ * Information can be obtained using the CriWare.CriFsWebInstaller::GetStatusInfo function.
+ *
+ * + */ + public enum Error : int + { + None, /**< No error */ + Timeout, /**< Timeout error */ + Memory, /**< Memory allocation failed */ + LocalFs, /**< Local file system error */ + DNS, /**< DNS error */ + Connection, /**< Connection error */ + SSL, /**< SSL error */ + HTTP, /**< HTTP error */ + Internal, /**< Internal error */ + } + + /** + * Status information + * + * Represents the detailed status including CriWare.CriFsWebInstaller::Status,
+ * which can be obtained by calling the CriWare.CriFsWebInstaller::GetStatusInfo function.
+ *
+ * + * + */ + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + public struct StatusInfo + { + /** + * Installer handle status + * + */ + public Status status; + + /** + * Error state of the installer handle + * + * A value other than CriFsWebInstaller::Error.None is stored + * when CriFsWebInstaller::StatusInfo.status != CriFsWebInstaller::Status.Error.
+ * When an error occurs, handle appropriately according to the error type.
+ *
+ * + */ + public Error error; + + /** + * HTTP status code + * + * HTTP status code is stored in either of the following cases.
+ * - CriFsWebInstaller::StatusInfo.status == CriFsWebInstaller::Status.Complete
+ * - CriFsWebInstaller::StatusInfo.status == CriFsWebInstaller::Status.Error and + * CriFsWebInstaller::StatusInfo.error == CriFsWebInstaller::Error.HTTP
+ * + * In other cases, a negative value ( CriFsWebInstaller.InvalidHttpStatusCode ) is stored.
+ *
+ * + */ + public int httpStatusCode; + + /** + * The size of the installation target (byte) + * + * The size of the installation target (byte) is stored.
+ * A negative value ( CriFsWebInstaller.InvalidContentsSize ) is stored if the size of the installation target is unknown.
+ * A valid value is stored when the transfer via HTTP starts.
+ *
+ * + * + */ + public long contentsSize; + + /** + * Received size (byte) + * + */ + public long receivedSize; + } + + /** + * Module configuration + * + * A structure for specifying the behavior of CriFsWebInstaller.
+ * You pass this structure as an argument when initializing a module (the CriWare.CriFsWebInstaller::InitializeModule function).
+ * Please get the default configuration with CriWare.CriFsWebInstaller::defaultModuleConfig , change it as needed, and pass it to the CriWare.CriFsWebInstaller::InitializeModule function.
+ *
+ * + * + */ + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + public struct ModuleConfig + { + /** + * Sets the maximum number of installers used at the same time + * + * CriFsWebInstallers cannot be generated at the same time exceeding this number. + * + */ + public uint numInstallers; + + [MarshalAs(UnmanagedType.LPStr)] + /** + * Sets the HTTP proxy server host name + * + * Set the host name of the proxy server used by CriFsWebInstaller.
+ * If set to null, proxy server will not be used.
+ *
+ */ + public string proxyHost; + + /** + * Sets the HTTP proxy server port + * + * Set the port of the proxy server used by CriFsWebInstaller.
+ * This value has an effect only if CriFsWebInstaller::ModuleConfig.proxyHost != null.
+ *
+ */ + public ushort proxyPort; + + /** + * User-Agent setting + * + * Set when overwriting the default User-Agent. + * If set to null, the default User-Agent is used. + * + */ + [MarshalAs(UnmanagedType.LPStr)] + public string userAgent; + + /** + * Sets the timeout time (in seconds) + * + * A timeout error ( CriFsWebinstaller::Error.Timeout ) occurs if the received size does not change over this time. + * + * + * + */ + public uint inactiveTimeoutSec; + + /** + * Enables the insecure HTTPS communication + * + * Insecure HTTPS communication is allowed when this flag is set to true.
+ * Please set it to true only if a valid server certificate cannot be provided during the application's development.
+ * - To allow insecure HTTPS internet connection on Apple platforms, + * set this flag to true, and either disable ATS (App Transport Security) + * or set up for exceptions. + *
+ */ + public bool allowInsecureSSL; + + /* CRCの有効化 + * \par 説明: + * CRI_TRUE の場合のみ、CRCの計算をします。 + */ + public bool crcEnabled; + + /** + * Platform-specific settings + */ + public ModulePlatformConfig platformConfig; + } + + #if UNITY_EDITOR_WIN || (!UNITY_EDITOR && UNITY_STANDALONE_WIN) + public struct ModulePlatformConfig + { + public byte reserved; + + public static ModulePlatformConfig defaultConfig { + get { + ModulePlatformConfig config; + config.reserved = 0; + return config; + } + } + } + #elif UNITY_EDITOR_OSX || (!UNITY_EDITOR && UNITY_STANDALONE_OSX) + public struct ModulePlatformConfig + { + public byte reserved; + + public static ModulePlatformConfig defaultConfig { + get { + ModulePlatformConfig config; + config.reserved = 0; + return config; + } + } + } + #elif UNITY_IOS + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + public struct ModulePlatformConfig + { + public byte reserved; + + public static ModulePlatformConfig defaultConfig { + get { + ModulePlatformConfig config; + config.reserved = 0; + return config; + } + } + } + #elif UNITY_ANDROID + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + public struct ModulePlatformConfig + { + public byte reserved; + + public static ModulePlatformConfig defaultConfig { + get { + ModulePlatformConfig config; + config.reserved = 0; + return config; + } + } + } + #else + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + public struct ModulePlatformConfig + { + public static ModulePlatformConfig defaultConfig { + get { + ModulePlatformConfig config; + return config; + } + } + } + #endif + #endregion + + #region Static Properties + public static bool isInitialized { get; private set; } + public static bool isCrcEnabled { get; private set; } + + /** + * Default module configuration + * + * Default module config. + * Change the default configuration obtained using this property + * and specify it in the CriWare.CriFsWebInstaller::InitializeModule function.
+ *
+ * + */ + public static ModuleConfig defaultModuleConfig { + get { + ModuleConfig config; + config.numInstallers = 2; + config.proxyHost = null; + config.proxyPort = 0; + config.userAgent = null; + config.inactiveTimeoutSec = 300; + config.allowInsecureSSL = false; + config.crcEnabled = false; + config.platformConfig = ModulePlatformConfig.defaultConfig; + return config; + } + } + #endregion + + #region Constant Variables + /** + * Invalid HTTP status code + * + * A constant that represents an invalid HTTP status code.
+ * It is set when the installation fails due to a reason other than HTTP.
+ * This value is guaranteed to be negative.
+ *
+ * + */ + public const int InvalidHttpStatusCode = -1; + + /** + * Invalid content size + * + * It is set when the size of the installation target cannot be acquired.
+ * This value is guaranteed to be negative.
+ *
+ * + */ + public const long InvalidContentsSize = -1; + #endregion + + + #if CRIFSWEBINSTALLER_SUPPORTED + #region Private Variables + private IntPtr handle = IntPtr.Zero; + #endregion + + public CriFsWebInstaller() + { + criFsWebInstaller_Create(out this.handle); + if (this.handle == IntPtr.Zero) + { + throw new Exception("criFsWebInstaller_Create() failed."); + } + CriDisposableObjectManager.Register(this, CriDisposableObjectManager.ModuleType.FsWeb); + } + + ~CriFsWebInstaller() + { + this.Dispose(false); + } + + /** + * Discards the installer. + * + * If you discard the installer during the installation process, + * the process may be blocked in this function for a long time.
+ *
+ */ + public override void Dispose() + { + this.Dispose(true); + System.GC.SuppressFinalize(this); + } + + + /** + * Installs the file. + * Installation source URL + * Installation destination file path name + * + * Starts installing files.
+ * This function returns immediately.
+ * To get the copy completion status, use the CriWare.CriFsWebInstaller::GetStatusInfo function.
+ * - If the installation destination file exists, error CriFsWebInstaller.Error.LocalFs occurs. + * - If the installation destination folder does not exist, the error CriFsWebInstaller.Error.LocalFs will occur. + *
+ * + */ + public void Copy(string url, string dstPath) + { + criFsWebInstaller_Copy(this.handle, url, dstPath); + } + + /** + * Stops the installation process. + * + * Stops the processing.
+ * This function returns immediately.
+ * Use the CriWare.CriFsWebInstaller::GetStatusInfo function to get the stop completion status.
+ *
+ * + */ + public void Stop() + { + if (this.handle != IntPtr.Zero) { + criFsWebInstaller_Stop(this.handle); + } + } + + /** + * Gets the status information. + * Status information + * + */ + public StatusInfo GetStatusInfo() + { + StatusInfo statusInfo; + if (this.handle != IntPtr.Zero) { + criFsWebInstaller_GetStatusInfo(this.handle, out statusInfo); + } else { + statusInfo.status = Status.Stop; + statusInfo.error = Error.Internal; + statusInfo.httpStatusCode = InvalidHttpStatusCode; + statusInfo.contentsSize = InvalidContentsSize; + statusInfo.receivedSize = 0; + } + return statusInfo; + } + + /** + * Acquire the CRC32 calculation result + * For CRC result storage + * + * Returns a checksum that is valid only in the Status.Complete state.
+ * If it is acquired in a state other than Status.Complete, the CRC result will be 0.
+ * This function can be used only when ModuleConfig.crcEnabled=true .
+ *
+ * + */ + public bool GetCRC32(out uint ret_val){ + int criErr = criFsWebInstaller_GetCRC32(this.handle, out ret_val); + // '0' means "OK". + return (criErr == 0); + } + + #region Static Methods + /** + * Initializes the CriFsWebInstaller module + * Configuration + * + * Initializes the CriFsWebInstaller module.
+ * In order to use the function of the module, you must call this function.
+ * (You can use the features of the module after calling this function + * and before calling the CriWare.CriFsWebInstaller::FinalizeModule function.)
+ * After calling this function, be sure to call the corresponding CriWare.CriFsWebInstaller::FinalizeModule function.
+ * In addition, this function cannot be called again until the CriWare.CriFsWebInstaller::FinalizeModule function is called.
+ *
+ * + * + */ + public static void InitializeModule(ModuleConfig config) + { + if (isInitialized) { + UnityEngine.Debug.LogError("[CRIWARE] CriFsWebInstaller module is already initialized."); + return; + } + Type type = GetCriFsWebInstallerCurlExpansionClass(); + if (type != null) { + System.Reflection.MethodInfo method_setup_curl_context = type.GetMethod("SetupCurlContext"); + if (method_setup_curl_context == null) { + UnityEngine.Debug.LogError("[CRIWARE] ERROR: CriFsWebInstallerCurl.SetupCurlContext method is not found."); + } else { + method_setup_curl_context.Invoke(null, new object[]{true}); + } + } + CriFsPlugin.InitializeLibrary(); + criFsWebInstaller_Initialize(ref config); + isCrcEnabled = config.crcEnabled; + isInitialized = true; + } + + private static Type GetCriFsWebInstallerCurlExpansionClass() { + Type type = Type.GetType("CriWare.CriFsWebInstallerCurl, CriMw.CriWare.FsModuleCurl.Runtime"); + return type; + } + + /** + * Terminates the CriFsWebInstaller module + * + * Terminates the CriFsWebInstaller module.
+ * - This function cannot be called before calling the CriWare.FsWebInstaller::InitializeModule function.
+ * - All CriWare.FsWebInstaller must be discarded.
+ *
+ * + */ + public static void FinalizeModule() + { + if (!isInitialized) { + UnityEngine.Debug.LogError("[CRIWARE] CriFsWebInstaller module is not initialized."); + return; + } + CriDisposableObjectManager.CallOnModuleFinalization(CriDisposableObjectManager.ModuleType.FsWeb); + criFsWebInstaller_Finalize(); + CriFsPlugin.FinalizeLibrary(); + isInitialized = false; + } + + /** + * Runs the server process + * + * Executes the server processing. It should be run regularly.
+ *
+ */ + public static void ExecuteMain() + { + criFsWebInstaller_ExecuteMain(); + } + + /** + * Changes the information in the HTTP request header. + * Field name + * Field value + * + * Changes the information in the HTTP request header.
+ * This function must be called after calling the CriWare.CriFsWebInstaller::InitializeModule function.
+ * Call this function before invoking the installation.
+ * If the field name is already registered, the field value will be overwritten.
+ * If null is passed as the field value, the field is removed.
+ *
+ */ + public static bool SetRequestHeader(string field, string value){ + int ret = criFsWebInstaller_SetRequestHeader(field, value); + return (ret == 0); + } + #endregion + + #region Private Methods + private void Dispose(bool disposing) + { + CriDisposableObjectManager.Unregister(this); + + if (this.handle != IntPtr.Zero) { + var statusInfo = this.GetStatusInfo(); + if (statusInfo.status != Status.Stop) { + this.Stop(); + while (true) { + ExecuteMain(); + statusInfo = this.GetStatusInfo(); + if (statusInfo.status == Status.Stop) { + break; + } + System.Threading.Thread.Sleep(1); + } + } + criFsWebInstaller_Destroy(this.handle); + this.handle = IntPtr.Zero; + } + } + #endregion + + #region DLL Import + #if !CRIWARE_ENABLE_HEADLESS_MODE + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criFsWebInstaller_Initialize([In] ref ModuleConfig config); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criFsWebInstaller_Finalize(); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criFsWebInstaller_ExecuteMain(); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criFsWebInstaller_Create(out IntPtr installer); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criFsWebInstaller_Destroy(IntPtr installer); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criFsWebInstaller_Copy(IntPtr installer, string url, string dstPath); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criFsWebInstaller_Stop(IntPtr installer); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criFsWebInstaller_GetStatusInfo(IntPtr installer, out StatusInfo status); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criFsWebInstaller_GetCRC32(IntPtr installer, out uint crc32); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criFsWebInstaller_SetRequestHeader (string field, string value); + + #else + private static int criFsWebInstaller_Initialize([In] ref ModuleConfig config) { return 0; } + private static int criFsWebInstaller_Finalize() { return 0; } + private static int criFsWebInstaller_ExecuteMain() { return 0; } + private static int criFsWebInstaller_Create(out IntPtr installer) { installer = new IntPtr(1); return 0; } + private static int criFsWebInstaller_Destroy(IntPtr installer) { return 0; } + private static int criFsWebInstaller_Copy(IntPtr installer, string url, string dstPath) { return 0; } + private static int criFsWebInstaller_Stop(IntPtr installer) { return 0; } + private static int criFsWebInstaller_GetStatusInfo(IntPtr installer, out StatusInfo status) { status = new StatusInfo(); return 0; } + private static int criFsWebInstaller_GetCRC32(IntPtr installer, out uint crc32) { crc32 = 0u; return 0; } + private static int criFsWebInstaller_SetRequestHeader (string field, string value){ return 0; } + #endif + #endregion + + #else + #region Internal Variables + private bool errorOccured = false; + #endregion + + public CriFsWebInstaller() + { + CriDisposableObjectManager.Register(this, CriDisposableObjectManager.ModuleType.Fs); + } + + ~CriFsWebInstaller() + { + this.Dispose(false); + } + + public override void Dispose() + { + CriDisposableObjectManager.Unregister(this); + this.Dispose(true); + System.GC.SuppressFinalize(this); + } + + public void Copy(string url, string dstPath) + { + Debug.LogError("[CRIWARE] CriWebInstaller does not support this platform."); + errorOccured = true; + } + + public void Stop() + { + errorOccured = false; + } + + public StatusInfo GetStatusInfo() + { + StatusInfo statusInfo; + if (errorOccured) { + statusInfo.status = Status.Error; + statusInfo.error = Error.None; + } else { + statusInfo.status = Status.Stop; + statusInfo.error = Error.Internal; + } + statusInfo.httpStatusCode = InvalidHttpStatusCode; + statusInfo.contentsSize = InvalidContentsSize; + statusInfo.receivedSize = 0; + return statusInfo; + } + + public bool GetCRC32(out uint ret_val){ + ret_val = 0; + return false; + } + + #region Static Methods + public static void InitializeModule(ModuleConfig config) + { + if (isInitialized) { + UnityEngine.Debug.LogError("[CRIWARE] CriFsWebInstaller module is already initialized."); + return; + } + CriFsPlugin.InitializeLibrary(); + isInitialized = true; + } + + public static void FinalizeModule() + { + if (!isInitialized) { + UnityEngine.Debug.LogError("[CRIWARE] CriFsWebInstaller module is not initialized."); + return; + } + CriFsPlugin.FinalizeLibrary(); + isInitialized = false; + } + + public static void ExecuteMain() + { + } + #endregion + + #region Private Methods + private void Dispose(bool disposing) + { + } + + private void UnsupportedError() + { + } + #endregion + #endif +} + +} //namespace CriWare +/** + * @} + */ diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriFs/CriFsWebInstaller.cs.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriFs/CriFsWebInstaller.cs.meta new file mode 100644 index 0000000..0b48e14 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriFs/CriFsWebInstaller.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 0fb09b347911d4830a3a3f4c937e7d77 +timeCreated: 1476854415 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana.meta new file mode 100644 index 0000000..d63f65a --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: f417196934b92f7458163dd0497210f0 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/CriMana.cs b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/CriMana.cs new file mode 100644 index 0000000..fb82fc3 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/CriMana.cs @@ -0,0 +1,568 @@ +/**************************************************************************** + * + * Copyright (c) 2011 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +using UnityEngine; +using System; +using System.Runtime.InteropServices; +using System.IO; +#if !UNITY_EDITOR && (UNITY_WINRT && !ENABLE_IL2CPP) +using System.Reflection; +#endif + +namespace CriWare { + +namespace CriMana +{ + /** + * A value indicating the type of movie codec. + */ + public enum CodecType + { + Unknown = 0, + SofdecPrime = 1, + H264 = 5, + VP9 = 9, + } + + + /** + * A value indicating the movie composition mode. + */ + public enum AlphaType + { + CompoOpaq = 0, /**< Opaque, no alpha information */ + CompoAlphaFull = 1, /**< Full Alpha synthesis (alpha data is 8 bits) */ + CompoAlpha3Step = 2, /**< Ternary alpha */ + CompoAlpha32Bit = 3, /**< Full Alpha, (32 bits with color and alpha data) */ + } + + + /** + * The audio analysis information in the movie file. + */ + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + public struct AudioInfo + { + public UInt32 samplingRate; /**< Sampling frequency */ + public UInt32 numChannels; /**< The number of audio channels */ + public UInt32 totalSamples; /**< Total number of samples */ + } + + + /** + * The header analysis information for movie files. + */ + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi), Serializable] + public class MovieInfo + { + private UInt32 _reserved1; + public UInt32 numAlphaStreams; /**< Number of alpha tracks (0 or 1) */ + public UInt32 width; /**< Maximum movie width (a multiple of 8) */ + public UInt32 height; /**< Maximum movie height (a multiple of 8) */ + public UInt32 dispWidth; /**< The number of horizontal pixels of the image to be displayed (from the left edge) */ + public UInt32 dispHeight; /**< The number of vertical pixels of the image to be displayed (from the top edge) */ + public UInt32 framerateN; /**< Rational format frame rate (numerator) framerate [x1000] = framerateN / framerateD */ + public UInt32 framerateD; /**< Rational format frame rate (denominator) framerate [x1000] = framerateN / framerateD */ + public UInt32 totalFrames; /**< Total number of frames */ + public CodecType codecType; /**< Codec type (information to be used inside the plug-in) */ + public CodecType alphaCodecType; /**< Alpha codec type (information to be used inside the plug-in) */ + public UInt32 numAudioStreams; /**< The number of audio streams */ + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)] + public AudioInfo[] audioPrm; /**< Audio parameters */ + public UInt32 numSubtitleChannels; /**< The number of subtitle channels */ + public UInt32 maxSubtitleSize; /**< Maximum size of the subtitle data */ + public UInt32 maxChunkSize; /**< Maximum USF chunk size */ + + public bool hasAlpha { get { return numAlphaStreams != 0; } internal set { numAlphaStreams = value ? 1u : 0u; } } /**< Whether it is an alpha movie */ + } + + + /** + * Video frame information. + */ + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + public class FrameInfo + { + public Int32 frameNo; /**< Frame identification number (serial number from 0) */ + public Int32 frameNoPerFile; /**< Frame identification number (identification number specific to movie files) */ + public UInt32 width; /**< Movie width [pixel] (a multiple of 8) */ + public UInt32 height; /**< Movie height [pixel] (a multiple of 8) */ + public UInt32 dispWidth; /**< The number of horizontal pixels of the image to be displayed (from the left edge) */ + public UInt32 dispHeight; /**< The number of vertical pixels of the image to be displayed (from the top edge) */ + public UInt32 numImages; /**< The number of images included in the frame */ + public UInt32 framerateN; /**< Rational format frame rate (numerator) framerate [x1000] = framerateN / framerateD */ + public UInt32 framerateD; /**< Rational format frame rate (numerator) framerate [x1000] = framerateN / framerateD */ + private UInt32 _reserved1; /**< For manual range adjustment */ + public UInt64 time; /**< Time. Seconds are represented by time/tunit. Continuously added during loop playback or linked playback. */ + public UInt64 tunit; /**< Time unit */ + public UInt32 cntConcatenatedMovie; /**< The number of movie concatenation */ + AlphaType alphaType; /**< Alpha composition mode */ + public UInt32 cntSkippedFrames; /**< The number of frames skipped in decoding */ + public UInt32 totalFramesPerFile; /**< Total number of frames (specific to movie files) */ + } + + + /** + * Event point information. + * + * Individual event point information embedded in the movie data using the Cue point feature.
+ *
+ */ + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + public struct EventPoint + { + public IntPtr cueName; /**< A pointer to the event point name. The character code follows the Cue point information text. Use it after conversion using System.Runtime.InteropServices.Marshal.PtrToStringAuto etc. */ + public UInt32 cueNameSize; /**< Data size of the event point name */ + public UInt64 time; /**< Timer count */ + public UInt64 tunit; /**< Timer count value per second. count ÷ unit gives the time in seconds. */ + public Int32 type; /**< Event point type */ + public IntPtr paramString; /**< A pointer to the user parameter string. The character code follows the Cue point information text. Use it after conversion using System.Runtime.InteropServices.Marshal.PtrToStringAuto etc. */ + public UInt32 paramStringSize; /**< Data size of the user parameter string */ + public UInt32 cntCallback; /**< Cue point callback call counter */ + } + + public static class Settings + { + + public static void SetDecodeSkippingEnabled(bool enabled) + { + CriManaPlugin.CRIWARE59A3ABE0(enabled); + } + + } +} + +/*========================================================================== + * CRI Mana Unity Integration + *=========================================================================*/ + +/** + * \addtogroup CRIMANA_UNITY_INTEGRATION + * @{ + */ + +/** + * Global class for the CRI Mana library. + * + * Class that contains the initialization functions of the CRI Mana library and the definitions of the types used within the library.
+ *
+ */ +public class CriManaPlugin +{ +#if (UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7 || UNITY_5_0) + private enum GraphicsApi + { + Unknown = -1, // Unknown (from unity cpp) + OpenGLES_2_0 = 8, // UnityEngine.Rendering.GraphicsDeviceType.OpenGLES2; + OpenGLES_3_0 = 11, // UnityEngine.Rendering.GraphicsDeviceType.OpenGLES3; + Metal = 16, // UnityEngine.Rendering.GraphicsDeviceType.Metal; + }; +#endif + + + /* 初期化カウンタ */ + private static int initializationCount = 0; + public static bool isInitialized { get { return initializationCount > 0; } } + + private static bool isConfigured = false; + + private static bool enabledMultithreadedRendering = false; + public static bool isMultithreadedRenderingEnabled { get { return enabledMultithreadedRendering; } } + + public static int renderingEventOffset = 0x43570000; // => 'CW\0\0' + + public static void SetConfigParameters(bool graphicsMultiThreaded, int num_decoders, int max_num_of_entries) + { +#if (UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7 || UNITY_5_0) + int graphicsApi = (int)GraphicsApi.Unknown; + #if !UNITY_EDITOR && (UNITY_IOS || UNITY_TVOS) + if (SystemInfo.graphicsDeviceVersion.IndexOf("OpenGL ES 2.") > -1) { + graphicsApi = (int)GraphicsApi.OpenGLES_2_0; + } else if (SystemInfo.graphicsDeviceVersion.IndexOf("OpenGL ES 3.") > -1) { + graphicsApi = (int)GraphicsApi.OpenGLES_3_0; + } else if (SystemInfo.graphicsDeviceVersion.IndexOf("Metal") > -1) { + graphicsApi = (int)GraphicsApi.Metal; + } + #endif +#else + int graphicsApi = (int)SystemInfo.graphicsDeviceType; +#endif + + enabledMultithreadedRendering = graphicsMultiThreaded; + CriWare.Common.criWareUnity_SetRenderingEventOffsetForMana(renderingEventOffset); + + CriManaPlugin.CRIWAREA4FEFA5E((int)graphicsApi, enabledMultithreadedRendering, num_decoders, max_num_of_entries); + + CriManaPlugin.isConfigured = true; + } + + /* VP9の設定 */ + private static void SetupVp9() { +#if !UNITY_EDITOR && UNITY_SWITCH + return; +#else + Type type = GetVp9ExpansionClass(); + if (type == null) { + /* Plugin not found */ + return; + } + + if (IsVp9CodecSupported() == false) { + Debug.LogError("[CRIWARE] ERROR: VP9 is not supported on the current platform."); + return; + } + + /* Call the setup function for VP9 decoder */ +#if !UNITY_EDITOR && (UNITY_WINRT && !ENABLE_IL2CPP) + System.Reflection.MethodInfo method_setup_vp9_decoder = type.GetTypeInfo().GetDeclaredMethod("SetupVp9Decoder"); +#else + System.Reflection.MethodInfo method_setup_vp9_decoder = type.GetMethod("SetupVp9Decoder"); +#endif + if (method_setup_vp9_decoder == null) { + Debug.LogError("[CRIWARE] ERROR: CriManaVp9.SetupVp9Decoder method is not found."); + return; + } + + method_setup_vp9_decoder.Invoke(null, null); +#endif + } + + /** + * \deprecated + * This is a deprecated API that will be removed. + */ + [System.Obsolete("Use CriWareVITA.EnableH264Playback and CriWareVITA.SetH264DecoderMaxSize instead.")] + public static void SetConfigAdditonalParameters_VITA(bool use_h264_playback, int width, int height) + { +#if !UNITY_EDITOR && UNITY_PSP2 + CriManaPlugin.CRIWARE07F6621E(use_h264_playback, (UInt32)width, (UInt32)height); +#endif + } + + public static void SetConfigAdditonalParameters_PC(bool use_h264_playback) + { +#if UNITY_EDITOR_WIN || (!UNITY_EDITOR && UNITY_STANDALONE_WIN) + CriManaPlugin.CRIWAREC4FA2781(use_h264_playback); +#endif + } + + public static void SetConfigAdditonalParameters_ANDROID(bool enable_buffer_output_for_h264, + bool enable_buffer_output_for_vp9) + { +#if !UNITY_EDITOR && UNITY_ANDROID + using (var version = new AndroidJavaClass("android.os.Build$VERSION")) { + if (version.GetStatic("SDK_INT") >= 16) { + // CRI H264 Decoder exists over API-16. + CriManaPlugin.criManaUnity_SetConfigAdditionalParameters_ANDROID(enable_buffer_output_for_h264, enable_buffer_output_for_vp9); + } + } +#endif + } + + + public static void SetConfigAdditonalParameters_WEBGL(string webworkerPath, uint heapSize) + { +#if !UNITY_EDITOR && UNITY_WEBGL + CriManaPlugin.CRIWARE7499A135(webworkerPath,heapSize); +#endif + } + + public static void InitializeLibrary() + { + /* 初期化カウンタの更新 */ + CriManaPlugin.initializationCount++; + if (CriManaPlugin.initializationCount != 1) { + return; + } + + /* シーン実行前に初期化済みの場合は終了させる */ + if (CriManaPlugin.IsLibraryInitialized() == true) { + CriManaPlugin.FinalizeLibrary(); + CriManaPlugin.initializationCount = 1; + } + + /* 初期化パラメータが設定済みかどうかを確認 */ + if (CriManaPlugin.isConfigured == false) { + Debug.Log("[CRIWARE] Mana initialization parameters are not configured. " + + "Initializes Mana by default parameters."); + } + + /* 依存ライブラリの初期化 */ + CriFsPlugin.InitializeLibrary(); + CriAtomPlugin.InitializeLibrary(); + + /* VP9の設定 */ + CriManaPlugin.SetupVp9(); + + /* ライブラリの初期化 */ + CriManaPlugin.CRIWARE4A2D20F5(); + + /* RendererResource の自動登録を実行 */ + CriMana.Detail.AutoResisterRendererResourceFactories.InvokeAutoRegister(); + } + + public static bool IsLibraryInitialized() + { + /* ライブラリが初期化済みかチェック */ + return CRIWAREA61F3614(); + } + + public static void FinalizeLibrary() + { + /* 初期化カウンタの更新 */ + CriManaPlugin.initializationCount--; + if (CriManaPlugin.initializationCount < 0) { + CriManaPlugin.initializationCount = 0; + if (CriManaPlugin.IsLibraryInitialized() == false) { + return; + } + } + if (CriManaPlugin.initializationCount != 0) { + return; + } + + /* 未破棄のDisposableを破棄 */ + CriDisposableObjectManager.CallOnModuleFinalization(CriDisposableObjectManager.ModuleType.Mana); + + /* ライブラリの終了 */ + CriManaPlugin.CRIWARE552CBE59(); + + /* RendererResourceFactoryのインスタンスを破棄 */ + CriMana.Detail.RendererResourceFactory.DisposeAllFactories(); + + /* 依存ライブラリの終了 */ + CriAtomPlugin.FinalizeLibrary(); + CriFsPlugin.FinalizeLibrary(); + } + + /** + * Whether playback with the specified video codec is supported + * Video codec type + * + * Determines whether the current platform supports playback with the specified video codec.
+ * If this function returns false, an error will occur when playing a video file that uses the corresponding codec. + * The playback and rendering will not be performed correctly.
+ * On some platforms, rendering may not be possible depending on the environment, + * even if the application has the same settings.
+ * Use this function to determine whether to play videos on the specific device.
+ *
+ */ + public static bool IsCodecSupported(CriMana.CodecType codecType) + { + switch (codecType) { + case CriMana.CodecType.SofdecPrime: + return true; + case CriMana.CodecType.VP9: + return IsVp9CodecSupported(); + case CriMana.CodecType.H264: + return IsH264CodecSupported(); + case CriMana.CodecType.Unknown: + default: + Debug.LogError("[CRIWARE] Invalid format " + codecType + " is specified to CriManaPlugin.IsCodecSupported."); + return false; + } + } + + private static Type GetVp9ExpansionClass() { + Type type = Type.GetType("CriManaVp9"); + if (type == null) { + type = Type.GetType("CriWare.CriManaVp9, CriMw.CriWare.Vp9.Runtime"); + } + return type; + } + + private static bool IsVp9CodecSupported() + { +#if !UNITY_EDITOR && UNITY_SWITCH + return true; +#else + Type type = GetVp9ExpansionClass(); + if (type == null) { + /* Plugin not found */ + return false; + } + + /* Check if the current platform supports VP9 by expansion */ +#if !UNITY_EDITOR && (UNITY_WINRT && !ENABLE_IL2CPP) + System.Reflection.MethodInfo method_support_current_platform = type.GetTypeInfo().GetDeclaredMethod("SupportCurrentPlatform"); +#else + System.Reflection.MethodInfo method_support_current_platform = type.GetMethod("SupportCurrentPlatform"); +#endif + if (method_support_current_platform == null) { + Debug.Log("function not found"); + return false; + } + + bool current_platform_supports_vp9 = (bool)method_support_current_platform.Invoke(null, null); + return current_platform_supports_vp9; +#endif + } + + private static bool IsH264CodecSupported() + { +#if UNITY_EDITOR || UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX || UNITY_IOS || UNITY_TVOS || UNITY_SWITCH || UNITY_PS4 || UNITY_PS5 || UNITY_XBOXONE + return true; +#elif UNITY_ANDROID + if (SystemInfo.graphicsDeviceType == UnityEngine.Rendering.GraphicsDeviceType.Vulkan) { + return true; + } else { + return CriMana.Detail.RendererResourceAndroidH264Rgb.IsSupported(); + } +#else + return false; +#endif + } + + public static void SetDecodeThreadPriorityAndroidExperimental(int prio) + { + /* + * + * デコードマスタースレッドのプライオリティを変更します。 + * + * スレッドプライオリティ + * + * Manaライブラリが初期化された後に本メソッドを呼び出してください。 + * + * + * デコード処理を行うスレッドのプライオリティを変更します。 + * デフォルトでは、デコードスレッドのプライオリティはメインスレッドよりも低く設定されています。 + * + * + * 本メソッドはExperimentalです。今後のアップデートで削除、または仕様変更される可能性があります。 + * + */ +#if !UNITY_EDITOR && UNITY_ANDROID + criManaUnity_SetDecodeThreadPriority_ANDROID(prio); +#endif + } + +#if UNITY_2017_1_OR_NEWER + public static bool ShouldSampleRed(UnityEngine.Rendering.GraphicsDeviceType type, IntPtr tex_ptr) + { +#if !UNITY_EDITOR && UNITY_ANDROID + if (type == UnityEngine.Rendering.GraphicsDeviceType.OpenGLES3) { + return criManaUnity_ShouldSwitchTextureSampleColorToRedGLES30_ANDROID(tex_ptr); + } +#endif + return false; + } +#endif + + public static void Lock() + { + CriManaPlugin.CRIWARE7AAA02A9(); + } + + public static void Unlock() + { + CriManaPlugin.CRIWARE4A44A5D3(); + } + + #region DLL Import + #if !CRIWARE_ENABLE_HEADLESS_MODE + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void CRIWAREA4FEFA5E(int graphics_api, bool graphics_multi_threaded, int num_decoders, int num_of_max_entries); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void CRIWARE4A2D20F5(); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + public static extern bool CRIWAREA61F3614(); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void CRIWARE552CBE59(); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + public static extern void CRIWARE59A3ABE0(bool flag); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + public static extern void CRIWARE7AAA02A9(); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + public static extern void CRIWARE4A44A5D3(); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + public static extern void criMana_UseStreamerManager(bool flag); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + public static extern bool criMana_IsStreamerManagerUsed(); + +#if !UNITY_EDITOR && UNITY_WEBGL +#else + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + public static extern uint CRIWARE065392A8(); +#endif + +#if UNITY_EDITOR_WIN || (!UNITY_EDITOR && UNITY_STANDALONE_WIN) + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + public static extern void CRIWAREC4FA2781(bool enable); +#endif + +#if !UNITY_EDITOR && UNITY_ANDROID + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + public static extern void criManaUnity_SetDecodeThreadPriority_ANDROID(int prio); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criManaUnity_SetConfigAdditionalParameters_ANDROID(bool buffer_h264, bool buffer_vp9); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + public static extern bool criManaUnity_IsBufferOutputForH264Enabled_ANDROID(); +#if UNITY_2017_1_OR_NEWER + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + public static extern void criManaUnity_EnableSwitchTextureSampleColorGLES30_ANDROID(); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool criManaUnity_ShouldSwitchTextureSampleColorToRedGLES30_ANDROID(System.IntPtr tex_ptr); +#endif +#elif !UNITY_EDITOR && UNITY_PSP2 + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + public static extern void CRIWARE07F6621E(bool use_h264_playback, UInt32 width, UInt32 height); +#elif !UNITY_EDITOR && UNITY_WEBGL + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + public static extern void CRIWARE7499A135(string webworkerPath, uint heapSize); +#endif + #else + private static bool _dummyInitialized = false; + private static void CRIWAREA4FEFA5E(int graphics_api, bool graphics_multi_threaded, int num_decoders, int num_of_max_entries) { } + private static void CRIWARE4A2D20F5() { _dummyInitialized = true; } + public static bool CRIWAREA61F3614() { return _dummyInitialized; } + private static void CRIWARE552CBE59() { _dummyInitialized = false; } + public static void CRIWARE59A3ABE0(bool flag) { } + public static void CRIWARE7AAA02A9() { } + public static void CRIWARE4A44A5D3() { } + public static void criMana_UseStreamerManager(bool flag) { } + public static bool criMana_IsStreamerManagerUsed() { return false; } +#if !UNITY_EDITOR && UNITY_WEBGL +#else + public static uint CRIWARE065392A8() { return 0u; } +#endif +#if UNITY_EDITOR_WIN || (!UNITY_EDITOR && UNITY_STANDALONE_WIN) + public static void CRIWAREC4FA2781(bool enable) { } +#endif +#if !UNITY_EDITOR && UNITY_ANDROID + public static void criManaUnity_SetDecodeThreadPriority_ANDROID(int prio) { } + private static void criManaUnity_SetConfigAdditionalParameters_ANDROID(bool buffer_h264, bool buffer_vp9) { } + public static bool criManaUnity_IsBufferOutputForH264Enabled_ANDROID() { return false; } +#if UNITY_2017_1_OR_NEWER + public static void criManaUnity_EnableSwitchTextureSampleColorGLES30_ANDROID() { } + private static bool criManaUnity_ShouldSwitchTextureSampleColorToRedGLES30_ANDROID(System.IntPtr tex_ptr) { return false; } +#endif +#elif !UNITY_EDITOR && UNITY_PSP2 + public static void CRIWARE07F6621E(bool use_h264_playback, UInt32 width, UInt32 height) { } +#elif !UNITY_EDITOR && UNITY_WEBGL + public static void CRIWARE7499A135(string webworkerPath, uint heapSize) { } +#endif + #endif + #endregion +} + +} //namespace CriWare + +/** + * @} + */ + +/* end of file */ diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/CriMana.cs.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/CriMana.cs.meta new file mode 100644 index 0000000..cd7765f --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/CriMana.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: d1a6c96058248f94db8a727cce779fbc +timeCreated: 1433816077 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/CriManaAmbisonicSource.cs b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/CriManaAmbisonicSource.cs new file mode 100644 index 0000000..e838906 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/CriManaAmbisonicSource.cs @@ -0,0 +1,130 @@ +using UnityEngine; +using System.Collections; + +/** + * \addtogroup CRIMANA_UNITY_COMPONENT + * @{ + */ + +namespace CriWare { + +/** + * A component for controlling the sound source of movies with Ambisonic sound. + * + * A component for controlling the sound source of movies with Ambisonic sound. + * By enabling the Advanced Audio mode of CriManaMovieMaterial, + * an object Audio Source with this component attached is created. + * This component updates the orientation of the sound source. + * Rotates the orientation vector of the sound source based on the angle (transform.eulerAngles ) of the GameObject to which this component is attached. + * + */ +public class CriManaAmbisonicSource : CriMonoBehaviour +{ + #region Internal Variables + private CriAtomEx3dSource atomEx3DsourceForAmbisonics; + private Vector3 ambisonicSourceOrientationFront; + private Vector3 ambisonicSourceOrientationTop; + private Vector3 lastEulerOfAmbisonicSource; + #endregion + + + #region MonoBehaviour Methods + public override void CriInternalUpdate() + { + UpdateAmbisonicSourceOrientation(); + } + + public override void CriInternalLateUpdate() { } + + protected override void OnEnable() + { + base.OnEnable(); + /* Ambisonic 音源の位置と向きを初期化 */ + atomEx3DsourceForAmbisonics = this.gameObject.transform.parent.GetComponent().player.atomEx3DsourceForAmbisonics; + if (atomEx3DsourceForAmbisonics == null) + { + Debug.LogError("atomEx3DsourceForAmbisonics == null"); + return; + } + ForceUpdateAmbisonicSourceOrientation(); + } + #endregion + + + #region Private Methods + private void ForceUpdateAmbisonicSourceOrientation() + { + lastEulerOfAmbisonicSource = this.transform.eulerAngles; + /* Ambisonic 音源の方向を回転させる */ + RoatateAmbisonicSourceOrientationByTransformOfChild(ref lastEulerOfAmbisonicSource); + atomEx3DsourceForAmbisonics.SetOrientation( + ambisonicSourceOrientationFront, + ambisonicSourceOrientationTop + ); + atomEx3DsourceForAmbisonics.Update(); + } + + + private void UpdateAmbisonicSourceOrientation() + { + /* Ambisonic Source の角度が変わっていたら Ambisonics 音源方向を更新 */ + if (lastEulerOfAmbisonicSource != this.transform.eulerAngles) + { + ForceUpdateAmbisonicSourceOrientation(); + } + } + + + private void RoatateAmbisonicSourceOrientationByTransformOfChild(ref Vector3 input_euler) + { + Quaternion quat = Quaternion.Euler(input_euler); + float square_norm = quat.x * quat.x + quat.y * quat.y + quat.z * quat.z + quat.w * quat.w; + float s; + /* 正規化係数算出 */ + if (square_norm <= 0.0f) + { + s = 0.0f; + } + else + { + s = 2.0f / square_norm; + } + float[] matrix = new float[9]; + matrix[0] = 1.0f - s * (quat.y * quat.y + quat.z * quat.z); + matrix[1] = s * (quat.x * quat.y - quat.w * quat.z); + matrix[2] = s * (quat.x * quat.z + quat.w * quat.y); + matrix[3] = s * (quat.x * quat.y + quat.w * quat.z); + matrix[4] = 1.0f - s * (quat.x * quat.x + quat.z * quat.z); + matrix[5] = s * (quat.y * quat.z - quat.w * quat.x); + matrix[6] = s * (quat.x * quat.z - quat.w * quat.y); + matrix[7] = s * (quat.y * quat.z + quat.w * quat.x); + matrix[8] = 1.0f - s * (quat.x * quat.x + quat.y * quat.y); + /* Matrix calculation */ + { + /* the default orientation vector to front of atom 3d source */ + Vector3 default_front = new Vector3(0, 0, 1); + Vector3 output_front = ambisonicSourceOrientationFront; + output_front.x = matrix[0] * default_front.x + matrix[1] * default_front.y + matrix[2] * default_front.z; + output_front.y = matrix[3] * default_front.x + matrix[4] * default_front.y + matrix[5] * default_front.z; + output_front.z = matrix[6] * default_front.x + matrix[7] * default_front.y + matrix[8] * default_front.z; + ambisonicSourceOrientationFront = output_front; + } + { + /* the default orientation vector to top of atom 3d source */ + Vector3 default_top = new Vector3(0, 1, 0); + Vector3 output_top = ambisonicSourceOrientationTop; + output_top.x = matrix[0] * default_top.x + matrix[1] * default_top.y + matrix[2] * default_top.z; + output_top.y = matrix[3] * default_top.x + matrix[4] * default_top.y + matrix[5] * default_top.z; + output_top.z = matrix[6] * default_top.x + matrix[7] * default_top.y + matrix[8] * default_top.z; + ambisonicSourceOrientationTop = output_top; + } + } + #endregion +} + +} //namespace CriWare +/** + * @} + */ + +/* end of file */ diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/CriManaAmbisonicSource.cs.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/CriManaAmbisonicSource.cs.meta new file mode 100644 index 0000000..17ca45a --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/CriManaAmbisonicSource.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: bd3bac4c19c4d3b469c7a3e130f32431 +timeCreated: 1498473932 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: -5 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/CriManaMovieController.cs b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/CriManaMovieController.cs new file mode 100644 index 0000000..b7b5cba --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/CriManaMovieController.cs @@ -0,0 +1,125 @@ +/**************************************************************************** + * + * Copyright (c) 2015 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +using UnityEngine; + +/** + * \addtogroup CRIMANA_UNITY_COMPONENT + * @{ + */ + +namespace CriWare { + +/** + * A component to be attached to a GameObject for playing movies. + * + * A component to be attached to a GameObject for playing movies.
+ * The movie is displayed by setting a Material to UnityEngine.Renderer.
+ * It inherits CriManaMovieMaterial.
+ * In this class, you can only perform basic operations such as play, stop, or pause.
+ * If you want to perform complicated playback control, operate the core player using the player property.
+ *
+ */ +[AddComponentMenu("CRIWARE/CriManaMovieController")] +public class CriManaMovieController : CriManaMovieMaterial +{ + #region Properties + /** + * A UnityEngine.Renderer to which the movie Material is set. + * + * A UnityEngine.Renderer to which the movie Material is set.
+ * If not specified, UnityEngine.Renderer of the attached game object is used.
+ *
+ */ + public Renderer target; + + + /** + * Whether to display the original Material when movie frames are not available. + * + * Whether to display the original material when a movie frame is not available.
+ * true : display the original material when a movie frame is not available.
+ * false : disable the rendering of the target when a movie frame is not available.
+ *
+ */ + public bool useOriginalMaterial; + #endregion + + + #region Internal Variables + private Material originalMaterial; + #endregion + + + + public override void CriInternalUpdate() + { + base.CriInternalUpdate(); + + // If there is a target connected but current GameObject is not a Renderer, + // we check target visibility an then update movie material if visible. + if (renderMode == RenderMode.OnVisibility) { + if (HaveRendererOwner == false && target != null && target.isVisible) { + player.OnWillRenderObject(this); + } + } + } + + + public override bool RenderTargetManualSetup() + { + if (target == null) { + target = gameObject.GetComponent(); + } + if (target == null) { + Debug.LogError("[CRIWARE] Missing render target for the Mana Controller component: Please add a renderer to the GameObject or specify the target manually."); + return false; + } + originalMaterial = target.sharedMaterial; + if (!useOriginalMaterial) { + target.enabled = false; + } + return true; + } + + + public override void RenderTargetManualFinalize() + { + if (target != null) { + target.material = originalMaterial; + if (!useOriginalMaterial) { + target.enabled = false; + } + } + originalMaterial = null; + } + + + protected override void OnMaterialAvailableChanged() + { + if (target == null) { + return; + } + + if (isMaterialAvailable) { + target.material = material; + target.enabled = true; + } else { + target.material = originalMaterial; + if (!useOriginalMaterial) { + target.enabled = false; + } + } + } +} + +} //namespace CriWare +/** + * @} + */ + + +/* end of file */ \ No newline at end of file diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/CriManaMovieController.cs.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/CriManaMovieController.cs.meta new file mode 100644 index 0000000..eefa5ac --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/CriManaMovieController.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 96f4515c07e664706973e1f78a07054b +timeCreated: 1467014239 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: -7 + icon: {fileID: 2800000, guid: a4c14449c19b8f346be66595b3db44ff, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/CriManaMovieControllerForUI.cs b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/CriManaMovieControllerForUI.cs new file mode 100644 index 0000000..c4faa90 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/CriManaMovieControllerForUI.cs @@ -0,0 +1,129 @@ +/**************************************************************************** + * + * Copyright (c) 2015 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +using UnityEngine; + +/** + * \addtogroup CRIMANA_UNITY_COMPONENT + * @{ + */ + +namespace CriWare { + +/** + * A component for playing movie on Unity UI. + * + * A component for playing movie on Unity UI.
+ * The movie is displayed by setting a Material to UnityEngine.UI.Graphic.
+ * It inherits CriManaMovieMaterial.
+ * In this class, you can only perform basic operations such as play, stop, or pause.
+ * If you want to perform complicated playback control, operate the core player using the player property.
+ *
+ */ +[AddComponentMenu("CRIWARE/CriManaMovieControllerForUI")] +public class CriManaMovieControllerForUI : CriManaMovieMaterial +{ + #region Properties + /** + * A UnityEngine.UI.Graphic to which the movie Material is set. + * + * A UnityEngine.UI.Graphic to which the movie Material is set.
+ * If not specified, UnityEngine.UI.Graphic of the attached game object is used.
+ *
+ */ + public UnityEngine.UI.Graphic target; + + + /** + * Whether to display the original Material when movie frames are not available. + * + * Whether to display the original material when a movie frame is not available.
+ * true : display the original material when a movie frame is not available.
+ * false : disable the rendering of the target when a movie frame is not available.
+ *
+ */ + public bool useOriginalMaterial; + #endregion + + + #region Internal Variables + private Material originalMaterial; + #endregion + + + protected override void Awake() + { + uiRenderMode = true; + base.Awake(); + } + + public override void CriInternalUpdate() + { + base.CriInternalUpdate(); + + // If there is a target connected but current GameObject is not a Renderer, + // we check target activation an then update movie material if active. + if (renderMode == RenderMode.OnVisibility) { + if (HaveRendererOwner == false && target != null && target.IsActive()) { + player.OnWillRenderObject(this); + } + } + } + + + public override bool RenderTargetManualSetup() + { + if (target == null) { + target = gameObject.GetComponent(); + } + if (target == null) { + Debug.LogError("[CRIWARE] Missing render target for the Mana Controller component: Please add a renderer to the GameObject or specify the target manually."); + return false; + } + originalMaterial = target.materialForRendering; + if (!useOriginalMaterial) { + target.enabled = false; + } + return true; + } + + + public override void RenderTargetManualFinalize() + { + if (target != null) { + target.material = originalMaterial; + if (!useOriginalMaterial) { + target.enabled = false; + } + } + originalMaterial = null; + } + + protected override void OnMaterialAvailableChanged() + { + if (target == null) { + return; + } + + if (isMaterialAvailable) { + target.material = material; + target.enabled = true; + } else { + target.material = originalMaterial; + if (!useOriginalMaterial) { + target.enabled = false; + } + } + } +} + +} //namespace CriWare +/** + * @} + */ + + +/* end of file */ diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/CriManaMovieControllerForUI.cs.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/CriManaMovieControllerForUI.cs.meta new file mode 100644 index 0000000..36acc61 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/CriManaMovieControllerForUI.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 3a80347b53d674ced9cc2dca045fd2ca +timeCreated: 1467013462 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: -8 + icon: {fileID: 2800000, guid: a4c14449c19b8f346be66595b3db44ff, type: 3} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/CriManaMovieMaterial.cs b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/CriManaMovieMaterial.cs new file mode 100644 index 0000000..09f287b --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/CriManaMovieMaterial.cs @@ -0,0 +1,860 @@ +/**************************************************************************** + * + * Copyright (c) 2015 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +using System.Collections; +using UnityEngine; + + +/** + * \addtogroup CRIMANA_UNITY_COMPONENT + * @{ + */ + +namespace CriWare { + +/** + * A component for feeding a movie to a Material. + * + * A component for feeding a movie to a Material.
+ * A base class for movie playback and rendering components.
+ * By inheriting this class, it is possible to render a movie on any drawing target.
+ * This component only feeds a movie to a Material, so nothing is displayed when it is attached and used.
+ * Usually, use the CriManaMovieController or CriManaMovieControllerForUI component + * according to the object you want to display the movie.
+ * In this class, you can only perform basic operations such as play, stop, or pause.
+ * If you want to perform complicated playback control, operate the core player using the player property.
+ *
+ */ +[AddComponentMenu("CRIWARE/CriManaMovieMaterial")] +public class CriManaMovieMaterial : CriManaMovieMaterialBase +{ + #region Properties + /** + * The file path for streaming playback at Start. + * File path + * + * The file path for streaming playback at Start.
+ * - If a relative path is specified, the file is loaded relative to StreamingAssets folder. + * - The file is loaded using the absolute path, or the specified path if a URL is specified.
+ * To set the file path from the script, use the CriMana::Player::SetFile method etc. of the player + * property.
+ * This property is provided to set the file path for streaming playback at Start on the Inspector. + * Changing this property after Start does not apply to the next playback.
+ *
+ */ + public string moviePath + { + get { return _moviePath; } + set { + if (isMonoBehaviourStartCalled) { + Debug.LogError("[CRIWARE] moviePath can not be changed. Use CriMana::Player::SetFile method."); + } else { + _moviePath = value; + } + } + } + + /** + * Loop setting for movie playback at Start. + * + * Loop setting applied on Start of a movie playback. The default value is false. + * To set the loop from the script, use the CriMana::Player::Loop method of the player property.
+ * This property is provided to set the loop at Start on the Inspector.
+ * Changing this property after Start does not apply to the next playback.
+ *
+ */ + public bool loop + { + get { return _loop; } + set { + if (isMonoBehaviourStartCalled) { + Debug.LogError("[CRIWARE] loop property can not be changed. Use CriMana::Player::Loop method."); + } else { + _loop = value; + } + } + } + + /** + * Switches to the Advanced Audio mode. + * + * Advanced audio playback features are available when the Advanced Audio mode is enabled. The default value is false.
+ * For example, it is necessary to enable this mode to play movies with Ambisonic audio.
+ *
+ */ + public bool advancedAudio + { + get { return _advancedAudio; } + set { + if (isMonoBehaviourStartCalled) { + Debug.LogError("[CRIWARE] advancedAudio property can not be changed in running."); + } else { + if (value == false) { + ambisonics = false; + } + _advancedAudio = value; + } + } + } + + + /** + * Enables the playback of movies with Ambisonic sound. + * + * A property to enable the playback of movies with Ambisonic sound.
+ * Only available when Advanced Audio mode is enabled.
+ * When enabling this mode, a GameObject called Ambisonic Source is created as a child object.
+ * The CriManaAmbisonicSource component is attached to this Ambisonic Source object.
+ *
+ */ + public bool ambisonics + { + get { return _ambisonics; } + set { + if (isMonoBehaviourStartCalled) { + Debug.LogError("[CRIWARE] ambisonics property can not be changed in running."); + } else if (_advancedAudio != true) { + Debug.LogError("[CRIWARE] ambisonics property needs for advancedAudio property to be true."); + } else { + /* Advanced Audio モードの ON/OFF 切替時に、Ambisonic Source オブジェクトを 生成/破棄 */ + if (value == false) { + GameObject obj = null; + if (gameObject.transform.childCount > 0) { + /* 自分の子オブジェクトである "Ambisonic Source" を破棄する */ + obj = (ambisonicSource != null) ? ambisonicSource : gameObject.transform.Find("Ambisonic Source").gameObject; + if (obj != null) { + DestroyImmediate(obj); + obj = null; + } + } + } else { + if (ambisonicSource == null) { + ambisonicSource = new GameObject(); + ambisonicSource.name = "Ambisonic Source"; + ambisonicSource.transform.parent = gameObject.transform; + ambisonicSource.transform.position = gameObject.transform.position; + ambisonicSource.transform.rotation = gameObject.transform.rotation; + ambisonicSource.transform.localScale = gameObject.transform.localScale; + ambisonicSource.AddComponent(); + } + } + _ambisonics = value; + } + } + } + + + /** + * Additive synthesis mode setting at Start. + * + * Additive mode setting applied on Start of a movie playback. The default value is false. + * To set the additive synthesis mode from the script, use the CriMana::Player::additiveMode property of + * the player property.
+ * This property is provided to set the additive synthesis mode at Start on the Inspector.
+ * Changing this property after Start does not apply to the next playback.
+ *
+ */ + public bool additiveMode + { + get { return _additiveMode; } + set { + if (isMonoBehaviourStartCalled) { + Debug.LogError("[CRIWARE] additiveMode can not be changed. Use CriMana::Player::additiveMode method."); + } else { + _additiveMode = value; + } + } + } + + /** + * Sets whether to apply the object transparency. + * + * Sets whether the movie will be transparent according to the transparency of the attached object.
+ * The default value is false.
+ *
+ */ + public bool applyTargetAlpha + { + get { return _applyTargetAlpha; } + set { + if (isMonoBehaviourStartCalled) { + Debug.LogError("[CRIWARE] applyTargetAlpha property can not be changed in running."); + } else { + _applyTargetAlpha = value; + } + } + } + + /** + * Specifies whether shader settings for UI components are applied. + * + * Sets whether to apply the rendering settings for UI components to the shader + * that renders the movie.
+ * The default value is false.
+ *
+ */ + public bool uiRenderMode + { + get { return _uiRenderMode; } + set { + if (isMonoBehaviourStartCalled) { + Debug.LogError("[CRIWARE] uiRenderMode property can not be changed in running."); + } else { + _uiRenderMode = value; + } + } + } + + #endregion + + protected override uint FilePathLength + { + get { + return + string.IsNullOrEmpty(moviePath) ? + 0 : (uint)(moviePath.Length + (CriWare.Common.IsStreamingAssetsPath(moviePath) ? CriWare.Common.streamingAssetsPath.Length + 1 : 0)) + 1; + } + } + + protected override bool initializeWithAdvancedAudio + { + get { + return advancedAudio; + } + } + + protected override bool initializeWithAmbisonics + { + get { + return ambisonics; + } + } + + protected override void SetDataToPlayer() + { + if (!System.String.IsNullOrEmpty(moviePath)) { + player.SetFile(null, moviePath); + } + player.Loop(loop); + player.additiveMode = additiveMode; + player.maxFrameDrop = (int)maxFrameDrop; + player.applyTargetAlpha = applyTargetAlpha; + player.uiRenderMode = uiRenderMode; + } + + [SerializeField] private string _moviePath; + + [SerializeField] private bool _loop = false; + [SerializeField] private bool _additiveMode = false; + [SerializeField] private bool _advancedAudio = false; + [SerializeField] private bool _ambisonics = false; + [SerializeField] private bool _applyTargetAlpha = false; + [SerializeField] private bool _uiRenderMode = false; + private GameObject ambisonicSource = null; +} + +public abstract class CriManaMovieMaterialBase : CriMonoBehaviour +{ + + #region Properties + + /** + * Sets whether to play at Start. + * + * Specifies whether playback is to be performed on Start. The default value is false. + * + */ + public bool playOnStart = false; + + /** + * A setting whether to play from the start on OnEnable. + * + * If true, the playback will start over from the beginning when a component is disabled during playback and then re-enabled.
+ * The default value is false.
+ *
+ */ + public bool restartOnEnable = false; + + /** + * Maximum frame drop number type + */ + public enum MaxFrameDrop + { + Disabled = 0, + One = 1, + Two = 2, + Three = 3, + Four = 4, + Five = 5, + Six = 6, + Seven = 7, + Eight = 8, + Nine = 9, + Ten = 10, + Infinite = -1 + }; + + /** + * Sets the maximum number of frame drops. + * + * Sets the maximum number of frames to be dropped in one update + * if the update of rendered frames is not keeping up with the playback.
+ * This allows intended playback if the frame rate of the application is low + * or when the playback speed of the video is raised higher than the frame rate.
+ *
+ */ + public MaxFrameDrop maxFrameDrop + { + get { return _maxFrameDrop; } + set { + _maxFrameDrop = value; + if (player != null) { + player.maxFrameDrop = (int)_maxFrameDrop; + } + } + } + + protected abstract bool initializeWithAdvancedAudio { get; } + protected abstract bool initializeWithAmbisonics { get; } + + /** + * Whether movie frames can be rendered with CriManaMovieMaterial::material + * + * Indicates whether movie frames can be rendered with CriManaMovieMaterial::material. + * + */ + public bool isMaterialAvailable { get; private set; } + + /** + * Playback control player + * + * A player property for fine movie playback control.
+ * If you want to perform operations other than Start/Stop/Pause, use the CriMana::Player API via this property.
+ *
+ */ + public CriMana.Player player { get; private set; } + + /** + * Sets the Material for feeding the movie. + * + * If you set a Material, the movie is fed to that Material.
+ * If you do not set a Material, a Material to which the movie is fed is created.
+ * If you set a Material, it must be set before the Start method is called. + *
+ */ + public Material material + { + get { return _material; } + set { + if (value != _material) { + if (materialOwn) { +#if UNITY_EDITOR + if (UnityEditor.EditorApplication.isPlaying == false) { + DestroyImmediate(_material); + } else { + Destroy(_material); + } +#else + Destroy(_material); +#endif + materialOwn = false; + } + _material = value; + isMaterialAvailable = false; + } + } + } + + /** + * Material rendering mode type + * + * A type which indicates how the video should be rendered on the Material.
+ * - Always: Draw every frame.
+ * - OnVisibility: Renders if the GameObject is the rendering target (if active for UI.Graphic).
+ * - Never: Do not render. You must explicitly call CriManaMovieMaterial::RenderMovie to do the rendering.
+ *
+ */ + public enum RenderMode + { + Always = 0, + OnVisibility = 1, + Never = 2 + }; + + /** + * Material rendering mode + * + * Sets how the video is rendered for the Material. + * On some platforms (PC/iOS, etc.), rendering is always done regardless of this setting. + * + */ + public RenderMode renderMode = RenderMode.Always; + + /** + * Callback delegate on application pause + * + * A callback delegate called at the time of suspend/resume or when the + * application pauses such as by pressing the pause button while running the Editor. + * + */ + public delegate void OnApplicationPauseCallback(CriManaMovieMaterialBase manaMovieMaterial, bool appPause); + + /** + * Callback on application pause + * + * Sets the processing when the application is paused/resumed.
+ * The behavior if not set (when null is specified) is "paused at start, resumed at end + * (remains paused if it was already paused at the)".
+ * If you want to change the above behavior in the application side, + * set your own callback process in this property.
+ *
+ */ + public OnApplicationPauseCallback onApplicationPauseCallback = null; + + private CriMana.Player.TimerType _timerType = CriMana.Player.TimerType.Audio; + public CriMana.Player.TimerType timerType + { + get { return _timerType; } + set { + _timerType = value; + if (player != null) + player.SetMasterTimerType(timerType); + } + } + + #endregion + + #region Abstracts + + protected abstract uint FilePathLength { get; } + protected abstract void SetDataToPlayer(); + + #endregion + + #region Internal Variables + [SerializeField] private Material _material; + [SerializeField] private MaxFrameDrop _maxFrameDrop = MaxFrameDrop.Disabled; + private bool materialOwn = false; + protected bool isMonoBehaviourStartCalled = false; + private bool wasDisabled = false; + private bool wasPausedOnDisable = false; + private WaitForEndOfFrame frameEnd = new WaitForEndOfFrame(); +#if UNITY_EDITOR + private bool isApplicationPaused = false; + private bool isEditorPaused = false; +#endif + private bool unpauseOnApplicationUnpause = false; + #endregion + protected bool HaveRendererOwner { get; private set; } + + + /** + * Start playback. + * + * Starts movie playback.
+ * When playback starts, the status ( CriWare.CriMana::Player::Status ) changes to Playing.
+ * After calling this function, it takes several frames before the rendering of movie actually starts.
+ * If you want to synchronize the movie playback, instead of using this function, access the player property, + * and prepare for playback in advance using the CriMana::Player::Prepare function.
+ *
+ * + * + */ + public void Play() + { + player.Start(); + this.CriInternalUpdate(); + } + + + /** + * Requests to stop movie playback. + * + * Issues a request to stop movie playback. This function returns immediately.
+ * The rendering ends immediately when you call this function, but the playback does not stop immediately.
+ *
+ * + */ + public void Stop() + { + player.Stop(); + if (isMaterialAvailable) { + isMaterialAvailable = false; + OnMaterialAvailableChanged(); + } + } + + + + /** + * Pauses/unpauses the movie playback. + * Pause switch (true: pause, false: resume) + * + * Turns the pause on and off.
+ * Pauses the playback if the argument is true, resumes the playback if it is false.
+ * The pause state will be cleared when CriManaMovieMaterial::Stop is called.
+ *
+ */ + public void Pause(bool sw) + { + if (this.wasDisabled) { + this.wasPausedOnDisable = sw; + } else { + player.Pause(sw); + } + } + + + /** + * A method called when the isMaterialAvailable property changes. + * + * A method called when the isMaterialAvailable property changes.
+ * It is supposed to be overridden in the inherited class.
+ *
+ */ + protected virtual void OnMaterialAvailableChanged() + { + } + + + /** + * A method called when a new frame is fed to the Material. + * + * A method called when a new frame is fed to the Material.
+ * It is supposed to be overridden in the inherited class.
+ *
+ */ + protected virtual void OnMaterialUpdated() + { + } + + private CriManaMoviePlayerHolder playerHolder; + + /** + * Initializes the player (for manual) + * + * Manually initializes the player.
+ * Since it is usually called from the Awake function, it is not required to call this function separately.
+ * Use this function only if you want to perform initialization manually for editor extension etc.
+ *
+ */ + public void PlayerManualInitialize() + { + if (player != null) { + Debug.LogError("[CRIWARE][Error] CriManaMovieMaterial is already initialized. There is no need to call this function multiple times."); + return; + } + + player = new CriMana.Player(initializeWithAdvancedAudio, initializeWithAmbisonics, FilePathLength); + player.SetMasterTimerType(timerType); + isMaterialAvailable = false; + if (Application.isPlaying) { + // object that can keep alive player for defering graphics cleaning + GameObject go = new GameObject("CriManaMovieResources"); + playerHolder = go.AddComponent(); + playerHolder.player = player; + player.playerHolder = playerHolder; + } + } + + /** + * Terminates the player (for manual) + * + * Manually terminates the player.
+ * This function is called from OnDestroy(), therefore it is not necessary to call it manually.
+ * Call this function only when you want to perform initialization manually (e.g., for editor customization).
+ *
+ */ + public void PlayerManualFinalize() + { + if (player != null) { + player.Dispose(); + player = null; + material = null; + } + } + + /** + * Prepares the player (for manual) + * + * Manually prepares the player.
+ * Since it is usually called from the Start function, it is not required to call this function separately.
+ * Use this function if you want perform preparation manually for editor extension etc.
+ *
+ */ + public void PlayerManualSetup() + { + HaveRendererOwner = (this.GetComponent() != null); + + if (_material == null) { + CreateMaterial(); + } + SetDataToPlayer(); + if (playOnStart) { + player.Start(); + } + } + + /** + * Initialization process of the rendering target (for manual use) + * + * This method should be called to set the rendering target at initialization.
+ * It is supposed to be overridden in the inherited class.
+ * Since it is usually called from the Start function, it is not required to call this function separately.
+ * Use this function if you want perform preparation manually for editor extension etc.
+ *
+ */ + public virtual bool RenderTargetManualSetup() + { + return true; + } + + /** + * Finalization process of the rendering target (for manual use) + * + * This method is called to configure the rendering target when finalizing.
+ * It is supposed to be overridden in the inherited class.
+ * Since it is usually called from the OnDestroy function, it is not required to call this function separately.
+ * Use this function if you want perform finalization manually for editor extension etc.
+ *
+ */ + public virtual void RenderTargetManualFinalize() + { + } + + + /** + * Updates the player frame (for manual) + * + * Manually updates the player frame.
+ * Since it is usually called from the Update function, it is not required to call this function separately.
+ * Use this function if you want update frames manually for editor extension etc.
+ *
+ */ + public void PlayerManualUpdate() + { + if (player != null) { + if (player.timerType == CriMana.Player.TimerType.User) { + player.UpdateWithUserTime(0ul, 1000ul); + } else { + player.Update(); + } + bool isMaterialAvailableCurrent; + if (player.isFrameAvailable) { + isMaterialAvailableCurrent = player.UpdateMaterial(material); + if (isMaterialAvailableCurrent) { + OnMaterialUpdated(); + } + } else { + isMaterialAvailableCurrent = false; + } + if (isMaterialAvailable != isMaterialAvailableCurrent) { + isMaterialAvailable = isMaterialAvailableCurrent; + OnMaterialAvailableChanged(); + } + } + } + + #region MonoBehavior Inherited Methods + protected virtual void Awake() + { + PlayerManualInitialize(); + } + + protected override void OnEnable() + { + base.OnEnable(); + if (this.wasDisabled && this.player != null && this.player.isAlive) { + this.player.Pause(this.wasPausedOnDisable); + if (this.restartOnEnable) { + StartCoroutine(RestartPlayerRoutine()); + } + } + this.wasDisabled = false; +#if UNITY_EDITOR +#if UNITY_2017_2_OR_NEWER + UnityEditor.EditorApplication.playModeStateChanged += OnPlayModeStateChanged; + UnityEditor.EditorApplication.pauseStateChanged += OnPauseStateChanged; +#else + UnityEditor.EditorApplication.playmodeStateChanged += OnPlaymodeStateChange; +#endif +#endif + } + + private IEnumerator RestartPlayerRoutine() + { + if (player.status == CriMana.Player.Status.Playing || player.status == CriMana.Player.Status.PlayEnd) { + this.Stop(); + while (this.player.status != CriMana.Player.Status.Stop) { + if (this.player.status != CriMana.Player.Status.StopProcessing) { + yield break; + } + yield return frameEnd; + } + this.Play(); + /* Re-applying pause */ + this.player.Pause(this.wasPausedOnDisable); + } + } + + protected override void OnDisable() + { + base.OnDisable(); + if (this.player != null && this.player.isAlive) { + this.wasPausedOnDisable = this.player.IsPaused(); + this.player.Pause(true); + } +#if UNITY_EDITOR +#if UNITY_2017_2_OR_NEWER + UnityEditor.EditorApplication.playModeStateChanged -= OnPlayModeStateChanged; + UnityEditor.EditorApplication.pauseStateChanged -= OnPauseStateChanged; +#else + UnityEditor.EditorApplication.playmodeStateChanged -= OnPlaymodeStateChange; +#endif +#endif + this.wasDisabled = true; + } + + protected virtual void OnDestroy() + { + RenderTargetManualFinalize(); + PlayerManualFinalize(); + } + + protected virtual void Start() + { + PlayerManualSetup(); + isMonoBehaviourStartCalled = true; + + if (!RenderTargetManualSetup()) { + Destroy(this); + } + } + + public override void CriInternalUpdate() + { + PlayerManualUpdate(); + } + + // Render the movie picture to target material. + public virtual void RenderMovie() + { + player.OnWillRenderObject(this); + } + + // The movie picture is always rendered to target material whenever owner object is visible or not. + public override void CriInternalLateUpdate() + { + if (renderMode == RenderMode.Always) { + player.OnWillRenderObject(this); + } + } + + // If owner object is visible the movie picture is rendered to target material. + protected virtual void OnWillRenderObject() + { + if (renderMode == RenderMode.OnVisibility) { + player.OnWillRenderObject(this); + } + } + +#if UNITY_EDITOR + private void OnPlaymodeStateChange() + { + bool paused = UnityEditor.EditorApplication.isPaused; + if (!isApplicationPaused && isEditorPaused != paused) { + ProcessApplicationPause(paused); + isEditorPaused = paused; + } + } + +#if UNITY_2017_2_OR_NEWER + private void OnPlayModeStateChanged(UnityEditor.PlayModeStateChange state) + { + OnPlaymodeStateChange(); + } + private void OnPauseStateChanged(UnityEditor.PauseState state) + { + OnPlaymodeStateChange(); + } +#endif + +#endif + + void OnApplicationPause(bool appPause) + { +#if UNITY_EDITOR + if (!isEditorPaused && isApplicationPaused != appPause) { + ProcessApplicationPause(appPause); + isApplicationPaused = appPause; + } +#else + ProcessApplicationPause(appPause); +#endif + } + + void ProcessApplicationPause(bool appPause) + { + if (onApplicationPauseCallback != null) { + onApplicationPauseCallback(this, appPause); + return; + } + + + if (appPause) { + unpauseOnApplicationUnpause = !player.IsPaused(); + if (unpauseOnApplicationUnpause) { + player.PauseOnApplicationPause(true); + } + } else { + if (unpauseOnApplicationUnpause) { + player.PauseOnApplicationPause(false); + } + unpauseOnApplicationUnpause = false; + } + } + +#if UNITY_EDITOR + protected virtual void OnDrawGizmos() + { + if ((player != null) && (player.status == CriMana.Player.Status.Playing)) { + Gizmos.color = new Color(1.0f, 1.0f, 1.0f, 0.8f); + } else { + Gizmos.color = new Color(1.0f, 1.0f, 1.0f, 0.5f); + } + + Gizmos.DrawLine(this.transform.position, new Vector3(0, 0, 0)); + } +#endif + #endregion + + + #region Private Methods + private void CreateMaterial() + { + _material = new Material(Shader.Find("VertexLit")); + _material.name = "CriMana-MovieMaterial"; + materialOwn = true; + } + + /* + private System.Collections.IEnumerator CallPluginAtEndOfFrames() + { + while (true) { + yield return new WaitForEndOfFrame(); + player.IssuePluginEvent(); + } + } + */ + #endregion +} + +} //namespace CriWare +/** + * @} + */ + +/* end of file */ diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/CriManaMovieMaterial.cs.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/CriManaMovieMaterial.cs.meta new file mode 100644 index 0000000..9bd7afd --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/CriManaMovieMaterial.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 3114ae2549999454481481b1f02427e8 +timeCreated: 1467014239 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: -9 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/CriManaMoviePlayerHolder.cs b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/CriManaMoviePlayerHolder.cs new file mode 100644 index 0000000..e23b587 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/CriManaMoviePlayerHolder.cs @@ -0,0 +1,34 @@ +/**************************************************************************** + * + * Copyright (c) 2019 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +using UnityEngine; + +namespace CriWare { + +public class CriManaMoviePlayerHolder : CriMonoBehaviour +{ + private CriMana.Player _player; + public CriMana.Player player { set { _player = value; } } + + void Awake() + { + DontDestroyOnLoad(this); + } + + public override void CriInternalUpdate() { } + + public override void CriInternalLateUpdate() { } + + void Start() + { + if (_player == null) + { + Debug.LogAssertion("Error: No CriMana.Player held by CriManaMoviePlayerHolder."); + } + } +} + +} //namespace CriWare diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/CriManaMoviePlayerHolder.cs.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/CriManaMoviePlayerHolder.cs.meta new file mode 100644 index 0000000..b135f19 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/CriManaMoviePlayerHolder.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: efd49b8bc45a9e542ae8be34e7a44b3f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Detail.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Detail.meta new file mode 100644 index 0000000..e0cc1e4 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Detail.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 558ddc81ecc764649be9069736e570b2 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Detail/RendererResource.cs b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Detail/RendererResource.cs new file mode 100644 index 0000000..968a8bc --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Detail/RendererResource.cs @@ -0,0 +1,423 @@ +/**************************************************************************** + * + * Copyright (c) 2015-2018 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +using System.Collections.Generic; +using System.Reflection; +using System.Runtime.InteropServices; +using UnityEngine; + +namespace CriWare { + +namespace CriMana.Detail +{ + public abstract class RendererResource : System.IDisposable + { + private bool disposed = false; + protected Shader shader; + protected Material currentMaterial; + protected bool hasAlpha; + protected bool additive; + protected bool applyTargetAlpha; + protected bool ui; + + ~RendererResource() + { + Dispose(false); + } + + public void Dispose() + { + this.Dispose(true); + System.GC.SuppressFinalize(this); + } + + private void Dispose(bool disposing) + { + if (disposed) { + return; + } + if (disposing) { + OnDisposeManaged(); + } + OnDisposeUnmanaged(); + disposed = true; + } + + public int GetNumberOfFrameBeforeDestroy(int playerId) + { + return CRIWAREB970989D(playerId); + } + + protected void SetupStaticMaterialProperties() + { + if (currentMaterial == null) { + return; + } + + int srcBlendMode, dstBlendMode; + GetBlendModes(out srcBlendMode, out dstBlendMode); + + if (currentMaterial.shader != shader) { + currentMaterial.shader = shader; + } + currentMaterial.SetInt("_SrcBlendMode", srcBlendMode); + currentMaterial.SetInt("_DstBlendMode", dstBlendMode); + currentMaterial.SetInt("_CullMode", ui ? 0 : 2); + currentMaterial.SetInt("_ZWriteMode", ui ? 0 : 1); + SetKeyword(currentMaterial, "CRI_ALPHA_MOVIE", hasAlpha); + SetKeyword(currentMaterial, "CRI_APPLY_TARGET_ALPHA", applyTargetAlpha); + SetKeyword(currentMaterial, "CRI_LINEAR_COLORSPACE", (QualitySettings.activeColorSpace == ColorSpace.Linear)); + } + + private void GetBlendModes(out int srcBlendMode, out int dstBlendMode) + { + srcBlendMode = additive ? (int)UnityEngine.Rendering.BlendMode.One : (int)UnityEngine.Rendering.BlendMode.SrcAlpha; + dstBlendMode = (additive && !hasAlpha) ? (int)UnityEngine.Rendering.BlendMode.One : (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha; + } + + public virtual void SetApplyTargetAlpha(bool flag) + { + applyTargetAlpha = flag; + SetupStaticMaterialProperties(); + } + + public virtual void SetUiRenderMode(bool flag) + { + ui = flag; + SetupStaticMaterialProperties(); + } + + protected abstract void OnDisposeManaged(); + + protected abstract void OnDisposeUnmanaged(); + + public abstract bool IsPrepared(); + + public abstract bool ContinuePreparing(); + + public abstract void AttachToPlayer(int playerId); + + public abstract bool UpdateFrame(int playerId, FrameInfo frameInfo, ref bool frameDrop); + + public abstract bool UpdateMaterial(UnityEngine.Material material); + + public abstract void UpdateTextures(); + + public abstract bool IsSuitable(int playerId, MovieInfo movieInfo, bool additive, UnityEngine.Shader userShader); + + public virtual void OnPlayerPause(bool pauseStatus, bool triggredFromApplciationPause) {} + + public virtual void OnPlayerStop() { } + + public virtual bool OnPlayerStopForSeek() { return false; } + + public virtual void OnPlayerStart() { } + + public virtual bool ShouldSkipDestroyOnStopForSeek() { return false; } + + public virtual bool HasRenderedNewFrame() { return true; } + + public static uint NextPowerOfTwo(uint x) + { + x = x - 1; + x = x | (x >> 1); + x = x | (x >> 2); + x = x | (x >> 4); + x = x | (x >> 8); + x = x | (x >>16); + return x + 1; + } + + public static int NextPowerOfTwo(int x) + { + return (int)NextPowerOfTwo((uint)x); + } + + public static int CeilingWith(int x, int ceilingValue) + { + return (x+ceilingValue-1) & -ceilingValue; + } + + public static int Ceiling16(int x) + { + return (x+15)& -16; + } + + public static int Ceiling32(int x) + { + return (x+31)& -32; + } + + public static int Ceiling64(int x) + { + return (x+63)& -64; + } + + public static int Ceiling256(int x) + { + return (x+255)& -256; + } + + protected static void DisposeTextures(Texture[] textures) + { + if (textures == null) { + return; + } + + for (int i = 0; i < textures.Length; i++) { + if (textures[i] != null) { +#if UNITY_EDITOR + if (UnityEditor.EditorApplication.isPlaying == false) { + Texture2D.DestroyImmediate(textures[i]); + } else { + Texture2D.Destroy(textures[i]); + } +#else + Texture2D.Destroy(textures[i]); +#endif + textures[i] = null; + } + } + } + + protected static void SetKeyword(Material material, string keyword, bool flag) + { + if (flag) { + material.EnableKeyword(keyword); + } else { + material.DisableKeyword(keyword); + } + } + + #region DLL Import + #if !CRIWARE_ENABLE_HEADLESS_MODE + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + protected static extern bool CRIWARE9061FF01( + int player_id, + int num_textures, + System.IntPtr[] tex_ptrs, + [In, Out] FrameInfo frame_info, + ref bool frame_drop // in -> Can drop a frame?, out -> Is Frame dropped? + ); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + protected static extern bool CRIWAREDA63C3D7( + int player_id, + int num_textures, + [In, Out] System.IntPtr[] tex_ptrs + ); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + protected static extern bool CRIWARE71A23DE1( + int player_id, + int num_textures, + [In, Out] System.IntPtr[] tex_ptrs + ); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + protected static extern bool CRIWARE2676F2A5( + int player_id, + int num_textures, + [In, Out] System.IntPtr[] tex_ptrs + ); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + protected static extern sbyte CRIWAREB970989D( + int player_id + ); + #else + protected static bool CRIWARE9061FF01( + int player_id, + int num_textures, + System.IntPtr[] tex_ptrs, + [In, Out] FrameInfo frame_info, + ref bool frame_drop + ) { return true; } + + protected static bool CRIWAREDA63C3D7( + int player_id, + int num_textures, + [In, Out] System.IntPtr[] tex_ptrs + ) { return true; } + + protected static bool CRIWARE71A23DE1( + int player_id, + int num_textures, + [In, Out] System.IntPtr[] tex_ptrs + ) { return true; } + + protected static bool CRIWARE2676F2A5( + int player_id, + int num_textures, + [In, Out] System.IntPtr[] tex_ptrs + ) { return true; } + + protected static sbyte CRIWAREB970989D( + int player_id + ) { return 0; } + #endif + #endregion + } + + + + + public abstract class RendererResourceFactory : System.IDisposable + { + #region Static + static private SortedList factoryList = new SortedList(); + + static public void RegisterFactory(RendererResourceFactory factory, int priority) + { + factoryList.Add(priority, factory); + } + + static public void DisposeAllFactories() + { + foreach (var factoryWithPriority in factoryList) { + factoryWithPriority.Value.Dispose(); + } + factoryList.Clear(); + } + + static public RendererResource DispatchAndCreate(int playerId, MovieInfo movieInfo, bool additive, UnityEngine.Shader userShader) + { + RendererResource rendererResource = null; + + foreach (var factoryWithPriority in factoryList) { + rendererResource = factoryWithPriority.Value.CreateRendererResource(playerId, movieInfo, additive, userShader); + if (rendererResource != null) { + return rendererResource; + } + } + + UnityEngine.Debug.LogError("[CRIWARE] unsupported movie."); + return null; + } + #endregion + + + #region Instance + private bool disposed = false; + + ~RendererResourceFactory() + { + Dispose(false); + } + + public void Dispose() + { + this.Dispose(true); + System.GC.SuppressFinalize(this); + } + + private void Dispose(bool disposing) + { + if (disposed) { + return; + } + if (disposing) { + OnDisposeManaged(); + } + OnDisposeUnmanaged(); + disposed = true; + } + + protected abstract void OnDisposeManaged(); + + protected abstract void OnDisposeUnmanaged(); + + public abstract RendererResource CreateRendererResource(int playerId, MovieInfo movieInfo, bool additive, UnityEngine.Shader userShader); + #endregion + } + + + + + [System.AttributeUsage(System.AttributeTargets.Class)] + public class RendererResourceFactoryPriorityAttribute : System.Attribute + { + public readonly int priority; + public RendererResourceFactoryPriorityAttribute(int priority) + { + this.priority = priority; + } + } + + + + + public static partial class AutoResisterRendererResourceFactories + { + public static void InvokeAutoRegister() + { + var factoryTypes = typeof(AutoResisterRendererResourceFactories).GetNestedTypes(BindingFlags.Public); + foreach (var factoryType in factoryTypes) { +#if !UNITY_EDITOR && (ENABLE_DOTNET || (UNITY_WINRT && !ENABLE_IL2CPP)) + if (!factoryType.GetTypeInfo().IsSubclassOf(typeof(RendererResourceFactory))) { +#else + if (!factoryType.IsSubclassOf(typeof(RendererResourceFactory))) { +#endif + UnityEngine.Debug.LogError("[CRIWARE] internal logic error. " + factoryType.Name + " is required to be a subclass of RendererResourceFactory."); + continue; + } +#if !UNITY_EDITOR && (ENABLE_DOTNET || (UNITY_WINRT && !ENABLE_IL2CPP)) + var priorityAttribute = (RendererResourceFactoryPriorityAttribute)CustomAttributeExtensions.GetCustomAttribute( + factoryType.GetTypeInfo(), + typeof(RendererResourceFactoryPriorityAttribute) + ); +#else + var priorityAttribute = (RendererResourceFactoryPriorityAttribute)System.Attribute.GetCustomAttribute( + factoryType, + typeof(RendererResourceFactoryPriorityAttribute) + ); +#endif + if (priorityAttribute == null) { + UnityEngine.Debug.LogError("[CRIWARE] internal logic error. need priority attribute. (" + factoryType.Name + ")"); + continue; + } + RendererResourceFactory.RegisterFactory( + (RendererResourceFactory)System.Activator.CreateInstance(factoryType), + priorityAttribute.priority + ); + } + } + } + +#if CRIWARE_ENABLE_HEADLESS_MODE + public static partial class AutoResisterRendererResourceFactories + { + [RendererResourceFactoryPriority(4000)] + public class RendererResourceFactoryDummy : RendererResourceFactory + { + public override RendererResource CreateRendererResource(int playerId, MovieInfo movieInfo, bool additive, UnityEngine.Shader userShader) + { + return new RendererResourceDummy(playerId, movieInfo, additive, userShader); + } + protected override void OnDisposeManaged() { } + protected override void OnDisposeUnmanaged() { } + } + } + + public class RendererResourceDummy : RendererResource + { + public RendererResourceDummy(int playerId, MovieInfo movieInfo, bool additive, UnityEngine.Shader userShader) { } + protected override void OnDisposeManaged() { } + protected override void OnDisposeUnmanaged() { } + public override bool IsPrepared() { return true; } + public override bool ContinuePreparing() { return true; } + public override bool IsSuitable(int playerId, MovieInfo movieInfo, bool additive, UnityEngine.Shader userShader) { return true; } + public override void SetApplyTargetAlpha(bool flag) { } + public override void AttachToPlayer(int playerId) { } + public override bool UpdateFrame(int playerId, FrameInfo frameInfo, ref bool frameDrop) { return true; } + public override bool UpdateMaterial(UnityEngine.Material material) { return true; } + private void UpdateMovieTextureST(System.UInt32 dispWidth, System.UInt32 dispHeight) { } + public override void UpdateTextures(){ } + } +#endif +} + +} //namespace CriWare \ No newline at end of file diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Detail/RendererResource.cs.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Detail/RendererResource.cs.meta new file mode 100644 index 0000000..5e97a99 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Detail/RendererResource.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 7932296e7ee8941a1b2b4ddfd1586559 +timeCreated: 1445063317 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Detail/RendererResources.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Detail/RendererResources.meta new file mode 100644 index 0000000..786bbc3 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Detail/RendererResources.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: e10b99d23434c474eab135cb7659364f +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Detail/RendererResources/SofdecPrimeRgb.cs b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Detail/RendererResources/SofdecPrimeRgb.cs new file mode 100644 index 0000000..0929cdc --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Detail/RendererResources/SofdecPrimeRgb.cs @@ -0,0 +1,203 @@ +/**************************************************************************** + * + * Copyright (c) 2015 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +#if !UNITY_EDITOR && (UNITY_PS3 || UNITY_WINRT) + +using UnityEngine; +using System.Runtime.InteropServices; + +namespace CriWare { + +namespace CriMana.Detail +{ + public static partial class AutoResisterRendererResourceFactories + { + [RendererResourceFactoryPriority(5050)] + public class RendererResourceFactorySofdecPrimeRgb : RendererResourceFactory + { + public override RendererResource CreateRendererResource(int playerId, MovieInfo movieInfo, bool additive, Shader userShader) + { + bool isCodecSuitable = movieInfo.codecType == CodecType.SofdecPrime; + bool isSuitable = isCodecSuitable; + return isSuitable + ? new RendererResourceSofdecPrimeRgb(playerId, movieInfo, additive, userShader) + : null; + } + + protected override void OnDisposeManaged() + { + } + + protected override void OnDisposeUnmanaged() + { + } + } + } + + + + + public class RendererResourceSofdecPrimeRgb : RendererResource + { + private int width; + private int height; + private bool useUserShader; + + private Vector4 movieTextureST = Vector4.zero; + + private Texture2D texture; + private Color32[] pixels; + private GCHandle pixelsHandle; + private bool isTextureReady; + + + public RendererResourceSofdecPrimeRgb(int playerId, MovieInfo movieInfo, bool additive, Shader userShader) + { +#if UNITY_EDITOR || UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX || UNITY_PSP2 || UNITY_PS5 || UNITY_PS4 || UNITY_PS3 || UNITY_WINRT || UNITY_SWITCH + width = Ceiling64((int)movieInfo.width); + height = Ceiling64((int)movieInfo.height); +#elif UNITY_ANDROID || UNITY_IOS || UNITY_TVOS + width = NextPowerOfTwo((int)movieInfo.width); + height = NextPowerOfTwo((int)movieInfo.height); +#else + #error unsupported platform +#endif + hasAlpha = movieInfo.hasAlpha; + this.additive = additive; + useUserShader = userShader != null; + + if (userShader != null) { + shader = userShader; + } else { + string shaderName = "CriMana/SofdecPrimeRgb"; + shader = Shader.Find(shaderName); + } + + UpdateMovieTextureST(movieInfo.dispWidth, movieInfo.dispHeight); + + texture = new Texture2D(width, height, TextureFormat.RGBA32, false); + texture.wrapMode = TextureWrapMode.Clamp; + pixels = texture.GetPixels32(0); + pixelsHandle = GCHandle.Alloc(pixels, GCHandleType.Pinned); + } + + + protected override void OnDisposeManaged() + { + } + + + protected override void OnDisposeUnmanaged() + { + if (texture != null) { + if (pixelsHandle.IsAllocated == true) { + pixelsHandle.Free(); + } + } + if (texture != null) { + Texture2D.Destroy(texture); + } + texture = null; + pixels = null; + currentMaterial = null; + } + + + public override bool IsPrepared() + { return isTextureReady; } + + + public override bool ContinuePreparing() + { return true; } + + + public override bool IsSuitable(int playerId, MovieInfo movieInfo, bool additive, Shader userShader) + { + bool isCodecSuitable = movieInfo.codecType == CodecType.SofdecPrime; + bool isSizeSuitable = (width >= (int)movieInfo.width) && (height >= (int)movieInfo.height); + bool isAlphaSuitable = hasAlpha == movieInfo.hasAlpha; + bool isAdditiveSuitable = this.additive == additive; + bool isShaderSuitable = this.useUserShader ? (userShader == shader) : true; + return isCodecSuitable && isSizeSuitable && isAlphaSuitable && isAdditiveSuitable && isShaderSuitable; + } + + + public override void AttachToPlayer(int playerId) + { + isTextureReady = false; + } + + + public override bool UpdateFrame(int playerId, FrameInfo frameInfo, ref bool frameDrop) + { + // Note: This renderer use a deprecated API: CRIWARE1DE4FE72. + // Todo: use CRIWAREDA63C3D7 with a c++ rendereDecoder class if needed. + bool isFrameUpdated = CRIWARE1DE4FE72( + playerId, + pixelsHandle.AddrOfPinnedObject(), + frameInfo, + width + ); + if (isFrameUpdated) { + texture.SetPixels32(pixels, 0); + texture.Apply(); + UpdateMovieTextureST(frameInfo.dispWidth, frameInfo.dispHeight); + isTextureReady = true; + } + // Frame dropping cannot be supported with deprecated API. + frameDrop = false; + return isFrameUpdated; + } + + + public override bool UpdateMaterial(Material material) + { + if (currentMaterial != material) { + currentMaterial = material; + SetupStaticMaterialProperties(); + //Temporary fix for Switch +#if !UNITY_EDITOR && UNITY_SWITCH + material.EnableKeyword("CRI_SWITCH"); +#endif + material.mainTexture = texture; + material.SetTexture("_TextureRGBA", texture); + } + material.SetVector("_MovieTexture_ST", movieTextureST); + return true; + } + + + private void UpdateMovieTextureST(System.UInt32 dispWidth, System.UInt32 dispHeight) + { + float uScale = (float)(dispWidth) / width; + float vScale = (float)(dispHeight) / height; + movieTextureST.x = uScale; + movieTextureST.y = -vScale; + movieTextureST.z = 0.0f; + movieTextureST.w = vScale; + } + + + public override void UpdateTextures() + { + } + + + #region Native API Definitions + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool CRIWARE1DE4FE72( + int player_id, + System.IntPtr texbuf, + [In, Out] FrameInfo frame_info, + int texbuf_width + ); + #endregion + } +} + +} //namespace CriWare + +#endif diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Detail/RendererResources/SofdecPrimeRgb.cs.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Detail/RendererResources/SofdecPrimeRgb.cs.meta new file mode 100644 index 0000000..667fe3d --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Detail/RendererResources/SofdecPrimeRgb.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: d3b0e9bed2abd4b9c9d2e11433545756 +timeCreated: 1445063317 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Detail/RendererResources/SofdecPrimeYuv.cs b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Detail/RendererResources/SofdecPrimeYuv.cs new file mode 100644 index 0000000..752a343 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Detail/RendererResources/SofdecPrimeYuv.cs @@ -0,0 +1,287 @@ +/**************************************************************************** + * + * Copyright (c) 2015-2018 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +#if UNITY_EDITOR || UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX || UNITY_PSP2 || UNITY_IOS || UNITY_TVOS || UNITY_WEBGL || UNITY_STANDALONE_LINUX || UNITY_STADIA + +using UnityEngine; +using System; + +namespace CriWare { + +namespace CriMana.Detail +{ + public static partial class AutoResisterRendererResourceFactories + { + [RendererResourceFactoryPriority(5000)] + public class RendererResourceFactorySofdecPrimeYuv : RendererResourceFactory + { + public override RendererResource CreateRendererResource(int playerId, MovieInfo movieInfo, bool additive, Shader userShader) + { + bool isCodecSuitable = movieInfo.codecType == CodecType.SofdecPrime; + #if (UNITY_EDITOR || !UNITY_SWITCH) + isCodecSuitable |= movieInfo.codecType == CodecType.VP9; + #endif + bool isSuitable = isCodecSuitable; + return isSuitable + ? new RendererResourceSofdecPrimeYuv(playerId, movieInfo, additive, userShader) + : null; + } + + protected override void OnDisposeManaged() + { + } + + protected override void OnDisposeUnmanaged() + { + } + } + } + + + + + public class RendererResourceSofdecPrimeYuv : RendererResource + { + private int width; + private int height; + private bool useUserShader; + private CodecType codecType; + + private Vector4 movieTextureST = Vector4.zero; + private Vector4 movieChromaTextureST = Vector4.zero; + + private static Int32 NumTextureSets { get { return 1; } } + + private Texture2D[] textureY = new Texture2D[NumTextureSets]; + private Texture2D[] textureU = new Texture2D[NumTextureSets]; + private Texture2D[] textureV = new Texture2D[NumTextureSets]; + private Texture2D[] textureA = new Texture2D[NumTextureSets]; + private IntPtr[] nativeTextures; + private Int32 currentTextureSet = 0; + private Int32 drawTextureSet = 0; + + private Int32 playerID; + private bool hasTextureUpdated = false; + private bool isTextureReady = false; + private bool hasRenderedNewFrame = false; + + + public RendererResourceSofdecPrimeYuv(int playerId, MovieInfo movieInfo, bool additive, Shader userShader) + { +#if UNITY_EDITOR || UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX || UNITY_PSP2 || UNITY_PS4 || UNITY_WINRT || UNITY_WEBGL || UNITY_STANDALONE_LINUX || UNITY_SWITCH || UNITY_STADIA + width = Ceiling256((int)movieInfo.width); + height = Ceiling16((int)movieInfo.height); +#elif UNITY_IOS || UNITY_TVOS + width = NextPowerOfTwo(Ceiling64((int)movieInfo.width)); + height = NextPowerOfTwo(Ceiling16((int)movieInfo.height)); +#else + #error unsupported platform +#endif + this.additive = additive; + hasAlpha = movieInfo.hasAlpha; + useUserShader = userShader != null; + codecType = movieInfo.codecType; + + if (useUserShader) { + shader = userShader; + } else { + string shaderName = "CriMana/SofdecPrimeYuv"; + shader = Shader.Find(shaderName); + } + + UpdateMovieTextureST(movieInfo.dispWidth, movieInfo.dispHeight); + + for (int i = 0; i < NumTextureSets; i++) { + textureY[i] = new Texture2D(width, height, TextureFormat.Alpha8, false); + textureY[i].wrapMode = TextureWrapMode.Clamp; + textureU[i] = new Texture2D(width / 2, height / 2, TextureFormat.Alpha8, false); + textureU[i].wrapMode = TextureWrapMode.Clamp; + textureV[i] = new Texture2D(width / 2, height / 2, TextureFormat.Alpha8, false); + textureV[i].wrapMode = TextureWrapMode.Clamp; + if (hasAlpha) { + textureA[i] = new Texture2D(width, height, TextureFormat.Alpha8, false); + textureA[i].wrapMode = TextureWrapMode.Clamp; + } + } + nativeTextures = new IntPtr[4]; + + playerID = playerId; + } + + + protected override void OnDisposeManaged() + { + } + + static private bool IsEditor { + get { +#if UNITY_EDITOR + if (UnityEditor.EditorApplication.isPlaying == false) { + return true; + } +#endif + return false; + } + } + + protected override void OnDisposeUnmanaged() + { + CRIWARE2676F2A5(playerID, 0 ,null); + + for (int i = 0; i < NumTextureSets; i++) { + if (textureY[i] != null) { + if(IsEditor){ + Texture2D.DestroyImmediate(textureY[i]); + } else{ + Texture2D.Destroy(textureY[i]); + } + textureY[i] = null; + } + if (textureU[i] != null) { + if (IsEditor) { + Texture2D.DestroyImmediate(textureU[i]); + } else { + Texture2D.Destroy(textureU[i]); + } + textureU[i] = null; + } + if (textureV[i] != null) { + if (IsEditor) { + Texture2D.DestroyImmediate(textureV[i]); + } else { + Texture2D.Destroy(textureV[i]); + } + textureV[i] = null; + } + if (textureA[i] != null) { + if (IsEditor) { + Texture2D.DestroyImmediate(textureA[i]); + } else { + Texture2D.Destroy(textureA[i]); + } + textureA[i] = null; + } + } + } + + + public override bool IsPrepared() + { return isTextureReady; } + + + public override bool ContinuePreparing() + { return true; } + + + public override bool IsSuitable(int playerId, MovieInfo movieInfo, bool additive, Shader userShader) + { + bool isCodecSuitable = movieInfo.codecType == codecType; + bool isSizeSuitable = (width >= (int)movieInfo.width) && (height >= (int)movieInfo.height); + bool isAlphaSuitable = hasAlpha == movieInfo.hasAlpha; + bool isAdditiveSuitable = this.additive == additive; + bool isShaderSuitable = this.useUserShader ? (userShader == shader) : true; + return isCodecSuitable && isSizeSuitable && isAlphaSuitable && isAdditiveSuitable && isShaderSuitable; + } + + + public override bool OnPlayerStopForSeek() + { + hasRenderedNewFrame = false; + return true; + } + + + public override bool HasRenderedNewFrame() + { + return hasRenderedNewFrame; + } + + + public override void AttachToPlayer(int playerId) + { + CRIWARE71A23DE1(playerID, 0, new IntPtr[1]); + hasRenderedNewFrame = false; + hasTextureUpdated = false; + isTextureReady = false; + } + + + public override bool UpdateFrame(int playerId, FrameInfo frameInfo, ref bool frameDrop) + { + bool isFrameUpdated = CRIWARE9061FF01(playerId, 0, null, frameInfo, ref frameDrop); + if (isFrameUpdated && !frameDrop) { + UpdateMovieTextureST(frameInfo.dispWidth, frameInfo.dispHeight); + drawTextureSet = currentTextureSet; + currentTextureSet = (currentTextureSet + 1) % NumTextureSets; + } + if (hasTextureUpdated) { + isTextureReady = true; + } + return isFrameUpdated; + } + + + public override bool UpdateMaterial(Material material) + { + if (!isTextureReady && NumTextureSets > 1) + return false; + + if (currentMaterial != material) { + currentMaterial = material; + SetupStaticMaterialProperties(); + } + material.SetTexture("_TextureY", textureY[drawTextureSet]); + material.SetTexture("_TextureU", textureU[drawTextureSet]); + material.SetTexture("_TextureV", textureV[drawTextureSet]); + material.SetVector("_MovieTexture_ST", movieTextureST); + material.SetVector("_MovieChromaTexture_ST", movieChromaTextureST); + if (hasAlpha) { + material.SetTexture("_TextureA", textureA[drawTextureSet]); + material.SetVector("_MovieAlphaTexture_ST", movieTextureST); + } + hasRenderedNewFrame = isTextureReady; + + return true; + } + + + private void UpdateMovieTextureST(System.UInt32 dispWidth, System.UInt32 dispHeight) + { + float uScale = (dispWidth != width) ? (float)(dispWidth - 1) / width : 1.0f; + float vScale = (dispHeight != height) ? (float)(dispHeight - 1) / height : 1.0f; + movieTextureST.x = uScale; + movieTextureST.y = -vScale; + movieTextureST.z = 0.0f; + movieTextureST.w = vScale; + + uScale = (dispWidth != width) ? (float)(dispWidth / 2 - 1) / width * 2 : 1.0f; + vScale = (dispHeight != height) ? (float)(dispHeight / 2 - 1) / height * 2 : 1.0f; + movieChromaTextureST.x = uScale; + movieChromaTextureST.y = -vScale; + movieChromaTextureST.z = 0.0f; + movieChromaTextureST.w = vScale; + } + + + public override void UpdateTextures() + { + int numTextures = 3; + nativeTextures[0] = textureY[currentTextureSet].GetNativeTexturePtr(); + nativeTextures[1] = textureU[currentTextureSet].GetNativeTexturePtr(); + nativeTextures[2] = textureV[currentTextureSet].GetNativeTexturePtr(); + if (hasAlpha) { + numTextures = 4; + nativeTextures[3] = textureA[currentTextureSet].GetNativeTexturePtr(); + } + + hasTextureUpdated |= CRIWAREDA63C3D7(playerID, numTextures, nativeTextures); + } + } +} + +} //namespace CriWare + +#endif diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Detail/RendererResources/SofdecPrimeYuv.cs.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Detail/RendererResources/SofdecPrimeYuv.cs.meta new file mode 100644 index 0000000..d259070 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Detail/RendererResources/SofdecPrimeYuv.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: e47a575e88bc94951879c95d6f513a85 +timeCreated: 1445063321 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Detail/RendererResources/SofdecPrimeYuvRawData.cs b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Detail/RendererResources/SofdecPrimeYuvRawData.cs new file mode 100644 index 0000000..08a8334 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Detail/RendererResources/SofdecPrimeYuvRawData.cs @@ -0,0 +1,280 @@ +/**************************************************************************** + * + * Copyright (c) 2020 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +using UnityEngine; +using System; +using System.Runtime.InteropServices; + +namespace CriWare { + +namespace CriMana.Detail +{ + + // Fallback to this renderer if none are usable (Prime) + + public static partial class AutoResisterRendererResourceFactories + { + [RendererResourceFactoryPriority(10000)] + public class RendererResourceFactorySofdecPrimeYuvRawData : RendererResourceFactory + { + public override RendererResource CreateRendererResource(int playerId, MovieInfo movieInfo, bool additive, Shader userShader) + { + bool isCodecSuitable = movieInfo.codecType == CodecType.SofdecPrime; + #if (UNITY_EDITOR || !UNITY_SWITCH) + isCodecSuitable |= movieInfo.codecType == CodecType.VP9; + #endif + #if (!UNITY_STANDALONE && UNITY_GAMECORE) + isCodecSuitable |= movieInfo.codecType == CodecType.H264; + #endif + bool isSuitable = isCodecSuitable; + return isSuitable + ? new RendererResourceSofdecPrimeYuvRawData(playerId, movieInfo, additive, userShader) + : null; + } + + protected override void OnDisposeManaged() + { + } + + protected override void OnDisposeUnmanaged() + { + } + } + } + + + public class RendererResourceSofdecPrimeYuvRawData : RendererResource + { + private int width, height; + private int chromaWidth, chromaHeight; + private bool useUserShader; + private CodecType codecType; + + private Vector4 movieTextureST = Vector4.zero; + private Vector4 movieChromaTextureST = Vector4.zero; + + private static Int32 NumTextureSets { get { return 1; } } + + private Texture2D[][] textures = new Texture2D[NumTextureSets][]; + private Int32 currentTextureSet = 0; + private Int32 drawTextureSet = 0; + System.IntPtr[] nativePixels; + + private Int32 playerID; + private bool hasTextureUpdated = false; + private bool isTextureReady = false; + private bool hasRenderedNewFrame = false; + + public RendererResourceSofdecPrimeYuvRawData(int playerId, MovieInfo movieInfo, bool additive, Shader userShader) + { + CalculateTextureSize(ref width, ref height, (int)movieInfo.width, (int)movieInfo.height, movieInfo.codecType, false); + CalculateTextureSize(ref chromaWidth, ref chromaHeight, (int)movieInfo.width, (int)movieInfo.height, movieInfo.codecType, true); + + this.additive = additive; + hasAlpha = movieInfo.hasAlpha; + useUserShader = userShader != null; + codecType = movieInfo.codecType; + + if (useUserShader) { + shader = userShader; + } else { + string shaderName = "CriMana/SofdecPrimeYuv"; + shader = Shader.Find(shaderName); + } + + UpdateMovieTextureST(movieInfo.dispWidth, movieInfo.dispHeight); + + for (int i = 0; i < NumTextureSets; i++) { + textures[i] = new Texture2D[hasAlpha ? 4 : 3]; + textures[i][0] = new Texture2D(width, height, TextureFormat.Alpha8, false); + textures[i][0].wrapMode = TextureWrapMode.Clamp; + textures[i][1] = new Texture2D(chromaWidth, chromaHeight, TextureFormat.Alpha8, false); + textures[i][1].wrapMode = TextureWrapMode.Clamp; + textures[i][2] = new Texture2D(chromaWidth, chromaHeight, TextureFormat.Alpha8, false); + textures[i][2].wrapMode = TextureWrapMode.Clamp; + if (hasAlpha) { + textures[i][3] = new Texture2D(width, height, TextureFormat.Alpha8, false); + textures[i][3].wrapMode = TextureWrapMode.Clamp; + } + } + nativePixels = new IntPtr[hasAlpha ? 4 : 3]; + + playerID = playerId; + } + + + protected override void OnDisposeManaged() + { + } + + + protected override void OnDisposeUnmanaged() + { + CRIWARE2676F2A5(playerID, 0 ,null); + + for (int i = 0; i < NumTextureSets; i++) { + DisposeTextures(textures[i]); + } + textures = null; + } + + + public override bool IsPrepared() + { return isTextureReady; } + + + public override bool ContinuePreparing() + { return true; } + + + public override bool IsSuitable(int playerId, MovieInfo movieInfo, bool additive, Shader userShader) + { + bool isCodecSuitable = movieInfo.codecType == codecType; + bool isSizeSuitable = (width >= (int)movieInfo.width) && (height >= (int)movieInfo.height); + bool isAlphaSuitable = hasAlpha == movieInfo.hasAlpha; + bool isAdditiveSuitable = this.additive == additive; + bool isShaderSuitable = this.useUserShader ? (userShader == shader) : true; + return isCodecSuitable && isSizeSuitable && isAlphaSuitable && isAdditiveSuitable && isShaderSuitable; + } + + public override bool OnPlayerStopForSeek() + { + hasTextureUpdated = false; + hasRenderedNewFrame = false; + return true; + } + + + public override bool HasRenderedNewFrame() + { + return hasRenderedNewFrame; + } + + public override void AttachToPlayer(int playerId) + { + CRIWARE71A23DE1(playerID, 0, new IntPtr[1]); + hasTextureUpdated = false; + hasRenderedNewFrame = false; + isTextureReady = false; + } + + + public override bool UpdateFrame(int playerId, FrameInfo frameInfo, ref bool frameDrop) + { + bool isFrameUpdated = CRIWARE9061FF01(playerId, 0, null, frameInfo, ref frameDrop); + if (isFrameUpdated && !frameDrop) { + UpdateMovieTextureST(frameInfo.dispWidth, frameInfo.dispHeight); + drawTextureSet = currentTextureSet; + currentTextureSet = (currentTextureSet + 1) % NumTextureSets; + } + if (hasTextureUpdated) { + isTextureReady = true; + } + return isFrameUpdated; + } + + + public override bool UpdateMaterial(Material material) + { + if (!isTextureReady && NumTextureSets > 1) + return false; + + if (currentMaterial != material) { + currentMaterial = material; + SetupStaticMaterialProperties(); + } + + material.SetTexture("_TextureY", textures[drawTextureSet][0]); + material.SetTexture("_TextureU", textures[drawTextureSet][1]); + material.SetTexture("_TextureV", textures[drawTextureSet][2]); + material.SetVector("_MovieTexture_ST", movieTextureST); + material.SetVector("_MovieChromaTexture_ST", movieChromaTextureST); + if (hasAlpha) { + material.SetTexture("_TextureA", textures[drawTextureSet][3]); + material.SetVector("_MovieAlphaTexture_ST", movieTextureST); + } + hasRenderedNewFrame = isTextureReady; + + return true; + } + + + private void UpdateMovieTextureST(System.UInt32 dispWidth, System.UInt32 dispHeight) + { + float uScale = (dispWidth != width) ? (float)(dispWidth - 1) / width : 1.0f; + float vScale = (dispHeight != height) ? (float)(dispHeight - 1) / height : 1.0f; + movieTextureST.x = uScale; + movieTextureST.y = -vScale; + movieTextureST.z = 0.0f; + movieTextureST.w = vScale; + + uScale = (dispWidth != chromaWidth * 2) ? (float)(dispWidth / 2 - 1) / (chromaWidth * 2) * 2 : 1.0f; + vScale = (dispHeight != chromaHeight * 2) ? (float)(dispHeight / 2 - 1) / (chromaHeight * 2) * 2 : 1.0f; + movieChromaTextureST.x = uScale; + movieChromaTextureST.y = -vScale; + movieChromaTextureST.z = 0.0f; + movieChromaTextureST.w = vScale; + } + + + public override void UpdateTextures() + { + int numTextures = hasAlpha ? 4 : 3; + nativePixels[0] = System.IntPtr.Zero; + + // update pinned pointers with ptr from native code + hasTextureUpdated |= CRIWAREDA63C3D7(playerID, numTextures, nativePixels); + + // copy native data to texture pixels + if (hasTextureUpdated && nativePixels[0] != System.IntPtr.Zero) { + textures[currentTextureSet][0].LoadRawTextureData(nativePixels[0], width * height); + textures[currentTextureSet][1].LoadRawTextureData(nativePixels[1], chromaWidth * chromaHeight); + textures[currentTextureSet][2].LoadRawTextureData(nativePixels[2], chromaWidth * chromaHeight); + + textures[currentTextureSet][0].Apply(); + textures[currentTextureSet][1].Apply(); + textures[currentTextureSet][2].Apply(); + + if (hasAlpha) { + textures[currentTextureSet][3].LoadRawTextureData(nativePixels[3], width * height); + textures[currentTextureSet][3].Apply(); + } + } + } + + private static void CalculateTextureSize(ref int w, ref int h, int videoWidth, int videoHeight, CodecType type, bool isChroma) + { + if (type == CodecType.SofdecPrime) { + if (!isChroma) { + w = Ceiling64(Ceiling16(CeilingWith(videoWidth, 8))); + h = CeilingWith(videoHeight, 8); + } else { + w = Ceiling64(Ceiling16(CeilingWith(videoWidth, 8)) / 2); + h = CeilingWith(videoHeight, 8) / 2; + } + + } else if (type == CodecType.VP9) { + if (!isChroma) { + w = CeilingWith(CeilingWith(videoWidth, 2), 8); + h = CeilingWith(videoHeight, 2); + } else { + w = CeilingWith(CeilingWith(videoWidth, 2) / 2, 8); + h = CeilingWith(videoHeight, 2) / 2; + } + } else if (type == CodecType.H264) { + if (!isChroma) { + w = videoWidth; + h = videoHeight; + } else { + w = CeilingWith(videoWidth / 2, 8); + h = CeilingWith(videoHeight, 2) / 2; + } + } + } + } +} + +} //namespace CriWare \ No newline at end of file diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Detail/RendererResources/SofdecPrimeYuvRawData.cs.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Detail/RendererResources/SofdecPrimeYuvRawData.cs.meta new file mode 100644 index 0000000..59d4186 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Detail/RendererResources/SofdecPrimeYuvRawData.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 74dfffafbdffc8441b8550df24cfeb9c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Extension.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Extension.meta new file mode 100644 index 0000000..606dc85 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Extension.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: b4f4f177caaed964d866f5d7d20644ff +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Extension/CriManaBehaviour.cs b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Extension/CriManaBehaviour.cs new file mode 100644 index 0000000..0361431 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Extension/CriManaBehaviour.cs @@ -0,0 +1,22 @@ +/**************************************************************************** + * + * Copyright (c) 2019 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +#if UNITY_2018_1_OR_NEWER && CRIWARE_TIMELINE_1_OR_NEWER + +using System; +using UnityEngine.Playables; + +namespace CriWare { + +namespace CriTimeline.Mana +{ + [Serializable] + public class CriManaBehaviour : PlayableBehaviour { } +} + +} //namespace CriWare + +#endif \ No newline at end of file diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Extension/CriManaBehaviour.cs.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Extension/CriManaBehaviour.cs.meta new file mode 100644 index 0000000..6aa14ba --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Extension/CriManaBehaviour.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 749c916c7dbf95445a82abfc6479b84a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Extension/CriManaClip.cs b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Extension/CriManaClip.cs new file mode 100644 index 0000000..e345dbe --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Extension/CriManaClip.cs @@ -0,0 +1,171 @@ +/**************************************************************************** + * + * Copyright (c) 2019 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +#if UNITY_2018_1_OR_NEWER && CRIWARE_TIMELINE_1_OR_NEWER + +using System; +using System.Runtime.InteropServices; +using UnityEngine; +using UnityEngine.Playables; +using UnityEngine.Timeline; + +namespace CriWare { + +namespace CriTimeline.Mana +{ + public class CriManaClip : CriManaClipBase + { + public string m_moviePath = ""; + public TextAsset m_movieData = null; + + public override string MoviePath { + get { + return m_moviePath; + } + } + + public override byte[] MovieData + { + get + { + return (m_movieData == null) ? null : m_movieData.bytes; + } + } + + public override string MovieName + { + get { + return (m_movieData != null) ? m_movieData.name : System.IO.Path.GetFileNameWithoutExtension(m_moviePath); + } + } + + public override int DataId { + get { + if(m_movieData == null) + { + Debug.LogError("[CRIWARE] This property is undefined when the movie is referenced by its file path."); + return 0; + } + return m_movieData.GetInstanceID(); + } + } + } + + public abstract class CriManaClipBase : PlayableAsset , ITimelineClipAsset + { + private struct MovieInfoStruct { + public UInt32 width; /**< ムービ最大幅(8の倍数) */ + public UInt32 height; /**< ムービ最大高さ(8の倍数) */ + public UInt32 dispWidth; /**< 表示したい映像の横ピクセル数(左端から) */ + public UInt32 dispHeight; /**< 表示したい映像の縦ピクセル数(上端から) */ + public UInt32 framerateN; /**< 有理数形式フレームレート(分子) framerate [x1000] = framerateN / framerateD */ + public UInt32 framerateD; /**< 有理数形式フレームレート(分母) framerate [x1000] = framerateN / framerateD */ + public UInt32 totalFrames; /**< 総フレーム数 */ + public CriMana.CodecType _codecType; + public CriMana.CodecType _alphaCodecType; + } + + public abstract string MoviePath { get; } + public abstract byte[] MovieData { get; } + public abstract string MovieName { get; } + public abstract int DataId { get; } + + public readonly Guid guid = Guid.NewGuid(); + public bool m_loopWithinClip = false; + public bool m_useOnMemoryPlayback = false; + public GCHandle gcHandle = default(GCHandle); + [SerializeField] private double m_movieFrameRate = 0.0; + [SerializeField] private double m_clipDuration = 0.0; + + public float m_fadeinDuration = 0f; + public AnimationCurve m_fadeinCurve = AnimationCurve.Linear(0f, 0f, 1f, 1f); + public float m_fadeoutDuration = 0f; + public AnimationCurve m_fadeoutCurve = AnimationCurve.Linear(0f, 1f, 1f, 0f); + public bool m_fadeAudio = true; + [NonSerialized] + public TimelineClip m_clip; + + public CriManaBehaviour m_manaBehaviour = new CriManaBehaviour(); + private MovieInfoStruct? m_movieInfoStruct = null; + + private MovieInfoStruct? StructToMovieInfo(CriMana.MovieInfo movieInfo){ + if (movieInfo == null) { + return null; + } + + MovieInfoStruct infoStruct = new MovieInfoStruct { + width = movieInfo.width, + height = movieInfo.height, + dispWidth = movieInfo.dispWidth, + dispHeight = movieInfo.dispHeight, + framerateN = movieInfo.framerateN, + framerateD = movieInfo.framerateD, + totalFrames = movieInfo.totalFrames, + _codecType = movieInfo.codecType, + _alphaCodecType = movieInfo.alphaCodecType, + }; + + return infoStruct; + } + + public ClipCaps clipCaps { + get { return ClipCaps.Looping; } + } + + public override Playable CreatePlayable(PlayableGraph graph, GameObject owner) { + return ScriptPlayable.Create(graph, m_manaBehaviour); + } + + public void ReplaceMovieInfo(CriMana.MovieInfo movieInfo) { + MovieInfoStruct? movieInfoStruct = StructToMovieInfo(movieInfo); + if (movieInfo == null || movieInfoStruct.Equals(m_movieInfoStruct)) { + return; + } + + m_movieInfoStruct = movieInfoStruct; + m_movieFrameRate = (m_movieInfoStruct.Value.framerateN / (double)m_movieInfoStruct.Value.framerateD); + m_clipDuration = (m_movieInfoStruct.Value.totalFrames * 1000.0 / (double)m_movieInfoStruct.Value.framerateN); + } + + public bool IsSameMovie(CriMana.MovieInfo movieInfo) { + if (!IsMovieInfoReady || movieInfo == null) { + return false; + } + + MovieInfoStruct? movieInfoStruct = StructToMovieInfo(movieInfo); + return movieInfoStruct.Equals(m_movieInfoStruct); + } + + public bool IsMovieInfoReady { + get { return (m_movieInfoStruct != null); } + } + + public int GetSeekFrame(double seekTimeSec, bool loop) { + if (m_movieInfoStruct != null) { + double seekFrame = seekTimeSec * m_movieFrameRate; + if (loop == false) { + seekFrame = Math.Min(seekFrame, m_movieInfoStruct.Value.totalFrames - 1); + } else { + seekFrame %= m_movieInfoStruct.Value.totalFrames; + } + return (int)seekFrame; + } else { + return 0; + } + } + + public override double duration { + get { + return m_clipDuration > 0.0 ? m_clipDuration : 10.0; + } + } + } + +} + +} //namespace CriWare + +#endif \ No newline at end of file diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Extension/CriManaClip.cs.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Extension/CriManaClip.cs.meta new file mode 100644 index 0000000..4dc81f9 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Extension/CriManaClip.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4126a9f8e4d459f44bf7f44623208450 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Extension/CriManaMixerBehaviour.cs b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Extension/CriManaMixerBehaviour.cs new file mode 100644 index 0000000..a205a92 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Extension/CriManaMixerBehaviour.cs @@ -0,0 +1,617 @@ +/**************************************************************************** + * + * Copyright (c) 2019 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +#if UNITY_2018_1_OR_NEWER && CRIWARE_TIMELINE_1_OR_NEWER + +//#define CRI_TIMELINE_MANA_VERBOSE_DEBUG + +using System; +using System.IO; +using System.Collections; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using System.Threading.Tasks; +using UnityEditor; +using UnityEngine; +using UnityEngine.Playables; +using UnityEngine.Timeline; + +namespace CriWare { + +namespace CriTimeline.Mana +{ + [Serializable] + public class CriManaMixerBehaviour : PlayableBehaviour { + internal PlayableDirector m_PlayableDirector; + internal IEnumerable m_clips; + internal CriManaMovieMaterialBase m_boundMovieMaterial; + internal Dictionary m_gcHandleList; + internal bool m_frameSync; + + static private double cPreloadTimeSec = 1.0; + + private Guid? m_lastClipId = null; + private double startTime = -1.0; + + private double m_currentSeekingFrameTime = 0f; + + private float m_originalAudioVolume = float.NaN; + private float m_originalSubAudioVolume = float.NaN; + private float m_originalExtraAudioVolume = float.NaN; + + static private bool IsEditMode { + get { +#if UNITY_EDITOR + if (EditorApplication.isPlaying == false) { + return true; + } +#endif + return false; + } + } + + private enum MovieMixerState { + Preloading, + Ready, + Playing, + Stopping, + Stopped + } + private MovieMixerState m_movieMixerState = MovieMixerState.Stopped; + + private void KeepAudioVolume(bool fadeAudio) { + m_originalAudioVolume = fadeAudio ? m_boundMovieMaterial.player.GetVolume() : float.NaN; +#if !UNITY_WEBGL + m_originalSubAudioVolume = fadeAudio ? m_boundMovieMaterial.player.GetSubAudioVolume() : float.NaN; + m_originalExtraAudioVolume = fadeAudio ? m_boundMovieMaterial.player.GetExtraAudioVolume() : float.NaN; +#endif + } + + private bool PlayMovie(CriManaClipBase clipAsset, int startFrame, double startTime) { + if (m_boundMovieMaterial == null || + m_boundMovieMaterial.player == null || + m_boundMovieMaterial.player.status == CriMana.Player.Status.StopProcessing || + m_boundMovieMaterial.player.status == CriMana.Player.Status.Error + ) { + return false; + } + + /** + * Set render target explicitly when in edit mode + * (since the Start method in the movie controller component will not run) + */ + if (IsEditMode) { + if (m_boundMovieMaterial is CriManaMovieController) { + var casted = m_boundMovieMaterial as CriManaMovieController; + if (casted.target == null) { + casted.target = casted.gameObject.GetComponent(); + } + if (casted.target == null) { + Debug.LogWarning("[CRIWARE] Missing render target on CriManaMovieController: Please add a renderer to the GameObject or specify the target manually."); + return false; + } + } else if (m_boundMovieMaterial is CriManaMovieControllerForUI) { + var casted = m_boundMovieMaterial as CriManaMovieControllerForUI; + if (casted.target == null) { + casted.target = casted.gameObject.GetComponent(); + } + if (casted.target == null) { + Debug.LogWarning("[CRIWARE] Missing render target on CriManaMovieControllerForUI: Please add a renderer to the GameObject or specify the target manually."); + return false; + } + } + } + + /** + * if (clipAsset == null) then play the prepared movie + * otherwise set new movie to play + */ + if (clipAsset != null) { + if (clipAsset.guid != m_lastClipId) { +#if CRI_TIMELINE_MANA_VERBOSE_DEBUG + Debug.Log("Set new movie"); +#endif + if (clipAsset.MovieData != null) { + if (!clipAsset.gcHandle.IsAllocated) { + Debug.LogError("[CRIWARE] GCHandle is not Allocated!"); + return false; + } + m_boundMovieMaterial.player.SetData(clipAsset.gcHandle.AddrOfPinnedObject(), clipAsset.MovieData.LongLength); + } else if (string.IsNullOrEmpty(clipAsset.MoviePath) == false) { + m_boundMovieMaterial.player.SetFile(null, clipAsset.MoviePath); + } else { + /* empty clip */ + return false; + } + + m_boundMovieMaterial.player.Loop(clipAsset.m_loopWithinClip); + m_lastClipId = clipAsset.guid; + } + if (startFrame > 0) { +#if CRI_TIMELINE_MANA_VERBOSE_DEBUG + Debug.Log("Set start Frame at " + startFrame); +#endif + m_boundMovieMaterial.player.SetSeekPosition(startFrame); + } else { +#if CRI_TIMELINE_MANA_VERBOSE_DEBUG + Debug.Log("Reset Frame"); +#endif + m_boundMovieMaterial.player.SetSeekPosition(0); + + KeepAudioVolume(clipAsset.m_fadeAudio); + } + } + +#if CRI_TIMELINE_MANA_VERBOSE_DEBUG + Debug.Log("PlayMovie"); +#endif + m_boundMovieMaterial.timerType = m_frameSync ? CriMana.Player.TimerType.User : CriMana.Player.TimerType.Audio; + m_boundMovieMaterial.player.Start(); + this.startTime = startTime; + + return true; + } + + private bool PrepareMovie(CriManaClipBase clipAsset) { +#if CRI_TIMELINE_MANA_VERBOSE_DEBUG + Debug.Log("PrepareMovie"); +#endif + if (m_boundMovieMaterial == null || + m_boundMovieMaterial.player == null || + m_boundMovieMaterial.player.status != CriMana.Player.Status.Stop + ) { + return false; + } + + if (clipAsset.MovieData != null) { + if (!clipAsset.gcHandle.IsAllocated) { + Debug.LogError("[CRIWARE] GCHandle is not Allocated!"); + return false; + } + m_boundMovieMaterial.player.SetData(clipAsset.gcHandle.AddrOfPinnedObject(), clipAsset.MovieData.LongLength); + } else if (string.IsNullOrEmpty(clipAsset.MoviePath) == false) { + m_boundMovieMaterial.player.SetFile(null, clipAsset.MoviePath); + } else { + /* empty clip */ + return false; + } + + m_boundMovieMaterial.player.Loop(clipAsset.m_loopWithinClip); + m_boundMovieMaterial.player.SetSeekPosition(0); + m_lastClipId = clipAsset.guid; + + m_boundMovieMaterial.player.Prepare(); + + KeepAudioVolume(clipAsset.m_fadeAudio); + + return true; + } + + private bool StopMovie() { +#if CRI_TIMELINE_MANA_VERBOSE_DEBUG + Debug.Log("StopMovie"); +#endif + if (m_boundMovieMaterial == null || m_boundMovieMaterial.player == null) { return false; } + + m_boundMovieMaterial.player.Stop(); + m_lastClipId = null; + + if (!float.IsNaN(m_originalAudioVolume)) { + m_boundMovieMaterial.player.SetVolume(m_originalAudioVolume); +#if !UNITY_WEBGL + m_boundMovieMaterial.player.SetSubAudioVolume(m_originalSubAudioVolume); + m_boundMovieMaterial.player.SetExtraAudioVolume(m_originalExtraAudioVolume); +#endif + } + + return true; + } + + private bool StopForSeekMovie() { +#if CRI_TIMELINE_MANA_VERBOSE_DEBUG + Debug.Log("StopForSeekMovie"); +#endif + if (m_boundMovieMaterial == null || m_boundMovieMaterial.player == null) { return false; } + + m_boundMovieMaterial.player.StopForSeek(); + return true; + } + + private static bool IsPlayerPreparing(CriMana.Player player) { + var status = player.status; + return status == CriMana.Player.Status.Dechead || + status == CriMana.Player.Status.Prep || + status == CriMana.Player.Status.WaitPrep; + } + + private static bool IsPlayerStopped(CriMana.Player player) { + var status = player.status; + return status == CriMana.Player.Status.Stop; + } + + private static bool IsPlayerError(CriMana.Player player) { + return player.status == CriMana.Player.Status.Error; + } + + private static bool IsPlayerReadyOrPlaying(CriMana.Player player) { + return (player.status == CriMana.Player.Status.Ready || + player.status == CriMana.Player.Status.ReadyForRendering || + player.status == CriMana.Player.Status.Playing); + } + + private enum ClipState { + Idle, + Prepare, + Play, + Seek + } + + private async void ProcessFrameOnSeeking(TimelineClip activeClip, CriManaClipBase clip, double frameTime) { + if (m_boundMovieMaterial == null || + m_boundMovieMaterial.player == null || + activeClip == null || + clip == null) { + return; + } + + m_currentSeekingFrameTime = frameTime; + await Task.Delay(1); + if (m_currentSeekingFrameTime != frameTime /* seeking frame changed */ + || m_boundMovieMaterial.player == null /* clip been moved out of track */ + ) { + return; + } + + this.ForceSyncedStop(); + + if (clip.MovieData != null) { + if (!clip.gcHandle.IsAllocated) { + Debug.LogError("[CRIWARE] GCHandle is not Allocated!"); + return; + } + if (clip.gcHandle.Target != null) { + m_boundMovieMaterial.player.SetData(clip.gcHandle.AddrOfPinnedObject(), clip.MovieData.LongLength); + } else { + /* empty clip */ + return; + } + } else if (string.IsNullOrEmpty(clip.MoviePath) == false) { + m_boundMovieMaterial.player.SetFile(null, clip.MoviePath); + } else { + return; + } + + int startFrame = clip.GetSeekFrame(frameTime - activeClip.start, clip.m_loopWithinClip); + m_boundMovieMaterial.player.SetSeekPosition(startFrame); + PausePlayer(true); + m_boundMovieMaterial.player.Start(); + m_lastClipId = clip.guid; + + bool movieInfoReplaced = false; + while (IsPlayerPreparing(m_boundMovieMaterial.player) || + !m_boundMovieMaterial.player.HasRenderedNewFrame()) { + await Task.Delay(1); + if (m_boundMovieMaterial.player == null) { return; } /* clip been moved out of track */ + if (m_currentSeekingFrameTime != frameTime) { break; } /* seeking frame changed */ + + m_boundMovieMaterial.PlayerManualUpdate(); + m_boundMovieMaterial.player.OnWillRenderObject(m_boundMovieMaterial); + if (movieInfoReplaced == false && IsPlayerReadyOrPlaying(m_boundMovieMaterial.player)) { + clip.ReplaceMovieInfo(m_boundMovieMaterial.player.movieInfo); + movieInfoReplaced = true; + } + + if (IsPlayerError(m_boundMovieMaterial.player)) { + Debug.LogError("[CRIWARE] An error has occured while preparing a frame."); + break; + } + } + + this.ForceSyncedStop(true); + } + + private void ForceSyncedStop(bool keepLastFrame = false) { + if (m_boundMovieMaterial.player == null) { return; } + + if (keepLastFrame) { + m_boundMovieMaterial.player.StopForSeek(); + } else { + m_boundMovieMaterial.player.Stop(); + } + + while (!IsPlayerStopped(m_boundMovieMaterial.player)) { + m_boundMovieMaterial.PlayerManualUpdate(); + } + /* refresh last frame */ + m_boundMovieMaterial.PlayerManualUpdate(); + } + + public override void ProcessFrame(Playable playable, FrameData info, object playerData) { + if (playable.GetInputCount() <= 0 || playerData == null) { + return; + } + + if (m_PlayableDirector.state == UnityEngine.Playables.PlayState.Paused) { + PausePlayer(true); + } else { + PausePlayer(false); + } + + double frameTime = m_PlayableDirector.time; + + ClipState clipState = ClipState.Idle; + TimelineClip activeClip = null; + CriManaClipBase clipAsset = null; + foreach (var clip in m_clips) { + if (frameTime >= clip.start && frameTime < clip.end) { + if (IsEditMode && m_PlayableDirector.state == PlayState.Paused) { + clipState = ClipState.Seek; + } else { + clipState = ClipState.Play; + } + activeClip = clip; + break; + } else if (frameTime >= clip.start - cPreloadTimeSec && frameTime <= clip.start) { + if (m_PlayableDirector.state == UnityEngine.Playables.PlayState.Playing) { + clipState = ClipState.Prepare; + } + activeClip = clip; + } + } + + if (clipState != ClipState.Idle) { + if (activeClip != null) { + clipAsset = activeClip.asset as CriManaClipBase; + } + if (activeClip == null || clipAsset == null) { + /* impossible if clip system works */ + Debug.LogWarning("[CRIWARE] Timeline / Mana: null clip"); + return; + } + } + + if (clipState == ClipState.Seek) { + ProcessFrameOnSeeking(activeClip, clipAsset, frameTime); + return; + } else if (clipState == ClipState.Idle) { + this.StopMovie(); + m_boundMovieMaterial.PlayerManualUpdate(); + return; + } + + var playerStatus = m_boundMovieMaterial.player.status; + + /** + * Cautions: + * 1. activeClip / clipAsset should never be used when clipState == ClipState.Idle + * 2. Each case should cover all ClipState variations. + */ + switch (m_movieMixerState) { + case MovieMixerState.Stopped: + if (clipState == ClipState.Prepare) { + if (this.PrepareMovie(clipAsset)) { + m_movieMixerState = MovieMixerState.Preloading; + } + } else if (clipState == ClipState.Play) { + if (this.PlayMovie(clipAsset, clipAsset.GetSeekFrame(frameTime - activeClip.start, clipAsset.m_loopWithinClip), frameTime)) { + m_movieMixerState = MovieMixerState.Playing; + } + } + break; + case MovieMixerState.Preloading: + if (clipState != ClipState.Prepare && clipState != ClipState.Play) { + if (this.StopMovie()) { + m_movieMixerState = MovieMixerState.Stopping; + } + } else { + if (playerStatus == CriMana.Player.Status.Ready || + playerStatus == CriMana.Player.Status.ReadyForRendering) { + if (m_boundMovieMaterial.player.movieInfo != null) { + m_movieMixerState = MovieMixerState.Ready; + } else { + if (this.StopMovie()) { + m_movieMixerState = MovieMixerState.Stopping; + } + } + } else { + m_boundMovieMaterial.PlayerManualUpdate(); + } + } + break; + case MovieMixerState.Ready: + if ((clipState == ClipState.Play || clipState == ClipState.Seek) && clipAsset.guid == m_lastClipId) { + if (this.PlayMovie(null, clipAsset.GetSeekFrame(frameTime - activeClip.start, clipAsset.m_loopWithinClip), frameTime)) { + m_movieMixerState = MovieMixerState.Playing; + } + } + /* Do nothing when clipState == ClipState.Prepare */ + if (clipState == ClipState.Idle || clipAsset.guid != m_lastClipId) { + if (this.StopMovie()) { + m_movieMixerState = MovieMixerState.Stopping; + } + } + break; + case MovieMixerState.Playing: + if (clipState != ClipState.Play || clipAsset.guid != m_lastClipId) { + if (this.StopMovie()) { + m_movieMixerState = MovieMixerState.Stopping; + } + break; + } + if (clipState != ClipState.Idle && clipAsset.IsMovieInfoReady == false) { + if (playerStatus == CriMana.Player.Status.Ready || + playerStatus == CriMana.Player.Status.ReadyForRendering || + playerStatus == CriMana.Player.Status.Playing + ) { + clipAsset.ReplaceMovieInfo(m_boundMovieMaterial.player.movieInfo); + } + } + if (m_boundMovieMaterial.timerType == CriMana.Player.TimerType.User) { + uint userTime = (uint)((frameTime - this.startTime) * 1000.0); + m_boundMovieMaterial.player.UpdateWithUserTime(userTime, 1000ul); + } + break; + case MovieMixerState.Stopping: + if (m_boundMovieMaterial.timerType == CriMana.Player.TimerType.User) { + uint userTime = (uint)((frameTime - this.startTime) * 1000.0); + m_boundMovieMaterial.player.UpdateWithUserTime(userTime, 1000ul); + } + if (playerStatus == CriMana.Player.Status.Stop) { + m_movieMixerState = MovieMixerState.Stopped; + } + break; + default: + break; + } + + /* Update movie material in Editor Mode */ + if (m_boundMovieMaterial != null && m_boundMovieMaterial.player != null) { + var _seekPlaybackIEnumrator = seekPlaybackEnumerator(); + do { /* Forcing update on intermediate states */ + if (startTime >= 0) { + m_boundMovieMaterial.PlayerManualUpdate(); + } + } while (_seekPlaybackIEnumrator.MoveNext()); + + if (m_boundMovieMaterial.renderMode == CriManaMovieMaterialBase.RenderMode.Always) { + m_boundMovieMaterial.player.OnWillRenderObject(m_boundMovieMaterial); + } + } + + /* Fade Movie Material and Audio Volume */ + var weight = Mathf.Min( + clipAsset.m_fadeinCurve.Evaluate(Mathf.Approximately(clipAsset.m_fadeinDuration, 0f) ? 1f : Mathf.InverseLerp((float)activeClip.start, (float)activeClip.start + clipAsset.m_fadeinDuration, (float)frameTime)), + clipAsset.m_fadeoutCurve.Evaluate(Mathf.Approximately(clipAsset.m_fadeoutDuration, 0f) ? 0f : Mathf.InverseLerp((float)activeClip.end - clipAsset.m_fadeoutDuration, (float)activeClip.end, (float)frameTime)) + ); + if (!float.IsNaN(m_originalAudioVolume) && m_movieMixerState == MovieMixerState.Playing) + { + m_boundMovieMaterial.player.SetVolume(weight * m_originalAudioVolume); +#if !UNITY_WEBGL + m_boundMovieMaterial.player.SetSubAudioVolume(weight * m_originalSubAudioVolume); + m_boundMovieMaterial.player.SetExtraAudioVolume(weight * m_originalExtraAudioVolume); +#endif + } + m_boundMovieMaterial.material.SetFloat("_Transparency", 1f - weight); + } + + IEnumerator seekPlaybackEnumerator() { + if (m_PlayableDirector.state != PlayState.Playing) { + switch (m_boundMovieMaterial.player.status) { + case CriMana.Player.Status.Dechead: + case CriMana.Player.Status.WaitPrep: + case CriMana.Player.Status.Prep: + case CriMana.Player.Status.StopProcessing: + yield return 0; + break; + default: + break; + } + } + } + + public override void OnBehaviourPlay(Playable playable, FrameData info) { + base.OnBehaviourPlay(playable, info); + + PausePlayer(false); + } + + public override void OnBehaviourPause(Playable playable, FrameData info) { + base.OnBehaviourPause(playable, info); + + PausePlayer(true); + } + + private void PausePlayer(bool pause) { + if (m_boundMovieMaterial == null || m_boundMovieMaterial.player == null) { return; } + m_boundMovieMaterial.player.Pause(pause); + } + + public override void OnGraphStart(Playable playable) { +#if CRI_TIMELINE_MANA_VERBOSE_DEBUG + Debug.Log("OnGraphStart" + (IsEditMode ? " (Editor)" : "")); +#endif + base.OnGraphStart(playable); + + if (IsEditMode) { + if (m_boundMovieMaterial != null) { + m_boundMovieMaterial.PlayerManualInitialize(); + m_boundMovieMaterial.PlayerManualSetup(); + m_boundMovieMaterial.RenderTargetManualSetup(); + } + } + + m_gcHandleList = new Dictionary(); + foreach (var clip in m_clips) { + var manaClip = clip.asset as CriManaClipBase; + if (manaClip.MovieData == null) { + continue; + } + if (m_gcHandleList.ContainsKey(manaClip.DataId) == false) { + manaClip.gcHandle = GCHandle.Alloc(manaClip.MovieData, GCHandleType.Pinned); + m_gcHandleList.Add(manaClip.DataId, manaClip.gcHandle); + } else { + manaClip.gcHandle = m_gcHandleList[manaClip.DataId]; + } + } + } + + public override void OnGraphStop(Playable playable) { +#if CRI_TIMELINE_MANA_VERBOSE_DEBUG + Debug.Log("OnGraphStop" + (IsEditMode ? " (Editor)" : "")); +#endif + base.OnGraphStop(playable); + + if (IsEditMode) { + if (this.StopMovie()) { + m_movieMixerState = MovieMixerState.Stopping; + } + if (m_boundMovieMaterial != null) { + m_boundMovieMaterial.PlayerManualFinalize(); + m_boundMovieMaterial.RenderTargetManualFinalize(); + } + } + foreach (var item in m_gcHandleList) { + item.Value.Free(); + } + } + + public override void OnPlayableCreate(Playable playable) { +#if CRI_TIMELINE_MANA_VERBOSE_DEBUG + Debug.Log("OnPlayableCreate" + (IsEditMode ? " (Editor)" : "")); +#endif + base.OnPlayableCreate(playable); + if (IsEditMode) { + if (CriManaPlugin.IsLibraryInitialized() == false) { + CriWareInitializer cfg = GameObject.FindObjectOfType(); + if (cfg != null) { + CriWareInitializer.InitializeMana(cfg.manaConfig); + } else { + CriWareInitializer.InitializeMana(new CriManaConfig()); + Debug.Log("[CRIWARE] Timeline / Mana: Can't find CriWareInitializer component; Using default parameters in edit mode."); + } + } + } + + m_lastClipId = null; + m_movieMixerState = MovieMixerState.Stopped; + } + + public override void OnPlayableDestroy(Playable playable) { +#if CRI_TIMELINE_MANA_VERBOSE_DEBUG + Debug.Log("OnPlayableDestroy" + (IsEditMode ? " (Editor)" : "")); +#endif + base.OnPlayableDestroy(playable); + + if (IsEditMode == false) { + this.StopMovie(); + } + } + } +} + +} //namespace CriWare + +#endif diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Extension/CriManaMixerBehaviour.cs.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Extension/CriManaMixerBehaviour.cs.meta new file mode 100644 index 0000000..d123878 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Extension/CriManaMixerBehaviour.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c6f6e31e7022bd9449c71334bb4d5df6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Extension/CriManaTrack.cs b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Extension/CriManaTrack.cs new file mode 100644 index 0000000..3e21438 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Extension/CriManaTrack.cs @@ -0,0 +1,102 @@ +/**************************************************************************** + * + * Copyright (c) 2019 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +#if UNITY_2018_1_OR_NEWER && CRIWARE_TIMELINE_1_OR_NEWER + +using System; +using System.Collections.Generic; +using UnityEngine; +using UnityEngine.Playables; +using UnityEngine.Timeline; + +namespace CriWare { + +namespace CriTimeline.Mana +{ + [TrackColor(0.15f, 0.5f, 1f)] + [TrackBindingType(typeof(CriManaMovieMaterialBase))] + [TrackClipType(typeof(CriManaClipBase))] + public class CriManaTrack : TrackAsset { + public bool frameSync = false; + public readonly Guid guid = Guid.NewGuid(); + + static private Dictionary bindDict = new Dictionary(); + + public override Playable CreateTrackMixer(PlayableGraph graph, GameObject go, int inputCount) { + var mixer = ScriptPlayable.Create(graph, inputCount); + var director = go.GetComponent(); + if (director != null) { + CriManaMovieMaterialBase boundMovieMaterial = director.GetGenericBinding(this) as CriManaMovieMaterialBase; + CriManaMixerBehaviour bh = mixer.GetBehaviour(); + bh.m_clips = GetClips(); + bh.m_PlayableDirector = director; + bh.m_frameSync = this.frameSync; + + foreach (var clip in bh.m_clips) { + var clipAsset = (clip.asset as CriManaClipBase); + clipAsset.m_clip = clip; + clip.displayName = clipAsset.MovieName; + } + + /* make sure binding is unique across all tracks */ + if (boundMovieMaterial != null) { + var movieInstanceID = boundMovieMaterial.GetInstanceID(); + + if (bindDict.ContainsKey(movieInstanceID) && bindDict[movieInstanceID] != guid) { + director.SetGenericBinding(this, null); + boundMovieMaterial = null; + Debug.LogWarning("[CRIWARE] Binding the same movie controller to multiple tracks is not allowed. Operation has been cancelled."); + } else { + if (bindDict.ContainsKey(movieInstanceID)) { + try { + bindDict.Remove(movieInstanceID); + } catch { + Debug.LogError("[CRIWARE] Timeline / Mana: (Internal) Binding dictionary logic error"); + } + } + RemoveTrackFromBindDict(this); + try { + bindDict.Add(movieInstanceID, guid); + } catch { + Debug.LogError("[CRIWARE] Timeline / Mana: (Internal) Binding dictionary logic error"); + } + } + } else { + RemoveTrackFromBindDict(this); + } + + bh.m_boundMovieMaterial = boundMovieMaterial; + } + return mixer; + } + + private void OnDestroy() { + /* remove binding record when track is destroyed */ + RemoveTrackFromBindDict(this); + } + + static private void RemoveTrackFromBindDict(CriManaTrack trackAsset) { + List deleteKeyList = new List(); + foreach (var pair in bindDict) { + if (pair.Value == trackAsset.guid) { + deleteKeyList.Add(pair.Key); + } + } + foreach (var key in deleteKeyList) { + try { + bindDict.Remove(key); + } catch { + Debug.LogError("[CRIWARE] Timeline / Mana: (Internal) Binding dictionary logic error"); + } + } + deleteKeyList.Clear(); + } + } +} + +} //namespace CriWare + +#endif \ No newline at end of file diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Extension/CriManaTrack.cs.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Extension/CriManaTrack.cs.meta new file mode 100644 index 0000000..85ea8ff --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Extension/CriManaTrack.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 51459101b5f808445bc87f15fca8e030 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Player.cs b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Player.cs new file mode 100644 index 0000000..6e83af7 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Player.cs @@ -0,0 +1,2330 @@ +/**************************************************************************** + * + * Copyright (c) 2015 - 2019 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +// Use old or new Low-level Native Plugin Interface (from unity 5.2) +#if (UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7 || UNITY_5_0 || UNITY_5_1) + #define CRIPLUGIN_USE_OLD_LOWLEVEL_INTERFACE +#endif + +// Uncomment this for debug information. +//#define CRIMANA_STAT + +using System; +using System.Runtime.InteropServices; +using UnityEngine; +#if CRIMANA_STAT +using System.Collections; +using UnityEngine.UI; +#endif + +/** + * \addtogroup CRIMANA_NATIVE_WRAPPER + * @{ + */ + +namespace CriWare { + +namespace CriMana +{ + +/** + * A wrapper class for native player that controls the movie playback. + * + *
+ * In general, it is used by extracting it from the CriManaMovieController or CriManaMovieControllerForUI component. + * Use this class when you want to perform complicated playback control beyond stopping/pausing playback. + *
+ * If you want to control movie playback directly without using a component, you can directly generate this object and use it. + *
+ * If you directly create an object of this class from the application, be sure to discard it using the Player::Dispose function after completing playback. + *
+ */ + public class Player : CriDisposable + { + #region Data Types + /** + * A value indicating the player status. + * + */ + public enum Status + { + Stop, /**< Stopped */ + Dechead, /**< The header is under analysis */ + WaitPrep, /**< Buffering start stopped */ + Prep, /**< Preparing for playback */ + Ready, /**< Playback preparation completed */ + Playing, /**< Playing */ + PlayEnd, /**< Playback completed */ + Error, /**< Error */ + StopProcessing, /**< Being stopped */ + + ReadyForRendering, /**< Rendering preparation completed */ + } + + + /** + * A mode for setting files. + * + * + * + */ + public enum SetMode + { + New, /**< Specifies the movie to use in the next playback */ + Append, /**< Adds to the concatenated playback Cue */ + AppendRepeatedly /**< Adds repeatedly until the next movie is enCued in the concatenated playback Cue */ + } + + /** + * Synchronization mode for movie events (Cue points, subtitles). + * + */ + public enum MovieEventSyncMode + { + FrameTime, /**< Synchronizes to the frame time */ + PlayBackTime /**< Synchronizes to the playback time based on the timer type */ + } + + /** + * A mode when setting the audio track. + * + * + */ + public enum AudioTrack + { + Off, /**< A value specifying the audio playback OFF */ + Auto, /**< Default value for audio track */ + } + + /** + * Timer type. + * + */ + public enum TimerType : int { + None = 0, /**< No time synchronization */ + System = 1, /**< System time */ + Audio = 2, /**< Audio time of the Main Audio Track */ + User = 3, /**< User-specific timer */ + Manual = 4, /**< Manual timer */ + } + + /** + * A Cue point callback delegate type. + * Event point information + * + * A Cue point callback delegate type.
+ * Do not call functions that control movie playback in the Cue point callback. + *
+ * + */ + public delegate void CuePointCallback(ref EventPoint eventPoint); + + /** + * A delegate type for the callback when the player status changes. + * Player state after change + * + * A delegate type for the callback when the player status changes.
+ *
+ * + */ + public delegate void StatusChangeCallback(Status status); + + /** + * Delegate type of subtitle information update callback + * Pointer to the subtitle string + * + * This is the delegate type for the subtitle information update callback. + * + * + */ + public delegate void SubtitleChangeCallback(IntPtr subtitleBuffer); + + /** + * A shader selection delegate type. + * Movie information + * Whether to do additive composition + * + * A shader selection delegate type.
+ *
+ * + */ + public delegate UnityEngine.Shader ShaderDispatchCallback(MovieInfo movieInfo, bool additiveMode); + #endregion + + + #region Constant Variables + private const int InvalidPlayerId = -1; + #endregion + + + #region Internal Variables + static private Player updatingPlayer = null; + + private int playerId = InvalidPlayerId; + private bool isDisposed = false; + private Status internalrequiredStatus = Status.Stop; + private Status _nativeStatus = Status.Stop; +#if CRIWARE_ENABLE_HEADLESS_MODE + #pragma warning disable 0414 +#endif + private Status? lastNativeStatus = null; +#if CRIWARE_ENABLE_HEADLESS_MODE + #pragma warning restore 0414 +#endif + private Status? lastPlayerStatus = null; + private bool wasStopping = false; + private bool isPreparingForRendering = false; + private bool isNativeStartInvoked = false; + private bool isNativeInitialized = false; + private Detail.RendererResource rendererResource; + private MovieInfo _movieInfo = new MovieInfo(); + private FrameInfo _frameInfo = new FrameInfo(); + private bool isMovieInfoAvailable = false; + private bool isFrameInfoAvailable = false; + private ShaderDispatchCallback _shaderDispatchCallback = null; + private bool enableSubtitle = false; + private int subtitleBufferSize = 0; + private uint droppedFrameCount = 0; + private CriAtomExPlayer _atomExPlayer = null; + private CriAtomEx3dSource _atomEx3Dsource = null; + private TimerType _timerType = TimerType.Audio; +#if CRIWARE_ENABLE_HEADLESS_MODE + #pragma warning disable 0414 +#endif + private bool isStoppingForSeek = false; +#if CRIWARE_ENABLE_HEADLESS_MODE + #pragma warning restore 0414 +#endif + + private Status requiredStatus { + get { return internalrequiredStatus; } + set { + internalrequiredStatus = value; + /* set temporary flags when requiredStatus changes */ + switch (value) { + case Status.Stop: + this.wasStopping = true; + break; + case Status.ReadyForRendering: + this.isPreparingForRendering = true; + break; + default: + break; + } + this.InvokePlayerStatusCheck(); + } + } + #endregion + + + #region Properties + /** + * A Cue point callback delegate. + * + * A Cue point callback delegate.
+ * This must be set before the Player::Prepare and Player::Start functions. + *
+ * + */ + public CuePointCallback cuePointCallback; + + + /** + * A delegate for the callback when the player status changes. + * + * A delegate for the callback when the player status changes.
+ *
+ * + */ + public StatusChangeCallback statusChangeCallback; + +#if CRIWARE_ENABLE_HEADLESS_MODE + #pragma warning disable 0067 +#endif + /** + * Callback function for subtitle information update + * + * This is the subtitle information callback event. + * + * + */ + public event SubtitleChangeCallback OnSubtitleChanged; +#if CRIWARE_ENABLE_HEADLESS_MODE + #pragma warning restore 0067 +#endif + + + /** + * Sets the blend mode to additive composition mode. + * + * This is an argument passed to the shader selection callback during playback.
+ * This must be set before the Player::Prepare and Player::Start functions. + *
+ * + */ + public bool additiveMode { get; set; } + + + /** + * Sets the maximum number of frame drops. + * + * Sets the maximum number of frames to be dropped in one update + * if the update of rendered frames is not keeping up with the playback.
+ * This allows intended playback if the frame rate of the application is low + * or when the playback speed of the video is raised higher than the frame rate.
+ *
+ */ + public int maxFrameDrop { get; set; } + + + /** + * Sets whether to apply the object transparency. + * + * Sets whether to make the movie transparent depending on the transparency of the attached object.
+ * This must be set before the Player::Prepare and Player::Start functions. + *
+ */ + public bool applyTargetAlpha { get; set; } + + + /** + * Specifies whether shader settings for UI components are applied. + * + * Sets whether to apply the rendering settings for UI components to the shader + * that renders the movie.
+ * The default value is false.
+ * This must be set before the Player::Prepare and Player::Start functions. + *
+ */ + public bool uiRenderMode { get; set; } + + + /** + * Whether a valid frame is held + * + * Returns whether a valid frame is maintained.
+ * When you render by yourself, switch the rendering using this flag.
+ *
+ */ + public bool isFrameAvailable + { + get { return isFrameInfoAvailable; } + } + + + /** + * Gets the information on the movie being played. + * Movie information + * + * The information on the header analysis result of the movie that was started.
+ * You can get information such as movie resolution and frame rate.
+ * Information can be acquired only when the player status is between Player.Status.WaitPrep and Player.Status.Playing.
+ * In other states, null is returned.
+ *
+ * + */ + public MovieInfo movieInfo + { + get { return isMovieInfoAvailable ? _movieInfo : null; } + } + + + /** + * Gets the frame information of the movie being played. + * Frame information + * + * You can get information about the frame currently being rendered.
+ * Information can be acquired only when the sound is being played. In other states, null is returned.
+ *
+ */ + public FrameInfo frameInfo + { + get { return isFrameAvailable ? _frameInfo : null; } + } + + + /** + * Gets the player status. + * Status + * + * Gets the player status.
+ *
+ */ + public Status status + { + get { + if (_nativeStatus == Status.Error) { + return Status.Error; + } + if (wasStopping && _nativeStatus != Status.Stop) { + return Status.StopProcessing; + } + if (requiredStatus == Status.ReadyForRendering) { + if (_nativeStatus == Status.Playing) { + return ((rendererResource != null) && (rendererResource.IsPrepared())) + ? Status.ReadyForRendering : Status.Prep; + } else { + return Status.Prep; + } + } + if (_nativeStatus == Status.Ready) { + return (rendererResource != null) ? Status.Ready : Status.Prep; + } else { + return _nativeStatus; + } + } + } + + + /** + * Gets the status of the internal handle. + * Status + * + * Gets the status of the Mana player handle used internally by the plugin.
+ * It is used for detailed debugging or state management.
+ * If you want to check the playback status of the video in the application, please use Player::status .
+ *
+ * + */ + public Status nativeStatus + { + get { return _nativeStatus; } + } + + + /** + * Gets the number of seamless playback entries. + * + * Gets the number of seamless playback entries.
+ * The value obtained from this property is the number of entries that are not started loading.
+ * Loading the movie registered in the entry starts few frames before it is linked.
+ *
+ */ + public System.Int32 numberOfEntries + { + get { + return CRIWAREDA3D6DF0(playerId); + } + } + + + /** + * Gets the pointer to the subtitle data buffer. + * + * Gets a pointer to the subtitle data buffer.
+ * The subtitle data at the display time is stored.
+ * The character code of the subtitle data follows the subtitle file specified when encoding the video file.
+ * Please convert to a string with the character code corresponding to the subtitle file.
+ *
+ * + * + */ + public System.IntPtr subtitleBuffer { get; private set; } + + + /** + * Gets the size of the subtitle data buffer. + * + * Gets the size of the subtitle data buffer.
+ * Please use it when you get the subtitle data from Player::subtitleBuffer .
+ *
+ * + * + */ + public int subtitleSize { get; private set; } + + + /** + * Gets the CriAtomExPlayer handle. + * + * Gets the CriAtomExPlayer handle used to play the audio data from the video.
+ * This property can only get a valid handle when Advanced Audio mode is enabled by CriManaMovieMaterial::advancedAudio.
+ *
+ * + */ + public CriAtomExPlayer atomExPlayer + { + get + { + return _atomExPlayer; + } + } + + + public CriAtomEx3dSource atomEx3DsourceForAmbisonics + { + get + { + return _atomEx3Dsource; + } + } + + + public TimerType timerType + { + get { return _timerType; } + } + + + /** + * Object to hold the player. + * + * MonoBehaviour object that holds a valid CriWare.CriMana::Player until it is destroyed. + * It is used inside the plugin to perform coroutine by which + * unmanaged resources handled by GPU and rendering thread will be deleted. + * + */ + public CriManaMoviePlayerHolder playerHolder { get; set; } + #endregion + + + public Player() + { + if (!CriManaPlugin.IsLibraryInitialized()) { + throw new Exception("CriManaPlugin is not initialized."); + } + playerId = CRIWAREBBA14C68(); + additiveMode = false; + maxFrameDrop = 0; + CriDisposableObjectManager.Register(this, CriDisposableObjectManager.ModuleType.Mana); + } + + + public Player(bool advanced_audio_mode, bool ambisonics_mode, uint max_path_length) { + if (!CriManaPlugin.IsLibraryInitialized()) { + throw new Exception("CriManaPlugin is not initialized."); + } + #if !(UNITY_WEBGL && !UNITY_EDITOR) + if (advanced_audio_mode || max_path_length > 0) { + playerId = CRIWARE888EE3FB(advanced_audio_mode, max_path_length); + if (advanced_audio_mode) { + /* AtomExPlayer 作成 */ + _atomExPlayer = new CriAtomExPlayer(CRIWARE1D2DA078(playerId)); + if (ambisonics_mode) { + _atomEx3Dsource = new CriAtomEx3dSource(); + _atomExPlayer.Set3dSource(_atomEx3Dsource); + _atomExPlayer.SetPanType(CriAtomEx.PanType.Pos3d); + _atomExPlayer.UpdateAll(); + } + } + } else { + playerId = CRIWAREBBA14C68(); + } + #else + playerId = CRIWAREBBA14C68(); + #endif + additiveMode = false; + maxFrameDrop = 0; + CriDisposableObjectManager.Register(this, CriDisposableObjectManager.ModuleType.Mana); + } + + ~Player() + { + Dispose(false); + } + + + /** + * Discards the player object + * + * Discards a player object.
+ * If you create your own CriMana::Player object, be sure to call the Dispose function. + * When this function is called, all the resources allocated when creating the player are released.
+ *
+ */ + public override void Dispose() + { + this.Dispose(true); + System.GC.SuppressFinalize(this); + } + + + /** + * Generates the resources required for movie rendering. + * Movie width + * Movie height + * Whether it is an alpha movie + * + * Generates the resources required for movie rendering.
+ * Normally, the resources required for movie rendering are automatically generated inside the player, + * but you can generate them in advance by calling this function before calling Player::Prepare and Player::Start.
+ * However, if the resource created in advance using this function cannot be used for rendering movie to be played
+ * due to insufficient width or height, the resource is discarded and regenerated.
+ *
+ * + */ + public void CreateRendererResource(int width, int height, bool alpha) + { + MovieInfo dummyMovieInfo = new MovieInfo(); + dummyMovieInfo.hasAlpha = alpha; + dummyMovieInfo.width = (System.UInt32)width; + dummyMovieInfo.height = (System.UInt32)height; + dummyMovieInfo.dispWidth = (System.UInt32)width; + dummyMovieInfo.dispHeight = (System.UInt32)height; + dummyMovieInfo.codecType = CodecType.SofdecPrime; + dummyMovieInfo.alphaCodecType = CodecType.SofdecPrime; + + UnityEngine.Shader userShader = (_shaderDispatchCallback == null) ? null : _shaderDispatchCallback(movieInfo, additiveMode); + if (rendererResource != null) { + if (!rendererResource.IsSuitable(playerId, dummyMovieInfo, additiveMode, userShader)) { + rendererResource.Dispose(); + rendererResource = null; + } + } + if (rendererResource == null) { + rendererResource = Detail.RendererResourceFactory.DispatchAndCreate(playerId, dummyMovieInfo, additiveMode, userShader); + } + } + + + /** + * Discards the resources required for rendering movie. + * + * Discards the resources required for rendering movie.
+ * Although the resource is discarded in Player::Dispose, + * it can be done explicitly using this function.
+ *
+ * + */ + public void DisposeRendererResource() + { + if (rendererResource != null) { + rendererResource.Dispose(); + rendererResource = null; + } + } + + + /** + * Prepares for playback. + * + * This function does not start movie playback but only analyzes the header and prepares for playback (buffering).
+ *
+ * Call this function after specifying the movie to be played. + * When the playback is ready, the player's status changes to Player.Status.Ready.
+ *
+ * Call this function only when the status of the player is Player.Status.Stop or Player.Status.PlayEnd.
+ *
+ * + */ + public void Prepare() + { + this.wasStopping = false; + if ((_nativeStatus == Status.Stop) || (_nativeStatus == Status.PlayEnd)) { + requiredStatus = Status.Ready; + PrepareNativePlayer(); + UpdateNativePlayer(); + } + } + + /** + * Prepares for playback. + * + * This function does not start movie playback but only analyzes the header and prepares for playback (buffering and preparation of the first frame).
+ * Use this function when you want to align the beginning of movie playback.
+ *
+ * Call this function after specifying the movie to be played. + * When the playback is ready, the player's status becomes Player.Status.ReadyForRendering, + * and rendering starts immediately by CriMana.Player.Play.
+ *
+ * Call this function only when the status of the player is Player.Status.Stop, + * Player.Status.PlayEnd or Player.Status.Prepare.
+ *
+ * + */ + public void PrepareForRendering() + { + if (requiredStatus == Status.Ready) { + Pause(true); + requiredStatus = Status.ReadyForRendering; + } else if ((_nativeStatus == Status.Stop) || (_nativeStatus == Status.PlayEnd)) { + Start(); + Pause(true); + requiredStatus = Status.ReadyForRendering; + } + } + + /** + * Start playback. + * + * Starts movie playback.
+ * When playback starts, the status changes to Player.Status.Playing.
+ * After calling this function, it takes several frames before the rendering of movie actually starts.
+ * If you want to synchronize the movie playback, prepare for playback in advance using the Player.Prepare function.
+ *
+ * + * + */ + public void Start() + { + this.wasStopping = false; + if (requiredStatus == Status.ReadyForRendering) { + requiredStatus = Status.Playing; + Pause(false); + UpdateNativePlayer(); + } else { + requiredStatus = Status.Playing; + if ((_nativeStatus == Status.Stop) || (_nativeStatus == Status.PlayEnd)) { + PrepareNativePlayer(); + UpdateNativePlayer(); + } + } + if (rendererResource != null) { + rendererResource.OnPlayerStart(); + } + isStoppingForSeek = false; + } + + + /** + * Requests to stop movie playback. + * + * Issues a request to stop movie playback. This function returns immediately.
+ * Playback does not stop immediately when this function is called.
+ *
+ * + */ + public void Stop() + { + isStoppingForSeek = false; + requiredStatus = Status.Stop; + if (rendererResource != null) { + rendererResource.OnPlayerStop(); + } + if (playerId != InvalidPlayerId) { + CRIWAREBA829E8A(playerId); + UpdateNativePlayer(); + } + DisableInfos(); + } + + + /** + * Requests to stop movie playback. + * + * Issues a request to stop movie playback. This function returns immediately.
+ * Playback does not stop immediately when this function is called.
+ * Playback is stopped internally, but the rendering status is kept.
+ * Use this when you need to stop the movie while keeping it be rendered, such as when performing a seek during playback.
+ *
+ * + * + */ + public void StopForSeek() { + if (rendererResource != null) { + if (!rendererResource.OnPlayerStopForSeek()) { + UnityEngine.Debug.LogWarning("[CRIWARE] StopForSeek is not supported on this platform/codec."); + Stop(); + return; + } + } + requiredStatus = Status.Stop; + if (playerId != InvalidPlayerId) { + isStoppingForSeek = true; + CRIWAREBA829E8A(playerId); + UpdateNativePlayer(); + } + DisableInfos(true); + } + + + /** + * Pauses/unpauses the movie playback. + * Pause switch (true: pause, false: resume) + * + * Turns the pause on and off.
+ * Pauses the playback if the argument is true, resumes the playback if it is false.
+ * The pause state will be cleared when the Player::Stop function is called.
+ *
+ * + */ + public void Pause(bool sw) + { + CRIWARE363F73DF(playerId, (sw) ? 1 : 0); + + if (rendererResource != null) { + rendererResource.OnPlayerPause(sw, false); + } + } + + + /** + * Gets the pausing status of the movie playback. + * Pausing status + * + * Gets the ON/OFF status of the pause.
+ *
+ * + */ + public bool IsPaused() + { + return CRIWARE98E7CD5C(playerId); + } + + + /** + * Sets the file path of the streaming playback. + * Binder with CPK file bound + * Content path in a CPK file + * Movie addition mode + * Whether the set was successful + * + * Sets the file path for streaming playback.
+ * A movie from the CPK file can be played by passing the binder handle to which the CPK file is bound for the first argument.
+ * To stream directly from a file instead of a CPK, specify null for the "binder" argument.
+ * If Player::SetMode::Append is passed for the third argument "setMode", concatenated playback will be performed. + * In this case, the function may return false.
+ * Movie files for concatenated playback must meet the following conditions.
+ * - Video resolution, frame rate and codec must be identical + * - Presence or not of alpha information must be identical + * - Audio tracks configuration (track numbers and number of channels) and codec must be identical
+ * - Equivalent to setting the moviePath property.
+ * - If a relative path is specified, the file is loaded relative to StreamingAssets folder. + * - If an absolute path is specified, the file is loaded from the specified path.
+ * If the moviePath property is set after setting the binder, + * the movie is played from the CPK file bound to the binder.
+ * You can also specify moviePath as URL. + * For example, by specifying a string such as "http://hoge-server/fuga-movie.usm", + * it is possible to stream playback the movie file on the HTTP server. However, this feature is not recommended. + * Also, only HTTP is supported as a communication protocol. HTTPS is not supported. + *
+ * + * + * + */ + public bool SetFile(CriFsBinder binder, string moviePath, SetMode setMode = SetMode.New) + { + System.IntPtr binderPtr = (binder == null) ? System.IntPtr.Zero : binder.nativeHandle; + if ((binder == null) && CriWare.Common.IsStreamingAssetsPath(moviePath) ) { + moviePath = System.IO.Path.Combine(CriWare.Common.streamingAssetsPath, moviePath); + } + if (setMode == SetMode.New) { + CRIWARE14E31860(playerId, binderPtr, moviePath); + return true; + } else { + return CRIWARE3D22605D( + playerId, binderPtr, moviePath, + (setMode == SetMode.AppendRepeatedly) + ); + } + } + + + /** + * Sets the data for memory playback. + * Movie data on the memory + * Data size + * Movie addition mode + * Whether the set was successful + * + * Assigns the data settings for in-memory playback.
+ * The first and second arguments specify the address and size of the data. + * If Player::SetMode::Append is passed for the third argument "setMode", concatenated playback will be performed. + * In this case, the function may return false.
+ * The conditions for the movie files that can be used for concatenated playback are the same than for the Player::SetFile function.
+ * The buffer address passed to SetData should be fixed beforehand by the application + * so that it is not moved by the garbage collector.
+ * In addition, release the memory lock after the playback is finished, the playback is stopped, or after the player object is discarded.
+ *
+ * + * + * + * + */ + public bool SetData(IntPtr data, System.Int64 dataSize, SetMode setMode = SetMode.New) + { + if (setMode == SetMode.New) { + CRIWARE310E5E04(playerId, data, dataSize); + return true; + } else { + return CRIWAREF433DBA3( + playerId, data, dataSize, + (setMode == SetMode.AppendRepeatedly) + ); + } + } + + /** + * \deprecated + * This is a deprecated API that will be removed. + * Please consider using Player.SetData(IntPtr, Int64, SetMode) instead. + */ + [Obsolete("Use SetData(IntPtr, Int64, SetMode) instead")] + public bool SetData(byte[] data, System.Int64 datasize, SetMode setMode = SetMode.New) { + if (setMode == SetMode.New) { + CRIWARE310E5E04(playerId, data, datasize); + return true; + } else { + return CRIWAREF433DBA3( + playerId, data, datasize, + (setMode == SetMode.AppendRepeatedly) + ); + } + } + + + /** + * Specifies the movie file in the CPK file. (Specify content ID) + * Binder with CPK file bound + * Content ID in the CPK file + * Movie addition mode + * Whether the set was successful + * + * Sets the content ID for streaming playback.
+ * By specifying a binder and a content ID as arguments, any movie data in the CPK file can be used as the data source. + * If Append is passed for the third argument "setMode", concatenated playback will be performed. In this case, the function may return false.
+ * Movie files for concatenated playback must meet the following conditions:
+ * - Video resolution, frame rate and codec must be identical + * - Presence or not of alpha information must be identical + * - Audio tracks configuration (track numbers and number of channels) and codec must be identical
+ *
+ * + * + * + */ + public bool SetContentId(CriFsBinder binder, int contentId, SetMode setMode = SetMode.New) + { + if (binder == null) { + UnityEngine.Debug.LogError("[CRIWARE] CriFsBinder is null"); + return false; + } + if (setMode == SetMode.New) { + CRIWARE1EA9BEEB(playerId, binder.nativeHandle, contentId); + return true; + } + else { + return CRIWARE6E2FDFF4( + playerId, binder.nativeHandle, contentId, + (setMode == SetMode.AppendRepeatedly) + ); + } + } + + + /** + * Specifies the movie file in the pack file. (File range specified) + * Path to the pack file + * Data start position of movie file in the pack file + * Data range of the movie file in pack file + * Movie addition mode + * Whether the set was successful + * + * Specifies a packed file containing movies for streaming playback.
+ * By specifying the offset and the data range (length) as arguments, any movie data in the packed file can be used as the data source. + * If -1 is specified for the second argument "range," the data range will extend to the end of the packed file. + * If Player::SetMode.Append is passed for the 4th argument "setMode", concatenated playback will be performed. In this case, the function may return false.
+ * Movie files for concatenated playback must meet the following conditions:
+ * - Video resolution, frame rate and codec must be identical + * - Presence or not of alpha information must be identical + * - Audio tracks configuration (track numbers and number of channels) and codec must be identical
+ *
+ * + * + * + * + */ + public bool SetFileRange(string filePath, System.UInt64 offset, System.Int64 range, SetMode setMode = SetMode.New) + { + if (setMode == SetMode.New) { + CRIWAREE1C717FE(playerId, filePath, offset, range); + return true; + } + else { + return CRIWAREB78E4D28( + playerId, filePath, offset, range, + (setMode == SetMode.AppendRepeatedly) + ); + } + } + + + /** + * Switching on/off the movie playback loop. + * Loop switch (True: loop mode, False: non-loop mode) + * + * Switches loop playback ON/OFF. By default, loop is OFF.
+ * When loop playback is turned ON, the playback does not end at the end of the movie, + * and the playback is repeated from the beginning.
+ *
+ */ + public void Loop(bool sw) + { + CRIWARE43862A29(playerId, sw ? 1 : 0); + } + + + /** + * Sets the master timer type. + * Master timer type + * + * Sets the timer mode for video playback.
+ * The default is the system timer specified when creating the handle.
+ * If you want to synchronize the display timing of video frames with an arbitrary timer, + * specify the user timer.
+ * In that case, call CriWare.CriMana::Player::UpdateWithUserTime regularly.
+ *
+ * + * + * + */ + public void SetMasterTimerType(TimerType timerType) + { + this._timerType = timerType; + CRIWARE86532BB0(playerId, timerType); + } + + + /** + * Sets the seek position. + * Seek frame number + * + * Specifies the frame number to start seek playback.
+ * If this function is not called, or if frame number 0 is specified, playback starts from the beginning of the movie. + * If the specified frame number is greater than the total number of frames in the movie data or is a negative value, the movie is also played from the beginning.
+ *
+ */ + public void SetSeekPosition(int frameNumber) + { + CRIWARE800B7627(playerId, frameNumber); + } + + /** + * Sets the sync mode for movie events (Cue points, subtitles). + * Movie event synchronization mode + * + * Sets the sync mode for movie events (Cue points, subtitles).
+ * By default, the event is triggered in sync with the frame time.
+ * If you want to synchronize with the movie playback time, specify MovieEventSyncMode::PlayBackTime.
+ * Call this function before starting playback. + *
+ */ + public void SetMovieEventSyncMode(MovieEventSyncMode mode) + { + CRIWAREC9D39689(playerId, mode); + } + + /** + * Adjusts the movie playback speed. + * Playback speed + * + * Specifies the playback speed of the movie.
+ * For the playback speed, specify a real value in the range of 0.0f to 3.0f.
+ * If 1.0f is specified, the data is played back at its original speed.
+ * For example, if 2.0f is specified, the movie is played back at twice the frame rate of movie data.
+ * The default playback speed is 1.0f.
+ * Changing the playback speed for movies that are being played is only supported when the movie has no sound.
+ * Changing the playback speed for the movie with sound during playback does not work correctly. For movies with sound, + * stop the playback, change the playback speed, and then perform seek playback from the target frame number.
+ *
+ *
+ */ + public void SetSpeed(float speed) + { + CRIWARE99D43814(playerId, speed); + } + + + /** + * Specifies the maximum picture data size + * Maximum picture data size + * + * Sets the maximum picture data size.
+ * It is not required to use this function in normal playback.
+ *
+ * When doing linked playback on videos with codec other than Sofdec.Prime, + * set the maximum picture data size with this function before starting playback.
+ * The data size to be set is the maximum "Maximum chunk size" of all USM files shown in the Wizz tool;
+ * or the maximum value of MovieInfo.maxChunkSize of all USM files scheduled for concatenated playback.
+ *
+ */ + public void SetMaxPictureDataSize(System.UInt32 maxDataSize) + { + CRIWARE16B49B0E(playerId, maxDataSize); + } + + + /** + * Specify the buffering time for the input data. + * Buffering time [sec] + * + * Specify the amount of input data to buffer for streaming playback, in seconds.
+ * The Mana player determines the size of the read buffer according to the buffering time and movie bitrate.
+ * The default buffering time is 1 second.
+ * If the buffering time is set to 0.0f, the default value of the library will be used.
+ *
+ */ + public void SetBufferingTime(float sec) + { + CRIWARE94E392EA(playerId, sec); + } + + + /** + * Specify the minimum buffer size. + * Minimum buffer size [byte] + * + * Specify the minimum buffer size for movie data.
+ * When a minimum buffer size is specified, the Mana player has an input buffer larger than the specified value.
+ * This function is not neccessary for simple playback. + * However, for seamless concatenated playback of videos with great bitrate differences, calling the function may be requisite.
+ * If it is set to 0, the attributive value of the movie data will be used. (Default)
+ *
+ */ + public void SetMinBufferSize(int min_buffer_size) + { + CRIWARE41838258(playerId, min_buffer_size); + } + + + /** + * Sets the Main Audio Track number. + * Track number + * + * Specifies the sound to be played if the movie has multiple sound tracks.
+ * If this function is not called, the audio track with the smallest number is played.
+ * If you specify a Track number that has no data, no audio is played.
+ *
+ * If you specify AudioTrack.Off as the Track number, no audio is played + * even if the movie contains audio.
+ *
+ * If you want to use the default settings (playing the sound of the smallest channel number), + * specify AudioTrack.Auto as the channel.
+ * Changing tracks during playback is not supported. Record the frame number before change and + * use the seek playback. + *
+ */ + public void SetAudioTrack(int track) + { + CRIWAREDBD8B38C(playerId, track); + } + + + public void SetAudioTrack(AudioTrack track) + { + if (track == AudioTrack.Off) { + CRIWAREDBD8B38C(playerId, -1); + } else if (track == AudioTrack.Auto) { + CRIWAREDBD8B38C(playerId, 100); + } + } + + + /** + * Sets the sub audio track number. + * Track number + * + * Specifies the sound to be played if the movie has multiple sound tracks.
+ * If you don't call this function (default setting), nothing is played from the sub-audio. + * If you specify a track number that has no data, nothing is played from the sub-audio, + * even if you specify the same track for the main audio as the sub-audio track.
+ * Changing tracks during playback is not supported. Record the frame number before change and + * use the seek playback. + *
+ */ + public void SetSubAudioTrack(int track) + { + CRIWAREBD88347C(playerId, track); + } + + + public void SetSubAudioTrack(AudioTrack track) + { + if (track == AudioTrack.Off) { + CRIWAREBD88347C(playerId, -1); + } else if (track == AudioTrack.Auto) { + CRIWAREBD88347C(playerId, 100); + } + } + + + /** + * Sets the extra audio track number. + * Track number + * + * Specifies the sound to be played if the movie has multiple sound tracks.
+ * If you don't call this function (default setting), nothing is played from the extra audio. + * If you specify a track number that has no data, nothing is played from the extra audio + * even if you specify the same track as the main audio as the extra audio track.
+ * Changing tracks during playback is not supported. Record the frame number before change and + * use the seek playback. + *
+ */ + public void SetExtraAudioTrack(int track) + { + CRIWAREFCFFC8DF(playerId, track); + } + + + public void SetExtraAudioTrack(AudioTrack track) + { + if (track == AudioTrack.Off) { + CRIWAREFCFFC8DF(playerId, -1); + } else if (track == AudioTrack.Auto) { + CRIWAREFCFFC8DF(playerId, 100); + } + } + + + /** + * Adjusts the sound volume for movie playback. (Main Audio Track) + * Volume + * + * Specifies the output sound volume of the movie's Main Audio Track.
+ * Specify a real value in the range of 0.0f to 1.0f for the volume value.
+ * The volume value is a scale factor for the amplitude of the sound data (the unit is not decibel).
+ * For example, if you specify 1.0f, the original sound is played at its unmodified volume.
+ * If you specify 0.0f, the sound is muted (silent).
+ * The default value for volume is 1.0f.
+ * If you specify a value outside the range of 0.0f to 1.0f, it is clipped to its minimum and maximum values.
+ *
+ */ + public void SetVolume(float volume) + { + CRIWARE7DF30886(playerId, volume); + } + + + /** + * Gets the volume of the movie playback. (Main audio track) + * + * Gets the output audio volume of the movie's main audio track.
+ * The range of the volume is [0.0f…1.0f].
+ *
+ */ + public float GetVolume() + { + return CRIWARE0F56B273(playerId); + } + + + /** + * Adjusts the sound volume for movie playback. (sub audio) + * Volume + * + * Specifies the output volume of the movie's sub-audio track.
+ * Specify a real value in the range of 0.0f to 1.0f for the volume value.
+ * The volume value is a scale factor for the amplitude of the sound data (the unit is not decibel).
+ * For example, if you specify 1.0f, the original sound is played at its unmodified volume.
+ * If you specify 0.0f, the sound is muted (silent).
+ * The default value for volume is 1.0f.
+ * If you specify a value outside the range of 0.0f to 1.0f, it is clipped to its minimum and maximum values.
+ *
+ */ + public void SetSubAudioVolume(float volume) + { + CRIWAREA3D2B492(playerId, volume); + } + + + /** + * Gets the volume of the movie playback. (Sub-audio track) + * + * Gets the output audio volume of the movie's sub-audio track.
+ * The range of the volume is [0.0f…1.0f].
+ *
+ */ + public float GetSubAudioVolume() + { + return CRIWARE46802F56(playerId); + } + + + /** + * Adjusts the sound volume for movie playback. (extra audio) + * Volume + * + * Specifies the output volume of the movie's extra audio track.
+ * Specify a real value in the range of 0.0f to 1.0f for the volume value.
+ * The volume value is a scale factor for the amplitude of the sound data (the unit is not decibel).
+ * For example, if you specify 1.0f, the original sound is played at its unmodified volume.
+ * If you specify 0.0f, the sound is muted (silent).
+ * The default value for volume is 1.0f.
+ * If you specify a value outside the range of 0.0f to 1.0f, it is clipped to its minimum and maximum values.
+ *
+ */ + public void SetExtraAudioVolume(float volume) + { + CRIWARE002828E8(playerId, volume); + } + + + /** + * Gets the volume of the movie playback. (Extra audio track) + * + * Gets the output audio volume of the movie's extra audio track.
+ * The range of the volume is [0.0f…1.0f].
+ *
+ */ + public float GetExtraAudioVolume() + { + return CRIWARE36687A5B(playerId); + } + + + /** + * Adjusts the Bus Send Level of the Main Audio Track. + * Bus name + * Bus Send Level + * + * Specifies the Bus Send Level (amplitude level) of the movie Main Audio Track and the name of the send destination bus.
+ * Specify a real value in the range of 0.0f to 1.0f for the Bus Send Level value.
+ * The Bus Send Level value is a scale factor for the amplitude of sound data (in decibels).
+ * For example, if you specify 1.0f, the original sound is sent to the bus at its unmodified volume.
+ * If you specify 0.0f, silence is output to the bus.
+ *
+ */ + public void SetBusSendLevel(string bus_name, float level) + { + CRIWARE71D5195F(playerId, bus_name, level); + } + + + /** + * Adjusts the Bus Send Level of the sub audio track. + * Bus name + * Bus Send Level + * + * Specifies the Bus Send Level (amplitude level) of the movie sub-audio track and the name of the send destination bus.
+ * The operation specification of this function is the same as SetBusSendLevel.
+ *
+ */ + public void SetSubAudioBusSendLevel(string bus_name, float volume) + { + CRIWARE736E9E8A(playerId, bus_name, volume); + } + + + /** + * Adjusts the Bus Send Level of the extra audio track. + * Bus name + * Bus Send Level + * + * Specifies the Bus Send Level (amplitude level) of the movie extra audio track and the name of the send destination bus.
+ * The operation specification of this function is the same as SetBusSendLevel.
+ *
+ */ + public void SetExtraAudioBusSendLevel(string bus_name, float volume) + { + CRIWARE32409767(playerId, bus_name, volume); + } + + + /** + * Sets the subtitle channel. + * Subtitle channel number + * + * Sets the subtitle channel to get. The default is no subtitle acquisition.
+ * If you want to use the default setting (no subtitle acquisition), specify -1 as the channel.
+ * It is also possible to switch the subtitle channel during movie playback. However, the is channel actually switched from the next subtitle + * immediately after the setting.
+ *
+ * + * + */ + public void SetSubtitleChannel(int channel) + { + enableSubtitle = (channel != -1); + if (enableSubtitle) { + if (isMovieInfoAvailable) { + AllocateSubtitleBuffer((int)movieInfo.maxSubtitleSize); + } + } else { + DeallocateSubtitleBuffer(); + } + CRIWARE478F89D6(playerId, channel); + } + + + /** + * Sets the shader selection delegate. + * Shader selection delegate + * + * Sets the delegate that determines the user-defined shader
+ * This must be set before the Player::Prepare and Player::Start functions. + *
+ * + */ + public void SetShaderDispatchCallback(ShaderDispatchCallback shaderDispatchCallback) + { + _shaderDispatchCallback = shaderDispatchCallback; + } + + + /** + * Gets the playback time. + * Playback time (in microseconds) + * + * Gets the playback time of the movie that is currently being played.
+ * Returns 0 before starting playback or after stopping playback.
+ * The unit is microseconds.
+ *
+ */ + public long GetTime() + { + return CRIWARE79AF06E4(this.playerId); + } + + + /** + * Gets the frame number being displayed. + * Frame number + * + * Gets the frame number currently being displayed.
+ * Returns -1 before starting rendering or after stopping playback.
+ * Depending on the platform and codec, a number that is smaller than + * the frame information that can be obtained may be returned.
+ *
+ */ + public int GetDisplayedFrameNo() + { + return CRIWAREC81DD455(this.playerId); + } + + + /** + * Checks whether a new frame was rendered. + * A flag whether the frame was rendered + * + * Returns whether a new frame was rendered on the screen after the current call of the playback control. + * + */ + public bool HasRenderedNewFrame() + { + if (rendererResource == null) { + return false; + } + return rendererResource.HasRenderedNewFrame(); + } + + + /** + * Configures the ASR Rack. + * ASR Rack ID + * + * Specifies the output ASR Rack ID of the sound to be played.
+ * The output ASR Rack ID setting is reflected on both the Main Audio Track and the sub audio track.
+ * It cannot be changed during playback. If this API is called during playback, the settings is reflected from the next movie playback.
+ *
+ * + */ + public void SetAsrRackId(int asrRackId) + { + CRIWARE95D115F5(this.playerId, asrRackId); + } + + +#if CRIMANA_STAT + float stat_DeltaPlayerUpdateTime = 0.0f; + float stat_PrevPlayerUpdateTime = 0.0f; + float stat_DeltaUpdateFrameTime = 0.0f; + float stat_PrevUpdateFrameTime = 0.0f; + float stat_DeltaRenderFrameTime = 0.0f; + float stat_PrevRenderFrameTime = 0.0f; + float stat_StartTime = 0.0f; + float stat_ElapsedTimeToFirstFrame = 0.0f; + uint stat_SkippedFrames = 0; + uint stat_DroppedFrames = 0; + + UnityEngine.UI.Text stat_UI_PlayerUpdate; + UnityEngine.UI.Text stat_UI_FrameUpdate; + UnityEngine.UI.Text stat_UI_RenderUpdate; + UnityEngine.UI.Text stat_UI_Status; + UnityEngine.UI.Text stat_UI_Elapased; + UnityEngine.UI.Text stat_UI_Skipped; + UnityEngine.UI.Text stat_UI_Dropped; + + bool stat_Init = false; + GameObject UIStats; + + public void UIInit() + { + stat_Init = true; + int layer = 30; + + var g = new GameObject("CriStat"); + g.layer = layer; + var c = g.AddComponent(); + + var UICam = new GameObject("StatCamera"); + UICam.layer = layer; + UICam.transform.position = new Vector3(0, 0, -615); + UICam.transform.parent = g.transform; + var cam = UICam.AddComponent(); + cam.orthographic = true; + cam.cullingMask = 1 << layer; + cam.clearFlags = CameraClearFlags.Depth; + + + c.worldCamera = cam; + c.renderMode = RenderMode.ScreenSpaceCamera; + var cs = g.AddComponent(); + cs.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize; + + g.AddComponent(); + + int w = 600, h = 400; + int d = 15; + var font = (Font)Resources.GetBuiltinResource(typeof(Font), "Arial.ttf"); + var color = Color.green; + var size = new Vector2(w, d*2); + var pivot = new Vector2(0, 0); + var scale = new Vector3(1, 1, 1); + + UIStats = new GameObject("stat_UI_PlayerUpdate"); + UIStats.transform.parent = g.transform; + UIStats.layer = layer; + stat_UI_PlayerUpdate = UIStats.AddComponent(); + stat_UI_PlayerUpdate.fontSize = d; + stat_UI_PlayerUpdate.font = font; + stat_UI_PlayerUpdate.alignment = TextAnchor.UpperLeft; + stat_UI_PlayerUpdate.color = color; + stat_UI_PlayerUpdate.rectTransform.sizeDelta = size; + stat_UI_PlayerUpdate.rectTransform.pivot = pivot; + stat_UI_PlayerUpdate.rectTransform.localScale = scale; + stat_UI_PlayerUpdate.rectTransform.localPosition = new Vector3(-w/2, h/2, 0); + + UIStats = new GameObject("stat_UI_FrameUpdate"); + UIStats.transform.parent = g.transform; + UIStats.layer = layer; + stat_UI_FrameUpdate = UIStats.AddComponent(); + stat_UI_FrameUpdate.fontSize = d; + stat_UI_FrameUpdate.font = font; + stat_UI_FrameUpdate.alignment = TextAnchor.UpperLeft; + stat_UI_FrameUpdate.color = color; + stat_UI_FrameUpdate.rectTransform.sizeDelta = size; + stat_UI_FrameUpdate.rectTransform.pivot = pivot; + stat_UI_FrameUpdate.rectTransform.localScale = scale; + stat_UI_FrameUpdate.rectTransform.localPosition = new Vector3(-w/2, h/2 - d, 0); + + UIStats = new GameObject("stat_UI_RenderUpdate"); + UIStats.transform.parent = g.transform; + UIStats.layer = layer; + stat_UI_RenderUpdate = UIStats.AddComponent(); + stat_UI_RenderUpdate.fontSize = d; + stat_UI_RenderUpdate.font = font; + stat_UI_RenderUpdate.alignment = TextAnchor.UpperLeft; + stat_UI_RenderUpdate.color = color; + stat_UI_RenderUpdate.rectTransform.sizeDelta = size; + stat_UI_RenderUpdate.rectTransform.pivot = pivot; + stat_UI_RenderUpdate.rectTransform.localScale = scale; + stat_UI_RenderUpdate.rectTransform.localPosition = new Vector3(-w/2, h/2 - d*2, 0); + + UIStats = new GameObject("stat_UI_Status"); + UIStats.transform.parent = g.transform; + UIStats.layer = layer; + stat_UI_Status = UIStats.AddComponent(); + stat_UI_Status.fontSize = d; + stat_UI_Status.font = font; + stat_UI_Status.alignment = TextAnchor.UpperLeft; + stat_UI_Status.color = color; + stat_UI_Status.rectTransform.sizeDelta = size; + stat_UI_Status.rectTransform.pivot = pivot; + stat_UI_Status.rectTransform.localScale = scale; + stat_UI_Status.rectTransform.localPosition = new Vector3(-w/2, h/2 - d*3, 0); + + UIStats = new GameObject("stat_UI_Elapased"); + UIStats.transform.parent = g.transform; + UIStats.layer = layer; + stat_UI_Elapased = UIStats.AddComponent(); + stat_UI_Elapased.fontSize = d; + stat_UI_Elapased.font = font; + stat_UI_Elapased.alignment = TextAnchor.UpperLeft; + stat_UI_Elapased.color = color; + stat_UI_Elapased.rectTransform.sizeDelta = size; + stat_UI_Elapased.rectTransform.pivot = pivot; + stat_UI_Elapased.rectTransform.localScale = scale; + stat_UI_Elapased.rectTransform.localPosition = new Vector3(-w/2, h/2 - d*4, 0); + + UIStats = new GameObject("stat_UI_Skipped"); + UIStats.transform.parent = g.transform; + UIStats.layer = layer; + stat_UI_Skipped = UIStats.AddComponent(); + stat_UI_Skipped.fontSize = d; + stat_UI_Skipped.font = font; + stat_UI_Skipped.alignment = TextAnchor.UpperLeft; + stat_UI_Skipped.color = color; + stat_UI_Skipped.rectTransform.sizeDelta = size; + stat_UI_Skipped.rectTransform.pivot = pivot; + stat_UI_Skipped.rectTransform.localScale = scale; + stat_UI_Skipped.rectTransform.localPosition = new Vector3(-w/2, h/2 - d*5, 0); + } + + public void UIUpdate() + { + float msec = stat_DeltaPlayerUpdateTime * 1000.0f; + float fps = 1.0f / stat_DeltaPlayerUpdateTime; + string text = string.Format("Mana Player Update: {0:0.0} ms ({1:0.} fps)", msec, fps); + stat_UI_PlayerUpdate.text = text; + + msec = stat_DeltaUpdateFrameTime * 1000.0f; + fps = 1.0f / stat_DeltaUpdateFrameTime; + text = string.Format("Mana Update Frame: {0:0.0} ms ({1:0.} fps)", msec, fps); + stat_UI_FrameUpdate.text = text; + + msec = stat_DeltaRenderFrameTime * 1000.0f; + fps = 1.0f / stat_DeltaRenderFrameTime; + text = string.Format("Mana Render Frame: {0:0.0} ms ({1:0.} fps)", msec, fps); + stat_UI_RenderUpdate.text = text; + + text = string.Format("Mana Player Status: {0}", _nativeStatus.ToString()); + stat_UI_Status.text = text; + + float elapsed = 0.0f; + if (stat_StartTime > float.Epsilon) { + elapsed = Time.time - stat_StartTime; + } + float frames = 0.0f; + if (movieInfo != null) { + frames = elapsed * (movieInfo.framerateN / movieInfo.framerateD); + } + msec = stat_ElapsedTimeToFirstFrame * 1000.0f; + text = string.Format("Mana Elapsed Time: {0:0.0} sec ({1:0.} frames) [Start Gap {2:0.0}ms]", elapsed, frames, msec); + stat_UI_Elapased.text = text; + + uint skipped = stat_SkippedFrames; + uint dropped = stat_DroppedFrames; + text = string.Format("Mana Skipped Frames: {0} frames, Dropped Frames: {1} frames", skipped, dropped); + stat_UI_Skipped.text = text; + + stat_DeltaPlayerUpdateTime = Time.time - stat_PrevPlayerUpdateTime; + stat_PrevPlayerUpdateTime = Time.time; + stat_DeltaUpdateFrameTime = 0.0f; + } +#endif + + + /** + * Updates the status by specifying the user time. + * + * Updates the player status.
+ * If you have enabled the user timer using CriWare.CriMana::Player::SetMasterTimerType , + * call this function periodically.
+ * If the call to this function is delayed, the movie playback may hitch.
+ * If the user timer is advanced fast or slow, the accuracy of the master timer decreases, + * and it will be difficult to acquire the frame at the correct time. + * So, normally, use this function in normal speed playback.
+ *
+ * + */ + public void UpdateWithUserTime(ulong timeCount, ulong timeUnit) + { + if (_timerType != TimerType.User) { + Debug.LogError("[CRIWARE] Timer type is invalid."); + } + + CRIWARE3B83B849(this.playerId, timeCount, timeUnit); + InternalUpdate(); + } + + + /** + * Sets the unit by which the time of the manual timer advances. + * Numerator of the unit in which time progresses + * Denominator of the unit in which time progresses + * + * Set the unit by which the time of the manual timer advances in rational number format.
+ * If you enabled the manual timer using CriWare.CriMana::Player::SetMasterTimerType , + * set the unit by which the time advances using this function.
+ * "Numerator (timer_manual_unit_n) / denominator (timer_manual_unit_d) = unit of time advancement (seconds)."
+ * For example, if you want to set to 29.97fps, specify 1001 and 30000.
+ *
+ * + * + */ + public void SetManualTimerUnit(ulong timeUnitN, ulong timeUnitD) + { + if (_timerType != TimerType.Manual) { + Debug.LogError("[CRIWARE] Timer type is invalid."); + } + + CRIWAREAA81C1BF(this.playerId, timeUnitN, timeUnitD); + } + + + /** + * Updates while advancing the time of the manual timer. + * + * Advance the handle time using the manual timer to update the rendering.
+ * If you enabled the manual timer using CriWare.CriMana::Player::SetMasterTimerType , + * it is necessary to call this function regularly.
+ * The time advances when the player status is PLAYING.
+ * Even if this function is called while the player is paused, and the time is reset to 0 when playback starts or stops.
+ *
+ * + * + */ + public void UpdateWithManualTimeAdvanced() + { + if (_timerType != TimerType.Manual) { + Debug.LogError("[CRIWARE] Timer type is invalid."); + } + + CRIWARE9F0B91FC(this.playerId); + InternalUpdate(); + } + + + /** + * Updates the status. + * + * Updates the player status.
+ * The application has to call this function regularly.
+ * If the call to this function is delayed, the movie playback may hitch. + *
+ */ + public void Update() + { + if (_timerType == TimerType.User || _timerType == TimerType.Manual) { + return; + } + + InternalUpdate(); + } + + + public void OnWillRenderObject(CriManaMovieMaterialBase sender) + { + if (rendererResource != null && + _nativeStatus == Status.Playing) { + // on main thread + // unfortunatly this is called on main thread before native render event occur on render thread! + rendererResource.UpdateTextures(); + // Native update - on render thread + IssuePluginEvent(CriManaUnityPlayer_RenderEventAction.RENDER); +#if CRIMANA_STAT + stat_DeltaRenderFrameTime = Time.time - stat_PrevRenderFrameTime; + stat_PrevRenderFrameTime = Time.time; + if (stat_ElapsedTimeToFirstFrame == 0.0f && status == Status.Playing) { + stat_ElapsedTimeToFirstFrame = Time.time - stat_StartTime; + } +#endif + } + } + + /** + * Sets up the Material to display the current frame. + * Material to be set + * Whether the setting succeeded + * + * Sets the shader and various parameters to display the current frame in the Material.
+ *
+ */ + public bool UpdateMaterial(UnityEngine.Material material) + { + if ((rendererResource != null) && isFrameInfoAvailable) { + bool result = rendererResource.UpdateMaterial(material); + return result && (requiredStatus != Status.ReadyForRendering); + } + return false; + } + + public bool isAlive { get { return this.playerId != InvalidPlayerId; } } + + public void IssuePluginEvent(CriManaUnityPlayer_RenderEventAction renderEventAction) + { +#if !CRIWARE_ENABLE_HEADLESS_MODE + int eventID = CriManaPlugin.renderingEventOffset | (int)renderEventAction | this.playerId; + #if CRIPLUGIN_USE_OLD_LOWLEVEL_INTERFACE + UnityEngine.GL.IssuePluginEvent(eventID); + #else + UnityEngine.GL.IssuePluginEvent(criWareUnity_GetRenderEventFunc(), eventID); + #endif +#endif + } + + #region Private Methods + private void Dispose(bool disposing) + { + if (isDisposed) { return; } + isDisposed = true; + + CriDisposableObjectManager.Unregister(this); + + int numFrames = 0; + + if (rendererResource != null && playerId != InvalidPlayerId) { + // signal to native plugin that it will be destroyed and begin to clean unmanaged resources. + IssuePluginEvent(CriManaUnityPlayer_RenderEventAction.DESTROY); + // get the number of frame to continue to send update events before unmamaged resoures destruction. + numFrames = rendererResource.GetNumberOfFrameBeforeDestroy(playerId); + } + + DisposeRendererResource(); + DeallocateSubtitleBuffer(); + + if (playerId != InvalidPlayerId) { + if (atomExPlayer != null) { + _atomExPlayer.Dispose(); + _atomExPlayer = null; + } + CRIWARE39FD3C8E(playerId); + if (atomEx3DsourceForAmbisonics != null) { + _atomEx3Dsource.Dispose(); + _atomEx3Dsource = null; + } + } + + // if unmamaged resource need some frames before be destroyed, + // we signal here Unity frame update events to native plugin. + if (playerHolder != null) { + if (numFrames > 0) { + playerHolder.StartCoroutine(IssuePluginUpdatesForFrames(numFrames, playerHolder, true, playerId)); + } else { + // destroy holder + UnityEngine.Object.Destroy(playerHolder.gameObject); + } + } + + playerId = InvalidPlayerId; + + cuePointCallback = null; + } + + private void InternalUpdate() + { +#if CRIMANA_STAT + if (!stat_Init) { + UIInit(); + } + UIUpdate(); +#endif + // signal unity frame update to plugin - always called once by unity update + CRIWARE7DC9891F(playerId); + + if (requiredStatus == Status.Stop) { + if (_nativeStatus != Status.Stop) { + UpdateNativePlayer(); + } + return; + } + + switch (_nativeStatus) { + case Status.Stop: + break; + case Status.Dechead: +#if CRIMANA_STAT + stat_StartTime = Time.time; + stat_ElapsedTimeToFirstFrame = 0.0f; +#endif + UpdateNativePlayer(); + if (_nativeStatus == Status.WaitPrep) { + goto case Status.WaitPrep; + } + break; + case Status.WaitPrep: + { + CRIWARE0FDF2A46(playerId, _movieInfo); + bool needRendererResourceDispatch = !isMovieInfoAvailable; + if (needRendererResourceDispatch) { + isMovieInfoAvailable = true; + if (enableSubtitle) { + AllocateSubtitleBuffer((int)movieInfo.maxSubtitleSize); + } + UnityEngine.Shader userShader = (_shaderDispatchCallback == null) ? null : _shaderDispatchCallback(movieInfo, additiveMode); + if (rendererResource != null) { + if (!rendererResource.IsSuitable(playerId, _movieInfo, additiveMode, userShader)) { + rendererResource.Dispose(); + rendererResource = null; + } + } + if (rendererResource == null) { + rendererResource = Detail.RendererResourceFactory.DispatchAndCreate(playerId, _movieInfo, additiveMode, userShader); + if (rendererResource == null) { + Stop(); + return; + } + } + rendererResource.SetApplyTargetAlpha(applyTargetAlpha); + rendererResource.SetUiRenderMode(uiRenderMode); + } + rendererResource.AttachToPlayer(playerId); + + if (requiredStatus == Status.Ready) { + goto case Status.Prep; + } + + if (requiredStatus == Status.Playing || + requiredStatus == Status.ReadyForRendering) { + CRIWARE7028B2E9(playerId); + isNativeStartInvoked = true; + if (isNativeInitialized) { + // Native destroy - on render thread + IssuePluginEvent(CriManaUnityPlayer_RenderEventAction.DESTROY); + } + // Native initialize - on render thread - must be called after start (iOS) + IssuePluginEvent(CriManaUnityPlayer_RenderEventAction.INITIALIZE); + isNativeInitialized = true; + goto case Status.Prep; + } + } + break; + case Status.Prep: + UpdateNativePlayer(); + if (_nativeStatus == Status.Ready) { + goto case Status.Ready; + } else if (_nativeStatus == Status.Playing) { + goto case Status.Playing; + } + break; + case Status.Ready: + if (requiredStatus == Status.Playing || + requiredStatus == Status.ReadyForRendering) { + if (!isNativeStartInvoked) { +#if CRIMANA_STAT + stat_StartTime = Time.time; + stat_ElapsedTimeToFirstFrame = 0.0f; +#endif + CRIWARE7028B2E9(playerId); + isNativeStartInvoked = true; + if (isNativeInitialized) { + // Native destroy - on render thread + IssuePluginEvent(CriManaUnityPlayer_RenderEventAction.DESTROY); + } + // Native initialize - on render thread - must be called after start (iOS) + IssuePluginEvent(CriManaUnityPlayer_RenderEventAction.INITIALIZE); + isNativeInitialized = true; + } + goto case Status.Playing; + } + break; + case Status.Playing: + UpdateNativePlayer(); + if (_nativeStatus == Status.Playing) { + bool frameDrop = (maxFrameDrop < 0 || droppedFrameCount < maxFrameDrop); // enable frame dropping if requested + bool updateNextFrame = true; + bool isFrameInfoUpdated = false; + + while (updateNextFrame) { + // FrameDrop refrence -> in (can drop frame?), out (is frame has been droped?) + isFrameInfoUpdated = rendererResource.UpdateFrame(playerId, _frameInfo, ref frameDrop); + + if (isFrameInfoUpdated && frameDrop && (maxFrameDrop < 0 || droppedFrameCount < maxFrameDrop)) { + // Frame was updated but not in-sync and dropped, try to get next decoded frame: continue + droppedFrameCount++; + + if (maxFrameDrop > 0 && droppedFrameCount == maxFrameDrop) { + frameDrop = false; // do not drop next frame. + } + } else { + // Frame has not been updated or is in-sync: break. + updateNextFrame = false; + + // Frame is drawable: reset the dropped frame counter. + if (isFrameInfoUpdated) { +#if CRIMANA_STAT + stat_DroppedFrames += droppedFrameCount; +#endif + droppedFrameCount = 0; + } + } + } + + // FrameInfo was updated? + isFrameInfoAvailable |= isFrameInfoUpdated; + + // Native update - on render thread + IssuePluginEvent(CriManaUnityPlayer_RenderEventAction.UPDATE); +#if CRIMANA_STAT + stat_DeltaUpdateFrameTime = Time.time - stat_PrevUpdateFrameTime; + stat_PrevUpdateFrameTime = Time.time; + stat_SkippedFrames = frameInfo.cntSkippedFrames; +#endif + } else if (_nativeStatus == Status.PlayEnd) { + goto case Status.PlayEnd; + } + break; + case Status.PlayEnd: + break; + case Status.Error: + UpdateNativePlayer(); + break; + } + + if (_nativeStatus == Status.Error) { + DisableInfos(); + } + } + + private System.Collections.IEnumerator IssuePluginUpdatesForFrames(int frameCount, MonoBehaviour playerHolder, bool destroy, int playerId) + { + while (frameCount > 0) { + // issue plugin event + IssuePluginEvent(CriManaUnityPlayer_RenderEventAction.UPDATE); + // continue update synchronizatons + CRIWARE7DC9891F(playerId); + frameCount--; + yield return null; + } + + if (destroy) { + // destroy holder + UnityEngine.Object.Destroy(playerHolder.gameObject); + } + } + + private void DisableInfos(bool keepFrameInfo = false) + { + if (keepFrameInfo == false) { + isFrameInfoAvailable = false; + isMovieInfoAvailable = false; + } + isNativeStartInvoked = false; + subtitleSize = 0; + } + + private void PrepareNativePlayer() + { + if (cuePointCallback != null) { + CRIWAREAF197FE6(playerId, CuePointCallbackFromNative); + } + CRIWARE5438B56B(playerId); + } + + + private void UpdateNativePlayer() + { +#if !CRIWARE_ENABLE_HEADLESS_MODE + updatingPlayer = this; + uint subtitleSizeTmp = (uint)subtitleBufferSize; + _nativeStatus = (Status)CRIWARE655B06DD(playerId, subtitleBuffer, ref subtitleSizeTmp); + if (this.lastNativeStatus.HasValue == false || this.lastNativeStatus != _nativeStatus || this.isPreparingForRendering) { + this.lastNativeStatus = _nativeStatus; + InvokePlayerStatusCheck(); + } + subtitleSize = (int)subtitleSizeTmp; + updatingPlayer = null; + + if (enableSubtitle) { + var changed = CRIWARE025527F5(playerId); + if (changed) { + if (OnSubtitleChanged != null){ + OnSubtitleChanged(subtitleBuffer); + } + CRIWAREC112D232(playerId); + } + } + + // check when status goes from any to stop + if (isNativeInitialized && ( + _nativeStatus == Status.StopProcessing || + _nativeStatus == Status.Stop)) + { + isNativeInitialized = false; + // Native destroy - on render thread + if (!isStoppingForSeek || + !(rendererResource != null && rendererResource.ShouldSkipDestroyOnStopForSeek())) { + IssuePluginEvent(CriManaUnityPlayer_RenderEventAction.DESTROY); + } + } +#else + if ((requiredStatus != Status.Stop) || + (_nativeStatus != requiredStatus)) { + DummyProceedNativeState(); + } +#endif + } + + private void InvokePlayerStatusCheck() + { + var playerStatus = this.status; + if (this.lastPlayerStatus.HasValue == false || this.lastPlayerStatus != playerStatus) { + this.lastPlayerStatus = playerStatus; + if (statusChangeCallback != null) { + statusChangeCallback.Invoke(playerStatus); + } + if (this.isPreparingForRendering && this.status != Status.Prep) { /* Finished preparing or unknown status */ + this.isPreparingForRendering = false; + } + } + } + +#if CRIWARE_ENABLE_HEADLESS_MODE + private void DummyProceedNativeState() + { + if (_nativeStatus == requiredStatus) { + if (_nativeStatus == Status.Playing && + _nativeStatus == requiredStatus && + !_dummyLoop && !_dummyPaused) { + _nativeStatus = Status.PlayEnd; + } + } else if (requiredStatus == Status.Playing || + requiredStatus == Status.Ready) { + if (_dummyNativeStatus == _nativeStatus + 1 && + !(_dummyPaused && _dummyNativeStatus == Status.Playing)) { + _nativeStatus = _dummyNativeStatus; + } else { + _dummyNativeStatus = _nativeStatus + 1; + } + } else if (requiredStatus == _dummyNativeStatus) { + _nativeStatus = requiredStatus; + } else { + _dummyNativeStatus = requiredStatus; + } + } + +#endif + + + private void AllocateSubtitleBuffer(int size) + { + if (subtitleBufferSize < size) { + DeallocateSubtitleBuffer(); + subtitleBuffer = Marshal.AllocHGlobal(size); + subtitleBufferSize = size; + subtitleSize = 0; + } + for (int i = 0; i < subtitleBufferSize; i++) { + Marshal.WriteByte(subtitleBuffer, i, 0x00); + } + CRIWAREA67D86BC(playerId, size); + } + + private void DeallocateSubtitleBuffer() + { + if (subtitleBuffer != System.IntPtr.Zero) { + Marshal.FreeHGlobal(subtitleBuffer); + subtitleBuffer = System.IntPtr.Zero; + subtitleBufferSize = 0; + subtitleSize = 0; + } + CRIWARE801A2706(playerId); + } + + + internal void PauseOnApplicationPause(bool sw) + { + CRIWARE363F73DF(playerId, (sw) ? 1 : 0); + + if (rendererResource != null) { + rendererResource.OnPlayerPause(sw, true); + } + } + + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private delegate void CuePointCallbackFromNativeDelegate(System.IntPtr ptr1, System.IntPtr ptr2, [In] ref EventPoint eventPoint); + + + [AOT.MonoPInvokeCallback(typeof(CuePointCallbackFromNativeDelegate))] + private static void CuePointCallbackFromNative(System.IntPtr ptr1, System.IntPtr ptr2, [In] ref EventPoint eventPoint) + { + if (updatingPlayer.cuePointCallback != null) { + updatingPlayer.cuePointCallback(ref eventPoint); + } + } + #endregion + + #region DLL Import + #if !CRIWARE_ENABLE_HEADLESS_MODE + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int CRIWAREBBA14C68(); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int CRIWARE31A77CF3(); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int CRIWARE888EE3FB(bool useAtomExPlayer, uint maxPathLength); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void CRIWARE39FD3C8E(int player_id); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void CRIWARE14E31860(int player_id, System.IntPtr binder, string path); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void CRIWARE1EA9BEEB(int player_id, System.IntPtr binder, int content_id); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void CRIWAREE1C717FE(int player_id, string path, System.UInt64 offset, System.Int64 range); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void CRIWARE310E5E04(int player_id, IntPtr data, System.Int64 datasize); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void CRIWARE310E5E04(int player_id, byte[] data, System.Int64 datasize); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool CRIWARE3D22605D(int player_id, System.IntPtr binder, string path, bool repeat); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool CRIWARE6E2FDFF4(int player_id, System.IntPtr binder, int content_id, bool repeat); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool CRIWAREB78E4D28(int player_id, string path, System.UInt64 offset, System.Int64 range, bool repeat); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool CRIWAREF433DBA3(int player_id, IntPtr data, System.Int64 datasize, bool repeat); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool CRIWAREF433DBA3(int player_id, byte[] data, System.Int64 datasize, bool repeat); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void CRIWARECAFDD93C(int player_id); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern System.Int32 CRIWAREDA3D6DF0(int player_id); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void CRIWAREAF197FE6( + int player_id, + CuePointCallbackFromNativeDelegate cbfunc + ); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void CRIWARE0FDF2A46(int player_id, [Out] MovieInfo movie_info); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int CRIWARE655B06DD( + int player_id, + System.IntPtr subtitle_buffer, + ref uint subtitle_size + ); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void CRIWARE5438B56B(int player_id); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void CRIWARE7028B2E9(int player_id); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void CRIWAREBA829E8A(int player_id); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void CRIWARE800B7627(int player_id, int seek_frame_no); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void CRIWAREC9D39689(int player_id, MovieEventSyncMode mode); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void CRIWARE363F73DF(int player_id, int sw); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool CRIWARE98E7CD5C(int player_id); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void CRIWARE43862A29(int player_id, int sw); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern long CRIWARE79AF06E4(int player_id); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int CRIWARE80AFF783(int player_id); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern IntPtr CRIWARE1D2DA078(int player_id); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int CRIWAREC81DD455(int player_id); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void CRIWAREDBD8B38C(int player_id, int track); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void CRIWARE7DF30886(int player_id, float vol); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern float CRIWARE0F56B273(int player_id); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void CRIWAREBD88347C(int player_id, int track); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void CRIWAREA3D2B492(int player_id, float vol); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern float CRIWARE46802F56(int player_id); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void CRIWAREFCFFC8DF(int player_id, int track); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void CRIWARE002828E8(int player_id, float vol); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern float CRIWARE36687A5B(int player_id); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void CRIWARE71D5195F(int player_id, string bus_name, float level); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void CRIWARE736E9E8A(int player_id, string bus_name, float level); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void CRIWARE32409767(int player_id, string bus_name, float level); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void CRIWARE478F89D6(int player_id, int channel); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void CRIWARE99D43814(int player_id, float speed); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void CRIWARE16B49B0E(int player_id, System.UInt32 max_data_size); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + public static extern void CRIWARE94E392EA(int player_id, float sec); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + public static extern void CRIWARE41838258(int player_id, int min_buffer_size); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + public static extern void CRIWARE95D115F5(int player_id, int asr_rack_id); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void CRIWARE7DC9891F(int player_id); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void CRIWARE86532BB0(int player_id, TimerType timer_type); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void CRIWARE3B83B849(int player_id, ulong user_count, ulong user_unit); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void CRIWAREAA81C1BF(int player_id, ulong timer_unit_n, ulong timer_unit_d); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void CRIWARE9F0B91FC(int player_id); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void CRIWARE801A2706(int player_id); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern IntPtr CRIWAREA67D86BC(int player_id, int bufferSize); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern bool CRIWARE025527F5(int player_id); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void CRIWAREC112D232(int player_id); +#if !CRIPLUGIN_USE_OLD_LOWLEVEL_INTERFACE + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern IntPtr criWareUnity_GetRenderEventFunc(); +#endif + #else + private Status _dummyNativeStatus = Status.Error; + private bool _dummyPaused = false; + private bool _dummyLoop = false; + private static int CRIWAREBBA14C68() { return 0; } + private static int CRIWARE31A77CF3() { return 0; } + private static int CRIWARE888EE3FB(bool useAtomExPlayer, uint maxPathLength) { return 0; } + private static void CRIWARE39FD3C8E(int player_id) { } + private static void CRIWARE14E31860(int player_id, System.IntPtr binder, string path) { } + private static void CRIWARE1EA9BEEB(int player_id, System.IntPtr binder, int content_id) { } + private static void CRIWAREE1C717FE(int player_id, string path, System.UInt64 offset, System.Int64 range) { } + private static void CRIWARE310E5E04(int player_id, IntPtr data, System.Int64 datasize) { } + private static void CRIWARE310E5E04(int player_id, byte[] data, System.Int64 datasize) { } + private static bool CRIWARE3D22605D(int player_id, System.IntPtr binder, string path, bool repeat) { return true; } + private static bool CRIWARE6E2FDFF4(int player_id, System.IntPtr binder, int content_id, bool repeat) { return true; } + private static bool CRIWAREB78E4D28(int player_id, string path, System.UInt64 offset, System.Int64 range, bool repeat) { return true; } + private static bool CRIWAREF433DBA3(int player_id, IntPtr data, System.Int64 datasize, bool repeat) { return true; } + private static bool CRIWAREF433DBA3(int player_id, byte[] data, System.Int64 datasize, bool repeat) { return true; } + private static void CRIWARECAFDD93C(int player_id) { } + private static System.Int32 CRIWAREDA3D6DF0(int player_id) { return 0; } + private static void CRIWAREAF197FE6(int player_id, CuePointCallbackFromNativeDelegate cbfunc) { } + private static void CRIWARE0FDF2A46(int player_id, [Out] MovieInfo movie_info) { movie_info = new MovieInfo(); } + private static int CRIWARE655B06DD(int player_id, System.IntPtr subtitle_buffer, ref uint subtitle_size ) { return 0; } + private void CRIWARE5438B56B(int player_id) { _dummyPaused = false; _nativeStatus = Status.WaitPrep; } + private void CRIWARE7028B2E9(int player_id) { _dummyPaused = false; _nativeStatus = Status.WaitPrep; } + private void CRIWAREBA829E8A(int player_id) { _nativeStatus = Status.Stop; } + private static void CRIWARE800B7627(int player_id, int seek_frame_no) { } + private static void CRIWAREC9D39689(int player_id, MovieEventSyncMode mode){} + private void CRIWARE363F73DF(int player_id, int sw) { _dummyPaused = (sw == 1); } + private static bool CRIWARE98E7CD5C(int player_id) { return false; } + private void CRIWARE43862A29(int player_id, int sw) { _dummyLoop = (sw == 1); } + private static long CRIWARE79AF06E4(int player_id) { return 0; } + private static int CRIWARE80AFF783(int player_id) { return 0; } + private static IntPtr CRIWARE1D2DA078(int player_id) { return new IntPtr(1); } + private static int CRIWAREC81DD455(int player_id) { return -1; } + private static void CRIWAREDBD8B38C(int player_id, int track) { } + private static void CRIWARE7DF30886(int player_id, float vol) { } + private static float CRIWARE0F56B273(int player_id){ return 0f; } + private static void CRIWAREBD88347C(int player_id, int track) { } + private static void CRIWAREA3D2B492(int player_id, float vol) { } + private static float CRIWARE46802F56(int player_id){ return 0f; } + private static void CRIWAREFCFFC8DF(int player_id, int track) { } + private static void CRIWARE002828E8(int player_id, float vol) { } + private static float CRIWARE36687A5B(int player_id){ return 0f; } + private static void CRIWARE71D5195F(int player_id, string bus_name, float level) { } + private static void CRIWARE736E9E8A(int player_id, string bus_name, float level) { } + private static void CRIWARE32409767(int player_id, string bus_name, float level) { } + private static void CRIWARE478F89D6(int player_id, int channel) { } + private static void CRIWARE99D43814(int player_id, float speed) { } + private static void CRIWARE16B49B0E(int player_id, System.UInt32 max_data_size) { } + public static void CRIWARE94E392EA(int player_id, float sec) { } + public static void CRIWARE41838258(int player_id, int min_buffer_size) { } + public static void CRIWARE95D115F5(int player_id, int asr_rack_id) { } + private static void CRIWARE7DC9891F(int player_id) { } + private static void CRIWARE86532BB0(int player_id, TimerType timer_type) { } + private static void CRIWARE3B83B849(int player_id, ulong user_count, ulong user_unit) { } + private static void CRIWAREAA81C1BF(int player_id, ulong timer_unit_n, ulong timer_unit_d) { } + private static void CRIWARE9F0B91FC(int player_id) { } + private static void CRIWARE801A2706(int player_id) {} + private static IntPtr CRIWAREA67D86BC(int player_id, int bufferSize){return IntPtr.Zero;} + private static bool CRIWARE025527F5(int player_id){return false;} + private static void CRIWAREC112D232(int player_id){} + #endif + + public enum CriManaUnityPlayer_RenderEventAction { + UPDATE = 0, // default action - always called at each loop + INITIALIZE = 1 << 8, // called only once at first + RENDER = 2 << 8, // called each loop each camera before render if visible + DESTROY = 3 << 8, // called only once at end + }; + + #endregion + } +} + +} //namespace CriWare +/** + * @} + */ + + +/* end of file */ diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Player.cs.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Player.cs.meta new file mode 100644 index 0000000..03acd88 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Player.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: c4dc317664f424bd78f8e62944207261 +timeCreated: 1445063317 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Resources.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Resources.meta new file mode 100644 index 0000000..15e6b4f --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Resources.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 05a23e2b5ed7a6f4cbb44afd7600de3a +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Resources/CriMana.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Resources/CriMana.meta new file mode 100644 index 0000000..ee30140 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Resources/CriMana.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 09cd41325a40dce40b620e37759c5728 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Resources/CriMana/SofdecPrimeRgb.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Resources/CriMana/SofdecPrimeRgb.meta new file mode 100644 index 0000000..fd36474 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Resources/CriMana/SofdecPrimeRgb.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 9e3ae25a84b18074dbfb758bbd19126c +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Resources/CriMana/SofdecPrimeRgb/SofdecPrimeRgb.shader b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Resources/CriMana/SofdecPrimeRgb/SofdecPrimeRgb.shader new file mode 100644 index 0000000..a4d4ba8 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Resources/CriMana/SofdecPrimeRgb/SofdecPrimeRgb.shader @@ -0,0 +1,99 @@ +Shader "CriMana/SofdecPrimeRgb" +{ + Properties + { + _MainTex ("Texture", 2D) = "white" {} + [HideInInspector] _MovieTexture_ST ("MovieTexture_ST", Vector) = (1.0, 1.0, 0, 0) + [HideInInspector] _TextureRGBA ("TextureRGBA", 2D) = "white" {} + [HideInInspector] _SrcBlendMode("SrcBlendMode", Int) = 0 + [HideInInspector] _DstBlendMode("DstBlendMode", Int) = 0 + [HideInInspector] _CullMode("CullMode", Int) = 2 + [HideInInspector] _ZWriteMode("ZWriteMode", Int) = 1 + } + + SubShader + { + Tags + { + "Queue" = "Transparent" + "PreviewType"="Plane" + } + + Pass + { + Blend [_SrcBlendMode] [_DstBlendMode] + Cull [_CullMode] + ZWrite [_ZWriteMode] + ZTest [unity_GUIZTestMode] + + CGPROGRAM + #pragma vertex vert + #pragma fragment frag + #if defined(SHADER_API_PSP2) || defined(SHADER_API_PS3) + // seems that ARB_precision_hint_fastest is not supported on these platforms. + #else + #pragma fragmentoption ARB_precision_hint_fastest + #endif + + #include "UnityCG.cginc" + + #pragma multi_compile _ CRI_LINEAR_COLORSPACE + #pragma multi_compile _ CRI_APPLY_TARGET_ALPHA + #pragma multi_compile _ CRI_SWITCH + + struct appdata + { + float4 vertex : POSITION; + half2 texcoord : TEXCOORD0; +#ifdef CRI_APPLY_TARGET_ALPHA + float4 color : COLOR; +#endif + }; + + struct v2f + { + float4 pos : SV_POSITION; + half2 uv : TEXCOORD0; +#ifdef CRI_APPLY_TARGET_ALPHA + float4 color : COLOR; +#endif + }; + + float4 _MainTex_ST; + float4 _MovieTexture_ST; + + v2f vert(appdata v) + { + v2f o; + o.pos = UnityObjectToClipPos(v.vertex); + o.uv = (TRANSFORM_TEX(v.texcoord, _MainTex) * _MovieTexture_ST.xy) + _MovieTexture_ST.zw; +#ifdef CRI_APPLY_TARGET_ALPHA + o.color = v.color; +#endif + return o; + } + + sampler2D _TextureRGBA; + fixed _Transparency; + + fixed4 frag(v2f i) : COLOR + { + fixed4 color = tex2D(_TextureRGBA, i.uv); +#ifdef CRI_LINEAR_COLORSPACE + color.rgb = pow(max(color.rgb, 0), 2.2); +#endif +#ifdef CRI_SWITCH + //Temporary fix for Switch + color.rgb = fixed3(color.b, color.g, color.r); +#endif +#ifdef CRI_APPLY_TARGET_ALPHA + color.a = color.a * i.color.a; +#endif + color.a *= 1 - _Transparency; + + return color; + } + ENDCG + } + } +} diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Resources/CriMana/SofdecPrimeRgb/SofdecPrimeRgb.shader.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Resources/CriMana/SofdecPrimeRgb/SofdecPrimeRgb.shader.meta new file mode 100644 index 0000000..f5a6535 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Resources/CriMana/SofdecPrimeRgb/SofdecPrimeRgb.shader.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: da14540f8017c42a4b499fb01d6d285c +timeCreated: 1445063784 +licenseType: Pro +ShaderImporter: + defaultTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Resources/CriMana/SofdecPrimeYuv.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Resources/CriMana/SofdecPrimeYuv.meta new file mode 100644 index 0000000..eb5d668 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Resources/CriMana/SofdecPrimeYuv.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 7dcbd15059978444cb9e08b4da027d00 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Resources/CriMana/SofdecPrimeYuv/SofdecPrimeYuv.shader b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Resources/CriMana/SofdecPrimeYuv/SofdecPrimeYuv.shader new file mode 100644 index 0000000..03dcc69 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Resources/CriMana/SofdecPrimeYuv/SofdecPrimeYuv.shader @@ -0,0 +1,135 @@ +Shader "CriMana/SofdecPrimeYuv" +{ + Properties + { + _MainTex ("Texture", 2D) = "white" {} + [HideInInspector] _MovieTexture_ST ("MovieTexture_ST", Vector) = (1.0, 1.0, 0, 0) + [HideInInspector] _MovieChromaTexture_ST("MovieChromaTexture_ST", Vector) = (1.0, 1.0, 0, 0) + [HideInInspector] _MovieAlphaTexture_ST("MovieAlphaTexture_ST", Vector) = (1.0, 1.0, 0, 0) + [HideInInspector] _TextureY ("TextureY", 2D) = "white" {} + [HideInInspector] _TextureU ("TextureU", 2D) = "white" {} + [HideInInspector] _TextureV ("TextureV", 2D) = "white" {} + [HideInInspector] _TextureA("TextureA", 2D) = "white" {} + [HideInInspector] _SrcBlendMode("SrcBlendMode", Int) = 0 + [HideInInspector] _DstBlendMode("DstBlendMode", Int) = 0 + [HideInInspector] _CullMode("CullMode", Int) = 2 + [HideInInspector] _ZWriteMode("ZWriteMode", Int) = 1 + } + + SubShader + { + Tags + { + "Queue" = "Transparent" + "PreviewType"="Plane" + } + + Pass + { + Blend [_SrcBlendMode] [_DstBlendMode] + Cull [_CullMode] + ZWrite [_ZWriteMode] + ZTest [unity_GUIZTestMode] + + CGPROGRAM + #pragma vertex vert + #pragma fragment frag + #if defined(SHADER_API_PSP2) || defined(SHADER_API_PS3) + // seems that ARB_precision_hint_fastest is not supported on these platforms. + #else + #pragma fragmentoption ARB_precision_hint_fastest + #endif + + #include "UnityCG.cginc" + + #pragma multi_compile _ CRI_ALPHA_MOVIE + #pragma multi_compile _ CRI_APPLY_TARGET_ALPHA + #pragma multi_compile _ CRI_LINEAR_COLORSPACE + + struct appdata + { + float4 vertex : POSITION; + half2 texcoord : TEXCOORD0; +#ifdef CRI_APPLY_TARGET_ALPHA + float4 color : COLOR; +#endif + }; + + struct v2f + { + float4 pos : SV_POSITION; + half2 uv : TEXCOORD0; + half2 uv2 : TEXCOORD1; +#ifdef CRI_ALPHA_MOVIE + half2 uv3 : TEXCOORD2; +#endif +#ifdef CRI_APPLY_TARGET_ALPHA + float4 color : COLOR; +#endif + }; + + float4 _MainTex_ST; + float4 _MovieTexture_ST; + float4 _MovieChromaTexture_ST; +#ifdef CRI_ALPHA_MOVIE + float4 _MovieAlphaTexture_ST; +#endif + + v2f vert(appdata v) + { + v2f o; + o.pos = UnityObjectToClipPos(v.vertex); + o.uv = (TRANSFORM_TEX(v.texcoord, _MainTex) * _MovieTexture_ST.xy) + _MovieTexture_ST.zw; + o.uv2 = (TRANSFORM_TEX(v.texcoord, _MainTex) * _MovieChromaTexture_ST.xy) + _MovieChromaTexture_ST.zw; +#ifdef CRI_ALPHA_MOVIE + o.uv3 = (TRANSFORM_TEX(v.texcoord, _MainTex) * _MovieAlphaTexture_ST.xy) + _MovieAlphaTexture_ST.zw; +#endif +#ifdef CRI_APPLY_TARGET_ALPHA + o.color = v.color; +#endif + return o; + } + + static const fixed3x3 yuv_to_rgb = { + {1.16438, 0.0, 1.59603}, + {1.16438, -0.39176, -0.81297}, + {1.16438, 2.01723, 0.0} + }; + + sampler2D _TextureY; + sampler2D _TextureU; + sampler2D _TextureV; +#ifdef CRI_ALPHA_MOVIE + sampler2D _TextureA; +#endif + + fixed _Transparency; + + fixed4 frag(v2f i) : COLOR + { + fixed3 yuv; + yuv.r = tex2D(_TextureY, i.uv).a; + yuv.g = tex2D(_TextureU, i.uv2).a; + yuv.b = tex2D(_TextureV, i.uv2).a; + yuv = yuv + fixed3(-0.06275, -0.50196, -0.50196); + fixed4 color; + color.rgb = mul(yuv_to_rgb, yuv); +#ifdef CRI_LINEAR_COLORSPACE + color.rgb = pow(max(color.rgb, 0), 2.2); +#endif +#ifdef CRI_ALPHA_MOVIE + color.a = tex2D(_TextureA, i.uv3).a; +#else + color.a = 1.0; +#endif +#ifdef CRI_APPLY_TARGET_ALPHA + color.a = color.a * i.color.a; +#endif + color.a *= 1- _Transparency; + + return color; + } + ENDCG + } + } +} diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Resources/CriMana/SofdecPrimeYuv/SofdecPrimeYuv.shader.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Resources/CriMana/SofdecPrimeYuv/SofdecPrimeYuv.shader.meta new file mode 100644 index 0000000..c324ef2 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriMana/Resources/CriMana/SofdecPrimeYuv/SofdecPrimeYuv.shader.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 1ac7f9ee6084e48ac96b6c17313fea88 +timeCreated: 1445063783 +licenseType: Pro +ShaderImporter: + defaultTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriWare.cs b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriWare.cs new file mode 100644 index 0000000..4868225 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriWare.cs @@ -0,0 +1,377 @@ +/**************************************************************************** + * + * Copyright (c) 2012 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +using UnityEngine; +using System; +using System.Runtime.InteropServices; +using System.Runtime.CompilerServices; +using System.Collections; +using System.Collections.Generic; +using System.IO; + +/** + * \addtogroup CRIWARE_COMMON_CLASS + * @{ + */ + +namespace CriWare { + +/** + * A class which provides auxiliary functions related to the CRIWARE plug-in. + * + * Provides an auxiliary method that can be commonly used in platforms.
+ * By using the properties and methods of this class, you can get a path to a special data folder + * or check the CPU /memory usage by CRIWARE plug-in.
+ *
+ */ + +public class Common +{ + /* スクリプトバージョン */ + private const string scriptVersionString = "2.39.68"; + private const int scriptVersionNumber = 0x02396800; + + /** + * Whether CriFsInstaller API is supported or not + * + * Used to determine if the CriFsInstaller API is available on the execution environment. + * + */ + public const bool supportsCriFsInstaller = + #if UNITY_EDITOR || UNITY_STANDALONE_OSX || UNITY_STANDALONE_WIN || UNITY_IOS || UNITY_TVOS || UNITY_ANDROID || UNITY_WINRT + true; + #else + false; + #endif + + /** + * Whether CriFsWebInstaller API is supported or not + * + * Used to determine if the CriFsWebInstaller API is available on the execution environment. + * + */ + public const bool supportsCriFsWebInstaller = + #if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX || UNITY_IOS || UNITY_ANDROID + true; + #else + false; + #endif + + /* ネイティブライブラリ */ + #if UNITY_EDITOR + public const string pluginName = "cri_ware_unity"; + #elif UNITY_IOS || UNITY_TVOS || UNITY_WEBGL || UNITY_SWITCH + public const string pluginName = "__Internal"; + #else + public const string pluginName = "cri_ware_unity"; + #endif + + #if ENABLE_IL2CPP && (UNITY_STANDALONE_WIN || UNITY_WINRT) + public const CallingConvention pluginCallingConvention = CallingConvention.Cdecl; + #else + public const CallingConvention pluginCallingConvention = CallingConvention.Winapi; /* default */ + #endif + + /** + * The path of the StreamingAssets folder. + * + * This property returns the StreamingAssets folder path. The value cannot be set. + * In Android environment, this property returns an empty string. + * When accessing the files in StreamingAssets using the function of the CRIWARE plug-in, + * directly specify the relative path below StreamingAssets in Android environment only. + * Note that "/" is not added to the beginning of the path. + * + */ + public static string streamingAssetsPath + { + get { + if (Application.platform == RuntimePlatform.Android) { + return ""; + } +#if UNITY_SWITCH + else if (Application.platform == RuntimePlatform.Switch) { + return "rom:/Data/StreamingAssets"; + } +#elif UNITY_PSP2 + else if (Application.platform == RuntimePlatform.PSP2) { + string ret = Application.streamingAssetsPath; + if (ret.StartsWith("/app0/")) { + var regex = new System.Text.RegularExpressions.Regex("/app0/"); + ret = regex.Replace(ret, "app0:/", 1); + } + return ret; + } +#endif + else { + return Application.streamingAssetsPath; + } + } + } + + /** + * The path of the data folder. + * + * This property returns the data folder path. The value cannot be set. + * In the case of iOS environment, writing files in this folder + * may cause problems in AppStore examination.
+ *
+ */ + public static string installTargetPath + { + get { + #if !UNITY_EDITOR && UNITY_IOS + return Application.temporaryCachePath; + #elif UNITY_EDITOR || !UNITY_SWITCH + return Application.persistentDataPath; + #else + return null; + #endif + } + } + + /** + * The path of the cache data folder. + * + * Returns the path of the cache data folder.
+ * The files under the directory returned by this property are writable (from the application).
+ * Returns a path which may not be persistent on some platforms.
+ * Whether the path returned by this property is persistent depends on whether AssetBundle caching is enabled / disabled for each platform.
+ *
+ */ + public static string installCachePath + { + get { +#if !UNITY_EDITOR && UNITY_SWITCH + return string.Format("{0}:/cri", CriWareSwitch.TemporaryStorageName); +#else // UNITY_EDITOR && UNITY_SWITCH +#if ENABLE_CACHING || !UNITY_2018_4_OR_NEWER + return Caching.currentCacheForWriting.path; +#else // ENABLE_CACHING || !UNITY_2018_4_ORNEWER + return Application.temporaryCachePath; +#endif // ENABLE_CACHING || !UNITY_2018_4_ORNEWER +#endif // UNITY_EDITOR && UNITY_SWITCH + } + } + + /** + * Determines whether it is used as a relative path from the StreamingAssets folder + * File path + * Whether it is used as a relative path from the StreamingAssets folder + * + * Determines whether the path is used as a relative path from the StreamingAssets folder in the CRIWARE plug-in.
+ * The CRIWARE plug-in uses the path that meets all the following conditions as a relative path from the StreamingAssets folder. + * - Is not an absolute path + * - Does not contain ':'
+ * Refer to the reference of each API to see if it is actually used as a relative path from the StreamingAssets folder. + *
+ */ + public static bool IsStreamingAssetsPath(string path) + { + return !Path.IsPathRooted(path) && (path.IndexOf(':') < 0); + } + + private static GameObject _managerObject = null; + public static GameObject managerObject + { + get { + if (_managerObject == null) { + _managerObject = GameObject.Find("/CRIWARE"); + if (_managerObject == null) { + _managerObject = new GameObject("CRIWARE"); + } + UnityEngine.Object.DontDestroyOnLoad(_managerObject); + } + return _managerObject; + } + } + + /** + * Gets script version string + * + * This method returns the script version string of CRIWARE. + * + */ + public static string GetScriptVersionString() { + return scriptVersionString; + } + + /** + * Gets script version number + * + * This method returns the script version number of CRIWARE. + * + */ + public static int GetScriptVersionNumber() { + return scriptVersionNumber; + } + + /** + * Gets the binary version number + * + * This method returns the binary version number of CRIWARE. + * The binary here means the library file (.dll etc.) included in the CRIWARE plug-in. + * + */ + public static int GetBinaryVersionNumber() { + return CRIWAREC9847394(); + } + + /** + * Gets the binary version required by the script + * + * This method returns the runtime version number required by the CRIWARE script. + * + */ + public static int GetRequiredBinaryVersionNumber() { +#if true + return 0x02396800; +#else +#if UNITY_EDITOR + switch (Application.platform) { + case RuntimePlatform.WindowsEditor: + return 0x02396800; + case RuntimePlatform.OSXEditor: + return 0x02396800; + case RuntimePlatform.LinuxEditor: + return 0x02396800; + default: + return 0x02396800; + } +#elif UNITY_STANDALONE_WIN + return 0x02396800; +#elif UNITY_STANDALONE_OSX + return 0x02396800; +#elif UNITY_IOS + return 0x02396800; +#elif UNITY_TVOS + return 0x02396800; +#elif UNITY_ANDROID + return 0x02396800; +#elif UNITY_PSP2 + return 0x02396800; +#elif UNITY_PS3 + return 0x02396800; +#elif UNITY_PS4 + return 0x02396800; +#elif UNITY_PS5 + return 0x02396800; +#elif UNITY_XBOXONE + return 0x02396800; +#elif UNITY_GAMECORE_XBOXONE + return 0x02396800; +#elif UNITY_GAMECORE_SCARLETT + return 0x02396800; +#elif UNITY_WINRT + return 0x02396800; +#elif UNITY_WEBGL + return 0x02396800; +#elif UNITY_SWITCH + return 0x02396800; +#elif UNITY_STADIA + return 0x02396800; +#elif UNITY_STANDALONE_LINUX + return 0x02396800; +#else + return 0x02396800; +#endif +#endif + } + + /** + * Checks the consistency between binary version and script version + * + * This method checks if the current binary matches the version number required by the script.
+ * If they match, the integrity check is considered successful and True is returned.
+ * If they don't match, it is considered as a failure, an error message is output to the console, and False is returned.
+ *
+ */ + public static bool CheckBinaryVersionCompatibility() { + if (GetBinaryVersionNumber() == GetRequiredBinaryVersionNumber()) { + return true; + } else { + Debug.LogError("CRI runtime library is not compatible. Confirm the version number."); + return false; + } + } + + /** + * Gets the memory usage of CRI FileSystem + * + * This method returns the memory usage of CRI FileSystem. + * + */ + public static uint GetFsMemoryUsage() + { + return CriFsPlugin.CRIWARE4A9B2613(); + } + + /** + * Gets the memory usage of CRI Atom + * + * This method returns the memory usage of CRI Atom. + * + */ + public static uint GetAtomMemoryUsage() + { + return CriAtomPlugin.CRIWARE581F45FE(); + } + + /** + * Gets the memory usage of CRI Mana + * + * This method returns the memory usage of CRI Mana. + * + */ + public static uint GetManaMemoryUsage() + { +#if !UNITY_EDITOR && UNITY_WEBGL + return 0; +#else + return CriManaPlugin.CRIWARE065392A8(); +#endif + } + + /** + * CPU usage of the CRIWARE plug-in + */ + public struct CpuUsage + { + public float last; + public float average; + public float peak; + } + + /** + * Gets the CPU usage of the CRIWARE plug-in + * + * This method returns the CPU usage by the native library of + * CRIWARE plug-in. The return value is a CpuUsage structure. + * + */ + public static CpuUsage GetAtomCpuUsage() + { + return CriAtomPlugin.GetCpuUsage(); + } + + #region DLL Import + #if !CRIWARE_ENABLE_HEADLESS_MODE + [DllImport(pluginName, CallingConvention = pluginCallingConvention)] + public static extern int CRIWAREC9847394(); + + [DllImport(pluginName, CallingConvention = pluginCallingConvention)] + public static extern void criWareUnity_SetRenderingEventOffsetForMana(int offset); + #else + public static int CRIWAREC9847394() { return GetRequiredBinaryVersionNumber(); } + public static void criWareUnity_SetRenderingEventOffsetForMana(int offset) { } + #endif + #endregion + +} // end of class + +} //namespace CriWare +/** @} */ + +/* --- end of file --- */ diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriWare.cs.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriWare.cs.meta new file mode 100644 index 0000000..e74edd7 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriWare.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: b2fb419eaf0c13a4db14aecebacf89e2 +timeCreated: 1433816076 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriWareDecrypter.cs b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriWareDecrypter.cs new file mode 100644 index 0000000..5ffd2c8 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriWareDecrypter.cs @@ -0,0 +1,110 @@ +/**************************************************************************** + * + * Copyright (c) 2018 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +using System; +using System.Runtime.InteropServices; + +/** + * \addtogroup CRIWARE_COMMON_CLASS + * @{ + */ + +namespace CriWare { + +/** + * A class which provides the function for setting encrypted data playback. + * + * Provides the function to set the decryption when playing encrypted data.
+ * The decryption function can be initialized by calling the functions provided by this class.
+ *
+ */ +public static class CriWareDecrypter { + + /** + * Initialization (config specified) + * Initialization config + * Whether the initialization succeeded + * + * Initializes the Decrytper.
+ * This function is called automatically when CriWareInitializer is set.
+ * Call this function after initializing the FileSystem library. + *
+ */ + public static bool Initialize(CriWareDecrypterConfig config) { + return Initialize(config.key, config.authenticationFile, + config.enableAtomDecryption, config.enableManaDecryption); + } + + /** + * Initialization (parameter specified) + * Encryption key + * Authentication file path (absolute path or relative path from SreamingAssets) + * Whether to decode the sound data + * Whether to decrypt the movie data + * Whether the initialization succeeded + * + * Initializes the Decrytper.
+ * This function is called automatically when CriWareInitializer is set.
+ * Call this function after initializing the FileSystem library. + *
+ */ + public static bool Initialize(string key, string authenticationFile, bool enableAtomDecryption, bool enableManaDecryption) { + if (!CriFsPlugin.IsLibraryInitialized()) { + return false; + } + + /* バージョン番号が不正なライブラリには暗号キーを伝えない */ + /* 備考)不正に差し替えられたsoファイルを使用している可能性あり。 */ + bool isCorrectVersion = CriWare.Common.CheckBinaryVersionCompatibility(); + if (isCorrectVersion == false) { + return false; + } + + ulong decryptionKey = (key.Length == 0) ? 0 : System.Convert.ToUInt64(key); + string authenticationPath = authenticationFile; + if (CriWare.Common.IsStreamingAssetsPath(authenticationPath)) { + authenticationPath = System.IO.Path.Combine(CriWare.Common.streamingAssetsPath, authenticationPath); + } + + temporalStorage = decryptionKey ^ 0x00D47EB533AEF7E5UL; + CRIWAREB9DA24BC(enableAtomDecryption, enableManaDecryption, CallbackFromNative, IntPtr.Zero); + temporalStorage = 0; + + return true; + } + + /* 変数の一時的な格納場所 */ + private static ulong temporalStorage = 0; + + #region Private Methods + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public delegate ulong CallbackFromNativeDelegate(System.IntPtr ptr1); + + [AOT.MonoPInvokeCallback(typeof(CallbackFromNativeDelegate))] + private static ulong CallbackFromNative(System.IntPtr ptr1) + { + return temporalStorage; + } + #endregion + + #region DLL Import + #if !CRIWARE_ENABLE_HEADLESS_MODE + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + public static extern int CRIWAREB9DA24BC( + bool enable_atom_decryption, bool enable_mana_decryption, CallbackFromNativeDelegate func, IntPtr obj + ); + #else + public static int CRIWAREB9DA24BC( + bool enable_atom_decryption, bool enable_mana_decryption, CallbackFromNativeDelegate func, IntPtr obj + ) { return 0; } + #endif + #endregion +} // end of class + +} //namespace CriWare +/** @} */ + +/* --- end of file --- */ diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriWareDecrypter.cs.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriWareDecrypter.cs.meta new file mode 100644 index 0000000..7214182 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriWareDecrypter.cs.meta @@ -0,0 +1,13 @@ +fileFormatVersion: 2 +guid: 1063d921dd231744b97252e916c51b2e +timeCreated: 1532426690 +licenseType: Pro +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriWareErrorHandler.cs b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriWareErrorHandler.cs new file mode 100644 index 0000000..9a336f7 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriWareErrorHandler.cs @@ -0,0 +1,322 @@ +/**************************************************************************** + * + * Copyright (c) 2012 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +#pragma warning disable 0618 + +using UnityEngine; +using System; +using System.Collections.Concurrent; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +/** + * \addtogroup CRIWARE_UNITY_COMPONENT + * @{ + */ + namespace CriWare { + +/** + * CRIWARE error handling object + * + * This component obtains and outputs error messages generated by the CRIWARE library.
+ *
+ */ +[AddComponentMenu("CRIWARE/Error Handler")] +public class CriWareErrorHandler : CriMonoBehaviour{ + /** + * \deprecated + * 削除予定の非推奨APIです。本値は使用されていません。 + * Whether to enable Coroutine debug output + * + * Whether to enable console debug output along with Unity debug window output [deprecated] + * It will only output to the Unity debug window on PC. + * + */ + public bool enableDebugPrintOnTerminal = false; + + /** Whether to force crashing on error (for debug only) */ + public bool enableForceCrashOnError = false; + + /** Whether to remove the error handler at scene change */ + public bool dontDestroyOnLoad = true; + + /** + * \deprecated + * This is a deprecated API that will be removed. The value is not used. + */ + public static string errorMessage { get; set; } + + /** + * Log message prefix + * + * Prefix indicating log messages from CRIWARE. + * + */ + public static readonly string logPrefix = "[CRIWARE]"; + + /** + * Error callback delegate + * + * A callback delegate that will be called when an error occurs + * in the CRIWARE native library.
+ * The argument string contains the message in the format "Error ID: Error details".
+ *
+ */ + public delegate void Callback(string message); + + /** + * Error callback event + * + * A callback event that will be called when an error occurs in the CRIWARE native library.
+ * If not set, the default log output function defined in this class will be called.
+ * If you want to write your own rror handling based on the error message, + * register a delegate and handle the error inside the callback function.
+ * This event is always called from the main thread.
+ * The registered callback may be called at any time while CriWareErrorHandler is active.
+ * Therefore, be careful not to release the instance of the callback before CriWareErrorHandler .
+ *
+ */ + public static event Callback OnCallback = null; + + /** + * \deprecated + * 削除予定の非推奨APIです。 + * CriWareErrorHandler.OnCallback event の使用を検討してください。 + * Error callback + * + * A callback that will be called when an error occurs in the CRIWARE native library.
+ * If not set, the default log output function defined in this class will be called.
+ * If a user defined process based on the error message is preferred, + * register a delegate and perform the process inside the callback function.
+ * Set the callback to null to unregister.
+ * The registered callback may be called at any time while CriWareErrorHandler is active.
+ * Therefore, be careful not to release the instance of the callback before CriWareErrorHandler .
+ *
+ */ + [Obsolete("CriWareErrorHandler.callback is deprecated. Use CriWareErrorHandler.OnCallback event", false)] + public static Callback callback = null; + + /** + * \deprecated + * This is a deprecated API that will be removed. + * This value is not referenced since error messages can now be queued regardless of this value. + */ + public uint messageBufferCounts = 8; + + private ConcurrentQueue unThreadSafeMessages = new ConcurrentQueue(); + + /* オブジェクト作成時の処理 */ + void Awake() { + /* 初期化カウンタの更新 */ + initializationCount++; + if (initializationCount != 1) { + /* 多重初期化は許可しない */ + GameObject.Destroy(this); + return; + } + + if (!CriErrorNotifier.IsRegistered(HandleMessage)) { + CriErrorNotifier.OnCallbackThreadUnsafe += HandleMessage; + } + + /* シーンチェンジ後もオブジェクトを維持するかどうかの設定 */ + if (dontDestroyOnLoad) { + DontDestroyOnLoad(transform.gameObject); + } + } + + /* Execution Order の設定を確実に有効にするために OnEnable をオーバーライド */ + protected override void OnEnable() { + base.OnEnable(); + if (!CriErrorNotifier.IsRegistered(HandleMessage)) { + CriErrorNotifier.OnCallbackThreadUnsafe += HandleMessage; + } + } + + protected override void OnDisable() { + base.OnDisable(); + if (CriErrorNotifier.IsRegistered(HandleMessage)) { + CriErrorNotifier.OnCallbackThreadUnsafe -= HandleMessage; + } + } + + public override void CriInternalUpdate() { + DequeueErrorMessages(); + } + + public override void CriInternalLateUpdate() { } + + void OnDestroy() { + /* 初期化カウンタの更新 */ + initializationCount--; + if (initializationCount != 0) { + return; + } + + /* エラー処理の終了処理 */ + if (CriErrorNotifier.IsRegistered(HandleMessage)) { + CriErrorNotifier.OnCallbackThreadUnsafe -= HandleMessage; + } + } + + /* エラーメッセージのポーリングと出力 */ + private void DequeueErrorMessages() { + string dequeuedMessage; + while (unThreadSafeMessages.Count != 0) { + if (!unThreadSafeMessages.TryDequeue(out dequeuedMessage)) { + continue; + } + if (OnCallback != null) { + OnCallback(dequeuedMessage); + } + if (callback != null) { + callback(dequeuedMessage); + } + } + } + + private void HandleMessage(string errmsg) { + if (errmsg == null) { + return; + } + + if (OnCallback == null && callback == null) { + OutputDefaultLog(errmsg); + } else { + unThreadSafeMessages.Enqueue(errmsg); + } + if (enableForceCrashOnError) { + UnityEngine.Diagnostics.Utils.ForceCrash(UnityEngine.Diagnostics.ForcedCrashCategory.Abort); + } + } + + /** Default log output */ + private static void OutputDefaultLog(string errmsg) + { + if (errmsg.StartsWith("E")) { + Debug.LogError(logPrefix + " Error:" + errmsg); + } else if (errmsg.StartsWith("W")) { + Debug.LogWarning(logPrefix + " Warning:" + errmsg); + } else { + Debug.Log(logPrefix + errmsg); + } + } + + /** Initialization counter */ + private static int initializationCount = 0; + +} // end of class + + /** + * Gets error log for CRIWARE native libraries + * + * This class obtains the error logs generated within the CRIWARE native library.
+ *
+ */ + public static class CriErrorNotifier { + /** + * Error callback delegate + * + * A callback delegate that will be called when an error occurs + * in the CRIWARE native library.
+ * The argument string contains the message in the format "Error ID: Error details".
+ *
+ * + */ + public delegate void Callback(string message); + private static event Callback _onCallbackThreadUnsafe = null; + private static object objectLock = new System.Object(); + + /** + * Error callback event + * + * Callback event triggered when an error occurs in the CRIWARE native library.
+ * If it is not set, no log is output.
+ * This event may be called from outside the main thread.
+ * Therefore, be sure to register a thread-safe API for this event.
+ *
+ * + */ + public static event Callback OnCallbackThreadUnsafe { + add { + lock (objectLock) { + if (_onCallbackThreadUnsafe == null || _onCallbackThreadUnsafe.GetInvocationList().Length <= 0) { + NativeMethod.criErr_SetCallback(null); + NativeMethod.criErr_SetCallback(ErrorCallbackFromNative); + } + _onCallbackThreadUnsafe += value; + } + } + remove { + lock (objectLock) { + _onCallbackThreadUnsafe -= value; + if (_onCallbackThreadUnsafe == null || _onCallbackThreadUnsafe.GetInvocationList().Length <= 0) { + NativeMethod.criErr_SetCallback(null); + } + } + } + } + + /** + * Check for registered error callback events + * Method to be evaluated + * Whether it is registered + * + * Checks whether the specified method is registered in .
+ * Use this to avoid duplicate registrations, and to ensure that everything has been properly released.
+ *
+ * + * + */ + public static bool IsRegistered(Callback target) { + if (_onCallbackThreadUnsafe == null) { + return false; + } + foreach (Callback item in _onCallbackThreadUnsafe.GetInvocationList()) { + if (item == target) { + return true; + } + } + return false; + } + + /** + * Plug-in internal functions + * This function is not designed to be called by the user.
+ */ + public static void CallEvent(string message) { + // for expansion + if (_onCallbackThreadUnsafe != null) { + _onCallbackThreadUnsafe(message); + } + } + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + internal delegate void ErrorCallbackFunc(IntPtr errmsgPtr, System.UInt32 p1, System.UInt32 p2, IntPtr parray); + + [AOT.MonoPInvokeCallback(typeof(ErrorCallbackFunc))] + private static void ErrorCallbackFromNative(IntPtr errmsgPtr, System.UInt32 p1, System.UInt32 p2, IntPtr parray) { + string errmsg = Marshal.PtrToStringAnsi(NativeMethod.criErr_ConvertIdToMessage(errmsgPtr, p1, p2)); + CallEvent(errmsg); + } + + protected static class NativeMethod { +#if !CRIWARE_ENABLE_HEADLESS_MODE + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + internal static extern void criErr_SetCallback(ErrorCallbackFunc callback); + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + internal static extern IntPtr criErr_ConvertIdToMessage(IntPtr errmsgPtr, System.UInt32 p1, System.UInt32 p2); +#else + internal static void criErr_SetCallback(ErrorCallbackFunc callback) { } + internal static IntPtr criErr_ConvertIdToMessage(IntPtr errmsgPtr, System.UInt32 p1, System.UInt32 p2) { return IntPtr.Zero; } +#endif + } + } + +} //namespace CriWare +/** @} */ + +/* --- end of file --- */ diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriWareErrorHandler.cs.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriWareErrorHandler.cs.meta new file mode 100644 index 0000000..e0594cf --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriWareErrorHandler.cs.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: f154ff0ac54c142928b46e94a4ee0790 +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: -13 + icon: {instanceID: 0} diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriWareInitializer.cs b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriWareInitializer.cs new file mode 100644 index 0000000..4244c5d --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriWareInitializer.cs @@ -0,0 +1,836 @@ +/**************************************************************************** + * + * Copyright (c) 2012 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +using UnityEngine; +using System; +using System.Runtime.InteropServices; +using System.IO; +using System.Collections.Generic; + +namespace CriWare { + +/** + * Parameters for initializing CRI File System + */ +[System.Serializable] +public class CriFsConfig { + /** Default reading performance of the device (bps) */ + public const int defaultAndroidDeviceReadBitrate = 50000000; + + /** Number of the loaders */ + public int numberOfLoaders = 16; + /** Number of binders */ + public int numberOfBinders = 8; + /** Number of installers */ + public int numberOfInstallers = 2; + /** Install buffer size */ + public int installBufferSize = CriFsPlugin.defaultInstallBufferSize / 1024; + /** Maximum length of the path */ + public int maxPath = 256; + /** User agent string */ + public string userAgentString = ""; + /** Flag of the file descriptor saving mode */ + public bool minimizeFileDescriptorUsage = false; + /** Whether to do CRC check on the CPK file */ + public bool enableCrcCheck = false; + /** [Android] Device reading performance (bps) */ + public int androidDeviceReadBitrate = defaultAndroidDeviceReadBitrate; + +} + +/** + * Parameters for initializing CRI Atom + */ +[System.Serializable] +public class CriAtomConfig { + /** + * ACF file name + * + * The ACF file need to be placed in the StreamingAssets folder. + * + */ + public string acfFileName = ""; + + /** Parameters for creating standard Voice Pool */ + [System.Serializable] + public class StandardVoicePoolConfig { + public int memoryVoices = 16; + public int streamingVoices = 8; + } + + /** HCA-MX Voice Pool creation parameters */ + [System.Serializable] + public class HcaMxVoicePoolConfig { + public int memoryVoices = 0; + public int streamingVoices = 0; + } + + /** In-Game Preview settings */ + [System.Serializable] + public enum InGamePreviewSwitchMode { + Disable, /** Disabled */ + Enable, /** Enabled */ + FollowBuildSetting, /** Available for Development Build only */ + Default /** "usesInGamePreview" */ + } + + /** In-Game Preview parameters */ + [System.Serializable] + public class InGamePreviewConfig { + /** Maximum number of preview objects */ + public int maxPreviewObjects = 200; + /** Communication buffer size (KiB) */ + public int communicationBufferSize = 2048; + /** Interval at which the playback position is updated (number of server processing calls) */ + public int playbackPositionUpdateInterval = 8; + } + + /** Maximum number of virtual Voices */ + public int maxVirtualVoices = 32; + /** Maximum number of Voice limit groups */ + public int maxVoiceLimitGroups = 32; + /** Maximum number of categories */ + public int maxCategories = 32; + /** Maximum number of AISACs */ + public int maxAisacs = 8; + /** Maximum number of bus sends */ + public int maxBusSends = 8; + /** Maximum number of sequence events in each frame */ + public int maxSequenceEventsPerFrame = 2; + /** Maximum number of beat-synchronization callbacks in each frame */ + public int maxBeatSyncCallbacksPerFrame = 1; + /** Maximum number of Cue Link callbacks per frame */ + public int maxCueLinkCallbacksPerFrame = 1; + /** Parameters for creating standard Voice Pool */ + public StandardVoicePoolConfig standardVoicePoolConfig = new StandardVoicePoolConfig(); + /** HCA-MX Voice Pool creation parameters */ + public HcaMxVoicePoolConfig hcaMxVoicePoolConfig = new HcaMxVoicePoolConfig(); + /** Output sampling rate */ + public int outputSamplingRate = 0; + /** Whether to use In-Game Preview */ + public bool usesInGamePreview = false; + /** In-Game Preview settings (effective only when specified in inspector) */ + public InGamePreviewSwitchMode inGamePreviewMode = InGamePreviewSwitchMode.Default; + /* @cond excludele */ + /** [Switch] Whether to initialize the socket library */ + public bool switchInitializeSocket = false; + /* @endcond*/ + /** In-Game Preview parameters */ + public InGamePreviewConfig inGamePreviewConfig = new InGamePreviewConfig(); + /** Server frequency */ + public float serverFrequency = 60.0f; + /** The number of ASR output channels */ + public int asrOutputChannels = 0; + /** Whether to use time(System.DateTime.Now.Ticks) as random seed */ + public bool useRandomSeedWithTime = true; + /** Number of category references per playback */ + public int categoriesPerPlayback = 4; + /** Maximum number of faders */ + public int maxFaders = 4; + /** Maximum number of buses */ + public int maxBuses = 8; + /** Maximum number of parameter blocks */ + public int maxParameterBlocks = 1024; + /** Whether to use VR sound output mode */ + public bool vrMode = false; + /** Whether to pause the audio output when paused on a StandAlone platform or in the editor */ + public bool keepPlayingSoundOnPause = true; + + /** [Editor] Parameters related to the User PCM Output Mode */ + [System.Serializable] + public class EditorPcmOutputConfig + { + public bool enable = false; + public int bufferLength = 4096; + } + /** [Editor] Parameters related to the User PCM Output Mode */ + public EditorPcmOutputConfig editorPcmOutputConfig = new EditorPcmOutputConfig(); + + /** [PC] Output buffering time */ + public int pcBufferingTime = 0; + + /* @cond excludele */ + /** [Linux] Output type */ + public enum LinuxOutput : int { + Default = 0, /** Outputs to default audio system (PulseAudio). */ + PulseAudio = 1, /** Outputs to PulseAudio system. */ + ALSA = 2 /** Outputs to Advanced Linux Sound Achitecture system. */ + }; + /** [Linux] Specify output type */ + public LinuxOutput linuxOutput = LinuxOutput.Default; + /** [Linux] PulseAudio latency (microsecond) */ + public int linuxPulseLatencyUsec = 60000; + /* @endcond */ + + /** [iOS] Enables SonicSYNC mode */ + public bool iosEnableSonicSync = true; + /** [iOS] Output buffering time (milliseconds) */ + public int iosBufferingTime = 50; + /** [iOS] Whether to override iPod playback */ + public bool iosOverrideIPodMusic = false; + + /** [Android] Enables SonicSYNC Mode */ + public bool androidEnableSonicSync = true; + /** [Android] ASR (normal playback) output buffering time */ + public int androidBufferingTime = 133; + /** [Android] NSR (Low Delay Playback) Playback Start Buffering Time */ + public int androidStartBufferingTime = 100; + + /** [Android] Parameters for creating low latency playback Voice Pool */ + [System.Serializable] + public class AndroidLowLatencyStandardVoicePoolConfig { + public int memoryVoices = 0; + public int streamingVoices = 0; + } + /** [Android] Parameters for creating low latency playback Voice Pool */ + public AndroidLowLatencyStandardVoicePoolConfig androidLowLatencyStandardVoicePoolConfig = new AndroidLowLatencyStandardVoicePoolConfig(); + /** [Android] Whether to use the Fast Mixer of Android to reduce the output delay during audio playback. Affects the output delay of ASR/NSR and the result of delay estimation function */ + public bool androidUsesAndroidFastMixer = true; + /** [Android] Force CriAtomSource to use ASR for playback when low lantency playback is enabled */ + public bool androidForceToUseAsrForDefaultPlayback = true; + /** [Android] Beta: Enable AAudio or not */ + public bool androidUsesAAudio = false; + + /* @cond excludele */ + /** [PSVita] Parameters for creating Voice Pool for Mana */ + [System.Serializable] + public class VitaManaVoicePoolConfig { + public int numberOfManaDecoders = 8; + } + /** [PSVita] Parameters for creating Voice Pool for Mana */ + public VitaManaVoicePoolConfig vitaManaVoicePoolConfig = new VitaManaVoicePoolConfig(); + + /** [PSVita] Parameters for creating ATRAC9 Voice Pool */ + [System.Serializable] + public class VitaAtrac9VoicePoolConfig { + public int memoryVoices = 0; + public int streamingVoices = 0; + } + /** [PSVita] Parameters for creating ATRAC9 Voice Pool */ + public VitaAtrac9VoicePoolConfig vitaAtrac9VoicePoolConfig = new VitaAtrac9VoicePoolConfig(); + + /** [PS4] Parameters for creating ATRAC9 Voice Pool */ + [System.Serializable] + public class Ps4Atrac9VoicePoolConfig { + public int memoryVoices = 0; + public int streamingVoices = 0; + } + /** [PS4] Parameters for creating ATRAC9 Voice Pool */ + public Ps4Atrac9VoicePoolConfig ps4Atrac9VoicePoolConfig = new Ps4Atrac9VoicePoolConfig(); + + /** [Switch] Enables the SonicSYNC mode */ + public bool switchEnableSonicSync = true; + + /** [Switch] Parameters for creating Opus Voice Pool */ + [System.Serializable] + public class SwitchOpusVoicePoolConfig { + public int memoryVoices = 0; + public int streamingVoices = 0; + } + /** [Switch] Parameters for creating Opus Voice Pool */ + public SwitchOpusVoicePoolConfig switchOpusVoicePoolConfig = new SwitchOpusVoicePoolConfig(); + + /** [PS4] Parameters for creating Audio3D Voice Pool */ + [System.Serializable] + public class Ps4Audio3dConfig { + /** [PS4] Whether to use Audio3D function */ + public bool useAudio3D = false; + + /** [PS4] Parameters for creating Audio3D Voice Pool */ + [System.Serializable] + public class VoicePoolConfig { + public int memoryVoices = 0; + public int streamingVoices = 0; + } + public VoicePoolConfig voicePoolConfig = new VoicePoolConfig(); + + } + public Ps4Audio3dConfig ps4Audio3dConfig = new Ps4Audio3dConfig(); + + /** [WebGL] Parameters for creating WebAudio Voice Pool */ + [System.Serializable] + public class WebGLWebAudioVoicePoolConfig { + public int voices = 16; + } + public WebGLWebAudioVoicePoolConfig webglWebAudioVoicePoolConfig = new WebGLWebAudioVoicePoolConfig(); + /* @endcond */ +} + +/** + * Parameters for initializing CRI Mana + */ +[System.Serializable] +public class CriManaConfig { + /** Number of decoders */ + public int numberOfDecoders = 8; + /** Number of seamless playback entries */ + public int numberOfMaxEntries = 4; + /** Whether to enable multi-threaded texture drawing processing using GL.IssuePluginEvent */ + public readonly bool graphicsMultiThreaded = true; // always true. + + /* @cond excludele */ + /** [PC] Configurations of H.264 movie playback */ + [System.Serializable] + public class PCH264PlaybackConfig { + public bool useH264Playback = true; + } + public PCH264PlaybackConfig pcH264PlaybackConfig = new PCH264PlaybackConfig(); + + /** [PSVita] Configurations of H.264 movie playback */ + [System.Serializable] + public class VitaH264PlaybackConfig { + /** Whether to use H.264 playback function */ + public bool useH264Playback = false; + /** Width of the playing H.264 movie (maximum) */ + public int maxWidth = 960; + /** Height of the playing H.264 movie (maximum) */ + public int maxHeight = 544; + public bool getMemoryFromTexture = false; + } + public VitaH264PlaybackConfig vitaH264PlaybackConfig = new VitaH264PlaybackConfig(); + + /** [WebGL] WebGL configurations */ + [System.Serializable] + public class WebGLConfig + { + /** Path to the JavaScript for WebWorker */ + public string webworkerPath = "StreamingAssets"; + public int heapSize = 32; + } + public WebGLConfig webglConfig = new WebGLConfig(); + /* @endcond */ +} + +/* @cond notpublic */ +/** + * CRI Ware Decrypter initialization parameters + */ +[System.Serializable] +public class CriWareDecrypterConfig { + /** Encryption key */ + public string key = ""; + /** Decryption authentication file path */ + public string authenticationFile = ""; + /** Whether to enable decryption in CRI Atom */ + public bool enableAtomDecryption = true; + /** Whether to enable decryption in CRI Mana */ + public bool enableManaDecryption = true; +} +/* @endcond */ + +} //namespace CriWare + +/** + * \addtogroup CRIWARE_UNITY_COMPONENT + * @{ + */ + +namespace CriWare { + +/** + * CRIWARE initialization component + * + * This component is used to initialize the CRIWARE library.
+ *
+ */ +[AddComponentMenu("CRIWARE/Library Initializer")] +public class CriWareInitializer : CriMonoBehaviour { + + /** Whether to initialize the CRI File System library */ + public bool initializesFileSystem = true; + + /** Initialization configuration of the CRI File System library */ + public CriFsConfig fileSystemConfig = new CriFsConfig(); + + /** Whether to initialize the CRI Atom library */ + public bool initializesAtom = true; + + /** Initialization configuration of the CRI Atom library */ + public CriAtomConfig atomConfig = new CriAtomConfig(); + + /** Whether to initialize the CRI Mana library */ + public bool initializesMana = true; + + /** Initialization configuration of the CRI Mana library */ + public CriManaConfig manaConfig = new CriManaConfig(); + + /* @cond notpublic */ + /** Whether to use CRI Ware Decrypter */ + public bool useDecrypter =false; + /* @endcond */ + + /* @cond notpublic */ + /** CRI Ware Decrypter configurations */ + public CriWareDecrypterConfig decrypterConfig = new CriWareDecrypterConfig(); + /* @endcond */ + + /** Whether to initialize the library on Awake */ + public bool dontInitializeOnAwake = false; + + /** Whether to finalize the library at scene change */ + public bool dontDestroyOnLoad = false; + + /* オブジェクト作成時の処理 */ + void Awake() { + /* 現在のランタイムのバージョンが正しいかチェック */ + CriWare.Common.CheckBinaryVersionCompatibility(); + + if (dontInitializeOnAwake) { + /* フラグが立っていた場合はAwakeでは初期化を行わない */ + return; + } + + /* プラグインの初期化 */ + this.Initialize(); + } + + /* Execution Order の設定を確実に有効にするために OnEnable をオーバーライド */ + protected override void OnEnable() { + base.OnEnable(); + } + + void Start () { } + + void OnDestroy() { + Shutdown(); + } + +#if !UNITY_EDITOR && UNITY_IOS + static int frameCnt = 0; +#endif + public override void CriInternalUpdate() { +#if !UNITY_EDITOR && UNITY_IOS + if (frameCnt > 3) { + return; + } + frameCnt++; + if (frameCnt == 2) { + CriAtomPlugin.Pause(true); + } else if (frameCnt == 3) { + CriAtomPlugin.Pause(false); + } +#endif + } + + public override void CriInternalLateUpdate() { } + + /** + * Initializes the plug-in (for manual initialization) + * + * Initializes the plug-in.
+ * By default, this function is automatically called in the Awake function, so the application does not need to call it directly.
+ *
+ * Use this function if you want to dynamically change the initialization parameters from the script.
+ * When using this function, check the CriWare.CriWareInitializer::dontInitializeOnAwake + * property on the Inspector to disable the automatic initialization.
+ * In addition, this function must be called before any plug-in APIs. + * Call it in a script with a higher Script Execution Order.
+ *
+ * + */ + public void Initialize() { + /* 初期化カウンタの更新 */ + initializationCount++; + if (initializationCount != 1) { + /* CriWareInitializer自身による多重初期化は許可しない */ + GameObject.Destroy(this); + return; + } + + /* 非実行時にライブラリ機能を使用していた場合は一度終了処理を行う */ + if ((CriFsPlugin.IsLibraryInitialized() == true && CriAtomPlugin.IsLibraryInitialized() == true && CriManaPlugin.IsLibraryInitialized() == true) || + (CriFsPlugin.IsLibraryInitialized() == true && CriAtomPlugin.IsLibraryInitialized() == true && CriManaPlugin.IsLibraryInitialized() == false) || + (CriFsPlugin.IsLibraryInitialized() == true && CriAtomPlugin.IsLibraryInitialized() == false && CriManaPlugin.IsLibraryInitialized() == false)) { +#if UNITY_EDITOR || (!UNITY_PS3) + /* CRI Manaライブラリの終了 */ + if (initializesMana) { + CriManaPlugin.FinalizeLibrary(); + } +#endif + + /* CRI Atomライブラリの終了 */ + if (initializesAtom) { + /* EstimatorがStop状態になるまでFinalize */ + while (CriAtomExLatencyEstimator.GetCurrentInfo().status != CriAtomExLatencyEstimator.Status.Stop) { + CriAtomExLatencyEstimator.FinalizeModule(); + } + + /* 終了処理の実行 */ + CriAtomPlugin.FinalizeLibrary(); + } + + /* CRI File Systemライブラリの終了 */ + if (initializesFileSystem) { + CriFsPlugin.FinalizeLibrary(); + } + } + + /* CRI File Systemライブラリの初期化 */ + if (initializesFileSystem) { + InitializeFileSystem(fileSystemConfig); + } + + /* @cond excludele */ +#if UNITY_EDITOR_WIN || (!UNITY_EDITOR && UNITY_STANDALONE_WIN) + if (initializesMana) { + /* Atom の初期化前に設定する必要がある */ + CriManaPlugin.SetConfigAdditonalParameters_PC(manaConfig.pcH264PlaybackConfig.useH264Playback); + } +#endif + /* @endcond */ + + /* CRI Atomライブラリの初期化 */ + if (initializesAtom) { + /* @cond excludele */ +#if !UNITY_EDITOR && UNITY_PSP2 + /* Mana と関連する初期化パラメータを設定 */ + atomConfig.vitaManaVoicePoolConfig.numberOfManaDecoders = initializesMana ? manaConfig.numberOfDecoders : 0; +#endif + /* @endcond */ + switch (atomConfig.inGamePreviewMode) { + case CriAtomConfig.InGamePreviewSwitchMode.Disable: + atomConfig.usesInGamePreview = false; + break; + case CriAtomConfig.InGamePreviewSwitchMode.Enable: + atomConfig.usesInGamePreview = true; + break; + case CriAtomConfig.InGamePreviewSwitchMode.FollowBuildSetting: + atomConfig.usesInGamePreview = UnityEngine.Debug.isDebugBuild; + break; + default: + /* 既に設定されたフラグに従う */ + break; + } + InitializeAtom(atomConfig); + } + + /* @cond excludele */ +#if UNITY_EDITOR || (!UNITY_PS3) + /* CRI Manaライブラリの初期化 */ + if (initializesMana) { + InitializeMana(manaConfig); + } +#endif + + /**< Configuration of the CRIWARE Decrypter */ + if (useDecrypter) { + CriWareDecrypter.Initialize(decrypterConfig); + } else { + CriWareDecrypter.Initialize("0", "", false, false); + } + /* @endcond */ + + /* シーンチェンジ後もオブジェクトを維持するかどうかの設定 */ + if (dontDestroyOnLoad) { + DontDestroyOnLoad(transform.gameObject); + } + } + + /** + * Terminates the plug-in (for manual termination) + * + * Exits the plug-in.
+ * By default, this function is automatically called in the OnDestroy function, so the application does not need to call it directly.
+ *
+ */ + public void Shutdown() { + /* 初期化カウンタの更新 */ + initializationCount--; + if (initializationCount != 0) { + initializationCount = initializationCount < 0 ? 0 : initializationCount; + return; + } + + /* @cond excludele */ +#if UNITY_EDITOR || (!UNITY_PS3) + /* CRI Manaライブラリの終了 */ + if (initializesMana) { + CriManaPlugin.FinalizeLibrary(); + } +#endif + /* @endcond */ + + /* CRI Atomライブラリの終了 */ + if (initializesAtom) { + /* EstimatorがStop状態になるまでFinalize */ + while (CriAtomExLatencyEstimator.GetCurrentInfo().status != CriAtomExLatencyEstimator.Status.Stop) { + CriAtomExLatencyEstimator.FinalizeModule(); + } + + /* 終了処理の実行 */ + CriAtomPlugin.FinalizeLibrary(); + } + + /* CRI File Systemライブラリの終了 */ + if (initializesFileSystem) { + CriFsPlugin.FinalizeLibrary(); + } + } + + /* 初期化カウンタ */ + private static int initializationCount = 0; + + /* 初期化実行チェック関数 */ + public static bool IsInitialized() { + if (initializationCount > 0) { + return true; + } else { + /* 現在のランタイムのバージョンが正しいかチェック */ + CriWare.Common.CheckBinaryVersionCompatibility(); + return false; + } + } + + /** + * Registers the interface of a custom effect + * + * A method for registering the interface of the ASR bus effect + * (custom effect) implemented by users. + * You can create your own ASR bus effect by using the + * CRI ADX2 Audio Effect Plugin SDK. + *
+ * Normally, you can only use the provided effect processing. + * By implementing the custom effects library according to the rules defined by CRIWARE, + * users can prepare the custom effects interface for CRIWAER Unity Plug-in. + *
+ * By registering the pointer to this interface with the CRIWAER Unity Plug-in using this function, + * the custom effect is enabled when the CRI library is initialized. + *
+ * Note that the registered custom effects is forcibly unregistered when the CRI library is finalized. + * When initializing the CRI library again, call this function again + * to register the custom effect interface.
+ * Be sure to call this function before initializing the CRI library. + * The custom effect interface added by this function is actually enabled in the + * initialization process of the CRI library. + *
+ */ + static public void AddAudioEffectInterface(IntPtr effect_interface) + { + List effect_interface_list = null; + if (CriAtomPlugin.GetAudioEffectInterfaceList(out effect_interface_list)) + { + effect_interface_list.Add(effect_interface); + } + } + + public static bool InitializeFileSystem(CriFsConfig config) + { + /* CRI File Systemライブラリの初期化 */ + if (!CriFsPlugin.IsLibraryInitialized()) { + CriFsPlugin.SetConfigParameters( + config.numberOfLoaders, + config.numberOfBinders, + config.numberOfInstallers, + (config.installBufferSize * 1024), + config.maxPath, + config.minimizeFileDescriptorUsage, + config.enableCrcCheck + ); + { + /* Ver.2.03.03 以前は 0 がデフォルト値だったことの互換性維持のための処理 */ + if (config.androidDeviceReadBitrate == 0) { + config.androidDeviceReadBitrate = CriFsConfig.defaultAndroidDeviceReadBitrate; + } + } + CriFsPlugin.SetConfigAdditionalParameters_ANDROID(config.androidDeviceReadBitrate); + CriFsPlugin.InitializeLibrary(); + if (config.userAgentString.Length != 0) { + CriFsUtility.SetUserAgentString(config.userAgentString); + } + return true; + } else { + return false; + } + } + + public static bool InitializeAtom(CriAtomConfig config) + { + /* CRI Atomライブラリの初期化 */ + if (CriAtomPlugin.IsLibraryInitialized() == false) { + /* 初期化処理の実行 */ + CriAtomPlugin.SetConfigParameters( + (int)Math.Max(config.maxVirtualVoices, CriAtomPlugin.GetRequiredMaxVirtualVoices(config)), + config.maxVoiceLimitGroups, + config.maxCategories, + config.maxAisacs, + config.maxBusSends, + config.maxSequenceEventsPerFrame, + config.maxBeatSyncCallbacksPerFrame, + config.maxCueLinkCallbacksPerFrame, + config.standardVoicePoolConfig.memoryVoices, + config.standardVoicePoolConfig.streamingVoices, + config.hcaMxVoicePoolConfig.memoryVoices, + config.hcaMxVoicePoolConfig.streamingVoices, + config.outputSamplingRate, + config.asrOutputChannels, + config.usesInGamePreview, + config.serverFrequency, + config.maxParameterBlocks, + config.categoriesPerPlayback, + config.maxFaders, + config.maxBuses, + config.vrMode); + + CriAtomPlugin.SetConfigMonitorParametes( + config.inGamePreviewConfig.maxPreviewObjects, + config.inGamePreviewConfig.communicationBufferSize, + config.inGamePreviewConfig.playbackPositionUpdateInterval + ); + + CriAtomPlugin.SetConfigAdditionalParameters_EDITOR( + config.editorPcmOutputConfig.enable, + config.editorPcmOutputConfig.bufferLength + ); + + CriAtomPlugin.SetConfigAdditionalParameters_PC( + config.pcBufferingTime + ); + + /* @cond excludele */ + CriAtomPlugin.SetConfigAdditionalParameters_LINUX( + config.linuxOutput, + config.linuxPulseLatencyUsec + ); + /* @endcond */ + + CriAtomPlugin.SetConfigAdditionalParameters_IOS( + config.iosEnableSonicSync, + (uint)Math.Max(config.iosBufferingTime, 16), + config.iosOverrideIPodMusic + ); + /* Android 固有の初期化パラメータを登録 */ + { + /* Ver.2.03.03 以前は 0 がデフォルト値だったことの互換性維持のための処理 */ + if (config.androidBufferingTime == 0) { + config.androidBufferingTime = (int)(4 * 1000.0 / config.serverFrequency); + } + if (config.androidStartBufferingTime == 0) { + config.androidStartBufferingTime = (int)(3 * 1000.0 / config.serverFrequency); + } +#if !UNITY_EDITOR && UNITY_ANDROID + CriAtomEx.androidDefaultSoundRendererType = config.androidForceToUseAsrForDefaultPlayback ? + CriAtomEx.SoundRendererType.Asr : CriAtomEx.SoundRendererType.Default; +#endif + CriAtomPlugin.SetConfigAdditionalParameters_ANDROID( + config.androidEnableSonicSync, + config.androidLowLatencyStandardVoicePoolConfig.memoryVoices, + config.androidLowLatencyStandardVoicePoolConfig.streamingVoices, + config.androidBufferingTime, + config.androidStartBufferingTime, + config.androidUsesAndroidFastMixer, + config.androidUsesAAudio); + } + /* @cond excludele */ + /* 要修正:static関数化したためinitializesMana、manaConfigが参照できない。暫定的に第三引数は0にしておく。*/ + CriAtomPlugin.SetConfigAdditionalParameters_VITA( + config.vitaAtrac9VoicePoolConfig.memoryVoices, + config.vitaAtrac9VoicePoolConfig.streamingVoices, + config.vitaManaVoicePoolConfig.numberOfManaDecoders); + { + /* VR Mode が有効なときも useAudio3D を True にする */ + config.ps4Audio3dConfig.useAudio3D |= config.vrMode; + CriAtomPlugin.SetConfigAdditionalParameters_PS4( + config.ps4Atrac9VoicePoolConfig.memoryVoices, + config.ps4Atrac9VoicePoolConfig.streamingVoices, + config.ps4Audio3dConfig.useAudio3D, + config.ps4Audio3dConfig.voicePoolConfig.memoryVoices, + config.ps4Audio3dConfig.voicePoolConfig.streamingVoices); + } + CriAtomPlugin.SetConfigAdditionalParameters_SWITCH( + config.switchEnableSonicSync, + config.switchOpusVoicePoolConfig.memoryVoices, + config.switchOpusVoicePoolConfig.streamingVoices, + config.switchInitializeSocket); + CriAtomPlugin.SetConfigAdditionalParameters_WEBGL( + config.webglWebAudioVoicePoolConfig.voices); + /* @endcond */ + + CriAtomPlugin.InitializeLibrary(); + + if (config.useRandomSeedWithTime == true){ + /* 時刻を乱数種に設定 */ + CriAtomEx.SetRandomSeed((uint)System.DateTime.Now.Ticks); + } + + /* ACFファイル指定時は登録 */ + if (config.acfFileName.Length != 0) { + #if UNITY_WEBGL + Debug.LogError("In WebGL, ACF File path should be set to CriAtom Component."); + #else + string acfPath = config.acfFileName; + if (CriWare.Common.IsStreamingAssetsPath(acfPath)) { + acfPath = Path.Combine(CriWare.Common.streamingAssetsPath, acfPath); + } + + CriAtomEx.RegisterAcf(null, acfPath); + #endif + } + CriAtomServer.KeepPlayingSoundOnPause = config.keepPlayingSoundOnPause; + return true; + } else { + return false; + } + + } + + public static bool InitializeMana(CriManaConfig config) { + /* CRI Manaライブラリの初期化 */ + if (CriManaPlugin.IsLibraryInitialized() == false) { + CriManaPlugin.SetConfigParameters(config.graphicsMultiThreaded, config.numberOfDecoders, config.numberOfMaxEntries); + /* @cond excludele */ +#if UNITY_EDITOR_WIN || (!UNITY_EDITOR && UNITY_STANDALONE_WIN) + if (CriAtomPlugin.IsLibraryInitialized() == false) { + CriManaPlugin.SetConfigAdditonalParameters_PC(config.pcH264PlaybackConfig.useH264Playback); + } +#endif +#if !UNITY_EDITOR && UNITY_ANDROID + CriManaPlugin.SetConfigAdditonalParameters_ANDROID( + UnityEngine.SystemInfo.graphicsDeviceType == UnityEngine.Rendering.GraphicsDeviceType.Vulkan, + false); +#endif +#if !UNITY_EDITOR && UNITY_PSP2 + CriWareVITA.EnableManaH264Playback(config.vitaH264PlaybackConfig.useH264Playback); + CriWareVITA.SetManaH264DecoderMaxSize(config.vitaH264PlaybackConfig.maxWidth, + config.vitaH264PlaybackConfig.maxHeight); + CriWareVITA.EnableManaH264DecoderGetDisplayMemoryFromUnityTexture(config.vitaH264PlaybackConfig.getMemoryFromTexture); +#endif +#if !UNITY_EDITOR && UNITY_WEBGL + CriManaPlugin.SetConfigAdditonalParameters_WEBGL( + config.webglConfig.webworkerPath, + (uint)config.webglConfig.heapSize); +#endif + /* @endcond */ + + CriManaPlugin.InitializeLibrary(); + + // set shader global keyword to inform cri mana shaders to output to correct colorspace + if (QualitySettings.activeColorSpace == ColorSpace.Linear) { + Shader.EnableKeyword("CRI_LINEAR_COLORSPACE"); + } + return true; + } else { + return false; + } + } + + /* @cond excludele */ + /** + * \deprecated + * This is a deprecated API that will be removed. + * Please consider using CriWareDecypter.Initialize instead. + */ + [System.Obsolete("Use CriWareDecypter.Initialize")] + public static bool InitializeDecrypter(CriWareDecrypterConfig config) { + return CriWareDecrypter.Initialize(config); + } + /* @endcond */ + +} // end of class + +} //namespace CriWare +/** @} */ + +/* --- end of file --- */ diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriWareInitializer.cs.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriWareInitializer.cs.meta new file mode 100644 index 0000000..5c7f008 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/CriWareInitializer.cs.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 5e49f339aff054453b2d8287aec75bf2 +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: -12 + icon: {instanceID: 0} diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/DebugApi.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/DebugApi.meta new file mode 100644 index 0000000..d241493 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/DebugApi.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: d3e70ccae37b643419a2899d1c62bbce +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/DebugApi/CriAtomDebug.cs b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/DebugApi/CriAtomDebug.cs new file mode 100644 index 0000000..089e3f7 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/DebugApi/CriAtomDebug.cs @@ -0,0 +1,908 @@ +/**************************************************************************** + * + * Copyright (c) 2016 CRI Middleware Co., Ltd. + * + ****************************************************************************/ +using System; +using System.Runtime.InteropServices; + + +/** + * \addtogroup CRIATOM_NATIVE_WRAPPER + * @{ + */ + +namespace CriWare { + +/** + * A class that contains the APIs for debugging the CriAtomEx application. + */ +public static class CriAtomExDebug +{ + /** + * Status of various resources inside CriAtomEx + */ + [StructLayout (LayoutKind.Sequential, CharSet = CharSet.Ansi)] + public struct ResourcesInfo + { + /** Virtual Voice usage status */ + public CriAtomEx.ResourceUsage virtualVoiceUsage; + + /** Sequence usage status */ + public CriAtomEx.ResourceUsage sequenceUsage; + + /** Sequence track usage status */ + public CriAtomEx.ResourceUsage sequenceTrackUsage; + + /** Sequence track item usage status */ + public CriAtomEx.ResourceUsage sequenceTrackItemUsage; + } + + /** + * Gets the status of various resources inside CriAtomEx + * Status of various resources inside CriAtomEx + * + * Gets the status of various resources inside CriAtomEx.
+ *
+ */ + public static void GetResourcesInfo (out ResourcesInfo resourcesInfo) + { + criAtomExDebug_GetResourcesInfo (out resourcesInfo); + } + + #region DLL Import + #if !CRIWARE_ENABLE_HEADLESS_MODE + [DllImport (CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern void criAtomExDebug_GetResourcesInfo (out ResourcesInfo resourcesInfo); + #else + private static void criAtomExDebug_GetResourcesInfo (out ResourcesInfo resourcesInfo) { resourcesInfo = new ResourcesInfo(); } + #endif + #endregion +} + + +/** + * A class that contains the APIs for debugging the CriAtomExAcf application. + */ +public static class CriAtomExAcfDebug +{ + /** + * Category information + */ + public struct CategoryInfo + { + /** Group number */ + public uint groupNo; + + /** Category ID */ + public uint id; + + /** Category name */ + public string name; + + /** Cue limit count */ + public uint numCueLimits; + + /** Volume */ + public float volume; + } + + /** + * DSP bus setting information + */ + public struct DspBusInfo + { + /** Name */ + public string name; + + /** Volume */ + public float volume; + + /** Pan3D volume */ + public float pan3dVolume; + + /** Pan3D Angle */ + public float pan3dAngle; + + /** Pan3D interior distance */ + public float pan3dDistance; + + /** Pan3D spread */ + public float pan3dSpread; + + [MarshalAs (UnmanagedType.ByValArray, SizeConst = 8)] + /** DSP FX index array */ + public ushort[] fxIndexes; + + [MarshalAs (UnmanagedType.ByValArray, SizeConst = 64)] + /** DSP bus link index array */ + public ushort[] busLinkIndexes; + + /** DSP bus number in setting */ + public ushort busNo; + + /** The number of DSP FXs */ + public byte numFxes; + + /** Number of DSP bus links */ + public byte numBusLinks; + } + + /** + * AISAC control information + */ + public struct AisacControlInfo + { + /** Name */ + public string name; + + /** ID */ + public uint id; + } + + /** + * AISAC type + */ + public enum AisacType + { + /** Normal type */ + Normal, + + /** Auto modulation type */ + AutoModulation, + } + + /** + * Global AISAC information + */ + public struct GlobalAisacInfo + { + /** Global AISAC name */ + public string name; + + /** Data index */ + public ushort index; + + /** Number of graphs */ + public ushort numGraphs; + + /** AISAC type */ + public AisacType type; + + /** Random range */ + public float randomRange; + + /** Control ID */ + public ushort controlId; + } + + /** + * Selector information + */ + public struct SelectorInfo + { + /** Selector name */ + public string name; + + /** Selector index */ + public ushort index; + + /** The number of Selector Labels */ + public ushort numLabels; + + /** Global reference label index */ + public ushort globalLabelIndex; + } + + /** + * Selector Label information + */ + public struct SelectorLabelInfo + { + /** Selector name */ + public string selectorName; + + /** Selector Label name */ + public string labelName; + } + + /** + * Gets the number of Categories + * The number of Categories + * + * Gets the number of Categories contained in the registered ACF. + * + */ + public static int GetNumCategories () + { + return criAtomExAcf_GetNumCategories (); + } + + /** + * Gets the Category information (index specified) + * Category index + * Category information + * Whether the information could be obtained + * + * Gets information relative to a category by specifying its index.
+ * If the category at the specified index does not exist, false is returned.
+ *
+ */ + public static bool GetCategoryInfoByIndex (ushort index, out CategoryInfo categoryInfo) + { + CategoryInfoForMarshaling x; + bool result = criAtomExAcf_GetCategoryInfo (index, out x) != 0; + x.Convert (out categoryInfo); + return result; + } + + /** + * Gets the Category information (name specified) + * Category name + * Category information + * Whether the information could be obtained + * + * Gets information relative to a category by specifying its index.
+ * If the category at the specified index does not exist, false is returned.
+ *
+ */ + public static bool GetCategoryInfoByName (string name, out CategoryInfo categoryInfo) + { + CategoryInfoForMarshaling x; + bool result = criAtomExAcf_GetCategoryInfoByName (name, out x) != 0; + x.Convert (out categoryInfo); + return result; + } + + /** + * Gets the Category information (ID specified) + * Category ID + * Category information + * Whether the information could be obtained + * + * Gets information relative to a category by specifying its index.
+ * If the category at the specified index does not exist, false is returned.
+ *
+ */ + public static bool GetCategoryInfoById (uint id, out CategoryInfo categoryInfo) + { + CategoryInfoForMarshaling x; + bool result = criAtomExAcf_GetCategoryInfoById (id, out x) != 0; + x.Convert (out categoryInfo); + return result; + } + + /** + * Gets the number of DSP buses + * Number of DSP buses + * + * Gets the number of buses contained in the registered ACF. + * + */ + public static int GetNumBuses() + { + return criAtomExAcf_GetNumBuses(); + } + + /** + * Gets the DSP bus + * Bus index + * Bus information + * Whether the bus information could be acquired + * + * Gets information relative to a DSP Bus by specifying its index.
+ * If the DSP bus with the specified index does not exist, false is returned.
+ *
+ */ + public static bool GetDspBusInformation (ushort index, out DspBusInfo dspBusInfo) + { + DspBusInfoForMarshaling x; + bool result = criAtomExAcf_GetDspBusInformation (index, out x) != 0; + x.Convert (out dspBusInfo); + return result; + } + + /** + * Gets the number of AISAC controls + * The number of AISAC controls + * + * Gets the number of AISAC controls contained in the registered ACF.
+ * Returns -1 if no ACF file is registered.
+ *
+ */ + public static int GetNumAisacControls () + { + return criAtomExAcf_GetNumAisacControls (); + } + + /** + * Gets the AISAC control information + * AISAC control index + * AISAC control information + * Whether the information could be obtained + * + * Obtains the AISAC control information from the AISAC control index.
+ * Returns false if there is no AISAC control at the specified index.
+ *
+ */ + public static bool GetAisacControlInfo (ushort index, out AisacControlInfo info) + { + AisacControlInfoForMarshaling x; + bool result = criAtomExAcf_GetAisacControlInfo (index, out x) != 0; + x.Convert (out info); + return result; + } + + /** + * Getting the AISAC control ID (specifying the AISAC control name) + * AISAC control name + * AISAC control ID + * + * Gets the AISAC control ID from the AISAC control name.
+ * Returns CriAtomEx.InvalidAisacControlId + * if ACF is not registered or the AISAC control with the specified AISAC control name does not exist.
+ *
+ */ + public static uint GetAisacControlIdByName (string name) + { + return criAtomExAcf_GetAisacControlIdByName (name); + } + + /** + * Gets the AISAC control name (specifying the AISAC control ID) + * AISAC control ID + * AISAC control ID + * + * Gets the AISAC control name from the AISAC control ID.
+ * Returns null if ACF is not registered or the AISAC control with the specified AISAC control ID does not exist.
+ *
+ */ + public static string GetAisacControlNameById (uint id) + { + IntPtr namePtr = criAtomExAcf_GetAisacControlNameById (id); + return CriAtomDebugDetail.Utility.PtrToStringAutoOrNull (namePtr); + } + + /** + * Gets the number of global AISACs + * The number of global AISACs + * + * Gets the number of global AISAC contained in the registered ACF.
+ * Returns -1 if no ACF file is registered.
+ *
+ */ + public static int GetNumGlobalAisacs () + { + return criAtomExAcf_GetNumGlobalAisacs (); + } + + /** + * Gets the global AISAC information + * Global AISAC index + * Global AISAC information + * Whether the information could be obtained + * + * Gets information relative to a global AISAC by specifying its index.
+ * If the global AISAC with the specified index does not exist, false is returned.
+ *
+ */ + public static bool GetGlobalAisacInfo (ushort index, out GlobalAisacInfo info) + { + GlobalAisacInfoForMarshaling x; + bool result = criAtomExAcf_GetGlobalAisacInfo (index, out x) != 0; + x.Convert (out info); + return result; + } + + /** + * Gets the global AISAC information + * Global AISAC name + * Global AISAC information + * Whether the information could be obtained + * + * Gets information relative to a global AISAC by specifying its name.
+ * If the global AISAC with the specified name does not exist, false is returned.
+ *
+ */ + public static bool GetGlobalAisacInfoByName(string name, out GlobalAisacInfo info) + { + GlobalAisacInfoForMarshaling x; + bool result = criAtomExAcf_GetGlobalAisacInfoByName (name, out x) != 0; + x.Convert(out info); + return result; + } + + /** + * Gets the number of selectors + * The number of selectors + * + * Gets the number of selectors contained in the registered ACF.
+ * Returns -1 if no ACF file is registered.
+ *
+ */ + public static int GetNumSelectors() + { + return criAtomExAcf_GetNumSelectors(); + } + + /** + * Gets the selector information + * Selector index + * Selector information + * Whether the information could be obtained + * + * Gets information relative to a selector by specifying its index.
+ * If no selector exists at the specified index, false is returned.
+ *
+ */ + public static bool GetSelectorInfoByIndex(ushort index, out SelectorInfo info) + { + SelectorInfoForMarshaling x; + bool result = criAtomExAcf_GetSelectorInfoByIndex(index, out x) != 0; + x.Convert(out info); + return result; + } + + /** + * Gets the selector information + * Selector name + * Selector information + * Whether the information could be obtained + * + * Gets information relative to a selector by specifying its name.
+ * If no selector with the specified name exists, false is returned.
+ *
+ */ + public static bool GetSelectorInfoByName(string name, out SelectorInfo info) + { + SelectorInfoForMarshaling x; + bool result = criAtomExAcf_GetSelectorInfoByName(name, out x) != 0; + x.Convert(out info); + return result; + } + + /** + * Gets the Selector Label information + * Selector information + * Label index + * Selector Label information + * Whether the information could be obtained + * + * Gets information relative to a selector label by specifying its index.
+ * If no selector label with the specified index exists, false will be returned.
+ *
+ */ + public static bool GetSelectorLabelInfo(ref SelectorInfo selectorInfo, ushort index, out SelectorLabelInfo labelInfo) + { + var selectorInfoInput = new SelectorInfoForMarshaling(); + selectorInfoInput.index = selectorInfo.index; + selectorInfoInput.numLabels = selectorInfo.numLabels; + SelectorLabelInfoForMarshaling x; + bool result = criAtomExAcf_GetSelectorLabelInfo(ref selectorInfoInput, index, out x) != 0; + x.Convert(out labelInfo); + return result; + } + + #region Private + + [StructLayout (LayoutKind.Sequential, CharSet = CharSet.Ansi)] + private struct CategoryInfoForMarshaling + { + public uint groupNo; + public uint id; + public IntPtr namePtr; + public uint numCueLimits; + public float volume; + + public void Convert (out CategoryInfo x) + { + x.groupNo = groupNo; + x.id = id; + x.name = CriAtomDebugDetail.Utility.PtrToStringAutoOrNull (namePtr); + x.numCueLimits = numCueLimits; + x.volume = volume; + } + }; + + [StructLayout (LayoutKind.Sequential, CharSet = CharSet.Ansi)] + private struct DspBusInfoForMarshaling + { + public IntPtr namePtr; + public float volume; + public float pan3dVolume; + public float pan3dAngle; + public float pan3dDistance; + public float pan3dSpread; + [MarshalAs (UnmanagedType.ByValArray, SizeConst = 8)] + public ushort[] fxIndexes; + [MarshalAs (UnmanagedType.ByValArray, SizeConst = 64)] + public ushort[] busLinkIndexes; + public ushort busNo; + public byte numFxes; + public byte numBusLinks; + + public void Convert (out DspBusInfo x) + { + x.name = CriAtomDebugDetail.Utility.PtrToStringAutoOrNull (namePtr); + x.volume = volume; + x.pan3dVolume = pan3dVolume; + x.pan3dAngle = pan3dAngle; + x.pan3dDistance = pan3dDistance; + x.pan3dSpread = pan3dSpread; + x.fxIndexes = fxIndexes; + x.busLinkIndexes = busLinkIndexes; + x.busNo = busNo; + x.numFxes = numFxes; + x.numBusLinks = numBusLinks; + } + }; + + [StructLayout (LayoutKind.Sequential, CharSet = CharSet.Ansi)] + private struct AisacControlInfoForMarshaling { + public IntPtr namePtr; + public uint id; + + public void Convert (out AisacControlInfo x) + { + x.name = CriAtomDebugDetail.Utility.PtrToStringAutoOrNull (namePtr); + x.id = id; + } + } + + [StructLayout (LayoutKind.Sequential, CharSet = CharSet.Ansi)] + private struct GlobalAisacInfoForMarshaling { + public IntPtr namePtr; + public ushort index; + public ushort numGraphs; + public uint type; + public float randomRange; + public ushort controlId; + public ushort dummy; + + public void Convert(out GlobalAisacInfo x) + { + x.name = CriAtomDebugDetail.Utility.PtrToStringAutoOrNull(namePtr); + x.index = index; + x.numGraphs = numGraphs; + x.type = (AisacType)type; + x.randomRange = randomRange; + x.controlId = controlId; + } + }; + + [StructLayout (LayoutKind.Sequential, CharSet = CharSet.Ansi)] + private struct SelectorInfoForMarshaling { + public IntPtr namePtr; + public ushort index; + public ushort numLabels; + public ushort globalLabelIndex; + + public void Convert(out SelectorInfo x) + { + x.name = CriAtomDebugDetail.Utility.PtrToStringAutoOrNull(namePtr); + x.index = index; + x.numLabels = numLabels; + x.globalLabelIndex = globalLabelIndex; + } + }; + + [StructLayout (LayoutKind.Sequential, CharSet = CharSet.Ansi)] + private struct SelectorLabelInfoForMarshaling { + public IntPtr selectorNamePtr; + public IntPtr labelNamePtr; + + public void Convert(out SelectorLabelInfo x) + { + x.selectorName = CriAtomDebugDetail.Utility.PtrToStringAutoOrNull(selectorNamePtr); + x.labelName = CriAtomDebugDetail.Utility.PtrToStringAutoOrNull(labelNamePtr); + } + }; + + #endregion + + #region DLL Import + #if !CRIWARE_ENABLE_HEADLESS_MODE + [DllImport (CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criAtomExAcf_GetNumCategories (); + + [DllImport (CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criAtomExAcf_GetCategoryInfo (ushort index, out CategoryInfoForMarshaling categoryInfo); + + [DllImport (CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criAtomExAcf_GetCategoryInfoByName (string name, out CategoryInfoForMarshaling categoryInfo); + + [DllImport (CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criAtomExAcf_GetCategoryInfoById (uint id, out CategoryInfoForMarshaling categoryInfo); + + [DllImport (CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criAtomExAcf_GetNumBuses(); + + [DllImport (CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criAtomExAcf_GetDspBusInformation (ushort index, out DspBusInfoForMarshaling dspBusInfo); + + [DllImport (CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criAtomExAcf_GetNumAisacControls (); + + [DllImport (CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criAtomExAcf_GetAisacControlInfo (ushort index, out AisacControlInfoForMarshaling info); + + [DllImport (CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern uint criAtomExAcf_GetAisacControlIdByName (string name); + + [DllImport (CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern IntPtr criAtomExAcf_GetAisacControlNameById (uint id); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criAtomExAcf_GetNumGlobalAisacs (); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criAtomExAcf_GetGlobalAisacInfo (ushort index, out GlobalAisacInfoForMarshaling info); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criAtomExAcf_GetGlobalAisacInfoByName (string name, out GlobalAisacInfoForMarshaling info); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criAtomExAcf_GetNumSelectors(); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criAtomExAcf_GetSelectorInfoByIndex(ushort index, out SelectorInfoForMarshaling info); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criAtomExAcf_GetSelectorInfoByName(string name, out SelectorInfoForMarshaling info); + + [DllImport(CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criAtomExAcf_GetSelectorLabelInfo(ref SelectorInfoForMarshaling info, ushort labelIndex, out SelectorLabelInfoForMarshaling label_info); + #else + private static int criAtomExAcf_GetNumCategories () { return 0; } + private static int criAtomExAcf_GetCategoryInfo (ushort index, out CategoryInfoForMarshaling categoryInfo) + { categoryInfo = new CategoryInfoForMarshaling(); return -1; } + private static int criAtomExAcf_GetCategoryInfoByName (string name, out CategoryInfoForMarshaling categoryInfo) + { categoryInfo = new CategoryInfoForMarshaling(); return -1; } + private static int criAtomExAcf_GetCategoryInfoById (uint id, out CategoryInfoForMarshaling categoryInfo) + { categoryInfo = new CategoryInfoForMarshaling(); return -1; } + private static int criAtomExAcf_GetNumBuses() { return 0; } + private static int criAtomExAcf_GetDspBusInformation (ushort index, out DspBusInfoForMarshaling dspBusInfo) + { dspBusInfo = new DspBusInfoForMarshaling(); return -1; } + private static int criAtomExAcf_GetNumAisacControls () { return 0; } + private static int criAtomExAcf_GetAisacControlInfo (ushort index, out AisacControlInfoForMarshaling info) + { info = new AisacControlInfoForMarshaling(); return -1; } + private static uint criAtomExAcf_GetAisacControlIdByName (string name) { return 0u; } + private static IntPtr criAtomExAcf_GetAisacControlNameById (uint id) { return IntPtr.Zero; } + private static int criAtomExAcf_GetNumGlobalAisacs () { return 0; } + private static int criAtomExAcf_GetGlobalAisacInfo (ushort index, out GlobalAisacInfoForMarshaling info) + { info = new GlobalAisacInfoForMarshaling(); return -1; } + private static int criAtomExAcf_GetGlobalAisacInfoByName (string name, out GlobalAisacInfoForMarshaling info) + { info = new GlobalAisacInfoForMarshaling(); return -1; } + private static int criAtomExAcf_GetNumSelectors() { return 0; } + private static int criAtomExAcf_GetSelectorInfoByIndex(ushort index, out SelectorInfoForMarshaling info) + { info = new SelectorInfoForMarshaling(); return -1; } + private static int criAtomExAcf_GetSelectorInfoByName(string name, out SelectorInfoForMarshaling info) + { info = new SelectorInfoForMarshaling(); return -1; } + private static int criAtomExAcf_GetSelectorLabelInfo(ref SelectorInfoForMarshaling info, ushort labelIndex, out SelectorLabelInfoForMarshaling label_info) + { label_info = new SelectorLabelInfoForMarshaling(); return -1; } + #endif + #endregion +} + + +/** + * A class that contains the APIs for debugging the CriAtomExAcb application. + */ +public static class CriAtomExAcbDebug +{ + /** + * ACB information + * + * Various information of the ACB data. + * + */ + public struct AcbInfo + { + /** Name */ + public string name; + + /** Size */ + public uint size; + + /** ACB version */ + public uint version; + + /** Character code */ + public CriAtomEx.CharacterEncoding characterEncoding; + + /** Cue Sheet volume */ + public float volume; + + /** Number of Cues */ + public int numCues; + }; + + /** + * Obtains the ACB information + * ACB + * ACB information + * Whether the information could be obtained + * + * Gets various information of the ACB data. + * + */ + public static bool GetAcbInfo (CriAtomExAcb acb, out AcbInfo acbInfo) + { + AcbInfoForMarshaling x; + bool result = criAtomExAcb_GetAcbInfo (acb.nativeHandle, out x) == 1; + x.Convert (out acbInfo); + return result; + } + + #region Private + + [StructLayout (LayoutKind.Sequential, CharSet = CharSet.Ansi)] + private struct AcbInfoForMarshaling + { + public IntPtr namePtr; + public uint size; + public uint version; + public CriAtomEx.CharacterEncoding characterEncoding; + public float volume; + public int numCues; + + public void Convert (out AcbInfo x) + { + x.name = CriAtomDebugDetail.Utility.PtrToStringAutoOrNull (namePtr); + x.size = size; + x.version = version; + x.characterEncoding = characterEncoding; + x.volume = volume; + x.numCues = numCues; + } + }; + + [DllImport (CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criAtomExAcb_GetAcbInfo (IntPtr acbHn, out AcbInfoForMarshaling acbInfo); + + #endregion +} + + +/** + * A class that contains the APIs for debugging the CriAtomExPlayback application. + */ +public static class CriAtomExPlaybackDebug +{ + /** + * Gets parameters + * CriAtomExPlayback + * Parameter ID + * Parameter value (output) + * Whether the parameter could be get successfully + * + * Gets the values of various parameters of CriAtomExPlayback.
+ * If the parameters could successfully be acquired, this function returns true.
+ * If the specified voice has already been deleted, this function returns false.
+ *
+ */ + public static bool GetParameter (CriAtomExPlayback playback, CriAtomEx.Parameter parameterId, out float value) + { + return criAtomExPlayback_GetParameterFloat32 (playback.id, (int)parameterId, out value) == 1; + } + + /** + * Gets parameters + * CriAtomExPlayback + * Parameter ID + * Parameter value (output) + * Whether the parameter could be get successfully + * + * Gets the values of various parameters of CriAtomExPlayback.
+ * If the parameters could successfully be acquired, this function returns true.
+ * If the specified voice has already been deleted, this function returns false.
+ *
+ */ + public static bool GetParameter (CriAtomExPlayback playback, CriAtomEx.Parameter parameterId, out uint value) + { + return criAtomExPlayback_GetParameterUint32 (playback.id, (int)parameterId, out value) == 1; + } + + /** + * Gets parameters + * CriAtomExPlayback + * Parameter ID + * Parameter value (output) + * Whether the parameter could be get successfully + * + * Gets the values of various parameters of CriAtomExPlayback.
+ * If the parameters could successfully be acquired, this function returns true.
+ * If the specified voice has already been deleted, this function returns false.
+ *
+ */ + public static bool GetParameter (CriAtomExPlayback playback, CriAtomEx.Parameter parameterId, out int value) + { + return criAtomExPlayback_GetParameterSint32 (playback.id, (int)parameterId, out value) == 1; + } + + /** + * Gets the AISAC control value (specifying the control ID) + * Playback + * Control ID + * Control value (0.0f to 1.0f), -1.0f when not set + * Whether the AISAC control value was obtained + * + * Returns the AISAC control value by specifying the control ID (for the audio played by CriWare.CriAtomExPlayer::Start).
+ * Returns true if the AISAC control value was successfully acquired (the value will be -1.0f if no value was set).
+ * If the specified voice has already been removed, this function returns false.
+ * This function can get the AISAC control value only during sound playback.
+ * Getting the AISAC control value fails after the playback ends or when the Voice is erased by the Voice control.
+ *
+ */ + public static bool GetAisacControl (CriAtomExPlayback playback, uint controlId, out float value) + { + return criAtomExPlayback_GetAisacControlById (playback.id, controlId, out value) == 1; + } + + /** + * Gets the AISAC control value (specifying the control name) + * Playback + * Control name + * Control value (0.0f to 1.0f), -1.0f when not set + * Whether the AISAC control value was obtained + * + * Returns the AISAC control value by specifying the control ID (for the audio played by CriWare.CriAtomExPlayer::Start).
+ * Returns true if the AISAC control value was successfully acquired (the value will be -1.0f if no value was set).
+ * If the specified voice has already been removed, this function returns false.
+ * This function can get the AISAC control value only during sound playback.
+ * Getting the AISAC control value fails after the playback ends or when the Voice is erased by the Voice control.
+ *
+ */ + public static bool GetAisacControl (CriAtomExPlayback playback, string controlName, out float value) + { + return criAtomExPlayback_GetAisacControlByName (playback.id, controlName, out value) == 1; + } + + #region DLL Import + #if !CRIWARE_ENABLE_HEADLESS_MODE + [DllImport (CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criAtomExPlayback_GetParameterFloat32 (uint id, int parameterId, out float value); + + [DllImport (CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criAtomExPlayback_GetParameterUint32 (uint id, int parameterId, out uint value); + + [DllImport (CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criAtomExPlayback_GetParameterSint32 (uint id, int parameterId, out int value); + + [DllImport (CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criAtomExPlayback_GetAisacControlById (uint id, uint controlId, out float value); + + [DllImport (CriWare.Common.pluginName, CallingConvention = CriWare.Common.pluginCallingConvention)] + private static extern int criAtomExPlayback_GetAisacControlByName (uint id, string controlName, out float value); + #else + private static int criAtomExPlayback_GetParameterFloat32 (uint id, int parameterId, out float value) { value = 0.0f; return 0; } + private static int criAtomExPlayback_GetParameterUint32 (uint id, int parameterId, out uint value) { value = 0u; return 0; } + private static int criAtomExPlayback_GetParameterSint32 (uint id, int parameterId, out int value) { value = 0;return 0; } + private static int criAtomExPlayback_GetAisacControlById (uint id, uint controlId, out float value) { value = 0.0f; return 0; } + private static int criAtomExPlayback_GetAisacControlByName (uint id, string controlName, out float value) { value = 0.0f; return 0; } + #endif + #endregion +} + + +namespace CriAtomDebugDetail +{ + public class Utility + { + public static string PtrToStringAutoOrNull(IntPtr stringPtr) + { +#if !UNITY_EDITOR && UNITY_WINRT + return (stringPtr == IntPtr.Zero) ? null : Marshal.PtrToStringUni(stringPtr); +#elif UNITY_EDITOR_WIN || (!UNITY_EDITOR && UNITY_STANDALONE_WIN) + return (stringPtr == IntPtr.Zero) ? null : Marshal.PtrToStringAnsi(stringPtr); +#else + return (stringPtr == IntPtr.Zero) ? null : Marshal.PtrToStringAuto(stringPtr); +#endif + } + } +} + +} //namespace CriWare +/** + * @} + */ diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/DebugApi/CriAtomDebug.cs.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/DebugApi/CriAtomDebug.cs.meta new file mode 100644 index 0000000..669ba76 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/DebugApi/CriAtomDebug.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: ef21010ae4a5b446c9b008a6a3d75e6a +timeCreated: 1480571321 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/Internal.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/Internal.meta new file mode 100644 index 0000000..61c675d --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/Internal.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 546d4a2444cb04142b671f4c9159b092 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/Internal/CriDisposableObjectManager.cs b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/Internal/CriDisposableObjectManager.cs new file mode 100644 index 0000000..6700430 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/Internal/CriDisposableObjectManager.cs @@ -0,0 +1,166 @@ +/**************************************************************************** + * + * Copyright (c) 2017 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +#if !(UNITY_WEBGL || UNITY_SWITCH || UNITY_STADIA || ENABLE_IL2CPP) +#define CRIWARE_DISPOSABLEOBJECTMANAGER_USE_WEAKREF +#endif + +using System; +using System.Collections.Generic; + +namespace CriWare { + +public abstract class CriDisposable : IDisposable +{ + public Guid guid; + + public CriDisposable() + { + guid = Guid.NewGuid(); + } + + public abstract void Dispose(); +} + +public static class CriDisposableObjectManager +{ + public enum ModuleType + { + Atom, + AtomMic, + Fs, + FsWeb, + Mana, + Lips, + Vip, + Rtc, + } + + public struct ObjectRef + { + public Guid guid; + public ModuleType type; + #if CRIWARE_DISPOSABLEOBJECTMANAGER_USE_WEAKREF + public WeakReference weakRef; + #else + /* WeakReference with trackResurrection is not supported currently. */ + public CriDisposable disposable; + #endif + + #if CRIWARE_DISPOSABLEOBJECTMANAGER_USE_WEAKREF + public ObjectRef(Guid _guid, WeakReference _weakRef, ModuleType _type) + { + guid = _guid; + type = _type; + weakRef = _weakRef; + } + #else + public ObjectRef(Guid _guid, CriDisposable _disposable, ModuleType _type) + { + guid = _guid; + type = _type; + disposable = _disposable; + } + #endif + } + + private static List refList = new List(); + + private static int SearchForDisposable(CriDisposable disposable){ + lock (refList) { + int listCount = CriDisposableObjectManager.refList.Count; + for (int i = listCount - 1; i >= 0; --i) { + if (CriDisposableObjectManager.refList[i].guid == disposable.guid) { + return i; + } + } + } + return -1; + } + + public static void Register(CriDisposable disposable, ModuleType type) + { + if (CriDisposableObjectManager.SearchForDisposable(disposable) >= 0) { + UnityEngine.Debug.LogWarning("[CRIWARE] Internal: Duplicated object GUID"); + return; + } + + #if CRIWARE_DISPOSABLEOBJECTMANAGER_USE_WEAKREF + /* Keep weak reference until object finalized */ + var weakRef = new WeakReference(disposable, true); + lock (refList) { + CriDisposableObjectManager.refList.Add(new ObjectRef(disposable.guid, weakRef, type)); + } + #else + /* Keep reference directly */ + lock (refList) { + CriDisposableObjectManager.refList.Add(new ObjectRef(disposable.guid, disposable, type)); + } + #endif + } + + public static bool Unregister(CriDisposable disposable) + { + lock (refList) { + int index = CriDisposableObjectManager.SearchForDisposable(disposable); + if (index >= 0) { + CriDisposableObjectManager.refList.RemoveAt(index); + return true; + } + } + return false; + } + + public static bool IsDisposed(CriDisposable disposable) + { + return (CriDisposableObjectManager.SearchForDisposable(disposable) < 0) ; + } + + public static void CallOnModuleFinalization(ModuleType type) + { + CriDisposableObjectManager.DisposeAll(type); + } + + private static int GetNextWithType(ModuleType type) + { + int listCount = CriDisposableObjectManager.refList.Count; + for (int i = listCount - 1; i >= 0; --i) { + if (CriDisposableObjectManager.refList[i].type == type) { + return i; + } + } + return -1; + } + + public static void DisposeAll(ModuleType type) + { + lock (refList) { + while (true) { + int index = GetNextWithType(type); + if (index < 0) { + break; + } + #if CRIWARE_DISPOSABLEOBJECTMANAGER_USE_WEAKREF + var target = (CriDisposable)CriDisposableObjectManager.refList[index].weakRef.Target; + #else + var target = CriDisposableObjectManager.refList[index].disposable; + #endif + if (target != null) { + target.Dispose(); + } else { + /* Unsafe fallback */ + UnityEngine.Debug.LogWarning("[CRIWARE] Internal: Object disposal(Type:" + + CriDisposableObjectManager.refList[index].type.ToString() + + ") not handled by CriDisposableObjectManager; " + + "memory leak may have occured."); + CriDisposableObjectManager.refList.RemoveAt(index); + } + } + } + } +} + +} //namespace CriWare \ No newline at end of file diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/Internal/CriDisposableObjectManager.cs.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/Internal/CriDisposableObjectManager.cs.meta new file mode 100644 index 0000000..a79923d --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/Internal/CriDisposableObjectManager.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: f3b47293583177f4bafc51ec6ca119f0 +timeCreated: 1503051740 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/Internal/CriMonoBehaviourManager.cs b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/Internal/CriMonoBehaviourManager.cs new file mode 100644 index 0000000..5153fdf --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/Internal/CriMonoBehaviourManager.cs @@ -0,0 +1,119 @@ +/**************************************************************************** + * + * Copyright (c) 2019 CRI Middleware Co., Ltd. + * + ****************************************************************************/ + +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace CriWare { + +public abstract class CriMonoBehaviour : MonoBehaviour +{ + public Guid guid { get; private set; } + + public CriMonoBehaviour() + { + guid = Guid.NewGuid(); + } + + protected virtual void OnEnable() + { + CriMonoBehaviourManager.instance.Register(this); + } + + protected virtual void OnDisable() + { + CriMonoBehaviourManager.UnRegister(this); + } + + public abstract void CriInternalUpdate(); + + public abstract void CriInternalLateUpdate(); +} + +public class CriMonoBehaviourManager : MonoBehaviour +{ + private static CriMonoBehaviourManager _instance = null; + private static List criMonoBehaviourList = new List(); + + public static CriMonoBehaviourManager instance + { + get { + CreateInstance(); + return _instance; + } + } + + public static void CreateInstance() + { + if (_instance == null) { + CriWare.Common.managerObject.AddComponent(); + } + } + + private static int GetIndex(CriMonoBehaviour criMonoBehaviour) + { + for (int i = 0; i < criMonoBehaviourList.Count; i++) { + if (criMonoBehaviourList[i].guid == criMonoBehaviour.guid) { + return i; + } + } + return -1; + } + + public bool Register(CriMonoBehaviour criMonoBehaviour) + { + lock (criMonoBehaviourList) { + if (GetIndex(criMonoBehaviour) >= 0) { + UnityEngine.Debug.LogWarning("[CRIWARE] Internal: Duplicated CriMonoBehaviour GUID"); + return false; + } + criMonoBehaviourList.Add(criMonoBehaviour); + } + return true; + } + + public static bool UnRegister(CriMonoBehaviour criMonoBehaviour) + { + lock (criMonoBehaviourList) { + int index = GetIndex(criMonoBehaviour); + if (index < 0) { + return false; + } + criMonoBehaviourList.RemoveAt(index); + } + return true; + } + + private void Awake() + { + if (_instance == null) { + _instance = this; + } else { + Destroy(this); + } + } + + private void Update() + { + lock (criMonoBehaviourList) { + for (int i = 0; i < criMonoBehaviourList.Count; i++) { + criMonoBehaviourList[i].CriInternalUpdate(); + } + } + } + + private void LateUpdate() + { + lock (criMonoBehaviourList) { + for (int i = 0; i < criMonoBehaviourList.Count; i++) { + criMonoBehaviourList[i].CriInternalLateUpdate(); + } + } + } +} + +} //namespace CriWare \ No newline at end of file diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/Internal/CriMonoBehaviourManager.cs.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/Internal/CriMonoBehaviourManager.cs.meta new file mode 100644 index 0000000..0bfa8c4 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/Internal/CriMonoBehaviourManager.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ea19340230f54b54688e1b1b30d60d45 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/link.xml b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/link.xml new file mode 100644 index 0000000..7218e2f --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/link.xml @@ -0,0 +1,17 @@ + + + + + \ + + + + + \ + + + + + + + \ No newline at end of file diff --git a/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/link.xml.meta b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/link.xml.meta new file mode 100644 index 0000000..0a010f8 --- /dev/null +++ b/Assets/Scripts/CRIMW/CriWare/Runtime/Scripts/link.xml.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: fecacde74fae5b445ac61cffd2cda08d +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: