sfxSystem.cpp 67 KB

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