audio_stream_player_3d.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938
  1. /**************************************************************************/
  2. /* audio_stream_player_3d.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "audio_stream_player_3d.h"
  31. #include "core/config/project_settings.h"
  32. #include "scene/3d/area_3d.h"
  33. #include "scene/3d/audio_listener_3d.h"
  34. #include "scene/3d/camera_3d.h"
  35. #include "scene/main/viewport.h"
  36. #include "scene/scene_string_names.h"
  37. // Based on "A Novel Multichannel Panning Method for Standard and Arbitrary Loudspeaker Configurations" by Ramy Sadek and Chris Kyriakakis (2004)
  38. // Speaker-Placement Correction Amplitude Panning (SPCAP)
  39. class Spcap {
  40. private:
  41. struct Speaker {
  42. Vector3 direction;
  43. real_t effective_number_of_speakers = 0; // precalculated
  44. mutable real_t squared_gain = 0; // temporary
  45. };
  46. Vector<Speaker> speakers;
  47. public:
  48. Spcap(unsigned int speaker_count, const Vector3 *speaker_directions) {
  49. this->speakers.resize(speaker_count);
  50. Speaker *w = this->speakers.ptrw();
  51. for (unsigned int speaker_num = 0; speaker_num < speaker_count; speaker_num++) {
  52. w[speaker_num].direction = speaker_directions[speaker_num];
  53. w[speaker_num].squared_gain = 0.0;
  54. w[speaker_num].effective_number_of_speakers = 0.0;
  55. for (unsigned int other_speaker_num = 0; other_speaker_num < speaker_count; other_speaker_num++) {
  56. w[speaker_num].effective_number_of_speakers += 0.5 * (1.0 + w[speaker_num].direction.dot(w[other_speaker_num].direction));
  57. }
  58. }
  59. }
  60. unsigned int get_speaker_count() const {
  61. return (unsigned int)this->speakers.size();
  62. }
  63. Vector3 get_speaker_direction(unsigned int index) const {
  64. return this->speakers.ptr()[index].direction;
  65. }
  66. void calculate(const Vector3 &source_direction, real_t tightness, unsigned int volume_count, real_t *volumes) const {
  67. const Speaker *r = this->speakers.ptr();
  68. real_t sum_squared_gains = 0.0;
  69. for (unsigned int speaker_num = 0; speaker_num < (unsigned int)this->speakers.size(); speaker_num++) {
  70. real_t initial_gain = 0.5 * powf(1.0 + r[speaker_num].direction.dot(source_direction), tightness) / r[speaker_num].effective_number_of_speakers;
  71. r[speaker_num].squared_gain = initial_gain * initial_gain;
  72. sum_squared_gains += r[speaker_num].squared_gain;
  73. }
  74. for (unsigned int speaker_num = 0; speaker_num < MIN(volume_count, (unsigned int)this->speakers.size()); speaker_num++) {
  75. volumes[speaker_num] = sqrtf(r[speaker_num].squared_gain / sum_squared_gains);
  76. }
  77. }
  78. };
  79. //TODO: hardcoded main speaker directions for 2, 3.1, 5.1 and 7.1 setups - these are simplified and could also be made configurable
  80. static const Vector3 speaker_directions[7] = {
  81. Vector3(-1.0, 0.0, -1.0).normalized(), // front-left
  82. Vector3(1.0, 0.0, -1.0).normalized(), // front-right
  83. Vector3(0.0, 0.0, -1.0).normalized(), // center
  84. Vector3(-1.0, 0.0, 1.0).normalized(), // rear-left
  85. Vector3(1.0, 0.0, 1.0).normalized(), // rear-right
  86. Vector3(-1.0, 0.0, 0.0).normalized(), // side-left
  87. Vector3(1.0, 0.0, 0.0).normalized(), // side-right
  88. };
  89. void AudioStreamPlayer3D::_calc_output_vol(const Vector3 &source_dir, real_t tightness, Vector<AudioFrame> &output) {
  90. unsigned int speaker_count = 0; // only main speakers (no LFE)
  91. switch (AudioServer::get_singleton()->get_speaker_mode()) {
  92. case AudioServer::SPEAKER_MODE_STEREO:
  93. speaker_count = 2;
  94. break;
  95. case AudioServer::SPEAKER_SURROUND_31:
  96. speaker_count = 3;
  97. break;
  98. case AudioServer::SPEAKER_SURROUND_51:
  99. speaker_count = 5;
  100. break;
  101. case AudioServer::SPEAKER_SURROUND_71:
  102. speaker_count = 7;
  103. break;
  104. }
  105. Spcap spcap(speaker_count, speaker_directions); //TODO: should only be created/recreated once the speaker mode / speaker positions changes
  106. real_t volumes[7];
  107. spcap.calculate(source_dir, tightness, speaker_count, volumes);
  108. switch (AudioServer::get_singleton()->get_speaker_mode()) {
  109. case AudioServer::SPEAKER_SURROUND_71:
  110. output.write[3].l = volumes[5]; // side-left
  111. output.write[3].r = volumes[6]; // side-right
  112. [[fallthrough]];
  113. case AudioServer::SPEAKER_SURROUND_51:
  114. output.write[2].l = volumes[3]; // rear-left
  115. output.write[2].r = volumes[4]; // rear-right
  116. [[fallthrough]];
  117. case AudioServer::SPEAKER_SURROUND_31:
  118. output.write[1].r = 1.0; // LFE - always full power
  119. output.write[1].l = volumes[2]; // center
  120. [[fallthrough]];
  121. case AudioServer::SPEAKER_MODE_STEREO:
  122. output.write[0].r = volumes[1]; // front-right
  123. output.write[0].l = volumes[0]; // front-left
  124. break;
  125. }
  126. }
  127. void AudioStreamPlayer3D::_calc_reverb_vol(Area3D *area, Vector3 listener_area_pos, Vector<AudioFrame> direct_path_vol, Vector<AudioFrame> &reverb_vol) {
  128. reverb_vol.resize(4);
  129. reverb_vol.write[0] = AudioFrame(0, 0);
  130. reverb_vol.write[1] = AudioFrame(0, 0);
  131. reverb_vol.write[2] = AudioFrame(0, 0);
  132. reverb_vol.write[3] = AudioFrame(0, 0);
  133. float uniformity = area->get_reverb_uniformity();
  134. float area_send = area->get_reverb_amount();
  135. if (uniformity > 0.0) {
  136. float distance = listener_area_pos.length();
  137. float attenuation = Math::db_to_linear(_get_attenuation_db(distance));
  138. // Determine the fraction of sound that would come from each speaker if they were all driven uniformly.
  139. float center_val[3] = { 0.5f, 0.25f, 0.16666f };
  140. int channel_count = AudioServer::get_singleton()->get_channel_count();
  141. AudioFrame center_frame(center_val[channel_count - 1], center_val[channel_count - 1]);
  142. if (attenuation < 1.0) {
  143. //pan the uniform sound
  144. Vector3 rev_pos = listener_area_pos;
  145. rev_pos.y = 0;
  146. rev_pos.normalize();
  147. // Stereo pair.
  148. float c = rev_pos.x * 0.5 + 0.5;
  149. reverb_vol.write[0].l = 1.0 - c;
  150. reverb_vol.write[0].r = c;
  151. if (channel_count >= 3) {
  152. // Center pair + Side pair
  153. float xl = Vector3(-1, 0, -1).normalized().dot(rev_pos) * 0.5 + 0.5;
  154. float xr = Vector3(1, 0, -1).normalized().dot(rev_pos) * 0.5 + 0.5;
  155. reverb_vol.write[1].l = xl;
  156. reverb_vol.write[1].r = xr;
  157. reverb_vol.write[2].l = 1.0 - xr;
  158. reverb_vol.write[2].r = 1.0 - xl;
  159. }
  160. if (channel_count >= 4) {
  161. // Rear pair
  162. // FIXME: Not sure what math should be done here
  163. reverb_vol.write[3].l = 1.0 - c;
  164. reverb_vol.write[3].r = c;
  165. }
  166. for (int i = 0; i < channel_count; i++) {
  167. reverb_vol.write[i] = reverb_vol[i].lerp(center_frame, attenuation);
  168. }
  169. } else {
  170. for (int i = 0; i < channel_count; i++) {
  171. reverb_vol.write[i] = center_frame;
  172. }
  173. }
  174. for (int i = 0; i < channel_count; i++) {
  175. reverb_vol.write[i] = direct_path_vol[i].lerp(reverb_vol[i] * attenuation, uniformity);
  176. reverb_vol.write[i] *= area_send;
  177. }
  178. } else {
  179. for (int i = 0; i < 4; i++) {
  180. reverb_vol.write[i] = direct_path_vol[i] * area_send;
  181. }
  182. }
  183. }
  184. float AudioStreamPlayer3D::_get_attenuation_db(float p_distance) const {
  185. float att = 0;
  186. switch (attenuation_model) {
  187. case ATTENUATION_INVERSE_DISTANCE: {
  188. att = Math::linear_to_db(1.0 / ((p_distance / unit_size) + CMP_EPSILON));
  189. } break;
  190. case ATTENUATION_INVERSE_SQUARE_DISTANCE: {
  191. float d = (p_distance / unit_size);
  192. d *= d;
  193. att = Math::linear_to_db(1.0 / (d + CMP_EPSILON));
  194. } break;
  195. case ATTENUATION_LOGARITHMIC: {
  196. att = -20 * Math::log(p_distance / unit_size + CMP_EPSILON);
  197. } break;
  198. case ATTENUATION_DISABLED:
  199. break;
  200. default: {
  201. ERR_PRINT("Unknown attenuation type");
  202. break;
  203. }
  204. }
  205. att += volume_db;
  206. if (att > max_db) {
  207. att = max_db;
  208. }
  209. return att;
  210. }
  211. void AudioStreamPlayer3D::_notification(int p_what) {
  212. switch (p_what) {
  213. case NOTIFICATION_ENTER_TREE: {
  214. velocity_tracker->reset(get_global_transform().origin);
  215. AudioServer::get_singleton()->add_listener_changed_callback(_listener_changed_cb, this);
  216. if (autoplay && !Engine::get_singleton()->is_editor_hint()) {
  217. play();
  218. }
  219. set_stream_paused(!can_process());
  220. } break;
  221. case NOTIFICATION_EXIT_TREE: {
  222. set_stream_paused(true);
  223. AudioServer::get_singleton()->remove_listener_changed_callback(_listener_changed_cb, this);
  224. } break;
  225. case NOTIFICATION_PREDELETE: {
  226. stop();
  227. } break;
  228. case NOTIFICATION_PAUSED: {
  229. if (!can_process()) {
  230. // Node can't process so we start fading out to silence.
  231. set_stream_paused(true);
  232. }
  233. } break;
  234. case NOTIFICATION_UNPAUSED: {
  235. set_stream_paused(false);
  236. } break;
  237. case NOTIFICATION_TRANSFORM_CHANGED: {
  238. if (doppler_tracking != DOPPLER_TRACKING_DISABLED) {
  239. velocity_tracker->update_position(get_global_transform().origin);
  240. }
  241. } break;
  242. case NOTIFICATION_INTERNAL_PHYSICS_PROCESS: {
  243. // Update anything related to position first, if possible of course.
  244. Vector<AudioFrame> volume_vector;
  245. if (setplay.get() > 0 || (active.is_set() && last_mix_count != AudioServer::get_singleton()->get_mix_count()) || force_update_panning) {
  246. force_update_panning = false;
  247. volume_vector = _update_panning();
  248. }
  249. if (setplayback.is_valid() && setplay.get() >= 0) {
  250. active.set();
  251. HashMap<StringName, Vector<AudioFrame>> bus_map;
  252. bus_map[_get_actual_bus()] = volume_vector;
  253. AudioServer::get_singleton()->start_playback_stream(setplayback, bus_map, setplay.get(), actual_pitch_scale, linear_attenuation, attenuation_filter_cutoff_hz);
  254. setplayback.unref();
  255. setplay.set(-1);
  256. }
  257. if (!stream_playbacks.is_empty() && active.is_set()) {
  258. // Stop playing if no longer active.
  259. Vector<Ref<AudioStreamPlayback>> playbacks_to_remove;
  260. for (Ref<AudioStreamPlayback> &playback : stream_playbacks) {
  261. if (playback.is_valid() && !AudioServer::get_singleton()->is_playback_active(playback) && !AudioServer::get_singleton()->is_playback_paused(playback)) {
  262. playbacks_to_remove.push_back(playback);
  263. }
  264. }
  265. // Now go through and remove playbacks that have finished. Removing elements from a Vector in a range based for is asking for trouble.
  266. for (Ref<AudioStreamPlayback> &playback : playbacks_to_remove) {
  267. stream_playbacks.erase(playback);
  268. }
  269. if (!playbacks_to_remove.is_empty() && stream_playbacks.is_empty()) {
  270. // This node is no longer actively playing audio.
  271. active.clear();
  272. set_physics_process_internal(false);
  273. }
  274. if (!playbacks_to_remove.is_empty()) {
  275. emit_signal(SNAME("finished"));
  276. }
  277. }
  278. while (stream_playbacks.size() > max_polyphony) {
  279. AudioServer::get_singleton()->stop_playback_stream(stream_playbacks[0]);
  280. stream_playbacks.remove_at(0);
  281. }
  282. } break;
  283. }
  284. }
  285. // Interacts with PhysicsServer3D, so can only be called during _physics_process
  286. Area3D *AudioStreamPlayer3D::_get_overriding_area() {
  287. //check if any area is diverting sound into a bus
  288. Ref<World3D> world_3d = get_world_3d();
  289. ERR_FAIL_COND_V(world_3d.is_null(), nullptr);
  290. Vector3 global_pos = get_global_transform().origin;
  291. PhysicsDirectSpaceState3D *space_state = PhysicsServer3D::get_singleton()->space_get_direct_state(world_3d->get_space());
  292. PhysicsDirectSpaceState3D::ShapeResult sr[MAX_INTERSECT_AREAS];
  293. PhysicsDirectSpaceState3D::PointParameters point_params;
  294. point_params.position = global_pos;
  295. point_params.collision_mask = area_mask;
  296. point_params.collide_with_bodies = false;
  297. point_params.collide_with_areas = true;
  298. int areas = space_state->intersect_point(point_params, sr, MAX_INTERSECT_AREAS);
  299. for (int i = 0; i < areas; i++) {
  300. if (!sr[i].collider) {
  301. continue;
  302. }
  303. Area3D *tarea = Object::cast_to<Area3D>(sr[i].collider);
  304. if (!tarea) {
  305. continue;
  306. }
  307. if (!tarea->is_overriding_audio_bus() && !tarea->is_using_reverb_bus()) {
  308. continue;
  309. }
  310. return tarea;
  311. }
  312. return nullptr;
  313. }
  314. // Interacts with PhysicsServer3D, so can only be called during _physics_process
  315. StringName AudioStreamPlayer3D::_get_actual_bus() {
  316. Area3D *overriding_area = _get_overriding_area();
  317. if (overriding_area && overriding_area->is_overriding_audio_bus() && !overriding_area->is_using_reverb_bus()) {
  318. return overriding_area->get_audio_bus_name();
  319. }
  320. return bus;
  321. }
  322. // Interacts with PhysicsServer3D, so can only be called during _physics_process
  323. Vector<AudioFrame> AudioStreamPlayer3D::_update_panning() {
  324. Vector<AudioFrame> output_volume_vector;
  325. output_volume_vector.resize(4);
  326. for (AudioFrame &frame : output_volume_vector) {
  327. frame = AudioFrame(0, 0);
  328. }
  329. if (!active.is_set() || stream.is_null()) {
  330. return output_volume_vector;
  331. }
  332. Vector3 linear_velocity;
  333. //compute linear velocity for doppler
  334. if (doppler_tracking != DOPPLER_TRACKING_DISABLED) {
  335. linear_velocity = velocity_tracker->get_tracked_linear_velocity();
  336. }
  337. Vector3 global_pos = get_global_transform().origin;
  338. Ref<World3D> world_3d = get_world_3d();
  339. ERR_FAIL_COND_V(world_3d.is_null(), output_volume_vector);
  340. HashSet<Camera3D *> cameras = world_3d->get_cameras();
  341. cameras.insert(get_viewport()->get_camera_3d());
  342. PhysicsDirectSpaceState3D *space_state = PhysicsServer3D::get_singleton()->space_get_direct_state(world_3d->get_space());
  343. for (Camera3D *camera : cameras) {
  344. if (!camera) {
  345. continue;
  346. }
  347. Viewport *vp = camera->get_viewport();
  348. if (!vp) {
  349. continue;
  350. }
  351. if (!vp->is_audio_listener_3d()) {
  352. continue;
  353. }
  354. bool listener_is_camera = true;
  355. Node3D *listener_node = camera;
  356. AudioListener3D *listener = vp->get_audio_listener_3d();
  357. if (listener) {
  358. listener_node = listener;
  359. listener_is_camera = false;
  360. }
  361. Vector3 local_pos = listener_node->get_global_transform().orthonormalized().affine_inverse().xform(global_pos);
  362. float dist = local_pos.length();
  363. Vector3 area_sound_pos;
  364. Vector3 listener_area_pos;
  365. Area3D *area = _get_overriding_area();
  366. if (area && area->is_using_reverb_bus() && area->get_reverb_uniformity() > 0) {
  367. area_sound_pos = space_state->get_closest_point_to_object_volume(area->get_rid(), listener_node->get_global_transform().origin);
  368. listener_area_pos = listener_node->get_global_transform().affine_inverse().xform(area_sound_pos);
  369. }
  370. if (max_distance > 0) {
  371. float total_max = max_distance;
  372. if (area && area->is_using_reverb_bus() && area->get_reverb_uniformity() > 0) {
  373. total_max = MAX(total_max, listener_area_pos.length());
  374. }
  375. if (total_max > max_distance) {
  376. continue; //can't hear this sound in this listener
  377. }
  378. }
  379. float multiplier = Math::db_to_linear(_get_attenuation_db(dist));
  380. if (max_distance > 0) {
  381. multiplier *= MAX(0, 1.0 - (dist / max_distance));
  382. }
  383. float db_att = (1.0 - MIN(1.0, multiplier)) * attenuation_filter_db;
  384. if (emission_angle_enabled) {
  385. Vector3 listenertopos = global_pos - listener_node->get_global_transform().origin;
  386. float c = listenertopos.normalized().dot(get_global_transform().basis.get_column(2).normalized()); //it's z negative
  387. float angle = Math::rad_to_deg(Math::acos(c));
  388. if (angle > emission_angle) {
  389. db_att -= -emission_angle_filter_attenuation_db;
  390. }
  391. }
  392. linear_attenuation = Math::db_to_linear(db_att);
  393. for (Ref<AudioStreamPlayback> &playback : stream_playbacks) {
  394. AudioServer::get_singleton()->set_playback_highshelf_params(playback, linear_attenuation, attenuation_filter_cutoff_hz);
  395. }
  396. // Bake in a constant factor here to allow the project setting defaults for 2d and 3d to be normalized to 1.0.
  397. float tightness = cached_global_panning_strength * 2.0f;
  398. tightness *= panning_strength;
  399. _calc_output_vol(local_pos.normalized(), tightness, output_volume_vector);
  400. for (unsigned int k = 0; k < 4; k++) {
  401. output_volume_vector.write[k] = multiplier * output_volume_vector[k];
  402. }
  403. HashMap<StringName, Vector<AudioFrame>> bus_volumes;
  404. if (area) {
  405. if (area->is_overriding_audio_bus()) {
  406. //override audio bus
  407. bus_volumes[area->get_audio_bus_name()] = output_volume_vector;
  408. }
  409. if (area->is_using_reverb_bus()) {
  410. StringName reverb_bus_name = area->get_reverb_bus_name();
  411. Vector<AudioFrame> reverb_vol;
  412. _calc_reverb_vol(area, listener_area_pos, output_volume_vector, reverb_vol);
  413. bus_volumes[reverb_bus_name] = reverb_vol;
  414. }
  415. } else {
  416. bus_volumes[bus] = output_volume_vector;
  417. }
  418. for (Ref<AudioStreamPlayback> &playback : stream_playbacks) {
  419. AudioServer::get_singleton()->set_playback_bus_volumes_linear(playback, bus_volumes);
  420. }
  421. if (doppler_tracking != DOPPLER_TRACKING_DISABLED) {
  422. Vector3 listener_velocity;
  423. if (listener_is_camera) {
  424. listener_velocity = camera->get_doppler_tracked_velocity();
  425. }
  426. Vector3 local_velocity = listener_node->get_global_transform().orthonormalized().basis.xform_inv(linear_velocity - listener_velocity);
  427. if (local_velocity != Vector3()) {
  428. float approaching = local_pos.normalized().dot(local_velocity.normalized());
  429. float velocity = local_velocity.length();
  430. float speed_of_sound = 343.0;
  431. float doppler_pitch_scale = pitch_scale * speed_of_sound / (speed_of_sound + velocity * approaching);
  432. doppler_pitch_scale = CLAMP(doppler_pitch_scale, (1 / 8.0), 8.0); //avoid crazy stuff
  433. actual_pitch_scale = doppler_pitch_scale;
  434. } else {
  435. actual_pitch_scale = pitch_scale;
  436. }
  437. } else {
  438. actual_pitch_scale = pitch_scale;
  439. }
  440. for (Ref<AudioStreamPlayback> &playback : stream_playbacks) {
  441. AudioServer::get_singleton()->set_playback_pitch_scale(playback, actual_pitch_scale);
  442. }
  443. }
  444. return output_volume_vector;
  445. }
  446. void AudioStreamPlayer3D::set_stream(Ref<AudioStream> p_stream) {
  447. stop();
  448. stream = p_stream;
  449. }
  450. Ref<AudioStream> AudioStreamPlayer3D::get_stream() const {
  451. return stream;
  452. }
  453. void AudioStreamPlayer3D::set_volume_db(float p_volume) {
  454. volume_db = p_volume;
  455. }
  456. float AudioStreamPlayer3D::get_volume_db() const {
  457. return volume_db;
  458. }
  459. void AudioStreamPlayer3D::set_unit_size(float p_volume) {
  460. unit_size = p_volume;
  461. update_gizmos();
  462. }
  463. float AudioStreamPlayer3D::get_unit_size() const {
  464. return unit_size;
  465. }
  466. void AudioStreamPlayer3D::set_max_db(float p_boost) {
  467. max_db = p_boost;
  468. }
  469. float AudioStreamPlayer3D::get_max_db() const {
  470. return max_db;
  471. }
  472. void AudioStreamPlayer3D::set_pitch_scale(float p_pitch_scale) {
  473. ERR_FAIL_COND(!(p_pitch_scale > 0.0));
  474. pitch_scale = p_pitch_scale;
  475. }
  476. float AudioStreamPlayer3D::get_pitch_scale() const {
  477. return pitch_scale;
  478. }
  479. void AudioStreamPlayer3D::play(float p_from_pos) {
  480. if (stream.is_null()) {
  481. return;
  482. }
  483. ERR_FAIL_COND_MSG(!is_inside_tree(), "Playback can only happen when a node is inside the scene tree");
  484. if (stream->is_monophonic() && is_playing()) {
  485. stop();
  486. }
  487. Ref<AudioStreamPlayback> stream_playback = stream->instantiate_playback();
  488. ERR_FAIL_COND_MSG(stream_playback.is_null(), "Failed to instantiate playback.");
  489. stream_playbacks.push_back(stream_playback);
  490. setplayback = stream_playback;
  491. setplay.set(p_from_pos);
  492. active.set();
  493. set_physics_process_internal(true);
  494. }
  495. void AudioStreamPlayer3D::seek(float p_seconds) {
  496. if (is_playing()) {
  497. stop();
  498. play(p_seconds);
  499. }
  500. }
  501. void AudioStreamPlayer3D::stop() {
  502. setplay.set(-1);
  503. for (Ref<AudioStreamPlayback> &playback : stream_playbacks) {
  504. AudioServer::get_singleton()->stop_playback_stream(playback);
  505. }
  506. stream_playbacks.clear();
  507. active.clear();
  508. set_physics_process_internal(false);
  509. }
  510. bool AudioStreamPlayer3D::is_playing() const {
  511. for (const Ref<AudioStreamPlayback> &playback : stream_playbacks) {
  512. if (AudioServer::get_singleton()->is_playback_active(playback)) {
  513. return true;
  514. }
  515. }
  516. if (setplay.get() >= 0) {
  517. return true; // play() has been called this frame, but no playback exists just yet.
  518. }
  519. return false;
  520. }
  521. float AudioStreamPlayer3D::get_playback_position() {
  522. // Return the playback position of the most recently started playback stream.
  523. if (!stream_playbacks.is_empty()) {
  524. return AudioServer::get_singleton()->get_playback_position(stream_playbacks[stream_playbacks.size() - 1]);
  525. }
  526. return 0;
  527. }
  528. void AudioStreamPlayer3D::set_bus(const StringName &p_bus) {
  529. //if audio is active, must lock this
  530. AudioServer::get_singleton()->lock();
  531. bus = p_bus;
  532. AudioServer::get_singleton()->unlock();
  533. }
  534. StringName AudioStreamPlayer3D::get_bus() const {
  535. for (int i = 0; i < AudioServer::get_singleton()->get_bus_count(); i++) {
  536. if (AudioServer::get_singleton()->get_bus_name(i) == bus) {
  537. return bus;
  538. }
  539. }
  540. return SceneStringNames::get_singleton()->Master;
  541. }
  542. void AudioStreamPlayer3D::set_autoplay(bool p_enable) {
  543. autoplay = p_enable;
  544. }
  545. bool AudioStreamPlayer3D::is_autoplay_enabled() {
  546. return autoplay;
  547. }
  548. void AudioStreamPlayer3D::_set_playing(bool p_enable) {
  549. if (p_enable) {
  550. play();
  551. } else {
  552. stop();
  553. }
  554. }
  555. bool AudioStreamPlayer3D::_is_active() const {
  556. return active.is_set();
  557. }
  558. void AudioStreamPlayer3D::_validate_property(PropertyInfo &p_property) const {
  559. if (p_property.name == "bus") {
  560. String options;
  561. for (int i = 0; i < AudioServer::get_singleton()->get_bus_count(); i++) {
  562. if (i > 0) {
  563. options += ",";
  564. }
  565. String name = AudioServer::get_singleton()->get_bus_name(i);
  566. options += name;
  567. }
  568. p_property.hint_string = options;
  569. }
  570. }
  571. void AudioStreamPlayer3D::set_max_distance(float p_metres) {
  572. ERR_FAIL_COND(p_metres < 0.0);
  573. max_distance = p_metres;
  574. update_gizmos();
  575. }
  576. float AudioStreamPlayer3D::get_max_distance() const {
  577. return max_distance;
  578. }
  579. void AudioStreamPlayer3D::set_area_mask(uint32_t p_mask) {
  580. area_mask = p_mask;
  581. }
  582. uint32_t AudioStreamPlayer3D::get_area_mask() const {
  583. return area_mask;
  584. }
  585. void AudioStreamPlayer3D::set_emission_angle_enabled(bool p_enable) {
  586. emission_angle_enabled = p_enable;
  587. update_gizmos();
  588. }
  589. bool AudioStreamPlayer3D::is_emission_angle_enabled() const {
  590. return emission_angle_enabled;
  591. }
  592. void AudioStreamPlayer3D::set_emission_angle(float p_angle) {
  593. ERR_FAIL_COND(p_angle < 0 || p_angle > 90);
  594. emission_angle = p_angle;
  595. update_gizmos();
  596. }
  597. float AudioStreamPlayer3D::get_emission_angle() const {
  598. return emission_angle;
  599. }
  600. void AudioStreamPlayer3D::set_emission_angle_filter_attenuation_db(float p_angle_attenuation_db) {
  601. emission_angle_filter_attenuation_db = p_angle_attenuation_db;
  602. }
  603. float AudioStreamPlayer3D::get_emission_angle_filter_attenuation_db() const {
  604. return emission_angle_filter_attenuation_db;
  605. }
  606. void AudioStreamPlayer3D::set_attenuation_filter_cutoff_hz(float p_hz) {
  607. attenuation_filter_cutoff_hz = p_hz;
  608. }
  609. float AudioStreamPlayer3D::get_attenuation_filter_cutoff_hz() const {
  610. return attenuation_filter_cutoff_hz;
  611. }
  612. void AudioStreamPlayer3D::set_attenuation_filter_db(float p_db) {
  613. attenuation_filter_db = p_db;
  614. }
  615. float AudioStreamPlayer3D::get_attenuation_filter_db() const {
  616. return attenuation_filter_db;
  617. }
  618. void AudioStreamPlayer3D::set_attenuation_model(AttenuationModel p_model) {
  619. ERR_FAIL_INDEX((int)p_model, 4);
  620. attenuation_model = p_model;
  621. update_gizmos();
  622. }
  623. AudioStreamPlayer3D::AttenuationModel AudioStreamPlayer3D::get_attenuation_model() const {
  624. return attenuation_model;
  625. }
  626. void AudioStreamPlayer3D::set_doppler_tracking(DopplerTracking p_tracking) {
  627. if (doppler_tracking == p_tracking) {
  628. return;
  629. }
  630. doppler_tracking = p_tracking;
  631. if (doppler_tracking != DOPPLER_TRACKING_DISABLED) {
  632. set_notify_transform(true);
  633. velocity_tracker->set_track_physics_step(doppler_tracking == DOPPLER_TRACKING_PHYSICS_STEP);
  634. if (is_inside_tree()) {
  635. velocity_tracker->reset(get_global_transform().origin);
  636. }
  637. } else {
  638. set_notify_transform(false);
  639. }
  640. }
  641. AudioStreamPlayer3D::DopplerTracking AudioStreamPlayer3D::get_doppler_tracking() const {
  642. return doppler_tracking;
  643. }
  644. void AudioStreamPlayer3D::set_stream_paused(bool p_pause) {
  645. // TODO this does not have perfect recall, fix that maybe? If there are zero playbacks registered with the AudioServer, this bool isn't persisted.
  646. for (Ref<AudioStreamPlayback> &playback : stream_playbacks) {
  647. AudioServer::get_singleton()->set_playback_paused(playback, p_pause);
  648. }
  649. }
  650. bool AudioStreamPlayer3D::get_stream_paused() const {
  651. // There's currently no way to pause some playback streams but not others. Check the first and don't bother looking at the rest.
  652. if (!stream_playbacks.is_empty()) {
  653. return AudioServer::get_singleton()->is_playback_paused(stream_playbacks[0]);
  654. }
  655. return false;
  656. }
  657. bool AudioStreamPlayer3D::has_stream_playback() {
  658. return !stream_playbacks.is_empty();
  659. }
  660. Ref<AudioStreamPlayback> AudioStreamPlayer3D::get_stream_playback() {
  661. ERR_FAIL_COND_V_MSG(stream_playbacks.is_empty(), Ref<AudioStreamPlayback>(), "Player is inactive. Call play() before requesting get_stream_playback().");
  662. return stream_playbacks[stream_playbacks.size() - 1];
  663. }
  664. void AudioStreamPlayer3D::set_max_polyphony(int p_max_polyphony) {
  665. if (p_max_polyphony > 0) {
  666. max_polyphony = p_max_polyphony;
  667. }
  668. }
  669. int AudioStreamPlayer3D::get_max_polyphony() const {
  670. return max_polyphony;
  671. }
  672. void AudioStreamPlayer3D::set_panning_strength(float p_panning_strength) {
  673. ERR_FAIL_COND_MSG(p_panning_strength < 0, "Panning strength must be a positive number.");
  674. panning_strength = p_panning_strength;
  675. }
  676. float AudioStreamPlayer3D::get_panning_strength() const {
  677. return panning_strength;
  678. }
  679. void AudioStreamPlayer3D::_on_bus_layout_changed() {
  680. notify_property_list_changed();
  681. }
  682. void AudioStreamPlayer3D::_on_bus_renamed(int p_bus_index, const StringName &p_old_name, const StringName &p_new_name) {
  683. notify_property_list_changed();
  684. }
  685. void AudioStreamPlayer3D::_bind_methods() {
  686. ClassDB::bind_method(D_METHOD("set_stream", "stream"), &AudioStreamPlayer3D::set_stream);
  687. ClassDB::bind_method(D_METHOD("get_stream"), &AudioStreamPlayer3D::get_stream);
  688. ClassDB::bind_method(D_METHOD("set_volume_db", "volume_db"), &AudioStreamPlayer3D::set_volume_db);
  689. ClassDB::bind_method(D_METHOD("get_volume_db"), &AudioStreamPlayer3D::get_volume_db);
  690. ClassDB::bind_method(D_METHOD("set_unit_size", "unit_size"), &AudioStreamPlayer3D::set_unit_size);
  691. ClassDB::bind_method(D_METHOD("get_unit_size"), &AudioStreamPlayer3D::get_unit_size);
  692. ClassDB::bind_method(D_METHOD("set_max_db", "max_db"), &AudioStreamPlayer3D::set_max_db);
  693. ClassDB::bind_method(D_METHOD("get_max_db"), &AudioStreamPlayer3D::get_max_db);
  694. ClassDB::bind_method(D_METHOD("set_pitch_scale", "pitch_scale"), &AudioStreamPlayer3D::set_pitch_scale);
  695. ClassDB::bind_method(D_METHOD("get_pitch_scale"), &AudioStreamPlayer3D::get_pitch_scale);
  696. ClassDB::bind_method(D_METHOD("play", "from_position"), &AudioStreamPlayer3D::play, DEFVAL(0.0));
  697. ClassDB::bind_method(D_METHOD("seek", "to_position"), &AudioStreamPlayer3D::seek);
  698. ClassDB::bind_method(D_METHOD("stop"), &AudioStreamPlayer3D::stop);
  699. ClassDB::bind_method(D_METHOD("is_playing"), &AudioStreamPlayer3D::is_playing);
  700. ClassDB::bind_method(D_METHOD("get_playback_position"), &AudioStreamPlayer3D::get_playback_position);
  701. ClassDB::bind_method(D_METHOD("set_bus", "bus"), &AudioStreamPlayer3D::set_bus);
  702. ClassDB::bind_method(D_METHOD("get_bus"), &AudioStreamPlayer3D::get_bus);
  703. ClassDB::bind_method(D_METHOD("set_autoplay", "enable"), &AudioStreamPlayer3D::set_autoplay);
  704. ClassDB::bind_method(D_METHOD("is_autoplay_enabled"), &AudioStreamPlayer3D::is_autoplay_enabled);
  705. ClassDB::bind_method(D_METHOD("_set_playing", "enable"), &AudioStreamPlayer3D::_set_playing);
  706. ClassDB::bind_method(D_METHOD("_is_active"), &AudioStreamPlayer3D::_is_active);
  707. ClassDB::bind_method(D_METHOD("set_max_distance", "meters"), &AudioStreamPlayer3D::set_max_distance);
  708. ClassDB::bind_method(D_METHOD("get_max_distance"), &AudioStreamPlayer3D::get_max_distance);
  709. ClassDB::bind_method(D_METHOD("set_area_mask", "mask"), &AudioStreamPlayer3D::set_area_mask);
  710. ClassDB::bind_method(D_METHOD("get_area_mask"), &AudioStreamPlayer3D::get_area_mask);
  711. ClassDB::bind_method(D_METHOD("set_emission_angle", "degrees"), &AudioStreamPlayer3D::set_emission_angle);
  712. ClassDB::bind_method(D_METHOD("get_emission_angle"), &AudioStreamPlayer3D::get_emission_angle);
  713. ClassDB::bind_method(D_METHOD("set_emission_angle_enabled", "enabled"), &AudioStreamPlayer3D::set_emission_angle_enabled);
  714. ClassDB::bind_method(D_METHOD("is_emission_angle_enabled"), &AudioStreamPlayer3D::is_emission_angle_enabled);
  715. ClassDB::bind_method(D_METHOD("set_emission_angle_filter_attenuation_db", "db"), &AudioStreamPlayer3D::set_emission_angle_filter_attenuation_db);
  716. ClassDB::bind_method(D_METHOD("get_emission_angle_filter_attenuation_db"), &AudioStreamPlayer3D::get_emission_angle_filter_attenuation_db);
  717. ClassDB::bind_method(D_METHOD("set_attenuation_filter_cutoff_hz", "degrees"), &AudioStreamPlayer3D::set_attenuation_filter_cutoff_hz);
  718. ClassDB::bind_method(D_METHOD("get_attenuation_filter_cutoff_hz"), &AudioStreamPlayer3D::get_attenuation_filter_cutoff_hz);
  719. ClassDB::bind_method(D_METHOD("set_attenuation_filter_db", "db"), &AudioStreamPlayer3D::set_attenuation_filter_db);
  720. ClassDB::bind_method(D_METHOD("get_attenuation_filter_db"), &AudioStreamPlayer3D::get_attenuation_filter_db);
  721. ClassDB::bind_method(D_METHOD("set_attenuation_model", "model"), &AudioStreamPlayer3D::set_attenuation_model);
  722. ClassDB::bind_method(D_METHOD("get_attenuation_model"), &AudioStreamPlayer3D::get_attenuation_model);
  723. ClassDB::bind_method(D_METHOD("set_doppler_tracking", "mode"), &AudioStreamPlayer3D::set_doppler_tracking);
  724. ClassDB::bind_method(D_METHOD("get_doppler_tracking"), &AudioStreamPlayer3D::get_doppler_tracking);
  725. ClassDB::bind_method(D_METHOD("set_stream_paused", "pause"), &AudioStreamPlayer3D::set_stream_paused);
  726. ClassDB::bind_method(D_METHOD("get_stream_paused"), &AudioStreamPlayer3D::get_stream_paused);
  727. ClassDB::bind_method(D_METHOD("set_max_polyphony", "max_polyphony"), &AudioStreamPlayer3D::set_max_polyphony);
  728. ClassDB::bind_method(D_METHOD("get_max_polyphony"), &AudioStreamPlayer3D::get_max_polyphony);
  729. ClassDB::bind_method(D_METHOD("set_panning_strength", "panning_strength"), &AudioStreamPlayer3D::set_panning_strength);
  730. ClassDB::bind_method(D_METHOD("get_panning_strength"), &AudioStreamPlayer3D::get_panning_strength);
  731. ClassDB::bind_method(D_METHOD("has_stream_playback"), &AudioStreamPlayer3D::has_stream_playback);
  732. ClassDB::bind_method(D_METHOD("get_stream_playback"), &AudioStreamPlayer3D::get_stream_playback);
  733. ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "stream", PROPERTY_HINT_RESOURCE_TYPE, "AudioStream"), "set_stream", "get_stream");
  734. ADD_PROPERTY(PropertyInfo(Variant::INT, "attenuation_model", PROPERTY_HINT_ENUM, "Inverse,Inverse Square,Logarithmic,Disabled"), "set_attenuation_model", "get_attenuation_model");
  735. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "volume_db", PROPERTY_HINT_RANGE, "-80,80,suffix:dB"), "set_volume_db", "get_volume_db");
  736. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "unit_size", PROPERTY_HINT_RANGE, "0.1,100,0.01,or_greater"), "set_unit_size", "get_unit_size");
  737. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "max_db", PROPERTY_HINT_RANGE, "-24,6,suffix:dB"), "set_max_db", "get_max_db");
  738. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "pitch_scale", PROPERTY_HINT_RANGE, "0.01,4,0.01,or_greater"), "set_pitch_scale", "get_pitch_scale");
  739. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "playing", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_EDITOR), "_set_playing", "is_playing");
  740. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "autoplay"), "set_autoplay", "is_autoplay_enabled");
  741. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "stream_paused", PROPERTY_HINT_NONE, ""), "set_stream_paused", "get_stream_paused");
  742. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "max_distance", PROPERTY_HINT_RANGE, "0,4096,0.01,or_greater,suffix:m"), "set_max_distance", "get_max_distance");
  743. ADD_PROPERTY(PropertyInfo(Variant::INT, "max_polyphony", PROPERTY_HINT_NONE, ""), "set_max_polyphony", "get_max_polyphony");
  744. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "panning_strength", PROPERTY_HINT_RANGE, "0,3,0.01,or_greater"), "set_panning_strength", "get_panning_strength");
  745. ADD_PROPERTY(PropertyInfo(Variant::STRING_NAME, "bus", PROPERTY_HINT_ENUM, ""), "set_bus", "get_bus");
  746. ADD_PROPERTY(PropertyInfo(Variant::INT, "area_mask", PROPERTY_HINT_LAYERS_2D_PHYSICS), "set_area_mask", "get_area_mask");
  747. ADD_GROUP("Emission Angle", "emission_angle");
  748. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "emission_angle_enabled"), "set_emission_angle_enabled", "is_emission_angle_enabled");
  749. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "emission_angle_degrees", PROPERTY_HINT_RANGE, "0.1,90,0.1,degrees"), "set_emission_angle", "get_emission_angle");
  750. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "emission_angle_filter_attenuation_db", PROPERTY_HINT_RANGE, "-80,0,0.1,suffix:dB"), "set_emission_angle_filter_attenuation_db", "get_emission_angle_filter_attenuation_db");
  751. ADD_GROUP("Attenuation Filter", "attenuation_filter_");
  752. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "attenuation_filter_cutoff_hz", PROPERTY_HINT_RANGE, "1,20500,1,suffix:Hz"), "set_attenuation_filter_cutoff_hz", "get_attenuation_filter_cutoff_hz");
  753. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "attenuation_filter_db", PROPERTY_HINT_RANGE, "-80,0,0.1,suffix:dB"), "set_attenuation_filter_db", "get_attenuation_filter_db");
  754. ADD_GROUP("Doppler", "doppler_");
  755. ADD_PROPERTY(PropertyInfo(Variant::INT, "doppler_tracking", PROPERTY_HINT_ENUM, "Disabled,Idle,Physics"), "set_doppler_tracking", "get_doppler_tracking");
  756. BIND_ENUM_CONSTANT(ATTENUATION_INVERSE_DISTANCE);
  757. BIND_ENUM_CONSTANT(ATTENUATION_INVERSE_SQUARE_DISTANCE);
  758. BIND_ENUM_CONSTANT(ATTENUATION_LOGARITHMIC);
  759. BIND_ENUM_CONSTANT(ATTENUATION_DISABLED);
  760. BIND_ENUM_CONSTANT(DOPPLER_TRACKING_DISABLED);
  761. BIND_ENUM_CONSTANT(DOPPLER_TRACKING_IDLE_STEP);
  762. BIND_ENUM_CONSTANT(DOPPLER_TRACKING_PHYSICS_STEP);
  763. ADD_SIGNAL(MethodInfo("finished"));
  764. }
  765. AudioStreamPlayer3D::AudioStreamPlayer3D() {
  766. velocity_tracker.instantiate();
  767. AudioServer::get_singleton()->connect("bus_layout_changed", callable_mp(this, &AudioStreamPlayer3D::_on_bus_layout_changed));
  768. AudioServer::get_singleton()->connect("bus_renamed", callable_mp(this, &AudioStreamPlayer3D::_on_bus_renamed));
  769. set_disable_scale(true);
  770. cached_global_panning_strength = GLOBAL_GET("audio/general/3d_panning_strength");
  771. }
  772. AudioStreamPlayer3D::~AudioStreamPlayer3D() {
  773. }