sfxSystem.cpp 70 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882
  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. DefineConsoleFunction( sfxCreateSource, S32, ( const char * SFXType, const char * filename, const char * x, const char * y, const char * z ), ("", "", "", ""),
  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( SFXType ) );
  1197. if ( !track )
  1198. {
  1199. description = dynamic_cast< SFXDescription* >( Sim::findObject( SFXType ) );
  1200. if ( !description )
  1201. {
  1202. Con::printf( "Unable to locate sound track/description '%s'", SFXType );
  1203. return 0;
  1204. }
  1205. }
  1206. SFXSource* source = NULL;
  1207. if ( track )
  1208. {
  1209. if (dStrcmp(x, "") == 0)
  1210. {
  1211. source = SFX->createSource( track );
  1212. }
  1213. else
  1214. {
  1215. MatrixF transform;
  1216. transform.set( EulerF(0,0,0), Point3F( dAtof(x), dAtof(y), dAtof(z)) );
  1217. source = SFX->createSource( track, &transform );
  1218. }
  1219. }
  1220. else if ( description )
  1221. {
  1222. SFXProfile* tempProfile = new SFXProfile( description, StringTable->insert( filename ), true );
  1223. if( !tempProfile->registerObject() )
  1224. {
  1225. Con::errorf( "sfxCreateSource - unable to create profile" );
  1226. delete tempProfile;
  1227. }
  1228. else
  1229. {
  1230. if ( dStrcmp(x , "")==0 )
  1231. {
  1232. source = SFX->createSource( tempProfile );
  1233. }
  1234. else
  1235. {
  1236. MatrixF transform;
  1237. transform.set(EulerF(0,0,0), Point3F( dAtof(x),dAtof(y),dAtof(z) ));
  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. DefineConsoleFunction( sfxPlay, S32, ( const char * trackName, const char * pointOrX, const char * y, const char * 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 ( dStrcmp(pointOrX , "")==0 )
  1288. {
  1289. SFXSource* source = dynamic_cast<SFXSource*>( Sim::findObject( trackName ) );
  1290. if ( source )
  1291. {
  1292. source->play();
  1293. return source->getId();
  1294. }
  1295. }
  1296. SFXTrack* track = dynamic_cast<SFXTrack*>( Sim::findObject( trackName ) );
  1297. if ( !track )
  1298. {
  1299. Con::printf( "Unable to locate sfx track '%s'", trackName );
  1300. return 0;
  1301. }
  1302. Point3F pos(0.f, 0.f, 0.f);
  1303. if ( pointOrX != "" && y == ""&& z == "" )
  1304. {
  1305. dSscanf( pointOrX, "%g %g %g", &pos.x, &pos.y, &pos.z );
  1306. }
  1307. else if( pointOrX != "" && y != "" && z != "" )
  1308. pos.set( dAtof(pointOrX), dAtof(y), dAtof(z) );
  1309. MatrixF transform;
  1310. transform.set( EulerF(0,0,0), pos );
  1311. SFXSource* source = SFX->playOnce( track, &transform );
  1312. if ( source )
  1313. return source->getId();
  1314. return 0;
  1315. }
  1316. //-----------------------------------------------------------------------------
  1317. static ConsoleDocFragment _sPlayOnce1(
  1318. "@brief Create a play-once source for the given @a track.\n\n"
  1319. "Once playback has finished, the source will be automatically deleted in the next sound system update.\n"
  1320. "@param track The sound datablock.\n"
  1321. "@return A newly created temporary source in \"Playing\" state or 0 if the operation failed.\n\n"
  1322. "@ref SFXSource_playonce\n\n"
  1323. "@ingroup SFX",
  1324. NULL,
  1325. "SFXSource sfxPlayOnce( SFXTrack track );"
  1326. );
  1327. static ConsoleDocFragment _sPlayOnce2(
  1328. "@brief Create a play-once source for the given given @a track and position the source's 3D sound at the given coordinates "
  1329. "only if the track's description is set up for 3D sound).\n\n"
  1330. "Once playback has finished, the source will be automatically deleted in the next sound system update.\n"
  1331. "@param track The sound datablock.\n"
  1332. "@param x The X coordinate of the 3D sound position.\n"
  1333. "@param y The Y coordinate of the 3D sound position.\n"
  1334. "@param z The Z coordinate of the 3D sound position.\n"
  1335. "@param fadeInTime If >=0, this overrides the SFXDescription::fadeInTime value on the track's description.\n"
  1336. "@return A newly created temporary source in \"Playing\" state or 0 if the operation failed.\n\n"
  1337. "@tsexample\n"
  1338. "// Immediately start playing the given track. Fade it in to full volume over 5 seconds.\n"
  1339. "sfxPlayOnce( MusicTrack, 0, 0, 0, 5.f );\n"
  1340. "@endtsexample\n\n"
  1341. "@ref SFXSource_playonce\n\n"
  1342. "@ingroup SFX",
  1343. NULL,
  1344. "SFXSource sfxPlayOnce( SFXTrack track, float x, float y, float z, float fadeInTime=-1 );"
  1345. );
  1346. static ConsoleDocFragment _sPlayOnce3(
  1347. "@brief Create a new temporary SFXProfile from the given @a description and @a filename, then create a play-once source "
  1348. "for it and start playback.\n\n"
  1349. "Once playback has finished, the source will be automatically deleted in the next sound system update. If not referenced "
  1350. "otherwise by then, the temporary SFXProfile will also be deleted.\n"
  1351. "@param description The description to use for playback.\n"
  1352. "@param filename Path to the sound file to play.\n"
  1353. "@return A newly created temporary source in \"Playing\" state or 0 if the operation failed.\n\n"
  1354. "@tsexample\n"
  1355. "// Play a sound effect file once.\n"
  1356. "sfxPlayOnce( AudioEffects, \"art/sound/weapons/Weapon_pickup\" );\n"
  1357. "@endtsexample\n\n"
  1358. "@ref SFXSource_playonce\n\n"
  1359. "@ingroup SFX",
  1360. NULL,
  1361. "SFXSource sfxPlayOnce( SFXDescription description, string filename );"
  1362. );
  1363. static ConsoleDocFragment _sPlayOnce4(
  1364. "@brief Create a new temporary SFXProfile from the given @a description and @a filename, then create a play-once source "
  1365. "for it and start playback. Position the source's 3D sound at the given coordinates (only if the description "
  1366. "is set up for 3D sound).\n\n"
  1367. "Once playback has finished, the source will be automatically deleted in the next sound system update. If not referenced "
  1368. "otherwise by then, the temporary SFXProfile will also be deleted.\n"
  1369. "@param description The description to use for playback.\n"
  1370. "@param filename Path to the sound file to play.\n"
  1371. "@param x The X coordinate of the 3D sound position.\n"
  1372. "@param y The Y coordinate of the 3D sound position.\n"
  1373. "@param z The Z coordinate of the 3D sound position.\n"
  1374. "@param fadeInTime If >=0, this overrides the SFXDescription::fadeInTime value on the track's description.\n"
  1375. "@return A newly created temporary source in \"Playing\" state or 0 if the operation failed.\n\n"
  1376. "@tsexample\n"
  1377. "// Play a sound effect file once using a 3D sound with a default falloff placed at the origin.\n"
  1378. "sfxPlayOnce( AudioDefault3D, \"art/sound/weapons/Weapon_pickup\", 0, 0, 0 );\n"
  1379. "@endtsexample\n\n"
  1380. "@ref SFXSource_playonce\n\n"
  1381. "@ingroup SFX",
  1382. NULL,
  1383. "SFXSource sfxPlayOnce( SFXDescription description, string filename, float x, float y, float z, float fadeInTime=-1 );"
  1384. );
  1385. DefineConsoleFunction( sfxPlayOnce, S32, ( const char * SFXType, const char * filename, const char * x, const char * y, const char * z, F32 fadeInTime ), ("", "", "", -1.0f),
  1386. "SFXSource sfxPlayOnce( ( SFXTrack track | SFXDescription description, string filename ) [, float x, float y, float z, float fadeInTime=-1 ] ) "
  1387. "Create a new play-once source for the given profile or description+filename and start playback of the source.\n"
  1388. "@hide" )
  1389. {
  1390. SFXDescription* description = NULL;
  1391. SFXTrack* track = dynamic_cast< SFXTrack* >( Sim::findObject( SFXType ) );
  1392. if( !track )
  1393. {
  1394. description = dynamic_cast< SFXDescription* >( Sim::findObject( SFXType ) );
  1395. if( !description )
  1396. {
  1397. Con::errorf( "sfxPlayOnce - Unable to locate sound track/description '%s'", SFXType );
  1398. return 0;
  1399. }
  1400. }
  1401. SFXSource* source = NULL;
  1402. if( track )
  1403. {
  1404. if (dStrcmp(x, "") == 0)
  1405. {
  1406. source = SFX->playOnce( track );
  1407. }
  1408. else
  1409. {
  1410. MatrixF transform;
  1411. transform.set( EulerF( 0, 0, 0 ), Point3F( dAtof( x ), dAtof( y ),dAtof( z ) ) );
  1412. source = SFX->playOnce( track, &transform, NULL, fadeInTime );
  1413. }
  1414. }
  1415. else if( description )
  1416. {
  1417. SFXProfile* tempProfile = new SFXProfile( description, StringTable->insert( filename ), true );
  1418. if( !tempProfile->registerObject() )
  1419. {
  1420. Con::errorf( "sfxPlayOnce - unable to create profile" );
  1421. delete tempProfile;
  1422. }
  1423. else
  1424. {
  1425. if (dStrcmp(x, "") == 0)
  1426. source = SFX->playOnce( tempProfile );
  1427. else
  1428. {
  1429. MatrixF transform;
  1430. transform.set( EulerF( 0, 0, 0 ), Point3F( dAtof( x ), dAtof( y ),dAtof( z ) ) );
  1431. source = SFX->playOnce( tempProfile, &transform, NULL, fadeInTime );
  1432. }
  1433. // Set profile to auto-delete when SFXSource releases its reference.
  1434. // Also add to root group so the profile will get deleted when the
  1435. // Sim system is shut down before the SFXSource has played out.
  1436. tempProfile->setAutoDelete( true );
  1437. Sim::getRootGroup()->addObject( tempProfile );
  1438. }
  1439. }
  1440. if( !source )
  1441. return 0;
  1442. return source->getId();
  1443. }
  1444. //-----------------------------------------------------------------------------
  1445. DefineEngineFunction( sfxStop, void, ( SFXSource* source ),,
  1446. "Stop playback of the given @a source.\n"
  1447. "This is equivalent to calling SFXSource::stop().\n\n"
  1448. "@param source The source to put into stopped state.\n\n"
  1449. "@ingroup SFX" )
  1450. {
  1451. if( source )
  1452. source->stop();
  1453. }
  1454. //-----------------------------------------------------------------------------
  1455. DefineEngineFunction( sfxStopAndDelete, void, ( SFXSource* source ),,
  1456. "Stop playback of the given @a source (if it is not already stopped) and delete the @a source.\n\n"
  1457. "The advantage of this function over directly calling delete() is that it will correctly "
  1458. "handle volume fades that may be configured on the source. Whereas calling delete() would immediately "
  1459. "stop playback and delete the source, this functionality will wait for the fade-out to play and only then "
  1460. "stop the source and delete it.\n\n"
  1461. "@param source A sound source.\n\n"
  1462. "@ref SFXSource_fades\n\n"
  1463. "@ingroup SFX" )
  1464. {
  1465. if( source )
  1466. SFX->stopAndDeleteSource( source );
  1467. }
  1468. //-----------------------------------------------------------------------------
  1469. DefineEngineFunction( sfxDeleteWhenStopped, void, ( SFXSource* source ),,
  1470. "Mark the given @a source for deletion as soon as it moves into stopped state.\n\n"
  1471. "This function will retroactively turn the given @a source into a play-once source (see @ref SFXSource_playonce).\n\n"
  1472. "@param source A sound source.\n\n"
  1473. "@ingroup SFX" )
  1474. {
  1475. if( source )
  1476. SFX->deleteWhenStopped( source );
  1477. }
  1478. //-----------------------------------------------------------------------------
  1479. DefineEngineFunction( sfxGetDistanceModel, SFXDistanceModel, (),,
  1480. "Get the falloff curve type currently being applied to 3D sounds.\n\n"
  1481. "@return The current distance model type.\n\n"
  1482. "@ref SFXSource_volume\n\n"
  1483. "@ref SFX_3d\n\n"
  1484. "@ingroup SFX" )
  1485. {
  1486. return SFX->getDistanceModel();
  1487. }
  1488. //-----------------------------------------------------------------------------
  1489. DefineEngineFunction( sfxSetDistanceModel, void, ( SFXDistanceModel model ),,
  1490. "Set the falloff curve type to use for distance-based volume attenuation of 3D sounds.\n\n"
  1491. "@param model The distance model to use for 3D sound.\n\n"
  1492. "@note This setting takes effect globally and is applied to all 3D sounds.\n\n"
  1493. "@ingroup SFX" )
  1494. {
  1495. SFX->setDistanceModel( model );
  1496. }
  1497. //-----------------------------------------------------------------------------
  1498. DefineEngineFunction( sfxGetDopplerFactor, F32, (),,
  1499. "Get the current global doppler effect setting.\n\n"
  1500. "@return The current global doppler effect scale factor (>=0).\n\n"
  1501. "@see sfxSetDopplerFactor\n\n"
  1502. "@ref SFXSource_doppler\n\n"
  1503. "@ingroup SFX" )
  1504. {
  1505. return SFX->getDopplerFactor();
  1506. }
  1507. //-----------------------------------------------------------------------------
  1508. DefineEngineFunction( sfxSetDopplerFactor, void, ( F32 value ),,
  1509. "Set the global doppler effect scale factor.\n"
  1510. "@param value The new doppler shift scale factor.\n"
  1511. "@pre @a value must be >= 0.\n"
  1512. "@see sfxGetDopplerFactor\n\n"
  1513. "@ref SFXSource_doppler\n\n"
  1514. "@ingroup SFX" )
  1515. {
  1516. if( value < 0.0f )
  1517. {
  1518. Con::errorf( "sfxSetDopplerFactor - factor must be >0" );
  1519. return;
  1520. }
  1521. SFX->setDopplerFactor( value );
  1522. }
  1523. //-----------------------------------------------------------------------------
  1524. DefineEngineFunction( sfxGetRolloffFactor, F32, (),,
  1525. "Get the current global scale factor applied to volume attenuation of 3D sounds in the logarithmic model.\n"
  1526. "@return The current scale factor for logarithmic 3D sound falloff curves.\n\n"
  1527. "@see sfxGetDistanceModel\n"
  1528. "@see SFXDistanceModel\n\n"
  1529. "@ref SFXSource_volume\n"
  1530. "@ref SFX_3d\n"
  1531. "@ingroup SFX" )
  1532. {
  1533. return SFX->getRolloffFactor();
  1534. }
  1535. //-----------------------------------------------------------------------------
  1536. DefineEngineFunction( sfxSetRolloffFactor, void, ( F32 value ),,
  1537. "Set the global scale factor to apply to volume attenuation of 3D sounds in the logarithmic model.\n"
  1538. "@param value The new scale factor for logarithmic 3D sound falloff curves.\n\n"
  1539. "@pre @a value must be > 0.\n"
  1540. "@note This function has no effect if the currently distance model is set to SFXDistanceModel::Linear.\n\n"
  1541. "@see sfxGetDistanceModel\n"
  1542. "@see SFXDistanceModel\n\n"
  1543. "@ref SFXSource_volume\n"
  1544. "@ref SFX_3d\n"
  1545. "@ingroup SFX" )
  1546. {
  1547. if( value <= 0.0f )
  1548. {
  1549. Con::errorf( "sfxSetRolloffFactor - factor must be >0" );
  1550. return;
  1551. }
  1552. SFX->setRolloffFactor( value );
  1553. }
  1554. //-----------------------------------------------------------------------------
  1555. DefineEngineFunction( sfxDumpSources, void, ( bool includeGroups ), ( false ),
  1556. "Dump information about all current SFXSource instances to the console.\n"
  1557. "The dump includes information about the playback status for each source, volume levels, virtualization, etc.\n"
  1558. "@param includeGroups If true, direct instances of SFXSources (which represent logical sound groups) will be included. "
  1559. "Otherwise only instances of subclasses of SFXSources are included in the dump.\n"
  1560. "@see SFXSource\n"
  1561. "@see sfxDumpSourcesToString\n"
  1562. "@ingroup SFX" )
  1563. {
  1564. SFX->dumpSources( NULL, !includeGroups );
  1565. }
  1566. //-----------------------------------------------------------------------------
  1567. DefineEngineFunction( sfxDumpSourcesToString, const char*, ( bool includeGroups ), ( false ),
  1568. "Dump information about all current SFXSource instances to a string.\n"
  1569. "The dump includes information about the playback status for each source, volume levels, virtualization, etc.\n"
  1570. "@param includeGroups If true, direct instances of SFXSources (which represent logical sound groups) will be included. "
  1571. "Otherwise only instances of subclasses of SFXSources are included in the dump.\n"
  1572. "@return A string containing a dump of information about all currently instantiated SFXSources.\n"
  1573. "@see SFXSource\n"
  1574. "@see sfxDumpSources\n"
  1575. "@ingroup SFX" )
  1576. {
  1577. StringBuilder str;
  1578. SFX->dumpSources( &str, !includeGroups );
  1579. return Con::getReturnBuffer( str );
  1580. }