Counter Strike : Global Offensive Source Code
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

10017 lines
275 KiB

  1. //===== Copyright � 1996-2005, Valve Corporation, All rights reserved. ======//
  2. //
  3. // Purpose: Main control for any streaming sound output device.
  4. //
  5. //===========================================================================//
  6. #include "audio_pch.h"
  7. #include "host.h"
  8. #include "time.h"
  9. #include "const.h"
  10. #include "cdll_int.h"
  11. #include "sound.h"
  12. #include "client_class.h"
  13. #include "icliententitylist.h"
  14. #include "tier1/fmtstr.h"
  15. #include "con_nprint.h"
  16. #include "tier0/icommandline.h"
  17. #include "vox_private.h"
  18. #include "../../traceinit.h"
  19. #include "../../cmd.h"
  20. #include "toolframework/itoolframework.h"
  21. #include "vstdlib/random.h"
  22. #include "vstdlib/jobthread.h"
  23. #include "vaudio/ivaudio.h"
  24. #include "../../client.h"
  25. #include "../../cl_main.h"
  26. #include "tier3/tier3.h"
  27. #include "utldict.h"
  28. #include "mempool.h"
  29. #include "../../enginetrace.h" // for traceline
  30. #include "../../public/bspflags.h" // for traceline
  31. #include "../../public/gametrace.h" // for traceline
  32. #include "vphysics_interface.h" // for surface props
  33. #include "../../ispatialpartitioninternal.h" // for entity enumerator
  34. #include "../../debugoverlay.h"
  35. #include "icliententity.h"
  36. #include "../../cmodel_engine.h"
  37. #include "../../staticpropmgr.h"
  38. #include "../../server.h"
  39. #include "edict.h"
  40. #include "../../pure_server.h"
  41. #include "filesystem/IQueuedLoader.h"
  42. #include "filesystem/IXboxInstaller.h"
  43. #include "voice.h"
  44. #include "snd_dma.h"
  45. #include "snd_mixgroups.h"
  46. #include "../../cl_splitscreen.h"
  47. #include "../../common/blackbox_helper.h"
  48. #include "snd_op_sys/sos_system.h"
  49. #include "snd_dev_common.h"
  50. #include "tier1/utlhashtable.h"
  51. #include "cl_steamauth.h"
  52. #include <vgui/ISurface.h>
  53. #if defined( _X360 )
  54. #include "xbox/xbox_console.h"
  55. #include "xmp.h"
  56. #include "avi/ibik.h"
  57. extern IBik *bik;
  58. #elif defined( _PS3 )
  59. #include "ps3/ps3_console.h"
  60. #include "snd_ps3_mp3dec.h"
  61. void HandleRemainingFrameInfos( int nMp3DecoderSlot, bool bBlocking );
  62. #include "avi/ibik.h"
  63. extern IBik *bik;
  64. #endif
  65. // memdbgon must be the last include file in a .cpp file!!!
  66. #include "tier0/memdbgon.h"
  67. ///////////////////////////////////
  68. // DEBUGGING
  69. //
  70. // Turn this on to print channel output msgs.
  71. //
  72. //#define DEBUG_CHANNELS
  73. ConVar snd_sos_show_client_rcv("snd_sos_show_client_rcv", "0", FCVAR_CHEAT);
  74. ConVar snd_sos_allow_dynamic_chantype( "snd_sos_allow_dynamic_chantype", IsPlatformX360() ? "1" : "1" );
  75. //Controls whether we use HRTF (phonon) audio for sounds marked to use it.
  76. ConVar snd_use_hrtf("snd_use_hrtf", "1", FCVAR_ARCHIVE);
  77. ConVar snd_hrtf_lerp_min_distance("snd_hrtf_lerp_min_distance", "0.0", FCVAR_CHEAT);
  78. ConVar snd_hrtf_lerp_max_distance("snd_hrtf_lerp_max_distance", "0.0", FCVAR_CHEAT);
  79. BEGIN_DEFINE_LOGGING_CHANNEL( LOG_SOUND_OPERATOR_SYSTEM, "SoundOperatorSystem", LCF_CONSOLE_ONLY, LS_MESSAGE );
  80. ADD_LOGGING_CHANNEL_TAG( "SoundOperatorSystem" );
  81. END_DEFINE_LOGGING_CHANNEL();
  82. extern ConVar dsp_spatial;
  83. extern IPhysicsSurfaceProps *physprops;
  84. extern IVEngineClient *engineClient;
  85. static void S_Play( const CCommand &args );
  86. static void S_PlayHRTF( const CCommand & args );
  87. static void S_PlayVol( const CCommand &args );
  88. void S_SoundList(void);
  89. static void S_Say ( const CCommand &args );
  90. void S_Update_(float);
  91. void S_StopAllSounds(bool clear);
  92. void S_StopAllSoundsC(void);
  93. bool S_GetPreventSound( void );
  94. void S_ShutdownMixThread();
  95. const char *GetClientClassname( SoundSource soundsource );
  96. void S_PreventSound(bool bSetting);
  97. float SND_GetGainObscured( int nSlot, gain_t *gs, const channel_t *ch, const Vector &vecListenerOrigin, bool fplayersound, bool flooping, bool bAttenuated, bool bOkayToTrace, Vector *pOrigin );
  98. void DSP_ChangePresetValue( int idsp, int channel, int iproc, float value );
  99. bool DSP_CheckDspAutoEnabled( void );
  100. void DSP_SetDspAuto( int dsp_preset );
  101. float dB_To_Radius ( float db );
  102. int dsp_room_GetInt ( void );
  103. void ChannelSetVolTargets( channel_t *pch, float *pvolumes, int ivol_offset, int cvol );
  104. void ChannelUpdateVolXfade( channel_t *pch );
  105. void ChannelClearVolumes( channel_t *pch );
  106. float VOX_GetChanVol(channel_t *ch);
  107. void ConvertListenerVectorTo2D( Vector *pvforward, const Vector *pvright );
  108. int ChannelGetMaxVol( channel_t *pch );
  109. bool S_IsMusic( channel_t *pChannel );
  110. bool S_ShouldSaveRestore( channel_t const* pChannel );
  111. // Forceably ends voice tweak mode (only occurs during snd_restart
  112. void VoiceTweak_EndVoiceTweakMode();
  113. bool VoiceTweak_IsStillTweaking();
  114. // Only does anything for voice tweak channel so if view entity changes it doesn't fade out to zero volume
  115. void Voice_Spatialize( channel_t *channel );
  116. extern float g_flReplayMusicGain;
  117. static ConVar snd_mergemethod( "snd_mergemethod", "1", 0, "Sound merge method (0 == sum and clip, 1 == max, 2 == avg)." );
  118. static ConVar snd_report_start_sound( "snd_report_start_sound", "0", FCVAR_CHEAT, "If set to 1, report all sounds played with S_StartSound(). The sound may not end up being played (if error occurred for example). Use snd_showstart to see the sounds that are really played.\n" );
  119. ConVar snd_report_stop_sound( "snd_report_stop_sound", "0", FCVAR_CHEAT, "If set to 1, report all sounds stopped with S_StopSound().\n" );
  120. ConVar snd_report_loop_sound( "snd_report_loop_sound", "0", FCVAR_CHEAT, "If set to 1, report all sounds that just looped.\n" );
  121. ConVar snd_report_format_sound( "snd_report_format_sound", "0", FCVAR_CHEAT, "If set to 1, report all sound formats.\n" );
  122. ConVar snd_report_verbose_error( "snd_report_verbose_error", "0", FCVAR_CHEAT, "If set to 1, report more error found when playing sounds.\n" );
  123. static ConVar snd_hrtf_distance_behind("snd_hrtf_distance_behind", "100", FCVAR_ARCHIVE, "HRTF calculations will calculate the player as being this far behind the camera\n");
  124. // store all played sounds for eliminating unplayed sounds for optimizations
  125. ConVar snd_store_filepaths("snd_store_filepaths", "");
  126. CUtlDict <int, int> g_StoreFilePaths;
  127. enum ESndMergeMethod
  128. {
  129. SND_MERGE_SUMANDCLIP = 0,
  130. SND_MERGE_MAX,
  131. SND_MERGE_AVG,
  132. SND_MERGE_COUNT
  133. };
  134. static ESndMergeMethod g_SndMergeMethod;
  135. // =======================================================================
  136. // Internal sound data & structures
  137. // =======================================================================
  138. ConVar snd_max_same_sounds( "snd_max_same_sounds", "4", FCVAR_CHEAT );
  139. ConVar snd_max_same_weapon_sounds( "snd_max_same_weapon_sounds", "3", FCVAR_CHEAT );
  140. CScratchPad g_scratchpad;
  141. channel_t channels[MAX_CHANNELS];
  142. int total_channels = MAX_DYNAMIC_CHANNELS;
  143. static int nShowDynamicChannelMax = 0;
  144. static int nShowStaticChannelMax = 0;
  145. CActiveChannels g_ActiveChannels;
  146. static double g_LastSoundFrame = 0.0f; // last full frame of sound
  147. static double g_LastMixTime = 0.0f; // last time we did mixing
  148. static float g_EstFrameTime = 0.1f; // estimated frame time running average
  149. // x360 override to fade out game music when the user is playing music through the dashboard
  150. static float g_DashboardMusicMixValue = 1.0f;
  151. static float g_DashboardMusicMixTarget = 1.0f;
  152. const float g_DashboardMusicFadeRate = 0.5f; // Fades one half full-scale volume per second (two seconds for complete fadeout)
  153. float S_GetDashboarMusicMixValue()
  154. {
  155. return g_DashboardMusicMixValue;
  156. }
  157. // This is a hack to prevent audio from being referenced during a load.
  158. bool g_bPreventSound = false;
  159. // global pitch scale
  160. static float g_flPitchScale = 1.0f;
  161. // this is used to enable/disable music playback on x360 when the user selects his own soundtrack to play
  162. void S_EnableMusic( bool bEnable )
  163. {
  164. if ( bEnable )
  165. {
  166. g_DashboardMusicMixTarget = 1.0f;
  167. }
  168. else
  169. {
  170. g_DashboardMusicMixTarget = 0.0f;
  171. }
  172. }
  173. CThreadMutex g_SndMutex;
  174. #define THREAD_LOCK_SOUND() AUTO_LOCK( g_SndMutex )
  175. CThreadFastMutex g_ActiveSoundListMutex;
  176. void CActiveChannels::Add( channel_t *pChannel )
  177. {
  178. Assert( pChannel->activeIndex == 0 );
  179. m_list[m_count] = pChannel - channels;
  180. m_count++;
  181. pChannel->activeIndex = m_count;
  182. }
  183. void CActiveChannels::Remove( channel_t *pChannel )
  184. {
  185. if ( pChannel->activeIndex == 0 )
  186. return;
  187. int activeIndex = pChannel->activeIndex - 1;
  188. Assert( activeIndex >= 0 && activeIndex < m_count );
  189. Assert( pChannel == &channels[m_list[activeIndex]] );
  190. m_count--;
  191. // Not the last one? Swap the last one with this one and fix its index
  192. if ( activeIndex < m_count )
  193. {
  194. m_list[activeIndex] = m_list[m_count];
  195. channels[m_list[activeIndex]].activeIndex = activeIndex+1;
  196. }
  197. pChannel->activeIndex = 0;
  198. }
  199. void CActiveChannels::GetActiveChannels( CChannelList &list ) const
  200. {
  201. list.m_count = m_count;
  202. if ( m_count )
  203. {
  204. Q_memcpy( list.m_list, m_list, sizeof(m_list[0])*m_count );
  205. }
  206. list.m_hasSpeakerChannels = true;
  207. list.m_has11kChannels = true;
  208. list.m_has22kChannels = true;
  209. list.m_has44kChannels = true;
  210. list.m_hasDryChannels = true;
  211. }
  212. void CActiveChannels::CopyActiveSounds( CUtlVector<activethreadsound_t> &list ) const
  213. {
  214. list.SetCount( m_count );
  215. for ( int i = 0; i < m_count; i++ )
  216. {
  217. list[i].m_nGuid = channels[m_list[i]].guid;
  218. list[i].m_flElapsedTime = 0.0f;
  219. CAudioMixer *pMixer = channels[m_list[i]].pMixer;
  220. if ( pMixer )
  221. {
  222. float flDivisor = ( pMixer->GetSource()->SampleRate() * channels[m_list[i]].pitch * 0.01f );
  223. if( flDivisor > 0.0f )
  224. {
  225. list[i].m_flElapsedTime = pMixer->GetSamplePosition() / flDivisor;
  226. }
  227. }
  228. }
  229. }
  230. channel_t * CActiveChannels::FindActiveChannelByGuid( int guid ) const
  231. {
  232. for ( int i = 0; i < m_count; i++ )
  233. {
  234. channel_t *pChannel = &channels[ m_list[ i ] ];
  235. if ( pChannel->guid == guid )
  236. {
  237. return pChannel;
  238. }
  239. }
  240. return NULL;
  241. }
  242. void CActiveChannels::DumpChannelInfo( CUtlBuffer &buf )
  243. {
  244. char nameBuf[ MAX_PATH ];
  245. for ( int i = 0; i < m_count; i++ )
  246. {
  247. channel_t *pChannel = &channels[ m_list[ i ] ];
  248. if ( pChannel->sfx != NULL )
  249. {
  250. buf.Printf( "%d. ch=%d %s p=%.2f,%.2f,%.2f v=%d s=%d l=%d \n", i, m_list[ i ], pChannel->sfx->getname( nameBuf, sizeof(nameBuf) ),
  251. pChannel->origin[0], pChannel->origin[1], pChannel->origin[2], pChannel->master_vol, pChannel->soundsource, pChannel->sfx->pSource->IsLooped() );
  252. }
  253. }
  254. }
  255. void CActiveChannels::Init()
  256. {
  257. m_count = 0;
  258. }
  259. bool snd_initialized = false;
  260. Vector listener_origin[ MAX_SPLITSCREEN_CLIENTS ];
  261. Vector listener_forward[ MAX_SPLITSCREEN_CLIENTS ];
  262. Vector listener_right[ MAX_SPLITSCREEN_CLIENTS ];
  263. static Vector listener_up[ MAX_SPLITSCREEN_CLIENTS ];
  264. static bool s_bIsListenerUnderwater;
  265. static vec_t sound_nominal_clip_dist=SOUND_NORMAL_CLIP_DIST;
  266. // @TODO (toml 05-08-02): put this somewhere more reasonable
  267. vec_t S_GetNominalClipDist()
  268. {
  269. return sound_nominal_clip_dist;
  270. }
  271. #if USE_AUDIO_DEVICE_V1
  272. int64 g_soundtime = 0; // sample PAIRS output since start
  273. double g_soundtimeerror = 0.0; // Error in sound time (used for synchronizing movie output sound to host_time)
  274. #endif
  275. int64 g_paintedtime = 0; // sample PAIRS mixed since start
  276. float g_ClockSyncArray[NUM_CLOCK_SYNCS] = {0};
  277. int64 g_SoundClockPaintTime[NUM_CLOCK_SYNCS] = {0};
  278. // default 30ms
  279. ConVar snd_delay_sound_shift( "snd_delay_sound_shift", "0.03" );
  280. // this forces the clock to resync on the next delayed/sync sound
  281. void S_SyncClockAdjust( clocksync_index_t syncIndex )
  282. {
  283. g_ClockSyncArray[syncIndex] = 0;
  284. g_SoundClockPaintTime[syncIndex] = 0;
  285. }
  286. float S_ComputeDelayForSoundtime( float soundtime, clocksync_index_t syncIndex )
  287. {
  288. // reset clock and return 0
  289. if ( g_ClockSyncArray[syncIndex] == 0 )
  290. {
  291. // Put the current time marker one tick back to impose a minimum delay on the first sample
  292. // this shifts the drift over so the sounds are more likely to delay (rather than skip)
  293. // over the burst
  294. // NOTE: The first sound after a sync MUST have a non-zero delay for the delay channel
  295. // detection logic to work (otherwise we keep resetting the clock)
  296. g_ClockSyncArray[syncIndex] = soundtime - host_state.interval_per_tick;
  297. g_SoundClockPaintTime[syncIndex] = g_paintedtime;
  298. }
  299. // how much time has passed in the game since we did a clock sync?
  300. float gameDeltaTime = soundtime - g_ClockSyncArray[syncIndex];
  301. // how many samples have been mixed since we did a clock sync?
  302. int paintedSamples = g_paintedtime - g_SoundClockPaintTime[syncIndex];
  303. int dmaSpeed = g_AudioDevice->SampleRate();
  304. int gameSamples = (gameDeltaTime * dmaSpeed);
  305. int delaySamples = gameSamples - paintedSamples;
  306. float delay = delaySamples / float(dmaSpeed);
  307. if ( gameDeltaTime < 0 || fabs(delay) > 0.200f )
  308. {
  309. // Note that the equations assume a correlation between game time and real time
  310. // some kind of clock error. This can happen with large host_timescale or when the
  311. // framerate hitches drastically (game time is a smaller clamped value wrt real time).
  312. // The current sync estimate has probably drifted due to this or some other problem, recompute.
  313. //Msg("Clock ERROR!: %.2f %.2f\n", gameDeltaTime, delay);
  314. S_SyncClockAdjust(syncIndex);
  315. return 0;
  316. }
  317. return delay + snd_delay_sound_shift.GetFloat();
  318. }
  319. static int s_buffers = 0;
  320. static int s_oldsampleOutCount = 0;
  321. static float s_lastsoundtime = 0.0f;
  322. bool s_bOnLoadScreen = false;
  323. static CClassMemoryPool< CSfxTable > s_SoundPool( MAX_SFX );
  324. struct SfxDictEntry
  325. {
  326. CSfxTable *pSfx;
  327. };
  328. static CUtlMap< FileNameHandle_t, SfxDictEntry > s_Sounds( 0, 0, DefLessFunc( FileNameHandle_t ) );
  329. CThreadFastMutex g_SoundMapMutex;
  330. class CDummySfx : public CSfxTable
  331. {
  332. public:
  333. virtual const char *getname( char *pBuf, size_t bufLen )
  334. {
  335. V_strncpy( pBuf, name, bufLen );
  336. return pBuf;
  337. }
  338. void setname( const char *pName )
  339. {
  340. Q_strncpy( name, pName, sizeof( name ) );
  341. OnNameChanged(name);
  342. }
  343. private:
  344. char name[MAX_PATH];
  345. };
  346. static CDummySfx dummySfx;
  347. CSfxTable *S_DummySfx( const char *name )
  348. {
  349. dummySfx.setname( name );
  350. return &dummySfx;
  351. }
  352. // returns true if ok to procede with TraceRay calls
  353. bool SND_IsInGame( void )
  354. {
  355. return GetBaseLocalClient().IsActive();
  356. }
  357. CSfxTable::CSfxTable()
  358. {
  359. m_namePoolIndex = s_Sounds.InvalidIndex();
  360. pSource = NULL;
  361. m_bUseErrorFilename = false;
  362. m_bIsUISound = false;
  363. m_bIsMusic = false;
  364. m_bIsLateLoad = false;
  365. m_bMixGroupsCached = false;
  366. m_bIsCreatedByQueuedLoader = false;
  367. m_pDebugName = NULL;
  368. }
  369. void CSfxTable::SetNamePoolIndex( int index )
  370. {
  371. m_namePoolIndex = index;
  372. char nameBuf[MAX_PATH];
  373. if ( m_namePoolIndex != s_Sounds.InvalidIndex() )
  374. {
  375. OnNameChanged(getname(nameBuf,sizeof(nameBuf)));
  376. }
  377. #ifdef _DEBUG
  378. m_pDebugName = strdup( getname(nameBuf, sizeof(nameBuf)) );
  379. #endif
  380. }
  381. extern int g_cgrouprules;
  382. void CSfxTable::OnNameChanged( const char *pName )
  383. {
  384. if ( pName && g_cgrouprules )
  385. {
  386. char szString[MAX_PATH];
  387. Q_strncpy( szString, pName, sizeof(szString) );
  388. Q_FixSlashes( szString, '/' );
  389. V_strlower( szString );
  390. m_mixGroupCount = MXR_GetMixGroupListFromDirName( szString, m_mixGroupList, ARRAYSIZE(m_mixGroupList) );
  391. m_bIsMusic = false;
  392. for ( int i = 0; i < m_mixGroupCount; i++ )
  393. {
  394. if ( MXR_IsMusicGroup( m_mixGroupList[i] ) )
  395. {
  396. m_bIsMusic = true;
  397. break;
  398. }
  399. }
  400. m_bMixGroupsCached = true;
  401. }
  402. else
  403. {
  404. m_mixGroupCount = 0;
  405. m_bMixGroupsCached = false;
  406. }
  407. }
  408. //-----------------------------------------------------------------------------
  409. // Returns the decorated name. Cannot be used nested more than a few levels.
  410. //-----------------------------------------------------------------------------
  411. const char *CSfxTable::getname( char *pBuf, size_t bufLen )
  412. {
  413. if ( s_Sounds.InvalidIndex() != m_namePoolIndex )
  414. {
  415. // based on pix capture, prior version using va() causing extra copies, was too costly
  416. // purposely doing it here
  417. // using va() was also very risky, naive code could easily get pointer contents changed
  418. g_pFileSystem->String( s_Sounds.Key( m_namePoolIndex ), pBuf, bufLen );
  419. return pBuf;
  420. }
  421. return NULL;
  422. }
  423. FileNameHandle_t CSfxTable::GetFileNameHandle()
  424. {
  425. if ( s_Sounds.InvalidIndex() != m_namePoolIndex )
  426. {
  427. return s_Sounds.Key( m_namePoolIndex );
  428. }
  429. return NULL;
  430. }
  431. //-----------------------------------------------------------------------------
  432. // Returns the file name, sound prefix chars are stripped
  433. //-----------------------------------------------------------------------------
  434. const char *CSfxTable::GetFileName( char *pOutBuf, size_t bufLen )
  435. {
  436. if ( IsGameConsole() && m_bUseErrorFilename )
  437. {
  438. // Redirecting error sounds to a valid empty wave, prevents a bad loading retry pattern during gameplay
  439. // which may event sounds skipped by preload, because they don't exist.
  440. return "common/null.wav";
  441. }
  442. const char *pName = getname(pOutBuf, bufLen);
  443. return pName ? PSkipSoundChars( pName ) : NULL;
  444. }
  445. bool CSfxTable::IsPrecachedSound()
  446. {
  447. char nameBuf[MAX_PATH];
  448. const char *pName = getname(nameBuf, sizeof(nameBuf));
  449. if ( sv.IsActive() )
  450. {
  451. // Server uses zero to mark invalid sounds
  452. return sv.LookupSoundIndex( pName ) != 0 ? true : false;
  453. }
  454. // Client uses -1
  455. // WE SHOULD FIX THIS!!!
  456. return ( GetBaseLocalClient().LookupSoundIndex( pName ) != -1 ) ? true : false;
  457. }
  458. float g_DuckScale = 1.0f;
  459. int g_DuckScaleInt256 = 256;
  460. // Structure used for fading in and out client sound volume.
  461. typedef struct
  462. {
  463. float initial_percent;
  464. // How far to adjust client's volume down by.
  465. float percent;
  466. // GetHostTime() when we started adjusting volume
  467. float starttime;
  468. // # of seconds to get to faded out state
  469. float fadeouttime;
  470. // # of seconds to hold
  471. float holdtime;
  472. // # of seconds to restore
  473. float fadeintime;
  474. } soundfade_t;
  475. static soundfade_t soundfade; // Client sound fading singleton object
  476. float g_flReplaySoundFade = 0.0f;
  477. float g_flReplayMusicGain = 1.0f;
  478. // 0)headphones 2)stereo speakers 4)quad 5)5point1
  479. // autodetected from windows settings
  480. ConVar snd_surround( "snd_surround_speakers", "-1" );
  481. #if USE_AUDIO_DEVICE_V1
  482. ConVar snd_legacy_surround( "snd_legacy_surround", "0", FCVAR_ARCHIVE );
  483. #endif
  484. ConVar snd_noextraupdate( "snd_noextraupdate", "0" );
  485. ConVar snd_show( "snd_show", "0", FCVAR_CHEAT, "Show sounds info");
  486. void OnSndShowEdgeChanged( IConVar *var, const char *pOldValue, float flOldValue );
  487. ConVar snd_show_print( "snd_show_print", "0", FCVAR_CHEAT, "Print to console the sounds that are normally printed on screen only. 1 = print to console and to screen; 2 = print only to console", OnSndShowEdgeChanged );
  488. ConVar snd_show_filter( "snd_show_filter", "", FCVAR_CHEAT, "Limit debug sounds to those containing this substring" );
  489. ConVar snd_find_channel( "snd_find_channel", "", 0, "Scan every channel to find the corresponding sound." );
  490. ConVar snd_visualize ("snd_visualize", "0", FCVAR_CHEAT, "Show sounds location in world" );
  491. ConVar snd_pitchquality( "snd_pitchquality", "1", FCVAR_ARCHIVE ); // 1) use high quality pitch shifters
  492. // master volume
  493. static ConVar volume( "volume", "1.0", FCVAR_ARCHIVE | FCVAR_ARCHIVE_GAMECONSOLE, "Sound volume", true, 0.0f, true, 1.0f );
  494. // since the volume convar is manipulated by the UI it needs to be 0-1, this is a lower level control to limit that to a smaller
  495. // range if necessary. On X360, we need to set this value to 0.5 to get similar level as the other X360 games.
  496. // On PS3 and PC however, a value of 1.0 matches the other games. This is mostly for the game engine as it is not used by the movie.
  497. static ConVar ui_volume_scale( "ui_volume_scale", IsPlatformX360() ? "0.5" : "1.0" );
  498. // Similar knob for the movies.
  499. // These values were given by Mike Morasky after various testing.
  500. ConVar movie_volume_scale( "movie_volume_scale", IsPlatformPS3() ? "0.9" : "1.0" );
  501. // user configurable music volume - NOTE there is no music submix so this is pre-multiplied into each channel
  502. ConVar snd_musicvolume_multiplier_inoverlay( "snd_musicvolume_multiplier_inoverlay", "0.1", FCVAR_ARCHIVE | FCVAR_ARCHIVE_GAMECONSOLE, "Music volume multiplier when Steam Overlay is active", true, 0.0f, true, 1.0f );
  503. ConVar snd_musicvolume( "snd_musicvolume", "0.7", FCVAR_ARCHIVE | FCVAR_ARCHIVE_GAMECONSOLE, "Overall music volume", true, 0.0f, true, 1.0f );
  504. ConVar snd_menumusic_volume( "snd_menumusic_volume", "1.0", FCVAR_ARCHIVE | FCVAR_RELEASE, "Relative volume of the main menu music." );
  505. ConVar snd_roundstart_volume( "snd_roundstart_volume", "1.0", FCVAR_ARCHIVE | FCVAR_RELEASE, "Relative volume of round start music." );
  506. ConVar snd_roundend_volume( "snd_roundend_volume", "1.0", FCVAR_ARCHIVE | FCVAR_RELEASE, "Relative volume of round end music." );
  507. ConVar snd_mapobjective_volume( "snd_mapobjective_volume", "1.0", FCVAR_ARCHIVE | FCVAR_RELEASE, "Relative volume of map objective music." );
  508. ConVar snd_tensecondwarning_volume( "snd_tensecondwarning_volume", "1.0", FCVAR_ARCHIVE | FCVAR_RELEASE, "Relative volume of ten second warning music." );
  509. ConVar snd_deathcamera_volume("snd_deathcamera_volume", "1.0", FCVAR_ARCHIVE | FCVAR_RELEASE, "Relative volume of the death camera music.");
  510. ConVar snd_mixahead( "snd_mixahead", "0.1", FCVAR_ARCHIVE );
  511. ConVar snd_delay_for_choreo_enabled( "snd_delay_for_choreo_enabled", "1", 0, "Enables update of delay for choreo to compensate for IO latency." );
  512. ConVar snd_delay_for_choreo_reset_after_N_milliseconds( "snd_delay_for_choreo_reset_after_N_milliseconds", "500", 0, "Resets the choreo latency after N milliseconds of VO not playing. Default is 500 ms." );
  513. float g_fDelayForChoreo = 0.0f; // Delay in seconds added to VCD VO due to IO latency.
  514. uint32 g_nDelayForChoreoLastCheckInMs = 0; // Used to reset the choreo latency (if last check time + snd_delay_for_choreo_reset_after_N_milliseconds is greater than current time, and no choreo sound is playing, we can reset).
  515. int g_nDelayForChoreoNumberOfSoundsPlaying = 0; // Number of choreo sound currently playing. Has to be zero for the reset of the latency to occur.
  516. ConVar snd_mix_async( "snd_mix_async", "0" );
  517. #ifdef _DEBUG
  518. static ConCommand snd_mixvol("snd_mixvol", MXR_DebugSetMixGroupVolume, "Set named Mixgroup to mix volume.");
  519. #endif
  520. extern ConVar host_threaded_sound;
  521. // vaudio DLL
  522. IVAudio *vaudio = NULL;
  523. CSysModule *g_pVAudioModule = NULL;
  524. //-----------------------------------------------------------------------------
  525. // Resource loading for sound
  526. //-----------------------------------------------------------------------------
  527. class CResourcePreloadSound : public CResourcePreload
  528. {
  529. public:
  530. CResourcePreloadSound()
  531. {
  532. }
  533. virtual void PrepareForCreate( bool bSameMap )
  534. {
  535. if ( !bSameMap )
  536. {
  537. // cannot support dynamic nature of sounds changing across maps due to deep fragmentation
  538. // always purge, tear all the sounds away, and put them back
  539. PurgeAllSounds();
  540. }
  541. }
  542. virtual bool CreateResource( const char *pName )
  543. {
  544. CSfxTable *pSfx = S_PrecacheSound( pName );
  545. if ( !pSfx )
  546. {
  547. return false;
  548. }
  549. return true;
  550. }
  551. private:
  552. void PurgeAllSounds()
  553. {
  554. bool bSpew = ( g_pQueuedLoader->GetSpewDetail() & LOADER_DETAIL_PURGES ) != 0;
  555. char nameBuf[MAX_PATH];
  556. for ( int i = s_Sounds.FirstInorder(); i != s_Sounds.InvalidIndex(); i = s_Sounds.NextInorder( i ) )
  557. {
  558. CSfxTable *pSfx = s_Sounds[i].pSfx;
  559. if ( pSfx && pSfx->pSource )
  560. {
  561. if ( !pSfx->m_bIsCreatedByQueuedLoader )
  562. {
  563. // never purge sounds we do not own
  564. if ( bSpew )
  565. {
  566. Msg( "CResourcePreloadSound: Skipping: %s\n", pSfx->GetFileName(nameBuf, sizeof(nameBuf)) );
  567. }
  568. continue;
  569. }
  570. // sound was not part of preload, purge it
  571. if ( bSpew )
  572. {
  573. Msg( "CResourcePreloadSound: Purging: %s\n", pSfx->GetFileName(nameBuf, sizeof(nameBuf)) );
  574. }
  575. pSfx->pSource->CacheUnload();
  576. delete pSfx->pSource;
  577. pSfx->pSource = NULL;
  578. }
  579. }
  580. wavedatacache->Flush( true );
  581. }
  582. };
  583. static CResourcePreloadSound s_ResourcePreloadSound;
  584. //-----------------------------------------------------------------------------
  585. // Purpose:
  586. // Output : float
  587. //-----------------------------------------------------------------------------
  588. float S_GetMasterVolume( void )
  589. {
  590. float scale = 1.0f;
  591. if ( soundfade.percent != 0 )
  592. {
  593. scale = clamp( (float)soundfade.percent / 100.0f, 0.0f, 1.0f );
  594. scale = 1.0f - scale;
  595. }
  596. return volume.GetFloat() * scale * ui_volume_scale.GetFloat() * ( 1.0f - g_flReplaySoundFade );
  597. }
  598. void S_SoundInfo_f(void)
  599. {
  600. #if !USE_AUDIO_DEVICE_V1
  601. g_AudioDevice->OutputDebugInfo();
  602. #endif
  603. if ( !g_AudioDevice->IsActive() )
  604. {
  605. Msg( "Sound system not active\n" );
  606. return;
  607. }
  608. Msg( "total_channels: %d\n", total_channels);
  609. char nameBuf[MAX_PATH];
  610. if ( IsGameConsole() )
  611. {
  612. // dump a glimpse of the mixing state
  613. CChannelList list;
  614. g_ActiveChannels.GetActiveChannels( list );
  615. Msg( "\nActive Channels: %d\n", list.Count() );
  616. for ( int i = 0; i < list.Count(); i++ )
  617. {
  618. channel_t *pChannel = list.GetChannel( i );
  619. Msg( "Channel:%2d Mixer:%p %s\n", list.GetChannelIndex( i ), pChannel->pMixer, pChannel->sfx->GetFileName( nameBuf, sizeof( nameBuf ) ) );
  620. }
  621. }
  622. else
  623. {
  624. for (int i = MAX_DYNAMIC_CHANNELS; i<total_channels; i++)
  625. {
  626. channel_t *ch = &channels[i];
  627. if (ch->sfx != NULL)
  628. {
  629. Msg( " %d: %s\n", i, ch->sfx->getname(nameBuf, sizeof(nameBuf)) );
  630. }
  631. }
  632. }
  633. }
  634. #if !USE_AUDIO_DEVICE_V1
  635. static void OnSndVarChanged( IConVar *pVar, const char *pOldString, float flOldValue );
  636. ConVar snd_mute_losefocus("snd_mute_losefocus", "1", FCVAR_ARCHIVE);
  637. static ConVar windows_speaker_config("windows_speaker_config", "-1", FCVAR_RELEASE|FCVAR_ARCHIVE);
  638. static ConVar sound_device_override( "sound_device_override", "", 0, "ID of the sound device to use" );
  639. // maintain a list of available audio devices
  640. static CAudioDeviceList g_AudioDeviceList;
  641. static audio_device_init_params_t g_AudioDeviceInitParams;
  642. static bool g_bRestartAudio = false;
  643. void OnSndVarChanged( IConVar *pVar, const char *pOldString, float flOldValue )
  644. {
  645. if ( !g_AudioDevice )
  646. return;
  647. ConVarRef var(pVar);
  648. // restart sound system so the change takes effect
  649. if ( var.GetInt() != int(flOldValue) || pVar == &sound_device_override )
  650. {
  651. if ( pVar == &snd_surround )
  652. {
  653. windows_speaker_config.SetValue( var.GetInt() );
  654. }
  655. if ( pVar == &snd_mute_losefocus )
  656. {
  657. // if the device can handle this, no need to restart
  658. if ( g_AudioDevice->SetShouldPlayWhenNotInFocus( !var.GetBool() ) )
  659. return;
  660. }
  661. g_bRestartAudio = true;
  662. }
  663. }
  664. void GetAudioDeviceList(CUtlVector<audio_device_description_t>& v)
  665. {
  666. v = g_AudioDeviceList.m_list;
  667. }
  668. // this checks for device errors or configuration changes
  669. void S_CheckDevice()
  670. {
  671. // any errors?
  672. bool bRestart = Audio_PollErrorEvents() || g_bRestartAudio;
  673. g_bRestartAudio = false;
  674. // current device removed? New default device installed?
  675. if ( g_AudioDevice && g_AudioDeviceList.UpdateDeviceList() )
  676. {
  677. const wchar_t *pDeviceToCreate = g_AudioDeviceList.GetDeviceToCreate( g_AudioDeviceInitParams );
  678. const wchar_t *pCurrent = g_AudioDevice->GetDeviceID();
  679. if ( !g_AudioDevice->IsActive() || V_wcscmp( pDeviceToCreate, pCurrent ) )
  680. {
  681. bRestart = true;
  682. }
  683. }
  684. // error or device change, restart audio
  685. if ( bRestart )
  686. {
  687. g_pSoundServices->RestartSoundSystem();
  688. }
  689. }
  690. void S_GetAudioDeviceList( CUtlVector<audio_device_description_t> &audioList )
  691. {
  692. audioList.RemoveAll();
  693. if ( g_AudioDeviceList.m_nSubsystem == AUDIO_SUBSYSTEM_XAUDIO && g_AudioDeviceList.m_list.Count() > 0 )
  694. {
  695. audioList.AddToTail();
  696. audioList[0].InitAsNullDevice();
  697. V_sprintf_safe( audioList[0].m_friendlyName, "#OS_Default_Device" );
  698. audioList[0].m_nSubsystemId = AUDIO_SUBSYSTEM_XAUDIO;
  699. audioList[0].m_bIsAvailable = true;
  700. }
  701. for ( int i = 0; i < g_AudioDeviceList.m_list.Count(); i++ )
  702. {
  703. if ( g_AudioDeviceList.m_list[i].m_bIsAvailable )
  704. {
  705. audioList.AddToTail(g_AudioDeviceList.m_list[i]);
  706. }
  707. }
  708. }
  709. eSubSystems_t GetDefaultAudioSubsystem()
  710. {
  711. eSubSystems_t nSubsystem = AUDIO_SUBSYSTEM_XAUDIO;
  712. #if IS_WINDOWS_PC
  713. if ( CommandLine()->CheckParm( "-directsound" ) )
  714. {
  715. nSubsystem = AUDIO_SUBSYSTEM_DSOUND;
  716. }
  717. #endif
  718. return nSubsystem;
  719. }
  720. CON_COMMAND( sound_device_list, "Lists all available audio devices." )
  721. {
  722. g_AudioDeviceList.UpdateDeviceList();
  723. int nDeviceCount = g_AudioDeviceList.m_list.Count();
  724. Msg( "Found %d available audio devices\n", nDeviceCount );
  725. for ( int i = 0; i < nDeviceCount; i++ )
  726. {
  727. char deviceId[256];
  728. V_wcstostr( g_AudioDeviceList.m_list[i].m_deviceName, -1, deviceId, sizeof(deviceId) );
  729. Msg( "%d) %s (%d output channels) [%s]", i+1, g_AudioDeviceList.m_list[i].m_friendlyName, g_AudioDeviceList.m_list[i].m_nChannelCount, deviceId );
  730. if ( g_AudioDeviceList.m_list[i].m_bIsDefault )
  731. {
  732. Msg( " ** DEFAULT DEVICE **" );
  733. }
  734. Msg("\n");
  735. }
  736. }
  737. #endif
  738. /*
  739. ================
  740. S_Startup
  741. ================
  742. */
  743. void S_Startup( void )
  744. {
  745. if ( !snd_initialized )
  746. return;
  747. static bool bFirst = true;
  748. if ( bFirst )
  749. {
  750. #if !USE_AUDIO_DEVICE_V1
  751. snd_mute_losefocus.InstallChangeCallback( &OnSndVarChanged );
  752. sound_device_override.InstallChangeCallback( &OnSndVarChanged );
  753. snd_surround.InstallChangeCallback( &OnSndVarChanged );
  754. #endif
  755. #if IS_WINDOWS_PC
  756. SetupWindowsMixerPreferences();
  757. #endif
  758. bFirst = false;
  759. }
  760. if ( !g_AudioDevice )
  761. {
  762. #if USE_AUDIO_DEVICE_V1
  763. g_AudioDevice = IAudioDevice::AutoDetectInit();
  764. if ( !g_AudioDevice )
  765. {
  766. Error( "Unable to init audio" );
  767. }
  768. #else
  769. extern HWND* pmainwindow;
  770. eSubSystems_t nSubsystem = GetDefaultAudioSubsystem();
  771. g_AudioDeviceList.BuildDeviceList( nSubsystem );
  772. Assert( g_AudioDeviceList.IsValid() );
  773. g_AudioDeviceInitParams.Defaults();
  774. g_AudioDeviceInitParams.m_bPlayEvenWhenNotInFocus = !snd_mute_losefocus.GetBool();
  775. int nSpeakerConfig = windows_speaker_config.GetInt();
  776. if ( nSpeakerConfig >= 0 )
  777. {
  778. g_AudioDeviceInitParams.OverrideSpeakerConfig( nSpeakerConfig );
  779. }
  780. g_AudioDeviceInitParams.m_pWindowHandle = *pmainwindow;
  781. // enough buffer to mix 150ms (+1 buffer to round up)
  782. g_AudioDeviceInitParams.m_nOutputBufferCount = (int(0.150f * SOUND_DMA_SPEED) / MIX_BUFFER_SIZE) + 1;
  783. const char *pUser = sound_device_override.GetString();
  784. audio_device_description_t *pDevice = g_AudioDeviceList.FindDeviceById( pUser );
  785. if ( pDevice )
  786. {
  787. g_AudioDeviceInitParams.OverrideDevice( pDevice );
  788. }
  789. g_AudioDevice = g_AudioDeviceList.CreateDevice( g_AudioDeviceInitParams );
  790. #endif
  791. }
  792. }
  793. static ConCommand play("play", S_Play, "Play a sound.", FCVAR_SERVER_CAN_EXECUTE );
  794. static ConCommand play_hrtf("play_hrtf", S_PlayHRTF, "Play a sound with HRTF spatialization.", FCVAR_SERVER_CAN_EXECUTE);
  795. static ConCommand playflush( "playflush", S_Play, "Play a sound, reloading from disk in case of changes." );
  796. static ConCommand playvol( "playvol", S_PlayVol, "Play a sound at a specified volume." );
  797. static ConCommand speak( "speak", S_Say, "Play a constructed sentence." );
  798. static ConCommand stopsound( "stopsound", S_StopAllSoundsC, 0, FCVAR_CHEAT); // Marked cheat because it gives an advantage to players minimizing ambient noise.
  799. static ConCommand soundlist( "soundlist", S_SoundList, "List all known sounds." );
  800. static ConCommand soundinfo( "soundinfo", S_SoundInfo_f, "Describe the current sound device." );
  801. bool IsValidSampleRate( int rate )
  802. {
  803. return rate == SOUND_11k || rate == SOUND_22k || rate == SOUND_44k;
  804. }
  805. void VAudioInit()
  806. {
  807. if ( IsPC() && !g_pVAudioModule )
  808. {
  809. if ( !IsPosix() )
  810. {
  811. g_pFileSystem->GetLocalCopy( "mss32.dll" ); // vaudio_miles.dll will load this...
  812. }
  813. g_pVAudioModule = FileSystem_LoadModule( "vaudio_miles" );
  814. if ( g_pVAudioModule )
  815. {
  816. CreateInterfaceFn vaudioFactory = Sys_GetFactory( g_pVAudioModule );
  817. vaudio = (IVAudio *)vaudioFactory( VAUDIO_INTERFACE_VERSION, NULL );
  818. }
  819. }
  820. }
  821. /*
  822. ================
  823. S_Init
  824. ================
  825. */
  826. #ifdef _PS3
  827. // On PS3 sound can only initialize once
  828. enum Ps3SoundState_t
  829. {
  830. PS3_SOUND_NOT_INITIALIZED,
  831. PS3_SOUND_INITIALIZED,
  832. PS3_SOUND_SHUTDOWN
  833. };
  834. static Ps3SoundState_t s_ePs3SoundState = PS3_SOUND_NOT_INITIALIZED;
  835. #endif
  836. void S_Init( void )
  837. {
  838. #ifdef _PS3
  839. if ( s_ePs3SoundState == PS3_SOUND_NOT_INITIALIZED )
  840. {
  841. s_ePs3SoundState = PS3_SOUND_INITIALIZED;
  842. }
  843. else
  844. {
  845. if ( s_ePs3SoundState != PS3_SOUND_INITIALIZED )
  846. {
  847. Warning( "ERROR: PS3 sound system cannot be initialized again (state %d)!\n", s_ePs3SoundState );
  848. }
  849. return;
  850. }
  851. #endif
  852. if ( sv.IsDedicated() )
  853. {
  854. TRACEINIT( audiosourcecache->Init( host_parms.memsize >> 2 ), audiosourcecache->Shutdown() );
  855. return;
  856. }
  857. DevMsg( "Sound Initialization: Start\n" );
  858. // KDB: init sentence array
  859. TRACEINIT( VOX_Init(), VOX_Shutdown() );
  860. if ( IsPC() )
  861. {
  862. VAudioInit();
  863. }
  864. #ifdef _PS3
  865. // even if we do have sound, do we still have to Init mp3dec ? E.g. because it's logically a decoder, not a sound service. It's not clear.
  866. for ( int i = 0 ; i < NUMBER_OF_MP3_DECODER_SLOTS ; ++i )
  867. {
  868. g_mp3dec[i].Init();
  869. }
  870. #endif
  871. if ( CommandLine()->CheckParm( "-nosound" ) )
  872. {
  873. g_AudioDevice = Audio_GetNullDevice();
  874. return;
  875. }
  876. snd_initialized = true;
  877. g_ActiveChannels.Init();
  878. S_Startup();
  879. MIX_InitAllPaintbuffers();
  880. SND_InitScaletable();
  881. MXR_LoadAllSoundMixers();
  882. g_pSoundOperatorSystem->Init();
  883. S_StopAllSounds( true );
  884. TRACEINIT( audiosourcecache->Init( host_parms.memsize >> 2 ), audiosourcecache->Shutdown() );
  885. AllocDsps( true );
  886. if ( IsGameConsole() )
  887. {
  888. g_pQueuedLoader->InstallLoader( RESOURCEPRELOAD_SOUND, &s_ResourcePreloadSound );
  889. }
  890. DevMsg( "Sound Initialization: Finish, Sampling Rate: %i\n", g_AudioDevice->SampleRate() );
  891. #ifdef _X360
  892. BOOL bPlaybackControl;
  893. // get initial state of the x360 media player
  894. if ( XMPTitleHasPlaybackControl( &bPlaybackControl ) == ERROR_SUCCESS )
  895. {
  896. S_EnableMusic(bPlaybackControl!=0);
  897. }
  898. #if defined( BINK_ENABLED_FOR_CONSOLE ) && defined(BINK_VIDEO)
  899. bik->HookXAudio();
  900. #endif
  901. #endif
  902. #if defined( _PS3 ) && defined( BINK_ENABLED_FOR_CONSOLE )
  903. bik->SetPS3SoundDevice( g_AudioDevice->DeviceChannels() );
  904. #endif // _PS3 && BINK_ENABLED_FOR_CONSOLE
  905. }
  906. void DumpFilePaths(const char *filename);
  907. void ShutdownPhononThread();
  908. // =======================================================================
  909. // Shutdown sound engine
  910. // =======================================================================
  911. void S_Shutdown(void)
  912. {
  913. #ifdef _PS3
  914. if ( s_ePs3SoundState == PS3_SOUND_INITIALIZED )
  915. {
  916. s_ePs3SoundState = PS3_SOUND_SHUTDOWN;
  917. Msg( "PS3 sound system is shutting down...\n" );
  918. }
  919. else
  920. {
  921. Warning( "ERROR: PS3 sound system cannot shutdown again (state %d)!\n", s_ePs3SoundState );
  922. return;
  923. }
  924. #endif
  925. if ( !sv.IsDedicated() )
  926. {
  927. #if !defined( _X360 )
  928. if ( VoiceTweak_IsStillTweaking() )
  929. {
  930. VoiceTweak_EndVoiceTweakMode();
  931. }
  932. #endif
  933. // dump a complete list of audio files played during this game
  934. #ifndef _PS3
  935. if ( IsPC() && snd_store_filepaths.GetString()[ 0 ])
  936. {
  937. /*time_t ltime;
  938. time(&ltime);
  939. localtime(&ltime);*/
  940. #ifdef WIN32
  941. SYSTEMTIME time;
  942. GetLocalTime(&time);
  943. char filename[64];
  944. Q_snprintf( filename, 64, "soundlog_%i_%02i_%02i_%02i_%02i.txt", time.wYear, time.wMonth, time.wDay, time.wHour, time.wMinute );
  945. #else
  946. time_t timet = time( NULL );
  947. struct tm *tm = localtime( &timet );
  948. char filename[32];
  949. Q_snprintf( filename, 32, "soundlog_%i_%02i_%02i_%02i_%02i.txt", tm->tm_year, tm->tm_mon, tm->tm_mday, tm->tm_hour, tm->tm_min );
  950. #endif
  951. DumpFilePaths(filename);
  952. }
  953. #endif
  954. S_StopAllSounds( true );
  955. S_ShutdownMixThread();
  956. ShutdownPhononThread();
  957. SNDDMA_Shutdown();
  958. for ( int i = s_Sounds.FirstInorder(); i != s_Sounds.InvalidIndex(); i = s_Sounds.NextInorder( i ) )
  959. {
  960. if ( s_Sounds[i].pSfx )
  961. {
  962. delete s_Sounds[i].pSfx->pSource;
  963. s_Sounds[i].pSfx->pSource = NULL;
  964. }
  965. }
  966. s_Sounds.RemoveAll();
  967. s_SoundPool.Clear();
  968. // release DSP resources
  969. FreeDsps( true );
  970. MXR_ReleaseMemory();
  971. g_pSoundOperatorSystem->Shutdown();
  972. // release sentences resources
  973. TRACESHUTDOWN( VOX_Shutdown() );
  974. if ( IsPC() )
  975. {
  976. // shutdown vaudio
  977. if ( vaudio )
  978. delete vaudio;
  979. FileSystem_UnloadModule( g_pVAudioModule );
  980. g_pVAudioModule = NULL;
  981. vaudio = NULL;
  982. }
  983. MIX_FreeAllPaintbuffers();
  984. snd_initialized = false;
  985. g_paintedtime = 0;
  986. #if USE_AUDIO_DEVICE_V1
  987. g_soundtime = 0;
  988. g_soundtimeerror = 0.0;
  989. #endif
  990. s_buffers = 0;
  991. s_oldsampleOutCount = 0;
  992. s_lastsoundtime = 0.0f;
  993. #if !defined( _X360 )
  994. Voice_Deinit();
  995. #endif
  996. }
  997. TRACESHUTDOWN( audiosourcecache->Shutdown() );
  998. #ifdef _PS3
  999. for ( int i = 0 ; i < NUMBER_OF_MP3_DECODER_SLOTS ; ++i )
  1000. {
  1001. HandleRemainingFrameInfos( i, true );
  1002. g_mp3dec[i].Shutdown();
  1003. }
  1004. #endif
  1005. }
  1006. bool S_IsInitted()
  1007. {
  1008. return snd_initialized;
  1009. }
  1010. // =======================================================================
  1011. // Load a sound
  1012. // =======================================================================
  1013. //-----------------------------------------------------------------------------
  1014. // Find or Alloc sfx based on name.
  1015. // On Alloc, sets optional pInCache to 0.
  1016. // On Find, sets optional pInCache to 1 if resident, otherwise 0.
  1017. //-----------------------------------------------------------------------------
  1018. CSfxTable *S_FindName( const char *szName, int *pInCache )
  1019. {
  1020. int i;
  1021. CSfxTable *sfx = NULL;
  1022. char szBuff[MAX_PATH];
  1023. const char *pName;
  1024. if ( !szName )
  1025. {
  1026. Error( "S_FindName: NULL\n" );
  1027. }
  1028. pName = szName;
  1029. if ( IsGameConsole() )
  1030. {
  1031. Q_strncpy( szBuff, pName, sizeof( szBuff ) );
  1032. int len = Q_strlen( szBuff )-4;
  1033. if ( len > 0 && !Q_strnicmp( szBuff+len, ".mp3", 4 ) )
  1034. {
  1035. // convert unsupported .mp3 to .wav
  1036. Q_strcpy( szBuff+len, ".wav" );
  1037. }
  1038. pName = szBuff;
  1039. if ( pName[0] == CHAR_STREAM )
  1040. {
  1041. // streaming (or not) is hardcoded to alternate criteria
  1042. // prevent the same sound from creating disparate instances
  1043. pName++;
  1044. }
  1045. }
  1046. AUTO_LOCK( g_SoundMapMutex );
  1047. // see if already loaded
  1048. FileNameHandle_t fnHandle = g_pFileSystem->FindOrAddFileName( pName );
  1049. i = s_Sounds.Find( fnHandle );
  1050. if ( i != s_Sounds.InvalidIndex() )
  1051. {
  1052. sfx = s_Sounds[i].pSfx;
  1053. Assert( sfx );
  1054. if ( pInCache )
  1055. {
  1056. // indicate whether or not sound is currently in the cache.
  1057. *pInCache = ( sfx->pSource && sfx->pSource->IsCached() ) ? 1 : 0;
  1058. }
  1059. return sfx;
  1060. }
  1061. else
  1062. {
  1063. SfxDictEntry entry;
  1064. entry.pSfx = ( CSfxTable * )s_SoundPool.Alloc();
  1065. Assert( entry.pSfx );
  1066. i = s_Sounds.Insert( fnHandle, entry );
  1067. sfx = s_Sounds[i].pSfx;
  1068. sfx->SetNamePoolIndex( i );
  1069. sfx->pSource = NULL;
  1070. if ( pInCache )
  1071. {
  1072. *pInCache = 0;
  1073. }
  1074. }
  1075. return sfx;
  1076. }
  1077. //-----------------------------------------------------------------------------
  1078. // S_LoadSound
  1079. //
  1080. // Check to see if wave data is in the cache. If so, return pointer to data.
  1081. // If not, allocate cache space for wave data, load wave file into temporary heap
  1082. // space, and dump/convert file data into cache.
  1083. //-----------------------------------------------------------------------------
  1084. double g_flAccumulatedSoundLoadTime = 0.0f;
  1085. CAudioSource *S_LoadSound( CSfxTable *pSfx, channel_t *ch, SoundError &soundError )
  1086. {
  1087. VPROF( "S_LoadSound" );
  1088. char nameBuf[MAX_PATH];
  1089. soundError = SE_OK;
  1090. const char *pSndName = pSfx->getname(nameBuf, sizeof(nameBuf));
  1091. if ( !pSndName )
  1092. {
  1093. soundError = SE_CANT_GET_NAME;
  1094. return NULL;
  1095. }
  1096. const char *pSndFilename = PSkipSoundChars( pSndName );
  1097. if ( !pSfx->pSource )
  1098. {
  1099. if ( IsGameConsole() )
  1100. {
  1101. if ( SND_IsInGame() && !g_pQueuedLoader->IsMapLoading() )
  1102. {
  1103. // sound should be present (due to reslists), but NOT allowing a load hitch during gameplay
  1104. // loading a sound during gameplay is a bad experience, causes a very expensive sync i/o to fetch the header
  1105. // and in the case of a memory wave, the actual audio data
  1106. bool bFound = false;
  1107. if ( !pSfx->m_bIsLateLoad )
  1108. {
  1109. if ( pSndName != pSndFilename )
  1110. {
  1111. // the sound might already exist as an undecorated audio source
  1112. FileNameHandle_t fnHandle = g_pFileSystem->FindOrAddFileName( pSndFilename );
  1113. int i = s_Sounds.Find( fnHandle );
  1114. if ( i != s_Sounds.InvalidIndex() )
  1115. {
  1116. CSfxTable *pOtherSfx = s_Sounds[i].pSfx;
  1117. Assert( pOtherSfx );
  1118. CAudioSource *pOtherSource = pOtherSfx->pSource;
  1119. if ( pOtherSource && pOtherSource->IsCached() )
  1120. {
  1121. // Can safely let the "load" continue because the headers are expected to be in the preload
  1122. // that are now persisted and the wave data cache will find an existing audio buffer match,
  1123. // so no sync i/o should occur from either.
  1124. bFound = true;
  1125. }
  1126. }
  1127. }
  1128. if ( !bFound )
  1129. {
  1130. // warn once
  1131. DevWarning( "[Sound] S_LoadSound: Late load '%s', skipping.\n", pSndName );
  1132. pSfx->m_bIsLateLoad = true;
  1133. }
  1134. }
  1135. if ( !bFound )
  1136. {
  1137. soundError = SE_SKIPPED;
  1138. return NULL;
  1139. }
  1140. }
  1141. else if ( pSfx->m_bIsLateLoad )
  1142. {
  1143. // outside of gameplay, let the load happen
  1144. pSfx->m_bIsLateLoad = false;
  1145. }
  1146. }
  1147. double st = Plat_FloatTime();
  1148. bool bStream = false;
  1149. bool bUserVox = false;
  1150. // sound chars can explicitly categorize usage
  1151. bStream = TestSoundChar( pSndName, CHAR_STREAM );
  1152. if ( !bStream )
  1153. {
  1154. bUserVox = TestSoundChar( pSndName, CHAR_USERVOX );
  1155. }
  1156. // stream music
  1157. if ( !bStream && !bUserVox )
  1158. {
  1159. bStream = V_stristr( pSndName, "music" ) != NULL;
  1160. }
  1161. // override streaming
  1162. if ( IsGameConsole() )
  1163. {
  1164. // these are the ONLY non-streaming static sounds
  1165. const char *s_CriticalSounds[] =
  1166. {
  1167. "common/",
  1168. "items/",
  1169. "ui/",
  1170. "weapons/",
  1171. "vfx/fizzler_lp_01",
  1172. "player/player_fall_whoosh_lp_01",
  1173. "ambient/machines/portalgun_rotate_loop1"
  1174. };
  1175. // can further refine critical sounds and ensure these stream
  1176. const char *s_NonCriticalSounds[] =
  1177. {
  1178. // forcing the streamer to do more work all these static sounds now stream
  1179. // freed memory devoted to more textures
  1180. "player/footsteps",
  1181. #if defined( CSTRIKE15 )
  1182. "weapons/",
  1183. #endif
  1184. "gamestartup",
  1185. };
  1186. // stream everything but critical sounds
  1187. bStream = true;
  1188. char cleanName[MAX_PATH];
  1189. V_strncpy( cleanName, pSndFilename, sizeof( cleanName ) );
  1190. V_FixSlashes( cleanName, '/' );
  1191. for ( int i = 0; bStream && i < ARRAYSIZE( s_CriticalSounds ); i++ )
  1192. {
  1193. if ( StringHasPrefix( cleanName, s_CriticalSounds[i] ) )
  1194. {
  1195. // never stream these, regardless of sound chars
  1196. bStream = false;
  1197. }
  1198. }
  1199. // some broad classified critical sounds can actually stream
  1200. for ( int i = 0; !bStream && i < ARRAYSIZE( s_NonCriticalSounds ); i++ )
  1201. {
  1202. if ( V_stristr( cleanName, s_NonCriticalSounds[i] ) )
  1203. {
  1204. bStream = true;
  1205. }
  1206. }
  1207. #if defined( _X360 )
  1208. // shutdown streaming sounds ONLY during the main menu while the installer might go active or is active
  1209. if ( bStream && V_stristr( cleanName, "music/mainmenu" ) &&
  1210. g_pXboxInstaller->IsInstallEnabled() && !g_pXboxInstaller->IsFullyInstalled() )
  1211. {
  1212. // installer only runs during main menu UI
  1213. // cannot stream at all during installer
  1214. // force this background ui music to not stream
  1215. bStream = false;
  1216. }
  1217. #endif
  1218. }
  1219. if ( bStream )
  1220. {
  1221. // setup as a streaming resource
  1222. pSfx->pSource = Audio_CreateStreamedWave( pSfx );
  1223. }
  1224. else
  1225. {
  1226. if ( bUserVox )
  1227. {
  1228. if ( !IsGameConsole() )
  1229. {
  1230. pSfx->pSource = Voice_SetupAudioSource( ch->soundsource, ch->entchannel );
  1231. }
  1232. else
  1233. {
  1234. // not supporting
  1235. Assert( 0 );
  1236. }
  1237. }
  1238. else
  1239. {
  1240. // load all into memory directly
  1241. pSfx->pSource = Audio_CreateMemoryWave( pSfx );
  1242. }
  1243. }
  1244. if ( IsGameConsole() )
  1245. {
  1246. // need to track these
  1247. pSfx->m_bIsCreatedByQueuedLoader = g_pQueuedLoader->IsMapLoading();
  1248. }
  1249. double ed = Plat_FloatTime();
  1250. g_flAccumulatedSoundLoadTime += ( ed - st );
  1251. }
  1252. else
  1253. {
  1254. pSfx->pSource->CheckAudioSourceCache();
  1255. }
  1256. if ( !pSfx->pSource )
  1257. {
  1258. soundError = SE_NO_SOURCE_SETUP;
  1259. return NULL;
  1260. }
  1261. // first time to load? Create the mixer
  1262. if ( ch && !ch->pMixer )
  1263. {
  1264. ch->pMixer = pSfx->pSource->CreateMixer(ch->initialStreamPosition, ch->skipInitialSamples, ch->flags.m_bUpdateDelayForChoreo, soundError, ch->wavtype == CHAR_HRTF ? &ch->hrtf : nullptr);
  1265. if ( !ch->pMixer )
  1266. {
  1267. return NULL;
  1268. }
  1269. }
  1270. return pSfx->pSource;
  1271. }
  1272. //-----------------------------------------------------------------------------
  1273. // S_PrecacheSound
  1274. //
  1275. // Reserve space for the name of the sound in a global array.
  1276. // Load the data for the non-streaming sound. Streaming sounds
  1277. // defer loading of data until just before playback.
  1278. //-----------------------------------------------------------------------------
  1279. CSfxTable *S_PrecacheSound( const char *name )
  1280. {
  1281. if ( !g_AudioDevice )
  1282. return NULL;
  1283. if ( !g_AudioDevice->IsActive() )
  1284. return NULL;
  1285. CSfxTable *sfx = S_FindName( name, NULL );
  1286. if ( sfx )
  1287. {
  1288. // cache sound
  1289. SoundError soundError;
  1290. S_LoadSound( sfx, NULL, soundError );
  1291. }
  1292. else
  1293. {
  1294. Assert( !"S_PrecacheSound: Failed to create sfx" );
  1295. }
  1296. return sfx;
  1297. }
  1298. void S_InternalReloadSound( CSfxTable *sfx )
  1299. {
  1300. if ( !sfx || !sfx->pSource )
  1301. return;
  1302. sfx->pSource->CacheUnload();
  1303. delete sfx->pSource;
  1304. sfx->pSource = NULL;
  1305. char pExt[10];
  1306. char nameBuf[MAX_PATH];
  1307. Q_ExtractFileExtension( sfx->getname(nameBuf,sizeof(nameBuf)), pExt, sizeof(pExt) );
  1308. int nSource = !Q_stricmp( pExt, "mp3" ) ? CAudioSource::AUDIO_SOURCE_MP3 : CAudioSource::AUDIO_SOURCE_WAV;
  1309. // audiosourcecache->RebuildCacheEntry( nSource, sfx->IsPrecachedSound(), sfx );
  1310. audiosourcecache->GetInfo( nSource, sfx->IsPrecachedSound(), sfx ); // Do a size/date check and rebuild the cache entry if necessary.
  1311. }
  1312. //-----------------------------------------------------------------------------
  1313. // Refresh a sound in the cache
  1314. //-----------------------------------------------------------------------------
  1315. void S_ReloadSound( const char *name )
  1316. {
  1317. if ( IsGameConsole() )
  1318. {
  1319. // not supporting
  1320. Assert( 0 );
  1321. return;
  1322. }
  1323. if ( !g_AudioDevice )
  1324. return;
  1325. if ( !g_AudioDevice->IsActive() )
  1326. return;
  1327. CSfxTable *sfx = S_FindName( name, NULL );
  1328. #ifdef _DEBUG
  1329. if ( sfx )
  1330. {
  1331. char nameBuf[MAX_PATH];
  1332. Assert( Q_stricmp( sfx->getname(nameBuf, sizeof(nameBuf)), name ) == 0 );
  1333. }
  1334. #endif
  1335. S_InternalReloadSound( sfx );
  1336. }
  1337. // See comments on CL_HandlePureServerWhitelist for details of what we're doing here.
  1338. void S_ReloadFilesInList( IFileList *pFilesToReload )
  1339. {
  1340. if ( !IsPC() )
  1341. return;
  1342. S_StopAllSounds( true );
  1343. wavedatacache->Flush();
  1344. // Reload any sounds that are:
  1345. // a) not from the Steam caches
  1346. // b) not in the whitelist
  1347. int iLast = s_Sounds.LastInorder();
  1348. for ( int i = s_Sounds.FirstInorder(); i != iLast; i = s_Sounds.NextInorder( i ) )
  1349. {
  1350. FileNameHandle_t fnHandle = s_Sounds.Key( i );
  1351. char filename[MAX_PATH * 3];
  1352. if ( !g_pFileSystem->String( fnHandle, filename, sizeof( filename ) ) )
  1353. {
  1354. Assert( !"S_HandlePureServerWhitelist - can't get a filename." );
  1355. continue;
  1356. }
  1357. // If the file isn't cached in yet, then the filesystem hasn't touched its file, so don't bother.
  1358. CSfxTable *sfx = s_Sounds[i].pSfx;
  1359. if ( sfx )
  1360. {
  1361. char fullFilename[MAX_PATH*2];
  1362. if ( IsSoundChar( filename[0] ) )
  1363. Q_snprintf( fullFilename, sizeof( fullFilename ), "sound/%s", &filename[1] );
  1364. else
  1365. Q_snprintf( fullFilename, sizeof( fullFilename ), "sound/%s", filename );
  1366. S_InternalReloadSound( sfx );
  1367. }
  1368. }
  1369. }
  1370. //-----------------------------------------------------------------------------
  1371. // Unfortunate confusing terminology.
  1372. // Here prefetching means hinting to the audio source (which may be a stream)
  1373. // to get its async data in flight.
  1374. //-----------------------------------------------------------------------------
  1375. void S_PrefetchSound( char const *name, bool bPlayOnce )
  1376. {
  1377. CSfxTable *sfx;
  1378. if ( !g_AudioDevice )
  1379. return;
  1380. if ( !g_AudioDevice->IsActive() )
  1381. return;
  1382. sfx = S_FindName( name, NULL );
  1383. if ( sfx )
  1384. {
  1385. // cache sound
  1386. SoundError soundError;
  1387. S_LoadSound( sfx, NULL, soundError );
  1388. }
  1389. if ( !sfx || !sfx->pSource )
  1390. {
  1391. return;
  1392. }
  1393. // hint the sound to start loading
  1394. sfx->pSource->Prefetch();
  1395. if ( bPlayOnce )
  1396. {
  1397. sfx->pSource->SetPlayOnce( true );
  1398. }
  1399. }
  1400. void S_MarkUISound( CSfxTable *pSfx )
  1401. {
  1402. pSfx->m_bIsUISound = true;
  1403. }
  1404. unsigned int RemainingSamples( channel_t *pChannel )
  1405. {
  1406. if ( !pChannel || !pChannel->sfx || !pChannel->sfx->pSource )
  1407. return 0;
  1408. unsigned int timeleft = pChannel->sfx->pSource->SampleCount();
  1409. if ( pChannel->sfx->pSource->IsLooped() )
  1410. {
  1411. return pChannel->sfx->pSource->SampleRate();
  1412. }
  1413. if ( pChannel->pMixer )
  1414. {
  1415. timeleft -= pChannel->pMixer->GetSamplePosition();
  1416. }
  1417. return timeleft;
  1418. }
  1419. // chooses the voice stealing algorithm
  1420. ConVar voice_steal("voice_steal", "2");
  1421. float ClosestListenerDistSqr( const Vector &check )
  1422. {
  1423. float bestDSqr = FLT_MAX;
  1424. FOR_EACH_VALID_SPLITSCREEN_PLAYER( hh )
  1425. {
  1426. float distSqr = check.DistToSqr( listener_origin[ hh ] );
  1427. if ( distSqr < bestDSqr )
  1428. {
  1429. bestDSqr = distSqr;
  1430. }
  1431. }
  1432. return bestDSqr;
  1433. }
  1434. /*
  1435. =================
  1436. SND_StealDynamicChannel
  1437. Select a channel from the dynamic channel allocation area. For the given entity,
  1438. override any other sound playing on the same channel (see code comments below for
  1439. exceptions).
  1440. =================
  1441. */
  1442. channel_t *SND_StealDynamicChannel(SoundSource soundsource, int entchannel, const Vector &origin, CSfxTable *sfx)
  1443. {
  1444. int canSteal[MAX_DYNAMIC_CHANNELS];
  1445. int canStealCount = 0;
  1446. int sameSoundCount = 0;
  1447. unsigned int sameSoundRemaining = 0xFFFFFFFF;
  1448. int sameSoundIndex = -1;
  1449. int sameVol = 0xFFFF;
  1450. int availableChannel = -1;
  1451. bool bDelaySame = false;
  1452. // first pass to replace sounds on same ent/channel, and search for free or stealable channels otherwise
  1453. for ( int ch_idx = 0; ch_idx < MAX_DYNAMIC_CHANNELS ; ++ch_idx )
  1454. {
  1455. channel_t *ch = &channels[ch_idx];
  1456. if ( ch->activeIndex )
  1457. {
  1458. bool canStealThisChannel = ch->entchannel != CHAN_STREAM && ch->entchannel != CHAN_VOICE && ch->entchannel < CHAN_USER_BASE;
  1459. canStealThisChannel = canStealThisChannel && (ch->entchannel < CHAN_VOICE_BASE || ch->entchannel >= CHAN_VOICE_BASE + VOICE_NUM_CHANNELS);
  1460. // channel CHAN_AUTO never overrides sounds on same channel
  1461. if ( entchannel != CHAN_AUTO )
  1462. {
  1463. int checkChannel = entchannel;
  1464. if ( checkChannel == -1 )
  1465. {
  1466. if ( canStealThisChannel )
  1467. {
  1468. checkChannel = ch->entchannel;
  1469. }
  1470. }
  1471. // delayed channels are never overridden
  1472. if ( !ch->flags.delayed_start &&
  1473. ch->soundsource == soundsource &&
  1474. (soundsource != -1) &&
  1475. ch->entchannel == checkChannel )
  1476. {
  1477. return ch; // always override sound from same entity
  1478. }
  1479. }
  1480. // Never steal the channel of a streaming sound that is currently playing or
  1481. // voice over IP data that is playing or any sound on CHAN_VOICE( acting )
  1482. if ( !canStealThisChannel )
  1483. continue;
  1484. // don't let monster sounds override player sounds
  1485. if ( g_pSoundServices->IsPlayer( ch->soundsource ) && !g_pSoundServices->IsPlayer(soundsource) )
  1486. continue;
  1487. if ( ch->sfx == sfx )
  1488. {
  1489. int maxVolume = ChannelGetMaxVol( ch );
  1490. // TERROR: prevent DSP from causing weapon sounds to be skipped
  1491. if ( entchannel == CHAN_WEAPON )
  1492. {
  1493. maxVolume = 255;
  1494. // TERROR: Allow each player's weapons to be stolen individually
  1495. if ( ch->soundsource != soundsource )
  1496. {
  1497. continue;
  1498. }
  1499. }
  1500. bDelaySame = ch->flags.delayed_start ? true : bDelaySame;
  1501. sameSoundCount++;
  1502. unsigned int remaining = RemainingSamples(ch);
  1503. if ( maxVolume < sameVol || (maxVolume == sameVol && remaining < sameSoundRemaining) )
  1504. {
  1505. sameSoundIndex = ch_idx;
  1506. sameVol = maxVolume;
  1507. sameSoundRemaining = remaining;
  1508. }
  1509. }
  1510. canSteal[canStealCount++] = ch_idx;
  1511. }
  1512. else
  1513. {
  1514. if ( availableChannel < 0 )
  1515. {
  1516. availableChannel = ch_idx;
  1517. }
  1518. }
  1519. }
  1520. // Limit the number of times a given sfx/wave can play simultaneously
  1521. if ( voice_steal.GetInt() > 1 && sameSoundIndex >= 0 )
  1522. {
  1523. // if sounds of this type are normally delayed, then add an extra slot for stealing
  1524. // NOTE: In HL2 these are usually NPC gunshot sounds - and stealing too soon will cut
  1525. // them off early. This is a safe heuristic to avoid that problem. There's probably a better
  1526. // long-term solution involving only counting channels that are actually going to play (delay included)
  1527. // at the same time as this one.
  1528. int maxSameSounds = bDelaySame ? snd_max_same_sounds.GetInt() + 1 : snd_max_same_sounds.GetInt();
  1529. if ( entchannel == CHAN_WEAPON )
  1530. {
  1531. maxSameSounds = bDelaySame ? snd_max_same_weapon_sounds.GetInt() + 1 : snd_max_same_weapon_sounds.GetInt();
  1532. }
  1533. float distSqr = 0.0f;
  1534. if ( sfx->pSource )
  1535. {
  1536. if ( sfx->pSource->IsLooped() )
  1537. {
  1538. maxSameSounds = 3;
  1539. }
  1540. distSqr = ClosestListenerDistSqr( origin );
  1541. }
  1542. // don't play more than N copies of the same sound, steal the quietest & closest one otherwise
  1543. if ( sameSoundCount >= maxSameSounds )
  1544. {
  1545. channel_t *ch = &channels[sameSoundIndex];
  1546. // you're already playing a closer version of this sound, don't steal
  1547. if ( distSqr > 0.0f &&
  1548. ClosestListenerDistSqr( ch->origin ) < distSqr &&
  1549. entchannel != CHAN_WEAPON )
  1550. return NULL;
  1551. // Msg("Sound playing %d copies, stole %s (%d) %i, %i, %u\n", sameSoundCount, ch->sfx->getname(), sameVol, ch->soundsource, soundsource, RemainingSamples(ch) );
  1552. return ch;
  1553. }
  1554. }
  1555. // if there's a free channel, just take that one - don't steal
  1556. if ( availableChannel >= 0 )
  1557. return &channels[availableChannel];
  1558. // Still haven't found a suitable channel, so choose the one with the least amount of time left to play
  1559. float life_left = FLT_MAX;
  1560. int first_to_die = -1;
  1561. bool bAllowVoiceSteal = voice_steal.GetBool();
  1562. for ( int i = 0; i < canStealCount; i++ )
  1563. {
  1564. int ch_idx = canSteal[i];
  1565. channel_t *ch = &channels[ch_idx];
  1566. float timeleft = 0;
  1567. if ( bAllowVoiceSteal )
  1568. {
  1569. // TERROR: don't steal looped sounds
  1570. if ( ch->sfx && ch->sfx->pSource )
  1571. {
  1572. if ( ch->sfx->pSource->IsLooped() )
  1573. continue;
  1574. }
  1575. int maxVolume = ChannelGetMaxVol( ch );
  1576. if ( maxVolume < 5 )
  1577. {
  1578. //Msg("Sound quiet, stole %s for %s\n", ch->sfx->getname(), sfx->getname() );
  1579. return ch;
  1580. }
  1581. if ( ch->sfx && ch->sfx->pSource )
  1582. {
  1583. unsigned int sampleCount = RemainingSamples( ch );
  1584. timeleft = (float)sampleCount / (float)ch->sfx->pSource->SampleRate();
  1585. }
  1586. // TERROR: bias weapon sounds longer so they don't get stolen when possible
  1587. if ( ch->entchannel == CHAN_WEAPON )
  1588. {
  1589. timeleft += 5.0f;
  1590. }
  1591. }
  1592. else
  1593. {
  1594. // UNDONE: Kill this when voice_steal 0,1,2 has been tested
  1595. // UNDONE: This is the old buggy code that we're trying to replace
  1596. if ( ch->sfx )
  1597. {
  1598. // basically steals the first one you come to
  1599. timeleft = 1; //ch->end - paintedtime
  1600. }
  1601. }
  1602. if ( timeleft < life_left )
  1603. {
  1604. life_left = timeleft;
  1605. first_to_die = ch_idx;
  1606. }
  1607. }
  1608. if ( first_to_die >= 0 )
  1609. {
  1610. //Msg("Stole %s, timeleft %d\n", channels[first_to_die].sfx->getname(), life_left );
  1611. return &channels[first_to_die];
  1612. }
  1613. return NULL;
  1614. }
  1615. channel_t *SND_PickDynamicChannel(SoundSource soundsource, int entchannel, const Vector &origin, CSfxTable *sfx)
  1616. {
  1617. channel_t *pChannel = SND_StealDynamicChannel( soundsource, entchannel, origin, sfx );
  1618. if ( !pChannel )
  1619. return NULL;
  1620. if ( pChannel->sfx )
  1621. {
  1622. // Don't restart looping sounds for the same entity
  1623. CAudioSource *pSource = pChannel->sfx->pSource;
  1624. if ( pSource )
  1625. {
  1626. if ( pSource->IsLooped() )
  1627. {
  1628. if ( pChannel->soundsource == soundsource && pChannel->entchannel == entchannel && pChannel->sfx == sfx )
  1629. {
  1630. // same looping sound, same ent, same channel, don't restart the sound
  1631. return NULL;
  1632. }
  1633. }
  1634. }
  1635. // be sure and release previous channel
  1636. // if sentence.
  1637. // ("Stealing channel from %s\n", channels[first_to_die].sfx->getname() );
  1638. if ( snd_report_verbose_error.GetBool() )
  1639. {
  1640. char sndname[MAX_PATH];
  1641. Msg( "%s(%d): Stealing channel from sound '%s'.\n", __FILE__, __LINE__, pChannel->sfx->GetFileName( sndname, sizeof( sndname ) ) );
  1642. }
  1643. S_FreeChannel(pChannel);
  1644. }
  1645. return pChannel;
  1646. }
  1647. /*
  1648. =====================
  1649. SND_PickStaticChannel
  1650. =====================
  1651. Pick an empty channel from the static sound area, or allocate a new
  1652. channel. Only fails if we're at max_channels (128!!!) or if
  1653. we're trying to allocate a channel for a stream sound that is
  1654. already playing.
  1655. */
  1656. channel_t *SND_PickStaticChannel(int soundsource, CSfxTable *pSfx)
  1657. {
  1658. int i;
  1659. channel_t *ch = NULL;
  1660. // Check for replacement sound, or find the best one to replace
  1661. for (i = MAX_DYNAMIC_CHANNELS; i<total_channels; i++)
  1662. if (channels[i].sfx == NULL)
  1663. break;
  1664. if (i < total_channels)
  1665. {
  1666. // reuse an empty static sound channel
  1667. ch = &channels[i];
  1668. }
  1669. else
  1670. {
  1671. // const int MAX_CHANNELS_MESSAGE = (3 * ( MAX_CHANNELS ) ) / 4;
  1672. // if ( total_channels > MAX_CHANNELS_MESSAGE )
  1673. // {
  1674. // DevMsg( "Warning: more than 3/4 of all static channels have been used: > %d\n", total_channels - MAX_DYNAMIC_CHANNELS );
  1675. // no empty slots, alloc a new static sound channel
  1676. if (total_channels == MAX_CHANNELS)
  1677. {
  1678. Warning( "Error: Total static audio channels have been used: %d ", MAX_CHANNELS - MAX_DYNAMIC_CHANNELS );
  1679. for (i = MAX_DYNAMIC_CHANNELS; i < total_channels; i++)
  1680. {
  1681. char buff[4096];
  1682. channels[i].sfx->GetFileName(buff, sizeof(buff));
  1683. Warning("%d, %s ", i, buff);
  1684. }
  1685. Warning("\n");
  1686. static bool bFirst = true;
  1687. if ( bFirst )
  1688. {
  1689. bFirst = false;
  1690. S_SoundInfo_f();
  1691. }
  1692. return NULL;
  1693. }
  1694. // }
  1695. // get a channel for the static sound
  1696. ch = &channels[total_channels];
  1697. if ( snd_report_verbose_error.GetBool() )
  1698. {
  1699. Msg( "%s(%d): Recycle channel index %d.\n", __FILE__, __LINE__, total_channels );
  1700. }
  1701. total_channels++;
  1702. }
  1703. return ch;
  1704. }
  1705. // &7DL Re-enabled, called from snd_dev_sdl.cpp
  1706. void S_SpatializeChannel( int nSlot, int volume[CCHANVOLUMES/2], int master_vol, const Vector *psourceDir, float gain, float mono )
  1707. {
  1708. float lscale, rscale, scale;
  1709. vec_t dotRight;
  1710. Vector sourceDir = *psourceDir;
  1711. dotRight = DotProduct(listener_right[ nSlot ], sourceDir);
  1712. // clear volumes
  1713. for (int i = 0; i < CCHANVOLUMES/2; i++)
  1714. volume[i] = 0;
  1715. if (mono > 0.0)
  1716. {
  1717. // sound has radius, within which spatialization becomes mono:
  1718. // mono is 0.0 -> 1.0, from radius 100% to radius 50%
  1719. // at radius * 0.5, dotRight is 0 (ie: sound centered left/right)
  1720. // at radius * 1.0, dotRight == dotRight
  1721. dotRight *= (1.0 - mono);
  1722. }
  1723. rscale = 1.0 + dotRight;
  1724. lscale = 1.0 - dotRight;
  1725. // add in distance effect
  1726. scale = gain * rscale / 2;
  1727. volume[IFRONT_RIGHT] = (int) (master_vol * scale);
  1728. scale = gain * lscale / 2;
  1729. volume[IFRONT_LEFT] = (int) (master_vol * scale);
  1730. volume[IFRONT_RIGHT] = clamp( volume[IFRONT_RIGHT], 0, 255 );
  1731. volume[IFRONT_LEFT] = clamp( volume[IFRONT_LEFT], 0, 255 );
  1732. }
  1733. bool S_IsPlayerVoice( channel_t *pChannel )
  1734. {
  1735. CSfxTable *sfx = pChannel->sfx;
  1736. if ( !sfx )
  1737. return false;
  1738. CAudioSource *source = sfx->pSource;
  1739. if ( !source )
  1740. return false;
  1741. return source->IsPlayerVoice();
  1742. }
  1743. bool S_IsMusic( channel_t *pChannel )
  1744. {
  1745. if ( !pChannel->flags.bdry )
  1746. return false;
  1747. CSfxTable *sfx = pChannel->sfx;
  1748. if ( !sfx )
  1749. return false;
  1750. CAudioSource *source = sfx->pSource;
  1751. if ( !source )
  1752. return false;
  1753. // Don't save restore looping sounds as you can end up with an entity restarting them again and have
  1754. // them accumulate, etc.
  1755. if ( source->IsLooped() )
  1756. return false;
  1757. CAudioMixer *pMixer = pChannel->pMixer;
  1758. if ( !pMixer )
  1759. return false;
  1760. if ( sfx->m_bIsMusic )
  1761. return true;
  1762. bool bIsMp3 = ( source->GetType() == CAudioSource::AUDIO_SOURCE_MP3 ) ? true : false;
  1763. for ( int i = 0; i < 8; i++ )
  1764. {
  1765. if ( pChannel->mixgroups[i] != -1 )
  1766. {
  1767. char *pGroupName = MXR_GetGroupnameFromId( pChannel->mixgroups[i] );
  1768. // HACK: Consider mp3s playing in the UI as music since the only cases of that
  1769. // currently are startup music files e.g. #ui/gamestartup1.mp3
  1770. if ( !Q_strcmp( pGroupName, "Music" ) || (bIsMp3 && !Q_stricmp(pGroupName,"UI")))
  1771. {
  1772. return true;
  1773. }
  1774. }
  1775. }
  1776. return false;
  1777. }
  1778. //-----------------------------------------------------------------------------
  1779. // Purpose: For save/restore of currently playing music
  1780. // Input : list -
  1781. //-----------------------------------------------------------------------------
  1782. void S_GetCurrentlyPlayingMusic( CUtlVector< musicsave_t >& musiclist )
  1783. {
  1784. CChannelList list;
  1785. g_ActiveChannels.GetActiveChannels( list );
  1786. for ( int i = 0; i < list.Count(); i++ )
  1787. {
  1788. channel_t *pChannel = &channels[list.GetChannelIndex(i)];
  1789. if ( !S_IsMusic( pChannel ) )
  1790. continue;
  1791. musicsave_t song;
  1792. char nameBuf[MAX_PATH];
  1793. Q_strncpy( song.songname, pChannel->sfx->getname(nameBuf,sizeof(nameBuf)), sizeof( song.songname ) );
  1794. song.sampleposition = pChannel->pMixer->GetPositionForSave();
  1795. song.master_volume = pChannel->master_vol;
  1796. musiclist.AddToTail( song );
  1797. }
  1798. }
  1799. //-----------------------------------------------------------------------------
  1800. // Purpose:
  1801. // Input : *song -
  1802. //-----------------------------------------------------------------------------
  1803. void S_RestartSong( const musicsave_t *song )
  1804. {
  1805. Assert( song );
  1806. // Start the song
  1807. CSfxTable *pSound = S_PrecacheSound( song->songname );
  1808. if ( pSound )
  1809. {
  1810. StartSoundParams_t params;
  1811. params.staticsound = true;
  1812. params.soundsource = SOUND_FROM_WORLD;
  1813. params.entchannel = CHAN_STATIC;
  1814. params.pSfx = pSound;
  1815. params.origin = vec3_origin;
  1816. params.fvol = ( (float)song->master_volume / 255.0f );
  1817. params.soundlevel = SNDLVL_NONE;
  1818. params.flags = SND_NOFLAGS;
  1819. params.pitch = PITCH_NORM;
  1820. params.initialStreamPosition = song->sampleposition;
  1821. S_StartSound( params );
  1822. if ( IsPC() )
  1823. {
  1824. // Now find the channel this went on and skip ahead in the mixer
  1825. for (int i = 0; i < total_channels; i++)
  1826. {
  1827. channel_t *ch = &channels[i];
  1828. if ( !ch->pMixer ||
  1829. !ch->pMixer->GetSource() )
  1830. {
  1831. continue;
  1832. }
  1833. if ( ch->pMixer->GetSource() != pSound->pSource )
  1834. {
  1835. continue;
  1836. }
  1837. ch->pMixer->SetPositionFromSaved( song->sampleposition );
  1838. break;
  1839. }
  1840. }
  1841. }
  1842. }
  1843. bool S_ShouldSaveRestore( channel_t const* pChannel )
  1844. {
  1845. // Invalid sound or audio source
  1846. if( !pChannel->sfx || !pChannel->sfx->pSource )
  1847. return false;
  1848. // No mixer
  1849. if( !pChannel->pMixer )
  1850. return false;
  1851. return pChannel->flags.m_bShouldSaveRestore;
  1852. }
  1853. void S_GetActiveSaveRestoreChannels( ChannelSaveVector& channelSaves )
  1854. {
  1855. CChannelList channelList;
  1856. g_ActiveChannels.GetActiveChannels( channelList );
  1857. for( int i = 0; i < channelList.Count(); ++i )
  1858. {
  1859. channel_t const& channel = channels[channelList.GetChannelIndex(i)];
  1860. if( S_ShouldSaveRestore( &channel ) )
  1861. {
  1862. channelsave channelSave;
  1863. if( channel.m_nSoundScriptHash != SOUNDEMITTER_INVALID_HASH )
  1864. V_strcpy( channelSave.soundName, g_pSoundEmitterSystem->GetSoundNameForHash( channel.m_nSoundScriptHash ) );
  1865. else
  1866. channel.sfx->getname( channelSave.soundName, sizeof( channelSave.soundName ) );
  1867. channelSave.origin = channel.origin;
  1868. channelSave.soundLevel = static_cast<soundlevel_t>( static_cast<int>( channel.m_flSoundLevel ) );
  1869. channelSave.soundSource = channel.soundsource;
  1870. channelSave.entChannel = channel.entchannel;
  1871. channelSave.masterVolume = channel.master_vol;
  1872. channelSave.pitch = channel.basePitch;
  1873. if( channel.m_pStackList )
  1874. {
  1875. // Note: According to Mike Morasky, elapsed time should only matter for the update stack, so if
  1876. // the stack list doesn't contain one, its value won't matter on restore.
  1877. const CSosOperatorStack* pUpdateStack = channel.m_pStackList->GetStack( CSosOperatorStack::SOS_UPDATE );
  1878. channelSave.opStackElapsedTime = pUpdateStack != NULL ? pUpdateStack->GetElapsedTime() : 0.0f;
  1879. channelSave.opStackElapsedStopTime = channel.m_pStackList->GetElapsedStopTime();
  1880. }
  1881. else
  1882. {
  1883. channelSave.opStackElapsedTime = S_GetElapsedTime( &channel );
  1884. channelSave.opStackElapsedStopTime = 0.0f;
  1885. }
  1886. channelSaves.AddToTail( channelSave );
  1887. }
  1888. }
  1889. }
  1890. channel_t* S_FindDuplicateChannel( StartSoundParams_t const& params )
  1891. {
  1892. THREAD_LOCK_SOUND();
  1893. CChannelList list;
  1894. g_ActiveChannels.GetActiveChannels( list );
  1895. channel_t* pDuplicateChannel = NULL;
  1896. bool const shouldIgnoreName = (params.flags & SND_IGNORE_NAME) != 0;
  1897. bool const isScriptSound = params.m_bIsScriptHandle && !shouldIgnoreName;
  1898. float maxElapsedTime = -1.0f;
  1899. for( int i = 0; i < list.Count(); ++i )
  1900. {
  1901. channel_t &currentChannel = channels[list.GetChannelIndex(i)];
  1902. bool const soundMatches = isScriptSound ? currentChannel.m_nSoundScriptHash == params.m_nSoundScriptHash :
  1903. shouldIgnoreName || currentChannel.sfx == params.pSfx;
  1904. // If this is the same sound from the same source on the same entity channel
  1905. if( currentChannel.soundsource == params.soundsource &&
  1906. currentChannel.entchannel == params.entchannel &&
  1907. soundMatches )
  1908. {
  1909. float const timeElapsed = S_GetElapsedTime( &currentChannel );
  1910. // If this isn't a script sound or is the oldest one that isn't stopping
  1911. if( !isScriptSound ||
  1912. ( currentChannel.m_pStackList && !currentChannel.m_pStackList->IsStopping() && timeElapsed > maxElapsedTime) )
  1913. {
  1914. // Consider this the duplicate
  1915. maxElapsedTime = timeElapsed;
  1916. pDuplicateChannel = &currentChannel;
  1917. }
  1918. }
  1919. }
  1920. return pDuplicateChannel;
  1921. }
  1922. void S_RestartChannel( channelsave const& channelSave )
  1923. {
  1924. // Start the channel
  1925. CSfxTable* pSound = S_PrecacheSound( channelSave.soundName );
  1926. if( pSound )
  1927. {
  1928. StartSoundParams_t params;
  1929. params.soundsource = channelSave.soundSource;
  1930. params.entchannel = channelSave.entChannel;
  1931. params.pSfx = pSound;
  1932. params.origin = channelSave.origin;
  1933. params.soundlevel = channelSave.soundLevel;
  1934. params.pitch = channelSave.pitch;
  1935. params.fvol = channelSave.masterVolume / 255.0f;
  1936. params.m_nSoundScriptHash = g_pSoundEmitterSystem->HashSoundName( channelSave.soundName );
  1937. params.m_bIsScriptHandle = params.m_nSoundScriptHash != SOUNDEMITTER_INVALID_HASH;
  1938. params.flags = SND_CHANGE_VOL | SND_CHANGE_PITCH;
  1939. params.flags |= params.m_bIsScriptHandle ? SND_IS_SCRIPTHANDLE : 0;
  1940. params.opStackElapsedTime = channelSave.opStackElapsedTime;
  1941. params.opStackElapsedStopTime = channelSave.opStackElapsedStopTime;
  1942. params.delay = -params.opStackElapsedTime; // For non-script entries (currently not saved), this will simply be the elapsed time
  1943. params.staticsound = params.entchannel == CHAN_STATIC ? true : false;
  1944. channel_t* pDuplicateChannel = S_FindDuplicateChannel( params );
  1945. if( pDuplicateChannel != NULL )
  1946. S_StopChannel( pDuplicateChannel );
  1947. S_StartSoundEntry( params, -1, false );
  1948. }
  1949. }
  1950. soundlevel_t SND_GetSndlvl ( channel_t *pchannel );
  1951. // calculate ammount of sound to be mixed to dsp, based on distance from listener
  1952. ConVar dsp_dist_min("dsp_dist_min", "0.0", FCVAR_DEMO|FCVAR_CHEAT); // range at which sounds are mixed at dsp_mix_min
  1953. ConVar dsp_dist_max("dsp_dist_max", "1440.0", FCVAR_DEMO|FCVAR_CHEAT); // range at which sounds are mixed at dsp_mix_max
  1954. ConVar dsp_mix_min("dsp_mix_min", "0.2", FCVAR_DEMO|FCVAR_CHEAT ); // dsp mix at dsp_dist_min distance "near"
  1955. ConVar dsp_mix_max("dsp_mix_max", "0.8", FCVAR_DEMO|FCVAR_CHEAT ); // dsp mix at dsp_dist_max distance "far"
  1956. ConVar dsp_db_min("dsp_db_min", "80", FCVAR_DEMO|FCVAR_CHEAT ); // sounds with sndlvl below this get dsp_db_mixdrop % less dsp mix
  1957. ConVar dsp_db_mixdrop("dsp_db_mixdrop", "0.5", FCVAR_DEMO|FCVAR_CHEAT ); // sounds with sndlvl below dsp_db_min get dsp_db_mixdrop % less mix
  1958. float DSP_ROOM_MIX = 1.0; // mix volume of dsp_room sounds when added back to 'dry' sounds
  1959. float DSP_NOROOM_MIX = 1.0; // mix volume of facing + facing away sounds. added to dsp_room_mix sounds
  1960. extern ConVar dsp_off;
  1961. // returns 0-1.0 dsp mix value. If sound source is at a range >= DSP_DIST_MAX, return a mix value of
  1962. // DSP_MIX_MAX. This mix value is used later to determine wet/dry mix ratio of sounds.
  1963. // This ramp changes with db level of sound source, and is set in the dsp room presets by room size
  1964. // empirical data: 0.78 is nominal mix for sound 100% at far end of room, 0.24 is mix for sound 25% into room
  1965. float SND_GetDspMix( channel_t *pchannel, int idist, float flSndlvl)
  1966. {
  1967. float mix;
  1968. float dist = (float)idist;
  1969. float dist_min = dsp_dist_min.GetFloat();
  1970. float dist_max = dsp_dist_max.GetFloat();
  1971. float mix_min;
  1972. float mix_max;
  1973. // only set dsp mix_min & mix_max when sound is first started
  1974. if ( pchannel->dsp_mix_min < 0 && pchannel->dsp_mix_max < 0 )
  1975. {
  1976. mix_min = dsp_mix_min.GetFloat(); // set via dsp_room preset
  1977. mix_max = dsp_mix_max.GetFloat(); // set via dsp_room preset
  1978. // set mix_min & mix_max based on db level of sound:
  1979. // sounds below dsp_db_min decrease dsp_mix_min & dsp_mix_max by N%
  1980. // ie: quiet sounds get less dsp mix than loud sounds
  1981. soundlevel_t sndlvl_min = (soundlevel_t)(dsp_db_min.GetInt());
  1982. if (( (int) flSndlvl) <= sndlvl_min)
  1983. {
  1984. mix_min *= dsp_db_mixdrop.GetFloat();
  1985. mix_max *= dsp_db_mixdrop.GetFloat();
  1986. }
  1987. pchannel->dsp_mix_min = mix_min;
  1988. pchannel->dsp_mix_max = mix_max;
  1989. }
  1990. else
  1991. {
  1992. mix_min = pchannel->dsp_mix_min;
  1993. mix_max = pchannel->dsp_mix_max;
  1994. }
  1995. // dspmix is 0 (100% mix to facing buffer) if dsp_off
  1996. if ( dsp_off.GetInt() )
  1997. return 0.0;
  1998. // linear ramp - get dry mix %
  1999. // dist: 0->(max - min)
  2000. dist = clamp( dist, dist_min, dist_max ) - dist_min;
  2001. // dist: 0->1.0
  2002. dist = dist / (dist_max - dist_min);
  2003. // mix: min->max
  2004. mix = ((mix_max - mix_min) * dist) + mix_min;
  2005. return mix;
  2006. }
  2007. float SND_GetDspMix( channel_t *pchannel, int idist)
  2008. {
  2009. // doppler wavs are mixed dry
  2010. if ( pchannel->wavtype == CHAR_DOPPLER )
  2011. return 0.0;
  2012. soundlevel_t sndlvl = SND_GetSndlvl( pchannel );
  2013. return SND_GetDspMix( pchannel, idist, sndlvl );
  2014. }
  2015. // calculate crossfade between wav left (close sound) and wav right (far sound) based on
  2016. // distance fron listener
  2017. ConVar snd_dvar_dist_min( "snd_dvar_dist_min", "240" /* (20.0 * 12.0) */, FCVAR_CHEAT, "Play full 'near' sound at this distance" );
  2018. ConVar snd_dvar_dist_max( "snd_dvar_dist_max", "1320" /* (110.0 * 12.0) */, FCVAR_CHEAT, "Play full 'far' sound at this distance" );
  2019. #define DVAR_MIX_MIN 0.0
  2020. #define DVAR_MIX_MAX 1.0
  2021. // calculate mixing parameter for CHAR_DISTVAR wavs
  2022. // returns 0 - 1.0, 1.0 is 100% far sound (wav right)
  2023. float SND_GetDistanceMix( channel_t *pchannel, int idist)
  2024. {
  2025. float mix;
  2026. float dist = (float)idist;
  2027. // doppler wavs are 100% near - their spatialization is calculated later.
  2028. if ( pchannel->wavtype == CHAR_DOPPLER || pchannel->wavtype == CHAR_DIRSTEREO )
  2029. return 0.0;
  2030. // linear ramp - get dry mix %
  2031. // dist 0->(max - min)
  2032. dist = clamp( dist, snd_dvar_dist_min.GetFloat(), snd_dvar_dist_max.GetFloat() ) - snd_dvar_dist_min.GetFloat();
  2033. // dist 0->1.0
  2034. dist = dist / (snd_dvar_dist_max.GetFloat() - snd_dvar_dist_min.GetFloat());
  2035. // mix min->max
  2036. mix = ((DVAR_MIX_MAX - DVAR_MIX_MIN) * dist) + DVAR_MIX_MIN;
  2037. return mix;
  2038. }
  2039. // given facing direction of source, and channel,
  2040. // return -1.0 - 1.0, where -1.0 is source facing away from listener
  2041. // and 1.0 is source facing listener
  2042. float SND_GetFacingDirection( channel_t *pChannel, const Vector &vecListenerOrigin, const QAngle &source_angles )
  2043. {
  2044. Vector SF; // sound source forward direction unit vector
  2045. Vector SL; // sound -> listener unit vector
  2046. float dotSFSL;
  2047. // no facing direction unless wavtyp CHAR_DIRECTIONAL
  2048. // this won't get used anyway if it's not directional
  2049. // if ( pChannel->wavtype != CHAR_DIRECTIONAL )
  2050. // return 1.0;
  2051. VectorSubtract(vecListenerOrigin, pChannel->origin, SL);
  2052. VectorNormalize(SL);
  2053. // compute forward vector for sound entity
  2054. AngleVectors( source_angles, &SF, NULL, NULL );
  2055. // dot source forward unit vector with source to listener unit vector to get -1.0 - 1.0 facing.
  2056. // ie: projection of SF onto SL
  2057. dotSFSL = DotProduct( SF, SL );
  2058. return dotSFSL;
  2059. }
  2060. // calculate point of closest approach - caller must ensure that the
  2061. // forward facing vector of the entity playing this sound points in exactly the direction of
  2062. // travel of the sound. ie: for bullets or tracers, forward vector must point in traceline direction.
  2063. // return true if sound is to be played, false if sound cannot be heard (shot away from player)
  2064. bool SND_GetClosestPoint( channel_t *pChannel, const Vector &vecListenerOrigin, QAngle &source_angles, Vector &vnearpoint )
  2065. {
  2066. // S - sound source origin
  2067. // L - listener origin
  2068. Vector SF; // sound source forward direction unit vector
  2069. Vector SL; // sound -> listener vector
  2070. Vector SD; // sound->closest point vector
  2071. vec_t dSLSF; // magnitude of project of SL onto SF
  2072. // P = SF (SF . SL) + S
  2073. // only perform this calculation for doppler wavs
  2074. if ( pChannel->wavtype != CHAR_DOPPLER )
  2075. return false;
  2076. // get vector 'SL' from sound source to listener
  2077. VectorSubtract(vecListenerOrigin, pChannel->origin, SL);
  2078. // compute sound->forward vector 'SF' for sound entity
  2079. AngleVectors( source_angles, &SF );
  2080. VectorNormalize( SF );
  2081. dSLSF = DotProduct( SL, SF );
  2082. if ( dSLSF <= 0 && !toolframework->IsToolRecording() )
  2083. {
  2084. // source is pointing away from listener, don't play anything
  2085. // unless we're recording in the tool, since we may play back from in front of the source
  2086. return false;
  2087. }
  2088. // project dSLSF along forward unit vector from sound source
  2089. VectorMultiply( SF, dSLSF, SD );
  2090. // output vector - add SD to sound source origin
  2091. VectorAdd( SD, pChannel->origin, vnearpoint );
  2092. return true;
  2093. }
  2094. // given point of nearest approach and sound source facing angles,
  2095. // return vector pointing into quadrant in which to play
  2096. // doppler left wav (incomming) and doppler right wav (outgoing).
  2097. // doppler left is point in space to play left doppler wav
  2098. // doppler right is point in space to play right doppler wav
  2099. // Also modifies channel pitch based on distance to nearest approach point
  2100. #define DOPPLER_DIST_LEFT_TO_RIGHT (4*12) // separate left/right sounds by 4'
  2101. #define DOPPLER_DIST_MAX (20*12) // max distance - causes min pitch
  2102. #define DOPPLER_DIST_MIN (1*12) // min distance - causes max pitch
  2103. #define DOPPLER_PITCH_MAX 1.5 // max pitch change due to distance
  2104. #define DOPPLER_PITCH_MIN 0.25 // min pitch change due to distance
  2105. #define DOPPLER_RANGE_MAX (10*12) // don't play doppler wav unless within this range
  2106. // UNDONE: should be set by caller!
  2107. static void SND_GetDopplerPoints( channel_t *pChannel, const Vector &vecListenerOrigin, QAngle &source_angles, Vector &vnearpoint, Vector &source_doppler_left, Vector &source_doppler_right)
  2108. {
  2109. Vector SF; // direction sound source is facing (forward)
  2110. Vector LN; // vector from listener to closest approach point
  2111. Vector DL;
  2112. Vector DR;
  2113. // nearpoint is closest point of approach, when playing CHAR_DOPPLER sounds
  2114. // SF is normalized vector in direction sound source is facing
  2115. AngleVectors( source_angles, &SF );
  2116. VectorNormalize( SF );
  2117. // source_doppler_left - location in space to play doppler left wav (incomming)
  2118. // source_doppler_right - location in space to play doppler right wav (outgoing)
  2119. VectorMultiply( SF, -1*DOPPLER_DIST_LEFT_TO_RIGHT, DL );
  2120. VectorMultiply( SF, DOPPLER_DIST_LEFT_TO_RIGHT, DR );
  2121. VectorAdd( vnearpoint, DL, source_doppler_left );
  2122. VectorAdd( vnearpoint, DR, source_doppler_right );
  2123. // set pitch of channel based on nearest distance to listener
  2124. // LN is vector from listener to closest approach point
  2125. VectorSubtract(vnearpoint, vecListenerOrigin, LN);
  2126. float pitch;
  2127. float dist = VectorLength( LN );
  2128. // dist varies 0->1
  2129. dist = clamp(dist, DOPPLER_DIST_MIN, DOPPLER_DIST_MAX);
  2130. dist = (dist - DOPPLER_DIST_MIN) / (DOPPLER_DIST_MAX - DOPPLER_DIST_MIN);
  2131. // pitch varies from max to min
  2132. pitch = DOPPLER_PITCH_MAX - dist * (DOPPLER_PITCH_MAX - DOPPLER_PITCH_MIN);
  2133. pChannel->basePitch = (int)(pitch * 100.0);
  2134. }
  2135. // console variables used to construct gain curve - don't change these!
  2136. extern ConVar snd_foliage_db_loss;
  2137. extern ConVar snd_gain;
  2138. extern ConVar snd_gain_max;
  2139. extern ConVar snd_gain_min;
  2140. ConVar snd_showstart( "snd_showstart", "0", FCVAR_CHEAT ); // showstart always skips info on player footsteps!
  2141. // 1 - show sound name, channel, volume, time
  2142. // 2 - show dspmix, distmix, dspface, l/r/f/r vols
  2143. // 3 - show sound origin coords
  2144. // 4 - show gain of dsp_room
  2145. // 5 - show dB loss due to obscured sound
  2146. // 6 - reserved
  2147. // 7 - show 2 and total gain & dist in ft. to sound source
  2148. // snd_showstart reports only the sounds being actively played. To see sounds that should be played but may have been discarded (for errors or other reasons), use snd_report_start_sound.
  2149. #define SND_GAIN_PLAYER_WEAPON_DB 2.0 // increase player weapon gain by N dB
  2150. // dB = 20 log (amplitude/32768) 0 to -90.3dB
  2151. // amplitude = 32768 * 10 ^ (dB/20) 0 to +/- 32768
  2152. // gain = amplitude/32768 0 to 1.0
  2153. float Gain_To_dB ( float gain )
  2154. {
  2155. float dB = 20 * log ( gain );
  2156. return dB;
  2157. }
  2158. float dB_To_Gain ( float dB )
  2159. {
  2160. float gain = powf (10, dB / 20.0);
  2161. return gain;
  2162. }
  2163. float Gain_To_Amplitude ( float gain )
  2164. {
  2165. return gain * 32768;
  2166. }
  2167. float Amplitude_To_Gain ( float amplitude )
  2168. {
  2169. return amplitude / 32768;
  2170. }
  2171. soundlevel_t SND_GetSndlvl ( channel_t *pchannel )
  2172. {
  2173. return DIST_MULT_TO_SNDLVL( pchannel->dist_mult );
  2174. }
  2175. // The complete gain calculation, with SNDLVL given in dB is:
  2176. //
  2177. // GAIN = 1/dist * snd_refdist * 10 ^ ( ( SNDLVL - snd_refdb - (dist * snd_foliage_db_loss / 1200)) / 20 )
  2178. //
  2179. // for gain > SND_GAIN_THRESH, start curve smoothing with
  2180. //
  2181. // GAIN = 1 - 1 / (Y * GAIN ^ SND_GAIN_POWER)
  2182. //
  2183. // where Y = -1 / ( (SND_GAIN_THRESH ^ SND_GAIN_POWER) * (SND_GAIN_THRESH - 1) )
  2184. //
  2185. float SND_GetGainFromMult( float gain, float dist_mult, vec_t dist );
  2186. // NOTE: This is to eliminate the effect of "volume" on the distance falloff curve
  2187. // NOTE: may NOT BE TRUE, only effects compression?? and only from master volume control!
  2188. ConVar snd_preGainDistFalloff( "snd_pre_gain_dist_falloff", "1", FCVAR_CHEAT ); // showstart always skips info on player footsteps!
  2189. // gain curve construction
  2190. static float SND_GetMusicVolumeGainMultiplierInOverlay()
  2191. {
  2192. if ( sv.IsDedicated() )
  2193. return 1.0f;
  2194. static float s_flMusicVolumeOverlayMultiplierPrevious = 1.0f;
  2195. static float s_flMusicVolumeOverlayMultiplierTarget = 1.0f;
  2196. static double s_flLastUpdateTime = Plat_FloatTime();
  2197. static bool s_bOverlayActiveLastKnown = false;
  2198. double flTimeNow = Plat_FloatTime();
  2199. if ( flTimeNow - s_flLastUpdateTime > 0.1 )
  2200. {
  2201. // Update every 0.1 sec
  2202. static ConVarRef cl_embedded_stream_video_playing( "cl_embedded_stream_video_playing" );
  2203. bool bInClientVideoPlaying = ( cl_embedded_stream_video_playing.IsValid() && cl_embedded_stream_video_playing.GetBool() );
  2204. bool bCurrentlyActive = Steam3Client().IsGameOverlayActive() || bInClientVideoPlaying;
  2205. if ( bCurrentlyActive != s_bOverlayActiveLastKnown )
  2206. {
  2207. s_flMusicVolumeOverlayMultiplierPrevious = ( flTimeNow > s_flLastUpdateTime + 1.0 ) ? s_flMusicVolumeOverlayMultiplierTarget : ( s_flMusicVolumeOverlayMultiplierPrevious + ( flTimeNow - s_flLastUpdateTime ) * ( s_flMusicVolumeOverlayMultiplierTarget - s_flMusicVolumeOverlayMultiplierPrevious ) );
  2208. s_flLastUpdateTime = flTimeNow;
  2209. s_bOverlayActiveLastKnown = bCurrentlyActive;
  2210. s_flMusicVolumeOverlayMultiplierTarget = bCurrentlyActive ? ( bInClientVideoPlaying ? 0.0f : snd_musicvolume_multiplier_inoverlay.GetFloat() ) : 1.0f;
  2211. }
  2212. }
  2213. return ( flTimeNow > s_flLastUpdateTime + 1.0 ) ? s_flMusicVolumeOverlayMultiplierTarget : ( s_flMusicVolumeOverlayMultiplierPrevious + ( flTimeNow - s_flLastUpdateTime ) * ( s_flMusicVolumeOverlayMultiplierTarget - s_flMusicVolumeOverlayMultiplierPrevious ) );
  2214. }
  2215. float SND_GetGain( int nSlot, gain_t *gs, const channel_t *ch, const Vector &vecListenerOrigin, bool fplayersound, bool fmusicsound, bool flooping, vec_t dist, bool bAttenuated, bool bOkayToTrace )
  2216. {
  2217. VPROF_( "SND_GetGain", 2, VPROF_BUDGETGROUP_OTHER_SOUND, false, BUDGETFLAG_OTHER );
  2218. if ( ch->flags.m_bCompatibilityAttenuation )
  2219. {
  2220. // Convert to the original attenuation value.
  2221. soundlevel_t soundlevel = DIST_MULT_TO_SNDLVL( ch->dist_mult );
  2222. float flAttenuation = SNDLVL_TO_ATTN( soundlevel );
  2223. // Now get the goldsrc dist_mult and use the same calculation it uses in SND_Spatialize.
  2224. // Straight outta Goldsrc!!!
  2225. vec_t sound_nominal_clip_dist = 1000.0;
  2226. float flGoldsrcDistMult = flAttenuation / sound_nominal_clip_dist;
  2227. dist *= flGoldsrcDistMult;
  2228. float flReturnValue = 1.0f - dist;
  2229. flReturnValue = clamp( flReturnValue, 0, 1 );
  2230. return flReturnValue;
  2231. }
  2232. else
  2233. {
  2234. float gain = 1.0;
  2235. // without volume free falloff, our overall gain changes falloff curve shape
  2236. // which in my opinion is not good
  2237. // pre-falloff gain
  2238. if(!snd_preGainDistFalloff.GetInt())
  2239. {
  2240. gain = snd_gain.GetFloat();
  2241. if ( fmusicsound )
  2242. {
  2243. gain = gain * snd_musicvolume.GetFloat();
  2244. gain = gain * g_DashboardMusicMixValue;
  2245. gain = gain * g_flReplayMusicGain;
  2246. gain = gain * SND_GetMusicVolumeGainMultiplierInOverlay();
  2247. }
  2248. }
  2249. // get soundlevel / distance based gain falloff
  2250. if ( ch->dist_mult && ch->wavtype != CHAR_DIRSTEREO)
  2251. {
  2252. gain = SND_GetGainFromMult( gain, ch->dist_mult, dist );
  2253. }
  2254. // post-falloff gain
  2255. if(snd_preGainDistFalloff.GetInt())
  2256. {
  2257. gain *= snd_gain.GetFloat();
  2258. if ( fmusicsound )
  2259. {
  2260. gain = gain * snd_musicvolume.GetFloat();
  2261. gain = gain * g_DashboardMusicMixValue;
  2262. gain = gain * g_flReplayMusicGain;
  2263. gain = gain * SND_GetMusicVolumeGainMultiplierInOverlay();
  2264. }
  2265. }
  2266. if ( fplayersound )
  2267. {
  2268. // player weapon sounds get extra gain - this compensates
  2269. // for npc distance effect weapons which mix louder as L+R into L,R
  2270. // Hack.
  2271. if ( ch->entchannel == CHAN_WEAPON )
  2272. gain = gain * dB_To_Gain( SND_GAIN_PLAYER_WEAPON_DB );
  2273. }
  2274. // modify gain if sound source not visible to player
  2275. if(ch->wavtype != CHAR_DIRSTEREO)
  2276. {
  2277. gain = gain * SND_GetGainObscured( nSlot, gs, ch, vecListenerOrigin, fplayersound, flooping, bAttenuated, bOkayToTrace, NULL );
  2278. }
  2279. if (snd_showstart.GetInt() == 6)
  2280. {
  2281. DevMsg( "(gain %1.3f : dist ft %1.1f) ", gain, (float)dist/12.0 );
  2282. snd_showstart.SetValue(5); // display once
  2283. }
  2284. return gain;
  2285. }
  2286. }
  2287. // always ramp channel gain changes over time
  2288. // returns ramped gain, given new target gain
  2289. #define SND_GAIN_FADE_TIME 0.25 // xfade seconds between obscuring gain changes
  2290. float SND_FadeToNewGain( gain_t *gs, const channel_t *ch, float gain_new )
  2291. {
  2292. if ( gain_new == -1.0 )
  2293. {
  2294. // if -1 passed in, just keep fading to existing target
  2295. gain_new = gs->ob_gain_target;
  2296. }
  2297. // if first time updating, store new gain into gain & target, return
  2298. // if gain_new is close to existing gain, store new gain into gain & target, return
  2299. if ( ch->flags.bfirstpass || (fabs (gain_new - gs->ob_gain) < 0.01))
  2300. {
  2301. gs->ob_gain = gain_new;
  2302. gs->ob_gain_target = gain_new;
  2303. gs->ob_gain_inc = 0.0;
  2304. return gain_new;
  2305. }
  2306. // set up new increment to new target
  2307. float frametime = g_pSoundServices->GetHostFrametime();
  2308. float speed;
  2309. speed = ( frametime / SND_GAIN_FADE_TIME ) * (gain_new - gs->ob_gain);
  2310. gs->ob_gain_inc = fabs(speed);
  2311. // gs->ob_gain_inc = fabs(gain_new - gs->ob_gain) / 10.0;
  2312. gs->ob_gain_target = gain_new;
  2313. // if not hit target, keep approaching
  2314. if ( fabs( gs->ob_gain - gs->ob_gain_target ) > 0.01 )
  2315. {
  2316. gs->ob_gain = Approach( gs->ob_gain_target, gs->ob_gain, gs->ob_gain_inc );
  2317. }
  2318. else
  2319. {
  2320. // close enough, set gain = target
  2321. gs->ob_gain = gs->ob_gain_target;
  2322. }
  2323. return gs->ob_gain;
  2324. }
  2325. #define SND_TRACE_UPDATE_MAX 2 // max of N channels may be checked for obscured source per frame
  2326. int g_snd_trace_count = 0; // total tracelines for gain obscuring made this frame
  2327. // All new sounds must traceline once,
  2328. // but cap the max number of tracelines performed per frame
  2329. // for longer or looping sounds to SND_TRACE_UPDATE_MAX.
  2330. bool SND_ChannelOkToTrace( channel_t *ch )
  2331. {
  2332. // always trace first time sound is spatialized (doesn't update counter)
  2333. if ( ch->flags.bfirstpass )
  2334. {
  2335. ch->flags.bTraced = true;
  2336. return true;
  2337. }
  2338. // if already traced max channels this frame, return
  2339. if ( g_snd_trace_count >= SND_TRACE_UPDATE_MAX )
  2340. return false;
  2341. // ok to trace if this sound hasn't yet been traced in this round
  2342. if ( ch->flags.bTraced )
  2343. return false;
  2344. // set flag - don't traceline this sound again until all others have
  2345. // been traced
  2346. ch->flags.bTraced = true;
  2347. return true;
  2348. }
  2349. // determine if we need to reset all flags for traceline limiting -
  2350. // this happens if we hit a frame whein no tracelines occur ie: all currently
  2351. // playing sounds are blocked.
  2352. void SND_ChannelTraceReset( void )
  2353. {
  2354. if ( g_snd_trace_count )
  2355. return;
  2356. // if no tracelines performed this frame, then reset all
  2357. // trace flags
  2358. for (int i = 0; i < total_channels; i++)
  2359. channels[i].flags.bTraced = false;
  2360. }
  2361. bool SND_IsLongWave( const channel_t *pChannel )
  2362. {
  2363. // force it to look like everything is streaming, like on the consoles
  2364. // this gets used in 2 places, if the volume is 0.0 for some reason
  2365. // and to test if getgainobscured should function
  2366. #ifdef PORTAL2
  2367. return true;
  2368. #endif
  2369. CAudioSource *pSource = pChannel->sfx ? pChannel->sfx->pSource : NULL;
  2370. if ( pSource )
  2371. {
  2372. if ( pSource->IsStreaming() )
  2373. return true;
  2374. // UNDONE: Do this on long wave files too?
  2375. #if 0
  2376. float length = (float)pSource->SampleCount() / (float)pSource->SampleRate();
  2377. if ( length > 0.75f )
  2378. return true;
  2379. #endif
  2380. }
  2381. return false;
  2382. }
  2383. ConVar snd_obscured_gain_db( "snd_obscured_gain_dB", "-2.70", FCVAR_CHEAT ); // dB loss due to obscured sound source
  2384. // drop gain on channel if sound emitter obscured by
  2385. // world, unbroken windows, closed doors, large solid entities etc.
  2386. float SND_GetGainObscured( int nSlot, gain_t *gs, const channel_t *ch, const Vector &vecListenerOrigin, bool fplayersound, bool flooping, bool bAttenuated, bool bOkayToTrace, Vector *pOrigin )
  2387. {
  2388. float gain = 1.0;
  2389. int count = 1;
  2390. float snd_gain_db; // dB loss due to obscured sound source
  2391. // Unattenuated sounds don't get obscured.
  2392. if ( !bAttenuated )
  2393. return 1.0f;
  2394. if ( fplayersound )
  2395. return gain;
  2396. // During signon just apply regular state machine since world hasn't been
  2397. // created or settled yet...
  2398. if ( !SND_IsInGame() )
  2399. {
  2400. if ( !toolframework->InToolMode() )
  2401. {
  2402. gain = SND_FadeToNewGain( gs, ch, -1.0 );
  2403. }
  2404. return gain;
  2405. }
  2406. // don't do gain obscuring more than once on short one-shot sounds
  2407. if ( !ch->flags.bfirstpass && !ch->flags.isSentence && !flooping && !SND_IsLongWave(ch) )
  2408. {
  2409. gain = SND_FadeToNewGain( gs, ch, -1.0 );
  2410. return gain;
  2411. }
  2412. snd_gain_db = snd_obscured_gain_db.GetFloat();
  2413. // if long or looping sound, process N channels per frame - set 'processed' flag, clear by
  2414. // cycling through all channels - this maintains a cap on traces per frame
  2415. if ( !bOkayToTrace )
  2416. {
  2417. // just keep updating fade to existing target gain - no new trace checking
  2418. gain = SND_FadeToNewGain( gs, ch, -1.0 );
  2419. return gain;
  2420. }
  2421. // set up traceline from player eyes to sound emitting entity origin
  2422. Vector endpoint;
  2423. if( pOrigin )
  2424. {
  2425. // it's been passed in by an operator
  2426. endpoint = *pOrigin;
  2427. }
  2428. else
  2429. {
  2430. endpoint = ch->origin;
  2431. }
  2432. trace_t tr;
  2433. CTraceFilterWorldOnly filter; // UNDONE: also test for static props?
  2434. Ray_t ray;
  2435. ray.Init( MainViewOrigin( nSlot ), endpoint );
  2436. g_pEngineTraceClient->TraceRay( ray, MASK_BLOCK_AUDIO, &filter, &tr );
  2437. // total traces this frame
  2438. g_snd_trace_count++;
  2439. if (tr.DidHit() && tr.fraction < 0.99)
  2440. {
  2441. // can't see center of sound source:
  2442. // build extents based on dB sndlvl of source,
  2443. // test to see how many extents are visible,
  2444. // drop gain by snd_gain_db per extent hidden
  2445. Vector endpoints[4];
  2446. soundlevel_t sndlvl = DIST_MULT_TO_SNDLVL( ch->dist_mult );
  2447. float radius;
  2448. Vector vsrc_forward;
  2449. Vector vsrc_right;
  2450. Vector vsrc_up;
  2451. Vector vecl;
  2452. Vector vecr;
  2453. Vector vecl2;
  2454. Vector vecr2;
  2455. int i;
  2456. // get radius
  2457. if ( ch->radius > 0 )
  2458. radius = ch->radius;
  2459. else
  2460. radius = dB_To_Radius( sndlvl); // approximate radius from soundlevel
  2461. // set up extent endpoints - on upward or downward diagonals, facing player
  2462. for (i = 0; i < 4; i++)
  2463. endpoints[i] = endpoint;
  2464. // vsrc_forward is normalized vector from sound source to listener
  2465. VectorSubtract( vecListenerOrigin, endpoint, vsrc_forward );
  2466. VectorNormalize( vsrc_forward );
  2467. VectorVectors( vsrc_forward, vsrc_right, vsrc_up );
  2468. VectorAdd( vsrc_up, vsrc_right, vecl );
  2469. // if src above listener, force 'up' vector to point down - create diagonals up & down
  2470. if ( endpoint.z > vecListenerOrigin.z + (10 * 12) )
  2471. vsrc_up.z = -vsrc_up.z;
  2472. VectorSubtract( vsrc_up, vsrc_right, vecr );
  2473. VectorNormalize( vecl );
  2474. VectorNormalize( vecr );
  2475. // get diagonal vectors from sound source
  2476. vecl2 = radius * vecl;
  2477. vecr2 = radius * vecr;
  2478. vecl = (radius / 2.0) * vecl;
  2479. vecr = (radius / 2.0) * vecr;
  2480. // endpoints from diagonal vectors
  2481. endpoints[0] += vecl;
  2482. endpoints[1] += vecr;
  2483. endpoints[2] += vecl2;
  2484. endpoints[3] += vecr2;
  2485. // drop gain for each point on radius diagonal that is obscured
  2486. for (count = 0, i = 0; i < 4; i++)
  2487. {
  2488. // UNDONE: some endpoints are in walls - in this case, trace from the wall hit location
  2489. Ray_t ray;
  2490. ray.Init( MainViewOrigin( nSlot ), endpoints[i] );
  2491. g_pEngineTraceClient->TraceRay( ray, MASK_BLOCK_AUDIO, &filter, &tr );
  2492. if (tr.DidHit() && tr.fraction < 0.99 && !tr.startsolid )
  2493. {
  2494. count++; // skip first obscured point: at least 2 points + center should be obscured to hear db loss
  2495. if (count > 1)
  2496. gain = gain * dB_To_Gain( snd_gain_db );
  2497. }
  2498. }
  2499. }
  2500. if ( flooping && snd_showstart.GetInt() == 7)
  2501. {
  2502. static float g_drop_prev = 0;
  2503. float drop = (count-1) * snd_gain_db;
  2504. if (drop != g_drop_prev)
  2505. {
  2506. DevMsg( "dB drop: %1.4f \n", drop);
  2507. g_drop_prev = drop;
  2508. }
  2509. }
  2510. // crossfade to new gain
  2511. gain = SND_FadeToNewGain( gs, ch, gain );
  2512. return gain;
  2513. }
  2514. struct snd_spatial_t
  2515. {
  2516. int chan; // 0..4 cycles through up to 5 channels
  2517. int cycle; // 0..2 cycles through 3 vectors per channel
  2518. int dist[5][3]; // stores last 3 channel distance values [channel][cycle]
  2519. float value_prev[5]; // previous value per channel
  2520. double last_change;
  2521. };
  2522. bool g_ssp_init = false;
  2523. snd_spatial_t g_ssp;
  2524. // return 0..1 percent difference between a & b
  2525. float PercentDifference( float a, float b )
  2526. {
  2527. float vp;
  2528. if (!(int)a && !(int)b)
  2529. return 0.0;
  2530. if (!(int)a || !(int)b)
  2531. return 1.0;
  2532. if (a > b)
  2533. vp = b / a;
  2534. else
  2535. vp = a / b;
  2536. return (1.0 - vp);
  2537. }
  2538. // NOTE: Do not change SND_WALL_TRACE_LEN without also changing PRC_MDY6 delay value in snd_dsp.cpp!
  2539. #define SND_WALL_TRACE_LEN (100.0*12.0) // trace max of 100' = max of 100 milliseconds of linear delay
  2540. #define SND_SPATIAL_WAIT (0.25) // seconds to wait between traces
  2541. // change mod delay value on chan 0..3 to v (inches)
  2542. void DSP_SetSpatialDelay( int chan, float v )
  2543. {
  2544. // remap delay value 0..1200 to 1.0 to -1.0 for modulation
  2545. float value = ( v / SND_WALL_TRACE_LEN) - 1.0; // -1.0...0
  2546. value = value * 2.0; // -2.0...0
  2547. value += 1.0; // -1.0...1.0 (0...1200)
  2548. value *= -1.0; // 1.0...-1.0 (0...1200)
  2549. // assume first processor in dsp_spatial is the modulating delay unit for DSP_ChangePresetValue
  2550. int iproc = 0;
  2551. DSP_ChangePresetValue( idsp_spatial, chan, iproc, value );
  2552. /*
  2553. if (chan & 0x01)
  2554. DevMsg("RDly: %3.0f \n", v/12 );
  2555. else
  2556. DevMsg("LDly: %3.0f \n", v/12 );
  2557. */
  2558. }
  2559. // use non-feedback delay to stereoize (or make quad, or quad + center) the mono dsp_room fx,
  2560. // This simulates the average sum of delays caused by reflections
  2561. // from the left and right walls relative to the player. The average delay
  2562. // difference between left & right wall is (l + r)/2. This becomes the average
  2563. // delay difference between left & right ear.
  2564. // call at most once per frame to update player->wall spatial delays
  2565. bool SND_IsListenerValid()
  2566. {
  2567. FOR_EACH_VALID_SPLITSCREEN_PLAYER( hh )
  2568. {
  2569. if ((listener_origin[ hh ] == vec3_origin) &&
  2570. (listener_forward[ hh ] == vec3_origin) &&
  2571. (listener_right[ hh ] == vec3_origin) &&
  2572. (listener_up[ hh ] == vec3_origin) )
  2573. {
  2574. continue;
  2575. }
  2576. return true;
  2577. }
  2578. return false;
  2579. }
  2580. void SND_SetSpatialDelays()
  2581. {
  2582. VPROF("SoundSpatialDelays");
  2583. float dist = FLT_MAX, v, vp;
  2584. Vector v_dir, v_dir2;
  2585. int chan_max = (g_AudioDevice->IsSurround() ? 4 : 2) + (g_AudioDevice->IsSurroundCenter() ? 1 : 0); // 2, 4, 5 channels
  2586. // use listener_forward2d, which doesn't change when player looks up/down.
  2587. // init struct if 1st time through
  2588. if ( !g_ssp_init )
  2589. {
  2590. Q_memset(&g_ssp, 0, sizeof(snd_spatial_t));
  2591. g_ssp_init = true;
  2592. }
  2593. // return if dsp_spatial is 0
  2594. if ( !dsp_spatial.GetInt() )
  2595. return;
  2596. // if listener has not been updated, do nothing
  2597. if ( !SND_IsListenerValid() )
  2598. return;
  2599. if ( !SND_IsInGame() )
  2600. return;
  2601. // get time
  2602. double dtime = g_pSoundServices->GetHostTime();
  2603. // compare to previous time - if starting new check - don't check for new room until timer expires
  2604. if (!g_ssp.chan && !g_ssp.cycle)
  2605. {
  2606. if (fabs(dtime - g_ssp.last_change) < SND_SPATIAL_WAIT)
  2607. return;
  2608. }
  2609. // cycle through forward, left, rearward vectors, averaging to get left/right delay
  2610. // count[chan][cycle] 0,1 0,2 0,3 1,1 1,2 1,3 2,1 2,2 2,3 ...
  2611. g_ssp.cycle++;
  2612. if (g_ssp.cycle == 3)
  2613. {
  2614. g_ssp.cycle = 0;
  2615. // cycle through front left, front right, rear left, rear right, front center delays
  2616. g_ssp.chan++;
  2617. if (g_ssp.chan >= chan_max )
  2618. g_ssp.chan = 0;
  2619. }
  2620. FOR_EACH_VALID_SPLITSCREEN_PLAYER( nSlot )
  2621. {
  2622. // HACK FOR NOW, THIS ONLY WORKS ON THE FIRST PLAYER!!!!!
  2623. //xxxFIXMESPLITSCREEN
  2624. if ( nSlot >= 1 )
  2625. break;
  2626. Vector listener_forward2d;
  2627. Vector vecListenerRight = listener_right[ nSlot ];
  2628. ConvertListenerVectorTo2D( &listener_forward2d, &vecListenerRight );
  2629. // set up traceline from player eyes to surrounding walls
  2630. switch( g_ssp.chan )
  2631. {
  2632. default:
  2633. case 0: // front left: trace max 100' 'cone' to player's left
  2634. if ( g_AudioDevice->IsSurround() )
  2635. {
  2636. // 4-5 speaker case - front left
  2637. v_dir = (-vecListenerRight + listener_forward2d) / 2.0;
  2638. v_dir = g_ssp.cycle ? (g_ssp.cycle == 1 ? -vecListenerRight * 0.5: listener_forward2d * 0.5) : v_dir;
  2639. }
  2640. else
  2641. {
  2642. // 2 speaker case - left
  2643. v_dir = vecListenerRight * -1.0;
  2644. v_dir2 = g_ssp.cycle ? (g_ssp.cycle == 1 ? listener_forward2d * 0.5 : -listener_forward2d * 0.5) : v_dir;
  2645. v_dir = (v_dir + v_dir2) / 2.0;
  2646. }
  2647. break;
  2648. case 1: // front right: trace max 100' 'cone' to player's right
  2649. if ( g_AudioDevice->IsSurround() )
  2650. {
  2651. // 4-5 speaker case - front right
  2652. v_dir = (vecListenerRight + listener_forward2d) / 2.0;
  2653. v_dir = g_ssp.cycle ? (g_ssp.cycle == 1 ? vecListenerRight * 0.5: listener_forward2d * 0.5) : v_dir;
  2654. }
  2655. else
  2656. {
  2657. // 2 speaker case - right
  2658. v_dir = vecListenerRight;
  2659. v_dir2 = g_ssp.cycle ? (g_ssp.cycle == 1 ? listener_forward2d * 0.5 : -listener_forward2d * 0.5) : v_dir;
  2660. v_dir = (v_dir + v_dir2) / 2.0;
  2661. }
  2662. break;
  2663. case 2: // rear left: trace max 100' 'cone' to player's rear left
  2664. v_dir = (vecListenerRight + listener_forward2d) / -2.0;
  2665. v_dir = g_ssp.cycle ? (g_ssp.cycle == 1 ? -vecListenerRight * 0.5 : -listener_forward2d * 0.5) : v_dir;
  2666. break;
  2667. case 3: // rear right: trace max 100' 'cone' to player's rear right
  2668. v_dir = (vecListenerRight - listener_forward2d) / 2.0;
  2669. v_dir = g_ssp.cycle ? (g_ssp.cycle == 1 ? vecListenerRight * 0.5: -listener_forward2d * 0.5) : v_dir;
  2670. break;
  2671. case 4: // front center: trace max 100' 'cone' to player's front
  2672. v_dir = listener_forward2d;
  2673. v_dir2 = g_ssp.cycle ? (g_ssp.cycle == 1 ? vecListenerRight * 0.15 : -vecListenerRight * 0.15) : v_dir;
  2674. v_dir = (v_dir + v_dir2);
  2675. break;
  2676. }
  2677. Vector endpoint;
  2678. trace_t tr;
  2679. CTraceFilterWorldOnly filter;
  2680. endpoint = MainViewOrigin( nSlot ) + v_dir * SND_WALL_TRACE_LEN;
  2681. Ray_t ray;
  2682. ray.Init( MainViewOrigin( nSlot ), endpoint );
  2683. g_pEngineTraceClient->TraceRay( ray, MASK_BLOCK_AUDIO, &filter, &tr );
  2684. float checkDist = SND_WALL_TRACE_LEN;
  2685. if ( tr.DidHit() )
  2686. {
  2687. checkDist = VectorLength( tr.endpos - MainViewOrigin( nSlot ) );
  2688. }
  2689. if ( checkDist < dist )
  2690. {
  2691. dist = checkDist;
  2692. }
  2693. }
  2694. g_ssp.dist[g_ssp.chan][g_ssp.cycle] = dist;
  2695. // set new result in dsp_spatial delay params when all delay values have been filled in
  2696. if (!g_ssp.cycle && !g_ssp.chan)
  2697. {
  2698. // update delay for each channel
  2699. for (int chan = 0; chan < chan_max; chan++)
  2700. {
  2701. // compute average of 3 traces per channel
  2702. v = (g_ssp.dist[chan][0] + g_ssp.dist[chan][1] + g_ssp.dist[chan][2]) / 3.0;
  2703. vp = g_ssp.value_prev[chan];
  2704. // only change if 10% difference from previous
  2705. if ((vp != v) && int(v) && (PercentDifference( v, vp ) >= 0.1))
  2706. {
  2707. // update when we have data for all L/R && RL/RR channels...
  2708. if (chan & 0x1)
  2709. {
  2710. float vr = fpmin( v, (50*12.0f) );
  2711. float vl = fpmin(g_ssp.value_prev[chan-1], (50*12.0f));
  2712. /* UNDONE: not needed, now that this applies only to dsp 'room' buffer
  2713. // ensure minimum separation = average distance to walls
  2714. float dmin = (vl + vr) / 2.0; // average distance to walls
  2715. float d = vl - vr; // l/r separation
  2716. // if separation is less than average, increase min
  2717. if (abs(d) < dmin/2)
  2718. {
  2719. if (vl > vr)
  2720. vl += dmin/2 - d;
  2721. else
  2722. vr += dmin/2 - d;
  2723. }
  2724. */
  2725. DSP_SetSpatialDelay(chan-1, vl);
  2726. DSP_SetSpatialDelay(chan, vr);
  2727. }
  2728. // update center chan
  2729. if (chan == 4)
  2730. {
  2731. float vl = fpmin( v, (50*12.0f) );
  2732. DSP_SetSpatialDelay(chan, vl);
  2733. }
  2734. }
  2735. g_ssp.value_prev[chan] = v;
  2736. }
  2737. // update wait timer now that all values have been checked
  2738. g_ssp.last_change = dtime;
  2739. }
  2740. }
  2741. // Dsp Automatic Selection:
  2742. // a) enabled by setting dsp_room to DSP_AUTOMATIC. Subsequently, dsp_automatic is the actual dsp value for dsp_room.
  2743. // b) disabled by setting dsp_room to anything else
  2744. // c) while enabled, detection nodes are placed as player moves into a new space
  2745. // i. at each node, a new dsp setting is calculated and dsp_automatic is set to an appropriate preset
  2746. // ii. new nodes are set when player moves out of sight of previous node
  2747. // iii. moving into line of sight of a detection node causes closest node to player to set dsp_automatic
  2748. // see void DAS_CheckNewRoomDSP() for main entrypoint
  2749. ConVar das_debug( "adsp_debug", "0", FCVAR_ARCHIVE );
  2750. // >0: draw blue dsp detection node location
  2751. // >1: draw green room trace height detection bars
  2752. // 3: draw yellow horizontal trace bars for room width/depth detection
  2753. // 4: draw yellow upward traces for height detection
  2754. // 5: draw teal box around all props around player
  2755. // 6: draw teal box around room as detected
  2756. #define DAS_CWALLS 20 // # of wall traces to save for calculating room dimensions
  2757. #define DAS_ROOM_TRACE_LEN (400.0*12.0) // max size of trace to check for room dimensions
  2758. #define DAS_AUTO_WAIT 0.25 // wait min of n seconds between dsp_room changes and update checks
  2759. #define DAS_WIDTH_MIN 0.4 // min % change in avg width of any wall pair to cause new dsp
  2760. #define DAS_REFL_MIN 0.5 // min % change in avg refl of any wall to cause new dsp
  2761. #define DAS_SKYHIT_MIN 0.8 // min % change in # of sky hits per wall
  2762. #define DAS_DIST_MIN (4.0 * 12.0) // min distance between room dsp changes
  2763. #define DAS_DIST_MAX (40.0 * 12.0) // max distance to preserve room dsp changes
  2764. #define DAS_DIST_MIN_OUTSIDE (6.0 * 12.0) // min distance between room dsp changes outside
  2765. #define DAS_DIST_MAX_OUTSIDE (100.0 * 12.0) // max distance to preserve room dsp changes outside
  2766. #define IVEC_DIAG_UP 8 // start of diagonal up vectors
  2767. #define IVEC_UP 18 // up vector
  2768. #define IVEC_DOWN 19 // down vector
  2769. #define DAS_REFLECTIVITY_NORM 0.5
  2770. #define DAS_REFLECTIVITY_SKY 0.0
  2771. // auto dsp room struct
  2772. struct das_room_t
  2773. {
  2774. int dist[DAS_CWALLS]; // distance in units from player to axis aligned and diagonal walls
  2775. float reflect[DAS_CWALLS]; // acoustic reflectivity per wall
  2776. float skyhits[DAS_CWALLS]; // every sky hit adds 0.1
  2777. Vector hit[DAS_CWALLS]; // location of trace hit on wall - used for calculating average centers
  2778. Vector norm[DAS_CWALLS]; // wall normal at hit location
  2779. Vector vplayer; // 'frozen' location above player's head
  2780. Vector vplayer_eyes; // 'frozen' location player's eyes
  2781. int width_max; // max width
  2782. int length_max; // max length
  2783. int height_max; // max height
  2784. float refl_avg; // running average of reflectivity of all walls
  2785. float refl_walls[6]; // left,right,front,back,ceiling,floor reflectivities
  2786. float sky_pct; // percent of sky hits
  2787. Vector room_mins; // room bounds
  2788. Vector room_maxs;
  2789. double last_dsp_change; // time since last dsp change
  2790. float diffusion; // 0..1.0 check radius (avg of width_avg) for # of props - scale diffusion based on # found
  2791. short iwall; // cycles through walls 0..5, ensuring only one trace per frame
  2792. short ent_count; // count of entities found in radius
  2793. bool bskyabove; // true if sky found above player (ie: outside)
  2794. bool broomready; // true if all distances are filled in and room is ready to check
  2795. short lowceiling; // if non-zero, ceiling directly above player if < 112 units
  2796. };
  2797. // dsp detection node
  2798. struct das_node_t
  2799. {
  2800. Vector vplayer; // position
  2801. bool fused; // true if valid node
  2802. bool fseesplayer; // true if node sees player on last check
  2803. short dsp_preset; // preset
  2804. int range_min; // min,max detection ranges
  2805. int range_max;
  2806. int dist; // last distance to player
  2807. // room parameters when node was created:
  2808. das_room_t room;
  2809. };
  2810. #define DAS_CNODES 40 // keep around last n nodes - must be same as DSP_CAUTO_PRESETS!!!
  2811. das_node_t g_das_nodes[DAS_CNODES]; // all dsp detection nodes
  2812. das_node_t *g_pdas_last_node = NULL; // last node that saw player
  2813. int g_das_check_next; // next node to check
  2814. int g_das_store_next; // next place to store node
  2815. bool g_das_all_checked; // true if all nodes checked
  2816. int g_das_checked_count; // count of nodes checked in latest pass
  2817. das_room_t g_das_room; // room detector
  2818. bool g_bdas_room_init = 0;
  2819. bool g_bdas_init_nodes = 0;
  2820. bool g_bdas_create_new_node = 0;
  2821. bool DAS_TraceNodeToPlayer( das_room_t *proom, das_node_t *pnode );
  2822. void DAS_InitAutoRoom( das_room_t *proom);
  2823. void DAS_DebugDrawTrace ( trace_t *ptr, int r, int g, int b, float duration, int imax );
  2824. Vector g_das_vec3[DAS_CWALLS]; // trace vectors to walls, ceiling, floor
  2825. // for engine api
  2826. // new and changed rooms are only reset by the api function call
  2827. // thus they really mean "new since the last check", not ideal
  2828. bool g_current_das_room_changed = false;
  2829. bool g_current_das_room_new = false;
  2830. // these are updated regardless of api calls
  2831. bool g_current_das_room_sky_above = false;
  2832. float g_current_das_room_sky_percent = false;
  2833. void DAS_StoreRoomVarsAPI(das_room_t *pdas_room)
  2834. {
  2835. g_current_das_room_sky_above = pdas_room->bskyabove;
  2836. g_current_das_room_sky_percent = pdas_room->sky_pct;
  2837. }
  2838. bool S_DSPGetCurrentDASRoomNew(void)
  2839. {
  2840. bool newRoom = g_current_das_room_new;
  2841. g_current_das_room_new = false;
  2842. return newRoom;
  2843. }
  2844. bool S_DSPGetCurrentDASRoomChanged(void)
  2845. {
  2846. bool changedRoom = g_current_das_room_changed;
  2847. g_current_das_room_changed = false;
  2848. return changedRoom;
  2849. }
  2850. bool S_DSPGetCurrentDASRoomSkyAbove(void)
  2851. {
  2852. return g_current_das_room_sky_above;
  2853. }
  2854. float S_DSPGetCurrentDASRoomSkyPercent(void)
  2855. {
  2856. return g_current_das_room_sky_percent;
  2857. }
  2858. void DAS_InitNodes( void )
  2859. {
  2860. Q_memset(g_das_nodes, 0, sizeof(das_node_t) * DAS_CNODES);
  2861. g_das_check_next = 0;
  2862. g_das_store_next = 0;
  2863. g_das_all_checked = 0;
  2864. g_das_checked_count = 0;
  2865. // init all rooms
  2866. for (int i = 0; i < DAS_CNODES; i++)
  2867. DAS_InitAutoRoom( &(g_das_nodes[i].room) );
  2868. // init trace vectors
  2869. // set up trace vectors for max, min width
  2870. float vl = DAS_ROOM_TRACE_LEN;
  2871. float vlu = DAS_ROOM_TRACE_LEN * 0.52;
  2872. float vlu2 = DAS_ROOM_TRACE_LEN * 0.48; // don't use 'perfect' diagonals
  2873. g_das_vec3[0].Init(vl, 0.0, 0.0); // x left
  2874. g_das_vec3[1].Init(-vl, 0.0, 0.0); // x right
  2875. g_das_vec3[2].Init(0.0, vl, 0.0); // y front
  2876. g_das_vec3[3].Init(0.0, -vl, 0.0); // y back
  2877. g_das_vec3[4].Init(-vlu, vlu2, 0.0); // diagonal front left
  2878. g_das_vec3[5].Init(vlu, -vlu2, 0.0); // diagonal rear right
  2879. g_das_vec3[6].Init(vlu, vlu2, 0.0); // diagonal front right
  2880. g_das_vec3[7].Init(-vlu, -vlu2, 0.0); // diagonal rear left
  2881. // set up trace vectors for max height - on x=y diagonal
  2882. g_das_vec3[8].Init(vlu, vlu2, vlu/2.0); // front right up A x,y,z/2 (IVEC_DIAG_UP)
  2883. g_das_vec3[9].Init(vlu, vlu2, vlu); // front right up B x,y,z
  2884. g_das_vec3[10].Init(vlu/2.0, vlu2/2.0, vlu); // front right up C x/2,y/2,z
  2885. g_das_vec3[11].Init(-vlu, -vlu2, vlu/2.0); // rear left up A -x,-y,z/2
  2886. g_das_vec3[12].Init(-vlu, -vlu2, vlu); // rear left up B -x,-y,z
  2887. g_das_vec3[13].Init(-vlu/2.0, -vlu2/2.0, vlu); // rear left up C -x/2,-y/2,z
  2888. // set up trace vectors for max height - on x axis & y axis
  2889. g_das_vec3[14].Init(-vlu, 0, vlu); // left up B -x,0,z
  2890. g_das_vec3[15].Init(0, vlu/2.0, vlu); // front up C -x/2,0,z
  2891. g_das_vec3[16].Init(0, -vlu, vlu); // rear up B x,0,z
  2892. g_das_vec3[17].Init(vlu/2.0, 0, vlu); // right up C x/2,0,z
  2893. g_das_vec3[18].Init(0.0, 0.0, vl); // up (IVEC_UP)
  2894. g_das_vec3[19].Init(0.0, 0.0, -vl); // down (IVEC_DOWN)
  2895. }
  2896. void DAS_InitAutoRoom( das_room_t *proom)
  2897. {
  2898. Q_memset(proom, 0, sizeof (das_room_t));
  2899. }
  2900. // reset all nodes for next round of visibility checks between player & nodes
  2901. void DAS_ResetNodes( void )
  2902. {
  2903. for (int i = 0; i < DAS_CNODES; i++)
  2904. {
  2905. g_das_nodes[i].fseesplayer = false;
  2906. g_das_nodes[i].dist = 0;
  2907. }
  2908. g_das_all_checked = false;
  2909. g_das_checked_count = 0;
  2910. g_bdas_create_new_node = false;
  2911. }
  2912. ConCommand adsp_reset_nodes("adsp_reset_nodes", DAS_ResetNodes);
  2913. // utility function - return next index, wrap at max
  2914. int DAS_GetNextIndex( int *pindex, int max )
  2915. {
  2916. int i = *pindex;
  2917. int j;
  2918. j = i+1;
  2919. if ( j >= max )
  2920. j = 0;
  2921. *pindex = j;
  2922. return i;
  2923. }
  2924. // returns true if dsp node is within range of player
  2925. bool DAS_NodeInRange( das_room_t *proom, das_node_t *pnode )
  2926. {
  2927. float dist;
  2928. dist = VectorLength( proom->vplayer - pnode->vplayer );
  2929. // player can still see previous room selection point, and it's less than n feet away,
  2930. // then flag this node as visible
  2931. pnode->dist = dist;
  2932. return ( dist <= pnode->range_max );
  2933. }
  2934. // update next valid node - set up internal node state if it can see player
  2935. // called once per frame
  2936. // returns true if all nodes have been checked
  2937. bool DAS_CheckNextNode( das_room_t *proom )
  2938. {
  2939. int i, j;
  2940. if ( g_das_all_checked )
  2941. return true;
  2942. // find next valid node
  2943. for (j = 0; j < DAS_CNODES; j++)
  2944. {
  2945. // track number of nodes checked
  2946. g_das_checked_count++;
  2947. // get next node in range to check
  2948. i = DAS_GetNextIndex( &g_das_check_next, DAS_CNODES );
  2949. if ( g_das_nodes[i].fused && DAS_NodeInRange( proom, &(g_das_nodes[i]) ) )
  2950. {
  2951. // trace to see if player can still see node,
  2952. // if so stop checking
  2953. if ( DAS_TraceNodeToPlayer( proom, &(g_das_nodes[i]) ))
  2954. goto checknode_exit;
  2955. }
  2956. }
  2957. checknode_exit:
  2958. // flag that all nodes have been checked
  2959. if ( g_das_checked_count >= DAS_CNODES )
  2960. g_das_all_checked = true;
  2961. return g_das_all_checked;
  2962. }
  2963. int DAS_GetNextNodeIndex()
  2964. {
  2965. return g_das_store_next;
  2966. }
  2967. // store new node for room
  2968. void DAS_StoreNode( das_room_t *proom, int dsp_preset)
  2969. {
  2970. // overwrite node in cyclic list
  2971. int i = DAS_GetNextIndex( &g_das_store_next, DAS_CNODES );
  2972. g_das_nodes[i].dsp_preset = dsp_preset;
  2973. g_das_nodes[i].fused = true;
  2974. g_das_nodes[i].vplayer = proom->vplayer;
  2975. // calculate node scanning range_max based on room size
  2976. if ( !proom->bskyabove )
  2977. {
  2978. // inside range - halls & tunnels have nodes every 5*width
  2979. g_das_nodes[i].range_max = fpmin(DAS_DIST_MAX, MIN(proom->width_max * 5, proom->length_max) );
  2980. g_das_nodes[i].range_min = DAS_DIST_MIN;
  2981. }
  2982. else
  2983. {
  2984. // outside range
  2985. g_das_nodes[i].range_max = DAS_DIST_MAX_OUTSIDE;
  2986. g_das_nodes[i].range_min = DAS_DIST_MIN_OUTSIDE;
  2987. }
  2988. g_das_nodes[i].fseesplayer = false;
  2989. g_das_nodes[i].dist = 0;
  2990. g_das_nodes[i].room = *proom;
  2991. // update last node visible as this node
  2992. g_pdas_last_node = &(g_das_nodes[i]);
  2993. }
  2994. // check all updated nodes,
  2995. // return dsp_preset of largest node (by area) that can see player
  2996. // return -1 if no preset found
  2997. // NOTE: outside nodes can't see player if player is inside and vice versa
  2998. // foutside is true if player is outside
  2999. int DAS_GetDspPreset( bool foutside )
  3000. {
  3001. int dsp_preset = -1;
  3002. int i;
  3003. // int dist_min = 100000;
  3004. int area_max = 0;
  3005. int area;
  3006. // find node that represents room with greatest floor area, return its preset.
  3007. for (i = 0; i < DAS_CNODES; i++)
  3008. {
  3009. if (g_das_nodes[i].fused && g_das_nodes[i].fseesplayer)
  3010. {
  3011. area = (g_das_nodes[i].room.width_max * g_das_nodes[i].room.length_max);
  3012. if ( g_das_nodes[i].room.bskyabove == foutside )
  3013. {
  3014. if (area > area_max)
  3015. {
  3016. area_max = area;
  3017. dsp_preset = g_das_nodes[i].dsp_preset;
  3018. // save pointer to last node that saw player
  3019. g_pdas_last_node = &(g_das_nodes[i]);
  3020. }
  3021. }
  3022. /*
  3023. // find nearest node, return its preset
  3024. if (g_das_nodes[i].dist < dist_min)
  3025. {
  3026. if ( g_das_nodes[i].room.bskyabove == foutside )
  3027. {
  3028. dist_min = g_das_nodes[i].dist;
  3029. dsp_preset = g_das_nodes[i].dsp_preset;
  3030. // save pointer to last node that saw player
  3031. g_pdas_last_node = &(g_das_nodes[i]);
  3032. }
  3033. }
  3034. */
  3035. }
  3036. }
  3037. return dsp_preset;
  3038. }
  3039. // custom trace filter:
  3040. // a) never hit player or monsters or entities
  3041. // b) always hit world, or moveables or static props
  3042. class CTraceFilterDAS : public ITraceFilter
  3043. {
  3044. public:
  3045. bool ShouldHitEntity( IHandleEntity *pHandleEntity, int contentsMask )
  3046. {
  3047. IClientUnknown *pUnk = static_cast<IClientUnknown*>(pHandleEntity);
  3048. IClientEntity *pEntity;
  3049. if ( !pUnk )
  3050. return false;
  3051. // don't hit non-collideable props
  3052. if ( StaticPropMgr()->IsStaticProp( pHandleEntity ) )
  3053. {
  3054. ICollideable *pCollide = StaticPropMgr()->GetStaticProp( pHandleEntity);
  3055. if (!pCollide)
  3056. return false;
  3057. }
  3058. // don't hit any ents
  3059. pEntity = pUnk->GetIClientEntity();
  3060. if ( pEntity )
  3061. return false;
  3062. return true;
  3063. }
  3064. virtual TraceType_t GetTraceType() const
  3065. {
  3066. return TRACE_EVERYTHING_FILTER_PROPS;
  3067. }
  3068. };
  3069. #define DAS_TRACE_MASK (CONTENTS_SOLID|CONTENTS_MOVEABLE|CONTENTS_WINDOW)
  3070. // returns true if clear line exists between node and player
  3071. // if node can see player, sets up node distance and flag fseesplayer
  3072. bool DAS_TraceNodeToPlayer( das_room_t *proom, das_node_t *pnode )
  3073. {
  3074. trace_t trP;
  3075. CTraceFilterDAS filterP;
  3076. bool fseesplayer = false;
  3077. float dist;
  3078. Ray_t ray;
  3079. ray.Init( proom->vplayer, pnode->vplayer );
  3080. g_pEngineTraceClient->TraceRay( ray, DAS_TRACE_MASK, &filterP, &trP );
  3081. dist = VectorLength( proom->vplayer - pnode->vplayer );
  3082. // player can still see previous room selection point, and it's less than n feet away,
  3083. // then flag this node as visible
  3084. if ( !trP.DidHit() && (dist <= DAS_DIST_MAX) )
  3085. {
  3086. fseesplayer = true;
  3087. pnode->dist = dist;
  3088. }
  3089. pnode->fseesplayer = fseesplayer;
  3090. return fseesplayer;
  3091. }
  3092. // update room boundary maxs, mins
  3093. void DAS_SetRoomBounds( das_room_t *proom, Vector &hit, bool bheight )
  3094. {
  3095. Vector maxs, mins;
  3096. maxs = proom->room_maxs;
  3097. mins = proom->room_mins;
  3098. if (!bheight)
  3099. {
  3100. if (hit.x > maxs.x)
  3101. maxs.x = hit.x;
  3102. if (hit.x < mins.x)
  3103. mins.x = hit.x;
  3104. if (hit.z > maxs.z)
  3105. maxs.z = hit.z;
  3106. if (hit.z < mins.z)
  3107. mins.z = hit.z;
  3108. }
  3109. if (bheight)
  3110. {
  3111. if (hit.y > maxs.y)
  3112. maxs.y = hit.y;
  3113. if (hit.y < mins.y)
  3114. mins.y = hit.y;
  3115. }
  3116. proom->room_maxs = maxs;
  3117. proom->room_mins = mins;
  3118. }
  3119. // when all walls are updated, calculate max length, width, height, reflectivity, sky hit%, room center
  3120. // returns true if room parameters are in good location to place a node
  3121. // returns false if room parameters are not in good location to place a node
  3122. // note: false occurs if up vector doesn't hit sky, but one or more up diagonal vectors do hit sky
  3123. #ifdef PORTAL2
  3124. ConVar das_process_overhang_spaces( "das_process_overhang_spaces", "1" );
  3125. #else
  3126. ConVar das_process_overhang_spaces( "das_process_overhang_spaces", "0" );
  3127. #endif
  3128. bool DAS_CalcRoomProps( das_room_t *proom )
  3129. {
  3130. int length_max = 0;
  3131. int width_max = 0;
  3132. int height_max = 0;
  3133. int dist[4];
  3134. float area1, area2;
  3135. int height;
  3136. int i;
  3137. int j;
  3138. int k;
  3139. if( das_process_overhang_spaces.GetInt() != 1 )
  3140. {
  3141. bool b_diaghitsky = false;
  3142. // reject this location if up vector doesn't hit sky, but
  3143. // one or more up diagonals do hit sky -
  3144. // in this case, player is under a slight overhang, narrow bridge, or
  3145. // standing just inside a window or doorway. keep looking for better node location
  3146. for (i = IVEC_DIAG_UP; i < IVEC_UP; i++)
  3147. {
  3148. if (proom->skyhits[i] > 0.0)
  3149. b_diaghitsky = true;
  3150. }
  3151. if (b_diaghitsky && !(proom->skyhits[IVEC_UP] > 0.0))
  3152. return false;
  3153. }
  3154. // get all distance pairs
  3155. for (i = 0; i < IVEC_DIAG_UP; i+=2)
  3156. dist[i/2] = proom->dist[i] + proom->dist[i+1]; // 1st pair is width
  3157. // if areas differ by more than 25%
  3158. // select the pair with the greater area
  3159. // if areas do not differ by more than 25%, select the pair with the
  3160. // longer measured distance. Filters incorrect selection due to diagonals.
  3161. area1 = (float)(dist[0] * dist[1]);
  3162. area2 = (float)(dist[2] * dist[3]);
  3163. area1 = (int)area1 == 0 ? 1.0 : area1;
  3164. area2 = (int)area2 == 0 ? 1.0 : area2;
  3165. if ( PercentDifference(area1, area2) > 0.25 )
  3166. {
  3167. // areas are more than 25% different - select pair with greater area
  3168. j = area1 > area2 ? 0 : 2;
  3169. }
  3170. else
  3171. {
  3172. // select pair with longer measured distance
  3173. int k = 0; // index to max dist
  3174. int dmax = 0;
  3175. for (i = 0; i < 4; i++)
  3176. {
  3177. if (dist[i] > dmax)
  3178. {
  3179. dmax = dist[i];
  3180. k = i;
  3181. }
  3182. }
  3183. j = k > 1 ? 2 : 0;
  3184. }
  3185. // width is always the smaller of the dimensions
  3186. width_max = MIN (dist[j], dist[j+1]);
  3187. length_max = MAX (dist[j], dist[j+1]);
  3188. // get max height
  3189. for (i = IVEC_DIAG_UP; i < IVEC_DOWN; i++)
  3190. {
  3191. height = proom->dist[i];
  3192. if (height > height_max)
  3193. height_max = height;
  3194. }
  3195. proom->length_max = length_max;
  3196. proom->width_max = width_max;
  3197. proom->height_max = height_max;
  3198. // get room max,min from chosen width, depth
  3199. // 0..3 or 4..7
  3200. for ( i = j*2; i < 4+(j*2); i++)
  3201. DAS_SetRoomBounds( proom, proom->hit[i], false );
  3202. // get room height min from down trace
  3203. proom->room_mins.z = proom->hit[IVEC_DOWN].z;
  3204. // reset room height max to player trace height
  3205. proom->room_maxs.z = proom->vplayer.z;
  3206. // draw box around room max,min
  3207. if (das_debug.GetInt() == 6)
  3208. {
  3209. // draw box around all objects detected
  3210. Vector maxs = proom->room_maxs;
  3211. Vector mins = proom->room_mins;
  3212. Vector orig = (maxs + mins) / 2.0;
  3213. Vector absMax = maxs - orig;
  3214. Vector absMin = mins - orig;
  3215. CDebugOverlay::AddBoxOverlay( orig, absMax, absMin, vec3_angle, 255, 0, 255, 0, 60.0f );
  3216. }
  3217. // calculate average reflectivity
  3218. float refl = 0.0;
  3219. // average reflectivity for walls
  3220. // 0..3 or 4..7
  3221. for ( k = 0, i = j*2; i < 4+(j*2); i++, k++)
  3222. {
  3223. refl += proom->reflect[i];
  3224. proom->refl_walls[k] = proom->reflect[i];
  3225. }
  3226. // assume ceiling is open
  3227. proom->refl_walls[4] = 0.0;
  3228. // get ceiling reflectivity, if any non zero
  3229. for ( i = IVEC_DIAG_UP; i < IVEC_DOWN; i++)
  3230. {
  3231. if (proom->reflect[i] == 0.0)
  3232. {
  3233. // if any upward trace hit sky, exit;
  3234. // ceiling reflectivity is 0.0
  3235. proom->refl_walls[4] = 0.0;
  3236. i = IVEC_DOWN; // exit loop
  3237. }
  3238. else
  3239. {
  3240. // upward trace didn't hit sky, keep checking
  3241. proom->refl_walls[4] = proom->reflect[i];
  3242. }
  3243. }
  3244. // add in ceiling reflectivity, if any
  3245. refl += proom->refl_walls[4];
  3246. // get floor reflectivity
  3247. refl += proom->reflect[IVEC_DOWN];
  3248. proom->refl_walls[5] = proom->reflect[IVEC_DOWN];
  3249. proom->refl_avg = refl / 6.0;
  3250. // calculate sky hit percent for this wall
  3251. float sky_pct = 0.0;
  3252. // 0..3 or 4..7
  3253. for ( i = j*2; i < 4+(j*2); i++)
  3254. sky_pct += proom->skyhits[i];
  3255. for ( i = IVEC_DIAG_UP; i < IVEC_DOWN; i++)
  3256. {
  3257. if (proom->skyhits[i] > 0.0)
  3258. {
  3259. // if any upward trace hit sky, exit loop
  3260. sky_pct += proom->skyhits[i];
  3261. i = IVEC_DOWN;
  3262. }
  3263. }
  3264. // get floor skyhit
  3265. sky_pct += proom->skyhits[IVEC_DOWN];
  3266. proom->sky_pct = sky_pct;
  3267. // check for sky above
  3268. proom->bskyabove = false;
  3269. for (i = IVEC_DIAG_UP; i < IVEC_DOWN; i++)
  3270. {
  3271. if (proom->skyhits[i] > 0.0)
  3272. proom->bskyabove = true;
  3273. }
  3274. return true;
  3275. }
  3276. // return true if trace hit solid
  3277. // return false if trace hit sky or didn't hit anything
  3278. bool DAS_HitSolid( trace_t *ptr )
  3279. {
  3280. // if hit nothing return false
  3281. if (!ptr->DidHit())
  3282. return false;
  3283. // if hit sky, return false (not solid)
  3284. if (ptr->surface.flags & SURF_SKY)
  3285. return false;
  3286. return true;
  3287. }
  3288. // returns true if trace hit sky
  3289. bool DAS_HitSky( trace_t *ptr )
  3290. {
  3291. if (ptr->DidHit() && (ptr->surface.flags & SURF_SKY))
  3292. return true;
  3293. if (!ptr->DidHit() )
  3294. {
  3295. float dz = ptr->endpos.z - ptr->startpos.z;
  3296. if ( dz > 200*12.0f )
  3297. return true;
  3298. }
  3299. return false;
  3300. }
  3301. bool DAS_ScanningForHeight( das_room_t *proom )
  3302. {
  3303. return (proom->iwall >= IVEC_DIAG_UP);
  3304. }
  3305. bool DAS_ScanningForWidth( das_room_t *proom )
  3306. {
  3307. return (proom->iwall < IVEC_DIAG_UP);
  3308. }
  3309. bool DAS_ScanningForFloor( das_room_t *proom )
  3310. {
  3311. return (proom->iwall == IVEC_DOWN);
  3312. }
  3313. ConVar das_door_height("adsp_door_height", "112"); // standard door height hl2
  3314. ConVar das_wall_height("adsp_wall_height", "128"); // standard wall height hl2
  3315. ConVar das_low_ceiling("adsp_low_ceiling", "108"); // low ceiling height hl2
  3316. // set origin for tracing out to walls to point above player's head
  3317. // allows calculations over walls and floor obstacles, and above door openings
  3318. // WARNING: the current settings are optimal for skipping floor and ceiling clutter,
  3319. // and for detecting rooms without 'looking' through doors or windows. Don't change these cvars for hl2!
  3320. void DAS_SetTraceHeight( das_room_t *proom, trace_t *ptrU, trace_t *ptrD )
  3321. {
  3322. // NOTE: when tracing down through player's box, endpos and startpos are reversed and
  3323. // startsolid and allsolid are true.
  3324. int zup = abs(ptrU->endpos.z - ptrU->startpos.z); // height above player's head
  3325. int zdown = abs(ptrD->endpos.z - ptrD->startpos.z); // distance to floor from player's head
  3326. int h;
  3327. h = zup + zdown;
  3328. int door_height = das_door_height.GetInt();
  3329. int wall_height = das_wall_height.GetInt();
  3330. int low_ceiling = das_low_ceiling.GetInt();
  3331. if (h > low_ceiling && h <= wall_height)
  3332. {
  3333. // low ceiling - trace out just above standard door height @ 112
  3334. if (h > door_height)
  3335. proom->vplayer.z = fpmin(ptrD->endpos.z, ptrD->startpos.z) + door_height + 1;
  3336. else
  3337. proom->vplayer.z = fpmin(ptrD->endpos.z, ptrD->startpos.z) + h - 1;
  3338. }
  3339. else if ( h > wall_height )
  3340. {
  3341. // tall ceiling - trace out over standard walls @ 128
  3342. proom->vplayer.z = fpmin(ptrD->endpos.z, ptrD->startpos.z) + wall_height + 1;
  3343. }
  3344. else
  3345. {
  3346. // very low ceiling, trace out from just below ceiling
  3347. proom->vplayer.z = fpmin(ptrD->endpos.z, ptrD->startpos.z) + h - 1;
  3348. proom->lowceiling = h;
  3349. }
  3350. Assert (proom->vplayer.z <= ptrU->endpos.z);
  3351. if (das_debug.GetInt() > 1)
  3352. {
  3353. // draw line to height, and between floor and ceiling
  3354. CDebugOverlay::AddLineOverlay( ptrD->endpos, ptrU->endpos, 0, 255, 0, 255, false, 20 );
  3355. Vector mins;
  3356. Vector maxs;
  3357. mins.Init(-1,-1,-2.0);
  3358. maxs.Init(1,1,0);
  3359. CDebugOverlay::AddBoxOverlay( proom->vplayer, mins, maxs, vec3_angle, 255, 0, 0, 0, 20 );
  3360. CDebugOverlay::AddBoxOverlay( ptrU->endpos, mins, maxs, vec3_angle, 0, 255, 0, 0, 20 );
  3361. CDebugOverlay::AddBoxOverlay( ptrD->endpos, mins, maxs, vec3_angle, 0, 255, 0, 0, 20 );
  3362. }
  3363. }
  3364. // we still want to test for new dsp even if jumping in portal2
  3365. #ifdef PORTAL2
  3366. ConVar das_max_z_trace_length( "das_max_z_trace_length", "100000", FCVAR_NONE, "Maximum height of player and still test for adsp" );
  3367. #else
  3368. ConVar das_max_z_trace_length( "das_max_z_trace_length", "72", FCVAR_NONE, "Maximum height of player and still test for adsp" );
  3369. #endif
  3370. // prepare room struct for new round of checks:
  3371. // clear out struct,
  3372. // init trace height origin by finding space above player's head
  3373. // returns true if player is in valid position to begin checks from
  3374. bool DAS_StartTraceChecks( das_room_t *proom )
  3375. {
  3376. // starting new check: store player position, init maxs, mins
  3377. // HACK FOR SPLITSCREEN
  3378. int nSlot = 0;
  3379. proom->vplayer_eyes = MainViewOrigin( nSlot );
  3380. proom->vplayer = MainViewOrigin( nSlot );
  3381. proom->height_max = 0;
  3382. proom->width_max = 0;
  3383. proom->length_max = 0;
  3384. proom->room_maxs.Init (0.0, 0.0, 0.0);
  3385. proom->room_mins.Init (10000.0, 10000.0, 10000.0);
  3386. proom->lowceiling = 0;
  3387. // find point between player's head and ceiling - trace out to walls from here
  3388. trace_t trU, trD;
  3389. CTraceFilterDAS filterU, filterD;
  3390. Vector v_dir = g_das_vec3[IVEC_DOWN]; // down - find floor
  3391. Vector endpoint = proom->vplayer + v_dir;
  3392. Ray_t ray;
  3393. ray.Init( proom->vplayer, endpoint );
  3394. g_pEngineTraceClient->TraceRay( ray, DAS_TRACE_MASK, &filterD, &trD );
  3395. // if player jumping or in air, don't continue
  3396. if ( trD.DidHit() && ( abs(trD.endpos.z - trD.startpos.z) > das_max_z_trace_length.GetFloat() ) )
  3397. {
  3398. return false;
  3399. }
  3400. v_dir = g_das_vec3[IVEC_UP]; // up - find ceiling
  3401. endpoint = proom->vplayer + v_dir;
  3402. ray.Init( proom->vplayer, endpoint );
  3403. g_pEngineTraceClient->TraceRay( ray, DAS_TRACE_MASK, &filterU, &trU );
  3404. // if down trace hits floor, set trace height, otherwise default is player eye location
  3405. if ( DAS_HitSolid( &trD) )
  3406. DAS_SetTraceHeight( proom, &trU, &trD );
  3407. return true;
  3408. }
  3409. void DAS_DebugDrawTrace ( trace_t *ptr, int r, int g, int b, float duration, int imax)
  3410. {
  3411. // das_debug == 3: draw horizontal trace bars for room width/depth detection
  3412. // das_debug == 4: draw upward traces for height detection
  3413. if (das_debug.GetInt() != imax)
  3414. return;
  3415. CDebugOverlay::AddLineOverlay( ptr->startpos, ptr->endpos, r, g, b, 255, false, duration );
  3416. Vector mins;
  3417. Vector maxs;
  3418. mins.Init(-1,-1,-2.0);
  3419. maxs.Init(1,1,0);
  3420. CDebugOverlay::AddBoxOverlay( ptr->endpos, mins, maxs, vec3_angle, r, g, b, 0, duration );
  3421. }
  3422. // wall surface data
  3423. struct das_surfdata_t
  3424. {
  3425. float dist; // distance to player
  3426. float reflectivity; // acoustic reflectivity of material on surface
  3427. Vector hit; // trace hit location
  3428. Vector norm; // wall normal at hit location
  3429. };
  3430. // trace hit wall surface, get info about surface and store in surfdata struct
  3431. // if scanning for height, bounce a second trace off of ceiling and get dist to floor
  3432. void DAS_GetSurfaceData( das_room_t *proom, trace_t *ptr, das_surfdata_t *psurfdata )
  3433. {
  3434. float dist; // distance to player
  3435. float reflectivity; // acoustic reflectivity of material on surface
  3436. Vector hit; // trace hit location
  3437. Vector norm; // wall normal at hit location
  3438. surfacedata_t *psurf;
  3439. psurf = physprops->GetSurfaceData( ptr->surface.surfaceProps );
  3440. reflectivity = psurf ? psurf->audio.reflectivity : DAS_REFLECTIVITY_NORM;
  3441. // keep wall hit location and normal, to calc room bounds and center
  3442. norm = ptr->plane.normal;
  3443. // get length to hit location
  3444. dist = VectorLength(ptr->endpos - ptr->startpos);
  3445. // if started tracing from within player box, startpos & endpos may be flipped
  3446. if (ptr->endpos.z >= ptr->startpos.z)
  3447. hit = ptr->endpos;
  3448. else
  3449. hit = ptr->startpos;
  3450. // if checking for max height by bouncing several vectors off of ceiling:
  3451. // ignore returned normal from 1st bounce, just search straight down from trace hit location
  3452. if ( DAS_ScanningForHeight( proom ) && !DAS_ScanningForFloor( proom ) )
  3453. {
  3454. trace_t tr2;
  3455. CTraceFilterDAS filter2;
  3456. norm.Init(0.0, 0.0, -1.0);
  3457. Vector endpoint = hit + ( norm * DAS_ROOM_TRACE_LEN );
  3458. Ray_t ray;
  3459. ray.Init( hit, endpoint );
  3460. g_pEngineTraceClient->TraceRay( ray, DAS_TRACE_MASK, &filter2, &tr2 );
  3461. //DAS_DebugDrawTrace( &tr2, 255, 255, 0, 10, 1);
  3462. if (tr2.DidHit())
  3463. {
  3464. // get distance between surfaces
  3465. dist = VectorLength(tr2.endpos - tr2.startpos);
  3466. }
  3467. }
  3468. // set up surface struct and return
  3469. psurfdata->dist = dist;
  3470. psurfdata->hit = hit;
  3471. psurfdata->norm = norm;
  3472. psurfdata->reflectivity = reflectivity;
  3473. }
  3474. // algorithm for detecting approximate size of space around player. Handles player in corner & non-axis aligned rooms.
  3475. // also handles player on catwalk or player under small bridge/overhang.
  3476. // The goal is to only change the dsp room description if the the player moves into
  3477. // a space which is SIGNIFICANTLY different from the previously set dsp space.
  3478. // save player position. find a point above player's head and trace out from here.
  3479. // from player position, get max width and max length:
  3480. // from player position,
  3481. // a) trace x,-x, y,-y axes
  3482. // b) trace xy, -xy, x-y, -x-y diagonals
  3483. // c) select largest room size detected from max width, max length
  3484. // from player position, get height
  3485. // a) trace out along front-up (or left-up, back-up, right-up), save hit locations
  3486. // b) trace down -z from hit locations
  3487. // c) save max height
  3488. // when max width, max length, max height all updated, get new player position
  3489. // get average room size & wall materials:
  3490. // update averages with one traceline per frame only
  3491. // returns true if room is fully updated and ready to check
  3492. bool DAS_UpdateRoomSize( das_room_t *proom )
  3493. {
  3494. Vector endpoint;
  3495. Vector startpoint;
  3496. Vector v_dir;
  3497. int iwall;
  3498. bool bskyhit = false;
  3499. das_surfdata_t surfdata;
  3500. // do nothing if room already fully checked
  3501. if ( proom->broomready )
  3502. return true;
  3503. // cycle through all walls, floor, ceiling
  3504. // get wall index
  3505. iwall = proom->iwall;
  3506. // get height above player and init proom for new round of checks
  3507. if (iwall == 0)
  3508. {
  3509. if (!DAS_StartTraceChecks( proom ))
  3510. return false; // bad location to check room - player is jumping etc.
  3511. }
  3512. // get trace vector
  3513. v_dir = g_das_vec3[iwall];
  3514. // trace out from trace origin, in axis-aligned direction or along diagonals
  3515. // if looking for max height, trace from top of player's eyes
  3516. if ( DAS_ScanningForHeight( proom ) )
  3517. {
  3518. startpoint = proom->vplayer_eyes;
  3519. endpoint = proom->vplayer_eyes + v_dir;
  3520. }
  3521. else
  3522. {
  3523. startpoint = proom->vplayer;
  3524. endpoint = proom->vplayer + v_dir;
  3525. }
  3526. // try less expensive world-only trace first (no props, no ents - just try to hit walls)
  3527. trace_t tr;
  3528. CTraceFilterWorldOnly filter;
  3529. Ray_t ray;
  3530. ray.Init( startpoint, endpoint );
  3531. g_pEngineTraceClient->TraceRay( ray, CONTENTS_SOLID, &filter, &tr );
  3532. // if didn't hit world, or we hit sky when looking horizontally,
  3533. // retrace, this time including props
  3534. if ( !DAS_HitSolid( &tr ) && DAS_ScanningForWidth( proom ) )
  3535. {
  3536. CTraceFilterDAS filterDas;
  3537. ray.Init( startpoint, endpoint );
  3538. g_pEngineTraceClient->TraceRay( ray, DAS_TRACE_MASK, &filterDas, &tr );
  3539. }
  3540. if (das_debug.GetInt() > 2)
  3541. {
  3542. // draw trace lines
  3543. if ( DAS_HitSolid( &tr ) )
  3544. DAS_DebugDrawTrace( &tr, 0, 255, 255, 10, DAS_ScanningForHeight( proom ) + 3);
  3545. else
  3546. DAS_DebugDrawTrace( &tr, 255, 0, 0, 10, DAS_ScanningForHeight( proom ) + 3); // red lines if sky hit or no hit
  3547. }
  3548. // init surface data with defaults, in case we didn't hit world
  3549. surfdata.dist = DAS_ROOM_TRACE_LEN;
  3550. surfdata.reflectivity = DAS_REFLECTIVITY_SKY; // assume sky or open area
  3551. surfdata.hit = endpoint; // trace hit location
  3552. surfdata.norm = -v_dir;
  3553. // check for sky hits
  3554. if ( DAS_HitSky( &tr ) )
  3555. {
  3556. bskyhit = true;
  3557. if ( DAS_ScanningForWidth( proom ) )
  3558. // ignore horizontal sky hits for distance calculations
  3559. surfdata.dist = 1.0;
  3560. else
  3561. surfdata.dist = surfdata.dist; // debug
  3562. }
  3563. // get length of trace if it hit world
  3564. // if hit solid and not sky (tr.DidHit() && !bskyhit)
  3565. // get surface information
  3566. if ( DAS_HitSolid( &tr) )
  3567. DAS_GetSurfaceData( proom, &tr, &surfdata );
  3568. // store surface data
  3569. proom->dist[iwall] = surfdata.dist;
  3570. proom->reflect[iwall] = clamp(surfdata.reflectivity, 0.0, 1.0);
  3571. proom->skyhits[iwall] = bskyhit ? 0.1 : 0.0;
  3572. proom->hit[iwall] = surfdata.hit;
  3573. proom->norm[iwall] = surfdata.norm;
  3574. // update wall counter
  3575. proom->iwall++;
  3576. if (proom->iwall == DAS_CWALLS)
  3577. {
  3578. bool b_good_node_location;
  3579. // calculate room mins, maxs, reflectivity etc
  3580. b_good_node_location = DAS_CalcRoomProps( proom );
  3581. // reset wall counter
  3582. proom->iwall = 0;
  3583. proom->broomready = b_good_node_location; // room ready to check if good node location
  3584. return b_good_node_location;
  3585. }
  3586. return false; // room not yet fully updated
  3587. }
  3588. // create entity enumerator for counting ents & summing volume of ents in room
  3589. class CDasEntEnum : public IPartitionEnumerator
  3590. {
  3591. public:
  3592. int m_count; // # of ents in space
  3593. float m_volume; // space occupied by ents
  3594. public:
  3595. void Reset()
  3596. {
  3597. m_count = 0;
  3598. m_volume = 0.0;
  3599. }
  3600. // called with each handle...
  3601. IterationRetval_t EnumElement( IHandleEntity *pHandleEntity )
  3602. {
  3603. float vol;
  3604. // get bounding box of entity
  3605. // Generate a collideable
  3606. ICollideable *pCollideable = g_pEngineTraceClient->GetCollideable( pHandleEntity );
  3607. if ( !pCollideable )
  3608. return ITERATION_CONTINUE;
  3609. // Check for solid
  3610. if ( !IsSolid( pCollideable->GetSolid(), pCollideable->GetSolidFlags() ) )
  3611. return ITERATION_CONTINUE;
  3612. m_count++;
  3613. // compute volume of space occupied by entity
  3614. Vector mins = pCollideable->OBBMins();
  3615. Vector maxs = pCollideable->OBBMaxs();
  3616. vol = fabs((maxs.x - mins.x) * (maxs.y - mins.y) * (maxs.z - mins.z));
  3617. m_volume += vol; // add to total vol
  3618. if (das_debug.GetInt() == 5)
  3619. {
  3620. // draw box around all objects detected
  3621. Vector orig = pCollideable->GetCollisionOrigin();
  3622. CDebugOverlay::AddBoxOverlay( orig, mins, maxs, pCollideable->GetCollisionAngles(), 255, 0, 255, 0, 60.0f );
  3623. }
  3624. return ITERATION_CONTINUE;
  3625. }
  3626. };
  3627. // determine # of solid ents/props within detected room boundaries
  3628. // and set diffusion based on count of ents and spatial volume of ents
  3629. void DAS_SetDiffusion( das_room_t *proom )
  3630. {
  3631. // BRJ 7/12/05
  3632. // This was commented out because the y component of proom->room_mins, proom->room_maxs was never
  3633. // being computed, causing a bogus box to be sent to the partition system. The results of
  3634. // this computation (namely the diffusion + ent_count fields of das_room_t) were never being used.
  3635. // Therefore, we'll avoid the enumeration altogether
  3636. proom->diffusion = 0.0f;
  3637. proom->ent_count = 0;
  3638. /*
  3639. CDasEntEnum enumerator;
  3640. SpatialPartitionListMask_t mask = PARTITION_CLIENT_SOLID_EDICTS; // count only solid ents in room
  3641. int count;
  3642. float vol;
  3643. float volroom;
  3644. float dfn;
  3645. enumerator.Reset();
  3646. SpatialPartition()->EnumerateElementsInBox(mask, proom->room_mins, proom->room_maxs, true, &enumerator );
  3647. count = enumerator.m_count;
  3648. vol = enumerator.m_volume;
  3649. // compute diffusion from volume
  3650. // how much space around player is filled with props?
  3651. volroom = (proom->room_maxs.x - proom->room_mins.x) * (proom->room_maxs.y - proom->room_mins.y) * (proom->room_maxs.z - proom->room_mins.z);
  3652. volroom = fabs(volroom);
  3653. if ( !(int)volroom )
  3654. volroom = 1.0;
  3655. dfn = vol / volroom; // % of total volume occupied by props
  3656. dfn = clamp (dfn, 0.0, 1.0);
  3657. proom->diffusion = dfn;
  3658. proom->ent_count = count;
  3659. */
  3660. }
  3661. // debug routine to display current room params
  3662. void DAS_DisplayRoomDEBUG( das_room_t *proom, bool fnew, float preset )
  3663. {
  3664. float dx,dy,dz;
  3665. Vector ctr;
  3666. float count;
  3667. if (das_debug.GetInt() == 0)
  3668. return;
  3669. dx = proom->length_max / 12.0;
  3670. dy = proom->width_max / 12.0;
  3671. dz = proom->height_max / 12.0;
  3672. float refl = proom->refl_avg;
  3673. count = (float)(proom->ent_count);
  3674. float fsky = (proom->bskyabove ? 1.0 : 0.0);
  3675. if (fnew)
  3676. DevMsg( "NEW DSP NODE: size:(%.0f,%.0f) height:(%.0f) dif %.4f : refl %.4f : cobj: %.0f : sky %.0f \n", dx, dy, dz, proom->diffusion, refl, count, fsky);
  3677. if (!fnew && preset < 0.0)
  3678. return;
  3679. if (preset >= 0.0)
  3680. {
  3681. if (proom == NULL)
  3682. return;
  3683. DevMsg( "DSP PRESET: %.0f size:(%.0f,%.0f) height:(%.0f) dif %.4f : refl %.4f : cobj: %.0f : sky %.0f \n", preset, dx, dy, dz, proom->diffusion, refl, count, fsky);
  3684. return;
  3685. }
  3686. // draw box around new node location
  3687. Vector mins;
  3688. Vector maxs;
  3689. mins.Init(-8,-8,-16);
  3690. maxs.Init(8,8,0);
  3691. CDebugOverlay::AddBoxOverlay( proom->vplayer, mins, maxs, vec3_angle, 0, 0, 255, 0, 1000.0f );
  3692. // draw red box around node origin
  3693. mins.Init(-0.5,-0.5,-1.0);
  3694. maxs.Init(0.5,0.5,0);
  3695. CDebugOverlay::AddBoxOverlay( proom->vplayer, mins, maxs, vec3_angle, 255, 0, 0, 0, 1000.0f );
  3696. CDebugOverlay::AddTextOverlay( proom->vplayer, 0, 10, 1.0, "DSP NODE" );
  3697. }
  3698. // check newly calculated room parameters against current stored params.
  3699. // if different, return true.
  3700. // NOTE: only call when all proom params have been calculated.
  3701. // return false if this is not a good location for creating a new node
  3702. bool DAS_CheckNewRoom( das_room_t *proom )
  3703. {
  3704. bool bnewroom;
  3705. float dw,dw2,dr,ds,dh;
  3706. int cchanged = 0;
  3707. das_room_t *proom_prev = NULL;
  3708. Vector2D v2d;
  3709. Vector v3d;
  3710. float dist;
  3711. // player can't see previous node, determine if this is a good place to lay down
  3712. // a new node. Get room at last seen node for comparison
  3713. if (g_pdas_last_node)
  3714. proom_prev = &(g_pdas_last_node->room);
  3715. // no previous room node saw player, go create new room node
  3716. if (!proom_prev)
  3717. {
  3718. bnewroom = true;
  3719. goto check_ret;
  3720. }
  3721. // if player not at least n feet from last node, return false
  3722. v3d = proom->vplayer - proom_prev->vplayer;
  3723. v2d.Init(v3d.x, v3d.y);
  3724. dist = Vector2DLength(v2d);
  3725. if (dist <= DAS_DIST_MIN)
  3726. return false;
  3727. // see if room size has changed significantly since last node
  3728. bnewroom = true;
  3729. dw = 0.0;
  3730. dw2 = 0.0;
  3731. dh = 0.0;
  3732. dr = 0.0;
  3733. if ( proom_prev->width_max != 0 )
  3734. dw = (float)proom->width_max / (float)proom_prev->width_max; // max width delta
  3735. if ( proom_prev->length_max != 0 )
  3736. dw2 = (float)proom->length_max / (float)proom_prev->length_max; // max length delta
  3737. if ( proom_prev->height_max != 0 )
  3738. dh = (float)proom->height_max / (float)proom_prev->height_max; // max height delta
  3739. if ( proom_prev->refl_avg != 0.0 )
  3740. dr = proom->refl_avg / proom_prev->refl_avg; // reflectivity delta
  3741. ds = fabs( proom->sky_pct - proom_prev->sky_pct); // sky hits delta
  3742. if (dw > 1.0) dw = 1.0 / dw;
  3743. if (dw2 > 1.0) dw = 1.0 / dw2;
  3744. if (dh > 1.0) dh = 1.0 / dh;
  3745. if (dr > 1.0) dr = 1.0 / dr;
  3746. if ( (1.0 - dw) >= DAS_WIDTH_MIN )
  3747. cchanged++;
  3748. if ( (1.0 - dw2) >= DAS_WIDTH_MIN )
  3749. cchanged++;
  3750. // if ( (1.0 - dh) >= DAS_WIDTH_MIN ) // don't change room based on height change
  3751. // cchanged++;
  3752. // new room only if at least 1 changed
  3753. if (cchanged >= 1)
  3754. goto check_ret;
  3755. // if ( (1.0 - dr) >= DAS_REFL_MIN ) // don't change room based on reflectivity change
  3756. // goto check_ret;
  3757. // if (ds >= DAS_SKYHIT_MIN )
  3758. // goto check_ret;
  3759. // new room if sky above changes state
  3760. if (proom->bskyabove != proom_prev->bskyabove)
  3761. goto check_ret;
  3762. // room didn't change significantly, return false
  3763. bnewroom = false;
  3764. check_ret:
  3765. if ( bnewroom )
  3766. {
  3767. // if low ceiling detected < 112 units, and max height is > low ceiling height by 20%, discard - no change
  3768. // this detects player in doorway, under pipe or narrow bridge
  3769. if ( proom->lowceiling && (proom->lowceiling < proom->height_max))
  3770. {
  3771. float h = (float)(proom->lowceiling) / (float)proom->height_max;
  3772. if (h < 0.8)
  3773. return false;
  3774. }
  3775. DAS_SetDiffusion( proom );
  3776. }
  3777. DAS_DisplayRoomDEBUG( proom, bnewroom, -1.0 );
  3778. return bnewroom;
  3779. }
  3780. extern int DSP_ConstructPreset( bool bskyabove, int width, int length, int height, float fdiffusion, float freflectivity, float *psurf_refl, int inode, int cnodes);
  3781. // select new dsp_room based on size, wall materials
  3782. // (or modulate params for current dsp)
  3783. // returns new preset # for dsp_automatic
  3784. int DAS_GetRoomDSP( das_room_t *proom, int inode )
  3785. {
  3786. // preset constructor
  3787. // call dsp module with params, get dsp preset back
  3788. bool bskyabove = proom->bskyabove;
  3789. int width = proom->width_max;
  3790. int length = proom->length_max;
  3791. int height = proom->height_max;
  3792. float fdiffusion = proom->diffusion;
  3793. float freflectivity = proom->refl_avg;
  3794. float surf_refl[6];
  3795. // fill array of surface reflectivities - for left,right,front,back,ceiling,floor
  3796. for (int i = 0; i < 6; i++)
  3797. surf_refl[i] = proom->refl_walls[i];
  3798. return DSP_ConstructPreset( bskyabove, width, length, height, fdiffusion, freflectivity, surf_refl, inode, DAS_CNODES);
  3799. }
  3800. // main entry point: call once per frame to update dsp_automatic
  3801. // for automatic room detection. dsp_room must be set to DSP_AUTOMATIC to enable.
  3802. // NOTE: this routine accumulates traceline information over several frames - it
  3803. // never traces more than 3 times per call, and normally just once per call.
  3804. void DAS_CheckNewRoomDSP()
  3805. {
  3806. VPROF("DAS_CheckNewRoomDSP");
  3807. das_room_t *proom = &g_das_room;
  3808. int dsp_preset;
  3809. bool bRoom_ready = false;
  3810. // if listener has not been updated, do nothing
  3811. if ( !SND_IsListenerValid() )
  3812. return;
  3813. if ( !SND_IsInGame() )
  3814. return;
  3815. // make sure we init nodes & vectors first time this is called
  3816. if ( !g_bdas_init_nodes )
  3817. {
  3818. g_bdas_init_nodes = 1;
  3819. DAS_InitNodes();
  3820. }
  3821. if ( !DSP_CheckDspAutoEnabled())
  3822. {
  3823. // make sure room params are reinitialized each time autoroom is selected
  3824. g_bdas_room_init = 0;
  3825. return;
  3826. }
  3827. if ( !g_bdas_room_init )
  3828. {
  3829. g_bdas_room_init = 1;
  3830. DAS_InitAutoRoom( proom );
  3831. }
  3832. // get time
  3833. double dtime = g_pSoundServices->GetHostTime();
  3834. // compare to previous time - don't check for new room until timer expires
  3835. // ie: wait at least DAS_AUTO_WAIT seconds betweeen preset changes
  3836. if ( fabs(dtime - proom->last_dsp_change) < DAS_AUTO_WAIT )
  3837. return;
  3838. // first, update room size parameters, see if room is ready to check - if room is updated, return true right away
  3839. // 3 traces per frame while accumulating room size info
  3840. for (int i = 0 ; i < 3; i++)
  3841. bRoom_ready = DAS_UpdateRoomSize( proom );
  3842. if (!bRoom_ready)
  3843. return;
  3844. // new room defaults to false
  3845. //g_current_das_room_new = false;
  3846. //g_current_das_room_changed = false;
  3847. if ( !g_bdas_create_new_node )
  3848. {
  3849. // next, check all nodes for line of sight to player - if all checked, return true right away
  3850. if ( !DAS_CheckNextNode( proom ) )
  3851. {
  3852. // check all nodes first
  3853. return;
  3854. }
  3855. // find out if any previously stored nodes can see player,
  3856. // if so, get closest node's dsp preset
  3857. dsp_preset = DAS_GetDspPreset( proom->bskyabove );
  3858. if (dsp_preset != -1)
  3859. {
  3860. // an existing node can see player - just set preset and return
  3861. if (dsp_preset != dsp_room_GetInt())
  3862. {
  3863. // changed preset, so update timestamp
  3864. proom->last_dsp_change = g_pSoundServices->GetHostTime();
  3865. if (g_pdas_last_node)
  3866. {
  3867. DAS_DisplayRoomDEBUG( &(g_pdas_last_node->room), false, (float)dsp_preset );
  3868. //memcpy(&g_current_adsp_auto_params, &(g_pdas_last_node->room), sizeof(g_current_adsp_auto_params));
  3869. // if it's changed is not new?
  3870. g_current_das_room_changed = true;
  3871. g_current_das_room_new = false;
  3872. DAS_StoreRoomVarsAPI(&(g_pdas_last_node->room));
  3873. }
  3874. }
  3875. DSP_SetDspAuto( dsp_preset );
  3876. goto check_new_room_exit;
  3877. }
  3878. }
  3879. g_bdas_create_new_node = true;
  3880. // no nodes can see player, need to try to create a new one
  3881. // check for 'new' room around player
  3882. if ( DAS_CheckNewRoom( proom ) )
  3883. {
  3884. // new room found - update dsp_automatic
  3885. dsp_preset = DAS_GetRoomDSP( proom, DAS_GetNextNodeIndex() );
  3886. DSP_SetDspAuto( dsp_preset );
  3887. // changed preset, so update timestamp
  3888. proom->last_dsp_change = g_pSoundServices->GetHostTime();
  3889. // save room as new node
  3890. DAS_StoreNode( proom, dsp_preset );
  3891. g_current_das_room_new = true;
  3892. DAS_StoreRoomVarsAPI(proom);
  3893. goto check_new_room_exit;
  3894. }
  3895. check_new_room_exit:
  3896. // reset new node creation flag - start checking for visible nodes again
  3897. g_bdas_create_new_node = false;
  3898. // reset room checking flag - start checking room around player again
  3899. proom->broomready = false;
  3900. // reset node checking flag - start checking nodes around player again
  3901. DAS_ResetNodes();
  3902. return;
  3903. }
  3904. //
  3905. //
  3906. //
  3907. // remap contents of volumes[] arrary if sound originates from player, or is music, and is 100% 'mono'
  3908. // ie: same volume in all channels
  3909. void RemapPlayerOrMusicVols( channel_t *ch, float volumes[CCHANVOLUMES/2], bool fplayersound, bool fmusicsound, float mono )
  3910. {
  3911. VPROF_("RemapPlayerOrMusicVols", 2, VPROF_BUDGETGROUP_OTHER_SOUND, false, BUDGETFLAG_OTHER );
  3912. if ( !fplayersound && !fmusicsound )
  3913. return; // no remapping
  3914. if ( ch->flags.bSpeaker )
  3915. return; // don't remap speaker sounds rebroadcast on player
  3916. // get total volume
  3917. float vol_total = 0.0;
  3918. int k;
  3919. for (k = 0; k < CCHANVOLUMES/2; k++)
  3920. vol_total += (float)volumes[k];
  3921. if ( !g_AudioDevice->IsSurround() )
  3922. {
  3923. if (mono < 1.0)
  3924. return;
  3925. // remap 2 chan non-spatialized versions of player and music sounds
  3926. // note: this is required to keep volumes same as 4 & 5 ch cases!
  3927. float vol_dist_music[] = {1.0, 1.0}; // FL, FR music volumes
  3928. float vol_dist_player[] = {1.0, 1.0}; // FL, FR player volumes
  3929. float *pvol_dist;
  3930. pvol_dist = (fplayersound ? vol_dist_player : vol_dist_music);
  3931. for (k = 0; k < 2; k++)
  3932. volumes[k] = clamp(vol_total * pvol_dist[k], 0, 255);
  3933. return;
  3934. }
  3935. // surround sound configuration...
  3936. if ( fplayersound ) // && (ch->bstereowav && ch->wavtype != CHAR_DIRECTIONAL && ch->wavtype != CHAR_DISTVARIANT) )
  3937. {
  3938. // NOTE: player sounds also get n% overall volume boost.
  3939. //float vol_dist5[] = {0.29, 0.29, 0.09, 0.09, 0.63}; // FL, FR, RL, RR, FC - 5 channel (mono source) volume distribution
  3940. //float vol_dist5st[] = {0.29, 0.29, 0.09, 0.09, 0.63}; // FL, FR, RL, RR, FC - 5 channel (stereo source) volume distribution
  3941. float vol_dist5[] = {0.30, 0.30, 0.09, 0.09, 0.59}; // FL, FR, RL, RR, FC - 5 channel (mono source) volume distribution
  3942. float vol_dist5st[] = {0.30, 0.30, 0.09, 0.09, 0.59}; // FL, FR, RL, RR, FC - 5 channel (stereo source) volume distribution
  3943. float vol_dist4[] = {0.50, 0.50, 0.15, 0.15, 0.00}; // FL, FR, RL, RR, 0 - 4 channel (mono source) volume distribution
  3944. float vol_dist4st[] = {0.50, 0.50, 0.15, 0.15, 0.00}; // FL, FR, RL, RR, 0 - 4 channel (stereo source)volume distribution
  3945. float *pvol_dist;
  3946. if ( ch->flags.bstereowav && (ch->wavtype == CHAR_OMNI || ch->wavtype == CHAR_SPATIALSTEREO || ch->wavtype == 0 || ch->wavtype == CHAR_DIRSTEREO))
  3947. {
  3948. pvol_dist = (g_AudioDevice->IsSurroundCenter() ? vol_dist5st : vol_dist4st);
  3949. }
  3950. else
  3951. {
  3952. pvol_dist = (g_AudioDevice->IsSurroundCenter() ? vol_dist5 : vol_dist4);
  3953. }
  3954. for (k = 0; k < 5; k++)
  3955. volumes[k] = clamp(vol_total * pvol_dist[k], 0, 255);
  3956. return;
  3957. }
  3958. // Special case for music in surround mode
  3959. if ( fmusicsound )
  3960. {
  3961. float vol_dist5[] = {0.5, 0.5, 0.25, 0.25, 0.0}; // FL, FR, RL, RR, FC - 5 channel distribution
  3962. float vol_dist4[] = {0.5, 0.5, 0.25, 0.25, 0.0}; // FL, FR, RL, RR, 0 - 4 channel distribution
  3963. float *pvol_dist;
  3964. pvol_dist = (g_AudioDevice->IsSurroundCenter() ? vol_dist5 : vol_dist4);
  3965. for (k = 0; k < 5; k++)
  3966. volumes[k] = clamp(vol_total * pvol_dist[k], 0, 255);
  3967. return;
  3968. }
  3969. return;
  3970. }
  3971. void SND_MergeVolumes( const int build_volumes[ MAX_SPLITSCREEN_CLIENTS ][CCHANVOLUMES/2], int volumes[CCHANVOLUMES/2] )
  3972. {
  3973. // Three methods
  3974. // Sum and clamp == 0
  3975. // Use max == 1
  3976. // Use avg == 2
  3977. for ( int v = 0; v < CCHANVOLUMES/2; ++v )
  3978. {
  3979. int val = 0;
  3980. int count = 0;
  3981. int maxVal = INT_MIN;
  3982. FOR_EACH_VALID_SPLITSCREEN_PLAYER( hh )
  3983. {
  3984. int check = build_volumes[ hh ][ v ];
  3985. if ( check > maxVal )
  3986. maxVal = check;
  3987. val += check;
  3988. ++count;
  3989. }
  3990. switch ( g_SndMergeMethod )
  3991. {
  3992. default:
  3993. case SND_MERGE_SUMANDCLIP:
  3994. {
  3995. volumes[ v ] = MIN( val, 255 );
  3996. }
  3997. break;
  3998. case SND_MERGE_MAX:
  3999. {
  4000. volumes[ v ] = maxVal;
  4001. }
  4002. break;
  4003. case SND_MERGE_AVG:
  4004. {
  4005. if ( count > 0 )
  4006. {
  4007. volumes[ v ] = val / count;
  4008. }
  4009. else
  4010. {
  4011. volumes[ v ] = 0;
  4012. }
  4013. }
  4014. break;
  4015. }
  4016. }
  4017. }
  4018. // float version
  4019. void SND_MergeVolumes( const float build_volumes[ MAX_SPLITSCREEN_CLIENTS ][CCHANVOLUMES/2], float volumes[CCHANVOLUMES/2] )
  4020. {
  4021. // Three methods
  4022. // Sum and clamp == 0
  4023. // Use max == 1
  4024. // Use avg == 2
  4025. for ( int v = 0; v < CCHANVOLUMES/2; ++v )
  4026. {
  4027. float val = 0;
  4028. float count = 0;
  4029. float maxVal = 0.0;
  4030. FOR_EACH_VALID_SPLITSCREEN_PLAYER( hh )
  4031. {
  4032. float check = build_volumes[ hh ][ v ];
  4033. if ( check > maxVal )
  4034. maxVal = check;
  4035. val += check;
  4036. ++count;
  4037. }
  4038. switch ( g_SndMergeMethod )
  4039. {
  4040. default:
  4041. case SND_MERGE_SUMANDCLIP:
  4042. {
  4043. volumes[ v ] = MIN( val, 1.0 );
  4044. }
  4045. break;
  4046. case SND_MERGE_MAX:
  4047. {
  4048. volumes[ v ] = maxVal;
  4049. }
  4050. break;
  4051. case SND_MERGE_AVG:
  4052. {
  4053. if ( count > 0 )
  4054. {
  4055. volumes[ v ] = val / count;
  4056. }
  4057. else
  4058. {
  4059. volumes[ v ] = 0.0;
  4060. }
  4061. }
  4062. break;
  4063. }
  4064. }
  4065. }
  4066. static CInterlockedInt s_nSoundGuid = 0;
  4067. static int s_nMaxQueuedGUID = 0; // Max GUID to go through the queue. Used to optimize some tests.
  4068. static CUtlVector<activethreadsound_t> g_ActiveSoundsLastUpdate( 0, MAX_CHANNELS );
  4069. static int SND_GetGUID()
  4070. {
  4071. int nextGUID = ++s_nSoundGuid;
  4072. if ( nextGUID < 0 )
  4073. {
  4074. s_nSoundGuid = nextGUID = 1; // No point having negative GUIDs
  4075. }
  4076. return nextGUID;
  4077. }
  4078. void SND_ActivateChannel( channel_t *pChannel, int nGUID )
  4079. {
  4080. Q_memset( pChannel, 0, sizeof(*pChannel) );
  4081. g_ActiveChannels.Add( pChannel );
  4082. pChannel->guid = nGUID;
  4083. pChannel->hrtf.lerp = 0.0f;
  4084. }
  4085. bool IsSoundSourceViewEntity( int soundsource )
  4086. {
  4087. FOR_EACH_VALID_SPLITSCREEN_PLAYER( hh )
  4088. {
  4089. if ( soundsource == g_pSoundServices->GetViewEntity( hh ) )
  4090. return true;
  4091. }
  4092. return false;
  4093. }
  4094. ConVar voice_minimum_gain("voice_minimum_gain", "0.5");
  4095. /*
  4096. =================
  4097. SND_ExecuteUpdateOperators
  4098. =================
  4099. */
  4100. ConVar snd_sos_exec_when_paused( "snd_sos_exec_when_paused", "1" );
  4101. void SND_ExecuteUpdateOperators( channel_t *ch )
  4102. {
  4103. // don't execute operators if game is paused
  4104. if( g_pSoundServices->IsGamePaused() && !snd_sos_exec_when_paused.GetInt() )
  4105. {
  4106. return;
  4107. }
  4108. // sanity check
  4109. if( !ch->m_pStackList || ( ch->m_pStackList && !ch->m_pStackList->HasStack( CSosOperatorStack::SOS_UPDATE ) ) )
  4110. {
  4111. return;
  4112. }
  4113. VPROF( "SND_ExecuteUpdateOperators" );
  4114. //////////////////////////////////////////////////////////////////////////
  4115. // set all scratch pad settings
  4116. //////////////////////////////////////////////////////////////////////////
  4117. // setup scratchpad
  4118. g_scratchpad.SetPerExecution( ch, NULL );
  4119. #if !defined( _X360 )
  4120. // Currently we don't process voice channels via operators
  4121. if ( ch->sfx &&
  4122. ch->sfx->pSource &&
  4123. ch->sfx->pSource->GetType() == CAudioSource::AUDIO_SOURCE_VOICE )
  4124. {
  4125. Log_Warning( LOG_SOUND_OPERATOR_SYSTEM, "Voice channel attempting to be processed by operators" );
  4126. // Voice_Spatialize( ch );
  4127. }
  4128. #endif
  4129. //////////////////////////////////////////////////////////////////////////
  4130. // Execute operators
  4131. //////////////////////////////////////////////////////////////////////////
  4132. ch->m_pStackList->Execute( CSosOperatorStack::SOS_UPDATE, ch, &g_scratchpad );
  4133. // ------------------------- post process stuff ----------------------------
  4134. // prevent left/right/front/rear/center volumes from changing too quickly & producing pops
  4135. ChannelUpdateVolXfade( ch );
  4136. // end of first time spatializing sound
  4137. if ( SND_IsInGame() || toolframework->InToolMode() )
  4138. {
  4139. ch->flags.bfirstpass = false;
  4140. }
  4141. }
  4142. /*
  4143. =================
  4144. SND_Spatialize
  4145. =================
  4146. */
  4147. void SND_Spatialize(channel_t *ch)
  4148. {
  4149. VPROF( "SND_Spatialize" );
  4150. if (ch->wavtype == CHAR_HRTF)
  4151. {
  4152. Vector origin;
  4153. IClientEntity *pEnt = ch->hrtf.follow_entity ? entitylist->GetClientEntity(ch->soundsource) : nullptr;
  4154. if (pEnt != nullptr)
  4155. {
  4156. origin = pEnt->GetRenderOrigin();
  4157. }
  4158. else
  4159. {
  4160. origin = ch->origin;
  4161. }
  4162. if (ch->hrtf.debug_lock_position == false)
  4163. {
  4164. QAngle listener_angles;
  4165. //Calculate the listener origin as some distance behind the camera ('snd_hrtf_distance_behind') as this
  4166. //gives better results for HRTF. For nearby sounds we want to make it closer to the camera position
  4167. //so sounds behind us don't sound like they are in front.
  4168. float distance_behind = snd_hrtf_distance_behind.GetFloat();
  4169. if ( distance_behind < 0.0f )
  4170. {
  4171. distance_behind = 0.0f;
  4172. }
  4173. if ( distance_behind > 100.0f )
  4174. {
  4175. distance_behind = 100.0f;
  4176. }
  4177. Vector listener_origin_modified = listener_origin[0] - distance_behind*listener_forward[0];
  4178. const float dist_to_sound = MIN((listener_origin_modified - origin).Length(), (listener_origin[0] - origin).Length());
  4179. if ( dist_to_sound < distance_behind )
  4180. {
  4181. listener_origin_modified = listener_origin[0] - dist_to_sound*listener_forward[0];
  4182. }
  4183. // sound_pos is really sound_pos_listener_relative
  4184. Vector sound_pos = listener_origin_modified - origin;
  4185. VectorAngles(listener_forward[0], listener_angles);
  4186. matrix3x4_t mat;
  4187. AngleMatrix(listener_angles, mat);
  4188. sound_pos = mat.TransformVectorByInverse(sound_pos);
  4189. VectorNormalize(sound_pos);
  4190. //Swizzle our co-ordinate system to Phonon's.
  4191. ch->hrtf.vec.x = sound_pos.y;
  4192. ch->hrtf.vec.y = -sound_pos.z;
  4193. ch->hrtf.vec.z = sound_pos.x;
  4194. }
  4195. //Give some reasonable default behavior for lerping off hrtf when
  4196. //close to the sound. Can always be overridden in operator stacks.
  4197. Vector diff = listener_origin[0] - origin;
  4198. float fDistance = sqrt(diff[0] * diff[0] + diff[1] * diff[1] + diff[2] * diff[2]);
  4199. const float fMinDistance = snd_hrtf_lerp_min_distance.GetFloat();
  4200. const float fMaxDistance = snd_hrtf_lerp_max_distance.GetFloat();
  4201. if (fDistance < fMinDistance)
  4202. {
  4203. ch->hrtf.lerp = 0.0f;
  4204. }
  4205. else if (fDistance > fMaxDistance)
  4206. {
  4207. ch->hrtf.lerp = 1.0f; //snd_hrtf_ratio.GetFloat();
  4208. }
  4209. else
  4210. {
  4211. ch->hrtf.lerp = 1.0f; //snd_hrtf_ratio.GetFloat() * (fDistance - fMinDistance) / (fMaxDistance - fMinDistance);
  4212. }
  4213. }
  4214. // process via operators only
  4215. if( ch->m_pStackList && ch->m_pStackList->HasStack( CSosOperatorStack::SOS_UPDATE ) )
  4216. {
  4217. SND_ExecuteUpdateOperators( ch );
  4218. return;
  4219. }
  4220. // This will be -1 if it's a sound that's merged at the channel volume level across the players
  4221. vec_t dist;
  4222. Vector source_vec[ MAX_SPLITSCREEN_CLIENTS ];
  4223. Vector source_vec_DL;
  4224. Vector source_vec_DR;
  4225. Vector source_doppler_left;
  4226. Vector source_doppler_right;
  4227. int dopplerSlot = -1;
  4228. bool fdopplerwav = false;
  4229. float gain;
  4230. float scale = 1.0;
  4231. bool fplayersound = false;
  4232. bool fmusicsound = false;
  4233. float mono = 0.0;
  4234. bool bAttenuated = true;
  4235. bool bOkayToTrace = false;
  4236. ch->dspface = 1.0; // default facing direction: always facing player
  4237. ch->dspmix = 0; // default mix 0% dsp_room fx
  4238. ch->distmix = 0; // default 100% left (near) wav
  4239. #if !defined( _X360 )
  4240. if ( ch->sfx &&
  4241. ch->sfx->pSource &&
  4242. ch->sfx->pSource->GetType() == CAudioSource::AUDIO_SOURCE_VOICE )
  4243. {
  4244. Voice_Spatialize( ch );
  4245. }
  4246. #endif
  4247. // For Splitscreen this is the average position, a total hack!!!
  4248. Vector blended_listener_origin( 0, 0, 0 );
  4249. int count = 0;
  4250. FOR_EACH_VALID_SPLITSCREEN_PLAYER( nSlot )
  4251. {
  4252. blended_listener_origin += listener_origin[ nSlot ];
  4253. ++count;
  4254. }
  4255. if ( count > 1 )
  4256. {
  4257. blended_listener_origin /= (float)count;
  4258. }
  4259. if ( ch->wavtype == CHAR_RADIO || ( IsSoundSourceViewEntity( ch->soundsource ) && !toolframework->InToolMode() ) || ( ch->sfx && ch->sfx->pSource && ch->sfx->pSource->GetType() == CAudioSource::AUDIO_SOURCE_VOICE))
  4260. {
  4261. // sounds coming from listener actually come from a short distance directly in front of listener
  4262. // in tool mode however, the view entity is meaningless, since we're viewing from arbitrary locations in space
  4263. fplayersound = true;
  4264. }
  4265. // music has separate mix properties, detect it
  4266. if ( ch->sfx && ch->sfx->m_bIsMusic )
  4267. {
  4268. fmusicsound = true;
  4269. fplayersound = false;
  4270. }
  4271. // map gain through global mixer by soundtype
  4272. // stores into channel for use later
  4273. int last_mixgroupid;
  4274. mixervalues_t mixValues;
  4275. MXR_GetVolFromMixGroup( ch, &mixValues, &last_mixgroupid );
  4276. // apply mixer levels to channel to carry through operations
  4277. // restored at the end of the function
  4278. float saveChannelDistMult = ch->dist_mult;
  4279. float soundlevel = (float)DIST_MULT_TO_SNDLVL(ch->dist_mult);
  4280. soundlevel *= mixValues.level;
  4281. ch->dist_mult = SNDLVL_TO_DIST_MULT((int)soundlevel);
  4282. // update channel's position in case ent that made the sound is moving.
  4283. QAngle source_angles;
  4284. source_angles.Init(0.0, 0.0, 0.0);
  4285. Vector vEntOrigin = ch->origin;
  4286. bool looping = false;
  4287. CAudioSource *pSource = ch->sfx ? ch->sfx->pSource : NULL;
  4288. if ( pSource )
  4289. {
  4290. looping = pSource->IsLooped();
  4291. }
  4292. SpatializationInfo_t si;
  4293. char nameBuf[MAX_PATH];
  4294. si.info.Set(
  4295. ch->soundsource,
  4296. ch->entchannel,
  4297. ch->sfx ? ch->sfx->getname(nameBuf,sizeof(nameBuf)) : "",
  4298. ch->origin,
  4299. ch->direction,
  4300. ch->master_vol,
  4301. DIST_MULT_TO_SNDLVL( ch->dist_mult ),
  4302. looping,
  4303. ch->pitch,
  4304. blended_listener_origin, // HACK FOR SPLITSCREEN, only client\c_func_tracktrain.cpp(100): CalcClosestPointOnLine( info.info.vListenerOrigin, vecStart, vecEnd, *info.pOrigin, &t ); every looked at listener origin in this structure...
  4305. ch->speakerentity,
  4306. 0 ); // unspecified index is fine
  4307. // csgo
  4308. bool bIsMenuMusic = false;
  4309. if( ch->sfx->m_bIsMusic && V_stristr( nameBuf, "mainmenu" ) )
  4310. {
  4311. bIsMenuMusic = true;
  4312. }
  4313. si.type = SpatializationInfo_t::SI_INSPATIALIZATION;
  4314. si.pOrigin = &vEntOrigin;
  4315. si.pAngles = &source_angles;
  4316. si.pflRadius = NULL;
  4317. if ( ch->soundsource != 0 && ch->radius == 0 )
  4318. {
  4319. si.pflRadius = &ch->radius;
  4320. }
  4321. CUtlVector< Vector > utlVecMultiOrigins;
  4322. si.m_pUtlVecMultiOrigins = &utlVecMultiOrigins;
  4323. si.m_pUtlVecMultiAngles = NULL;
  4324. {
  4325. VPROF_("SoundServices->GetSoundSpatializtion", 2, VPROF_BUDGETGROUP_OTHER_SOUND, false, BUDGETFLAG_OTHER );
  4326. g_pSoundServices->GetSoundSpatialization( ch->soundsource, si );
  4327. }
  4328. if ( ch->flags.bUpdatePositions )
  4329. {
  4330. AngleVectors( source_angles, &ch->direction );
  4331. ch->origin = vEntOrigin;
  4332. }
  4333. else
  4334. {
  4335. VectorAngles( ch->direction, source_angles );
  4336. }
  4337. if ( IsPC() && ch->userdata != 0 )
  4338. {
  4339. g_pSoundServices->GetToolSpatialization( ch->userdata, ch->guid, si );
  4340. if ( ch->flags.bUpdatePositions )
  4341. {
  4342. AngleVectors( source_angles, &ch->direction );
  4343. ch->origin = vEntOrigin;
  4344. }
  4345. }
  4346. fdopplerwav = ((ch->wavtype == CHAR_DOPPLER) && !fplayersound);
  4347. if ( fdopplerwav )
  4348. {
  4349. VPROF_( "SND_Spatialize doppler", 2, VPROF_BUDGETGROUP_OTHER_SOUND, false, BUDGETFLAG_OTHER );
  4350. // along sound source forward direction (doppler wavs)
  4351. // calculate point of closest approach for CHAR_DOPPLER wavs, replace source_vec
  4352. float bestDist = FLT_MAX;
  4353. Vector nearestPoint;
  4354. FOR_EACH_VALID_SPLITSCREEN_PLAYER( nSlot )
  4355. {
  4356. Vector nearPoint = ch->origin; // default nearest sound approach point
  4357. if ( SND_GetClosestPoint( ch, listener_origin[ nSlot ], source_angles, nearPoint ) )
  4358. {
  4359. float dist = (nearPoint - listener_origin[nSlot]).Length();
  4360. if ( dist < bestDist )
  4361. {
  4362. dopplerSlot = nSlot;
  4363. bestDist = dist;
  4364. nearestPoint = nearPoint;
  4365. }
  4366. }
  4367. }
  4368. // if doppler sound was 'shot' away from all listeners, don't play it
  4369. if ( dopplerSlot < 0 )
  4370. {
  4371. goto ClearAllVolumes;
  4372. }
  4373. // find location of doppler left & doppler right points
  4374. SND_GetDopplerPoints( ch, listener_origin[ dopplerSlot ], source_angles, nearestPoint, source_doppler_left, source_doppler_right);
  4375. // source_vec_DL is vector from listener to doppler left point
  4376. // source_vec_DR is vector from listener to doppler right point
  4377. VectorSubtract(source_doppler_left, listener_origin[ dopplerSlot ], source_vec_DL );
  4378. VectorSubtract(source_doppler_right, listener_origin[ dopplerSlot ], source_vec_DR );
  4379. // normalized vectors to left and right doppler locations
  4380. dist = VectorNormalize( source_vec_DL );
  4381. VectorNormalize( source_vec_DR );
  4382. // don't play doppler if out of range
  4383. // unless recording in the tool, since we may play back in range
  4384. if ( dist > DOPPLER_RANGE_MAX && !toolframework->IsToolRecording() )
  4385. goto ClearAllVolumes;
  4386. }
  4387. else
  4388. {
  4389. // source_vec is vector from listener to sound source
  4390. dist = FLT_MAX;
  4391. FOR_EACH_VALID_SPLITSCREEN_PLAYER( hh )
  4392. {
  4393. if ( fplayersound )
  4394. {
  4395. // Hack for now
  4396. // get 2d forward direction vector, ignoring pitch angle
  4397. Vector listener_forward2d;
  4398. ConvertListenerVectorTo2D( &listener_forward2d, &listener_right[ hh ] );
  4399. // player sounds originate from 1' in front of player, 2d
  4400. VectorMultiply(listener_forward2d, 12.0, source_vec[ hh ] );
  4401. }
  4402. else
  4403. {
  4404. VectorSubtract(ch->origin, listener_origin[ hh ], source_vec[ hh ]);
  4405. }
  4406. // normalize source_vec and get distance from listener to source
  4407. float checkDist = VectorNormalize( source_vec[ hh ] );
  4408. if ( checkDist < dist )
  4409. {
  4410. dist = checkDist;
  4411. }
  4412. }
  4413. }
  4414. // calculate dsp mix based on distance to listener & sound level (linear approximation)
  4415. // ... and sound mixer contribution
  4416. if (ch->wavtype != CHAR_DIRSTEREO)
  4417. {
  4418. ch->dspmix = mixValues.dsp * SND_GetDspMix( ch, dist );
  4419. }
  4420. // calculate sound source facing direction for CHAR_DIRECTIONAL wavs
  4421. if ( !fplayersound )
  4422. {
  4423. ch->dspface = SND_GetFacingDirection( ch, blended_listener_origin, source_angles );
  4424. // calculate mixing parameter for CHAR_DISTVAR wavs
  4425. ch->distmix = SND_GetDistanceMix( ch, dist );
  4426. }
  4427. // for sounds with a radius, spatialize left/right/front/rear evenly within the radius
  4428. if ( ch->radius > 0 && dist < ch->radius && !fdopplerwav )
  4429. {
  4430. float interval = ch->radius * 0.5;
  4431. mono = dist - interval;
  4432. if ( mono < 0.0 )
  4433. mono = 0.0;
  4434. mono /= interval;
  4435. // mono is 0.0 -> 1.0 from radius 100% to radius 50%
  4436. mono = 1.0 - mono;
  4437. }
  4438. // don't pan sounds with no attenuation
  4439. if ( ch->dist_mult <= 0 && !fdopplerwav && !( ch->wavtype == CHAR_DIRSTEREO))
  4440. {
  4441. // sound is centered left/right/front/back
  4442. mono = 1.0;
  4443. bAttenuated = false;
  4444. }
  4445. if ( ch->wavtype == CHAR_OMNI )
  4446. {
  4447. // omni directional sound sources are mono mix, all speakers
  4448. // ie: they only attenuate by distance, not by source direction.
  4449. mono = 1.0;
  4450. bAttenuated = false;
  4451. }
  4452. // calculate gain based on distance, atmospheric attenuation, interposed objects
  4453. // perform compression as gain approaches 1.0
  4454. bOkayToTrace = SND_ChannelOkToTrace( ch );
  4455. // TODO: get mixer values before this and eliminate volume effect dist fall off
  4456. gain = 0.0f;
  4457. FOR_EACH_VALID_SPLITSCREEN_PLAYER( hh )
  4458. {
  4459. // In theory, due to obscured object traces, the two SS views might have different gains... generally doesn't occur, but I did catch it in the debugger a few times
  4460. float usegain = SND_GetGain( hh, &ch->gain[ hh ], ch, listener_origin[ hh ], fplayersound, fmusicsound, looping, dist, bAttenuated, bOkayToTrace );
  4461. if ( usegain > gain )
  4462. {
  4463. gain = usegain;
  4464. }
  4465. }
  4466. if( bIsMenuMusic )
  4467. gain = gain * snd_menumusic_volume.GetFloat();
  4468. #if !defined( _X360 )
  4469. if ( ch->sfx &&
  4470. ch->sfx->pSource &&
  4471. ch->sfx->pSource->GetType() == CAudioSource::AUDIO_SOURCE_VOICE )
  4472. {
  4473. gain = MAX(gain, voice_minimum_gain.GetFloat());
  4474. }
  4475. #endif
  4476. // map gain through global mixer by soundtype
  4477. // int last_mixgroupid;
  4478. // gain *= MXR_GetVolFromMixGroup( ch, &last_mixgroupid );
  4479. gain *= mixValues.volume;
  4480. // if playing a word, get volume scale of word - scale gain
  4481. scale = VOX_GetChanVol(ch);
  4482. gain *= scale;
  4483. // save spatialized volume and mixgroupid for display later
  4484. ch->last_mixgroupid = last_mixgroupid;
  4485. if ( fdopplerwav )
  4486. {
  4487. // we've already picked the best doppler listener in the code above, so only spaitilize for that player
  4488. // don't merge volumes because there is only one set of volumes here.
  4489. VPROF_("SND_Spatialize doppler", 2, VPROF_BUDGETGROUP_OTHER_SOUND, false, BUDGETFLAG_OTHER );
  4490. // fill out channel volumes for both doppler sound source locations
  4491. float volumes[CCHANVOLUMES/2];
  4492. Device_SpatializeChannel( dopplerSlot, volumes, ch->master_vol, source_vec_DL, gain, mono, int(ch->wavtype) );
  4493. // load volumes into channel as crossfade targets
  4494. ChannelSetVolTargets( ch, volumes, IFRONT_LEFT, CCHANVOLUMES/2 );
  4495. // right doppler location
  4496. Device_SpatializeChannel( dopplerSlot, volumes, ch->master_vol, source_vec_DR, gain, mono, int(ch->wavtype) );
  4497. // load volumes into channel as crossfade targets
  4498. ChannelSetVolTargets( ch, volumes, IFRONT_LEFTD, CCHANVOLUMES/2 );
  4499. }
  4500. else
  4501. {
  4502. VPROF( "SND_Spatialize no-doppler" );
  4503. // fill out channel volumes for single sound source location
  4504. float volumes[CCHANVOLUMES/2];
  4505. {
  4506. float build_volumes[ MAX_SPLITSCREEN_CLIENTS ][CCHANVOLUMES/2] = { 0 };
  4507. FOR_EACH_VALID_SPLITSCREEN_PLAYER( hh )
  4508. {
  4509. Device_SpatializeChannel( hh, build_volumes[ hh ], ch->master_vol, source_vec[ hh ], gain, mono, int(ch->wavtype) );
  4510. }
  4511. SND_MergeVolumes( build_volumes, volumes );
  4512. }
  4513. // Special case for stereo sounds originating from player in surround mode
  4514. // and special case for music: remap volumes directly to channels.
  4515. RemapPlayerOrMusicVols( ch, volumes, fplayersound, fmusicsound, mono );
  4516. // in dirstereo we perform a 'reflection' for the other channel to fill space
  4517. if ( ch->wavtype == CHAR_DIRSTEREO )
  4518. {
  4519. float volumeOpposite[CCHANVOLUMES/2];
  4520. // currently center is unused
  4521. volumeOpposite[IFRONT_CENTER] = 0;
  4522. if ( g_AudioDevice->IsSurround() )
  4523. {
  4524. volumeOpposite[IFRONT_LEFT] = volumes[IREAR_RIGHT];
  4525. volumeOpposite[IFRONT_RIGHT] = volumes[IREAR_LEFT];
  4526. volumeOpposite[IREAR_LEFT] = volumes[IFRONT_RIGHT];
  4527. volumeOpposite[IREAR_RIGHT] = volumes[IFRONT_LEFT];
  4528. }
  4529. else
  4530. {
  4531. volumeOpposite[IFRONT_LEFT] = volumes[IFRONT_RIGHT];
  4532. volumeOpposite[IFRONT_RIGHT] = volumes[IFRONT_LEFT];
  4533. volumeOpposite[IREAR_LEFT] = 0;
  4534. volumeOpposite[IREAR_RIGHT] = 0;
  4535. }
  4536. // clamp to 3 to fool the volume clippers so we don't skip mixing partial channels (lower level mix code doesn't distinguish this yet)
  4537. for ( int i = 0; i < IFRONT_LEFTD; i++ )
  4538. {
  4539. int nMax = MAX(volumes[i], volumeOpposite[i]);
  4540. if ( nMax )
  4541. {
  4542. volumes[i] = MAX(volumes[i],3);
  4543. volumeOpposite[i] = MAX(volumeOpposite[i],3);
  4544. }
  4545. }
  4546. ChannelSetVolTargets( ch, volumeOpposite, IFRONT_LEFTD, CCHANVOLUMES/2 );
  4547. }
  4548. // load volumes into channel as crossfade volume targets
  4549. ChannelSetVolTargets( ch, volumes, IFRONT_LEFT, CCHANVOLUMES/2 );
  4550. }
  4551. // prevent left/right/front/rear/center volumes from changing too quickly & producing pops
  4552. ChannelUpdateVolXfade( ch );
  4553. // end of first time spatializing sound
  4554. if ( SND_IsInGame() || toolframework->InToolMode() )
  4555. {
  4556. ch->flags.bfirstpass = false;
  4557. }
  4558. // calculate total volume solely for display and ducking later
  4559. ch->last_vol = gain * (ch->master_vol/255.0);
  4560. // restore dist_mult
  4561. ch->dist_mult = saveChannelDistMult;
  4562. return;
  4563. ClearAllVolumes:
  4564. // Clear all volumes and return.
  4565. // This shuts the sound off permanently.
  4566. ChannelClearVolumes( ch );
  4567. // end of first time spatializing sound
  4568. ch->flags.bfirstpass = false;
  4569. // restore dist_mult
  4570. ch->dist_mult = saveChannelDistMult;
  4571. }
  4572. ConVar snd_defer_trace("snd_defer_trace","1");
  4573. void SND_SpatializeFirstFrameNoTrace( channel_t *pChannel)
  4574. {
  4575. // Don't do this in tools mode since if we are scrubbing time, all of the sounds will come it at a low volume
  4576. if ( snd_defer_trace.GetBool() &&
  4577. !toolframework->InToolMode() )
  4578. {
  4579. // set up tracing state to be non-obstructed
  4580. pChannel->flags.bfirstpass = false;
  4581. pChannel->flags.bTraced = true;
  4582. for ( int i = 0; i < MAX_SPLITSCREEN_CLIENTS; ++i )
  4583. {
  4584. pChannel->gain[ i ].ob_gain = 1.0;
  4585. pChannel->gain[ i ].ob_gain_inc = 1.0;
  4586. pChannel->gain[ i ].ob_gain_target = 1.0;
  4587. }
  4588. // now spatialize without tracing
  4589. SND_Spatialize(pChannel);
  4590. // now reset tracing state to firstpass so the trace gets done on next spatialize
  4591. for ( int i = 0; i < MAX_SPLITSCREEN_CLIENTS; ++i )
  4592. {
  4593. pChannel->gain[ i ].ob_gain = 0.0;
  4594. pChannel->gain[ i ].ob_gain_inc = 0.0;
  4595. pChannel->gain[ i ].ob_gain_target = 0.0;
  4596. }
  4597. pChannel->flags.bfirstpass = true;
  4598. pChannel->flags.bTraced = false;
  4599. }
  4600. else
  4601. {
  4602. for ( int i = 0; i < MAX_SPLITSCREEN_CLIENTS; ++i )
  4603. {
  4604. pChannel->gain[ i ].ob_gain = 0.0;
  4605. pChannel->gain[ i ].ob_gain_inc = 0.0;
  4606. pChannel->gain[ i ].ob_gain_target = 0.0;
  4607. }
  4608. pChannel->flags.bfirstpass = true;
  4609. pChannel->flags.bTraced = false;
  4610. SND_Spatialize(pChannel);
  4611. }
  4612. }
  4613. void PrintSoundFileName( const char *pText1, CSfxTable *pSfx, const char * pText2 = NULL )
  4614. {
  4615. char nameBuf[MAX_PATH];
  4616. char const *pfn = "(Unknown)";
  4617. if ( pSfx != NULL )
  4618. {
  4619. pfn = pSfx->GetFileName( nameBuf, sizeof(nameBuf) );
  4620. if ( pfn == NULL )
  4621. {
  4622. pfn = "(null)";
  4623. }
  4624. }
  4625. if ( pText2 == NULL )
  4626. {
  4627. pText2 = "";
  4628. }
  4629. Warning( "[Sound] %s(\"%s\") called. %s\n", pText1, pfn, pText2 );
  4630. }
  4631. void PrintSoundFileName( const char *pText1, const char *pFileName, CSfxTable *pSfx, const char * pText2 = NULL )
  4632. {
  4633. if ( pText2 == NULL )
  4634. {
  4635. pText2 = "";
  4636. }
  4637. Warning( "[Sound] %s(\"%s\") called. %s\n", pText1, pFileName, pText2 );
  4638. }
  4639. void PrintChannel( const char *pText1, const char *pFileName, channel_t * pChannel, const char *pText2 = NULL )
  4640. {
  4641. int nIndex = pChannel - &channels[ 0 ];
  4642. Assert( ( nIndex >= 0 ) && ( nIndex < MAX_CHANNELS ) );
  4643. Msg( "Channel - Index: %d - Guid: %d.\n", nIndex, pChannel->guid );
  4644. PrintSoundFileName( pText1, pFileName, pChannel->sfx, pText2 );
  4645. }
  4646. void PrintChannel( const char *pText1, channel_t * pChannel, const char *pText2 = NULL )
  4647. {
  4648. int nIndex = pChannel - &channels[ 0 ];
  4649. Assert( ( nIndex >= 0 ) && ( nIndex < MAX_CHANNELS ) );
  4650. Msg( "Channel - Index: %d - Guid: %d.\n", nIndex, pChannel->guid );
  4651. PrintSoundFileName( pText1, pChannel->sfx, pText2 );
  4652. }
  4653. void PrintChannelInfo( channel_t * pChannel )
  4654. {
  4655. int nIndex = pChannel - &channels[ 0 ];
  4656. Assert( ( nIndex >= 0 ) && ( nIndex < MAX_CHANNELS ) );
  4657. unsigned int sampleCount = RemainingSamples( pChannel );
  4658. float timeleft = (float)sampleCount / (float)pChannel->sfx->pSource->SampleRate();
  4659. bool bLooping = pChannel->sfx->pSource->IsLooped();
  4660. char nameBuf[MAX_PATH];
  4661. Msg( "index(%03d) guid(% 4d) l(% 3d) c(% 3d) r(% 3d) rl(% 3d) rr(% 3d) vol(% 3d) ent(% 3d) pos(% 6.2f % 6.2f % 6.2f) timeleft(% 2.2f) pitch(% 2.2f) looped(%d) %s\n",
  4662. nIndex,
  4663. pChannel->guid,
  4664. (int)pChannel->fvolume[IFRONT_LEFT],
  4665. (int)pChannel->fvolume[IFRONT_CENTER],
  4666. (int)pChannel->fvolume[IFRONT_RIGHT],
  4667. (int)pChannel->fvolume[IREAR_LEFT],
  4668. (int)pChannel->fvolume[IREAR_RIGHT],
  4669. pChannel->master_vol,
  4670. pChannel->soundsource,
  4671. pChannel->origin[0],
  4672. pChannel->origin[1],
  4673. pChannel->origin[2],
  4674. timeleft,
  4675. pChannel->pitch,
  4676. bLooping,
  4677. pChannel->sfx->getname(nameBuf, sizeof(nameBuf)));
  4678. }
  4679. // Stops a channel.
  4680. // Returns true if the stop is delayed, false if it has been applied within the function.
  4681. enum StopChannelResult
  4682. {
  4683. SCR_Done,
  4684. SCR_Delayed,
  4685. //SCR_Failed, // Not used for the moment
  4686. };
  4687. StopChannelResult S_StopChannelUnlocked( channel_t *pChannel )
  4688. {
  4689. if ( snd_report_stop_sound.GetBool() )
  4690. {
  4691. PrintSoundFileName( "S_StopChannelUnlocked", pChannel->sfx, "Stopping sound." );
  4692. }
  4693. if( pChannel->m_pStackList )
  4694. {
  4695. pChannel->m_pStackList->StopStacks( SOS_STOP_NORM );
  4696. return SCR_Delayed;
  4697. }
  4698. else
  4699. {
  4700. S_FreeChannel( pChannel );
  4701. return SCR_Done;
  4702. }
  4703. }
  4704. void S_StopChannel( channel_t *pChannel )
  4705. {
  4706. THREAD_LOCK_SOUND();
  4707. S_StopChannelUnlocked( pChannel );
  4708. }
  4709. // search through all channels for a channel that matches this
  4710. // soundsource, entchannel and sfx, and perform alteration on channel
  4711. // as indicated by 'flags' parameter. If shut down request and
  4712. // sfx contains a sentence name, shut off the sentence.
  4713. // returns TRUE if sound was altered,
  4714. // returns FALSE if sound was not found (sound is not playing)
  4715. int S_AlterChannel( StartSoundParams_t &pParams )
  4716. {
  4717. THREAD_LOCK_SOUND();
  4718. int soundsource = pParams.soundsource;
  4719. int entchannel = pParams.entchannel;
  4720. CSfxTable *sfx = pParams.pSfx;
  4721. int pitch = pParams.pitch;
  4722. int flags = pParams.flags;
  4723. int vol = clamp( (int)( pParams.fvol * 255.0f ), 0, 255 );
  4724. int ch_idx;
  4725. char nameBuf[MAX_PATH];
  4726. if ( TestSoundChar(sfx->getname(nameBuf, sizeof(nameBuf)), CHAR_SENTENCE) )
  4727. {
  4728. // This is a sentence name.
  4729. // For sentences: assume that the entity is only playing one sentence
  4730. // at a time, so we can just shut off
  4731. // any channel that has ch->isentence >= 0 and matches the
  4732. // soundsource.
  4733. CChannelList list;
  4734. g_ActiveChannels.GetActiveChannels( list );
  4735. for ( int i = 0; i < list.Count(); i++ )
  4736. {
  4737. ch_idx = list.GetChannelIndex(i);
  4738. if (channels[ch_idx].soundsource == soundsource
  4739. && channels[ch_idx].entchannel == entchannel
  4740. && channels[ch_idx].sfx != NULL )
  4741. {
  4742. if (flags & SND_CHANGE_PITCH)
  4743. {
  4744. channels[ch_idx].basePitch = pitch;
  4745. }
  4746. if (flags & SND_CHANGE_VOL)
  4747. {
  4748. channels[ch_idx].master_vol = vol;
  4749. }
  4750. if ( flags & SND_STOP )
  4751. {
  4752. S_StopChannelUnlocked( &channels[ch_idx] );
  4753. }
  4754. return TRUE;
  4755. }
  4756. }
  4757. // channel not found
  4758. if ( snd_report_verbose_error.GetBool() )
  4759. {
  4760. Msg( "%s(%d): Channel not found for sound '%s'.\n", __FILE__, __LINE__, nameBuf );
  4761. }
  4762. return FALSE;
  4763. }
  4764. // regular sound or streaming sound
  4765. CChannelList list;
  4766. g_ActiveChannels.GetActiveChannels( list );
  4767. bool bSuccess = false;
  4768. //
  4769. // Because operators can now "fade out" ie: stopping not stopped" we can have the same
  4770. // sound entry on the same entity in the state of "stopping" so we must dismiss these.
  4771. // we will stop the channel that matches and has elapsed the most time
  4772. // THIS IS TEMPORARY AND SHOULD BE MOVED TO AN OPERATOR DEFINABLE ACTION AND/OR ALWAYS BE GUID BASED
  4773. //
  4774. // Volume and pitch are similarly ignoring "stopping" channels as there are currently
  4775. // no systems in place that "stop" a channel then change it's volume or pitch (through traditional methods)
  4776. // This definitely needs to be addressed.
  4777. ///
  4778. // separate path for script handles
  4779. // NOTE: SND_IGNORE_NAME uses old system regardless
  4780. if( pParams.m_bIsScriptHandle && ( flags & SND_IGNORE_NAME ) == 0 )
  4781. {
  4782. float flMaxElapsed = -1.0;
  4783. int nMaxElapseedIndex = -1;
  4784. // find oldest matching, non-stopping entry
  4785. for ( int i = 0; i < list.Count(); i++ )
  4786. {
  4787. ch_idx = list.GetChannelIndex(i);
  4788. // current matching criteria
  4789. if( channels[ch_idx].soundsource == soundsource &&
  4790. channels[ch_idx].entchannel == entchannel &&
  4791. channels[ch_idx].m_nSoundScriptHash == pParams.m_nSoundScriptHash )
  4792. {
  4793. if( ( &channels[ch_idx] )->m_pStackList &&
  4794. !( ( ( &channels[ch_idx] )->m_pStackList)->IsStopping() ) )
  4795. {
  4796. // acquire max elapsed, not-stopping channel
  4797. float flElapsed = S_GetElapsedTimeByGuid( channels[ch_idx].guid );
  4798. if( flElapsed > flMaxElapsed )
  4799. {
  4800. flMaxElapsed = flElapsed;
  4801. nMaxElapseedIndex = ch_idx;
  4802. }
  4803. }
  4804. }
  4805. }
  4806. // stopping oldest matching entry
  4807. if( nMaxElapseedIndex > -1 )
  4808. {
  4809. channel_t *pChannel = &channels[ nMaxElapseedIndex ];
  4810. if ( flags & SND_STOP )
  4811. {
  4812. S_StopChannelUnlocked( pChannel );
  4813. }
  4814. if ( flags & SND_CHANGE_PITCH )
  4815. {
  4816. pChannel->basePitch = pitch;
  4817. }
  4818. if ( flags & SND_CHANGE_VOL )
  4819. {
  4820. pChannel->master_vol = vol;
  4821. }
  4822. return true;
  4823. }
  4824. }
  4825. else // almost the same as the original system
  4826. {
  4827. for ( int i = 0; i < list.Count(); i++ )
  4828. {
  4829. ch_idx = list.GetChannelIndex(i);
  4830. if ( (channels[ch_idx].soundsource == soundsource || (channels[ch_idx].flags.m_bInEyeSound && pParams.m_bInEyeSound)) &&
  4831. ( ( flags & SND_IGNORE_NAME ) ||
  4832. (channels[ch_idx].entchannel == entchannel && channels[ch_idx].sfx == sfx )))
  4833. {
  4834. if ( flags & SND_CHANGE_PITCH )
  4835. {
  4836. channels[ch_idx].basePitch = pitch;
  4837. }
  4838. if ( flags & SND_CHANGE_VOL )
  4839. {
  4840. channels[ch_idx].master_vol = vol;
  4841. }
  4842. if ( flags & SND_STOP )
  4843. {
  4844. S_StopChannelUnlocked( &channels[ch_idx] );
  4845. }
  4846. if ( ( flags & SND_IGNORE_NAME ) == 0 )
  4847. return TRUE;
  4848. else
  4849. bSuccess = true;
  4850. }
  4851. }
  4852. }
  4853. return ( bSuccess ) ? ( TRUE ) : ( FALSE );
  4854. }
  4855. int S_AlterChannelByGuid( StartSoundParams_t &pParams )
  4856. {
  4857. THREAD_LOCK_SOUND();
  4858. int guid = pParams.m_nQueuedGUID;
  4859. int pitch = pParams.pitch;
  4860. int flags = pParams.flags;
  4861. int vol = clamp( (int)( pParams.fvol * 255.0f ), 0, 255 );
  4862. channel_t *pChannel = S_FindChannelByGuid(guid);
  4863. if ( pChannel )
  4864. {
  4865. if (flags & SND_CHANGE_PITCH)
  4866. {
  4867. pChannel->basePitch = pitch;
  4868. }
  4869. if (flags & SND_CHANGE_VOL)
  4870. {
  4871. pChannel->master_vol = vol;
  4872. }
  4873. if (flags & SND_STOP)
  4874. {
  4875. S_StopChannelUnlocked( pChannel );
  4876. }
  4877. return true;
  4878. }
  4879. if ( snd_report_verbose_error.GetBool() )
  4880. {
  4881. Msg( "%s(%d): Channel not found for sound guid '%d'.\n", __FILE__, __LINE__, guid );
  4882. }
  4883. return false;
  4884. }
  4885. static void S_IsDopplerWave( char const *pchSoundName, int soundsource, bool &bPlayerSound, bool &bDopplerWave )
  4886. {
  4887. bDopplerWave = false;
  4888. bPlayerSound = ( IsSoundSourceViewEntity( soundsource ) && !toolframework->InToolMode() );
  4889. if ( !bPlayerSound )
  4890. {
  4891. return;
  4892. }
  4893. bDopplerWave = TestSoundChar( pchSoundName, CHAR_DOPPLER );
  4894. }
  4895. // set channel flags during initialization based on
  4896. // source name
  4897. void S_SetChannelWavtype( channel_t *target_chan, const char *pSndName )
  4898. {
  4899. // if 1st or 2nd character of name is CHAR_DRYMIX, sound should be mixed dry with no dsp (ie: music)
  4900. target_chan->flags.bdry = TestSoundChar( pSndName, CHAR_DRYMIX );
  4901. target_chan->flags.bfast_pitch = TestSoundChar( pSndName, CHAR_FAST_PITCH );
  4902. // get sound spatialization encoding
  4903. target_chan->wavtype = 0;
  4904. if ( TestSoundChar( pSndName, CHAR_DOPPLER ) )
  4905. target_chan->wavtype = CHAR_DOPPLER;
  4906. if ( TestSoundChar( pSndName, CHAR_DIRECTIONAL ) )
  4907. target_chan->wavtype = CHAR_DIRECTIONAL;
  4908. if ( TestSoundChar( pSndName, CHAR_DISTVARIANT ) )
  4909. target_chan->wavtype = CHAR_DISTVARIANT;
  4910. if ( TestSoundChar( pSndName, CHAR_OMNI ) )
  4911. target_chan->wavtype = CHAR_OMNI;
  4912. if ( TestSoundChar( pSndName, CHAR_SPATIALSTEREO ) )
  4913. target_chan->wavtype = CHAR_SPATIALSTEREO;
  4914. if ( TestSoundChar( pSndName, CHAR_DIRSTEREO ) )
  4915. target_chan->wavtype = CHAR_DIRSTEREO;
  4916. if (snd_use_hrtf.GetBool() && TestSoundChar(pSndName, CHAR_HRTF) && (!IsSoundSourceViewEntity(target_chan->soundsource) || target_chan->hrtf.debug_lock_position))
  4917. {
  4918. target_chan->wavtype = CHAR_HRTF;
  4919. target_chan->hrtf.lerp = 1.0; //snd_hrtf_ratio.GetFloat();
  4920. }
  4921. if ( TestSoundChar( pSndName, CHAR_RADIO ) )
  4922. target_chan->wavtype = CHAR_RADIO;
  4923. }
  4924. // Sets bstereowav flag in channel if source is true stereo wav
  4925. // sets default wavtype for stereo wavs to CHAR_DISTVARIANT -
  4926. // ie: sound varies with distance (left is close, right is far)
  4927. // Must be called after S_SetChannelWavtype
  4928. void S_SetChannelStereo( channel_t *target_chan, CAudioSource *pSource )
  4929. {
  4930. if ( !pSource )
  4931. {
  4932. target_chan->flags.bstereowav = false;
  4933. return;
  4934. }
  4935. // returns true only if source data is a stereo wav file.
  4936. // ie: mp3, voice, sentence are all excluded.
  4937. target_chan->flags.bstereowav = pSource->IsStereoWav();
  4938. // Default stereo wavtype:
  4939. // just player standard stereo wavs on player entity - no override.
  4940. if ( IsSoundSourceViewEntity( target_chan->soundsource ) )
  4941. return;
  4942. // default wavtype for stereo wavs is OMNI - except for drymix or sounds with 0 attenuation
  4943. if ( target_chan->flags.bstereowav && !target_chan->wavtype && !target_chan->flags.bdry && target_chan->dist_mult )
  4944. // target_chan->wavtype = CHAR_DISTVARIANT;
  4945. target_chan->wavtype = CHAR_OMNI;
  4946. }
  4947. // =======================================================================
  4948. // Channel volume management routines:
  4949. // channel volumes crossfade between values over time
  4950. // to prevent pops due to rapid spatialization changes
  4951. // =======================================================================
  4952. // return true if all volumes and target volumes for channel are less/equal to 'vol'
  4953. bool BChannelLowVolume( channel_t *pch, float vol_min )
  4954. {
  4955. float max = -1;
  4956. float max_target = -1;
  4957. float vol;
  4958. float vol_target;
  4959. for (int i = 0; i < CCHANVOLUMES; i++)
  4960. {
  4961. vol = pch->fvolume[i];
  4962. vol_target = pch->fvolume_target[i];
  4963. if (vol > max)
  4964. max = vol;
  4965. if (vol_target > max_target)
  4966. max_target = vol_target;
  4967. }
  4968. return (max <= vol_min && max_target <= vol_min);
  4969. }
  4970. // Get the loudest actual volume for a channel (not counting targets).
  4971. float ChannelLoudestCurVolume( const channel_t * RESTRICT pch )
  4972. {
  4973. float loudest = pch->fvolume[0];
  4974. for (int i = 1; i < CCHANVOLUMES; i++)
  4975. {
  4976. loudest = fpmax(loudest, pch->fvolume[i]);
  4977. }
  4978. return loudest;
  4979. }
  4980. // clear all volumes, targets, crossfade increments
  4981. void ChannelClearVolumes( channel_t *pch )
  4982. {
  4983. for (int i = 0; i < CCHANVOLUMES; i++)
  4984. {
  4985. pch->fvolume[i] = 0.0;
  4986. pch->fvolume_target[i] = 0.0;
  4987. pch->fvolume_inc[i] = 0.0;
  4988. }
  4989. }
  4990. // return current volume as integer
  4991. int ChannelGetVol( channel_t *pch, int ivol )
  4992. {
  4993. Assert(ivol < CCHANVOLUMES);
  4994. return (int)(pch->fvolume[ivol]);
  4995. }
  4996. // return maximum current output volume
  4997. int ChannelGetMaxVol( channel_t *pch )
  4998. {
  4999. float max = 0.0;
  5000. for (int i = 0; i < CCHANVOLUMES; i++)
  5001. {
  5002. if (pch->fvolume[i] > max)
  5003. max = pch->fvolume[i];
  5004. }
  5005. return (int)max;
  5006. }
  5007. // set current volume (clears crossfading - instantaneous value change)
  5008. void ChannelSetVol( channel_t *pch, int ivol, int vol )
  5009. {
  5010. Assert(ivol < CCHANVOLUMES);
  5011. pch->fvolume[ivol] = (float)(iclamp(vol, 0, 255));
  5012. pch->fvolume_target[ivol] = pch->fvolume[ivol];
  5013. pch->fvolume_inc[ivol] = 0.0;
  5014. }
  5015. // copy current channel volumes into target array, starting at ivol, copying cvol entries
  5016. void ChannelCopyVolumes( channel_t *pch, float *pvolume_dest, int ivol_start, int cvol )
  5017. {
  5018. Assert (ivol_start < CCHANVOLUMES);
  5019. Assert (ivol_start + cvol <= CCHANVOLUMES);
  5020. if ( ( ivol_start == 0 ) && ( cvol == CCHANVOLUMES ) )
  5021. {
  5022. // This is the path executed in most cases
  5023. // Unroll by hand so the code can be optimized to reduce LHS a bit (due to float to int conversion)
  5024. // I.e. if the compiler does a proper job, we will only pay for the first LHS
  5025. pvolume_dest[0] = pch->fvolume[0];
  5026. pvolume_dest[1] = pch->fvolume[1];
  5027. pvolume_dest[2] = pch->fvolume[2];
  5028. pvolume_dest[3] = pch->fvolume[3];
  5029. pvolume_dest[4] = pch->fvolume[4];
  5030. pvolume_dest[5] = pch->fvolume[5];
  5031. pvolume_dest[6] = pch->fvolume[6];
  5032. pvolume_dest[7] = pch->fvolume[7];
  5033. pvolume_dest[8] = pch->fvolume[8];
  5034. pvolume_dest[9] = pch->fvolume[9];
  5035. pvolume_dest[10] = pch->fvolume[10];
  5036. pvolume_dest[11] = pch->fvolume[11];
  5037. }
  5038. else
  5039. {
  5040. for (int i = 0; i < cvol; i++)
  5041. pvolume_dest[i] = pch->fvolume[i + ivol_start];
  5042. }
  5043. }
  5044. // volume has hit target, shut off crossfading increment
  5045. inline void ChannelStopVolXfade( channel_t *pch, int ivol )
  5046. {
  5047. pch->fvolume[ivol] = pch->fvolume_target[ivol];
  5048. pch->fvolume_inc[ivol] = 0.0;
  5049. }
  5050. // Once the correct parameters are determined, we can bake them in if we want (and if there is a noticeable performance overhead)
  5051. #if 0
  5052. #define VOL_XFADE_TIME 0.070
  5053. #define VOL_INCR_MAX 20.0
  5054. #define VOL_NO_XFADE 5.0
  5055. #else
  5056. ConVar snd_vol_xfade_time( "snd_vol_xfade_time", "0.070", 0, "Channel volume cross-fade time in seconds." );
  5057. ConVar snd_vol_xfade_incr_max( "snd_vol_xfade_incr_max", "20.0", 0, "Never change volume by more than +/-N units per frame during cross-fade." );
  5058. ConVar snd_vol_no_xfade( "snd_vol_no_xfade", "5.0", 0, "If current and target volumes are close, don't cross-fade." );
  5059. ConVar snd_vol_xfade_speed_multiplier_for_doppler( "snd_vol_xfade_speed_multiplier_for_doppler", "1", 0, "Doppler effect is extremely sensible to volume variation. To reduce the pops, the cross-fade has to be very slow." );
  5060. #define VOL_XFADE_TIME snd_vol_xfade_time.GetFloat()
  5061. #define VOL_INCR_MAX snd_vol_xfade_incr_max.GetFloat()
  5062. #define VOL_NO_XFADE snd_vol_no_xfade.GetFloat()
  5063. #endif
  5064. // set volume target and volume increment (for crossfade) for channel & speaker
  5065. void ChannelSetVolTarget( channel_t *pch, int ivol, float volume_target )
  5066. {
  5067. float frametime = g_pSoundServices->GetHostFrametime();
  5068. float speed;
  5069. float vol_target = (float)(clamp(volume_target, 0, 255));
  5070. float vol_current;
  5071. Assert(ivol < CCHANVOLUMES);
  5072. // set volume target
  5073. pch->fvolume_target[ivol] = vol_target;
  5074. // current volume
  5075. vol_current = pch->fvolume[ivol];
  5076. float fMultiplier = 1.0f;
  5077. if ( ( pch->wavtype == CHAR_DIRSTEREO ) || ( pch->wavtype == CHAR_DOPPLER ) )
  5078. {
  5079. // CHAR_DIRSTEREO uses Doppler under the hood. Reduce the speed for these.
  5080. fMultiplier = snd_vol_xfade_speed_multiplier_for_doppler.GetFloat();
  5081. }
  5082. // if first time spatializing, set target = volume with no crossfade
  5083. // if current & target volumes are close - don't bother crossfading
  5084. if ( pch->flags.bfirstpass || (fabs(vol_target - vol_current) < VOL_NO_XFADE * fMultiplier))
  5085. {
  5086. // set current volume = target, no increment
  5087. ChannelStopVolXfade( pch, ivol);
  5088. return;
  5089. }
  5090. // get crossfade increment 'speed' (volume change per frame)
  5091. speed = ( frametime / VOL_XFADE_TIME ) * (vol_target - vol_current);
  5092. // make sure we never increment by more than +/- VOL_INCR_MAX volume units per frame
  5093. speed = clamp(speed, -VOL_INCR_MAX, VOL_INCR_MAX) * fMultiplier;
  5094. pch->fvolume_inc[ivol] = speed;
  5095. }
  5096. // set volume targets, using array pvolume as source volumes.
  5097. // set into channel volumes starting at ivol_offset index
  5098. // set cvol volumes
  5099. void ChannelSetVolTargets( channel_t *pch, float *pvolumes, int ivol_offset, int cvol )
  5100. {
  5101. float volume_target;
  5102. Assert(ivol_offset + cvol <= CCHANVOLUMES);
  5103. for (int i = 0; i < cvol; i++)
  5104. {
  5105. volume_target = pvolumes[i];
  5106. if (volume_target < 2.0f)
  5107. {
  5108. volume_target -= 2.0f - volume_target;
  5109. }
  5110. volume_target = clamp( volume_target, 0, 255 );
  5111. ChannelSetVolTarget( pch, ivol_offset + i, volume_target );
  5112. }
  5113. }
  5114. // Call once per frame, per channel:
  5115. // update all volume crossfades, from fvolume -> fvolume_target
  5116. // if current volume reaches target, set increment to 0
  5117. void ChannelUpdateVolXfade( channel_t *pch )
  5118. {
  5119. float fincr;
  5120. for (int i = 0; i < CCHANVOLUMES; i++)
  5121. {
  5122. fincr = pch->fvolume_inc[i];
  5123. if (fincr != 0.0)
  5124. {
  5125. pch->fvolume[i] += fincr;
  5126. // test for hit target
  5127. if (fincr > 0.0)
  5128. {
  5129. if (pch->fvolume[i] >= pch->fvolume_target[i])
  5130. ChannelStopVolXfade( pch, i );
  5131. }
  5132. else
  5133. {
  5134. if (pch->fvolume[i] <= pch->fvolume_target[i])
  5135. ChannelStopVolXfade( pch, i );
  5136. }
  5137. }
  5138. }
  5139. }
  5140. void DumpFilePaths(const char *filename)
  5141. {
  5142. // Don't Write to internal storage on the 360
  5143. if ( IsGameConsole() )
  5144. return;
  5145. // Generate a new .cfg file.
  5146. char szFileName[MAX_PATH];
  5147. CUtlBuffer configBuff( 0, 0, CUtlBuffer::TEXT_BUFFER);
  5148. char computername[ 64 ];
  5149. Q_memset( computername, 0, sizeof( computername ) );
  5150. #if defined ( _WIN32 )
  5151. DWORD length = sizeof( computername ) - 1;
  5152. if ( !GetComputerName( computername, &length ) )
  5153. {
  5154. Q_strncpy( computername, "???", sizeof( computername ) );
  5155. }
  5156. #elif defined( _PS3 )
  5157. Q_strncpy( computername, "PS3", sizeof( computername ) );
  5158. #else
  5159. if ( gethostname( computername, sizeof(computername) ) == -1 )
  5160. {
  5161. Q_strncpy( computername, "Linux????", sizeof( computername ) );
  5162. }
  5163. computername[sizeof(computername)-1] = '\0';
  5164. #endif
  5165. // todo: morasky, ugly, fix this and make generic!
  5166. // Q_snprintf( szFileName, sizeof(szFileName), "\\\\fileserver\\User\\portal2\\soundlogs\\%s_%s", computername, filename );
  5167. Q_snprintf( szFileName, sizeof(szFileName), "%s\\%s_%s", snd_store_filepaths.GetString(), computername, filename );
  5168. // g_pFileSystem->CreateDirHierarchy( "\\fileserver\\User\\portal2\\soundlogs\\", NULL );
  5169. g_pFileSystem->CreateDirHierarchy( snd_store_filepaths.GetString(), NULL );
  5170. if ( g_pFileSystem->FileExists( szFileName, NULL ) && !g_pFileSystem->IsFileWritable( szFileName, NULL ) )
  5171. {
  5172. ConMsg( "Soundlog file %s is read-only!!\n", szFileName );
  5173. return;
  5174. }
  5175. for (int i = 0; i < g_StoreFilePaths.Count(); i++)
  5176. {
  5177. configBuff.Printf( "%s %i, ", g_StoreFilePaths.GetElementName( i ), g_StoreFilePaths[i] );
  5178. }
  5179. if ( !configBuff.TellMaxPut() )
  5180. {
  5181. // nothing to write
  5182. return;
  5183. }
  5184. // make a persistent copy that async will use and free
  5185. char *tempBlock = new char[configBuff.TellMaxPut()];
  5186. Q_memcpy( tempBlock, configBuff.Base(), configBuff.TellMaxPut() );
  5187. // async write the buffer, and then free it
  5188. g_pFileSystem->AsyncWrite( szFileName, tempBlock, configBuff.TellMaxPut(), true );
  5189. ConMsg( "snd_dump_filepaths: Wrote %s\n", szFileName );
  5190. }
  5191. void S_DumpFilePaths( const CCommand &args )
  5192. {
  5193. if ( args.ArgC() != 2)
  5194. {
  5195. // if dsp_parms with no arguments, reload entire preset file
  5196. DevMsg("Error: Filepath arg required\n");
  5197. return;
  5198. }
  5199. const char *filename = args[1];
  5200. Assert( filename && filename [ 0 ] );
  5201. DumpFilePaths(filename);
  5202. }
  5203. static ConCommand dump_file_paths( "snd_dump_filepaths", S_DumpFilePaths );
  5204. static ConVar snd_filter( "snd_filter", "", FCVAR_CHEAT );
  5205. // This function is capable of starting both static and dynamic sounds
  5206. static int S_StartSound_Immediate( StartSoundParams_t& params )
  5207. {
  5208. if ( !g_AudioDevice || !g_AudioDevice->IsActive() )
  5209. return 0;
  5210. // handle queued updates
  5211. if ( ( params.m_nQueuedGUID > 0 ) && ( params.flags & ( SND_STOP | SND_CHANGE_VOL | SND_CHANGE_PITCH ) ) )
  5212. {
  5213. if ( S_AlterChannelByGuid( params ) )
  5214. return 0;
  5215. }
  5216. if ( !params.pSfx )
  5217. {
  5218. if ( snd_report_verbose_error.GetBool() )
  5219. {
  5220. Msg( "%s(%d): params.pSfx is NULL.\n", __FILE__, __LINE__ );
  5221. }
  5222. return 0;
  5223. }
  5224. char sndname[ MAX_PATH ];
  5225. params.pSfx->getname(sndname, sizeof(sndname));
  5226. if ( g_bPreventSound )
  5227. {
  5228. // We must respect the prevention, this is likely the loading state where
  5229. // the mixer cannot be allowed to operate.
  5230. DevWarning( "Starting sound '%s' while system disabled.\n", sndname );
  5231. return 0;
  5232. }
  5233. #ifndef NO_TOOLFRAMEWORK
  5234. if ( toolframework->InToolMode() )
  5235. {
  5236. // If the active tool does not want game sounds to be played, return if the sound did not originate from a tool.
  5237. if ( !toolframework->ShouldGamePlaySounds() && !params.bToolSound )
  5238. return 0;
  5239. }
  5240. #endif
  5241. if ( snd_filter.GetString()[ 0 ] && !Q_stristr( sndname, snd_filter.GetString() ) )
  5242. {
  5243. return 0;
  5244. }
  5245. // storing file paths for complete list of sounds used in game
  5246. if ( IsPC() && snd_store_filepaths.GetString()[ 0 ] )
  5247. {
  5248. if( CommandLine()->FindParm("-playtest") != 0 &&
  5249. !( params.flags & ( SND_STOP | SND_CHANGE_VOL | SND_CHANGE_PITCH ) ) )
  5250. {
  5251. int i = g_StoreFilePaths.Find( sndname );
  5252. if ( !g_StoreFilePaths.IsValidIndex( i ) )
  5253. {
  5254. g_StoreFilePaths.Insert( sndname, 1 );
  5255. }
  5256. else
  5257. {
  5258. g_StoreFilePaths[i] = g_StoreFilePaths[i] + 1;
  5259. }
  5260. }
  5261. }
  5262. #if defined( _X360 )
  5263. if ( !engineClient->IsConnected() && g_pXboxInstaller->IsInstallEnabled() && !g_pXboxInstaller->IsFullyInstalled() )
  5264. {
  5265. // prevent ANY audio streaming during main menu while the install might go active or is occurring
  5266. // static memory sounds are fine
  5267. if ( params.pSfx->pSource && params.pSfx->pSource->IsStreaming() )
  5268. {
  5269. DevWarning( "Ignoring streaming sound '%s' while installer may become active.\n", sndname );
  5270. return 0;
  5271. }
  5272. }
  5273. #endif
  5274. // Override the entchannel to CHAN_STREAM if this is a non-voice stream sound.
  5275. if ( !params.staticsound &&
  5276. TestSoundChar( sndname, CHAR_STREAM ) && params.entchannel != CHAN_VOICE )
  5277. {
  5278. params.entchannel = CHAN_STREAM;
  5279. }
  5280. int vol = clamp( (int)( params.fvol * 255.0f ), 0, 255 );
  5281. int nSndShowStart = snd_showstart.GetInt();
  5282. if ( ( params.flags & SND_STOP ) && ( nSndShowStart > 0 ) )
  5283. {
  5284. DevMsg( "S_StartSound: %s Stopped.\n", sndname );
  5285. }
  5286. THREAD_LOCK_SOUND();
  5287. if ( params.flags & ( SND_STOP | SND_CHANGE_VOL | SND_CHANGE_PITCH ) )
  5288. {
  5289. if ( S_AlterChannel( params ) || ( params.flags & SND_STOP ) )
  5290. return 0;
  5291. }
  5292. if ( params.pitch == 0 )
  5293. {
  5294. DevMsg( "Warning: S_StartSound (%s) Ignored, called with pitch 0\n", sndname );
  5295. return 0;
  5296. }
  5297. // First, make sure the sound source entity is even in the PVS.
  5298. float flSoundRadius = 0.0f;
  5299. bool looping = false;
  5300. SpatializationInfo_t si;
  5301. si.info.Set(
  5302. params.soundsource,
  5303. params.entchannel,
  5304. params.pSfx ? sndname : "",
  5305. params.origin,
  5306. params.direction,
  5307. vol,
  5308. params.soundlevel,
  5309. looping,
  5310. params.pitch,
  5311. listener_origin[ 0 ],
  5312. params.speakerentity,
  5313. 0 );
  5314. si.type = SpatializationInfo_t::SI_INCREATION;
  5315. Vector vEntOrigin = params.origin;
  5316. si.pOrigin = &vEntOrigin;
  5317. si.pAngles = NULL;
  5318. si.pflRadius = &flSoundRadius;
  5319. CUtlVector< Vector > utlVecMultiOrigins;
  5320. si.m_pUtlVecMultiOrigins = &utlVecMultiOrigins;
  5321. si.m_pUtlVecMultiAngles = NULL;
  5322. // Morasky: why it doesn't spatialize for dynamic? (because is could be thrown out immediatelly?)
  5323. // why it doesn't use an updated position for starting?
  5324. channel_t *ch = NULL;
  5325. if ( params.staticsound || ( params.m_bIsScriptHandle && !snd_sos_allow_dynamic_chantype.GetInt() ) )
  5326. {
  5327. g_pSoundServices->GetSoundSpatialization( params.soundsource, si );
  5328. ch = SND_PickStaticChannel( params.soundsource, params.pSfx );
  5329. if( !ch )
  5330. {
  5331. DevMsg("Error: Sound %s failed to allocate a static channel and will not play\n", sndname );
  5332. }
  5333. }
  5334. else
  5335. {
  5336. // pick a channel to play on
  5337. ch = SND_PickDynamicChannel( params.soundsource, params.entchannel, params.origin, params.pSfx );
  5338. // if( !ch )
  5339. // {
  5340. // DevMsg("Error: Sound %s failed to allocate a dynamic channel and will not play\n", sndname );
  5341. // }
  5342. }
  5343. if ( !ch )
  5344. {
  5345. if ( snd_report_verbose_error.GetBool() )
  5346. {
  5347. Msg( "%s(%d): Could not pick channel for sound '%s'.\n", __FILE__, __LINE__, sndname );
  5348. }
  5349. return 0;
  5350. }
  5351. bool bIsSentence = TestSoundChar( sndname, CHAR_SENTENCE );
  5352. int nGUID = ( params.m_nQueuedGUID > 0 ) ? params.m_nQueuedGUID : SND_GetGUID();
  5353. // clear all channel memory and set guid
  5354. SND_ActivateChannel( ch, nGUID );
  5355. ChannelClearVolumes( ch );
  5356. if ( ( (*snd_find_channel.GetString()) != '\0' ) && ( Q_stristr( sndname, snd_find_channel.GetString() ) != 0 ) )
  5357. {
  5358. // This is a sound we are interested in. Display some useful information.
  5359. PrintChannel( "FoundChannel", sndname, ch, "from ConVar snd_find_channel." );
  5360. }
  5361. // Default save/restore to disabled
  5362. ch->flags.m_bShouldSaveRestore = false;
  5363. ch->hrtf.follow_entity = params.m_bHRTFFollowEntity;
  5364. ch->hrtf.bilinear_filtering = params.m_bHRTFBilinear;
  5365. ch->hrtf.debug_lock_position = params.m_bHRTFLock;
  5366. if (ch->hrtf.debug_lock_position)
  5367. {
  5368. ch->hrtf.vec = params.origin;
  5369. }
  5370. //-----------------------------------------------------------------------------
  5371. // initialize operators for this channel and execute start stack if possible
  5372. //-----------------------------------------------------------------------------
  5373. CSosOperatorStackList *pStackList = NULL;
  5374. if( params.m_bIsScriptHandle )
  5375. {
  5376. stack_data_t stackData;
  5377. stackData.m_pOperatorsKV = params.m_pOperatorsKV;
  5378. stackData.m_nSoundScriptHash = params.m_nSoundScriptHash;
  5379. stackData.m_nGuid = ch->guid;
  5380. stackData.m_flStartTime = g_pSoundServices->GetHostTime() - params.opStackElapsedTime;
  5381. pStackList = S_InitChannelOperators( stackData );
  5382. ch->m_pStackList = pStackList;
  5383. if( pStackList )
  5384. {
  5385. // pStackList->SetChannelGuid( ch->guid );
  5386. // pStackList->SetStartTime( g_pSoundServices->GetHostTime() - params.opStackElapsedTime );
  5387. // pStackList->SetScriptHash( params.m_nSoundScriptHash );
  5388. if( params.opStackElapsedStopTime > 0.0f )
  5389. pStackList->SetStopTime( g_pSoundServices->GetHostTime() - params.opStackElapsedStopTime );
  5390. }
  5391. }
  5392. ch->m_nSoundScriptHash = params.m_nSoundScriptHash;
  5393. ch->userdata = params.userdata;
  5394. ch->initialStreamPosition = params.initialStreamPosition;
  5395. ch->skipInitialSamples = params.skipInitialSamples;
  5396. if ( IsPC() && ch->userdata != 0 )
  5397. {
  5398. g_pSoundServices->GetToolSpatialization( ch->userdata, ch->guid, si );
  5399. }
  5400. #ifdef DEBUG_CHANNELS
  5401. {
  5402. char szTmp[128];
  5403. Q_snprintf( szTmp, sizeof( szTmp ), "Sound %s playing on Dynamic game channel %d\n", sndname, IWavstreamOfCh( ch ) );
  5404. Plat_DebugString(szTmp);
  5405. }
  5406. #endif
  5407. CAudioSource *pSource = NULL;
  5408. ch->flags.isSentence = false;
  5409. ch->sfx = params.pSfx;
  5410. VectorCopy( params.origin, ch->origin );
  5411. VectorCopy( params.direction, ch->direction );
  5412. // never update positions if source entity is 0
  5413. ch->flags.bUpdatePositions = params.bUpdatePositions && ( params.soundsource == 0 ? 0 : 1 );
  5414. ch->master_vol = vol;
  5415. ch->flags.m_bCompatibilityAttenuation = SNDLEVEL_IS_COMPATIBILITY_MODE( params.soundlevel );
  5416. if ( ch->flags.m_bCompatibilityAttenuation )
  5417. {
  5418. // Translate soundlevel from its 'encoded' value to a real soundlevel that we can use in the sound system.
  5419. params.soundlevel = SNDLEVEL_FROM_COMPATIBILITY_MODE( params.soundlevel );
  5420. }
  5421. ch->m_flSoundLevel = params.soundlevel; // currently only used to get mixgroup
  5422. ch->dist_mult = SNDLVL_TO_DIST_MULT( params.soundlevel );
  5423. ch->soundsource = params.soundsource;
  5424. S_SetChannelWavtype( ch, sndname );
  5425. ch->basePitch = params.pitch;
  5426. ch->entchannel = params.entchannel;
  5427. ch->flags.fromserver = params.fromserver;
  5428. ch->speakerentity = params.speakerentity;
  5429. ch->flags.m_bShouldPause = (params.flags & SND_SHOULDPAUSE) ? 1 : 0;
  5430. ch->flags.delayed_start = params.m_bDelayedStart;
  5431. ch->flags.m_bUpdateDelayForChoreo = ( params.flags & SND_UPDATE_DELAY_FOR_CHOREO ) != 0;
  5432. ch->flags.m_bInEyeSound = params.m_bInEyeSound;
  5433. // initialize dsp room mixing params
  5434. ch->dsp_mix_min = -1;
  5435. ch->dsp_mix_max = -1;
  5436. // set the default radius
  5437. ch->radius = flSoundRadius;
  5438. ch->m_nSoundScriptHash = params.m_nSoundScriptHash;
  5439. // If the sound is from a speaker, and it's looping, ignore it.
  5440. ch->flags.bSpeaker = (params.flags & SND_SPEAKER) ? 1 : 0;
  5441. if ( ch->flags.bSpeaker )
  5442. {
  5443. if ( params.pSfx->pSource && params.pSfx->pSource->IsLooped() )
  5444. {
  5445. if ( ( nSndShowStart > 0 &&
  5446. nSndShowStart < 7 &&
  5447. nSndShowStart != 4 )
  5448. || snd_report_verbose_error.GetBool() )
  5449. {
  5450. Msg( "%s(%d): Speaker entity ignored for looping sound '%s'.\n", __FILE__, __LINE__, sndname );
  5451. }
  5452. S_FreeChannel( ch );
  5453. return 0;
  5454. }
  5455. }
  5456. // This should load a mixer object for the sound, too
  5457. if ( bIsSentence )
  5458. {
  5459. // This is a sentence, link words to play in sequence.
  5460. // NOTE: sentence names stored in the cache lookup are pre-pended with a '!'. Sentence names stored in the
  5461. // sentence file do not have a leading '!'.
  5462. VOX_LoadSound( ch, PSkipSoundChars( sndname ) );
  5463. }
  5464. else
  5465. {
  5466. // load regular or stream sound
  5467. SoundError soundError;
  5468. pSource = S_LoadSound( params.pSfx, ch, soundError );
  5469. if ( pSource && !IsValidSampleRate( pSource->SampleRate() ) )
  5470. {
  5471. Warning( "S_StartSound: Invalid sample rate (%d) for sound '%s'.\n", pSource->SampleRate(), sndname );
  5472. }
  5473. if ( !pSource && !params.pSfx->m_bIsLateLoad )
  5474. {
  5475. // Display the text about missing sound only the first time, but other texts every time...
  5476. const char * pText = "";
  5477. switch ( soundError )
  5478. {
  5479. case SE_NO_STREAM_BUFFER:
  5480. pText = "No stream buffers are available.";
  5481. break;
  5482. case SE_NO_SOURCE_SETUP:
  5483. // If there was no source, it is probably because the sound was missing to begin with.
  5484. // Pass through
  5485. case SE_FILE_NOT_FOUND:
  5486. {
  5487. static CUtlRBTree< FileNameHandle_t > s_MissingSounds( 0, 0, DefLessFunc( FileNameHandle_t ) );
  5488. FileNameHandle_t h;
  5489. h = g_pFileSystem->FindOrAddFileName( sndname );
  5490. if ( ( s_MissingSounds.Find( h ) == s_MissingSounds.InvalidIndex() ) || snd_report_verbose_error.GetBool() )
  5491. {
  5492. s_MissingSounds.Insert( h );
  5493. pText = "File is missing from disk/repository.";
  5494. }
  5495. else
  5496. {
  5497. pText = NULL; // Do not display anything if already reported as missing...
  5498. }
  5499. }
  5500. break;
  5501. case SE_CANT_GET_NAME:
  5502. pText = "Can't get name";
  5503. break;
  5504. case SE_SKIPPED:
  5505. pText = "Skipped.";
  5506. break;
  5507. case SE_CANT_CREATE_MIXER:
  5508. pText = "Can't create mixer.";
  5509. break;
  5510. }
  5511. if ( pText != NULL )
  5512. {
  5513. Warning( "[Sound] S_StartSound(): Failed to load sound '%s'. %s\n", sndname, pText );
  5514. }
  5515. }
  5516. ch->flags.isSentence = false;
  5517. //Dry mix voice chat.
  5518. if ( pSource && pSource->GetType() == CAudioSource::AUDIO_SOURCE_VOICE )
  5519. {
  5520. ch->flags.bdry = true;
  5521. }
  5522. }
  5523. if ( !ch->pMixer )
  5524. {
  5525. // couldn't load sounds' data, or sentence has 0 words (not an error)
  5526. if ( snd_report_verbose_error.GetBool() )
  5527. {
  5528. Msg( "%s(%d): Channel does not have a mixer for sound '%s'.\n", __FILE__, __LINE__, sndname );
  5529. }
  5530. S_FreeChannel( ch );
  5531. return 0;
  5532. }
  5533. S_SetChannelStereo( ch, pSource );
  5534. if (nSndShowStart == 5)
  5535. {
  5536. // display gain once only
  5537. snd_showstart.SetValue( 6 );
  5538. nSndShowStart = 6;
  5539. }
  5540. // get sound type before we spatialize
  5541. MXR_GetMixGroupFromSoundsource( ch );
  5542. // skip the trace on the first spatialization. This channel may be stolen
  5543. // by another sound played this frame. Defer the trace to the mix loop
  5544. SND_SpatializeFirstFrameNoTrace( ch );
  5545. // Init client entity mouth movement vars
  5546. ch->flags.m_bIgnorePhonemes = ( params.flags & SND_IGNORE_PHONEMES ) != 0;
  5547. SND_InitMouth( ch );
  5548. // Morasky: below needs to be changed/eliminated for operator stack based sounds
  5549. // If a client can't hear a sound when they FIRST receive the StartSound message,
  5550. // the client will never be able to hear that sound. This is so that out of
  5551. // range sounds don't fill the playback buffer. For streaming sounds, we bypass this optimization.
  5552. if ( !params.staticsound && BChannelLowVolume( ch, 0 ) && !toolframework->IsToolRecording() )
  5553. {
  5554. // Looping sounds don't use this optimization because they should stick around until they're killed.
  5555. // Also bypass for speech (GetSentence)
  5556. if ( !params.pSfx->pSource || (!params.pSfx->pSource->IsLooped() && !params.pSfx->pSource->GetSentence()) )
  5557. {
  5558. // if this is long sound, play the whole thing.
  5559. if (!SND_IsLongWave( ch ))
  5560. {
  5561. // DevMsg("S_StartDynamicSound: spatialized to 0 vol & ignored %s", sndname);
  5562. if ( snd_report_verbose_error.GetBool() )
  5563. {
  5564. Msg( "%s(%d): Sound '%s' spatialized to volume 0. Ignored.\n", __FILE__, __LINE__, sndname );
  5565. }
  5566. S_FreeChannel( ch );
  5567. return 0; // not audible at all
  5568. }
  5569. }
  5570. }
  5571. bool bIsMusic = S_IsMusic( ch );
  5572. // apply global pitch scale to non-music sounds
  5573. if ( !bIsMusic && g_flPitchScale != 1.0f )
  5574. {
  5575. if ( !S_IsPlayerVoice( ch ) )
  5576. {
  5577. int new_pitch = clamp( float(params.pitch) * g_flPitchScale, 0.0f, 255.0f );
  5578. params.pitch = new_pitch;
  5579. ch->basePitch = new_pitch;
  5580. }
  5581. }
  5582. // Pre-startup delay. Compute # of samples over which to mix in zeros from data source before
  5583. // actually reading first set of samples
  5584. if ( params.delay != 0.0f )
  5585. {
  5586. Assert( ch->sfx );
  5587. Assert( ch->sfx->pSource );
  5588. float rate = ch->sfx->pSource->SampleRate();
  5589. int delaySamples = (int)( params.delay * rate * params.pitch * 0.01f );
  5590. ch->pMixer->SetStartupDelaySamples( delaySamples );
  5591. if ( params.delay > 0 )
  5592. {
  5593. ch->pMixer->SetStartupDelaySamples( delaySamples );
  5594. ch->flags.delayed_start = true;
  5595. }
  5596. else
  5597. {
  5598. int skipSamples = -delaySamples;
  5599. if ( ch->sfx->pSource->GetType() != CAudioSource::AUDIO_SOURCE_MP3)
  5600. {
  5601. // For MP3, SampleCount() is inaccurate (it returns size in bytes of the Mp3 file, not the number of samples).
  5602. // It makes this whole test incorrect. Also MP3 does not support correctly looping either. Don't optimize for MP3 here.
  5603. int totalSamples = ch->sfx->pSource->SampleCount();
  5604. if ( ch->sfx->pSource->IsLooped() )
  5605. {
  5606. skipSamples = skipSamples % totalSamples;
  5607. }
  5608. if ( skipSamples >= totalSamples )
  5609. {
  5610. if ( snd_report_verbose_error.GetBool() )
  5611. {
  5612. Msg( "%s(%d): Negative delay greater than sound length for sound '%s'.\n", __FILE__, __LINE__, sndname );
  5613. }
  5614. S_FreeChannel( ch );
  5615. return 0;
  5616. }
  5617. }
  5618. ch->pitch = ch->basePitch * 0.01f;
  5619. ch->pMixer->SkipSamples( ch, skipSamples, rate, 0 );
  5620. for ( int i = 0; i < MAX_SPLITSCREEN_CLIENTS; ++i )
  5621. {
  5622. gain_t *gs = &ch->gain[ i ];
  5623. gs->ob_gain_target = 1.0f;
  5624. gs->ob_gain = 1.0f;
  5625. gs->ob_gain_inc = 0.0f;
  5626. }
  5627. ch->flags.bfirstpass = false;
  5628. ch->flags.delayed_start = true;
  5629. }
  5630. }
  5631. if ( params.staticsound && S_IsMusic( ch ) )
  5632. {
  5633. // See if we have "music" of same name playing from "world" which means we save/restored this sound already. If so,
  5634. // kill the new version and update the soundsource
  5635. CChannelList list;
  5636. g_ActiveChannels.GetActiveChannels( list );
  5637. for ( int i = 0; i < list.Count(); i++ )
  5638. {
  5639. channel_t *pChannel = list.GetChannel(i);
  5640. // Don't mess with the channel we just created, of course
  5641. if ( ch == pChannel )
  5642. continue;
  5643. if ( ch->sfx != pChannel->sfx )
  5644. continue;
  5645. if ( pChannel->soundsource != SOUND_FROM_WORLD )
  5646. continue;
  5647. if ( !S_IsMusic( pChannel ) )
  5648. continue;
  5649. if ( snd_report_verbose_error.GetBool() )
  5650. {
  5651. Msg( "%s(%d): Hooking duplicate restored song track %s\n", __FILE__, __LINE__, sndname );
  5652. }
  5653. // the new channel will have an updated soundsource and probably
  5654. // has an updated pitch or volume since we are receiving this sound message
  5655. // after the sound has started playing (usually a volume change)
  5656. // copy that data out of the source
  5657. pChannel->soundsource = ch->soundsource;
  5658. pChannel->master_vol = ch->master_vol;
  5659. pChannel->basePitch = ch->basePitch;
  5660. pChannel->pitch = ch->pitch;
  5661. S_FreeChannel( ch );
  5662. return 0;
  5663. }
  5664. }
  5665. if (nSndShowStart > 0 && nSndShowStart < 7 && nSndShowStart != 4)
  5666. {
  5667. DevMsg( "%s %s : src %d : channel %d : %d dB : vol %.2f : time %.3f\n",
  5668. params.staticsound ? "StaticSound" : "DynamicSound",
  5669. sndname, params.soundsource, params.entchannel, params.soundlevel, params.fvol, g_pSoundServices->GetHostTime() );
  5670. if (nSndShowStart == 2 || nSndShowStart == 5)
  5671. DevMsg( "\t dspmix %1.2f : distmix %1.2f : dspface %1.2f : lvol %1.2f : cvol %1.2f : rvol %1.2f : rlvol %1.2f : rrvol %1.2f\n",
  5672. ch->dspmix, ch->distmix, ch->dspface,
  5673. ch->fvolume[IFRONT_LEFT], ch->fvolume[IFRONT_CENTER], ch->fvolume[IFRONT_RIGHT], ch->fvolume[IREAR_LEFT], ch->fvolume[IREAR_RIGHT] );
  5674. if (nSndShowStart == 3)
  5675. DevMsg( "\t x: %4f y: %4f z: %4f\n", ch->origin.x, ch->origin.y, ch->origin.z );
  5676. if ( snd_visualize.GetInt() )
  5677. {
  5678. CDebugOverlay::AddTextOverlay( ch->origin, 2.0f, sndname );
  5679. }
  5680. }
  5681. g_pSoundServices->OnSoundStarted( ch->guid, params, sndname );
  5682. return ch->guid;
  5683. }
  5684. static bool S_ShouldSplitSound( const StartSoundParams_t &params )
  5685. {
  5686. if ( !params.pSfx )
  5687. return false;
  5688. // Only certain sound types need to be spatialized separately
  5689. char nameBuf[MAX_PATH];
  5690. char const *pchSoundName = params.pSfx->getname(nameBuf, sizeof(nameBuf));
  5691. if ( TestSoundChar( pchSoundName, CHAR_DOPPLER ) ||
  5692. TestSoundChar( pchSoundName, CHAR_DIRECTIONAL ) ||
  5693. TestSoundChar( pchSoundName, CHAR_DISTVARIANT ) )
  5694. {
  5695. return true;
  5696. }
  5697. return false;
  5698. }
  5699. CTSQueue< StartSoundParams_t > g_QueuedSounds;
  5700. static int S_StartSound_( StartSoundParams_t& params )
  5701. {
  5702. VPROF_( "S_StartSound_", 0, VPROF_BUDGETGROUP_OTHER_SOUND, false, BUDGETFLAG_OTHER );
  5703. if ( host_threaded_sound.GetInt() )
  5704. {
  5705. // queue the sounds up, drained when viable
  5706. // this also solves not losing inter-loading sounds from network events
  5707. // these queue up and get drained when loading is completed
  5708. if ( g_AudioDevice && g_AudioDevice->IsActive() && ( params.pSfx || params.m_nQueuedGUID > 0 ) )
  5709. {
  5710. bool bGenerateGuid = ( params.m_nQueuedGUID == StartSoundParams_t::GENERATE_GUID );
  5711. if ( params.m_nQueuedGUID == StartSoundParams_t::UNINT_GUID )
  5712. {
  5713. // Generate guid for unambiguous start command, not changes.
  5714. bGenerateGuid = ( ( params.flags & ( SND_STOP | SND_CHANGE_VOL | SND_CHANGE_PITCH ) ) == 0 );
  5715. }
  5716. if ( bGenerateGuid )
  5717. {
  5718. params.m_nQueuedGUID = SND_GetGUID();
  5719. }
  5720. g_QueuedSounds.PushItem( params );
  5721. return params.m_nQueuedGUID;
  5722. }
  5723. }
  5724. return S_StartSound_Immediate( params );
  5725. }
  5726. int S_StartSound( StartSoundParams_t& params )
  5727. {
  5728. // bump the guid here at the earliest possible pre-failure point
  5729. SND_GetGUID();
  5730. // In all cases, we are getting the filename so we can test null.wav
  5731. char nameBuf[MAX_PATH];
  5732. char const *pfn = "(Unknown)";
  5733. if ( params.pSfx != NULL )
  5734. {
  5735. pfn = params.pSfx->GetFileName( nameBuf, sizeof(nameBuf) );
  5736. if ( pfn == NULL )
  5737. {
  5738. pfn = "(null)";
  5739. }
  5740. }
  5741. // Skip the null sound, no reason to waste channels and a bunch of CPU cycles for no reason, don't even report it.
  5742. const char NULL_SOUND[] = "common/null.wav";
  5743. if ( V_stricmp( pfn, NULL_SOUND ) == 0 )
  5744. {
  5745. return 0;
  5746. }
  5747. bool bReport = snd_report_start_sound.GetBool();
  5748. if ( bReport || IsPC() )
  5749. {
  5750. if ( bReport )
  5751. {
  5752. const char * pLooping = "";
  5753. if ( snd_report_loop_sound.GetBool() )
  5754. {
  5755. if ( params.pSfx->pSource != NULL )
  5756. {
  5757. bool bIsLooped = params.pSfx->pSource->IsLooped();
  5758. pLooping = bIsLooped ? "Looping." : "Not looping.";
  5759. }
  5760. else
  5761. {
  5762. pLooping = "CAudioSource is NULL.";
  5763. }
  5764. }
  5765. const char * pFormat = "";
  5766. if ( snd_report_format_sound.GetBool() )
  5767. {
  5768. if ( params.pSfx->pSource != NULL )
  5769. {
  5770. switch ( params.pSfx->pSource->Format() )
  5771. {
  5772. case WAVE_FORMAT_ADPCM: pFormat = "ADPCM."; break;
  5773. case WAVE_FORMAT_PCM: pFormat = "PCM."; break;
  5774. case WAVE_FORMAT_XMA: pFormat = "XMA."; break;
  5775. case WAVE_FORMAT_TEMP: pFormat = "Fake-MP3."; break;
  5776. case WAVE_FORMAT_MP3: pFormat = "MP3."; break;
  5777. default: pFormat = "Unknown format."; break;
  5778. }
  5779. }
  5780. else
  5781. {
  5782. if ( pLooping[0] == '\0' )
  5783. {
  5784. // Don't want to write the same text twice.
  5785. pFormat = "CAudioSource is NULL.";
  5786. }
  5787. }
  5788. }
  5789. Warning( "[Sound] S_StartSound(\"%s\") called. Flags: %d. %s%s\n", pfn, params.flags, pLooping, pFormat );
  5790. }
  5791. if ( IsPC() )
  5792. {
  5793. BlackBox_Record( "wav", "%s", pfn );
  5794. }
  5795. }
  5796. if ( params.flags & SND_UPDATE_DELAY_FOR_CHOREO )
  5797. {
  5798. params.delay = 0; // If we update for choreo, there is no real need to have a delay (usually few ms before or after).
  5799. // We try to synchronize each sentence after the other and in some cases where the IO latency is a bit high,
  5800. // the accumulated error may actually make very small sounds disappear or sound bad.
  5801. }
  5802. if ( IsGameConsole() && params.delay < 0 && !params.initialStreamPosition && params.pSfx && params.pSfx->pSource )
  5803. {
  5804. // calculate an initial stream position from the expected sample position
  5805. float rate = params.pSfx->pSource->SampleRate();
  5806. int nSamplePosition = (int)( -params.delay * rate * params.pitch * 0.01f );
  5807. #ifdef PORTAL2
  5808. // We only use this for Portal 2, as we may want to keep the other behavior when there are machine guns involved.
  5809. const int DONT_SKIP_N_SAMPLES = (int)( rate / 20.0f ); // Let's not skip if less than 1/20th of a second
  5810. if ( nSamplePosition <= DONT_SKIP_N_SAMPLES)
  5811. {
  5812. // Nothing to skip
  5813. params.delay = 0;
  5814. }
  5815. else
  5816. #endif
  5817. {
  5818. int nResult = params.pSfx->pSource->SampleToStreamPosition( nSamplePosition );
  5819. // Here are the various possibilities for consoles:
  5820. // nResult < 0
  5821. // - For XMA or MP3 with no seek-table, we don't get an initial stream position but we will use the delay to skip the samples.
  5822. // nResult >= 0
  5823. // - For XMA with seek-table, we need initial stream position and no delay.
  5824. // - For WAV file, we need the initial stream position and a delay (but it will not skip the samples and use SetStartSample() instead).
  5825. if ( nResult >= 0 )
  5826. {
  5827. params.initialStreamPosition = nResult;
  5828. if ( params.pSfx->pSource->Format() == WAVE_FORMAT_XMA )
  5829. {
  5830. // As stated above, if we are in XMA and we got a stream position we need to remove the delay
  5831. params.delay = 0;
  5832. params.m_bDelayedStart = true;
  5833. }
  5834. }
  5835. else
  5836. {
  5837. // If the feature is not supported, we are going to use the other model (skipping the first samples).
  5838. // To avoid the higher I/O requirement (see comment below), we are going to skip samples when we play the sound (instead of ahead of time).
  5839. // In many cases, the delay is actually rather small, so we can actually hide it as part of the normal process.
  5840. // It happens because a lot of sounds are played with a delay to fix timing differences between server and client (think machine gun).
  5841. // However it is applied on many sounds (like VO) where it does not make much sense.
  5842. // For a 32 Kb block, compressed with MP3 (or XMA without seek-table), the compression ratio is around 8x,
  5843. // so a normal block read will contain around 130K mono samples, 65K stereo samples.
  5844. //
  5845. // Thus we can safely skip the first 32K stereo samples as part of the normal process without incurring more I/O pressure.
  5846. // The call to SkipSamples() below is much heavier.
  5847. // MP3 has actually better facility than XMA. It knows the number of samples per frame, and thus can avoid the SPU decoding on PS3.
  5848. // With XMA, each 2048 bytes block have N samples, so we need to decode one at a time.
  5849. // However if we push too many samples to skip to later (when we play the sound), we could end up with the sound being delayed with video
  5850. // say after a save in the Portal 2 container ride. So it is better in this case to forcibly skip the samples when we play the sound.
  5851. const int SAFE_NUMBER_OF_SAMPLES_TO_SKIP = params.pSfx->pSource->IsStereoWav() ? 16000 : 32000;
  5852. if ( nSamplePosition < SAFE_NUMBER_OF_SAMPLES_TO_SKIP )
  5853. {
  5854. params.delay = 0;
  5855. params.skipInitialSamples = nSamplePosition;
  5856. params.m_bDelayedStart = true;
  5857. }
  5858. // Although it works on PS3 and X360, the downside is that it has a higher I/O requirement at the beginning of the sound
  5859. // and a much bigger requirement if we have a lot to skip (it is as if we are playing the sound very quickly).
  5860. // On PS3 MP3, it is acceptable, especially as we are using the HDD to store sounds.
  5861. // On X360, it sounds bad the first second, however most VO sound will have seek table, so will support the feature above.
  5862. // As of today, PS3 MP3 does not support seek table.
  5863. // Keep the delay here, it will be used later.
  5864. }
  5865. }
  5866. }
  5867. // It mixes once with volumes for all split players consolidated into a single set of speaker volumes
  5868. return S_StartSound_( params );
  5869. }
  5870. // SoundEntry handling
  5871. void S_CompareSoundParams( StartSoundParams_t &pStartParams , CSoundParameters &pScriptParams )
  5872. {
  5873. if( pStartParams.entchannel != pScriptParams.channel )
  5874. {
  5875. Log_Warning( LOG_SOUND_OPERATOR_SYSTEM, "Warning: SoundEntry %s has differing emitter and script channels: emitter %i : script %i\n",
  5876. pStartParams.m_pSoundEntryName,
  5877. pStartParams.entchannel,
  5878. pScriptParams.channel );
  5879. }
  5880. if( pStartParams.delay != pScriptParams.delay_msec )
  5881. {
  5882. Log_Warning( LOG_SOUND_OPERATOR_SYSTEM, "Warning: SoundEntry %s has differing emitter and script delay times: emitter %f : script %d\n",
  5883. pStartParams.m_pSoundEntryName,
  5884. pStartParams.delay,
  5885. pScriptParams.delay_msec );
  5886. }
  5887. }
  5888. ConVar snd_sos_show_block_debug("snd_sos_show_block_debug", "0", FCVAR_CHEAT, "Spew data about the list of block entries." );
  5889. int S_StartSoundEntry( StartSoundParams_t &pStartParams, int nSeed, bool bFromPrestart )
  5890. {
  5891. if ( CommandLine()->CheckParm( "-nosound" ) )
  5892. {
  5893. return 0;
  5894. }
  5895. if ( !g_pSoundEmitterSystem )
  5896. {
  5897. DevWarning("Error: SoundEmitterSystem not initialized in engine!");
  5898. return 0;
  5899. }
  5900. if( !g_pSoundEmitterSystem->IsValidHash( pStartParams.m_nSoundScriptHash ))
  5901. {
  5902. DevMsg( "Error: Invalid SoundEntry hash %i received on client", pStartParams.m_nSoundScriptHash );
  5903. return 0;
  5904. }
  5905. // ----------------------------------------------------
  5906. // TODO: Morasky
  5907. // Need to get either the model name networked so we can
  5908. // identify gender or actually network the gender itself
  5909. // ----------------------------------------------------
  5910. // Try to deduce the actor's gender
  5911. gender_t gender = GENDER_NONE;
  5912. #if 0
  5913. //
  5914. // IClientEntity *pClientEntity = NULL;
  5915. // if ( entitylist )
  5916. // {
  5917. // pClientEntity = entitylist->GetClientEntity( pStartParams.soundsource );
  5918. // if ( pClientEntity )
  5919. // {
  5920. // char const *actorModel = STRING( pClientEntity->GetModelName() );
  5921. // if( actorModel )
  5922. // {
  5923. // gender = g_pSoundEmitterSystem->GetActorGender( actorModel );
  5924. // }
  5925. // }
  5926. // }
  5927. #endif
  5928. pStartParams.m_pSoundEntryName = g_pSoundEmitterSystem->GetSoundNameForHash( pStartParams.m_nSoundScriptHash );
  5929. if ( !pStartParams.m_pSoundEntryName )
  5930. {
  5931. DevWarning( "Error: Unable to get SoundEntry name for entry : %i", pStartParams.m_nSoundScriptHash );
  5932. return 0;
  5933. }
  5934. CSoundParameters pScriptParams;
  5935. pScriptParams.m_nRandomSeed = nSeed;
  5936. if ( !g_pSoundEmitterSystem->GetParametersForSoundEx( pStartParams.m_pSoundEntryName, pStartParams.m_nSoundScriptHash, pScriptParams, gender, true ) )
  5937. {
  5938. DevWarning("Error: Unable to get parameters for soundentry %s", pStartParams.m_pSoundEntryName );
  5939. return 0;
  5940. }
  5941. if ( !pScriptParams.soundname[0] )
  5942. return 0;
  5943. // if ( !Q_strncasecmp( pScriptParams.soundname, "vo", 2 ) &&
  5944. // !( pScriptParams.channel == CHAN_STREAM ||
  5945. // pScriptParams.channel == CHAN_VOICE ) )
  5946. // {
  5947. // DevMsg( "EmitSound: Voice wave file %s doesn't specify CHAN_VOICE or CHAN_STREAM for sound %s\n",
  5948. // pScriptParams.soundname, pStartParams.m_pSoundEntryName );
  5949. // }
  5950. if( pScriptParams.m_pOperatorsKV )
  5951. {
  5952. pStartParams.m_pOperatorsKV = pScriptParams.m_pOperatorsKV;
  5953. }
  5954. pStartParams.m_bHRTFBilinear = pScriptParams.m_bHRTFBilinear;
  5955. pStartParams.m_bHRTFFollowEntity = pScriptParams.m_bHRTFFollowEntity;
  5956. // ----------------------------------------------------
  5957. // debug sanity checking
  5958. // ----------------------------------------------------
  5959. if( snd_sos_show_client_rcv.GetInt() )
  5960. {
  5961. Log_Msg( LOG_SOUND_OPERATOR_SYSTEM, Color( 180, 256, 180, 255 ),
  5962. "Client: Received SoundEntry: %i : %s : %s : operators: %s: seed: %i\n",
  5963. pStartParams.m_nSoundScriptHash,
  5964. pStartParams.m_pSoundEntryName,
  5965. pScriptParams.soundname,
  5966. pScriptParams.m_pOperatorsKV ? "true" : "false",
  5967. nSeed );
  5968. }
  5969. #if 0
  5970. S_CompareSoundParams( pStartParams , pScriptParams );
  5971. #endif
  5972. // only block and execute start stack if an actual "start" message
  5973. if ( !( pStartParams.flags & SND_STOP ||
  5974. pStartParams.flags & SND_CHANGE_PITCH ||
  5975. pStartParams.flags & SND_CHANGE_VOL ) )
  5976. {
  5977. // check for a blocked entry
  5978. CSosEntryMatch sosEntryMatch;
  5979. V_strncpy( sosEntryMatch.m_nMatchString1, pStartParams.m_pSoundEntryName, sizeof( sosEntryMatch.m_nMatchString1 ) );
  5980. // V_strncpy( sosEntryMatch.m_nMatchString2, pScriptParams.soundname, sizeof( sosEntryMatch.m_nMatchString2 ) );
  5981. sosEntryMatch.m_nMatchInt1 = pScriptParams.channel;
  5982. sosEntryMatch.m_nMatchInt2 = pStartParams.soundsource;
  5983. if( g_pSoundOperatorSystem->m_sosEntryBlockList.HasAMatch( &sosEntryMatch ) )
  5984. {
  5985. if( snd_sos_show_block_debug.GetInt() )
  5986. {
  5987. Log_Msg(LOG_SOUND_OPERATOR_SYSTEM, Color( 180, 256, 180, 255 ), "Entry Blocked: %s\n", pStartParams.m_pSoundEntryName );
  5988. }
  5989. return 0;
  5990. }
  5991. stack_data_t stackData;
  5992. stackData.m_nSoundScriptHash = pScriptParams.m_hSoundScriptHash;
  5993. stackData.m_pOperatorsKV = pScriptParams.m_pOperatorsKV;
  5994. g_scratchpad.SetPerExecution( NULL, &pStartParams );
  5995. if( !bFromPrestart )
  5996. {
  5997. CSosOperatorStack *pCueStack = S_GetStack( CSosOperatorStack::SOS_CUE, stackData );
  5998. if( pCueStack )
  5999. {
  6000. pCueStack->Execute( NULL, &g_scratchpad );
  6001. if( snd_sos_show_operator_prestart.GetInt() )
  6002. {
  6003. pCueStack->Print( 0 );
  6004. }
  6005. pCueStack->Shutdown();
  6006. delete pCueStack;
  6007. if( g_scratchpad.m_bBlockStart )
  6008. {
  6009. return 0;
  6010. }
  6011. if( g_scratchpad.m_flDelayToQueue > 0.0 )
  6012. {
  6013. g_pSoundOperatorSystem->QueueStartEntry( pStartParams, g_scratchpad.m_flDelayToQueue, true );
  6014. return 0;
  6015. }
  6016. }
  6017. }
  6018. CSosOperatorStack *pStartStack = S_GetStack( CSosOperatorStack::SOS_START, stackData );
  6019. if( pStartStack )
  6020. {
  6021. pStartStack->SetScriptHash( pScriptParams.m_hSoundScriptHash );
  6022. pStartStack->Execute( NULL, &g_scratchpad );
  6023. if( snd_sos_show_operator_start.GetInt() )
  6024. {
  6025. const char *pFilterString = snd_sos_show_operator_entry_filter.GetString();
  6026. if( !pFilterString || !pFilterString[0] || ( pFilterString && pFilterString[0] && V_stristr( pStartParams.m_pSoundEntryName, pFilterString ) ))
  6027. {
  6028. pStartStack->Print( 0 );
  6029. }
  6030. }
  6031. pStartStack->Shutdown();
  6032. delete pStartStack;
  6033. pStartParams.delay = g_scratchpad.m_flDelay;
  6034. // this gets set to true in "SetPerExecution" or the start_stack
  6035. if( g_scratchpad.m_bBlockStart )
  6036. {
  6037. return 0;
  6038. }
  6039. }
  6040. }
  6041. CSfxTable *pSound = S_PrecacheSound( pScriptParams.soundname );
  6042. if (!pSound)
  6043. return 0;
  6044. pStartParams.pSfx = pSound;
  6045. return S_StartSound( pStartParams );
  6046. }
  6047. // Restart all the sounds on the specified channel
  6048. inline bool IsChannelLooped( int iChannel )
  6049. {
  6050. return (channels[iChannel].sfx &&
  6051. channels[iChannel].sfx->pSource &&
  6052. channels[iChannel].sfx->pSource->IsLooped() );
  6053. }
  6054. int S_GetCurrentStaticSounds( SoundInfo_t *pResult, int nSizeResult, int entchannel )
  6055. {
  6056. int nSlot = 0;
  6057. int nSpaceRemaining = nSizeResult;
  6058. char nameBuf[MAX_PATH];
  6059. for (int i = MAX_DYNAMIC_CHANNELS; i < total_channels && nSpaceRemaining; i++)
  6060. {
  6061. if ( channels[i].entchannel == entchannel && channels[i].sfx )
  6062. {
  6063. pResult->Set( channels[i].soundsource,
  6064. channels[i].entchannel,
  6065. channels[i].sfx->getname(nameBuf, sizeof(nameBuf)),
  6066. channels[i].origin,
  6067. channels[i].direction,
  6068. ( (float)channels[i].master_vol / 255.0 ),
  6069. DIST_MULT_TO_SNDLVL( channels[i].dist_mult ),
  6070. IsChannelLooped( i ),
  6071. channels[i].basePitch,
  6072. listener_origin[ nSlot ],
  6073. channels[i].speakerentity,
  6074. 0 ); // unspecified soundfile index is fine here
  6075. pResult++;
  6076. nSpaceRemaining--;
  6077. }
  6078. }
  6079. return (nSizeResult - nSpaceRemaining);
  6080. }
  6081. // Stop all sounds for entity on a channel.
  6082. void S_StopSound(int soundsource, int entchannel)
  6083. {
  6084. THREAD_LOCK_SOUND();
  6085. CChannelList list;
  6086. g_ActiveChannels.GetActiveChannels( list );
  6087. for ( int i = 0; i < list.Count(); i++ )
  6088. {
  6089. channel_t *pChannel = list.GetChannel(i);
  6090. if (pChannel->soundsource == soundsource
  6091. && pChannel->entchannel == entchannel)
  6092. {
  6093. S_StopChannelUnlocked( pChannel );
  6094. }
  6095. }
  6096. }
  6097. channel_t *S_FindChannelByGuid( int guid )
  6098. {
  6099. return g_ActiveChannels.FindActiveChannelByGuid( guid );
  6100. }
  6101. //-----------------------------------------------------------------------------
  6102. channel_t *S_FindChannelByScriptHash( HSOUNDSCRIPTHASH nHandle )
  6103. {
  6104. CChannelList list;
  6105. g_ActiveChannels.GetActiveChannels( list );
  6106. for ( int i = 0; i < list.Count(); i++ )
  6107. {
  6108. channel_t *pChannel = list.GetChannel(i);
  6109. if ( pChannel->m_nSoundScriptHash == nHandle )
  6110. {
  6111. return pChannel;
  6112. }
  6113. }
  6114. return NULL;
  6115. }
  6116. //-----------------------------------------------------------------------------
  6117. // Purpose:
  6118. // Input : guid -
  6119. //-----------------------------------------------------------------------------
  6120. void S_StopSoundByGuid( int guid, bool bForceSync )
  6121. {
  6122. if ( host_threaded_sound.GetInt() && !bForceSync )
  6123. {
  6124. // queued sounds, must also queue stops, volume & pitch changes
  6125. StartSoundParams_t params;
  6126. params.flags = SND_STOP;
  6127. params.m_nQueuedGUID = guid;
  6128. g_QueuedSounds.PushItem( params );
  6129. return;
  6130. }
  6131. THREAD_LOCK_SOUND();
  6132. while ( true )
  6133. {
  6134. channel_t *pChannel = S_FindChannelByGuid( guid );
  6135. if( pChannel )
  6136. {
  6137. if ( S_StopChannelUnlocked( pChannel ) == SCR_Delayed )
  6138. {
  6139. // Because it is delayed, the channel is still there, have to stop the loop now
  6140. break;
  6141. }
  6142. }
  6143. else
  6144. {
  6145. break;
  6146. }
  6147. }
  6148. }
  6149. //-----------------------------------------------------------------------------
  6150. // Purpose: Gets the sound duration.
  6151. // Input : pChannel - Channel to get the duration from.
  6152. // Output : The sound duration.
  6153. //-----------------------------------------------------------------------------
  6154. float S_SoundDuration( channel_t * pChannel )
  6155. {
  6156. if ( !pChannel || !pChannel->sfx )
  6157. return 0.0f;
  6158. // NOTE: Looping sounds will return the length of a single loop
  6159. // Use S_IsLoopingSoundByGuid to see if they are looped
  6160. return AudioSource_GetSoundDuration( pChannel->sfx ) / ( pChannel->basePitch * 0.01f );
  6161. }
  6162. //-----------------------------------------------------------------------------
  6163. // Purpose:
  6164. // Input : guid -
  6165. //-----------------------------------------------------------------------------
  6166. float S_SoundDurationByGuid( int guid )
  6167. {
  6168. THREAD_LOCK_SOUND();
  6169. channel_t *pChannel = S_FindChannelByGuid( guid );
  6170. return S_SoundDuration( pChannel );
  6171. }
  6172. //-----------------------------------------------------------------------------
  6173. // Is this sound a looping sound?
  6174. //-----------------------------------------------------------------------------
  6175. bool S_IsLoopingSoundByGuid( int guid )
  6176. {
  6177. channel_t *pChannel = S_FindChannelByGuid( guid );
  6178. if ( !pChannel || !pChannel->sfx )
  6179. return false;
  6180. return( pChannel->sfx->pSource->IsLooped() );
  6181. }
  6182. //-----------------------------------------------------------------------------
  6183. // Purpose: Note that the guid is preincremented, so we can just return the current value as the "last sound" indicator
  6184. // Input : -
  6185. // Output : int
  6186. //-----------------------------------------------------------------------------
  6187. int S_GetGuidForLastSoundEmitted()
  6188. {
  6189. return s_nSoundGuid;
  6190. }
  6191. //-----------------------------------------------------------------------------
  6192. // Purpose:
  6193. // Input : guid -
  6194. // Output : Returns true on success, false on failure.
  6195. //-----------------------------------------------------------------------------
  6196. bool S_IsSoundStillPlaying( int guid )
  6197. {
  6198. // sound was submitted after last channel queue went into the mix, won't have a channel yet
  6199. THREAD_LOCK_SOUND();
  6200. if ( host_threaded_sound.GetBool() )
  6201. {
  6202. AUTO_LOCK( g_ActiveSoundListMutex );
  6203. if ( guid > s_nMaxQueuedGUID )
  6204. {
  6205. // If the GUID is greater than the last set of queued GUID, it means the sound has probably not made through the active sound list yet
  6206. // We assume that it is still playing. This is not accurate though if the caller passed a bogus GUID.
  6207. return true;
  6208. }
  6209. // don't need to lock the sound mutex if we use this list
  6210. for ( int i = 0; i < g_ActiveSoundsLastUpdate.Count(); i++ )
  6211. {
  6212. if ( guid == g_ActiveSoundsLastUpdate[i].m_nGuid )
  6213. return true;
  6214. }
  6215. return false;
  6216. }
  6217. channel_t *pChannel = S_FindChannelByGuid( guid );
  6218. return pChannel != NULL ? true : false;
  6219. }
  6220. //-----------------------------------------------------------------------------
  6221. // Purpose:
  6222. // Input : guid -
  6223. // fvol -
  6224. //-----------------------------------------------------------------------------
  6225. void S_SetVolumeByGuid( int guid, float fvol )
  6226. {
  6227. if ( host_threaded_sound.GetInt() )
  6228. {
  6229. // queued sounds, must also queue stops, volume & pitch changes
  6230. StartSoundParams_t params;
  6231. params.flags = SND_CHANGE_VOL;
  6232. params.fvol = fvol;
  6233. params.m_nQueuedGUID = guid;
  6234. g_QueuedSounds.PushItem( params );
  6235. return;
  6236. }
  6237. if ( channel_t *pChannel = S_FindChannelByGuid( guid ) )
  6238. {
  6239. pChannel->master_vol = 255.0f * clamp( fvol, 0.0f, 1.0f );
  6240. }
  6241. }
  6242. //-----------------------------------------------------------------------------
  6243. // Purpose: Gets the elapsed time.
  6244. // Input : pChannel - the channel to get the elapsed time from.
  6245. // Output : The elapsed time.
  6246. //-----------------------------------------------------------------------------
  6247. float S_GetElapsedTime( const channel_t * pChannel )
  6248. {
  6249. if ( !pChannel )
  6250. return 0.0f;
  6251. CAudioMixer *mixer = pChannel->pMixer;
  6252. if ( !mixer )
  6253. return 0.0f;
  6254. CAudioSource * pSource = mixer->GetSource();
  6255. if ( !pSource )
  6256. return 0.0f;
  6257. float divisor = ( pSource->SampleRate() * pChannel->pitch * 0.01f );
  6258. if( divisor <= 0.0f )
  6259. return 0.0f;
  6260. float elapsed = mixer->GetSamplePosition() / divisor;
  6261. return elapsed;
  6262. }
  6263. //-----------------------------------------------------------------------------
  6264. // Purpose:
  6265. // Input : guid -
  6266. // Output : float
  6267. //-----------------------------------------------------------------------------
  6268. float S_GetElapsedTimeByGuid( int guid )
  6269. {
  6270. if ( host_threaded_sound.GetBool() )
  6271. {
  6272. AUTO_LOCK( g_ActiveSoundListMutex );
  6273. if ( guid < s_nMaxQueuedGUID )
  6274. {
  6275. // The guid is in the range of GUIDs from current active sounds, let's do the look-up.
  6276. // don't need to lock the sound mutex if we use this list
  6277. for ( int i = 0; i < g_ActiveSoundsLastUpdate.Count(); i++ )
  6278. {
  6279. if ( guid == g_ActiveSoundsLastUpdate[i].m_nGuid )
  6280. return g_ActiveSoundsLastUpdate[i].m_flElapsedTime;
  6281. }
  6282. }
  6283. // We did not find the GUID, that's an error condition returning 0.0f.
  6284. // Or we did not access it yet from the thread sound, in that case the elapsed time of the sound is 0.0f.
  6285. return 0.0f;
  6286. }
  6287. THREAD_LOCK_SOUND();
  6288. channel_t *pChannel = S_FindChannelByGuid( guid );
  6289. return S_GetElapsedTime( pChannel );
  6290. }
  6291. //-----------------------------------------------------------------------------
  6292. // Purpose:
  6293. // Input : sndlist -
  6294. //-----------------------------------------------------------------------------
  6295. void S_GetActiveSounds( CUtlVector< SndInfo_t >& sndlist )
  6296. {
  6297. THREAD_LOCK_SOUND();
  6298. CChannelList list;
  6299. g_ActiveChannels.GetActiveChannels( list );
  6300. for ( int i = 0; i < list.Count(); i++ )
  6301. {
  6302. channel_t *ch = list.GetChannel(i);
  6303. SndInfo_t info;
  6304. info.m_nGuid = ch->guid;
  6305. info.m_filenameHandle = ch->sfx ? ch->sfx->GetFileNameHandle() : NULL;
  6306. info.m_nSoundSource = ch->soundsource;
  6307. info.m_nChannel = ch->entchannel;
  6308. // If a sound is being played through a speaker entity (e.g., on a monitor,), this is the
  6309. // entity upon which to show the lips moving, if the sound has sentence data
  6310. info.m_nSpeakerEntity = ch->speakerentity;
  6311. info.m_flVolume = (float)ch->master_vol / 255.0f;
  6312. info.m_flLastSpatializedVolume = ch->last_vol;
  6313. // Radius of this sound effect (spatialization is different within the radius)
  6314. info.m_flRadius = ch->radius;
  6315. info.m_nPitch = ch->basePitch;
  6316. info.m_pOrigin = &ch->origin;
  6317. info.m_pDirection = &ch->direction;
  6318. // if true, assume sound source can move and update according to entity
  6319. info.m_bUpdatePositions = ch->flags.bUpdatePositions;
  6320. // true if playing linked sentence
  6321. info.m_bIsSentence = ch->flags.isSentence;
  6322. // if true, bypass all dsp processing for this sound (ie: music)
  6323. info.m_bDryMix = ch->flags.bdry;
  6324. // true if sound is playing through in-game speaker entity.
  6325. info.m_bSpeaker = ch->flags.bSpeaker;
  6326. // for snd_show, networked sounds get colored differently than local sounds
  6327. info.m_bFromServer = ch->flags.fromserver;
  6328. sndlist.AddToTail( info );
  6329. }
  6330. }
  6331. void S_StopAllSounds( bool bClear )
  6332. {
  6333. THREAD_LOCK_SOUND();
  6334. int i;
  6335. if ( !g_AudioDevice )
  6336. return;
  6337. if ( !g_AudioDevice->IsActive() )
  6338. return;
  6339. total_channels = MAX_DYNAMIC_CHANNELS; // no statics
  6340. DevMsg( 1, "Stopping All Sounds...\n" );
  6341. CChannelList list;
  6342. g_ActiveChannels.GetActiveChannels( list );
  6343. for ( i = 0; i < list.Count(); i++ )
  6344. {
  6345. char nameBuf[MAX_PATH];
  6346. channel_t *pChannel = list.GetChannel( i );
  6347. char *pName = nameBuf;
  6348. if ( pChannel->sfx )
  6349. {
  6350. pChannel->sfx->getname( nameBuf, sizeof( nameBuf ) );
  6351. }
  6352. else
  6353. {
  6354. pName = "Unknown";
  6355. }
  6356. DevMsg( 1, "Stopping: Channel:%2d %s\n", list.GetChannelIndex( i ), pName );
  6357. S_FreeChannel( pChannel );
  6358. }
  6359. // flush the mouth update queue
  6360. SND_MouthUpdateAll();
  6361. g_QueuedSounds.Purge();
  6362. // sound operator system stuff
  6363. g_pSoundOperatorSystem->ClearSubSystems();
  6364. Q_memset( channels, 0, MAX_CHANNELS * sizeof(channel_t) );
  6365. if ( bClear )
  6366. {
  6367. S_ClearBuffer();
  6368. }
  6369. // Clear any remaining soundfade
  6370. memset( &soundfade, 0, sizeof( soundfade ) );
  6371. Assert( g_ActiveChannels.GetActiveCount() == 0 );
  6372. }
  6373. void S_PreventSound( bool bSetting )
  6374. {
  6375. g_bPreventSound = bSetting;
  6376. }
  6377. bool S_GetPreventSound( void )
  6378. {
  6379. return g_bPreventSound;
  6380. }
  6381. void S_StopAllSoundsC( void )
  6382. {
  6383. S_StopAllSounds( true );
  6384. }
  6385. void S_OnLoadScreen( bool value )
  6386. {
  6387. s_bOnLoadScreen = value;
  6388. }
  6389. void S_ClearBuffer( void )
  6390. {
  6391. if ( !g_AudioDevice )
  6392. return;
  6393. g_AudioDevice->ClearBuffer();
  6394. DSP_ClearState();
  6395. MIX_ClearAllPaintBuffers( PAINTBUFFER_SIZE, true );
  6396. }
  6397. //-----------------------------------------------------------------------------
  6398. // Purpose:
  6399. // Input : percent -
  6400. // holdtime -
  6401. // intime -
  6402. // outtime -
  6403. //-----------------------------------------------------------------------------
  6404. void S_SoundFade( float percent, float holdtime, float intime, float outtime )
  6405. {
  6406. soundfade.starttime = g_pSoundServices->GetHostTime();
  6407. soundfade.initial_percent = percent;
  6408. soundfade.fadeouttime = outtime;
  6409. soundfade.holdtime = holdtime;
  6410. soundfade.fadeintime = intime;
  6411. }
  6412. //-----------------------------------------------------------------------------
  6413. // Purpose: Modulates sound volume on the client.
  6414. //-----------------------------------------------------------------------------
  6415. void S_UpdateSoundFade(void)
  6416. {
  6417. float totaltime;
  6418. float f;
  6419. // Determine current fade value.
  6420. // Assume no fading remains
  6421. soundfade.percent = 0;
  6422. totaltime = soundfade.fadeouttime + soundfade.fadeintime + soundfade.holdtime;
  6423. float elapsed = g_pSoundServices->GetHostTime() - soundfade.starttime;
  6424. // Clock wrapped or reset (BUG) or we've gone far enough
  6425. if ( elapsed < 0.0f || elapsed >= totaltime || totaltime <= 0.0f )
  6426. {
  6427. return;
  6428. }
  6429. // We are in the fade time, so determine amount of fade.
  6430. if ( soundfade.fadeouttime > 0.0f && ( elapsed < soundfade.fadeouttime ) )
  6431. {
  6432. // Ramp up
  6433. f = elapsed / soundfade.fadeouttime;
  6434. }
  6435. // Inside the hold time
  6436. else if ( elapsed <= ( soundfade.fadeouttime + soundfade.holdtime ) )
  6437. {
  6438. // Stay
  6439. f = 1.0f;
  6440. }
  6441. else
  6442. {
  6443. // Ramp down
  6444. f = ( elapsed - ( soundfade.fadeouttime + soundfade.holdtime ) ) / soundfade.fadeintime;
  6445. // backward interpolated...
  6446. f = 1.0f - f;
  6447. }
  6448. // Spline it.
  6449. f = SimpleSpline( f );
  6450. f = clamp( f, 0.0f, 1.0f );
  6451. soundfade.percent = soundfade.initial_percent * f;
  6452. }
  6453. //=============================================================================
  6454. // Global Voice Ducker - enabled in vcd scripts, when characters deliver important dialog. Overrides all
  6455. // other mixer ducking, and ducks all other sounds except dialog.
  6456. ConVar snd_ducktovolume( "snd_ducktovolume", "0.55", FCVAR_ARCHIVE );
  6457. ConVar snd_duckerattacktime( "snd_duckerattacktime", "0.5", FCVAR_ARCHIVE );
  6458. ConVar snd_duckerreleasetime( "snd_duckerreleasetime", "2.5", FCVAR_ARCHIVE );
  6459. ConVar snd_duckerthreshold("snd_duckerthreshold", "0.15", FCVAR_ARCHIVE );
  6460. ConVar snd_ducking_off("snd_ducking_off", "1", FCVAR_ARCHIVE );
  6461. static void S_UpdateVoiceDuck( int voiceChannelCount, int voiceChannelMaxVolume, float frametime )
  6462. {
  6463. if( !snd_ducking_off.GetInt() )
  6464. {
  6465. float volume_when_ducked = snd_ducktovolume.GetFloat();
  6466. int volume_threshold = (int)(snd_duckerthreshold.GetFloat() * 255.0);
  6467. float duckTarget = 1.0;
  6468. if ( voiceChannelCount > 0 )
  6469. {
  6470. voiceChannelMaxVolume = clamp(voiceChannelMaxVolume, 0, 255);
  6471. // duckTarget = RemapVal( voiceChannelMaxVolume, 0, 255, 1.0, volume_when_ducked );
  6472. // KB: Change: ducker now active if any character is speaking above threshold volume.
  6473. // KB: Active ducker drops all volumes to volumes * snd_duckvolume
  6474. if ( voiceChannelMaxVolume > volume_threshold )
  6475. duckTarget = volume_when_ducked;
  6476. }
  6477. float rate = ( duckTarget < g_DuckScale ) ? snd_duckerattacktime.GetFloat() : snd_duckerreleasetime.GetFloat();
  6478. g_DuckScale = Approach( duckTarget, g_DuckScale, frametime * ((1-volume_when_ducked) / rate) );
  6479. g_DuckScaleInt256 = g_DuckScale * 256.0f;
  6480. }
  6481. else
  6482. {
  6483. g_DuckScale = 1.0;
  6484. g_DuckScaleInt256 = 256;
  6485. }
  6486. }
  6487. // set 2d forward vector, given 3d right vector.
  6488. // NOTE: this should only be used for a listener forward
  6489. // vector from a listener right vector. It is not a general use routine.
  6490. void ConvertListenerVectorTo2D( Vector *pvforward, const Vector *pvright )
  6491. {
  6492. // get 2d forward direction vector, ignoring pitch angle
  6493. QAngle angles2d;
  6494. Vector source2d;
  6495. Vector listener_forward2d;
  6496. source2d = *pvright;
  6497. source2d.z = 0.0;
  6498. VectorNormalize(source2d);
  6499. // convert right vector to euler angles (yaw & pitch)
  6500. VectorAngles(source2d, angles2d);
  6501. // get forward angle of listener
  6502. angles2d[PITCH] = 0;
  6503. angles2d[YAW] += 90; // rotate 90 ccw
  6504. angles2d[ROLL] = 0;
  6505. if (angles2d[YAW] >= 360)
  6506. angles2d[YAW] -= 360;
  6507. AngleVectors(angles2d, &listener_forward2d);
  6508. VectorNormalize(listener_forward2d);
  6509. *pvforward = listener_forward2d;
  6510. }
  6511. // If this is nonzero, we will only spatialize some of the static
  6512. // channels each frame. The round robin will spatialize 1 / (2 ^ x)
  6513. // of the spatial channels each frame.
  6514. ConVar snd_spatialize_roundrobin( "snd_spatialize_roundrobin", "0", FCVAR_NONE, "Lowend optimization: if nonzero, spatialize only a fraction of sound channels each frame. 1/2^x of channels will be spatialized per frame." );
  6515. // draw a curve of the db based volume falloff
  6516. ConVar snd_debug_gaincurve( "snd_debug_gaincurve", "0", FCVAR_NONE, "Visualize sound gain fall off" );
  6517. ConVar snd_debug_gaincurvevol( "snd_debug_gaincurvevol", "1.0", FCVAR_NONE, "Visualize sound gain fall off" );
  6518. void DEBUG_drawGainCurve(void)
  6519. {
  6520. CUtlVector<float> gainList;
  6521. float startY = .03;
  6522. float totalY = .4;
  6523. float startX = .03;
  6524. float minGain = .015;
  6525. int maxEntries = 800;
  6526. float stepDist = 12;
  6527. for(int i = 0; i < maxEntries; i++)
  6528. {
  6529. // float gain = SND_GetGainFromMult( float gain, float dist_mult, vec_t dist )
  6530. float gain = SND_GetGainFromMult( snd_debug_gaincurvevol.GetFloat(), SNDLVL_TO_DIST_MULT(snd_debug_gaincurve.GetInt()), stepDist * (float)i );
  6531. if(gain < minGain)
  6532. break;
  6533. // gainList.AddToTail((float)(maxEntries - i) / ((float) maxEntries));
  6534. gainList.AddToTail(gain);
  6535. }
  6536. int count = gainList.Count();
  6537. char str[32];
  6538. sprintf(str, "%i ft", 0);
  6539. CDebugOverlay::AddScreenTextOverlay(0, 0, .1, 0, 255, 0, 255, str);
  6540. sprintf(str, "%i ft", count / 2);
  6541. CDebugOverlay::AddScreenTextOverlay(.5, 0, .1, 0, 255, 0, 255, str);
  6542. sprintf(str, "%i ft", count / 4);
  6543. CDebugOverlay::AddScreenTextOverlay(.25, 0, .1, 0, 255, 0, 255, str);
  6544. sprintf(str, "%i ft", count / 2 + count / 4);
  6545. CDebugOverlay::AddScreenTextOverlay(.75, 0, .1, 0, 255, 0, 255, str);
  6546. sprintf(str, "%i ft", count);
  6547. CDebugOverlay::AddScreenTextOverlay(.95, 0, .1, 0, 255, 0, 255, str);
  6548. sprintf(str, "1.0");
  6549. CDebugOverlay::AddScreenTextOverlay(0, startY, .1, 0, 255, 0, 255, str);
  6550. sprintf(str, "0.75");
  6551. CDebugOverlay::AddScreenTextOverlay(0, startY + (totalY * .25), .1, 0, 255, 0, 255, str);
  6552. sprintf(str, "0.5");
  6553. CDebugOverlay::AddScreenTextOverlay(0, startY + (totalY * .5), .1, 0, 255, 0, 255, str);
  6554. sprintf(str, "0.25");
  6555. CDebugOverlay::AddScreenTextOverlay(0, startY + (totalY * .75), .1, 0, 255, 0, 255, str);
  6556. sprintf(str, "0.0");
  6557. CDebugOverlay::AddScreenTextOverlay(0, startY + totalY , .1, 0, 255, 0, 255, str);
  6558. for(int i = 0; i < count; i++)
  6559. {
  6560. CDebugOverlay::AddScreenTextOverlay(startX + (float)(((float)i)*(float)(1.0 / (float)count)), startY + (totalY - (gainList[i]*totalY)), .1, 0, 255, 0, 255, "+");
  6561. CDebugOverlay::AddScreenTextOverlay(startX + (float)(((float)i)*(float)(1.0 / (float)count)), startY, .1, 255, 0, 0, 255, "-");
  6562. CDebugOverlay::AddScreenTextOverlay(startX + (float)(((float)i)*(float)(1.0 / (float)count)), startY + totalY, .1, 255, 0, 0, 255, "-");
  6563. CDebugOverlay::AddScreenTextOverlay(startX, startY + (totalY - (gainList[i]*totalY)), .1, 255, 0, 0, 255, "+");
  6564. }
  6565. }
  6566. ConVar snd_debug_panlaw( "snd_debug_panlaw", "0", FCVAR_CHEAT, "Visualize panning crossfade curves" );
  6567. void S_StartQueuedSounds()
  6568. {
  6569. if ( !g_QueuedSounds.Count() || g_bPreventSound )
  6570. {
  6571. // empty or not ready to drain the queued yet
  6572. return;
  6573. }
  6574. // Update the max queued GUID only if it is greater, modifying an old sound should not change the behavior of this value
  6575. int lastGUID = s_nMaxQueuedGUID;
  6576. while ( 1 )
  6577. {
  6578. StartSoundParams_t soundParams;
  6579. if ( !g_QueuedSounds.PopItem( &soundParams ) )
  6580. {
  6581. break;
  6582. }
  6583. int nGuid = S_StartSound_Immediate( soundParams );
  6584. lastGUID = MAX( lastGUID, nGuid );
  6585. }
  6586. s_nMaxQueuedGUID = lastGUID;
  6587. }
  6588. static CUtlHashtable< HSOUNDSCRIPTHASH, int > s_SoundsPrintedLastUpdate;
  6589. void OnSndShowEdgeChanged( IConVar *var, const char *pOldValue, float flOldValue )
  6590. {
  6591. s_SoundsPrintedLastUpdate.Purge();
  6592. }
  6593. /*
  6594. ============
  6595. S_Update
  6596. Called once each time through the main loop
  6597. ============
  6598. */
  6599. void S_Update( const CAudioState *pAudioState )
  6600. {
  6601. VPROF_BUDGET( "S_Update", VPROF_BUDGETGROUP_OTHER_SOUND );
  6602. int i;
  6603. channel_t *ch;
  6604. channel_t *combine;
  6605. #if !USE_AUDIO_DEVICE_V1
  6606. S_CheckDevice();
  6607. #endif
  6608. // check for errors and handle them
  6609. if ( !g_AudioDevice->IsActive() )
  6610. return;
  6611. MDLCACHE_CRITICAL_SECTION_( g_pMDLCache );
  6612. // update soundoperator system before doing anything that uses
  6613. g_pSoundOperatorSystem->Update();
  6614. // start queued sounds
  6615. if ( host_threaded_sound.GetInt() )
  6616. {
  6617. S_StartQueuedSounds();
  6618. }
  6619. g_SndMutex.Lock();
  6620. if ( host_threaded_sound.GetInt() )
  6621. {
  6622. AUTO_LOCK( g_ActiveSoundListMutex );
  6623. g_ActiveChannels.CopyActiveSounds( g_ActiveSoundsLastUpdate );
  6624. }
  6625. g_SndMergeMethod = (ESndMergeMethod)clamp( snd_mergemethod.GetInt(), 0, SND_MERGE_COUNT - 1 );
  6626. // Update any client side sound fade
  6627. S_UpdateSoundFade();
  6628. // pipe the mouth events to the client
  6629. SND_MouthUpdateAll();
  6630. // should make this all access matrix vectors instead of euler trig operations?
  6631. if ( pAudioState )
  6632. {
  6633. FOR_EACH_VALID_SPLITSCREEN_PLAYER( hh )
  6634. {
  6635. VectorCopy( pAudioState->GetPerUser( hh ).m_Origin, listener_origin[ hh ] );
  6636. AngleVectors( pAudioState->GetPerUser( hh ).m_Angles, &listener_forward[ hh ], &listener_right[ hh ], &listener_up[ hh ] );
  6637. }
  6638. s_bIsListenerUnderwater = pAudioState->IsAnyPlayerUnderwater();
  6639. }
  6640. else
  6641. {
  6642. FOR_EACH_VALID_SPLITSCREEN_PLAYER( hh )
  6643. {
  6644. VectorCopy( vec3_origin, listener_origin[ hh ] );
  6645. VectorCopy( vec3_origin, listener_forward[ hh ] );
  6646. VectorCopy( vec3_origin, listener_right[ hh ] );
  6647. VectorCopy( vec3_origin, listener_up[ hh ] );
  6648. }
  6649. s_bIsListenerUnderwater = false;
  6650. }
  6651. // making copies for the operator system
  6652. int count = 0;
  6653. g_scratchpad.m_vBlendedListenerOrigin.Init( 0.0, 0.0, 0.0 );
  6654. FOR_EACH_VALID_SPLITSCREEN_PLAYER( hh )
  6655. {
  6656. VectorCopy( listener_origin[ hh ], g_scratchpad.m_vPlayerOrigin[hh] );
  6657. VectorCopy( listener_forward[ hh ], g_scratchpad.m_vPlayerForward[hh] );
  6658. VectorCopy( listener_right[ hh ], g_scratchpad.m_vPlayerRight[hh] );
  6659. VectorCopy( listener_up[ hh ], g_scratchpad.m_vPlayerUp[hh] );
  6660. g_scratchpad.m_vBlendedListenerOrigin += g_scratchpad.m_vPlayerOrigin[ hh ];
  6661. ++count;
  6662. }
  6663. //////////////////////////////////////////////////////////////////////////
  6664. // For Splitscreen this is the average position, a total hack!!!
  6665. // used in getting client state, etc. (AND facing..??)
  6666. //////////////////////////////////////////////////////////////////////////
  6667. if ( count > 1 )
  6668. {
  6669. g_scratchpad.m_vBlendedListenerOrigin /= (float)count;
  6670. }
  6671. combine = NULL;
  6672. int voiceChannelCount = 0;
  6673. int voiceChannelMaxVolume = 0;
  6674. // visualizer for distance falloff curve
  6675. if ( snd_debug_gaincurve.GetInt() )
  6676. {
  6677. DEBUG_drawGainCurve();
  6678. }
  6679. // visualizer for distance falloff curve
  6680. if ( snd_debug_panlaw.GetInt() )
  6681. {
  6682. DEBUG_DrawPanCurves();
  6683. }
  6684. // reset traceline counter for this frame
  6685. g_snd_trace_count = 0;
  6686. // calculate distance to nearest walls, update dsp_spatial
  6687. // updates one wall only per frame (one trace per frame)
  6688. SND_SetSpatialDelays();
  6689. // updates dsp_room if automatic room detection enabled
  6690. DAS_CheckNewRoomDSP();
  6691. // update mix group solo status
  6692. MXR_SetSoloActive();
  6693. // update spatialization for static and dynamic sounds
  6694. CChannelList list;
  6695. g_ActiveChannels.GetActiveChannels( list );
  6696. if ( snd_spatialize_roundrobin.GetInt() == 0 )
  6697. {
  6698. // spatialize each channel each time
  6699. for ( i = 0; i < list.Count(); i++ )
  6700. {
  6701. ch = list.GetChannel(i);
  6702. Assert( ch->sfx );
  6703. Assert( ch->activeIndex > 0 );
  6704. // respatialize channel
  6705. SND_Spatialize( ch );
  6706. if ( ch->sfx->pSource && ch->sfx->pSource->IsVoiceSource() )
  6707. {
  6708. voiceChannelCount++;
  6709. int iThisChannelMaxVol = ChannelGetMaxVol( ch );
  6710. voiceChannelMaxVolume = MAX( voiceChannelMaxVolume, iThisChannelMaxVol );
  6711. }
  6712. }
  6713. }
  6714. else
  6715. {
  6716. static unsigned int s_roundrobin = 0 ; ///< number of times this function is called.
  6717. ///< used instead of host_frame because that number
  6718. ///< isn't necessarily available here (sez Yahn).
  6719. // lowend performance improvement: spatialize only some channels each frame.
  6720. unsigned int robinmask = (1 << snd_spatialize_roundrobin.GetInt()) - 1;
  6721. // now do static channels
  6722. for ( i = 0 ; i < list.Count() ; ++i )
  6723. {
  6724. ch = list.GetChannel(i);
  6725. Assert(ch->sfx);
  6726. Assert(ch->activeIndex > 0);
  6727. // need to check bfirstpass because sound tracing may have been deferred
  6728. if ( ch->flags.bfirstpass || (robinmask & s_roundrobin) == ( i & robinmask ) )
  6729. {
  6730. SND_Spatialize(ch); // respatialize channel
  6731. }
  6732. if ( ch->sfx->pSource && ch->sfx->pSource->IsVoiceSource() )
  6733. {
  6734. voiceChannelCount++;
  6735. int iThisChannelMaxVol = ChannelGetMaxVol( ch );
  6736. voiceChannelMaxVolume = MAX( voiceChannelMaxVolume, iThisChannelMaxVol );
  6737. }
  6738. }
  6739. ++s_roundrobin;
  6740. }
  6741. SND_ChannelTraceReset();
  6742. // check if stacks associated with channels were stopped
  6743. // do this before new stops happen and don't get updated
  6744. // MORASKY: introduces yet another 1 frame delay
  6745. CChannelList stopList;
  6746. g_ActiveChannels.GetActiveChannels( stopList );
  6747. // spatialize each channel each time
  6748. for ( i = 0; i < stopList.Count(); i++ )
  6749. {
  6750. ch = stopList.GetChannel(i);
  6751. if( ch->m_pStackList && ch->m_pStackList->IsStopped() )
  6752. {
  6753. S_FreeChannel( ch );
  6754. }
  6755. }
  6756. // drain updated sos start queue
  6757. g_pSoundOperatorSystem->StartQueuedEntries();
  6758. // drain updated sos start queue
  6759. g_pSoundOperatorSystem->StopQueuedChannels();
  6760. // set new target for voice ducking
  6761. float frametime = g_pSoundServices->GetHostFrametime();
  6762. S_UpdateVoiceDuck( voiceChannelCount, voiceChannelMaxVolume, frametime );
  6763. // update x360 music volume
  6764. g_DashboardMusicMixValue = Approach( g_DashboardMusicMixTarget, g_DashboardMusicMixValue, g_DashboardMusicFadeRate * frametime );
  6765. //
  6766. // debugging output
  6767. //
  6768. g_pSoundOperatorSystem->DEBUG_ShowTrackList( );
  6769. g_pSoundOperatorSystem->DEBUG_ShowOpvarList( );
  6770. if ( snd_show.GetInt() || snd_show_print.GetInt())
  6771. {
  6772. static int s_nPrintTickCount = 0; s_nPrintTickCount++;// = g_ClientGlobalVariables.tickcount;
  6773. con_nprint_t np;
  6774. np.time_to_live = 2.0f;
  6775. np.fixed_width_font = true;
  6776. int numActiveChannels = g_ActiveChannels.GetActiveCount();
  6777. int total = 0;
  6778. int sndsurround = snd_surround.GetInt();
  6779. np.index = 0;
  6780. np.color[0] = 1.0;
  6781. np.color[1] = 1.0;
  6782. np.color[2] = 1.0;
  6783. Con_NXPrintf ( &np, "Total Channels: %i", numActiveChannels);
  6784. char nameBuf[ 256 ];
  6785. for ( int i = 0; i < list.Count(); i++ )
  6786. {
  6787. channel_t *ch = list.GetChannel(i);
  6788. if ( !ch->sfx )
  6789. continue;
  6790. if( snd_show.GetInt() == 2 && ch->entchannel >= CHAN_STATIC )
  6791. {
  6792. continue;
  6793. }
  6794. else if( snd_show.GetInt() == 3 && ch->entchannel != CHAN_STATIC )
  6795. {
  6796. continue;
  6797. }
  6798. char nSoundEntryName[64] = "";
  6799. if( ch->m_nSoundScriptHash != SOUNDEMITTER_INVALID_HASH )
  6800. {
  6801. const char *pSoundEntryName = g_pSoundEmitterSystem->GetSoundNameForHash( ch->m_nSoundScriptHash );
  6802. if( pSoundEntryName )
  6803. {
  6804. if ( const char *pFilter = snd_show_filter.GetString() )
  6805. {
  6806. if ( *pFilter && !V_stristr( pSoundEntryName, pFilter ) )
  6807. {
  6808. continue;
  6809. }
  6810. }
  6811. V_strncpy( nSoundEntryName, pSoundEntryName, sizeof(nSoundEntryName) );
  6812. }
  6813. }
  6814. np.index = total + 2;
  6815. if ( ch->flags.fromserver )
  6816. {
  6817. np.color[0] = 1.0;
  6818. np.color[1] = 0.8;
  6819. np.color[2] = 0.1;
  6820. }
  6821. else
  6822. {
  6823. np.color[0] = 0.1;
  6824. np.color[1] = 0.9;
  6825. np.color[2] = 1.0;
  6826. }
  6827. unsigned int sampleCount = RemainingSamples( ch );
  6828. float timeleft = (float)sampleCount / (float)ch->sfx->pSource->SampleRate();
  6829. bool bLooping = ch->sfx->pSource->IsLooped();
  6830. if (snd_show.GetInt())
  6831. {
  6832. if (ch->wavtype == CHAR_HRTF)
  6833. {
  6834. const float hdist = sqrt(ch->hrtf.vec.x*ch->hrtf.vec.x + ch->hrtf.vec.z*ch->hrtf.vec.z);
  6835. const float yaw = -VEC_RAD2DEG(atan2(-ch->hrtf.vec.x, -ch->hrtf.vec.z));
  6836. const float pitch = VEC_RAD2DEG(atan2(ch->hrtf.vec.y, hdist));
  6837. Con_NXPrintf(&np, "%s %02i hrtf(%.2f %.2f %.2f) yaw(%.2f) pitch(%.2f) xfade(%.2f) vol(%.2f %.2f) ent(%03d) pos(%6d %6d %6d) timeleft(%f) looped(%d) %50s",
  6838. nSoundEntryName,
  6839. total + 1,
  6840. ch->hrtf.vec.x,
  6841. ch->hrtf.vec.y,
  6842. ch->hrtf.vec.z,
  6843. yaw,
  6844. pitch,
  6845. ch->hrtf.lerp,
  6846. ch->fvolume_target[0], ch->fvolume_target[1],
  6847. ch->soundsource,
  6848. (int)ch->origin[0],
  6849. (int)ch->origin[1],
  6850. (int)ch->origin[2],
  6851. timeleft,
  6852. bLooping,
  6853. ch->sfx->getname(nameBuf, sizeof(nameBuf)));
  6854. }
  6855. else if ( sndsurround < 4 )
  6856. {
  6857. Con_NXPrintf( &np, "%s %02i l(%.02f) r(%.02f) vol(%03d) ent(%03d) pos(%6d %6d %6d) timeleft(%f) looped(%d) %50s",
  6858. nSoundEntryName,
  6859. total + 1,
  6860. ch->fvolume[ IFRONT_LEFT ],
  6861. ch->fvolume[ IFRONT_RIGHT ],
  6862. ch->master_vol,
  6863. ch->soundsource,
  6864. ( int )ch->origin[ 0 ],
  6865. ( int )ch->origin[ 1 ],
  6866. ( int )ch->origin[ 2 ],
  6867. timeleft,
  6868. bLooping,
  6869. ch->sfx->getname( nameBuf, sizeof( nameBuf ) ) );
  6870. }
  6871. else
  6872. {
  6873. Con_NXPrintf( &np, "%s %02i l(%.02f) c(%.02f) r(%.02f) rl(%.02f) rr(%.02f) vol(%03d) ent(%03d) pos(%6d %6d %6d) timeleft(%f) looped(%d) %50s",
  6874. nSoundEntryName,
  6875. total + 1,
  6876. ch->fvolume[ IFRONT_LEFT ],
  6877. ch->fvolume[ IFRONT_CENTER ],
  6878. ch->fvolume[ IFRONT_RIGHT ],
  6879. ch->fvolume[ IREAR_LEFT ],
  6880. ch->fvolume[ IREAR_RIGHT ],
  6881. ch->master_vol,
  6882. ch->soundsource,
  6883. ( int )ch->origin[ 0 ],
  6884. ( int )ch->origin[ 1 ],
  6885. ( int )ch->origin[ 2 ],
  6886. timeleft,
  6887. bLooping,
  6888. ch->sfx->getname( nameBuf, sizeof( nameBuf ) ) );
  6889. }
  6890. }
  6891. if ( snd_visualize.GetInt() )
  6892. {
  6893. CDebugOverlay::AddTextOverlay( ch->origin, 0.05f, ch->sfx->getname(nameBuf, sizeof(nameBuf)) );
  6894. }
  6895. #ifndef DEDICATED
  6896. if ( snd_show_print.GetInt() )
  6897. {
  6898. bool bPrint = false;
  6899. // did we print this sound last frame? If we didn't, then print it now
  6900. int nFind = s_SoundsPrintedLastUpdate.Find( ch->m_nSoundScriptHash );
  6901. if ( nFind == s_SoundsPrintedLastUpdate.InvalidHandle() )
  6902. {
  6903. bPrint = true;
  6904. s_SoundsPrintedLastUpdate.Insert( ch->m_nSoundScriptHash, s_nPrintTickCount );
  6905. }
  6906. else
  6907. {
  6908. int &nLastPlayed = s_SoundsPrintedLastUpdate.Element( nFind );
  6909. if ( uint( s_nPrintTickCount - nLastPlayed ) > uint( snd_show_print.GetInt() ) )
  6910. {
  6911. bPrint = true;
  6912. }
  6913. nLastPlayed = s_nPrintTickCount;
  6914. }
  6915. if ( bPrint )
  6916. {
  6917. if (ch->wavtype == CHAR_HRTF)
  6918. {
  6919. const float hdist = sqrt(ch->hrtf.vec.x*ch->hrtf.vec.x + ch->hrtf.vec.z*ch->hrtf.vec.z);
  6920. const float yaw = -VEC_RAD2DEG(atan2(-ch->hrtf.vec.x, -ch->hrtf.vec.z));
  6921. const float pitch = VEC_RAD2DEG(atan2(ch->hrtf.vec.y, hdist));
  6922. Msg( "%32s hrtf lerp(%.2f) yaw(%.2f) pitch(%.2f) %02i vol(%03d) ent(%03d) pos(%6d %6d %6d) timeleft(%f) looped(%d) %50s\n",
  6923. nSoundEntryName,
  6924. ch->hrtf.lerp,
  6925. yaw,
  6926. pitch,
  6927. total + 1,
  6928. ch->master_vol,
  6929. ch->soundsource,
  6930. ( int )ch->origin[ 0 ],
  6931. ( int )ch->origin[ 1 ],
  6932. ( int )ch->origin[ 2 ],
  6933. timeleft,
  6934. bLooping,
  6935. ch->sfx->getname( nameBuf, sizeof( nameBuf ) ) );
  6936. }
  6937. else
  6938. if ( sndsurround < 4 )
  6939. {
  6940. Msg( "%s %02i l(%03d) r(%03d) vol(%03d) ent(%03d) pos(%6d %6d %6d) timeleft(%f) looped(%d) %50s\n",
  6941. nSoundEntryName,
  6942. total + 1,
  6943. ( int )ch->fvolume[ IFRONT_LEFT ],
  6944. ( int )ch->fvolume[ IFRONT_RIGHT ],
  6945. ch->master_vol,
  6946. ch->soundsource,
  6947. ( int )ch->origin[ 0 ],
  6948. ( int )ch->origin[ 1 ],
  6949. ( int )ch->origin[ 2 ],
  6950. timeleft,
  6951. bLooping,
  6952. ch->sfx->getname( nameBuf, sizeof( nameBuf ) ) );
  6953. }
  6954. else
  6955. {
  6956. Msg( "%s %02i l(%03d) c(%03d) r(%03d) rl(%03d) rr(%03d) vol(%03d) ent(%03d) pos(%6d %6d %6d) timeleft(%f) looped(%d) %50s\n",
  6957. nSoundEntryName,
  6958. total + 1,
  6959. ( int )ch->fvolume[ IFRONT_LEFT ],
  6960. ( int )ch->fvolume[ IFRONT_CENTER ],
  6961. ( int )ch->fvolume[ IFRONT_RIGHT ],
  6962. ( int )ch->fvolume[ IREAR_LEFT ],
  6963. ( int )ch->fvolume[ IREAR_RIGHT ],
  6964. ch->master_vol,
  6965. ch->soundsource,
  6966. ( int )ch->origin[ 0 ],
  6967. ( int )ch->origin[ 1 ],
  6968. ( int )ch->origin[ 2 ],
  6969. timeleft,
  6970. bLooping,
  6971. ch->sfx->getname( nameBuf, sizeof( nameBuf ) ) );
  6972. }
  6973. }
  6974. }
  6975. #endif
  6976. ++total;
  6977. }
  6978. while ( total <= 128 )
  6979. {
  6980. Con_NPrintf( total + 2, "" );
  6981. total++;
  6982. }
  6983. }
  6984. g_SndMutex.Unlock();
  6985. if ( s_bOnLoadScreen )
  6986. return;
  6987. // not time to update yet?
  6988. double tNow = Plat_FloatTime();
  6989. // this is the last time we ran a sound frame
  6990. g_LastSoundFrame = tNow;
  6991. // this is the last time we did mixing (extraupdate also advances this if it mixes)
  6992. g_LastMixTime = tNow;
  6993. // mix some sound
  6994. // try to stay at least one frame + mixahead ahead in the mix.
  6995. g_EstFrameTime = (g_EstFrameTime * 0.9f) + (g_pSoundServices->GetHostFrametime() * 0.1f);
  6996. S_Update_( g_EstFrameTime + snd_mixahead.GetFloat() );
  6997. }
  6998. void S_DumpClientSounds( )
  6999. {
  7000. con_nprint_t np;
  7001. np.time_to_live = 2.0f;
  7002. np.fixed_width_font = true;
  7003. int total = 0;
  7004. char nameBuf[MAX_PATH];
  7005. CChannelList list;
  7006. g_ActiveChannels.GetActiveChannels( list );
  7007. for ( int i = 0; i < list.Count(); i++ )
  7008. {
  7009. channel_t *ch = list.GetChannel(i);
  7010. if ( !ch->sfx )
  7011. continue;
  7012. unsigned int sampleCount = RemainingSamples( ch );
  7013. float timeleft = (float)sampleCount / (float)ch->sfx->pSource->SampleRate();
  7014. bool bLooping = ch->sfx->pSource->IsLooped();
  7015. const char *pszclassname = GetClientClassname(ch->soundsource);
  7016. Msg( "%02i %s l(%03d) c(%03d) r(%03d) rl(%03d) rr(%03d) vol(%03d) pos(%6d %6d %6d) timeleft(%f) looped(%d) %50s chan:%d ent(%03d):%s\n",
  7017. total+ 1,
  7018. ch->flags.fromserver ? "SERVER" : "CLIENT",
  7019. (int)ch->fvolume[IFRONT_LEFT],
  7020. (int)ch->fvolume[IFRONT_CENTER],
  7021. (int)ch->fvolume[IFRONT_RIGHT],
  7022. (int)ch->fvolume[IREAR_LEFT],
  7023. (int)ch->fvolume[IREAR_RIGHT],
  7024. ch->master_vol,
  7025. (int)ch->origin[0],
  7026. (int)ch->origin[1],
  7027. (int)ch->origin[2],
  7028. timeleft,
  7029. bLooping,
  7030. ch->sfx->getname(nameBuf, sizeof(nameBuf)),
  7031. ch->entchannel,
  7032. ch->soundsource,
  7033. pszclassname ? pszclassname : "NULL" );
  7034. total++;
  7035. }
  7036. }
  7037. CON_COMMAND( snd_dumpclientsounds, "Dump sounds to console" )
  7038. {
  7039. S_DumpClientSounds();
  7040. // con_nprint_t np;
  7041. // np.time_to_live = 2.0f;
  7042. // np.fixed_width_font = true;
  7043. //
  7044. // int total = 0;
  7045. // char nameBuf[MAX_PATH];
  7046. //
  7047. // CChannelList list;
  7048. // g_ActiveChannels.GetActiveChannels( list );
  7049. // for ( int i = 0; i < list.Count(); i++ )
  7050. // {
  7051. // channel_t *ch = list.GetChannel(i);
  7052. // if ( !ch->sfx )
  7053. // continue;
  7054. //
  7055. // unsigned int sampleCount = RemainingSamples( ch );
  7056. // float timeleft = (float)sampleCount / (float)ch->sfx->pSource->SampleRate();
  7057. // bool bLooping = ch->sfx->pSource->IsLooped();
  7058. // const char *pszclassname = GetClientClassname(ch->soundsource);
  7059. //
  7060. // Msg( "%02i %s l(%03d) c(%03d) r(%03d) rl(%03d) rr(%03d) vol(%03d) pos(%6d %6d %6d) timeleft(%f) looped(%d) %50s chan:%d ent(%03d):%s\n",
  7061. // total+ 1,
  7062. // ch->flags.fromserver ? "SERVER" : "CLIENT",
  7063. // (int)ch->fvolume[IFRONT_LEFT],
  7064. // (int)ch->fvolume[IFRONT_CENTER],
  7065. // (int)ch->fvolume[IFRONT_RIGHT],
  7066. // (int)ch->fvolume[IREAR_LEFT],
  7067. // (int)ch->fvolume[IREAR_RIGHT],
  7068. // ch->master_vol,
  7069. // (int)ch->origin[0],
  7070. // (int)ch->origin[1],
  7071. // (int)ch->origin[2],
  7072. // timeleft,
  7073. // bLooping,
  7074. // ch->sfx->getname(nameBuf, sizeof(nameBuf)),
  7075. // ch->entchannel,
  7076. // ch->soundsource,
  7077. // pszclassname ? pszclassname : "NULL" );
  7078. //
  7079. // total++;
  7080. // }
  7081. }
  7082. ConVar snd_show_channel_count( "snd_show_channel_count", "0", FCVAR_NONE, "Show the current count of channel types." );
  7083. //-----------------------------------------------------------------------------
  7084. // Set g_soundtime to number of full samples that have been transfered out to hardware
  7085. // since start.
  7086. //-----------------------------------------------------------------------------
  7087. void DEBUG_ShowChannelCount( void )
  7088. {
  7089. if (snd_show_channel_count.GetInt() == 0)
  7090. return;
  7091. CChannelList list;
  7092. g_ActiveChannels.GetActiveChannels( list );
  7093. int nStaticNum = 0;
  7094. int nDynamicNum = 0;
  7095. for ( int i = 0; i < list.Count(); i++ )
  7096. {
  7097. int ch_idx = list.GetChannelIndex(i);
  7098. if( ch_idx < MAX_DYNAMIC_CHANNELS )
  7099. {
  7100. nDynamicNum++;
  7101. }
  7102. else
  7103. {
  7104. nStaticNum++;
  7105. }
  7106. }
  7107. if( nDynamicNum > nShowDynamicChannelMax )
  7108. {
  7109. nShowDynamicChannelMax = nDynamicNum;
  7110. }
  7111. if( nStaticNum > nShowStaticChannelMax )
  7112. {
  7113. nShowStaticChannelMax = nStaticNum;
  7114. }
  7115. int r, g, b, a;
  7116. r = g = b = 200;
  7117. a = 255;
  7118. if( nStaticNum > MAX_CHANNELS - MAX_DYNAMIC_CHANNELS - 10 )
  7119. {
  7120. r = 255;
  7121. }
  7122. char chanStr[128];
  7123. sprintf( chanStr, "STATIC CHANNEL COUNT: %i : %i", nStaticNum, nShowStaticChannelMax );
  7124. CDebugOverlay::AddScreenTextOverlay( 0.01, 0.4, 0.01, r, g, b, a, chanStr );
  7125. if( nDynamicNum > MAX_DYNAMIC_CHANNELS - 10 )
  7126. {
  7127. r = 255;
  7128. }
  7129. else
  7130. {
  7131. r = 200;
  7132. }
  7133. sprintf( chanStr, "DYNAMIC CHANNEL COUNT: %i : %i", nDynamicNum, nShowDynamicChannelMax );
  7134. CDebugOverlay::AddScreenTextOverlay( 0.01, 0.45, 0.01, r, g, b, a, chanStr );
  7135. if( nStaticNum >= MAX_CHANNELS - MAX_DYNAMIC_CHANNELS || nDynamicNum >= MAX_DYNAMIC_CHANNELS )
  7136. {
  7137. S_DumpClientSounds();
  7138. }
  7139. }
  7140. #if USE_AUDIO_DEVICE_V1
  7141. //-----------------------------------------------------------------------------
  7142. // Set g_soundtime to number of full samples that have been transfered out to hardware
  7143. // since start.
  7144. //-----------------------------------------------------------------------------
  7145. void GetSoundTime(void)
  7146. {
  7147. // Make them 64 bits so calculation is done in 64 bits.
  7148. int64 fullsamples;
  7149. int64 sampleOutCount;
  7150. // size of output buffer in *full* 16 bit samples
  7151. // A 2 channel device has a *full* sample consisting of a 16 bit LR pair.
  7152. // A 1 channel device has a *full* sample consiting of a 16 bit single sample.
  7153. fullsamples = g_AudioDevice->DeviceSampleCount() / g_AudioDevice->ChannelCount();
  7154. // NOTE: it is possible to miscount buffers if it has wrapped twice between
  7155. // calls to S_Update. However, since the output buffer size is > 1 second of sound,
  7156. // this should only occur for framerates lower than 1hz
  7157. // sampleOutCount is counted in 16 bit *full* samples, of number of samples output to hardware
  7158. // for current output buffer
  7159. sampleOutCount = g_AudioDevice->GetOutputPosition();
  7160. if ( sampleOutCount < s_oldsampleOutCount )
  7161. {
  7162. // buffer wrapped
  7163. s_buffers++;
  7164. }
  7165. s_oldsampleOutCount = sampleOutCount;
  7166. if ( cl_movieinfo.IsRecording() )
  7167. {
  7168. // in movie, just mix one frame worth of sound
  7169. float t = g_pSoundServices->GetHostTime();
  7170. if ( s_lastsoundtime != t )
  7171. {
  7172. double flSamples = (double)g_pSoundServices->GetHostFrametime() * (double)g_AudioDevice->SampleRate();
  7173. int nSamples = (int)flSamples;
  7174. double flSampleError = flSamples - (double)nSamples;
  7175. g_soundtimeerror += flSampleError;
  7176. if ( fabs( g_soundtimeerror ) > 1.0 )
  7177. {
  7178. int nErrorSamples = (int)g_soundtimeerror;
  7179. g_soundtimeerror -= (double)nErrorSamples;
  7180. nSamples += nErrorSamples;
  7181. }
  7182. g_soundtime += nSamples;
  7183. s_lastsoundtime = t;
  7184. }
  7185. }
  7186. else
  7187. {
  7188. // g_soundtime indicates how many *full* samples have actually been
  7189. // played out to dma
  7190. g_soundtime = s_buffers*fullsamples + sampleOutCount;
  7191. }
  7192. }
  7193. #endif
  7194. void S_ExtraUpdate( void )
  7195. {
  7196. if ( IsGameConsole() )
  7197. return;
  7198. if ( !g_AudioDevice || !g_pSoundServices )
  7199. return;
  7200. if ( !g_AudioDevice->IsActive() )
  7201. return;
  7202. if ( s_bOnLoadScreen )
  7203. return;
  7204. if ( snd_noextraupdate.GetInt() || cl_movieinfo.IsRecording() )
  7205. return; // don't pollute timings
  7206. // If listener position and orientation has not yet been updated (ie: no call to S_Update since level load)
  7207. // then don't mix. Important - mixing with listener at 'false' origin causes
  7208. // some sounds to incorrectly spatialize to 0 volume, killing them before they can play.
  7209. if ( !SND_IsListenerValid() )
  7210. return;
  7211. VPROF_BUDGET( "CEngineClient::Sound_ExtraUpdate()", VPROF_BUDGETGROUP_OTHER_SOUND );
  7212. // Only mix if you have used up 90% of the mixahead buffer
  7213. double tNow = Plat_FloatTime();
  7214. float delta = (tNow - g_LastMixTime);
  7215. // we know we were at least snd_mixahead seconds ahead of the output the last time we did mixing
  7216. // if we're not close to running out just exit to avoid small mix batches
  7217. if ( delta > 0 && delta < (snd_mixahead.GetFloat() * 0.9f) )
  7218. return;
  7219. g_LastMixTime = tNow;
  7220. g_pSoundServices->OnExtraUpdate();
  7221. // Shouldn't have to do any work here if your framerate hasn't dropped
  7222. S_Update_( snd_mixahead.GetFloat() );
  7223. }
  7224. extern void DEBUG_StartSoundMeasure(int type, int samplecount );
  7225. extern void DEBUG_StopSoundMeasure(int type, int samplecount );
  7226. void S_Update_Guts( float mixAheadTime )
  7227. {
  7228. VPROF( "S_Update_Guts" );
  7229. DEBUG_StartSoundMeasure(4, 0);
  7230. #if USE_AUDIO_DEVICE_V1
  7231. // Update our perception of audio time.
  7232. // 'g_soundtime' tells how many samples have
  7233. // been played out of the dma buffer since sound system startup.
  7234. // 'g_paintedtime' indicates how many samples we've actually mixed
  7235. // and sent to the dma buffer since sound system startup.
  7236. GetSoundTime();
  7237. // if ( g_soundtime > g_paintedtime )
  7238. // {
  7239. // // if soundtime > paintedtime, then the dma buffer
  7240. // // has played out more sound than we've actually
  7241. // // mixed. We need to call S_Update_ more often.
  7242. //
  7243. // DevMsg ("S_Update_ : Underflow\n");
  7244. // paintedtime = g_soundtime;
  7245. // }
  7246. // (kdb) above code doesn't handle underflow correctly
  7247. // should actually zero out the paintbuffer to advance to the new
  7248. // time.
  7249. // mix ahead of current position
  7250. int64 endtime = g_AudioDevice->PaintBegin( mixAheadTime, g_soundtime, g_paintedtime );
  7251. int samples = endtime - g_paintedtime;
  7252. samples = samples < 0 ? 0 : samples;
  7253. if ( samples )
  7254. {
  7255. THREAD_LOCK_SOUND();
  7256. DEBUG_StartSoundMeasure( 2, samples );
  7257. MIX_PaintChannels( endtime, s_bIsListenerUnderwater );
  7258. MXR_DebugShowMixVolumes();
  7259. MXR_UpdateAllDuckerVolumes();
  7260. DEBUG_ShowChannelCount( );
  7261. DEBUG_StopSoundMeasure( 2, 0 );
  7262. }
  7263. g_AudioDevice->PaintEnd();
  7264. DEBUG_StopSoundMeasure( 4, samples );
  7265. #else
  7266. THREAD_LOCK_SOUND();
  7267. uint nTotal = 0;
  7268. // compute how much audio time is queued up waiting for output
  7269. int nQueuedSamples = g_AudioDevice->QueuedBufferCount() * MIX_BUFFER_SIZE;
  7270. float flQueuedTime = nQueuedSamples * SECONDS_PER_SAMPLE;
  7271. // we want to stay "mixAheadTime" ahead of the audio buffer, how much additional audio do we need to mix?
  7272. float flNeededTime = mixAheadTime - flQueuedTime;
  7273. if ( flNeededTime > 0 )
  7274. {
  7275. // round up to the number of buffers needed to mix
  7276. int nAvailBuffers = g_AudioDevice->EmptyBufferCount();
  7277. int nMixBuffers = 1 + ( flNeededTime / (MIX_BUFFER_SIZE * SECONDS_PER_SAMPLE) );
  7278. // clamp to available buffers
  7279. nMixBuffers = Min( nMixBuffers, nAvailBuffers );
  7280. // now mix & output each buffer
  7281. for ( int i = 0; i < nMixBuffers; i++ )
  7282. {
  7283. uint nSamples = MIX_BUFFER_SIZE;
  7284. int nEndTime = g_paintedtime + nSamples;
  7285. // handle wraparound
  7286. if ( nEndTime < g_paintedtime )
  7287. {
  7288. g_paintedtime = 0;
  7289. nEndTime = nSamples;
  7290. }
  7291. nTotal += nSamples;
  7292. DEBUG_StartSoundMeasure( 2, nSamples );
  7293. MIX_PaintChannels( nEndTime, s_bIsListenerUnderwater );
  7294. MXR_DebugShowMixVolumes();
  7295. MXR_UpdateAllDuckerVolumes();
  7296. DEBUG_StopSoundMeasure( 2, 0 );
  7297. }
  7298. }
  7299. DEBUG_StopSoundMeasure( 4, nTotal );
  7300. #endif
  7301. }
  7302. #if !defined( _X360 )
  7303. #define THREADED_MIX_TIME 33
  7304. #else
  7305. #define THREADED_MIX_TIME XMA_POLL_RATE
  7306. #endif
  7307. ConVar snd_ShowThreadFrameTime( "snd_ShowThreadFrameTime", "0" );
  7308. bool g_bMixThreadExit;
  7309. ThreadHandle_t g_hMixThread;
  7310. void S_Update_Thread()
  7311. {
  7312. float frameTime = THREADED_MIX_TIME * 0.001f;
  7313. double lastFrameTime = Plat_FloatTime();
  7314. while ( !g_bMixThreadExit )
  7315. {
  7316. // mixing (for 360) needs to be updated at a steady rate
  7317. // large update times causes the mixer to demand more audio data
  7318. // the 360 decoder has finite latency and cannot fulfill spike requests
  7319. double t0 = Plat_FloatTime();
  7320. S_Update_Guts( frameTime + snd_mixahead.GetFloat() );
  7321. int updateTime = ( Plat_FloatTime() - t0 ) * 1000.0f;
  7322. // try to maintain a steadier rate by compensating for fluctuating mix times
  7323. int sleepTime = THREADED_MIX_TIME - updateTime;
  7324. if ( sleepTime > 0 )
  7325. {
  7326. ThreadSleep( sleepTime );
  7327. }
  7328. // mimic a frametime needed for sound update
  7329. double t1 = Plat_FloatTime();
  7330. frameTime = t1 - lastFrameTime;
  7331. lastFrameTime = t1;
  7332. if ( snd_ShowThreadFrameTime.GetBool() )
  7333. {
  7334. Msg( "S_Update_Thread: frameTime: %d ms\n", (int)( frameTime * 1000.0f ) );
  7335. }
  7336. }
  7337. }
  7338. void S_ShutdownMixThread()
  7339. {
  7340. if ( g_hMixThread )
  7341. {
  7342. g_bMixThreadExit = true;
  7343. ThreadJoin( g_hMixThread );
  7344. ReleaseThreadHandle( g_hMixThread );
  7345. g_hMixThread = NULL;
  7346. }
  7347. }
  7348. void StartPhononThread();
  7349. void S_Update_( float mixAheadTime )
  7350. {
  7351. if (snd_use_hrtf.GetBool())
  7352. {
  7353. StartPhononThread();
  7354. }
  7355. if ( !snd_mix_async.GetBool() )
  7356. {
  7357. S_ShutdownMixThread();
  7358. S_Update_Guts( mixAheadTime );
  7359. }
  7360. else
  7361. {
  7362. if ( !g_hMixThread )
  7363. {
  7364. g_bMixThreadExit = false;
  7365. g_hMixThread = ThreadExecuteSolo( "SndMix", S_Update_Thread );
  7366. if ( IsX360() )
  7367. {
  7368. ThreadSetAffinity( g_hMixThread, XBOX_PROCESSOR_5 );
  7369. }
  7370. }
  7371. }
  7372. }
  7373. //-----------------------------------------------------------------------------
  7374. // Threaded mixing enable. Purposely hiding enable/disable details.
  7375. //-----------------------------------------------------------------------------
  7376. void S_EnableThreadedMixing( bool bEnable )
  7377. {
  7378. if ( snd_mix_async.GetBool() != bEnable )
  7379. {
  7380. snd_mix_async.SetValue( bEnable );
  7381. }
  7382. }
  7383. /*
  7384. ===============================================================================
  7385. console functions
  7386. ===============================================================================
  7387. */
  7388. extern void DSP_DEBUGSetParams(int ipreset, int iproc, float *pvalues, int cparams);
  7389. extern void DSP_DEBUGReloadPresetFile( void );
  7390. void S_DspParms( const CCommand &args )
  7391. {
  7392. if ( args.ArgC() == 1)
  7393. {
  7394. // if dsp_parms with no arguments, reload entire preset file
  7395. DSP_DEBUGReloadPresetFile();
  7396. return;
  7397. }
  7398. if ( args.ArgC() < 4 )
  7399. {
  7400. Msg( "Usage: dsp_parms PRESET# PROC# param0 param1 ...up to param15 \n" );
  7401. return;
  7402. }
  7403. int cparam = MIN( args.ArgC() - 4, 16);
  7404. float params[16];
  7405. Q_memset( params, 0, sizeof(float) * 16 );
  7406. // get preset & proc
  7407. int idsp, iproc;
  7408. idsp = Q_atof( args[1] );
  7409. iproc = Q_atof( args[2] );
  7410. // get params
  7411. for (int i = 0; i < cparam; i++)
  7412. {
  7413. params[i] = Q_atof( args[i+4] );
  7414. }
  7415. // set up params & switch preset
  7416. DSP_DEBUGSetParams(idsp, iproc, params, cparam);
  7417. }
  7418. static ConCommand dsp_parm("dsp_reload", S_DspParms, "", FCVAR_CHEAT );
  7419. void S_Play( const char *pszName, bool flush = false )
  7420. {
  7421. int inCache;
  7422. char szName[256];
  7423. CSfxTable *pSfx;
  7424. Q_strncpy( szName, pszName, sizeof( szName ) );
  7425. if ( !Q_strrchr( pszName, '.' ) )
  7426. {
  7427. Q_strncat( szName, ".wav", sizeof( szName ), COPY_ALL_CHARACTERS );
  7428. }
  7429. pSfx = S_FindName( szName, &inCache );
  7430. if ( inCache && flush )
  7431. {
  7432. pSfx->pSource->CacheUnload();
  7433. }
  7434. int nSlot = GET_ACTIVE_SPLITSCREEN_SLOT();
  7435. StartSoundParams_t params;
  7436. params.staticsound = false;
  7437. params.soundsource = g_pSoundServices->GetViewEntity( nSlot );
  7438. params.entchannel = CHAN_REPLACE;
  7439. params.pSfx = pSfx;
  7440. params.origin = listener_origin[ nSlot ];
  7441. params.fvol = 1.0f;
  7442. params.soundlevel = SNDLVL_NONE;
  7443. params.flags = 0;
  7444. params.pitch = PITCH_NORM;
  7445. S_StartSound( params );
  7446. }
  7447. static void S_Play( const CCommand &args )
  7448. {
  7449. bool bFlush = !Q_stricmp( args[0], "playflush" );
  7450. for ( int i = 1; i < args.ArgC(); ++i )
  7451. {
  7452. S_Play( args[i], bFlush );
  7453. }
  7454. }
  7455. static void S_PlayHRTF(const CCommand& args)
  7456. {
  7457. if (args.ArgC() != 5)
  7458. {
  7459. DevMsg("Usage: play_hrtf sound x y z\n");
  7460. return;
  7461. }
  7462. char nameBuf[4096];
  7463. ::Q_snprintf(nameBuf, sizeof(nameBuf), "~%s", args[1]);
  7464. const char* pszName = nameBuf;
  7465. Vector origin;
  7466. origin[0] = Q_atof(args[2]);
  7467. origin[1] = Q_atof(args[3]);
  7468. origin[2] = Q_atof(args[4]);
  7469. int inCache;
  7470. char szName[256];
  7471. CSfxTable *pSfx;
  7472. Q_strncpy(szName, pszName, sizeof(szName));
  7473. if (!Q_strrchr(pszName, '.'))
  7474. {
  7475. Q_strncat(szName, ".wav", sizeof(szName), COPY_ALL_CHARACTERS);
  7476. }
  7477. pSfx = S_FindName(szName, &inCache);
  7478. int nSlot = GET_ACTIVE_SPLITSCREEN_SLOT();
  7479. StartSoundParams_t params;
  7480. params.staticsound = false;
  7481. params.soundsource = g_pSoundServices->GetViewEntity(nSlot);
  7482. params.entchannel = CHAN_REPLACE;
  7483. params.pSfx = pSfx;
  7484. params.origin = origin;
  7485. params.fvol = 1.0f;
  7486. params.soundlevel = SNDLVL_NONE;
  7487. params.flags = 0;
  7488. params.pitch = PITCH_NORM;
  7489. params.m_bHRTFLock = true;
  7490. params.m_bInEyeSound = false;
  7491. S_StartSound(params);
  7492. }
  7493. static void S_PlayVol( const CCommand &args )
  7494. {
  7495. static int hash=543;
  7496. float vol;
  7497. char name[256];
  7498. CSfxTable *pSfx;
  7499. for ( int i = 1; i<args.ArgC(); i += 2 )
  7500. {
  7501. if ( !Q_strrchr( args[i], '.') )
  7502. {
  7503. Q_strncpy( name, args[i], sizeof( name ) );
  7504. Q_strncat( name, ".wav", sizeof( name ), COPY_ALL_CHARACTERS );
  7505. }
  7506. else
  7507. {
  7508. Q_strncpy( name, args[i], sizeof( name ) );
  7509. }
  7510. pSfx = S_PrecacheSound( name );
  7511. vol = Q_atof( args[i+1] );
  7512. int nSlot = GET_ACTIVE_SPLITSCREEN_SLOT();
  7513. StartSoundParams_t params;
  7514. params.staticsound = false;
  7515. params.soundsource = hash++;
  7516. params.entchannel = CHAN_AUTO;
  7517. params.pSfx = pSfx;
  7518. params.origin = listener_origin[ nSlot ];
  7519. params.fvol = vol;
  7520. params.soundlevel = SNDLVL_NONE;
  7521. params.flags = 0;
  7522. params.pitch = PITCH_NORM;
  7523. S_StartSound( params );
  7524. }
  7525. }
  7526. static void S_PlayDelay( const CCommand &args )
  7527. {
  7528. if ( args.ArgC() != 3 )
  7529. {
  7530. Msg( "Usage: playdelay delay_in_msec (negative to skip ahead) soundname\n" );
  7531. return;
  7532. }
  7533. char szName[256];
  7534. CSfxTable *pSfx;
  7535. float delay = Q_atof( args[ 1 ] );
  7536. Q_strncpy(szName, args[ 2 ], sizeof( szName ) );
  7537. if ( !Q_strrchr( args[ 2 ], '.' ) )
  7538. {
  7539. Q_strncat( szName, ".wav", sizeof( szName ), COPY_ALL_CHARACTERS );
  7540. }
  7541. pSfx = S_FindName( szName, NULL );
  7542. int nSlot = GET_ACTIVE_SPLITSCREEN_SLOT();
  7543. StartSoundParams_t params;
  7544. params.staticsound = false;
  7545. params.soundsource = g_pSoundServices->GetViewEntity( nSlot );
  7546. params.entchannel = CHAN_REPLACE;
  7547. params.pSfx = pSfx;
  7548. params.origin = listener_origin[ nSlot ];
  7549. params.fvol = 1.0f;
  7550. params.soundlevel = SNDLVL_NONE;
  7551. params.flags = 0;
  7552. params.pitch = PITCH_NORM;
  7553. params.delay = delay;
  7554. S_StartSound( params );
  7555. }
  7556. static ConCommand sndplaydelay( "sndplaydelay", S_PlayDelay );
  7557. #if defined( _GAMECONSOLE )
  7558. void S_UnloadSound( const char *pName )
  7559. {
  7560. CSfxTable *pSfx = S_FindName( pName, NULL );
  7561. if ( pSfx && pSfx->pSource )
  7562. {
  7563. pSfx->pSource->CacheUnload();
  7564. delete pSfx->pSource;
  7565. pSfx->pSource = NULL;
  7566. }
  7567. }
  7568. #endif
  7569. void S_PurgeSoundsDueToLanguageChange()
  7570. {
  7571. DevMsg( "S_PurgeSoundsDueToLanguageChange()\n" );
  7572. for ( int i = s_Sounds.FirstInorder(); i != s_Sounds.InvalidIndex(); i = s_Sounds.NextInorder( i ) )
  7573. {
  7574. CSfxTable *pSfx = s_Sounds[i].pSfx;
  7575. if ( pSfx && pSfx->pSource )
  7576. {
  7577. if ( pSfx->m_bIsUISound || pSfx->m_bIsMusic )
  7578. continue;
  7579. // will skip past any prefix chars
  7580. char filename[MAX_PATH];
  7581. const char *pFilename = pSfx->GetFileName( filename, sizeof( filename ) );
  7582. if ( !pFilename )
  7583. continue;
  7584. V_FixSlashes( filename, '/' );
  7585. if ( StringHasPrefix( pFilename, "ui/" ) || StringHasPrefix( pFilename, "common/" ) || StringHasPrefix( pFilename, "music/" ) )
  7586. {
  7587. continue;
  7588. }
  7589. pSfx->pSource->CacheUnload();
  7590. delete pSfx->pSource;
  7591. pSfx->pSource = NULL;
  7592. }
  7593. }
  7594. }
  7595. static bool SortByNameLessFunc( const int &lhs, const int &rhs )
  7596. {
  7597. CSfxTable *pSfx1 = s_Sounds[lhs].pSfx;
  7598. CSfxTable *pSfx2 = s_Sounds[rhs].pSfx;
  7599. char nameBuf1[MAX_PATH];
  7600. char nameBuf2[MAX_PATH];
  7601. return CaselessStringLessThan( pSfx1->getname(nameBuf1,sizeof(nameBuf1)), pSfx2->getname(nameBuf2,sizeof(nameBuf2)) );
  7602. }
  7603. void S_SoundList(void)
  7604. {
  7605. CSfxTable *sfx;
  7606. CAudioSource *pSource;
  7607. int size, total;
  7608. char nameBuf[MAX_PATH];
  7609. total = 0;
  7610. for ( int i = s_Sounds.FirstInorder(); i != s_Sounds.InvalidIndex(); i = s_Sounds.NextInorder( i ) )
  7611. {
  7612. sfx = s_Sounds[i].pSfx;
  7613. pSource = sfx->pSource;
  7614. if ( !pSource )
  7615. continue;
  7616. size = pSource->SampleSize() * pSource->SampleCount();
  7617. total += size;
  7618. if ( pSource->IsLooped() )
  7619. {
  7620. Msg( "L" );
  7621. }
  7622. else
  7623. {
  7624. Msg( " " );
  7625. }
  7626. Msg( "(%2db) %6i : %s\n", pSource->SampleSize(), size, sfx->getname(nameBuf,sizeof(nameBuf)));
  7627. }
  7628. Msg( "Total: %.2f MB\n", (float)total/(1024.0f * 1024.0f) );
  7629. }
  7630. #if defined( _X360 ) || defined( _PS3 )
  7631. CON_COMMAND( vx_soundlist, "Dump sounds to VXConsole" )
  7632. {
  7633. CSfxTable *sfx;
  7634. CAudioSource *pSource;
  7635. int dataSize;
  7636. char *pFormatStr;
  7637. int sampleRate;
  7638. int sampleBits;
  7639. int streamed;
  7640. int looped;
  7641. int channels;
  7642. int numSamples;
  7643. int quality;
  7644. int numSounds = s_Sounds.Count();
  7645. xSoundList_t* pSoundList = new xSoundList_t[numSounds];
  7646. int i = 0;
  7647. char nameBuf[MAX_PATH];
  7648. for ( int iSrcSound=s_Sounds.FirstInorder(); iSrcSound != s_Sounds.InvalidIndex(); iSrcSound = s_Sounds.NextInorder( iSrcSound ) )
  7649. {
  7650. dataSize = -1;
  7651. sampleRate = -1;
  7652. sampleBits = -1;
  7653. pFormatStr = "???";
  7654. streamed = -1;
  7655. looped = -1;
  7656. channels = -1;
  7657. numSamples = -1;
  7658. quality = -1;
  7659. sfx = s_Sounds[iSrcSound].pSfx;
  7660. pSource = sfx->pSource;
  7661. if ( pSource && pSource->IsCached() )
  7662. {
  7663. numSamples = pSource->SampleCount();
  7664. dataSize = pSource->DataSize();
  7665. sampleRate = pSource->SampleRate();
  7666. streamed = pSource->IsStreaming();
  7667. looped = pSource->IsLooped();
  7668. channels = pSource->IsStereoWav() ? 2 : 1;
  7669. quality = pSource->GetQuality();
  7670. switch ( pSource->Format() )
  7671. {
  7672. case WAVE_FORMAT_ADPCM:
  7673. pFormatStr = "ADPCM";
  7674. sampleBits = 16;
  7675. break;
  7676. case WAVE_FORMAT_PCM:
  7677. pFormatStr = "PCM";
  7678. sampleBits = (pSource->SampleSize() * 8)/channels;
  7679. break;
  7680. case WAVE_FORMAT_XMA:
  7681. pFormatStr = "XMA";
  7682. sampleBits = 16;
  7683. break;
  7684. case WAVE_FORMAT_MP3:
  7685. case WAVE_FORMAT_TEMP:
  7686. pFormatStr = "MP3";
  7687. sampleBits = 16;
  7688. break;
  7689. default:
  7690. pFormatStr = "Unknown";
  7691. sampleBits = 16;
  7692. break;
  7693. }
  7694. }
  7695. V_strncpy( pSoundList[i].name, sfx->getname(nameBuf, sizeof(nameBuf)), sizeof( pSoundList[i].name ) );
  7696. V_strncpy( pSoundList[i].formatName, pFormatStr, sizeof( pSoundList[i].formatName ) );
  7697. pSoundList[i].rate = sampleRate;
  7698. pSoundList[i].bits = sampleBits;
  7699. pSoundList[i].channels = channels;
  7700. pSoundList[i].looped = looped;
  7701. pSoundList[i].dataSize = dataSize;
  7702. pSoundList[i].numSamples = numSamples;
  7703. pSoundList[i].streamed = streamed;
  7704. pSoundList[i].quality = quality;
  7705. ++i;
  7706. }
  7707. XBX_rSoundList( numSounds, pSoundList );
  7708. delete [] pSoundList;
  7709. }
  7710. #endif
  7711. extern unsigned g_snd_time_debug;
  7712. extern unsigned g_snd_call_time_debug;
  7713. extern unsigned g_snd_count_debug;
  7714. extern unsigned g_snd_samplecount;
  7715. extern unsigned g_snd_frametime;
  7716. extern unsigned g_snd_frametime_total;
  7717. extern int g_snd_profile_type;
  7718. // start measuring sound perf, 100 reps
  7719. // type 1 - dsp, 2 - mix, 3 - load sound, 4 - all sound
  7720. // set type via ConVar snd_profile
  7721. void DEBUG_StartSoundMeasure(int type, int samplecount )
  7722. {
  7723. if (type != g_snd_profile_type)
  7724. return;
  7725. if (samplecount)
  7726. g_snd_samplecount += samplecount;
  7727. g_snd_call_time_debug = Plat_MSTime();
  7728. }
  7729. // show sound measurement after 25 reps - show as % of total frame
  7730. // type 1 - dsp, 2 - mix, 3 - load sound, 4 - all sound
  7731. // BUGBUG: snd_profile 4 reports a lower average because it's average cost
  7732. // PER CALL and most calls (via SoundExtraUpdate()) don't do any work and
  7733. // bring the average down. If you want an average PER FRAME instead, it's generally higher.
  7734. void DEBUG_StopSoundMeasure(int type, int samplecount )
  7735. {
  7736. if (type != g_snd_profile_type)
  7737. return;
  7738. if (samplecount)
  7739. g_snd_samplecount += samplecount;
  7740. // add total time since last frame
  7741. g_snd_frametime_total += Plat_MSTime() - g_snd_frametime;
  7742. // performance timing
  7743. g_snd_time_debug += Plat_MSTime() - g_snd_call_time_debug;
  7744. if (++g_snd_count_debug >= 100)
  7745. {
  7746. switch (g_snd_profile_type)
  7747. {
  7748. case 1:
  7749. Msg("dsp: (%2.2f) millisec ", ((float)g_snd_time_debug) / 100.0);
  7750. Msg("(%2.2f) pct of frame \n", 100.0 * ((float)g_snd_time_debug) / ((float)g_snd_frametime_total));
  7751. break;
  7752. case 2:
  7753. Msg("mix+dsp:(%2.2f) millisec ", ((float)g_snd_time_debug) / 100.0);
  7754. Msg("(%2.2f) pct of frame \n", 100.0 * ((float)g_snd_time_debug) / ((float)g_snd_frametime_total));
  7755. break;
  7756. case 3:
  7757. //if ( (((float)g_snd_time_debug) / 100.0) < 0.01 )
  7758. // break;
  7759. Msg("snd load: (%2.2f) millisec ", ((float)g_snd_time_debug) / 100.0);
  7760. Msg("(%2.2f) pct of frame \n", 100.0 * ((float)g_snd_time_debug) / ((float)g_snd_frametime_total));
  7761. break;
  7762. case 4:
  7763. Msg("sound: (%2.2f) millisec ", ((float)g_snd_time_debug) / 100.0);
  7764. Msg("(%2.2f) pct of frame (%d samples) \n", 100.0 * ((float)g_snd_time_debug) / ((float)g_snd_frametime_total), g_snd_samplecount);
  7765. break;
  7766. }
  7767. g_snd_count_debug = 0;
  7768. g_snd_time_debug = 0;
  7769. g_snd_samplecount = 0;
  7770. g_snd_frametime_total = 0;
  7771. }
  7772. g_snd_frametime = Plat_MSTime();
  7773. }
  7774. #ifndef LINUX
  7775. extern ConVar dsp_room;
  7776. #endif
  7777. // speak a sentence from console; works by passing in "!sentencename"
  7778. // or "sentence"
  7779. static void S_Say( const CCommand &args )
  7780. {
  7781. #ifndef LINUX
  7782. CSfxTable *pSfx;
  7783. if ( !g_AudioDevice->IsActive() )
  7784. return;
  7785. char sound[256];
  7786. Q_strncpy( sound, args[1], sizeof( sound ) );
  7787. // DEBUG - test performance of dsp code
  7788. if ( !Q_stricmp( sound, "dsp" ) )
  7789. {
  7790. unsigned time;
  7791. int i;
  7792. int count = 10000;
  7793. int idsp;
  7794. for (i = 0; i < PAINTBUFFER_SIZE; i++)
  7795. {
  7796. g_paintbuffer[i].left = RandomInt(0,2999);
  7797. g_paintbuffer[i].right = RandomInt(0,2999);
  7798. }
  7799. Msg ("Start profiling 10,000 calls to DSP\n");
  7800. idsp = dsp_room.GetInt();
  7801. // get system time
  7802. time = Plat_MSTime();
  7803. for (i = 0; i < count; i++)
  7804. {
  7805. // SX_RoomFX(PAINTBUFFER_SIZE, TRUE, TRUE);
  7806. DSP_Process(idsp, g_paintbuffer, NULL, NULL, PAINTBUFFER_SIZE);
  7807. }
  7808. // display system time delta
  7809. Msg("%d milliseconds \n", Plat_MSTime() - time);
  7810. return;
  7811. }
  7812. if ( !Q_stricmp(sound, "paint") )
  7813. {
  7814. unsigned time;
  7815. int count = 10000;
  7816. static int hash=543;
  7817. int64 psav = g_paintedtime;
  7818. Msg ("Start profiling MIX_PaintChannels\n");
  7819. pSfx = S_PrecacheSound("ambience/labdrone1.wav");
  7820. int nSlot = GET_ACTIVE_SPLITSCREEN_SLOT();
  7821. StartSoundParams_t params;
  7822. params.staticsound = false;
  7823. params.soundsource = hash++;
  7824. params.entchannel = CHAN_AUTO;
  7825. params.pSfx = pSfx;
  7826. params.origin = listener_origin[ nSlot ];
  7827. params.fvol = 1.0f;
  7828. params.soundlevel = SNDLVL_NONE;
  7829. params.flags = 0;
  7830. params.pitch = PITCH_NORM;
  7831. S_StartSound( params );
  7832. // get system time
  7833. time = Plat_MSTime();
  7834. // paint a boatload of sound
  7835. MIX_PaintChannels( g_paintedtime + 512*count, s_bIsListenerUnderwater );
  7836. // display system time delta
  7837. Msg("%d milliseconds \n", Plat_MSTime() - time);
  7838. g_paintedtime = psav;
  7839. return;
  7840. }
  7841. // DEBUG
  7842. if ( !TestSoundChar( sound, CHAR_SENTENCE ) )
  7843. {
  7844. // build a fake sentence name, then play the sentence text
  7845. Q_strncpy(sound, "xxtestxx ", sizeof( sound ) );
  7846. Q_strncat(sound, args[1], sizeof( sound ), COPY_ALL_CHARACTERS );
  7847. int addIndex = g_Sentences.AddToTail();
  7848. sentence_t *pSentence = &g_Sentences[addIndex];
  7849. pSentence->pName = sound;
  7850. pSentence->length = 0;
  7851. // insert null terminator after sentence name
  7852. sound[8] = 0;
  7853. pSfx = S_PrecacheSound ("!xxtestxx");
  7854. if (!pSfx)
  7855. {
  7856. Msg ("S_Say: can't cache %s\n", sound);
  7857. return;
  7858. }
  7859. int nSlot = GET_ACTIVE_SPLITSCREEN_SLOT();
  7860. StartSoundParams_t params;
  7861. params.staticsound = false;
  7862. params.soundsource = g_pSoundServices->GetViewEntity( nSlot );
  7863. params.entchannel = CHAN_REPLACE;
  7864. params.pSfx = pSfx;
  7865. params.origin = vec3_origin;
  7866. params.fvol = 1.0f;
  7867. params.soundlevel = SNDLVL_NONE;
  7868. params.flags = 0;
  7869. params.pitch = PITCH_NORM;
  7870. S_StartSound ( params );
  7871. // remove last
  7872. g_Sentences.Remove( g_Sentences.Count() - 1 );
  7873. }
  7874. else
  7875. {
  7876. pSfx = S_FindName(sound, NULL);
  7877. if (!pSfx)
  7878. {
  7879. Msg ("S_Say: can't find sentence name %s\n", sound);
  7880. return;
  7881. }
  7882. int nSlot = GET_ACTIVE_SPLITSCREEN_SLOT();
  7883. StartSoundParams_t params;
  7884. params.staticsound = false;
  7885. params.soundsource = g_pSoundServices->GetViewEntity( nSlot );
  7886. params.entchannel = CHAN_REPLACE;
  7887. params.pSfx = pSfx;
  7888. params.origin = vec3_origin;
  7889. params.fvol = 1.0f;
  7890. params.soundlevel = SNDLVL_NONE;
  7891. params.flags = 0;
  7892. params.pitch = PITCH_NORM;
  7893. S_StartSound( params );
  7894. }
  7895. #endif // LINUX
  7896. }
  7897. float S_GetMono16Samples( const char *pszName, CUtlVector< short >& sampleList )
  7898. {
  7899. CSfxTable *pSfx = S_PrecacheSound( PSkipSoundChars( pszName ) );
  7900. if ( !pSfx )
  7901. return 0.0f;
  7902. CAudioSource *pWave = pSfx->pSource;
  7903. if ( !pWave )
  7904. return 0.0f;
  7905. int nType = pWave->GetType();
  7906. if ( nType != CAudioSource::AUDIO_SOURCE_WAV )
  7907. return 0.0f;
  7908. SoundError soundError;
  7909. CAudioMixer *pMixer = pWave->CreateMixer( 0, 0, false, soundError, nullptr );
  7910. if ( !pMixer )
  7911. return 0.0f;
  7912. float duration = AudioSource_GetSoundDuration( pSfx );
  7913. // Determine start/stop positions
  7914. int totalsamples = (int)( duration * pWave->SampleRate() );
  7915. if ( totalsamples <= 0 )
  7916. return 0;
  7917. bool bStereo = pWave->IsStereoWav();
  7918. int mix_sample_size = pMixer->GetMixSampleSize();
  7919. int nNumChannels = bStereo ? 2 : 1;
  7920. char *pData = NULL;
  7921. int pos = 0;
  7922. int remaining = totalsamples;
  7923. while ( remaining > 0 )
  7924. {
  7925. int blockSize = MIN( remaining, 1000 );
  7926. char copyBuf[AUDIOSOURCE_COPYBUF_SIZE];
  7927. int copied = pWave->GetOutputData( (void **)&pData, pos, blockSize, copyBuf );
  7928. if ( !copied )
  7929. {
  7930. break;
  7931. }
  7932. remaining -= copied;
  7933. pos += copied;
  7934. // Now get samples out of output data
  7935. switch ( nNumChannels )
  7936. {
  7937. default:
  7938. case 1:
  7939. {
  7940. for ( int i = 0; i < copied; ++i )
  7941. {
  7942. int offset = i * mix_sample_size;
  7943. short sample = 0;
  7944. if ( mix_sample_size == 1 )
  7945. {
  7946. char s = *( char * )( pData + offset );
  7947. // Upscale it to fit into a short
  7948. sample = s << 8;
  7949. }
  7950. else if ( mix_sample_size == 2 )
  7951. {
  7952. sample = *( short * )( pData + offset );
  7953. }
  7954. else if ( mix_sample_size == 4 )
  7955. {
  7956. // Not likely to have 4 bytes mono!!!
  7957. Assert( 0 );
  7958. int s = *( int * )( pData + offset );
  7959. sample = s >> 16;
  7960. }
  7961. else
  7962. {
  7963. Assert( 0 );
  7964. }
  7965. sampleList.AddToTail( sample );
  7966. }
  7967. }
  7968. break;
  7969. case 2:
  7970. {
  7971. for ( int i = 0; i < copied; ++i )
  7972. {
  7973. int offset = i * mix_sample_size;
  7974. short left = 0;
  7975. short right = 0;
  7976. if ( mix_sample_size == 1 )
  7977. {
  7978. // Not possible!!!, must be at least 2 bytes!!!
  7979. Assert( 0 );
  7980. char v = *( char * )( pData + offset );
  7981. left = right = ( v << 8 );
  7982. }
  7983. else if ( mix_sample_size == 2 )
  7984. {
  7985. // One byte per channel
  7986. left = (short)( ( *(char *)( pData + offset ) ) << 8 );
  7987. right = (short)( ( *(char *)( pData + offset + 1 ) ) << 8 );
  7988. }
  7989. else if ( mix_sample_size == 4 )
  7990. {
  7991. // 2 bytes per channel
  7992. left = *( short * )( pData + offset );
  7993. right = *( short * )( pData + offset + 2 );
  7994. }
  7995. else
  7996. {
  7997. Assert( 0 );
  7998. }
  7999. short sample = ( left + right ) >> 1;
  8000. sampleList.AddToTail( sample );
  8001. }
  8002. }
  8003. break;
  8004. }
  8005. }
  8006. delete pMixer;
  8007. return duration;
  8008. }
  8009. //-----------------------------------------------------------------------------
  8010. // Get left and right channel volume for a particular sound
  8011. //-----------------------------------------------------------------------------
  8012. bool S_GetSoundChannelVolume( const char* sound, float &flVolumeLeft, float &flVolumeRight )
  8013. {
  8014. THREAD_LOCK_SOUND();
  8015. char buf[MAX_PATH];
  8016. CChannelList list;
  8017. g_ActiveChannels.GetActiveChannels( list );
  8018. for ( int i = 0; i < list.Count(); i++ )
  8019. {
  8020. channel_t* ch = list.GetChannel(i);
  8021. Assert( ch->sfx );
  8022. Assert( ch->activeIndex > 0 );
  8023. ch->sfx->GetFileName( buf, MAX_PATH );
  8024. Q_FixSlashes( buf, '/' );
  8025. if ( !Q_stricmp( buf, sound ) )
  8026. {
  8027. flVolumeLeft = ch->fvolume[IFRONT_LEFT];
  8028. flVolumeRight = ch->fvolume[IFRONT_RIGHT];
  8029. return true;
  8030. }
  8031. }
  8032. return false;
  8033. }
  8034. void S_SoundSetPitchScale( float flPitchScale )
  8035. {
  8036. g_flPitchScale = flPitchScale;
  8037. }
  8038. float S_SoundGetPitchScale( void )
  8039. {
  8040. return g_flPitchScale;
  8041. }
  8042. CON_COMMAND( snd_print_channel_by_index, "Prints the content of a channel from its index. snd_print_channel_by_index <index>." )
  8043. {
  8044. if ( args.ArgC() != 2 )
  8045. {
  8046. Warning( "Incorrect usage of snd_print_channel_by_index. Pass the index from 0 to %d.\n", MAX_CHANNELS - 1 );
  8047. return;
  8048. }
  8049. int nIndex = atoi( args.Arg( 1 ) );
  8050. if ( ( nIndex < 0 ) || ( nIndex >= MAX_CHANNELS ) )
  8051. {
  8052. Warning( "Incorrect usage of snd_print_channel_by_index. Pass the index from 0 to %d.\n", MAX_CHANNELS - 1 );
  8053. return;
  8054. }
  8055. AUTO_LOCK( g_SndMutex );
  8056. channel_t *pChannel = &channels[ nIndex ];
  8057. PrintChannel( "PrintChannel", pChannel );
  8058. }
  8059. CON_COMMAND( snd_print_channel_by_guid, "Prints the content of a channel from its guid. snd_print_channel_by_guid <guid>." )
  8060. {
  8061. if ( args.ArgC() != 2 )
  8062. {
  8063. Warning( "Incorrect usage of snd_print_channel_by_guid. Pass the guid.\n" );
  8064. return;
  8065. }
  8066. int nGuid = atoi( args.Arg( 1 ) );
  8067. AUTO_LOCK( g_SndMutex );
  8068. channel_t *pChannel = NULL;
  8069. for ( int i = 0 ; i < MAX_CHANNELS ; ++i )
  8070. {
  8071. if ( channels[i].guid == nGuid )
  8072. {
  8073. pChannel = &channels[i];
  8074. break;
  8075. }
  8076. }
  8077. if ( pChannel == NULL )
  8078. {
  8079. Warning( "Could not find the channel with the guid: %d\n", nGuid );
  8080. return;
  8081. }
  8082. PrintChannel( "PrintChannel", pChannel );
  8083. }
  8084. CON_COMMAND( snd_print_channels, "Prints all the active channel.")
  8085. {
  8086. AUTO_LOCK( g_SndMutex );
  8087. int nNumActiveChannels = g_ActiveChannels.GetActiveCount();
  8088. Msg( "Total Channels: %d\n", nNumActiveChannels);
  8089. CChannelList list;
  8090. g_ActiveChannels.GetActiveChannels( list );
  8091. for ( int i = 0; i < list.Count(); i++ )
  8092. {
  8093. channel_t *pChannel = list.GetChannel(i);
  8094. if ( pChannel->sfx == NULL )
  8095. {
  8096. continue;
  8097. }
  8098. PrintChannelInfo( pChannel );
  8099. }
  8100. }
  8101. CON_COMMAND( snd_set_master_volume, "Sets the master volume for a channel. snd_set_master_volume <guid> <mastervolume>." )
  8102. {
  8103. if ( args.ArgC() != 3 )
  8104. {
  8105. Warning( "Incorrect usage of snd_set_master_volume. snd_set_master_volume <guid> <mastervolume>.\n" );
  8106. return;
  8107. }
  8108. int nGuid = atoi( args.Arg( 1 ) );
  8109. int nVolume = atoi( args.Arg( 2 ) );
  8110. AUTO_LOCK( g_SndMutex );
  8111. channel_t *pChannel = NULL;
  8112. for ( int i = 0 ; i < MAX_CHANNELS ; ++i )
  8113. {
  8114. if ( channels[i].guid == nGuid )
  8115. {
  8116. pChannel = &channels[i];
  8117. break;
  8118. }
  8119. }
  8120. if ( pChannel == NULL )
  8121. {
  8122. Warning( "Could not find the channel with the guid: %d\n", nGuid );
  8123. return;
  8124. }
  8125. // Do we have to do more than that?
  8126. pChannel->master_vol = nVolume;
  8127. }