sfxSystem.cpp 71 KB

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