summaryrefslogtreecommitdiff
path: root/engine/engsoundservice.cpp
blob: 079910f46d3dd48020afbbb84cec15f4c1e6647b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose: Engine implementation of services required by the audio subsystem
//
// $NoKeywords: $
//=============================================================================//

#include "quakedef.h"
#include "soundservice.h"
#include "zone.h"
#include "cdll_engine_int.h"
#include "gl_model_private.h"
#include "icliententity.h"
#include "icliententitylist.h"
#include "mouthinfo.h"
#include "host.h"
#include "vstdlib/random.h"
#include "tier0/icommandline.h"
#include "igame.h"
#include "client.h"
#include "server.h"
#include "filesystem.h"
#include "filesystem_engine.h"
#include "sound.h"
#include "vgui_controls/Controls.h"
#include "vgui/ILocalize.h"
#include "vgui_baseui_interface.h"
#include "datacache/idatacache.h"
#include "sys_dll.h"
#include "toolframework/itoolframework.h"
#include "tier0/vprof.h"
#include "cl_steamauth.h"
#include "tier1/fmtstr.h"
#include "MapReslistGenerator.h"
#include "cl_main.h"

// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"

void Snd_Restart_f();

#define MAPLIST_FILE "maplist.txt"

class CEngineSoundServices : public ISoundServices
{
public:
	CEngineSoundServices() { m_frameTime = 0; }

	virtual void *LevelAlloc( int nBytes, const char *pszTag )
	{
		return Hunk_AllocName(nBytes, pszTag);
	}

	virtual void OnExtraUpdate()
	{
		if ( IsPC() && g_ClientDLL && game && game->IsActiveApp() )
		{
			g_ClientDLL->IN_Accumulate();
		}
	}

	virtual bool GetSoundSpatialization( int entIndex, SpatializationInfo_t& info )
	{
		if ( !entitylist )
		{
			return false;
		}

		// Entity has been deleted
		IClientEntity *pClientEntity = entitylist->GetClientEntity( entIndex );
		if ( !pClientEntity )
		{
			// FIXME:  Should this assert?
			return false;
		}
		
		MDLCACHE_CRITICAL_SECTION_( g_pMDLCache );
		bool bResult = pClientEntity->GetSoundSpatialization( info );

		return bResult;
	}

	virtual bool GetToolSpatialization( int iUserData, int guid, SpatializationInfo_t& info )
	{
		if ( IsX360() )
		{
			return false;
		}

		return toolframework->GetSoundSpatialization( iUserData, guid, info );
	}

	virtual float GetClientTime()
	{
		return cl.GetTime();
	}

	// Filtered local time
	virtual float GetHostTime()
	{
		return host_time;
	}

	virtual int GetViewEntity()
	{
		return cl.m_nViewEntity;
	}

	virtual void SetSoundFrametime( float realDt, float hostDt )
	{
		extern bool IsReplayRendering();
		if ( cl_movieinfo.IsRecording() || IsReplayRendering() )
		{
			m_frameTime = hostDt;
		}
		else
		{
			m_frameTime = realDt;
		}
	}

	virtual float GetHostFrametime()
	{
		return m_frameTime;
	}

	virtual int GetServerCount()
	{
		return cl.m_nServerCount;
	}

	virtual bool IsPlayer( SoundSource source )
	{
		return ( source == cl.m_nPlayerSlot + 1 );
	}

	virtual void OnChangeVoiceStatus( int entity, bool status)
	{
		ClientDLL_VoiceStatus(entity, status);
	}

	virtual bool IsConnected() 
	{
		return cl.IsConnected();
	}

	// Calls into client .dll with list of close caption tokens to construct a caption out of
	virtual void EmitSentenceCloseCaption( char const *tokenstream )
	{
		if ( g_ClientDLL )
		{
			g_ClientDLL->EmitSentenceCloseCaption( tokenstream );
		}
	}

	virtual void EmitCloseCaption( char const *captionname, float duration )
	{
		if ( g_ClientDLL )
		{
			g_ClientDLL->EmitCloseCaption( captionname, duration );
		}
	}

