sfxSystem.cpp 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888
  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. const S32 bufferSize = 2048;
  1015. char* deviceList = Con::getReturnBuffer( bufferSize );
  1016. S32 len = bufferSize;
  1017. char *ptr = deviceList;
  1018. *ptr = 0;
  1019. SFXProvider* provider = SFXProvider::getFirstProvider();
  1020. while ( provider )
  1021. {
  1022. // List the devices in this provider.
  1023. const SFXDeviceInfoVector& deviceInfo = provider->getDeviceInfo();
  1024. for ( S32 d=0; d < deviceInfo.size(); d++ )
  1025. {
  1026. const SFXDeviceInfo* info = deviceInfo[d];
  1027. const char *providerName = provider->getName().c_str();
  1028. const char *infoName = info->name.c_str();
  1029. dSprintf(ptr, len, "%s\t%s\t%s\t%i\n", providerName, infoName, info->hasHardware ? "1" : "0", info->maxBuffers);
  1030. ptr += dStrlen(ptr);
  1031. len = bufferSize - (ptr - deviceList);
  1032. if (len <= 0)
  1033. return deviceList;
  1034. }
  1035. provider = provider->getNextProvider();
  1036. }
  1037. return deviceList;
  1038. }
  1039. //-----------------------------------------------------------------------------
  1040. DefineEngineFunction( sfxCreateDevice, bool, ( const char* provider, const char* device, bool useHardware, S32 maxBuffers ),,
  1041. "Try to create a new sound device using the given properties.\n"
  1042. "If a sound device is currently initialized, it will be uninitialized first. However, be aware that in this case, "
  1043. "if this function fails, it will not restore the previously active device but rather leave the sound system in an "
  1044. "uninitialized state.\n\n"
  1045. "Sounds that are already playing while the new device is created will be temporarily transitioned to virtualized "
  1046. "playback and then resume normal playback once the device has been created.\n\n"
  1047. "In the core scripts, sound is automatically set up during startup in the sfxStartup() function.\n\n"
  1048. "@param provider The name of the device provider as returned by sfxGetAvailableDevices().\n"
  1049. "@param device The name of the device as returned by sfxGetAvailableDevices().\n"
  1050. "@param useHardware Whether to enabled hardware mixing on the device or not. Only relevant if supported by the given device.\n"
  1051. "@param maxBuffers The maximum number of concurrent voices for this device to use or -1 for the device to pick its own reasonable default."
  1052. "@return True if the initialization was successful, false if not.\n"
  1053. "@note This function must be called before any of the sound playback functions can be used.\n"
  1054. "@see sfxGetAvailableDevices\n"
  1055. "@see sfxGetDeviceInfo\n"
  1056. "@see sfxDeleteDevice\n\n"
  1057. "@ref SFX_devices\n"
  1058. "@ingroup SFX" )
  1059. {
  1060. return SFX->createDevice( provider, device, useHardware, maxBuffers, true );
  1061. }
  1062. //-----------------------------------------------------------------------------
  1063. DefineEngineFunction( sfxDeleteDevice, void, (),,
  1064. "Delete the currently active sound device and release all its resources.\n"
  1065. "SFXSources that are still playing will be transitioned to virtualized playback mode. "
  1066. "When creating a new device, they will automatically transition back to normal playback.\n\n"
  1067. "In the core scripts, this is done automatically for you during shutdown in the sfxShutdown() function.\n\n"
  1068. "@see sfxCreateDevice\n\n"
  1069. "@ref SFX_devices\n"
  1070. "@ingroup SFX" )
  1071. {
  1072. SFX->deleteDevice();
  1073. }
  1074. //-----------------------------------------------------------------------------
  1075. DefineEngineFunction( sfxGetDeviceInfo, const char*, (),,
  1076. "Return information about the currently active sound device.\n"
  1077. "The return value is a tab-delimited string of the following format:\n"
  1078. "@verbatim\n"
  1079. "provider TAB device TAB hasHardware TAB numMaxBuffers TAB caps\n"
  1080. "@endverbatim\n"
  1081. "- provider: The name of the device provider (e.g. \"FMOD\").\n"
  1082. "- device: The name of the device as returned by the device layer.\n"
  1083. "- hasHardware: Whether the device supports hardware mixing or not.\n"
  1084. "- numMaxBuffers: The maximum number of concurrent voices supported by the device's mixer. If this limit "
  1085. "limit is exceeded, i.e. if there are more active sounds playing at any one time, then voice virtualization "
  1086. "will start culling voices and put them into virtualized playback mode. Voice virtualization may or may not "
  1087. "be provided by the device itself; if not provided by the device, it will be provided by Torque's sound system.\n"
  1088. "- caps: A bitfield of capability flags.\n\n"
  1089. "@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"
  1090. "@see sfxCreateDevice\n"
  1091. "@see sfxGetAvailableDevices\n\n"
  1092. "@see $SFX::DEVICE_INFO_PROVIDER\n\n"
  1093. "@see $SFX::DEVICE_INFO_NAME\n\n"
  1094. "@see $SFX::DEVICE_INFO_USEHARDWARE\n\n"
  1095. "@see $SFX::DEVICE_INFO_MAXBUFFERS\n\n"
  1096. "@see $SFX::DEVICE_INFO_CAPS\n\n"
  1097. "@see $SFX::DEVICE_CAPS_REVERB\n\n"
  1098. "@see $SFX::DEVICE_CAPS_VOICEMANAGEMENT\n\n"
  1099. "@see $SFX::DEVICE_CAPS_OCCLUSION\n\n"
  1100. "@see $SFX::DEVICE_CAPS_DSPEFFECTS\n\n"
  1101. "@see $SFX::DEVICE_CAPS_MULTILISTENER\n\n"
  1102. "@see $SFX::DEVICE_CAPS_FMODDESIGNER\n\n"
  1103. "@ref SFX_devices\n"
  1104. "@ingroup SFX" )
  1105. {
  1106. String deviceInfo = SFX->getDeviceInfoString();
  1107. if( deviceInfo.isEmpty() )
  1108. return "";
  1109. return Con::getReturnBuffer( deviceInfo );
  1110. }
  1111. //-----------------------------------------------------------------------------
  1112. static ConsoleDocFragment _sfxCreateSource1(
  1113. "@brief Create a new source that plays the given track.\n\n"
  1114. "The source will be returned in stopped state. Call SFXSource::play() to start playback.\n\n"
  1115. "In contrast to play-once sources, the source object will not be automatically deleted once playback stops. "
  1116. "Call delete() to release the source object.\n\n"
  1117. "This function will automatically create the right SFXSource type for the given SFXTrack.\n\n"
  1118. "@param track The track the source should play.\n"
  1119. "@return A new SFXSource for playback of the given track or 0 if no source could be created from the given track.\n\n"
  1120. "@note Trying to create a source for a device-specific track type will fail if the currently selected device "
  1121. "does not support the type. Example: trying to create a source for an FMOD Designer event when not running FMOD.\n\n"
  1122. "@tsexample\n"
  1123. "// Create and play a source from a pre-existing profile:\n"
  1124. "%source = sfxCreateSource( SoundFileProfile );\n"
  1125. "%source.play();\n"
  1126. "@endtsexample\n\n"
  1127. "@ingroup SFX",
  1128. NULL,
  1129. "SFXSource sfxCreateSource( SFXTrack track );" );
  1130. static ConsoleDocFragment _sfxCreateSource2(
  1131. "@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"
  1132. "The source will be returned in stopped state. Call SFXSource::play() to start playback.\n\n"
  1133. "In contrast to play-once sources, the source object will not be automatically deleted once playback stops. "
  1134. "Call delete() to release the source object.\n\n"
  1135. "This function will automatically create the right SFXSource type for the given SFXTrack.\n\n"
  1136. "@param track The track the source should play.\n"
  1137. "@param x The X coordinate of the 3D sound position.\n"
  1138. "@param y The Y coordinate of the 3D sound position.\n"
  1139. "@param z The Z coordinate of the 3D sound position.\n"
  1140. "@return A new SFXSource for playback of the given track or 0 if no source could be created from the given track.\n\n"
  1141. "@note Trying to create a source for a device-specific track type will fail if the currently selected device "
  1142. "does not support the type. Example: trying to create a source for an FMOD Designer event when not running FMOD.\n\n"
  1143. "@tsexample\n"
  1144. "// Create and play a source from a pre-existing profile and position it at (100, 200, 300):\n"
  1145. "%source = sfxCreateSource( SoundFileProfile, 100, 200, 300 );\n"
  1146. "%source.play();\n"
  1147. "@endtsexample\n\n"
  1148. "@ingroup SFX",
  1149. NULL,
  1150. "SFXSource sfxCreateSource( SFXTrack track, float x, float y, float z );" );
  1151. static ConsoleDocFragment _sfxCreateSource3(
  1152. "@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"
  1153. "The source will be returned in stopped state. Call SFXSource::play() to start playback.\n\n"
  1154. "In contrast to play-once sources, the source object will not be automatically deleted once playback stops. "
  1155. "Call delete() to release the source object.\n\n"
  1156. "@param description The description to use for setting up the temporary SFXProfile.\n"
  1157. "@param filename Path to the sound file to play.\n"
  1158. "@return A new SFXSource for playback of the given track or 0 if no source or no temporary profile could be created.\n\n"
  1159. "@tsexample\n"
  1160. "// Create a source for a music track:\n"
  1161. "%source = sfxCreateSource( AudioMusicLoop2D, \"art/sound/backgroundMusic\" );\n"
  1162. "%source.play();\n"
  1163. "@endtsexample\n\n"
  1164. "@see SFXProfile\n\n"
  1165. "@ingroup SFX",
  1166. NULL,
  1167. "SFXSound sfxCreateSource( SFXDescription description, string filename );" );
  1168. static ConsoleDocFragment _sfxCreateSource4(
  1169. "@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. "
  1170. "Position the sound source at the given coordinates (if it is a 3D sound).\n\n"
  1171. "The source will be returned in stopped state. Call SFXSource::play() to start playback.\n\n"
  1172. "In contrast to play-once sources, the source object will not be automatically deleted once playback stops. "
  1173. "Call delete() to release the source object.\n\n"
  1174. "@param description The description to use for setting up the temporary SFXProfile.\n"
  1175. "@param filename Path to the sound file to play.\n"
  1176. "@param x The X coordinate of the 3D sound position.\n"
  1177. "@param y The Y coordinate of the 3D sound position.\n"
  1178. "@param z The Z coordinate of the 3D sound position.\n"
  1179. "@return A new SFXSource for playback of the given track or 0 if no source or no temporary profile could be created.\n\n"
  1180. "@tsexample\n"
  1181. "// Create a source for a music track and position it at (100, 200, 300):\n"
  1182. "%source = sfxCreateSource( AudioMusicLoop3D, \"art/sound/backgroundMusic\", 100, 200, 300 );\n"
  1183. "%source.play();\n"
  1184. "@endtsexample\n\n"
  1185. "@see SFXProfile\n\n"
  1186. "@ingroup SFX",
  1187. NULL,
  1188. "SFXSound sfxCreateSource( SFXDescription description, string filename, float x, float y, float z );" );
  1189. DefineConsoleFunction( sfxCreateSource, S32, ( const char * sfxType, const char * arg0, const char * arg1, const char * arg2, const char * arg3 ), ("", "", "", ""),
  1190. "( SFXTrack track | ( SFXDescription description, string filename ) [, float x, float y, float z ] ) "
  1191. "Creates a new paused sound source using a profile or a description "
  1192. "and filename. The return value is the source which must be "
  1193. "released by delete().\n"
  1194. "@hide" )
  1195. {
  1196. SFXDescription* description = NULL;
  1197. SFXTrack* track = dynamic_cast< SFXTrack* >( Sim::findObject( sfxType ) );
  1198. if ( !track )
  1199. {
  1200. description = dynamic_cast< SFXDescription* >( Sim::findObject( sfxType ) );
  1201. if ( !description )
  1202. {
  1203. Con::printf( "Unable to locate sound track/description '%s'", sfxType );
  1204. return 0;
  1205. }
  1206. }
  1207. SFXSource* source = NULL;
  1208. if ( track )
  1209. {
  1210. // In this overloaded use of the function, arg0..arg2 are x, y, and z.
  1211. if ( dStrIsEmpty(arg0) )
  1212. {
  1213. source = SFX->createSource( track );
  1214. }
  1215. else
  1216. {
  1217. MatrixF transform;
  1218. transform.set( EulerF(0,0,0), Point3F( dAtof(arg0), dAtof(arg1), dAtof(arg2)) );
  1219. source = SFX->createSource( track, &transform );
  1220. }
  1221. }
  1222. else if ( description )
  1223. {
  1224. // In this use, arg0 is the filename, and arg1..arg3 are x, y, and z.
  1225. SFXProfile* tempProfile = new SFXProfile( description, StringTable->insert( arg0), true );
  1226. if( !tempProfile->registerObject() )
  1227. {
  1228. Con::errorf( "sfxCreateSource - unable to create profile" );
  1229. delete tempProfile;
  1230. }
  1231. else
  1232. {
  1233. if ( dStrIsEmpty(arg1) )
  1234. {
  1235. source = SFX->createSource( tempProfile );
  1236. }
  1237. else
  1238. {
  1239. MatrixF transform;
  1240. transform.set(EulerF(0,0,0), Point3F( dAtof(arg1), dAtof(arg2), dAtof(arg3) ));
  1241. source = SFX->createSource( tempProfile, &transform );
  1242. }
  1243. tempProfile->setAutoDelete( true );
  1244. }
  1245. }
  1246. if ( source )
  1247. return source->getId();
  1248. return 0;
  1249. }
  1250. //-----------------------------------------------------------------------------
  1251. static ConsoleDocFragment _sfxPlay1(
  1252. "@brief Start playback of the given source.\n\n"
  1253. "This is the same as calling SFXSource::play() directly.\n\n"
  1254. "@param source The source to start playing.\n\n"
  1255. "@return @a source.\n\n"
  1256. "@tsexample\n"
  1257. "// Create and play a source from a pre-existing profile:\n"
  1258. "%source = sfxCreateSource( SoundFileProfile );\n"
  1259. "%source.play();\n"
  1260. "@endtsexample\n\n"
  1261. "@ingroup SFX",
  1262. NULL,
  1263. "SFXSource sfxPlay( SFXSource source );" );
  1264. static ConsoleDocFragment _sfxPlay2(
  1265. "@brief Create a new play-once source for the given @a track and start playback of the source.\n\n"
  1266. "This is equivalent to calling sfxCreateSource() on @track and SFXSource::play() on the resulting source.\n\n"
  1267. "@param track The sound datablock to play.\n\n"
  1268. "@return The newly created play-once source or 0 if the creation failed.\n\n"
  1269. "@ref SFXSource_playonce\n\n"
  1270. "@ingroup SFX",
  1271. NULL,
  1272. "void sfxPlay( SFXTrack track );" );
  1273. static ConsoleDocFragment _sfxPlay3(
  1274. "@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 "
  1275. "is set up for 3D sound) and start playback of the source.\n\n"
  1276. "This is equivalent to calling sfxCreateSource() on @track and SFXSource::play() on the resulting source.\n\n"
  1277. "@param track The sound datablock to play.\n\n"
  1278. "@param x The X coordinate of the 3D sound position.\n"
  1279. "@param y The Y coordinate of the 3D sound position.\n"
  1280. "@param z The Z coordinate of the 3D sound position.\n"
  1281. "@return The newly created play-once source or 0 if the creation failed.\n\n"
  1282. "@ref SFXSource_playonce\n\n"
  1283. "@ingroup SFX",
  1284. NULL,
  1285. "void sfxPlay( SFXTrack track, float x, float y, float z );" );
  1286. DefineConsoleFunction( sfxPlay, S32, ( const char * trackName, const char * pointOrX, const char * y, const char * z ), ( "", "", ""),
  1287. "Start playing the given source or create a new source for the given track and play it.\n"
  1288. "@hide" )
  1289. {
  1290. if ( dStrIsEmpty(pointOrX) )
  1291. {
  1292. SFXSource* source = dynamic_cast<SFXSource*>( Sim::findObject( trackName ) );
  1293. if ( source )
  1294. {
  1295. source->play();
  1296. return source->getId();
  1297. }
  1298. }
  1299. SFXTrack* track = dynamic_cast<SFXTrack*>( Sim::findObject( trackName ) );
  1300. if ( !track )
  1301. {
  1302. Con::printf( "Unable to locate sfx track '%s'", trackName );
  1303. return 0;
  1304. }
  1305. Point3F pos(0.f, 0.f, 0.f);
  1306. if ( !dStrIsEmpty( pointOrX ) && dStrIsEmpty( y ) && dStrIsEmpty( z ) )
  1307. {
  1308. dSscanf( pointOrX, "%g %g %g", &pos.x, &pos.y, &pos.z );
  1309. }
  1310. else if( !dStrIsEmpty( pointOrX ) && !dStrIsEmpty( y ) && !dStrIsEmpty( z ) )
  1311. pos.set( dAtof(pointOrX), dAtof(y), dAtof(z) );
  1312. MatrixF transform;
  1313. transform.set( EulerF(0,0,0), pos );
  1314. SFXSource* source = SFX->playOnce( track, &transform );
  1315. if ( source )
  1316. return source->getId();
  1317. return 0;
  1318. }
  1319. //-----------------------------------------------------------------------------
  1320. static ConsoleDocFragment _sPlayOnce1(
  1321. "@brief Create a play-once source for the given @a track.\n\n"
  1322. "Once playback has finished, the source will be automatically deleted in the next sound system update.\n"
  1323. "@param track The sound datablock.\n"
  1324. "@return A newly created temporary source in \"Playing\" state or 0 if the operation failed.\n\n"
  1325. "@ref SFXSource_playonce\n\n"
  1326. "@ingroup SFX",
  1327. NULL,
  1328. "SFXSource sfxPlayOnce( SFXTrack track );"
  1329. );
  1330. static ConsoleDocFragment _sPlayOnce2(
  1331. "@brief Create a play-once source for the given given @a track and position the source's 3D sound at the given coordinates "
  1332. "only if the track's description is set up for 3D sound).\n\n"
  1333. "Once playback has finished, the source will be automatically deleted in the next sound system update.\n"
  1334. "@param track The sound datablock.\n"
  1335. "@param x The X coordinate of the 3D sound position.\n"
  1336. "@param y The Y coordinate of the 3D sound position.\n"
  1337. "@param z The Z coordinate of the 3D sound position.\n"
  1338. "@param fadeInTime If >=0, this overrides the SFXDescription::fadeInTime value on the track's description.\n"
  1339. "@return A newly created temporary source in \"Playing\" state or 0 if the operation failed.\n\n"
  1340. "@tsexample\n"
  1341. "// Immediately start playing the given track. Fade it in to full volume over 5 seconds.\n"
  1342. "sfxPlayOnce( MusicTrack, 0, 0, 0, 5.f );\n"
  1343. "@endtsexample\n\n"
  1344. "@ref SFXSource_playonce\n\n"
  1345. "@ingroup SFX",
  1346. NULL,
  1347. "SFXSource sfxPlayOnce( SFXTrack track, float x, float y, float z, float fadeInTime=-1 );"
  1348. );
  1349. static ConsoleDocFragment _sPlayOnce3(
  1350. "@brief Create a new temporary SFXProfile from the given @a description and @a filename, then create a play-once source "
  1351. "for it and start playback.\n\n"
  1352. "Once playback has finished, the source will be automatically deleted in the next sound system update. If not referenced "
  1353. "otherwise by then, the temporary SFXProfile will also be deleted.\n"
  1354. "@param description The description to use for playback.\n"
  1355. "@param filename Path to the sound file to play.\n"
  1356. "@return A newly created temporary source in \"Playing\" state or 0 if the operation failed.\n\n"
  1357. "@tsexample\n"
  1358. "// Play a sound effect file once.\n"
  1359. "sfxPlayOnce( AudioEffects, \"art/sound/weapons/Weapon_pickup\" );\n"
  1360. "@endtsexample\n\n"
  1361. "@ref SFXSource_playonce\n\n"
  1362. "@ingroup SFX",
  1363. NULL,
  1364. "SFXSource sfxPlayOnce( SFXDescription description, string filename );"
  1365. );
  1366. static ConsoleDocFragment _sPlayOnce4(
  1367. "@brief Create a new temporary SFXProfile from the given @a description and @a filename, then create a play-once source "
  1368. "for it and start playback. Position the source's 3D sound at the given coordinates (only if the description "
  1369. "is set up for 3D sound).\n\n"
  1370. "Once playback has finished, the source will be automatically deleted in the next sound system update. If not referenced "
  1371. "otherwise by then, the temporary SFXProfile will also be deleted.\n"
  1372. "@param description The description to use for playback.\n"
  1373. "@param filename Path to the sound file to play.\n"
  1374. "@param x The X coordinate of the 3D sound position.\n"
  1375. "@param y The Y coordinate of the 3D sound position.\n"
  1376. "@param z The Z coordinate of the 3D sound position.\n"
  1377. "@param fadeInTime If >=0, this overrides the SFXDescription::fadeInTime value on the track's description.\n"
  1378. "@return A newly created temporary source in \"Playing\" state or 0 if the operation failed.\n\n"
  1379. "@tsexample\n"
  1380. "// Play a sound effect file once using a 3D sound with a default falloff placed at the origin.\n"
  1381. "sfxPlayOnce( AudioDefault3D, \"art/sound/weapons/Weapon_pickup\", 0, 0, 0 );\n"
  1382. "@endtsexample\n\n"
  1383. "@ref SFXSource_playonce\n\n"
  1384. "@ingroup SFX",
  1385. NULL,
  1386. "SFXSource sfxPlayOnce( SFXDescription description, string filename, float x, float y, float z, float fadeInTime=-1 );"
  1387. );
  1388. DefineConsoleFunction( sfxPlayOnce, S32, ( const char * sfxType, const char * arg0, const char * arg1, const char * arg2, const char * arg3, const char* arg4 ), ("", "", "", "", "-1.0f"),
  1389. "SFXSource sfxPlayOnce( ( SFXTrack track | SFXDescription description, string filename ) [, float x, float y, float z, float fadeInTime=-1 ] ) "
  1390. "Create a new play-once source for the given profile or description+filename and start playback of the source.\n"
  1391. "@hide" )
  1392. {
  1393. SFXDescription* description = NULL;
  1394. SFXTrack* track = dynamic_cast< SFXTrack* >( Sim::findObject( sfxType ) );
  1395. if( !track )
  1396. {
  1397. description = dynamic_cast< SFXDescription* >( Sim::findObject( sfxType ) );
  1398. if( !description )
  1399. {
  1400. Con::errorf( "sfxPlayOnce - Unable to locate sound track/description '%s'", sfxType );
  1401. return 0;
  1402. }
  1403. }
  1404. SFXSource* source = NULL;
  1405. if( track )
  1406. {
  1407. // In this overloaded use, arg0..arg2 are x, y, z, and arg3 is the fadeInTime.
  1408. if (dStrIsEmpty(arg0))
  1409. {
  1410. source = SFX->playOnce( track );
  1411. }
  1412. else
  1413. {
  1414. MatrixF transform;
  1415. transform.set( EulerF( 0, 0, 0 ), Point3F( dAtof( arg0 ), dAtof( arg1 ),dAtof( arg2 ) ) );
  1416. source = SFX->playOnce( track, &transform, NULL, dAtof( arg3 ) );
  1417. }
  1418. }
  1419. else if( description )
  1420. {
  1421. // In this overload, arg0 is the filename, arg1..arg3 are x, y, z, and arg4 is fadeInTime.
  1422. SFXProfile* tempProfile = new SFXProfile( description, StringTable->insert( arg0 ), true );
  1423. if( !tempProfile->registerObject() )
  1424. {
  1425. Con::errorf( "sfxPlayOnce - unable to create profile" );
  1426. delete tempProfile;
  1427. }
  1428. else
  1429. {
  1430. if (dStrIsEmpty(arg1))
  1431. source = SFX->playOnce( tempProfile );
  1432. else
  1433. {
  1434. MatrixF transform;
  1435. transform.set( EulerF( 0, 0, 0 ), Point3F( dAtof( arg1 ), dAtof( arg2 ),dAtof( arg3 ) ) );
  1436. source = SFX->playOnce( tempProfile, &transform, NULL, dAtof( arg4 ) );
  1437. }
  1438. // Set profile to auto-delete when SFXSource releases its reference.
  1439. // Also add to root group so the profile will get deleted when the
  1440. // Sim system is shut down before the SFXSource has played out.
  1441. tempProfile->setAutoDelete( true );
  1442. Sim::getRootGroup()->addObject( tempProfile );
  1443. }
  1444. }
  1445. if( !source )
  1446. return 0;
  1447. return source->getId();
  1448. }
  1449. //-----------------------------------------------------------------------------
  1450. DefineEngineFunction( sfxStop, void, ( SFXSource* source ),,
  1451. "Stop playback of the given @a source.\n"
  1452. "This is equivalent to calling SFXSource::stop().\n\n"
  1453. "@param source The source to put into stopped state.\n\n"
  1454. "@ingroup SFX" )
  1455. {
  1456. if( source )
  1457. source->stop();
  1458. }
  1459. //-----------------------------------------------------------------------------
  1460. DefineEngineFunction( sfxStopAndDelete, void, ( SFXSource* source ),,
  1461. "Stop playback of the given @a source (if it is not already stopped) and delete the @a source.\n\n"
  1462. "The advantage of this function over directly calling delete() is that it will correctly "
  1463. "handle volume fades that may be configured on the source. Whereas calling delete() would immediately "
  1464. "stop playback and delete the source, this functionality will wait for the fade-out to play and only then "
  1465. "stop the source and delete it.\n\n"
  1466. "@param source A sound source.\n\n"
  1467. "@ref SFXSource_fades\n\n"
  1468. "@ingroup SFX" )
  1469. {
  1470. if( source )
  1471. SFX->stopAndDeleteSource( source );
  1472. }
  1473. //-----------------------------------------------------------------------------
  1474. DefineEngineFunction( sfxDeleteWhenStopped, void, ( SFXSource* source ),,
  1475. "Mark the given @a source for deletion as soon as it moves into stopped state.\n\n"
  1476. "This function will retroactively turn the given @a source into a play-once source (see @ref SFXSource_playonce).\n\n"
  1477. "@param source A sound source.\n\n"
  1478. "@ingroup SFX" )
  1479. {
  1480. if( source )
  1481. SFX->deleteWhenStopped( source );
  1482. }
  1483. //-----------------------------------------------------------------------------
  1484. DefineEngineFunction( sfxGetDistanceModel, SFXDistanceModel, (),,
  1485. "Get the falloff curve type currently being applied to 3D sounds.\n\n"
  1486. "@return The current distance model type.\n\n"
  1487. "@ref SFXSource_volume\n\n"
  1488. "@ref SFX_3d\n\n"
  1489. "@ingroup SFX" )
  1490. {
  1491. return SFX->getDistanceModel();
  1492. }
  1493. //-----------------------------------------------------------------------------
  1494. DefineEngineFunction( sfxSetDistanceModel, void, ( SFXDistanceModel model ),,
  1495. "Set the falloff curve type to use for distance-based volume attenuation of 3D sounds.\n\n"
  1496. "@param model The distance model to use for 3D sound.\n\n"
  1497. "@note This setting takes effect globally and is applied to all 3D sounds.\n\n"
  1498. "@ingroup SFX" )
  1499. {
  1500. SFX->setDistanceModel( model );
  1501. }
  1502. //-----------------------------------------------------------------------------
  1503. DefineEngineFunction( sfxGetDopplerFactor, F32, (),,
  1504. "Get the current global doppler effect setting.\n\n"
  1505. "@return The current global doppler effect scale factor (>=0).\n\n"
  1506. "@see sfxSetDopplerFactor\n\n"
  1507. "@ref SFXSource_doppler\n\n"
  1508. "@ingroup SFX" )
  1509. {
  1510. return SFX->getDopplerFactor();
  1511. }
  1512. //-----------------------------------------------------------------------------
  1513. DefineEngineFunction( sfxSetDopplerFactor, void, ( F32 value ),,
  1514. "Set the global doppler effect scale factor.\n"
  1515. "@param value The new doppler shift scale factor.\n"
  1516. "@pre @a value must be >= 0.\n"
  1517. "@see sfxGetDopplerFactor\n\n"
  1518. "@ref SFXSource_doppler\n\n"
  1519. "@ingroup SFX" )
  1520. {
  1521. if( value < 0.0f )
  1522. {
  1523. Con::errorf( "sfxSetDopplerFactor - factor must be >0" );
  1524. return;
  1525. }
  1526. SFX->setDopplerFactor( value );
  1527. }
  1528. //-----------------------------------------------------------------------------
  1529. DefineEngineFunction( sfxGetRolloffFactor, F32, (),,
  1530. "Get the current global scale factor applied to volume attenuation of 3D sounds in the logarithmic model.\n"
  1531. "@return The current scale factor for logarithmic 3D sound falloff curves.\n\n"
  1532. "@see sfxGetDistanceModel\n"
  1533. "@see SFXDistanceModel\n\n"
  1534. "@ref SFXSource_volume\n"
  1535. "@ref SFX_3d\n"
  1536. "@ingroup SFX" )
  1537. {
  1538. return SFX->getRolloffFactor();
  1539. }
  1540. //-----------------------------------------------------------------------------
  1541. DefineEngineFunction( sfxSetRolloffFactor, void, ( F32 value ),,
  1542. "Set the global scale factor to apply to volume attenuation of 3D sounds in the logarithmic model.\n"
  1543. "@param value The new scale factor for logarithmic 3D sound falloff curves.\n\n"
  1544. "@pre @a value must be > 0.\n"
  1545. "@note This function has no effect if the currently distance model is set to SFXDistanceModel::Linear.\n\n"
  1546. "@see sfxGetDistanceModel\n"
  1547. "@see SFXDistanceModel\n\n"
  1548. "@ref SFXSource_volume\n"
  1549. "@ref SFX_3d\n"
  1550. "@ingroup SFX" )
  1551. {
  1552. if( value <= 0.0f )
  1553. {
  1554. Con::errorf( "sfxSetRolloffFactor - factor must be >0" );
  1555. return;
  1556. }
  1557. SFX->setRolloffFactor( value );
  1558. }
  1559. //-----------------------------------------------------------------------------
  1560. DefineEngineFunction( sfxDumpSources, void, ( bool includeGroups ), ( false ),
  1561. "Dump information about all current SFXSource instances to the console.\n"
  1562. "The dump includes information about the playback status for each source, volume levels, virtualization, etc.\n"
  1563. "@param includeGroups If true, direct instances of SFXSources (which represent logical sound groups) will be included. "
  1564. "Otherwise only instances of subclasses of SFXSources are included in the dump.\n"
  1565. "@see SFXSource\n"
  1566. "@see sfxDumpSourcesToString\n"
  1567. "@ingroup SFX" )
  1568. {
  1569. SFX->dumpSources( NULL, !includeGroups );
  1570. }
  1571. //-----------------------------------------------------------------------------
  1572. DefineEngineFunction( sfxDumpSourcesToString, const char*, ( bool includeGroups ), ( false ),
  1573. "Dump information about all current SFXSource instances to a string.\n"
  1574. "The dump includes information about the playback status for each source, volume levels, virtualization, etc.\n"
  1575. "@param includeGroups If true, direct instances of SFXSources (which represent logical sound groups) will be included. "
  1576. "Otherwise only instances of subclasses of SFXSources are included in the dump.\n"
  1577. "@return A string containing a dump of information about all currently instantiated SFXSources.\n"
  1578. "@see SFXSource\n"
  1579. "@see sfxDumpSources\n"
  1580. "@ingroup SFX" )
  1581. {
  1582. StringBuilder str;
  1583. SFX->dumpSources( &str, !includeGroups );
  1584. return Con::getReturnBuffer( str );
  1585. }