PXR_Audio_Spatializer_AudioSource.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. // Copyright © 2015-2022 Pico Technology Co., Ltd. All Rights Reserved.
  2. using System;
  3. using System.Collections;
  4. using PXR_Audio.Spatializer;
  5. using UnityEditor;
  6. using UnityEngine;
  7. [RequireComponent(typeof(AudioSource))]
  8. public class PXR_Audio_Spatializer_AudioSource : MonoBehaviour
  9. {
  10. [SerializeField] [Range(0.0f, 24.0f)] private float sourceGainDB = 0.0f;
  11. private float sourceGainAmplitude = 1.0f;
  12. [SerializeField] [Range(-120.0f, 48.0f)] private float reflectionGainDB = 0.0f;
  13. private float reflectionGainAmplitude = 1.0f;
  14. [SerializeField] [Range(0.0f, 100000.0f)]
  15. private float sourceSize = 0.0f;
  16. [SerializeField] private bool enableDoppler = true;
  17. [SerializeField] public SourceAttenuationMode sourceAttenuationMode = SourceAttenuationMode.InverseSquare;
  18. [SerializeField] public float minAttenuationDistance = 1.0f;
  19. [SerializeField] public float maxAttenuationDistance = 100.0f;
  20. [SerializeField] [Range(0.0f, 1.0f)] private float directivityAlpha = 0.0f;
  21. [SerializeField] [Range(0.0f, 1000.0f)]
  22. private float directivityOrder = 1.0f;
  23. #if UNITY_EDITOR
  24. private Mesh directivityDisplayMesh;
  25. #endif
  26. private SourceConfig sourceConfig;
  27. private uint sourcePropertyMask = 0;
  28. private bool isActive;
  29. private bool isAudioDSPInProgress = false;
  30. public bool IsAudioDSPInProgress
  31. {
  32. get { return isAudioDSPInProgress; }
  33. }
  34. private PXR_Audio_Spatializer_Context context;
  35. private PXR_Audio_Spatializer_Context Context
  36. {
  37. get
  38. {
  39. if (context == null)
  40. context = PXR_Audio_Spatializer_Context.Instance;
  41. return context;
  42. }
  43. }
  44. private AudioSource nativeSource;
  45. private int sourceId = -1;
  46. private int currentContextUuid = -2;
  47. private float[] positionArray = new float[3] { 0.0f, 0.0f, 0.0f };
  48. private float playheadPosition = 0.0f;
  49. private bool wasPlaying = false;
  50. private void OnEnable()
  51. {
  52. if (Context != null && Context.Initialized)
  53. {
  54. if (Context.UUID == currentContextUuid)
  55. isActive = true;
  56. else
  57. RegisterInternal();
  58. }
  59. else
  60. {
  61. sourceId = -1;
  62. currentContextUuid = -2;
  63. }
  64. }
  65. /// <summary>
  66. /// Register this audio source in spatializer
  67. /// </summary>
  68. internal void RegisterInternal()
  69. {
  70. nativeSource = GetComponent<AudioSource>();
  71. positionArray[0] = transform.position.x;
  72. positionArray[1] = transform.position.y;
  73. positionArray[2] = -transform.position.z;
  74. sourceConfig = new SourceConfig(PXR_Audio.Spatializer.SourceMode.Spatialize);
  75. sourcePropertyMask = 0;
  76. sourceConfig.position.x = positionArray[0];
  77. sourceConfig.position.y = positionArray[1];
  78. sourceConfig.position.z = positionArray[2];
  79. sourceConfig.front.x = transform.forward.x;
  80. sourceConfig.front.y = transform.forward.y;
  81. sourceConfig.front.z = -transform.forward.z;
  82. sourceConfig.up.x = transform.up.x;
  83. sourceConfig.up.y = transform.up.y;
  84. sourceConfig.up.z = -transform.up.z;
  85. sourceConfig.enableDoppler = enableDoppler;
  86. sourceGainAmplitude = DB2Mag(sourceGainDB);
  87. sourceConfig.sourceGain = sourceGainAmplitude;
  88. reflectionGainAmplitude = DB2Mag(reflectionGainDB);
  89. sourceConfig.reflectionGain = reflectionGainAmplitude;
  90. sourceConfig.radius = sourceSize;
  91. sourceConfig.attenuationMode = sourceAttenuationMode;
  92. sourceConfig.minAttenuationDistance = minAttenuationDistance;
  93. sourceConfig.maxAttenuationDistance = maxAttenuationDistance;
  94. sourceConfig.directivityAlpha = directivityAlpha;
  95. sourceConfig.directivityOrder = directivityOrder;
  96. PXR_Audio.Spatializer.Result ret = Context.AddSourceWithConfig(
  97. ref sourceConfig,
  98. ref sourceId,
  99. true);
  100. if (ret != PXR_Audio.Spatializer.Result.Success)
  101. {
  102. Debug.LogError("Failed to add source.");
  103. return;
  104. }
  105. isActive = true;
  106. currentContextUuid = Context.UUID;
  107. Debug.Log("Source #" + sourceId + " is added.");
  108. }
  109. /// <summary>
  110. /// Resume playing status of this source
  111. /// </summary>
  112. public void Resume()
  113. {
  114. nativeSource.time = playheadPosition;
  115. if (wasPlaying)
  116. {
  117. nativeSource.Play();
  118. }
  119. }
  120. /// <summary>
  121. /// Setup source gain in dB
  122. /// </summary>
  123. /// <param name="gainDB">Gain in dB</param>
  124. public void SetGainDB(float gainDB)
  125. {
  126. // if (Mathf.Abs(gainDB - sourceGainDB) < 1e-7) return;
  127. sourceGainDB = gainDB;
  128. sourceConfig.sourceGain = sourceGainAmplitude = DB2Mag(gainDB);
  129. sourcePropertyMask |= (uint)SourceProperty.SourceGain;
  130. }
  131. /// <summary>
  132. /// Setup source gain in Amplitude
  133. /// </summary>
  134. /// <param name="gainAmplitude">Gain in Amplitude</param>
  135. public void SetGainAmplitude(float gainAmplitude)
  136. {
  137. sourceConfig.sourceGain = sourceGainAmplitude = gainAmplitude;
  138. sourceGainDB = Mag2DB(gainAmplitude);
  139. sourcePropertyMask |= (uint)SourceProperty.SourceGain;
  140. }
  141. /// <summary>
  142. /// Setup source reflection gain in dB
  143. /// </summary>
  144. /// <param name="gainDB">Gain in dB</param>
  145. public void SetReflectionGainDB(float gainDB)
  146. {
  147. reflectionGainDB = gainDB;
  148. sourceConfig.reflectionGain = reflectionGainAmplitude = DB2Mag(gainDB);
  149. sourcePropertyMask |= (uint)SourceProperty.ReflectionGain;
  150. }
  151. /// <summary>
  152. /// Setup source radius in meters
  153. /// </summary>
  154. /// <param name="radius">source radius in meter</param>
  155. public void SetSize(float radius)
  156. {
  157. sourceConfig.radius = sourceSize = radius;
  158. sourcePropertyMask |= (uint)SourceProperty.VolumetricRadius;
  159. }
  160. /// <summary>
  161. /// Turn on/off in-engine doppler effect
  162. /// </summary>
  163. /// <param name="on">Turn doppler effect on/off </param>
  164. public void SetDopplerStatus(bool on)
  165. {
  166. sourceConfig.enableDoppler = enableDoppler = on;
  167. sourcePropertyMask |= (uint)SourceProperty.DopplerOnOff;
  168. }
  169. /// <summary>
  170. /// Setup min attenuation range
  171. /// </summary>
  172. /// <param name="min"> Minimum attenuation range. Source loudness would stop increasing when source-listener
  173. /// distance is shorter than this </param>
  174. public void SetMinAttenuationRange(float min)
  175. {
  176. sourceConfig.minAttenuationDistance = minAttenuationDistance = min;
  177. sourcePropertyMask |= (uint)SourceProperty.RangeMin;
  178. }
  179. /// <summary>
  180. /// Setup max attenuation range
  181. /// </summary>
  182. /// <param name="max"> Maximum attenuation range. Source loudness would stop decreasing when source-listener
  183. /// distance is further than this </param>
  184. public void SetMaxAttenuationRange(float max)
  185. {
  186. sourceConfig.maxAttenuationDistance = maxAttenuationDistance = max;
  187. sourcePropertyMask |= (uint)SourceProperty.RangeMax;
  188. }
  189. /// <summary>
  190. /// Setup the radiation polar pattern of source, which describes the gain of initial sound wave radiated towards
  191. /// different directions. The relation between sound emission direction, alpha, and order can be described as
  192. /// follows: Let theta equals the angle between radiation direction and source front direction, the directivity
  193. /// gain g is:
  194. /// g = (|1 - alpha| + alpha * cos(theta)) ^ order;
  195. /// </summary>
  196. /// <param name="alpha"> Define the shape of the directivity pattern.
  197. /// <param name="order"> Indicates how sharp the source polar pattern is.
  198. public void SetDirectivity(float alpha, float order)
  199. {
  200. sourceConfig.directivityAlpha = directivityAlpha = alpha;
  201. sourceConfig.directivityOrder = directivityOrder = order;
  202. sourcePropertyMask |= (uint)SourceProperty.Directivity;
  203. }
  204. void Update()
  205. {
  206. if (isActive && sourceId >= 0 && context != null && context.Initialized)
  207. {
  208. if (transform.hasChanged)
  209. {
  210. sourceConfig.position.x = transform.position.x;
  211. sourceConfig.position.y = transform.position.y;
  212. sourceConfig.position.z = -transform.position.z;
  213. sourceConfig.front.x = transform.forward.x;
  214. sourceConfig.front.y = transform.forward.y;
  215. sourceConfig.front.z = -transform.forward.z;
  216. sourceConfig.up.x = transform.up.x;
  217. sourceConfig.up.y = transform.up.y;
  218. sourceConfig.up.z = -transform.up.z;
  219. sourcePropertyMask |= (uint)SourceProperty.Position | (uint)SourceProperty.Orientation;
  220. transform.hasChanged = false;
  221. }
  222. if (sourcePropertyMask != 0)
  223. {
  224. var ret = Context.SetSourceConfig(sourceId, ref sourceConfig, sourcePropertyMask);
  225. if (ret == Result.Success)
  226. sourcePropertyMask = 0;
  227. }
  228. if (nativeSource.isPlaying)
  229. playheadPosition = nativeSource.time;
  230. wasPlaying = nativeSource.isPlaying;
  231. }
  232. }
  233. private void OnDisable()
  234. {
  235. isActive = false;
  236. isAudioDSPInProgress = false;
  237. }
  238. private void OnDestroy()
  239. {
  240. DestroyInternal();
  241. }
  242. #if UNITY_EDITOR
  243. void OnValidate()
  244. {
  245. if (EditorApplication.isPlaying)
  246. {
  247. SetGainDB(sourceGainDB);
  248. SetReflectionGainDB(reflectionGainDB);
  249. SetSize(sourceSize);
  250. SetDopplerStatus(enableDoppler);
  251. SetDirectivity(directivityAlpha, directivityOrder);
  252. }
  253. }
  254. #endif
  255. private void DestroyInternal()
  256. {
  257. isActive = false;
  258. if (context != null && context.Initialized)
  259. {
  260. var ret = context.RemoveSource(sourceId);
  261. if (ret != PXR_Audio.Spatializer.Result.Success)
  262. {
  263. Debug.LogError("Failed to delete source #" + sourceId + ", error code is: " + ret);
  264. }
  265. else
  266. {
  267. Debug.Log("Source #" + sourceId + " is deleted.");
  268. }
  269. }
  270. isAudioDSPInProgress = false;
  271. sourceId = -1;
  272. }
  273. private void OnAudioFilterRead(float[] data, int channels)
  274. {
  275. if (!isActive || sourceId < 0 || context == null || !context.Initialized)
  276. {
  277. // Mute Original signal
  278. for (int i = 0; i < data.Length; ++i)
  279. data[i] = 0.0f;
  280. return;
  281. }
  282. isAudioDSPInProgress = true;
  283. int numFrames = data.Length / channels;
  284. float oneOverChannelsF = 1.0f / ((float)channels);
  285. // force to mono
  286. if (channels > 1)
  287. {
  288. for (int frame = 0; frame < numFrames; ++frame)
  289. {
  290. float sample = 0.0f;
  291. for (int channel = 0; channel < channels; ++channel)
  292. {
  293. sample += data[frame * channels + channel];
  294. }
  295. data[frame] = sample * oneOverChannelsF;
  296. }
  297. }
  298. Context.SubmitSourceBuffer(sourceId, data, (uint)numFrames);
  299. // Mute Original signal
  300. for (int i = 0; i < data.Length; ++i)
  301. data[i] = 0.0f;
  302. isAudioDSPInProgress = false;
  303. }
  304. private float DB2Mag(float db)
  305. {
  306. return Mathf.Pow(10.0f, db / 20.0f);
  307. }
  308. private float Mag2DB(float mag)
  309. {
  310. return 20 * Mathf.Log10(mag);
  311. }
  312. void OnDrawGizmos()
  313. {
  314. Color c;
  315. const float colorSolidAlpha = 0.1f;
  316. // VolumetricRadius (purple)
  317. c.r = 1.0f;
  318. c.g = 0.0f;
  319. c.b = 1.0f;
  320. c.a = 1.0f;
  321. Gizmos.color = c;
  322. Gizmos.DrawWireSphere(transform.position, sourceSize);
  323. c.a = colorSolidAlpha;
  324. Gizmos.color = c;
  325. Gizmos.DrawSphere(transform.position, sourceSize);
  326. // Attenuation distance (min && max)
  327. if (sourceAttenuationMode == SourceAttenuationMode.InverseSquare)
  328. {
  329. // min
  330. c.r = 1.0f;
  331. c.g = 0.35f;
  332. c.b = 0.0f;
  333. c.a = 1.0f;
  334. Gizmos.color = c;
  335. Gizmos.DrawWireSphere(transform.position, minAttenuationDistance);
  336. c.a = colorSolidAlpha;
  337. Gizmos.color = c;
  338. Gizmos.DrawSphere(transform.position, minAttenuationDistance);
  339. // max
  340. c.r = 0.0f;
  341. c.g = 1.0f;
  342. c.b = 1.0f;
  343. c.a = 1.0f;
  344. Gizmos.color = c;
  345. Gizmos.DrawWireSphere(transform.position, maxAttenuationDistance);
  346. c.a = colorSolidAlpha;
  347. Gizmos.color = c;
  348. Gizmos.DrawSphere(transform.position, maxAttenuationDistance);
  349. }
  350. }
  351. #if UNITY_EDITOR
  352. private void OnDrawGizmosSelected()
  353. {
  354. // Draw directivity mesh
  355. GeneratePolarPatternMesh(directivityDisplayMesh, directivityAlpha, directivityOrder);
  356. }
  357. private void GeneratePolarPatternMesh(Mesh mesh, float alpha, float order)
  358. {
  359. if (mesh == null)
  360. mesh = new Mesh();
  361. Vector2[] cardioidVertices2D = GeneratePolarPatternVertices2D(alpha, order, 90);
  362. int numVertices = cardioidVertices2D.Length * 2;
  363. Vector3[] vertices = new Vector3[numVertices];
  364. for (int i = 0; i < cardioidVertices2D.Length; ++i)
  365. {
  366. var vertex2D = cardioidVertices2D[i];
  367. vertices[i] = new Vector3(vertex2D.x, 0.0f, vertex2D.y);
  368. vertices[cardioidVertices2D.Length + i] = Quaternion.AngleAxis(45, Vector3.forward) *
  369. new Vector3(vertex2D.x, 0.0f, vertex2D.y);
  370. }
  371. int[] indices = new int[cardioidVertices2D.Length * 2 * 3];
  372. int idx = 0;
  373. for (idx = 0; idx < cardioidVertices2D.Length - 1; ++idx)
  374. {
  375. indices[idx * 6 + 0] = idx;
  376. indices[idx * 6 + 1] = idx + 1;
  377. indices[idx * 6 + 2] = idx + cardioidVertices2D.Length;
  378. indices[idx * 6 + 3] = idx + 1;
  379. indices[idx * 6 + 4] = idx + cardioidVertices2D.Length + 1;
  380. indices[idx * 6 + 5] = idx + cardioidVertices2D.Length;
  381. }
  382. // Construct a new mesh for the gizmo.
  383. mesh.vertices = vertices;
  384. mesh.triangles = indices;
  385. mesh.RecalculateNormals();
  386. // Draw the mesh.
  387. Vector3 scale = 2.0f * Mathf.Max(transform.lossyScale.x, transform.lossyScale.z) * Vector3.one;
  388. Color c;
  389. c.r = 0.2f;
  390. c.g = 0.5f;
  391. c.b = 0.7f;
  392. c.a = 0.5f;
  393. Gizmos.color = c;
  394. Gizmos.DrawMesh(mesh, transform.position, transform.rotation, scale);
  395. Gizmos.DrawMesh(mesh, transform.position, transform.rotation * Quaternion.AngleAxis(45, Vector3.forward),
  396. scale);
  397. Gizmos.DrawMesh(mesh, transform.position, transform.rotation * Quaternion.AngleAxis(90, Vector3.forward),
  398. scale);
  399. Gizmos.DrawMesh(mesh, transform.position, transform.rotation * Quaternion.AngleAxis(135, Vector3.forward),
  400. scale);
  401. Gizmos.DrawMesh(mesh, transform.position, transform.rotation * Quaternion.AngleAxis(180, Vector3.forward),
  402. scale);
  403. Gizmos.DrawMesh(mesh, transform.position, transform.rotation * Quaternion.AngleAxis(225, Vector3.forward),
  404. scale);
  405. Gizmos.DrawMesh(mesh, transform.position, transform.rotation * Quaternion.AngleAxis(270, Vector3.forward),
  406. scale);
  407. Gizmos.DrawMesh(mesh, transform.position, transform.rotation * Quaternion.AngleAxis(315, Vector3.forward),
  408. scale);
  409. }
  410. private Vector2[] GeneratePolarPatternVertices2D(float alpha, float order, int numVertices)
  411. {
  412. Vector2[] points = new Vector2[numVertices];
  413. float interval = Mathf.PI / (numVertices - 1);
  414. for (int i = 0; i < numVertices; ++i)
  415. {
  416. float theta = 0.0f;
  417. if (i != numVertices - 1)
  418. theta = i * interval;
  419. else
  420. theta = Mathf.PI;
  421. // Magnitude |r| for |theta| in radians.
  422. float r = Mathf.Pow(Mathf.Abs((1 - alpha) + alpha * Mathf.Cos(theta)), order);
  423. points[i] = new Vector2(r * Mathf.Sin(theta), r * Mathf.Cos(theta));
  424. }
  425. return points;
  426. }
  427. #endif
  428. }
粤ICP备19079148号