	virtual char const *GetGameDir() 
	{
		return com_gamedir;
	}

	// If the game is paused, certain audio will pause, too (anything with phoneme/sentence data for now)
	virtual bool IsGamePaused()
	{
		extern IVEngineClient *engineClient;
		if ( !engineClient )
		{
			Assert( !"No engineClient, bug???" );
			return false;
		}

		return engineClient->IsPaused();
	}
	
	virtual bool IsGameActive()
	{
		extern IVEngineClient *engineClient;
		if ( !engineClient )
		{
			Assert( !"No engineClient, bug???" );
			return true;
		}

		return engineClient->IsActiveApp();
	}

	virtual void RestartSoundSystem()
	{
		Snd_Restart_f();
	}

	virtual void GetAllManifestFiles( CUtlRBTree< FileNameHandle_t, int >& list )
	{
		list.RemoveAll();

		// Load them in
		FileHandle_t resfilehandle = g_pFileSystem->Open( MAPLIST_FILE, "rb", "MOD" );
		if ( FILESYSTEM_INVALID_HANDLE != resfilehandle )
		{
			// Read in and parse mapcycle.txt
			int length = g_pFileSystem->Size(resfilehandle);
			if ( length > 0 )
			{
				char *pStart = (char *)new char[ length + 1 ];
				if ( pStart && ( length == g_pFileSystem->Read(pStart, length, resfilehandle) )
				   )
				{
					pStart[ length ] = 0;
					const char *pFileList = pStart;

					while ( 1 )
					{
						pFileList = COM_Parse( pFileList );
						if ( strlen( com_token ) <= 0 )
							break;

						char manifest_file[ 512 ];
						Q_snprintf( manifest_file, sizeof( manifest_file ), "%s/%s.manifest", AUDIOSOURCE_CACHE_ROOTDIR, com_token );

						if ( g_pFileSystem->FileExists( manifest_file, "MOD" ) )
						{
							FileNameHandle_t handle = g_pFileSystem->FindOrAddFileName( manifest_file );
							if ( list.Find( handle ) == list.InvalidIndex() )
							{
								list.Insert( handle );
							}
						}

						// Any more tokens on this line?
						while ( COM_TokenWaiting( pFileList ) )
						{
							pFileList = COM_Parse( pFileList );
						}
					}
				}
				delete[] pStart;
			}

			g_pFileSystem->Close(resfilehandle);
		}
		else
		{
			Warning( "GetAllManifestFiles:  Unable to load %s\n", MAPLIST_FILE );
		}
	}

	virtual void GetAllSoundFilesInManifest( CUtlRBTree< FileNameHandle_t, int >& list, char const *manifestfile )
	{
		list.RemoveAll();
		CacheSoundsFromResFile( true, list, manifestfile, false );
	}

	virtual void GetAllSoundFilesReferencedInReslists( CUtlRBTree< FileNameHandle_t, int >& list )
	{
		char reslistdir[ MAX_PATH ];
		Q_strncpy( reslistdir, MapReslistGenerator().GetResListDirectory(), sizeof( reslistdir ) );
		list.RemoveAll();

		// Load them in
		FileHandle_t resfilehandle = g_pFileSystem->Open( MAPLIST_FILE, "rb", "MOD" );
		if ( FILESYSTEM_INVALID_HANDLE != resfilehandle )
		{
			// Read in and parse mapcycle.txt
			int length = g_pFileSystem->Size(resfilehandle);
			if ( length > 0 )
			{
				char *pStart = (char *)new char[ length + 1 ];
				if ( pStart && ( length == g_pFileSystem->Read(pStart, length, resfilehandle) )
				   )
				{
					pStart[ length ] = 0;
					const char *pFileList = pStart;

					while ( 1 )
					{
						char resfile[ 512 ];

						pFileList = COM_Parse( pFileList );
						if ( strlen( com_token ) <= 0 )
							break;

						Q_snprintf( resfile, sizeof( resfile ), "%s\\%s.lst", reslistdir, com_token );

						CacheSoundsFromResFile( false, list, resfile );

						// Any more tokens on this line?
						while ( COM_TokenWaiting( pFileList ) )
						{
							pFileList = COM_Parse( pFileList );
						}
					}
				}
				delete[] pStart;
			}

			g_pFileSystem->Close(resfilehandle);

			CacheSoundsFromResFile( false, list, CFmtStr( "%s\\engine.lst", reslistdir ) );
			CacheSoundsFromResFile( false, list, CFmtStr( "%s\\all.lst", reslistdir ) );
		}
		else
		{
			Warning( "GetAllSoundFilesReferencedInReslists:  Unable to load file %s\n", MAPLIST_FILE );
		}
	}

