sfxSystem.cpp 70 KB

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