sfxSystem.cpp 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "platform/platform.h"
  23. #include "sfx/sfxSystem.h"
  24. #include "sfx/sfxProvider.h"
  25. #include "sfx/sfxDevice.h"
  26. #include "sfx/sfxInternal.h"
  27. #include "sfx/sfxSource.h"
  28. #include "sfx/sfxProfile.h"
  29. #include "sfx/sfxDescription.h"
  30. #include "sfx/sfxTrack.h"
  31. #include "sfx/sfxPlayList.h"
  32. #include "sfx/sfxSound.h"
  33. #include "sfx/sfxController.h"
  34. #include "sfx/sfxSoundscape.h"
  35. #include "console/console.h"
  36. #include "console/engineAPI.h"
  37. #include "T3D/gameBase/processList.h"
  38. #include "platform/profiler.h"
  39. #include "platform/platformTimer.h"
  40. #include "core/util/autoPtr.h"
  41. #include "core/module.h"
  42. #include "sfx/media/sfxWavStream.h"
  43. #ifdef TORQUE_OGGVORBIS
  44. #include "sfx/media/sfxVorbisStream.h"
  45. #endif
  46. MODULE_BEGIN( SFX )
  47. MODULE_INIT_BEFORE( Sim )
  48. MODULE_SHUTDOWN_BEFORE( Sim ) // Make sure all SimObjects disappear in time.
  49. MODULE_INIT
  50. {
  51. SFXSystem::init();
  52. }
  53. MODULE_SHUTDOWN
  54. {
  55. SFXSystem::destroy();
  56. }
  57. MODULE_END;
  58. SFXSystem* SFXSystem::smSingleton = NULL;
  59. /// Default SFXAmbience used to reset the global soundscape.
  60. SFXAmbience *sDefaultAmbience;
  61. // Excludes Null and Blocked as these are not passed out to the control layer.
  62. ImplementEnumType( SFXStatus,
  63. "Playback status of sound source.\n"
  64. "@ingroup SFX" )
  65. { SFXStatusPlaying, "Playing",
  66. "The source is currently playing." },
  67. { SFXStatusStopped, "Stopped",
  68. "Playback of the source is stopped. When transitioning to Playing state, playback will start at the beginning "
  69. "of the source." },
  70. { SFXStatusPaused, "Paused",
  71. "Playback of the source is paused. Resuming playback will play from the current playback position." },
  72. EndImplementEnumType;
  73. ImplementEnumType( SFXDistanceModel,
  74. "Type of volume distance attenuation curve.\n"
  75. "The distance model determines the falloff curve applied to the volume of 3D sounds over distance.\n\n"
  76. "@ref SFXSource_volume\n\n"
  77. "@ref SFX_3d\n\n"
  78. "@ingroup SFX" )
  79. { SFXDistanceModelLinear, "Linear",
  80. "Volume attenuates linearly from the references distance onwards to max distance where it reaches zero." },
  81. { SFXDistanceModelLogarithmic, "Logarithmic",
  82. "Volume attenuates logarithmically starting from the reference distance and halving every reference distance step from there on. "
  83. "Attenuation stops at max distance but volume won't reach zero." },
  84. { SFXDistanceModelExponent, "Exponential",
  85. "Volume attenuates exponentially starting from the reference distance and attenuating every reference distance step by the rolloff factor. "
  86. "Attenuation stops at max distance but volume won't reach zero." },
  87. EndImplementEnumType;
  88. ImplementEnumType( SFXChannel,
  89. "Channels are individual properties of sound sources that may be animated over time.\n\n"
  90. "@see SFXParameter\n\n"
  91. "@ref SFX_interactive\n\n"
  92. "@ingroup SFX" )
  93. { SFXChannelVolume, "Volume",
  94. "Channel controls volume level of attached sound sources.\n"
  95. "@see SFXDescription::volume" },
  96. { SFXChannelPitch, "Pitch",
  97. "Channel controls pitch of attached sound sources.\n"
  98. "@see SFXDescription::pitch" },
  99. { SFXChannelPriority, "Priority",
  100. "Channel controls virtualizaton priority level of attached sound sources.\n"
  101. "@see SFXDescription::priority" },
  102. { SFXChannelPositionX, "PositionX",
  103. "Channel controls X coordinate of 3D sound position of attached sources." },
  104. { SFXChannelPositionY, "PositionY",
  105. "Channel controls Y coordinate of 3D sound position of attached sources." },
  106. { SFXChannelPositionZ, "PositionZ",
  107. "Channel controls Z coordinate of 3D sound position of attached sources." },
  108. { SFXChannelRotationX, "RotationX",
  109. "Channel controls X rotation (in degrees) of 3D sound orientation of attached sources." },
  110. { SFXChannelRotationY, "RotationY",
  111. "Channel controls Y rotation (in degrees) of 3D sound orientation of attached sources." },
  112. { SFXChannelRotationZ, "RotationZ",
  113. "Channel controls Z rotation (in degrees) of 3D sound orientation of attached sources." },
  114. { SFXChannelVelocityX, "VelocityX",
  115. "Channel controls X coordinate of 3D sound velocity vector of attached sources." },
  116. { SFXChannelVelocityY, "VelocityY",
  117. "Channel controls Y coordinate of 3D sound velocity vector of attached sources." },
  118. { SFXChannelVelocityZ, "VelocityZ",
  119. "Channel controls Z coordinate of 3D sound velocity vector of attached sources." },
  120. { SFXChannelMinDistance, "ReferenceDistance",
  121. "Channel controls reference distance of 3D sound of attached sources.\n"
  122. "@see SFXDescription::referenceDistance" },
  123. { SFXChannelMaxDistance, "MaxDistance",
  124. "Channel controls max volume attenuation distance of 3D sound of attached sources.\n"
  125. "@see SFXDescription::maxDistance" },
  126. { SFXChannelConeInsideAngle, "ConeInsideAngle",
  127. "Channel controls angle (in degrees) of 3D sound inner volume cone of attached sources.\n"
  128. "@see SFXDescription::coneInsideAngle" },
  129. { SFXChannelConeOutsideAngle, "ConeOutsideAngle",
  130. "Channel controls angle (in degrees) of 3D sound outer volume cone of attached sources.\n"
  131. "@see SFXDescription::coneOutsideAngle" },
  132. { SFXChannelConeOutsideVolume, "ConeOutsideVolume",
  133. "Channel controls volume outside of 3D sound outer cone of attached sources.\n"
  134. "@see SFXDescription::coneOutsideVolume" },
  135. { SFXChannelCursor, "Cursor",
  136. "Channel controls playback cursor of attached sound sources.\n\n"
  137. "@note Be aware that different types of sound sources interpret play cursor positions differently "
  138. "or do not actually have play cursors (these sources will ignore the channel)." },
  139. { SFXChannelStatus, "Status",
  140. "Channel controls playback status of attached sound sources.\n\n"
  141. "The channel's value is rounded down to the nearest integer and interpreted in the following way:\n"
  142. "- 1: Play\n"
  143. "- 2: Stop\n"
  144. "- 3: Pause\n\n" },
  145. { SFXChannelUser0, "User0",
  146. "Channel available for custom use. By default ignored by sources.\n\n"
  147. "@see SFXSource::onParameterValueChange" },
  148. { SFXChannelUser1, "User1",
  149. "Channel available for custom use. By default ignored by sources.\n\n"
  150. "@see SFXSource::onParameterValueChange" },
  151. { SFXChannelUser2, "User2",
  152. "Channel available for custom use. By default ignored by sources.\n\n"
  153. "@see SFXSource::onParameterValueChange" },
  154. { SFXChannelUser3, "User3",
  155. "Channel available for custom use. By default ignored by sources.\n\n"
  156. "@see SFXSource::onParameterValueChange" },
  157. EndImplementEnumType;
  158. // Constants.
  159. static const U32 sDeviceCapsReverb = SFXDevice::CAPS_Reverb;
  160. static const U32 sDeviceCapsVoiceManagement = SFXDevice::CAPS_VoiceManagement;
  161. static const U32 sDeviceCapsOcclusion = SFXDevice::CAPS_Occlusion;
  162. static const U32 sDeviceCapsDSPEffects = SFXDevice::CAPS_DSPEffects;
  163. static const U32 sDeviceCapsMultiListener = SFXDevice::CAPS_MultiListener;
  164. static const U32 sDeviceInfoProvider = 0;
  165. static const U32 sDeviceInfoName = 1;
  166. static const U32 sDeviceInfoUseHardware = 2;
  167. static const U32 sDeviceInfoMaxBuffers = 3;
  168. //-----------------------------------------------------------------------------
  169. SFXSystem::SFXSystem()
  170. : mDevice( NULL ),
  171. mLastSourceUpdateTime( 0 ),
  172. mLastAmbientUpdateTime( 0 ),
  173. mLastParameterUpdateTime( 0 ),
  174. mStatNumSources( 0 ),
  175. mStatNumSounds( 0 ),
  176. mStatNumPlaying( 0 ),
  177. mStatNumCulled( 0 ),
  178. mStatNumVoices( 0 ),
  179. mStatSourceUpdateTime( 0 ),
  180. mStatParameterUpdateTime( 0 ),
  181. mDistanceModel( SFXDistanceModelLinear ),
  182. mStatAmbientUpdateTime( 0 ),
  183. mDopplerFactor( 0.5 ),
  184. mRolloffFactor( 1.0 ),
  185. mSoundscapeMgr( NULL )
  186. {
  187. VECTOR_SET_ASSOCIATION( mSounds );
  188. VECTOR_SET_ASSOCIATION( mPlayOnceSources );
  189. VECTOR_SET_ASSOCIATION( mPlugins );
  190. VECTOR_SET_ASSOCIATION( mListeners );
  191. // Always at least one listener.
  192. mListeners.increment();
  193. // Register stat variables.
  194. Con::addVariable( "SFX::numSources", TypeS32, &mStatNumSources,
  195. "Number of SFXSource type objects that are currently instantiated.\n"
  196. "@ingroup SFX" );
  197. Con::addVariable( "SFX::numSounds", TypeS32, &mStatNumSounds,
  198. "Number of SFXSound type objects (i.e. actual single-file sounds) that are currently instantiated.\n"
  199. "@ingroup SFX" );
  200. Con::addVariable( "SFX::numPlaying", TypeS32, &mStatNumPlaying,
  201. "Number of SFXSources that are currently in playing state.\n"
  202. "@ingroup SFX" );
  203. Con::addVariable( "SFX::numCulled", TypeS32, &mStatNumCulled,
  204. "Number of SFXSounds that are currently in virtualized playback mode.\n"
  205. "@ref SFXSound_virtualization\n\n"
  206. "@ingroup SFX" );
  207. Con::addVariable( "SFX::numVoices", TypeS32, &mStatNumVoices,
  208. "Number of voices that are currently allocated on the sound device.\n"
  209. "@ingroup SFX" );
  210. Con::addVariable( "SFX::sourceUpdateTime", TypeS32, &mStatSourceUpdateTime,
  211. "Milliseconds spent on the last SFXSource update loop.\n"
  212. "@ref SFX_updating\n\n"
  213. "@ingroup SFX" );
  214. Con::addVariable( "SFX::parameterUpdateTime", TypeS32, &mStatParameterUpdateTime,
  215. "Milliseconds spent on the last SFXParameter update loop.\n"
  216. "@ref SFX_updating\n\n"
  217. "@ref SFX_interactive\n\n"
  218. "@ingroup SFX" );
  219. Con::addVariable( "SFX::ambientUpdateTime", TypeS32, &mStatAmbientUpdateTime,
  220. "Milliseconds spent on the last ambient audio update.\n"
  221. "@ref SFX_updating\n\n"
  222. "@ref SFX_ambient\n\n"
  223. "@ingroup SFX" );
  224. // Register constants.
  225. Con::addConstant( "$SFX::DEVICE_CAPS_REVERB", TypeS32, &sDeviceCapsReverb,
  226. "Sound device capability flag indicating that the sound device supports reverb.\n\n"
  227. "@see sfxGetDeviceInfo\n\n"
  228. "@ref SFX_reverb\n\n"
  229. "@ingroup SFX" );
  230. Con::addConstant( "$SFX::DEVICE_CAPS_VOICEMANAGEMENT", TypeS32, &sDeviceCapsVoiceManagement,
  231. "Sound device capability flag indicating that the sound device implements its own voice virtualization.\n\n"
  232. "For these devices, the sound system will deactivate its own voice management and leave voice "
  233. "virtualization entirely to the device.\n\n"
  234. "@see sfxGetDeviceInfo\n\n"
  235. "@ref SFXSound_virtualization\n\n"
  236. "@ingroup SFX" );
  237. Con::addConstant( "$SFX::DEVICE_CAPS_OCCLUSION", TypeS32, &sDeviceCapsOcclusion,
  238. "Sound device capability flag indicating that the sound device implements sound occlusion.\n\n"
  239. "@note This is not yet used by the sound system.\n\n"
  240. "@see sfxGetDeviceInfo\n\n"
  241. "@ingroup SFX" );
  242. Con::addConstant( "$SFX::DEVICE_CAPS_DSPEFFECTS", TypeS32, &sDeviceCapsDSPEffects,
  243. "Sound device capability flag indicating that the sound device supports adding DSP effect chains to sounds.\n\n"
  244. "@see sfxGetDeviceInfo\n\n"
  245. "@note This is not yet used by the sound system.\n\n"
  246. "@see sfxGetDeviceInfo\n\n"
  247. "@ingroup SFX" );
  248. Con::addConstant( "$SFX::DEVICE_CAPS_MULTILISTENER", TypeS32, &sDeviceCapsMultiListener,
  249. "Sound device capability flag indicating that the sound device supports multiple concurrent listeners.\n\n"
  250. "@see sfxGetDeviceInfo\n\n"
  251. "@ingroup SFX" );
  252. Con::addConstant( "$SFX::DEVICE_INFO_PROVIDER", TypeS32, &sDeviceInfoProvider,
  253. "Index of sound provider field in device info string.\n\n"
  254. "@see sfxGetDeviceInfo\n\n"
  255. "@see sfxGetAvailableDevices\n\n"
  256. "@ingroup SFX" );
  257. Con::addConstant( "$SFX::DEVICE_INFO_NAME", TypeS32, &sDeviceInfoName,
  258. "Index of device name field in device info string.\n\n"
  259. "@see sfxGetDeviceInfo\n\n"
  260. "@see sfxGetAvailableDevices\n\n"
  261. "@ingroup SFX" );
  262. Con::addConstant( "$SFX::DEVICE_INFO_USEHARDWARE", TypeS32, &sDeviceInfoUseHardware,
  263. "Index of use hardware flag in device info string.\n\n"
  264. "@see sfxGetDeviceInfo\n\n"
  265. "@see sfxGetAvailableDevices\n\n"
  266. "@ingroup SFX" );
  267. Con::addConstant( "$SFX::DEVICE_INFO_MAXBUFFERS", TypeS32, &sDeviceInfoMaxBuffers,
  268. "Index of buffer limit number in device info string.\n\n"
  269. "@see sfxGetDeviceInfo\n\n"
  270. "@see sfxGetAvailableDevices\n\n"
  271. "@ingroup SFX" );
  272. Con::addConstant( "$SFX::DEVICE_INFO_CAPS", TypeS32, &sDeviceInfoMaxBuffers,
  273. "Index of device capability flags in device info string.\n\n"
  274. "@see sfxGetDeviceInfo\n\n"
  275. "@see sfxGetAvailableDevices\n\n"
  276. "@ingroup SFX" );
  277. // Create subsystems.
  278. mSoundscapeMgr = new SFXSoundscapeManager();
  279. }
  280. //-----------------------------------------------------------------------------
  281. SFXSystem::~SFXSystem()
  282. {
  283. // Unregister stat variables.
  284. Con::removeVariable( "SFX::numSources" );
  285. Con::removeVariable( "SFX::numSounds" );
  286. Con::removeVariable( "SFX::numPlaying" );
  287. Con::removeVariable( "SFX::numCulled" );
  288. Con::removeVariable( "SFX::numVoices" );
  289. Con::removeVariable( "SFX::sourceUpdateTime" );
  290. Con::removeVariable( "SFX::parameterUpdateTime" );
  291. Con::removeVariable( "SFX::ambientUpdateTime" );
  292. // Cleanup any remaining sources.
  293. if( Sim::getSFXSourceSet() )
  294. Sim::getSFXSourceSet()->deleteAllObjects();
  295. mSounds.clear();
  296. mPlayOnceSources.clear();
  297. mListeners.clear();
  298. // Delete subsystems.
  299. if( mSoundscapeMgr )
  300. SAFE_DELETE( mSoundscapeMgr );
  301. // Delete device if we still have one.
  302. deleteDevice();
  303. }
  304. //-----------------------------------------------------------------------------
  305. void SFXSystem::init()
  306. {
  307. AssertWarn( smSingleton == NULL, "SFX has already been initialized!" );
  308. SFXProvider::initializeAllProviders();
  309. // Register the streams and resources. Note that
  310. // the order here does matter!
  311. SFXFileStream::registerExtension( ".wav", ( SFXFILESTREAM_CREATE_FN ) SFXWavStream::create );
  312. #ifdef TORQUE_OGGVORBIS
  313. SFXFileStream::registerExtension( ".ogg", ( SFXFILESTREAM_CREATE_FN ) SFXVorbisStream::create );
  314. #endif
  315. // Create the stream thread pool.
  316. SFXInternal::SFXThreadPool::createSingleton();
  317. // Note: If you have provider specific file types you should
  318. // register them in the provider initialization.
  319. // Create the system.
  320. smSingleton = new SFXSystem();
  321. sDefaultAmbience = new SFXAmbience();
  322. }
  323. //-----------------------------------------------------------------------------
  324. void SFXSystem::destroy()
  325. {
  326. AssertWarn( smSingleton != NULL, "SFX has not been initialized!" );
  327. SFXFileStream::unregisterExtension( ".wav" );
  328. #ifdef TORQUE_OGGVORBIS
  329. SFXFileStream::unregisterExtension( ".ogg" );
  330. #endif
  331. delete smSingleton;
  332. smSingleton = NULL;
  333. // Destroy the stream thread pool
  334. SFXInternal::SFXThreadPool::deleteSingleton();
  335. delete(sDefaultAmbience);
  336. }
  337. //-----------------------------------------------------------------------------
  338. void SFXSystem::addPlugin( SFXSystemPlugin* plugin )
  339. {
  340. for( U32 i = 0; i < mPlugins.size(); ++ i )
  341. AssertFatal( mPlugins[ i ] != plugin, "SFXSystem::addPlugin - plugin already added to the system!" );
  342. mPlugins.push_back( plugin );
  343. }
  344. //-----------------------------------------------------------------------------
  345. void SFXSystem::removePlugin( SFXSystemPlugin* plugin )
  346. {
  347. for( U32 i = 0; i < mPlugins.size(); ++ i )
  348. if( mPlugins[ i ] == plugin )
  349. {
  350. mPlugins.erase_fast( i );
  351. break;
  352. }
  353. }
  354. //-----------------------------------------------------------------------------
  355. bool SFXSystem::createDevice( const String& providerName, const String& deviceName, bool useHardware, S32 maxBuffers, bool changeDevice )
  356. {
  357. // Make sure we don't have a device already.
  358. if( mDevice && !changeDevice )
  359. return false;
  360. // Lookup the provider.
  361. SFXProvider* provider = SFXProvider::findProvider( providerName );
  362. if( !provider )
  363. return false;
  364. // If we have already created this device and are using it then no need to do anything.
  365. if( mDevice
  366. && providerName.equal( mDevice->getProvider()->getName(), String::NoCase )
  367. && deviceName.equal( mDevice->getName(), String::NoCase )
  368. && useHardware == mDevice->getUseHardware() )
  369. return true;
  370. // If we have an existing device remove it.
  371. if( mDevice )
  372. deleteDevice();
  373. // Create the new device..
  374. mDevice = provider->createDevice( deviceName, useHardware, maxBuffers );
  375. if( !mDevice )
  376. {
  377. Con::errorf( "SFXSystem::createDevice - failed creating %s device '%s'", providerName.c_str(), deviceName.c_str() );
  378. return false;
  379. }
  380. // Print capabilities.
  381. Con::printf( "SFXSystem::createDevice - created %s device '%s'", providerName.c_str(), deviceName.c_str() );
  382. if( mDevice->getCaps() & SFXDevice::CAPS_Reverb )
  383. Con::printf( " CAPS_Reverb" );
  384. if( mDevice->getCaps() & SFXDevice::CAPS_VoiceManagement )
  385. Con::printf( " CAPS_VoiceManagement" );
  386. if( mDevice->getCaps() & SFXDevice::CAPS_Occlusion )
  387. Con::printf( "\tCAPS_Occlusion" );
  388. if( mDevice->getCaps() & SFXDevice::CAPS_MultiListener )
  389. Con::printf( "\tCAPS_MultiListener" );
  390. // Set defaults.
  391. mDevice->setNumListeners( getNumListeners() );
  392. mDevice->setDistanceModel( mDistanceModel );
  393. mDevice->setDopplerFactor( mDopplerFactor );
  394. mDevice->setRolloffFactor( mRolloffFactor );
  395. //OpenAL requires slots for effects, this creates an empty function
  396. //that will run when a sfxdevice is created.
  397. mDevice->openSlots();
  398. mDevice->setReverb( mReverb );
  399. // Signal system.
  400. getEventSignal().trigger( SFXSystemEvent_CreateDevice );
  401. return true;
  402. }
  403. //-----------------------------------------------------------------------------
  404. String SFXSystem::getDeviceInfoString()
  405. {
  406. // Make sure we have a valid device.
  407. if( !mDevice )
  408. return String();
  409. return String::ToString( "%s\t%s\t%s\t%d\t%d",
  410. mDevice->getProvider()->getName().c_str(),
  411. mDevice->getName().c_str(),
  412. mDevice->getUseHardware() ? "1" : "0",
  413. mDevice->getMaxBuffers(),
  414. mDevice->getCaps() );
  415. }
  416. //-----------------------------------------------------------------------------
  417. void SFXSystem::deleteDevice()
  418. {
  419. // Make sure we have a valid device.
  420. if ( !mDevice )
  421. return;
  422. // Put all playing sounds into virtualized playback mode. Where this fails,
  423. // stop the source.
  424. for( U32 i = 0; i < mSounds.size(); ++ i )
  425. {
  426. SFXSound* sound = mSounds[ i ];
  427. if( sound->hasVoice() && !sound->_releaseVoice() )
  428. sound->stop();
  429. }
  430. // Signal everyone who cares that the
  431. // device is being deleted.
  432. getEventSignal().trigger( SFXSystemEvent_DestroyDevice );
  433. // Free the device which should delete all
  434. // the active voices and buffers.
  435. delete mDevice;
  436. mDevice = NULL;
  437. }
  438. //-----------------------------------------------------------------------------
  439. SFXSource* SFXSystem::createSource( SFXTrack* track,
  440. const MatrixF* transform,
  441. const VectorF* velocity )
  442. {
  443. if( !track )
  444. return NULL;
  445. SFXSource* source = NULL;
  446. // Try creating through a plugin first so that they
  447. // always get the first shot and may override our
  448. // logic here.
  449. for( U32 i = 0; !source && i < mPlugins.size(); ++ i )
  450. source = mPlugins[ i ]->createSource( track );
  451. // If that failed, try our own logic using the track
  452. // types that we know about.
  453. if( !source )
  454. {
  455. if( !mDevice )
  456. {
  457. Con::errorf( "SFXSystem::createSource() - no device initialized!" );
  458. return NULL;
  459. }
  460. if( dynamic_cast< SFXPlayList* >( track ) )
  461. {
  462. // Create a playback controller for the track.
  463. SFXPlayList* playList = static_cast< SFXPlayList* >( track );
  464. source = SFXController::_create( playList );
  465. }
  466. else if( dynamic_cast< SFXProfile* >( track ) )
  467. {
  468. // Create a sound.
  469. SFXProfile* profile = static_cast< SFXProfile* >( track );
  470. source = SFXSound::_create( mDevice, profile );
  471. if( !source )
  472. {
  473. Con::errorf(
  474. "SFXSystem::createSource() - Failed to create sound!\n"
  475. " Profile: %s\n"
  476. " Filename: %s",
  477. profile->getName(),
  478. profile->getSoundFileName().c_str() );
  479. }
  480. }
  481. else
  482. {
  483. Con::errorf( "SFXSystem::createSource - cannot create source for %i (%s) of type '%s'",
  484. track->getId(), track->getName(), track->getClassName() );
  485. Con::errorf( "SFXSystem::createSource - maybe you are using the wrong SFX provider for this type of track" );
  486. return NULL;
  487. }
  488. }
  489. if( source )
  490. {
  491. if( transform )
  492. source->setTransform( *transform );
  493. if( velocity )
  494. source->setVelocity( *velocity );
  495. }
  496. return source;
  497. }
  498. //-----------------------------------------------------------------------------
  499. SFXSound* SFXSystem::createSourceFromStream( const ThreadSafeRef< SFXStream >& stream,
  500. SFXDescription* description )
  501. {
  502. AssertFatal( mDevice, "SFXSystem::createSourceFromStream() - no device initialized!" );
  503. // We sometimes get null values from script... fail in that case.
  504. if( !stream || !description )
  505. return NULL;
  506. // Create the sound.
  507. SFXSound* sound = SFXSound::_create( mDevice, stream, description );
  508. if( !sound )
  509. return NULL;
  510. return sound;
  511. }
  512. //-----------------------------------------------------------------------------
  513. void SFXSystem::stopAndDeleteSource( SFXSource* source )
  514. {
  515. if( source->getFadeOutTime() > 0.f )
  516. {
  517. // Fade-out. Stop and put on play-once list to
  518. // ensure deletion when the source actually stops.
  519. source->stop();
  520. deleteWhenStopped( source );
  521. }
  522. else
  523. {
  524. // No fade-out. Just stop and delete the source.
  525. source->stop();
  526. SFX_DELETE( source );
  527. }
  528. }
  529. //-----------------------------------------------------------------------------
  530. void SFXSystem::deleteWhenStopped( SFXSource* source )
  531. {
  532. // If the source isn't already on the play-once source list,
  533. // put it there now.
  534. Vector< SFXSource* >::iterator iter = T3D::find( mPlayOnceSources.begin(), mPlayOnceSources.end(), source );
  535. if( iter == mPlayOnceSources.end() )
  536. mPlayOnceSources.push_back( source );
  537. }
  538. //-----------------------------------------------------------------------------
  539. void SFXSystem::_onAddSource( SFXSource* source )
  540. {
  541. if( dynamic_cast< SFXSound* >( source ) )
  542. {
  543. SFXSound* sound = static_cast< SFXSound* >( source );
  544. mSounds.push_back( sound );
  545. mStatNumSounds = mSounds.size();
  546. }
  547. // Update the stats.
  548. mStatNumSources ++;
  549. }
  550. //-----------------------------------------------------------------------------
  551. void SFXSystem::_onRemoveSource( SFXSource* source )
  552. {
  553. // Check if it was a play once source.
  554. Vector< SFXSource* >::iterator sourceIter = T3D::find( mPlayOnceSources.begin(), mPlayOnceSources.end(), source );
  555. if (sourceIter != mPlayOnceSources.end() )
  556. mPlayOnceSources.erase_fast(sourceIter);
  557. // Update the stats.
  558. mStatNumSources --;
  559. if( dynamic_cast< SFXSound* >( source ) )
  560. {
  561. SFXSoundVector::iterator vectorIter = T3D::find( mSounds.begin(), mSounds.end(), static_cast< SFXSound* >( source ) );
  562. if(vectorIter != mSounds.end() )
  563. mSounds.erase_fast(vectorIter);
  564. mStatNumSounds = mSounds.size();
  565. }
  566. }
  567. //-----------------------------------------------------------------------------
  568. SFXBuffer* SFXSystem::_createBuffer( const ThreadSafeRef< SFXStream >& stream, SFXDescription* description )
  569. {
  570. // The buffers are created by the active
  571. // device... without one we cannot do anything.
  572. if ( !mDevice )
  573. {
  574. Con::errorf( "SFXSystem::_createBuffer - No sound device initialized!!" );
  575. return NULL;
  576. }
  577. // Some sanity checking for streaming. If the stream isn't at least three packets
  578. // in size given the current settings in "description", then turn off streaming.
  579. // The device code *will* mess up if the stream input fails to match certain metrics.
  580. // Just disabling streaming when it doesn't make sense is easier than complicating the
  581. // device logic to account for bad metrics.
  582. bool streamFlag = description->mIsStreaming;
  583. if( description->mIsStreaming
  584. && stream->getDuration() < description->mStreamPacketSize * 1000 * SFXInternal::SFXAsyncQueue::DEFAULT_STREAM_QUEUE_LENGTH )
  585. description->mIsStreaming = false;
  586. SFXBuffer* buffer = mDevice->createBuffer( stream, description );
  587. description->mIsStreaming = streamFlag; // restore in case we stomped it
  588. return buffer;
  589. }
  590. //-----------------------------------------------------------------------------
  591. SFXBuffer* SFXSystem::_createBuffer( const String& filename, SFXDescription* description )
  592. {
  593. if( !mDevice )
  594. {
  595. Con::errorf( "SFXSystem::_createBuffer - No sound device initialized!!" );
  596. return NULL;
  597. }
  598. return mDevice->createBuffer( filename, description );
  599. }
  600. //-----------------------------------------------------------------------------
  601. SFXSource* SFXSystem::playOnce( SFXTrack* track,
  602. const MatrixF *transform,
  603. const VectorF *velocity,
  604. F32 fadeInTime )
  605. {
  606. // We sometimes get null profiles... nothing to play without a profile!
  607. if( !track )
  608. return NULL;
  609. SFXSource *source = createSource( track, transform, velocity );
  610. if( source )
  611. {
  612. mPlayOnceSources.push_back( source );
  613. source->play( fadeInTime );
  614. }
  615. return source;
  616. }
  617. //-----------------------------------------------------------------------------
  618. void SFXSystem::_update()
  619. {
  620. PROFILE_SCOPE( SFXSystem_Update );
  621. getEventSignal().trigger( SFXSystemEvent_Update );
  622. for( U32 i = 0; i < mPlugins.size(); ++ i )
  623. mPlugins[ i ]->update();
  624. const U32 SOURCE_UPDATE_MS = TickMs * 2;
  625. const U32 PARAMETER_UPDATE_MS = TickMs * 3;
  626. const U32 AMBIENT_UPDATE_MS = TickMs * 4;
  627. static AutoPtr< PlatformTimer > sTimer;
  628. if( sTimer.isNull() )
  629. sTimer = PlatformTimer::create();
  630. // The update of the sources can be a bit expensive
  631. // and it does not need to be updated every frame.
  632. const U32 currentTime = Platform::getRealMilliseconds();
  633. if( ( currentTime - mLastSourceUpdateTime ) >= SOURCE_UPDATE_MS )
  634. {
  635. S32 tick = sTimer->getElapsedMs();
  636. _updateSources();
  637. mLastSourceUpdateTime = currentTime;
  638. mStatSourceUpdateTime = ( sTimer->getElapsedMs() - tick );
  639. }
  640. if( ( currentTime - mLastParameterUpdateTime ) >= PARAMETER_UPDATE_MS )
  641. {
  642. S32 tick = sTimer->getElapsedMs();
  643. SimSet* set = Sim::getSFXParameterGroup();
  644. for( SimSet::iterator iter = set->begin(); iter != set->end(); ++ iter )
  645. {
  646. SFXParameter* parameter = dynamic_cast< SFXParameter* >( *iter );
  647. if( parameter )
  648. parameter->update();
  649. }
  650. mLastParameterUpdateTime = currentTime;
  651. mStatParameterUpdateTime = ( sTimer->getElapsedMs() - tick );
  652. }
  653. if( mSoundscapeMgr && ( currentTime - mLastAmbientUpdateTime ) >= AMBIENT_UPDATE_MS )
  654. {
  655. S32 tick = sTimer->getElapsedMs();
  656. mSoundscapeMgr->update();
  657. mLastAmbientUpdateTime = currentTime;
  658. mStatAmbientUpdateTime = ( sTimer->getElapsedMs() - tick );
  659. }
  660. // If we have a device then update it.
  661. if( mDevice )
  662. mDevice->update();
  663. }
  664. //-----------------------------------------------------------------------------
  665. void SFXSystem::_updateSources()
  666. {
  667. PROFILE_SCOPE( SFXSystem_UpdateSources );
  668. SimSet* sources = Sim::getSFXSourceSet();
  669. if( !sources )
  670. return;
  671. // Check the status of the sources here once.
  672. //
  673. // NOTE: We do not use iterators in this loop because
  674. // SFXControllers can add to the source list during the
  675. // loop.
  676. //
  677. mStatNumPlaying = 0;
  678. for( S32 i=0; i < sources->size(); i++ )
  679. {
  680. SFXSource *source = dynamic_cast< SFXSource* >( sources->at( i ) );
  681. if ( source )
  682. {
  683. source->update();
  684. if( source->getStatus() == SFXStatusPlaying )
  685. ++ mStatNumPlaying;
  686. }
  687. }
  688. // First check to see if any play once sources have
  689. // finished playback... delete them.
  690. for( SFXSourceVector::iterator iter = mPlayOnceSources.begin(); iter != mPlayOnceSources.end(); )
  691. {
  692. SFXSource* source = *iter;
  693. if( source->getLastStatus() == SFXStatusStopped &&
  694. source->getSavedStatus() != SFXStatusPlaying )
  695. {
  696. S32 index = iter - mPlayOnceSources.begin();
  697. // Erase it from the vector first, so that onRemoveSource
  698. // doesn't do it during cleanup and screw up our loop here!
  699. mPlayOnceSources.erase_fast( iter );
  700. source->deleteObject();
  701. iter = mPlayOnceSources.begin() + index;
  702. continue;
  703. }
  704. ++ iter;
  705. }
  706. if( mDevice )
  707. {
  708. // Reassign buffers to the sounds (if voices are managed by
  709. // us instead of by the device).
  710. if( !( mDevice->getCaps() & SFXDevice::CAPS_VoiceManagement ) )
  711. _assignVoices();
  712. // Update the voice count stat.
  713. mStatNumVoices = mDevice->getVoiceCount();
  714. }
  715. }
  716. //-----------------------------------------------------------------------------
  717. void SFXSystem::_sortSounds( const SFXListenerProperties& listener )
  718. {
  719. PROFILE_SCOPE( SFXSystem_SortSounds );
  720. // Sort the source vector by the attenuated
  721. // volume and priorities. This leaves us
  722. // with the loudest and highest priority sounds
  723. // at the front of the vector.
  724. dQsort( ( void* ) mSounds.address(), mSounds.size(), sizeof( SFXSound* ), SFXSound::qsortCompare );
  725. }
  726. //-----------------------------------------------------------------------------
  727. void SFXSystem::_assignVoices()
  728. {
  729. AssertFatal( getNumListeners() == 1, "SFXSystem::_assignVoices() - must only have a single listener" );
  730. PROFILE_SCOPE( SFXSystem_AssignVoices );
  731. mStatNumVoices = 0;
  732. mStatNumCulled = 0;
  733. if( !mDevice )
  734. return;
  735. // Sort the sources in the SFX source set by priority. This also
  736. // updates each soures effective volume first.
  737. _sortSounds( getListener() );
  738. // We now make sure that the sources closest to the
  739. // listener, the ones at the top of the source list,
  740. // have a device buffer to play thru.
  741. mStatNumCulled = 0;
  742. for( SFXSoundVector::iterator iter = mSounds.begin(); iter != mSounds.end(); ++ iter )
  743. {
  744. SFXSound* sound = *iter;
  745. // Non playing sources (paused or stopped) are at the
  746. // end of the vector, so when i encounter one i know
  747. // that nothing else in the vector needs buffer assignment.
  748. if( !sound->isPlaying() )
  749. break;
  750. // If the source is outside it's max range we can
  751. // skip it as well, so that we don't waste cycles
  752. // setting up a buffer for something we won't hear.
  753. if( sound->getAttenuatedVolume() <= 0.0f )
  754. {
  755. ++ mStatNumCulled;
  756. continue;
  757. }
  758. // If the source has a voice then we can skip it.
  759. if( sound->hasVoice() )
  760. continue;
  761. // Ok let the device try to assign a new voice for
  762. // this source... this may fail if we're out of voices.
  763. if( sound->_allocVoice( mDevice ) )
  764. continue;
  765. // The device couldn't assign a new voice, so we go through
  766. // local priority sounds and try to steal a voice.
  767. for( SFXSoundVector::iterator hijack = mSounds.end() - 1; hijack != iter; -- hijack )
  768. {
  769. SFXSound* other = *hijack;
  770. if( other->hasVoice() )
  771. {
  772. // If the sound is a suitable candidate, try to steal
  773. // its voice. While the sound definitely is lower down the chain
  774. // in the total priority ordering, we don't want to steal voices
  775. // from sounds that are clearly audible as that results in noticable
  776. // sound pops.
  777. if( ( other->getAttenuatedVolume() < 0.1 // Very quiet or maybe not even audible.
  778. || !other->isPlaying() // Not playing so not audible anyways.
  779. || other->getPosition() == 0 ) // Not yet started playing.
  780. && other->_releaseVoice() )
  781. break;
  782. }
  783. }
  784. // Ok try to assign a voice once again!
  785. if( sound->_allocVoice( mDevice ) )
  786. continue;
  787. // If the source still doesn't have a buffer... well
  788. // tough cookies. It just cannot be heard yet, maybe
  789. // it can in the next update.
  790. mStatNumCulled ++;
  791. }
  792. // Update the voice count stat.
  793. mStatNumVoices = mDevice->getVoiceCount();
  794. }
  795. //-----------------------------------------------------------------------------
  796. void SFXSystem::_assignVoice( SFXSound* sound )
  797. {
  798. if( !mDevice )
  799. return;
  800. // Make sure all properties are up-to-date.
  801. sound->_update();
  802. // If voices are managed by the device, just let the sound
  803. // allocate a voice on it. Otherwise, do a voice allocation pass
  804. // on all our active sounds.
  805. if( mDevice->getCaps() & SFXDevice::CAPS_VoiceManagement )
  806. sound->_allocVoice( mDevice );
  807. else
  808. _assignVoices();
  809. // Update the voice count stat.
  810. mStatNumVoices = mDevice->getVoiceCount();
  811. }
  812. //-----------------------------------------------------------------------------
  813. void SFXSystem::setDistanceModel( SFXDistanceModel model )
  814. {
  815. const bool changed = ( model != mDistanceModel );
  816. mDistanceModel = model;
  817. if( mDevice && changed )
  818. mDevice->setDistanceModel( model );
  819. }
  820. //-----------------------------------------------------------------------------
  821. void SFXSystem::setDopplerFactor( F32 factor )
  822. {
  823. const bool changed = ( factor != mDopplerFactor );
  824. mDopplerFactor = factor;
  825. if( mDevice && changed )
  826. mDevice->setDopplerFactor( factor );
  827. }
  828. //-----------------------------------------------------------------------------
  829. void SFXSystem::setRolloffFactor( F32 factor )
  830. {
  831. const bool changed = ( factor != mRolloffFactor );
  832. mRolloffFactor = factor;
  833. if( mDevice && changed )
  834. mDevice->setRolloffFactor( factor );
  835. }
  836. //-----------------------------------------------------------------------------
  837. void SFXSystem::setReverb( const SFXReverbProperties& reverb )
  838. {
  839. mReverb = reverb;
  840. // Allow the plugins to adjust the reverb.
  841. for( U32 i = 0; i < mPlugins.size(); ++ i )
  842. mPlugins[ i ]->filterReverb( mReverb );
  843. // Pass it on to the device.
  844. if( mDevice )
  845. mDevice->setReverb( mReverb );
  846. }
  847. //-----------------------------------------------------------------------------
  848. void SFXSystem::setNumListeners( U32 num )
  849. {
  850. // If we are set to a single listener, just accept this as
  851. // we always support this no matter what.
  852. if( num == 1 )
  853. {
  854. mListeners.setSize( 1 );
  855. if( mDevice )
  856. mDevice->setNumListeners( 1 );
  857. return;
  858. }
  859. // If setting to multiple listeners, make sure that the device
  860. // both supports multiple listeners and implements its own voice
  861. // management (as our voice virtualization does not work with more
  862. // than a single listener).
  863. if( !mDevice || !( mDevice->getCaps() & SFXDevice::CAPS_MultiListener )
  864. || !( mDevice->getCaps() & SFXDevice::CAPS_VoiceManagement ) )
  865. {
  866. Con::errorf( "SFXSystem::setNumListeners() - multiple listeners not supported on current configuration" );
  867. return;
  868. }
  869. mListeners.setSize( num );
  870. if( mDevice )
  871. mDevice->setNumListeners( num );
  872. }
  873. //-----------------------------------------------------------------------------
  874. void SFXSystem::setListener( U32 index, const MatrixF& transform, const Point3F& velocity )
  875. {
  876. if( index >= mListeners.size() )
  877. return;
  878. mListeners[ index ] = SFXListenerProperties( transform, velocity );
  879. if( mDevice )
  880. mDevice->setListener( index, mListeners[ index ] );
  881. }
  882. //-----------------------------------------------------------------------------
  883. void SFXSystem::notifyDescriptionChanged( SFXDescription* description )
  884. {
  885. SimSet* set = Sim::getSFXSourceSet();
  886. for( SimSet::iterator iter = set->begin(); iter != set->end(); ++ iter )
  887. {
  888. SFXSource* source = dynamic_cast< SFXSource* >( *iter );
  889. if( source && source->getDescription() == description )
  890. source->notifyDescriptionChanged();
  891. }
  892. }
  893. //-----------------------------------------------------------------------------
  894. void SFXSystem::notifyTrackChanged( SFXTrack* track )
  895. {
  896. SimSet* set = Sim::getSFXSourceSet();
  897. for( SimSet::iterator iter = set->begin(); iter != set->end(); ++ iter )
  898. {
  899. SFXSource* source = dynamic_cast< SFXSource* >( *iter );
  900. if( source && source->getTrack() == track )
  901. source->notifyTrackChanged();
  902. }
  903. }
  904. //-----------------------------------------------------------------------------
  905. void SFXSystem::dumpSources( StringBuilder* toString, bool excludeGroups )
  906. {
  907. SimSet* sources = Sim::getSFXSourceSet();
  908. if( !sources )
  909. return;
  910. bool isFirst = true;
  911. for( SimSet::iterator iter = sources->begin(); iter != sources->end(); ++ iter )
  912. {
  913. SFXSource* source = dynamic_cast< SFXSource* >( *iter );
  914. if( !source )
  915. continue;
  916. bool isGroup = typeid( *source ) == typeid( SFXSource );
  917. if( isGroup && excludeGroups )
  918. continue;
  919. bool isPlayOnce = false;
  920. for( U32 j = 0; j < mPlayOnceSources.size(); ++ j )
  921. if( mPlayOnceSources[ j ] == source )
  922. {
  923. isPlayOnce = true;
  924. break;
  925. }
  926. SFXSource* sourceGroup = source->getSourceGroup();
  927. SFXSound* sound = dynamic_cast< SFXSound* >( source );
  928. SFXController* controller = dynamic_cast< SFXController* >( source );
  929. if( toString )
  930. toString->format( "%s%5i: type=%s, status=%s, blocked=%s, volume=%.2f, priority=%.2f, virtual=%s, looping=%s, 3d=%s, group=%s, playtime=%.2f, playOnce=%s, streaming=%s, hasVoice=%s, track=%s",
  931. ( isFirst ? "" : "\n" ),
  932. source->getId(),
  933. ( isGroup ? "group" : sound ? "sound" : controller ? "list" : "other" ),
  934. source->isPlaying()
  935. ? "playing"
  936. : source->isPaused()
  937. ? "paused"
  938. : source->isStopped()
  939. ? "stopped"
  940. : "unknown",
  941. ( sound && sound->isBlocked() ? "1" : "0" ),
  942. source->getAttenuatedVolume(),
  943. source->getEffectivePriority(),
  944. ( sound && sound->isVirtualized() ? "1" : "0" ),
  945. ( sound && sound->isLooping() ) ? "1" : "0",
  946. source->getDescription()->mIs3D ? "1" : "0",
  947. sourceGroup ? sourceGroup->getName() : "",
  948. source->getElapsedPlayTimeCurrentCycle(),
  949. isPlayOnce ? "1" : "0",
  950. ( sound && sound->isStreaming() ? "1" : "0" ),
  951. ( sound && sound->hasVoice() ? "1" : "0" ),
  952. source->getTrack() ? source->getTrack()->getName() : ""
  953. );
  954. else
  955. Con::printf( "%5i: type=%s, status=%s, blocked=%s, volume=%.2f, priority=%.2f, virtual=%s, looping=%s, 3d=%s, group=%s, playtime=%.2f, playOnce=%s, streaming=%s, hasVoice=%s, track=%s",
  956. source->getId(),
  957. ( isGroup ? "group" : sound ? "sound" : controller ? "list" : "other" ),
  958. source->isPlaying()
  959. ? "playing"
  960. : source->isPaused()
  961. ? "paused"
  962. : source->isStopped()
  963. ? "stopped"
  964. : "unknown",
  965. ( sound && sound->isBlocked() ? "1" : "0" ),
  966. source->getAttenuatedVolume(),
  967. source->getEffectivePriority(),
  968. ( sound && sound->isVirtualized() ? "1" : "0" ),
  969. ( sound && sound->isLooping() ) ? "1" : "0",
  970. source->getDescription()->mIs3D ? "1" : "0",
  971. sourceGroup ? sourceGroup->getName() : "",
  972. source->getElapsedPlayTimeCurrentCycle(),
  973. isPlayOnce ? "1" : "0",
  974. ( sound && sound->isStreaming() ? "1" : "0" ),
  975. ( sound && sound->hasVoice() ? "1" : "0" ),
  976. source->getTrack() ? source->getTrack()->getName() : ""
  977. );
  978. isFirst = false;
  979. }
  980. }
  981. //=============================================================================
  982. // Console Functions.
  983. //=============================================================================
  984. // MARK: ---- Console Functions ----
  985. //-----------------------------------------------------------------------------
  986. DefineEngineFunction( sfxGetAvailableDevices, const char*, (),,
  987. "Get a list of all available sound devices.\n"
  988. "The return value will be a newline-separated list of entries where each line describes one available sound "
  989. "device. Each such line will have the following format:"
  990. "@verbatim\n"
  991. "provider TAB device TAB hasHardware TAB numMaxBuffers\n"
  992. "@endverbatim\n"
  993. "- provider: The name of the device provider (e.g. \"OpenAL\").\n"
  994. "- device: The name of the device as returned by the device layer.\n"
  995. "- hasHardware: Whether the device supports hardware mixing or not.\n"
  996. "- numMaxBuffers: The maximum number of concurrent voices supported by the device's mixer. If this limit "
  997. "limit is exceeded, i.e. if there are more active sounds playing at any one time, then voice virtualization "
  998. "will start culling voices and put them into virtualized playback mode. Voice virtualization may or may not "
  999. "be provided by the device itself; if not provided by the device, it will be provided by Torque's sound system.\n\n"
  1000. "@return A newline-separated list of information about all available sound devices.\n"
  1001. "@see sfxCreateDevice\n"
  1002. "@see sfxGetDeviceInfo\n\n"
  1003. "@see $SFX::DEVICE_INFO_PROVIDER\n\n"
  1004. "@see $SFX::DEVICE_INFO_NAME\n\n"
  1005. "@see $SFX::DEVICE_INFO_USEHARDWARE\n\n"
  1006. "@see $SFX::DEVICE_INFO_MAXBUFFERS\n\n"
  1007. "@ref SFX_devices\n"
  1008. "@ingroup SFX" )
  1009. {
  1010. const S32 bufferSize = 2048;
  1011. char* deviceList = Con::getReturnBuffer( bufferSize );
  1012. S32 len = bufferSize;
  1013. char *ptr = deviceList;
  1014. *ptr = 0;
  1015. SFXProvider* provider = SFXProvider::getFirstProvider();
  1016. while ( provider )
  1017. {
  1018. // List the devices in this provider.
  1019. const SFXDeviceInfoVector& deviceInfo = provider->getDeviceInfo();
  1020. for ( S32 d=0; d < deviceInfo.size(); d++ )
  1021. {
  1022. const SFXDeviceInfo* info = deviceInfo[d];
  1023. const char *providerName = provider->getName().c_str();
  1024. char *infoName = (char*)info->name.c_str();
  1025. dSprintf(ptr, len, "%s\t%s\t%s\t%i\n", providerName, infoName, info->hasHardware ? "1" : "0", info->maxBuffers);
  1026. ptr += dStrlen(ptr);
  1027. len = bufferSize - (ptr - deviceList);
  1028. if (len <= 0)
  1029. return deviceList;
  1030. }
  1031. provider = provider->getNextProvider();
  1032. }
  1033. return deviceList;
  1034. }
  1035. //-----------------------------------------------------------------------------
  1036. DefineEngineFunction( sfxCreateDevice, bool, ( const char* provider, const char* device, bool useHardware, S32 maxBuffers ),,
  1037. "Try to create a new sound device using the given properties.\n"
  1038. "If a sound device is currently initialized, it will be uninitialized first. However, be aware that in this case, "
  1039. "if this function fails, it will not restore the previously active device but rather leave the sound system in an "
  1040. "uninitialized state.\n\n"
  1041. "Sounds that are already playing while the new device is created will be temporarily transitioned to virtualized "
  1042. "playback and then resume normal playback once the device has been created.\n\n"
  1043. "In the core scripts, sound is automatically set up during startup in the sfxStartup() function.\n\n"
  1044. "@param provider The name of the device provider as returned by sfxGetAvailableDevices().\n"
  1045. "@param device The name of the device as returned by sfxGetAvailableDevices().\n"
  1046. "@param useHardware Whether to enabled hardware mixing on the device or not. Only relevant if supported by the given device.\n"
  1047. "@param maxBuffers The maximum number of concurrent voices for this device to use or -1 for the device to pick its own reasonable default."
  1048. "@return True if the initialization was successful, false if not.\n"
  1049. "@note This function must be called before any of the sound playback functions can be used.\n"
  1050. "@see sfxGetAvailableDevices\n"
  1051. "@see sfxGetDeviceInfo\n"
  1052. "@see sfxDeleteDevice\n\n"
  1053. "@ref SFX_devices\n"
  1054. "@ingroup SFX" )
  1055. {
  1056. return SFX->createDevice( provider, device, useHardware, maxBuffers, true );
  1057. }
  1058. //-----------------------------------------------------------------------------
  1059. DefineEngineFunction( sfxDeleteDevice, void, (),,
  1060. "Delete the currently active sound device and release all its resources.\n"
  1061. "SFXSources that are still playing will be transitioned to virtualized playback mode. "
  1062. "When creating a new device, they will automatically transition back to normal playback.\n\n"
  1063. "In the core scripts, this is done automatically for you during shutdown in the sfxShutdown() function.\n\n"
  1064. "@see sfxCreateDevice\n\n"
  1065. "@ref SFX_devices\n"
  1066. "@ingroup SFX" )
  1067. {
  1068. SFX->deleteDevice();
  1069. }
  1070. //-----------------------------------------------------------------------------
  1071. DefineEngineFunction( sfxGetDeviceInfo, const char*, (),,
  1072. "Return information about the currently active sound device.\n"
  1073. "The return value is a tab-delimited string of the following format:\n"
  1074. "@verbatim\n"
  1075. "provider TAB device TAB hasHardware TAB numMaxBuffers TAB caps\n"
  1076. "@endverbatim\n"
  1077. "- provider: The name of the device provider (e.g. \"OpenALD\").\n"
  1078. "- device: The name of the device as returned by the device layer.\n"
  1079. "- hasHardware: Whether the device supports hardware mixing or not.\n"
  1080. "- numMaxBuffers: The maximum number of concurrent voices supported by the device's mixer. If this limit "
  1081. "limit is exceeded, i.e. if there are more active sounds playing at any one time, then voice virtualization "
  1082. "will start culling voices and put them into virtualized playback mode. Voice virtualization may or may not "
  1083. "be provided by the device itself; if not provided by the device, it will be provided by Torque's sound system.\n"
  1084. "- caps: A bitfield of capability flags.\n\n"
  1085. "@return A tab-separated list of properties of the currently active sound device or the empty string if no sound device has been initialized.\n"
  1086. "@see sfxCreateDevice\n"
  1087. "@see sfxGetAvailableDevices\n\n"
  1088. "@see $SFX::DEVICE_INFO_PROVIDER\n\n"
  1089. "@see $SFX::DEVICE_INFO_NAME\n\n"
  1090. "@see $SFX::DEVICE_INFO_USEHARDWARE\n\n"
  1091. "@see $SFX::DEVICE_INFO_MAXBUFFERS\n\n"
  1092. "@see $SFX::DEVICE_INFO_CAPS\n\n"
  1093. "@see $SFX::DEVICE_CAPS_REVERB\n\n"
  1094. "@see $SFX::DEVICE_CAPS_VOICEMANAGEMENT\n\n"
  1095. "@see $SFX::DEVICE_CAPS_OCCLUSION\n\n"
  1096. "@see $SFX::DEVICE_CAPS_DSPEFFECTS\n\n"
  1097. "@see $SFX::DEVICE_CAPS_MULTILISTENER\n\n"
  1098. "@ref SFX_devices\n"
  1099. "@ingroup SFX" )
  1100. {
  1101. String deviceInfo = SFX->getDeviceInfoString();
  1102. if( deviceInfo.isEmpty() )
  1103. return "";
  1104. return Con::getReturnBuffer( deviceInfo );
  1105. }
  1106. //-----------------------------------------------------------------------------
  1107. static ConsoleDocFragment _sfxCreateSource1(
  1108. "@brief Create a new source that plays the given track.\n\n"
  1109. "The source will be returned in stopped state. Call SFXSource::play() to start playback.\n\n"
  1110. "In contrast to play-once sources, the source object will not be automatically deleted once playback stops. "
  1111. "Call delete() to release the source object.\n\n"
  1112. "This function will automatically create the right SFXSource type for the given SFXTrack.\n\n"
  1113. "@param track The track the source should play.\n"
  1114. "@return A new SFXSource for playback of the given track or 0 if no source could be created from the given track.\n\n"
  1115. "@note Trying to create a source for a device-specific track type will fail if the currently selected device "
  1116. "does not support the type. \n\n"
  1117. "@tsexample\n"
  1118. "// Create and play a source from a pre-existing profile:\n"
  1119. "%source = sfxCreateSource( SoundFileProfile );\n"
  1120. "%source.play();\n"
  1121. "@endtsexample\n\n"
  1122. "@ingroup SFX",
  1123. NULL,
  1124. "SFXSource sfxCreateSource( SFXTrack track );" );
  1125. static ConsoleDocFragment _sfxCreateSource2(
  1126. "@brief Create a new source that plays the given track and position its 3D sounds source at the given coordinates (if it is a 3D sound).\n\n"
  1127. "The source will be returned in stopped state. Call SFXSource::play() to start playback.\n\n"
  1128. "In contrast to play-once sources, the source object will not be automatically deleted once playback stops. "
  1129. "Call delete() to release the source object.\n\n"
  1130. "This function will automatically create the right SFXSource type for the given SFXTrack.\n\n"
  1131. "@param track The track the source should play.\n"
  1132. "@param x The X coordinate of the 3D sound position.\n"
  1133. "@param y The Y coordinate of the 3D sound position.\n"
  1134. "@param z The Z coordinate of the 3D sound position.\n"
  1135. "@return A new SFXSource for playback of the given track or 0 if no source could be created from the given track.\n\n"
  1136. "@note Trying to create a source for a device-specific track type will fail if the currently selected device "
  1137. "does not support the type. \n\n"
  1138. "@tsexample\n"
  1139. "// Create and play a source from a pre-existing profile and position it at (100, 200, 300):\n"
  1140. "%source = sfxCreateSource( SoundFileProfile, 100, 200, 300 );\n"
  1141. "%source.play();\n"
  1142. "@endtsexample\n\n"
  1143. "@ingroup SFX",
  1144. NULL,
  1145. "SFXSource sfxCreateSource( SFXTrack track, float x, float y, float z );" );
  1146. static ConsoleDocFragment _sfxCreateSource3(
  1147. "@brief Create a temporary SFXProfile from the given @a description and @a filename and then create and return a new source that plays the profile.\n\n"
  1148. "The source will be returned in stopped state. Call SFXSource::play() to start playback.\n\n"
  1149. "In contrast to play-once sources, the source object will not be automatically deleted once playback stops. "
  1150. "Call delete() to release the source object.\n\n"
  1151. "@param description The description to use for setting up the temporary SFXProfile.\n"
  1152. "@param filename Path to the sound file to play.\n"
  1153. "@return A new SFXSource for playback of the given track or 0 if no source or no temporary profile could be created.\n\n"
  1154. "@tsexample\n"
  1155. "// Create a source for a music track:\n"
  1156. "%source = sfxCreateSource( AudioMusicLoop2D, \"art/sound/backgroundMusic\" );\n"
  1157. "%source.play();\n"
  1158. "@endtsexample\n\n"
  1159. "@see SFXProfile\n\n"
  1160. "@ingroup SFX",
  1161. NULL,
  1162. "SFXSound sfxCreateSource( SFXDescription description, string filename );" );
  1163. static ConsoleDocFragment _sfxCreateSource4(
  1164. "@brief Create a temporary SFXProfile from the given @a description and @a filename and then create and return a new source that plays the profile. "
  1165. "Position the sound source at the given coordinates (if it is a 3D sound).\n\n"
  1166. "The source will be returned in stopped state. Call SFXSource::play() to start playback.\n\n"
  1167. "In contrast to play-once sources, the source object will not be automatically deleted once playback stops. "
  1168. "Call delete() to release the source object.\n\n"
  1169. "@param description The description to use for setting up the temporary SFXProfile.\n"
  1170. "@param filename Path to the sound file to play.\n"
  1171. "@param x The X coordinate of the 3D sound position.\n"
  1172. "@param y The Y coordinate of the 3D sound position.\n"
  1173. "@param z The Z coordinate of the 3D sound position.\n"
  1174. "@return A new SFXSource for playback of the given track or 0 if no source or no temporary profile could be created.\n\n"
  1175. "@tsexample\n"
  1176. "// Create a source for a music track and position it at (100, 200, 300):\n"
  1177. "%source = sfxCreateSource( AudioMusicLoop3D, \"art/sound/backgroundMusic\", 100, 200, 300 );\n"
  1178. "%source.play();\n"
  1179. "@endtsexample\n\n"
  1180. "@see SFXProfile\n\n"
  1181. "@ingroup SFX",
  1182. NULL,
  1183. "SFXSound sfxCreateSource( SFXDescription description, string filename, float x, float y, float z );" );
  1184. DefineEngineFunction( sfxCreateSource, S32, ( const char * sfxType, const char * arg0, const char * arg1, const char * arg2, const char * arg3 ), ("", "", "", ""),
  1185. "( SFXTrack track | ( SFXDescription description, string filename ) [, float x, float y, float z ] ) "
  1186. "Creates a new paused sound source using a profile or a description "
  1187. "and filename. The return value is the source which must be "
  1188. "released by delete().\n"
  1189. "@hide" )
  1190. {
  1191. SFXDescription* description = NULL;
  1192. SFXTrack* track = dynamic_cast< SFXTrack* >( Sim::findObject( sfxType ) );
  1193. if ( !track )
  1194. {
  1195. description = dynamic_cast< SFXDescription* >( Sim::findObject( sfxType ) );
  1196. if ( !description )
  1197. {
  1198. Con::printf( "Unable to locate sound track/description '%s'", sfxType );
  1199. return 0;
  1200. }
  1201. }
  1202. SFXSource* source = NULL;
  1203. if ( track )
  1204. {
  1205. // In this overloaded use of the function, arg0..arg2 are x, y, and z.
  1206. if ( String::isEmpty(arg0) )
  1207. {
  1208. source = SFX->createSource( track );
  1209. }
  1210. else
  1211. {
  1212. MatrixF transform;
  1213. transform.set( EulerF(0,0,0), Point3F( dAtof(arg0), dAtof(arg1), dAtof(arg2)) );
  1214. source = SFX->createSource( track, &transform );
  1215. }
  1216. }
  1217. else if ( description )
  1218. {
  1219. // In this use, arg0 is the filename, and arg1..arg3 are x, y, and z.
  1220. SFXProfile* tempProfile = new SFXProfile( description, StringTable->insert( arg0), true );
  1221. if( !tempProfile->registerObject() )
  1222. {
  1223. Con::errorf( "sfxCreateSource - unable to create profile" );
  1224. delete tempProfile;
  1225. }
  1226. else
  1227. {
  1228. if ( String::isEmpty(arg1) )
  1229. {
  1230. source = SFX->createSource( tempProfile );
  1231. }
  1232. else
  1233. {
  1234. MatrixF transform;
  1235. transform.set(EulerF(0,0,0), Point3F( dAtof(arg1), dAtof(arg2), dAtof(arg3) ));
  1236. source = SFX->createSource( tempProfile, &transform );
  1237. }
  1238. tempProfile->setAutoDelete( true );
  1239. }
  1240. }
  1241. if ( source )
  1242. return source->getId();
  1243. return 0;
  1244. }
  1245. //-----------------------------------------------------------------------------
  1246. static ConsoleDocFragment _sfxPlay1(
  1247. "@brief Start playback of the given source.\n\n"
  1248. "This is the same as calling SFXSource::play() directly.\n\n"
  1249. "@param source The source to start playing.\n\n"
  1250. "@return @a source.\n\n"
  1251. "@tsexample\n"
  1252. "// Create and play a source from a pre-existing profile:\n"
  1253. "%source = sfxCreateSource( SoundFileProfile );\n"
  1254. "%source.play();\n"
  1255. "@endtsexample\n\n"
  1256. "@ingroup SFX",
  1257. NULL,
  1258. "SFXSource sfxPlay( SFXSource source );" );
  1259. static ConsoleDocFragment _sfxPlay2(
  1260. "@brief Create a new play-once source for the given @a track and start playback of the source.\n\n"
  1261. "This is equivalent to calling sfxCreateSource() on @track and SFXSource::play() on the resulting source.\n\n"
  1262. "@param track The sound datablock to play.\n\n"
  1263. "@return The newly created play-once source or 0 if the creation failed.\n\n"
  1264. "@ref SFXSource_playonce\n\n"
  1265. "@ingroup SFX",
  1266. NULL,
  1267. "void sfxPlay( SFXTrack track );" );
  1268. static ConsoleDocFragment _sfxPlay3(
  1269. "@brief Create a new play-once source for the given @a track, position its 3D sound at the given coordinates (if the track's description "
  1270. "is set up for 3D sound) and start playback of the source.\n\n"
  1271. "This is equivalent to calling sfxCreateSource() on @track and SFXSource::play() on the resulting source.\n\n"
  1272. "@param track The sound datablock to play.\n\n"
  1273. "@param x The X coordinate of the 3D sound position.\n"
  1274. "@param y The Y coordinate of the 3D sound position.\n"
  1275. "@param z The Z coordinate of the 3D sound position.\n"
  1276. "@return The newly created play-once source or 0 if the creation failed.\n\n"
  1277. "@ref SFXSource_playonce\n\n"
  1278. "@ingroup SFX",
  1279. NULL,
  1280. "void sfxPlay( SFXTrack track, float x, float y, float z );" );
  1281. DefineEngineFunction( sfxPlay, S32, ( const char * trackName, const char * pointOrX, const char * y, const char * z ), ( "", "", ""),
  1282. "Start playing the given source or create a new source for the given track and play it.\n"
  1283. "@hide" )
  1284. {
  1285. if ( String::isEmpty(pointOrX) )
  1286. {
  1287. SFXSource* source = dynamic_cast<SFXSource*>( Sim::findObject( trackName ) );
  1288. if ( source )
  1289. {
  1290. source->play();
  1291. return source->getId();
  1292. }
  1293. }
  1294. SFXTrack* track = dynamic_cast<SFXTrack*>( Sim::findObject( trackName ) );
  1295. if ( !track )
  1296. {
  1297. Con::printf( "Unable to locate sfx track '%s'", trackName );
  1298. return 0;
  1299. }
  1300. Point3F pos(0.f, 0.f, 0.f);
  1301. if ( !String::isEmpty( pointOrX ) && String::isEmpty( y ) && String::isEmpty( z ) )
  1302. {
  1303. dSscanf( pointOrX, "%g %g %g", &pos.x, &pos.y, &pos.z );
  1304. }
  1305. else if( !String::isEmpty( pointOrX ) && !String::isEmpty( y ) && !String::isEmpty( z ) )
  1306. pos.set( dAtof(pointOrX), dAtof(y), dAtof(z) );
  1307. MatrixF transform;
  1308. transform.set( EulerF(0,0,0), pos );
  1309. SFXSource* source = SFX->playOnce( track, &transform );
  1310. if ( source )
  1311. return source->getId();
  1312. return 0;
  1313. }
  1314. //-----------------------------------------------------------------------------
  1315. static ConsoleDocFragment _sPlayOnce1(
  1316. "@brief Create a play-once source for the given @a asset.\n\n"
  1317. "Once playback has finished, the source will be automatically deleted in the next sound system update.\n"
  1318. "@param track The sound datablock.\n"
  1319. "@return A newly created temporary source in \"Playing\" state or 0 if the operation failed.\n\n"
  1320. "@ref SFXSource_playonce\n\n"
  1321. "@ingroup SFX",
  1322. NULL,
  1323. "SFXSource sfxPlayOnce( StringTableEntry assetID );"
  1324. );
  1325. static ConsoleDocFragment _sPlayOnce2(
  1326. "@brief Create a play-once source for the given given @a asset and position the source's 3D sound at the given coordinates "
  1327. "only if the asset is set up for 3D sound).\n\n"
  1328. "Once playback has finished, the source will be automatically deleted in the next sound system update.\n"
  1329. "@param assetId The sound asset.\n"
  1330. "@param x The X coordinate of the 3D sound position.\n"
  1331. "@param y The Y coordinate of the 3D sound position.\n"
  1332. "@param z The Z coordinate of the 3D sound position.\n"
  1333. "@param fadeInTime If >=0, this overrides the SFXDescription::fadeInTime value on the asset's definition.\n"
  1334. "@return A newly created temporary source in \"Playing\" state or 0 if the operation failed.\n\n"
  1335. "@tsexample\n"
  1336. "// Immediately start playing the given asset. Fade it in to full volume over 5 seconds.\n"
  1337. "sfxPlayOnce( ExampleModule:MusicTrack, 0, 0, 0, 5.f );\n"
  1338. "@endtsexample\n\n"
  1339. "@ref SFXSource_playonce\n\n"
  1340. "@ingroup SFX",
  1341. NULL,
  1342. "SFXSource sfxPlayOnce( StringTableEntry assetID, float x, float y, float z, float fadeInTime=-1 );"
  1343. );
  1344. DefineEngineFunction( sfxPlayOnce, S32, (StringTableEntry assetId, const char* arg0, const char * arg1, const char * arg2, const char * arg3 ), (StringTable->EmptyString(), "", "", "", "-1.0f"),
  1345. "SFXSource sfxPlayOnce( ( SFXTrack track | SFXDescription description, string filename ) [, float x, float y, float z, float fadeInTime=-1 ] ) "
  1346. "Create a new play-once source for the given profile or description+filename and start playback of the source.\n"
  1347. "@hide" )
  1348. {
  1349. SFXDescription* description = NULL;
  1350. if (assetId == StringTable->EmptyString())
  1351. {
  1352. Con::errorf( "sfxPlayOnce - Must Define a sound asset");
  1353. return 0;
  1354. }
  1355. SFXSource* source = NULL;
  1356. if (AssetDatabase.isDeclaredAsset(assetId))
  1357. {
  1358. AssetPtr<SoundAsset> tempSoundAsset;
  1359. tempSoundAsset = assetId;
  1360. if (String::isEmpty(arg0) || !tempSoundAsset->is3D())
  1361. {
  1362. source = SFX->playOnce(tempSoundAsset->getSfxProfile());
  1363. }
  1364. else
  1365. {
  1366. MatrixF transform;
  1367. transform.set(EulerF(0, 0, 0), Point3F(dAtof(arg0), dAtof(arg1), dAtof(arg2)));
  1368. source = SFX->playOnce(tempSoundAsset->getSfxProfile(), &transform, NULL, dAtof(arg3));
  1369. }
  1370. }
  1371. else
  1372. {
  1373. Con::errorf("sfxPlayOnce - Could not locate assetId '%s'", assetId);
  1374. return 0;
  1375. }
  1376. if( !source )
  1377. return 0;
  1378. return source->getId();
  1379. }
  1380. //-----------------------------------------------------------------------------
  1381. DefineEngineFunction( sfxStop, void, ( SFXSource* source ),,
  1382. "Stop playback of the given @a source.\n"
  1383. "This is equivalent to calling SFXSource::stop().\n\n"
  1384. "@param source The source to put into stopped state.\n\n"
  1385. "@ingroup SFX" )
  1386. {
  1387. if( source )
  1388. source->stop();
  1389. }
  1390. //-----------------------------------------------------------------------------
  1391. DefineEngineFunction( sfxStopAndDelete, void, ( SFXSource* source ),,
  1392. "Stop playback of the given @a source (if it is not already stopped) and delete the @a source.\n\n"
  1393. "The advantage of this function over directly calling delete() is that it will correctly "
  1394. "handle volume fades that may be configured on the source. Whereas calling delete() would immediately "
  1395. "stop playback and delete the source, this functionality will wait for the fade-out to play and only then "
  1396. "stop the source and delete it.\n\n"
  1397. "@param source A sound source.\n\n"
  1398. "@ref SFXSource_fades\n\n"
  1399. "@ingroup SFX" )
  1400. {
  1401. if( source )
  1402. SFX->stopAndDeleteSource( source );
  1403. }
  1404. //-----------------------------------------------------------------------------
  1405. DefineEngineFunction( sfxDeleteWhenStopped, void, ( SFXSource* source ),,
  1406. "Mark the given @a source for deletion as soon as it moves into stopped state.\n\n"
  1407. "This function will retroactively turn the given @a source into a play-once source (see @ref SFXSource_playonce).\n\n"
  1408. "@param source A sound source.\n\n"
  1409. "@ingroup SFX" )
  1410. {
  1411. if( source )
  1412. SFX->deleteWhenStopped( source );
  1413. }
  1414. //-----------------------------------------------------------------------------
  1415. DefineEngineFunction( sfxGetDistanceModel, SFXDistanceModel, (),,
  1416. "Get the falloff curve type currently being applied to 3D sounds.\n\n"
  1417. "@return The current distance model type.\n\n"
  1418. "@ref SFXSource_volume\n\n"
  1419. "@ref SFX_3d\n\n"
  1420. "@ingroup SFX" )
  1421. {
  1422. return SFX->getDistanceModel();
  1423. }
  1424. //-----------------------------------------------------------------------------
  1425. DefineEngineFunction( sfxSetDistanceModel, void, ( SFXDistanceModel model ),,
  1426. "Set the falloff curve type to use for distance-based volume attenuation of 3D sounds.\n\n"
  1427. "@param model The distance model to use for 3D sound.\n\n"
  1428. "@note This setting takes effect globally and is applied to all 3D sounds.\n\n"
  1429. "@ingroup SFX" )
  1430. {
  1431. SFX->setDistanceModel( model );
  1432. }
  1433. //-----------------------------------------------------------------------------
  1434. DefineEngineFunction( sfxGetDopplerFactor, F32, (),,
  1435. "Get the current global doppler effect setting.\n\n"
  1436. "@return The current global doppler effect scale factor (>=0).\n\n"
  1437. "@see sfxSetDopplerFactor\n\n"
  1438. "@ref SFXSource_doppler\n\n"
  1439. "@ingroup SFX" )
  1440. {
  1441. return SFX->getDopplerFactor();
  1442. }
  1443. //-----------------------------------------------------------------------------
  1444. DefineEngineFunction( sfxSetDopplerFactor, void, ( F32 value ),,
  1445. "Set the global doppler effect scale factor.\n"
  1446. "@param value The new doppler shift scale factor.\n"
  1447. "@pre @a value must be >= 0.\n"
  1448. "@see sfxGetDopplerFactor\n\n"
  1449. "@ref SFXSource_doppler\n\n"
  1450. "@ingroup SFX" )
  1451. {
  1452. if( value < 0.0f )
  1453. {
  1454. Con::errorf( "sfxSetDopplerFactor - factor must be >0" );
  1455. return;
  1456. }
  1457. SFX->setDopplerFactor( value );
  1458. }
  1459. //-----------------------------------------------------------------------------
  1460. DefineEngineFunction( sfxGetRolloffFactor, F32, (),,
  1461. "Get the current global scale factor applied to volume attenuation of 3D sounds in the logarithmic model.\n"
  1462. "@return The current scale factor for logarithmic 3D sound falloff curves.\n\n"
  1463. "@see sfxGetDistanceModel\n"
  1464. "@see SFXDistanceModel\n\n"
  1465. "@ref SFXSource_volume\n"
  1466. "@ref SFX_3d\n"
  1467. "@ingroup SFX" )
  1468. {
  1469. return SFX->getRolloffFactor();
  1470. }
  1471. //-----------------------------------------------------------------------------
  1472. DefineEngineFunction( sfxSetRolloffFactor, void, ( F32 value ),,
  1473. "Set the global scale factor to apply to volume attenuation of 3D sounds in the logarithmic model.\n"
  1474. "@param value The new scale factor for logarithmic 3D sound falloff curves.\n\n"
  1475. "@pre @a value must be > 0.\n"
  1476. "@note This function has no effect if the currently distance model is set to SFXDistanceModel::Linear.\n\n"
  1477. "@see sfxGetDistanceModel\n"
  1478. "@see SFXDistanceModel\n\n"
  1479. "@ref SFXSource_volume\n"
  1480. "@ref SFX_3d\n"
  1481. "@ingroup SFX" )
  1482. {
  1483. if( value <= 0.0f )
  1484. {
  1485. Con::errorf( "sfxSetRolloffFactor - factor must be >0" );
  1486. return;
  1487. }
  1488. SFX->setRolloffFactor( value );
  1489. }
  1490. //-----------------------------------------------------------------------------
  1491. DefineEngineFunction( sfxDumpSources, void, ( bool includeGroups ), ( false ),
  1492. "Dump information about all current SFXSource instances to the console.\n"
  1493. "The dump includes information about the playback status for each source, volume levels, virtualization, etc.\n"
  1494. "@param includeGroups If true, direct instances of SFXSources (which represent logical sound groups) will be included. "
  1495. "Otherwise only instances of subclasses of SFXSources are included in the dump.\n"
  1496. "@see SFXSource\n"
  1497. "@see sfxDumpSourcesToString\n"
  1498. "@ingroup SFX" )
  1499. {
  1500. SFX->dumpSources( NULL, !includeGroups );
  1501. }
  1502. //-----------------------------------------------------------------------------
  1503. DefineEngineFunction( sfxDumpSourcesToString, const char*, ( bool includeGroups ), ( false ),
  1504. "Dump information about all current SFXSource instances to a string.\n"
  1505. "The dump includes information about the playback status for each source, volume levels, virtualization, etc.\n"
  1506. "@param includeGroups If true, direct instances of SFXSources (which represent logical sound groups) will be included. "
  1507. "Otherwise only instances of subclasses of SFXSources are included in the dump.\n"
  1508. "@return A string containing a dump of information about all currently instantiated SFXSources.\n"
  1509. "@see SFXSource\n"
  1510. "@see sfxDumpSources\n"
  1511. "@ingroup SFX" )
  1512. {
  1513. StringBuilder str;
  1514. SFX->dumpSources( &str, !includeGroups );
  1515. return Con::getReturnBuffer( str );
  1516. }