	virtual void CacheBuildingStart()
	{
		if ( IsX360() )
		{
			return;
		}

		EngineVGui()->ActivateGameUI();
		EngineVGui()->StartCustomProgress();
		const wchar_t *str = g_pVGuiLocalize->Find( "#Valve_CreatingCache" );
		if ( str )
		{
			EngineVGui()->UpdateCustomProgressBar( 0.0f, str );
		}
	}

	virtual void CacheBuildingUpdateProgress( float percent, char const *cachefile )
	{
		if ( IsX360() )
		{
			return;
		}

		const wchar_t *format = g_pVGuiLocalize->Find( "Valve_CreatingSpecificSoundCache" );
		if ( format )
		{
			wchar_t constructed[ 1024 ];
			wchar_t file[ 256 ];
			g_pVGuiLocalize->ConvertANSIToUnicode( cachefile, file, sizeof( file ) );

			g_pVGuiLocalize->ConstructString_safe( 
				constructed, 
				( wchar_t * )format,
				1,
				file );

			EngineVGui()->UpdateCustomProgressBar( percent, constructed );
		}
	}

	virtual void CacheBuildingFinish()
	{
		if ( IsX360() )
		{
			return;
		}

		EngineVGui()->FinishCustomProgress();
		EngineVGui()->HideGameUI();
	}

	virtual int GetPrecachedSoundCount()
	{
		if ( !sv.IsActive() )
			return 0;

		INetworkStringTable *table = sv.GetSoundPrecacheTable();
		if ( !table )
			return 0;

		return table->GetNumStrings();
	}

	virtual char const *GetPrecachedSound( int index )
	{
		Assert( sv.IsActive() );

		INetworkStringTable *table = sv.GetSoundPrecacheTable();
		if ( !table )
			return "";

		return table->GetString( index );
	}

	virtual bool ShouldSuppressNonUISounds()
	{
		return EngineVGui()->IsGameUIVisible() || IsGamePaused();
	}

	virtual char const *GetUILanguage()
	{
		extern ConVar cl_language;
		return cl_language.GetString();
	}

private:

	float m_frameTime;

	void CacheSoundsFromResFile( bool quiet, CUtlRBTree< FileNameHandle_t, int >& list, char const *resfile, bool checkandcleanname = true )
	{
		if ( !g_pFileSystem->FileExists( resfile, "MOD" ) )
		{
			Warning( "CacheSoundsFromResFile:  Unable to find '%s'\n", resfile );
			return;
		}

		int oldCount = list.Count();

		FileHandle_t resfilehandle = g_pFileSystem->Open( resfile, "rb", "MOD" );
		if ( FILESYSTEM_INVALID_HANDLE != resfilehandle )
		{
			// Read in and parse mapcycle.txt
			int length = g_pFileSystem->Size(resfilehandle);
			if ( length > 0 )
			{
				char *pStart = (char *)new char[ length + 1 ];
				if ( pStart && ( length == g_pFileSystem->Read(pStart, length, resfilehandle) )
				   )
				{
					pStart[ length ] = 0;
					const char *pFileList = pStart;

					while ( 1 )
					{
						pFileList = COM_Parse( pFileList );
						if ( strlen( com_token ) <= 0 )
							break;

						if ( checkandcleanname )
						{
							if ( Q_stristr( com_token, ".wav" ) ||
								 Q_stristr( com_token, ".mp3" ) )
							{
								// skip past the game/mod directory		   "hl2/sound/player/footstep.wav"
								Q_FixSlashes(com_token);				// "hl2\sound\player\footstep.wav"
								const char *pName = com_token;
								while (pName[0] && pName[0] != CORRECT_PATH_SEPARATOR)
								{
									pName++;
								}										// "\sound\player\footstep.wav"
								FileNameHandle_t handle = g_pFileSystem->FindOrAddFileName( pName+1 );   // "sound\player\footstep.wav"
								if ( list.Find( handle ) == list.InvalidIndex() )
								{
									list.Insert( handle );
								}
							}
						}
						else
						{
							FileNameHandle_t handle = g_pFileSystem->FindOrAddFileName( com_token );
							if ( list.Find( handle ) == list.InvalidIndex() )
							{
								list.Insert( handle );
							}
						}
					}
				}
				delete[] pStart;
			}

			g_pFileSystem->Close(resfilehandle);
		}

		int newCount = list.Count();

		if ( !quiet )
		{
			Msg( "Processing (%i new) from %s\n", newCount - oldCount, resfile );
		}
	}

	virtual void OnSoundStarted( int guid, StartSoundParams_t& params, char const *soundname )
	{
		VPROF("OnSoundStarted");

		if ( IsX360() || !toolframework->IsToolRecording() || params.suppressrecording )
			return;

		KeyValues *msg = new KeyValues( "StartSound" );
		msg->SetInt( "guid", guid );
		msg->SetFloat( "time", cl.GetTime() );
		msg->SetInt( "staticsound", params.staticsound ? 1 : 0 );
		msg->SetInt( "soundsource", params.soundsource );
		msg->SetInt( "entchannel", params.entchannel );
		msg->SetString( "soundname", soundname );
		msg->SetFloat( "originx", params.origin.x );
		msg->SetFloat( "originy", params.origin.y );
		msg->SetFloat( "originz", params.origin.z );
		msg->SetFloat( "directionx", params.direction.x );
		msg->SetFloat( "directiony", params.direction.y );
		msg->SetFloat( "directionz", params.direction.z );
		msg->SetInt( "updatepositions", params.bUpdatePositions );
		msg->SetFloat( "fvol", params.fvol );
		msg->SetInt( "soundlevel", (int)params.soundlevel );
		msg->SetInt( "flags", params.flags );
		msg->SetInt( "pitch", params.pitch );
		msg->SetInt( "specialdsp", params.specialdsp );
		msg->SetInt( "fromserver", params.fromserver ? 1 : 0 );
		msg->SetFloat( "delay", params.delay );
		msg->SetInt( "speakerentity", params.speakerentity );

		toolframework->PostMessage( msg );

		msg->deleteThis();
	}

	virtual void OnSoundStopped( int guid, int soundsource, int channel, char const *soundname )
	{
		// NOTE: At the moment, if we don't receive a StartSound message but we do
		// receive a StopSound message, the StopSound message is ignored. In a perfect
		// world, if the StartSound message was not sent, a StopSound message should not
		// be sent for that guid either. This requires more plumbing, though, and
		// for the moment, it's not necessary to do that plumbing.

		VPROF("OnSoundStopped");

		if ( IsX360() || !toolframework->IsToolRecording() )
			return;

		KeyValues *msg = new KeyValues( "StopSound" );
		msg->SetInt( "guid", guid );
		msg->SetFloat( "time", cl.GetTime() );
		msg->SetInt( "soundsource", soundsource );
		msg->SetInt( "entchannel", channel );
		msg->SetString( "soundname", soundname );

		toolframework->PostMessage( msg );

		msg->deleteThis();
	}
};


static CEngineSoundServices g_EngineSoundServices;
ISoundServices *g_pSoundServices = &g_EngineSoundServices;