]> icculus.org git repositories - divverent/darkplaces.git/blob - snd_dma.c
added graphics options menu and put realtime lighting stuff in it
[divverent/darkplaces.git] / snd_dma.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 See the GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18
19 */
20 // snd_dma.c -- main control for any streaming sound output device
21
22 #include "quakedef.h"
23
24 #ifdef USE_DSOUND
25 #include <windows.h>
26 #include <dsound.h>
27 extern DWORD gSndBufSize;
28 extern LPDIRECTSOUND pDS;
29 extern LPDIRECTSOUNDBUFFER pDSBuf;
30 #endif
31
32 #include "snd_ogg.h"
33
34
35 void S_Play(void);
36 void S_PlayVol(void);
37 void S_Play2(void);
38 void S_SoundList(void);
39 void S_Update_();
40 void S_StopAllSounds(qboolean clear);
41 void S_StopAllSoundsC(void);
42
43 void S_ClearBuffer (void);
44
45
46 // =======================================================================
47 // Internal sound data & structures
48 // =======================================================================
49
50 channel_t channels[MAX_CHANNELS];
51 unsigned int total_channels;
52
53 int snd_blocked = 0;
54 cvar_t snd_initialized = { CVAR_READONLY, "snd_initialized", "0"};
55 cvar_t snd_streaming = { CVAR_SAVE, "snd_streaming", "1"};
56
57 // pointer should go away
58 volatile dma_t *shm = 0;
59 volatile dma_t sn;
60
61 vec3_t listener_vieworigin;
62 vec3_t listener_viewforward;
63 vec3_t listener_viewleft;
64 vec3_t listener_viewup;
65 vec_t sound_nominal_clip_dist=1000.0;
66 mempool_t *snd_mempool;
67
68 // sample PAIRS
69 int soundtime;
70 int paintedtime;
71
72
73 //LordHavoc: increased the client sound limit from 512 to 4096 for the Nehahra movie
74 #define MAX_SFX 4096
75 sfx_t *known_sfx; // allocated [MAX_SFX]
76 int num_sfx;
77
78 sfx_t *ambient_sfx[NUM_AMBIENTS];
79
80 int sound_started = 0;
81
82 cvar_t bgmvolume = {CVAR_SAVE, "bgmvolume", "1"};
83 cvar_t volume = {CVAR_SAVE, "volume", "0.7"};
84 cvar_t snd_staticvolume = {CVAR_SAVE, "snd_staticvolume", "1"};
85
86 cvar_t nosound = {0, "nosound", "0"};
87 cvar_t snd_precache = {0, "snd_precache", "1"};
88 cvar_t bgmbuffer = {0, "bgmbuffer", "4096"};
89 cvar_t ambient_level = {0, "ambient_level", "0.3"};
90 cvar_t ambient_fade = {0, "ambient_fade", "100"};
91 cvar_t snd_noextraupdate = {0, "snd_noextraupdate", "0"};
92 cvar_t snd_show = {0, "snd_show", "0"};
93 cvar_t _snd_mixahead = {CVAR_SAVE, "_snd_mixahead", "0.1"};
94 cvar_t snd_swapstereo = {CVAR_SAVE, "snd_swapstereo", "0"};
95
96
97 // ====================================================================
98 // User-setable variables
99 // ====================================================================
100
101
102 //
103 // Fake dma is a synchronous faking of the DMA progress used for
104 // isolating performance in the renderer.  The fakedma_updates is
105 // number of times S_Update() is called per second.
106 //
107
108 qboolean fakedma = false;
109 int fakedma_updates = 15;
110
111
112 void S_SoundInfo_f(void)
113 {
114         if (!sound_started || !shm)
115         {
116                 Con_Print("sound system not started\n");
117                 return;
118         }
119
120         Con_Printf("%5d stereo\n", shm->format.channels - 1);
121         Con_Printf("%5d samples\n", shm->samples);
122         Con_Printf("%5d samplepos\n", shm->samplepos);
123         Con_Printf("%5d samplebits\n", shm->format.width * 8);
124         Con_Printf("%5d speed\n", shm->format.speed);
125         Con_Printf("%p dma buffer\n", shm->buffer);
126         Con_Printf("%5u total_channels\n", total_channels);
127 }
128
129 void S_UnloadSounds(void)
130 {
131         int i;
132         for (i = 0;i < num_sfx;i++)
133                 S_UnloadSound(known_sfx + i);
134 }
135
136 void S_LoadSounds(void)
137 {
138         int i;
139         for (i = 0;i < num_sfx;i++)
140                 S_LoadSound(known_sfx + i, false);
141 }
142
143 void S_Startup(void)
144 {
145         if (!snd_initialized.integer)
146                 return;
147
148         shm = &sn;
149         memset((void *)shm, 0, sizeof(*shm));
150
151 // create a piece of DMA memory
152
153         if (fakedma)
154         {
155                 shm->format.width = 2;
156                 shm->format.speed = 22050;
157                 shm->format.channels = 2;
158                 shm->samples = 32768;
159                 shm->samplepos = 0;
160                 shm->buffer = Mem_Alloc(snd_mempool, shm->format.channels * shm->samples * shm->format.width);
161         }
162         else
163         {
164                 if (!SNDDMA_Init())
165                 {
166                         Con_Print("S_Startup: SNDDMA_Init failed.\n");
167                         sound_started = 0;
168                         shm = NULL;
169                         return;
170                 }
171         }
172
173         sound_started = 1;
174
175         Con_DPrintf("Sound sampling rate: %i\n", shm->format.speed);
176
177         //S_LoadSounds();
178
179         S_StopAllSounds(true);
180 }
181
182 void S_Shutdown(void)
183 {
184         if (!sound_started)
185                 return;
186
187         //S_UnloadSounds();
188
189         if (fakedma)
190                 Mem_Free(shm->buffer);
191         else
192                 SNDDMA_Shutdown();
193
194         shm = NULL;
195         sound_started = 0;
196 }
197
198 void S_Restart_f(void)
199 {
200         S_Shutdown();
201         S_Startup();
202 }
203
204 /*
205 ================
206 S_Init
207 ================
208 */
209 void S_Init(void)
210 {
211         Con_DPrint("\nSound Initialization\n");
212
213         Cvar_RegisterVariable(&volume);
214         Cvar_RegisterVariable(&bgmvolume);
215         Cvar_RegisterVariable(&snd_staticvolume);
216
217         if (COM_CheckParm("-nosound") || COM_CheckParm("-safe"))
218                 return;
219
220         snd_mempool = Mem_AllocPool("sound");
221
222         if (COM_CheckParm("-simsound"))
223                 fakedma = true;
224
225         Cmd_AddCommand("play", S_Play);
226         Cmd_AddCommand("play2", S_Play2);
227         Cmd_AddCommand("playvol", S_PlayVol);
228         Cmd_AddCommand("stopsound", S_StopAllSoundsC);
229         Cmd_AddCommand("soundlist", S_SoundList);
230         Cmd_AddCommand("soundinfo", S_SoundInfo_f);
231         Cmd_AddCommand("snd_restart", S_Restart_f);
232
233         Cvar_RegisterVariable(&nosound);
234         Cvar_RegisterVariable(&snd_precache);
235         Cvar_RegisterVariable(&snd_initialized);
236         Cvar_RegisterVariable(&snd_streaming);
237         Cvar_RegisterVariable(&bgmbuffer);
238         Cvar_RegisterVariable(&ambient_level);
239         Cvar_RegisterVariable(&ambient_fade);
240         Cvar_RegisterVariable(&snd_noextraupdate);
241         Cvar_RegisterVariable(&snd_show);
242         Cvar_RegisterVariable(&_snd_mixahead);
243         Cvar_RegisterVariable(&snd_swapstereo); // LordHavoc: for people with backwards sound wiring
244
245         Cvar_SetValueQuick(&snd_initialized, true);
246
247         known_sfx = Mem_Alloc(snd_mempool, MAX_SFX*sizeof(sfx_t));
248         num_sfx = 0;
249
250         SND_InitScaletable ();
251
252         ambient_sfx[AMBIENT_WATER] = S_PrecacheSound ("ambience/water1.wav", false, true);
253         ambient_sfx[AMBIENT_SKY] = S_PrecacheSound ("ambience/wind2.wav", false, true);
254
255         total_channels = MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS;   // no statics
256         memset(channels, 0, MAX_CHANNELS * sizeof(channel_t));
257
258         OGG_OpenLibrary ();
259 }
260
261
262 // =======================================================================
263 // Load a sound
264 // =======================================================================
265
266 /*
267 =========
268 S_GetCached
269
270 =========
271 */
272 sfx_t *S_GetCached (const char *name, qboolean stdpath)
273 {
274         char namebuffer [MAX_QPATH];
275         size_t len;
276         int i;
277
278         if (!snd_initialized.integer)
279                 return NULL;
280
281         if (!name)
282                 Host_Error("S_GetCached: NULL");
283
284         // Add the default sound directory to the path
285         len = snprintf (namebuffer, sizeof (namebuffer), stdpath ? "sound/%s" : "%s", name);
286         if (len >= sizeof (namebuffer))
287                 Host_Error ("S_GetCached: sound name too long (%s)", name);
288
289         for(i = 0;i < num_sfx;i++)
290                 if(!strcmp(known_sfx[i].name, namebuffer))
291                         return &known_sfx[i];
292
293         return NULL;
294 }
295
296 /*
297 ==================
298 S_FindName
299
300 ==================
301 */
302 sfx_t *S_FindName (const char *name, qboolean stdpath)
303 {
304         sfx_t *sfx;
305
306         if (!snd_initialized.integer)
307                 return NULL;
308
309         sfx = S_GetCached (name, stdpath);
310
311         // If we haven't allocated a sfx_t struct for it yet
312         if (sfx == NULL)
313         {
314                 if (num_sfx == MAX_SFX)
315                         Sys_Error ("S_FindName: out of sfx_t");
316
317                 sfx = &known_sfx[num_sfx++];
318                 memset (sfx, 0, sizeof(*sfx));
319                 snprintf (sfx->name, sizeof (sfx->name), stdpath ? "sound/%s" : "%s", name);
320         }
321         return sfx;
322 }
323
324
325 /*
326 ==================
327 S_TouchSound
328
329 ==================
330 */
331 void S_TouchSound (const char *name, qboolean stdpath)
332 {
333         sfx_t *sfx;
334
335         sfx = S_FindName (name, stdpath);
336
337         // Set the "used" flag for this sound
338         if (sfx != NULL)
339                 sfx->flags |= SFXFLAG_USED;
340 }
341
342
343 /*
344 ==================
345 S_ClearUsed
346
347 Reset the "used" flag of all precached sounds
348 ==================
349 */
350 void S_ClearUsed (void)
351 {
352         int i;
353
354         for (i = 0; i < num_sfx; i++)
355                 known_sfx[i].flags &= ~SFXFLAG_USED;
356 }
357
358
359 /*
360 ==================
361 S_PurgeUnused
362
363 Free all precached sounds without the "used" flag
364 ==================
365 */
366 void S_PurgeUnused (void)
367 {
368         int i;
369         sfx_t *sfx;
370
371         for (i = 0; i < num_sfx; i++)
372         {
373                 sfx = &known_sfx[i];
374                 if (! (sfx->flags & SFXFLAG_USED))
375                         S_UnloadSound (sfx);
376         }
377 }
378
379
380 /*
381 ==================
382 S_PrecacheSound
383
384 ==================
385 */
386 sfx_t *S_PrecacheSound (const char *name, qboolean complain, qboolean stdpath)
387 {
388         sfx_t *sfx;
389
390         if (!snd_initialized.integer)
391                 return NULL;
392
393         sfx = S_FindName (name, stdpath);
394
395         if (!nosound.integer && snd_precache.integer)
396                 S_LoadSound(sfx, complain);
397
398         return sfx;
399 }
400
401
402 //=============================================================================
403
404 /*
405 =================
406 SND_PickChannel
407
408 Picks a channel based on priorities, empty slots, number of channels
409 =================
410 */
411 channel_t *SND_PickChannel(int entnum, int entchannel)
412 {
413         int ch_idx;
414         int first_to_die;
415         int life_left;
416         channel_t* ch;
417
418 // Check for replacement sound, or find the best one to replace
419         first_to_die = -1;
420         life_left = 0x7fffffff;
421         for (ch_idx=NUM_AMBIENTS ; ch_idx < NUM_AMBIENTS + MAX_DYNAMIC_CHANNELS ; ch_idx++)
422         {
423                 ch = &channels[ch_idx];
424                 if (entchannel != 0             // channel 0 never overrides
425                 && ch->entnum == entnum
426                 && (ch->entchannel == entchannel || entchannel == -1) )
427                 {       // always override sound from same entity
428                         first_to_die = ch_idx;
429                         break;
430                 }
431
432                 // don't let monster sounds override player sounds
433                 if (ch->entnum == cl.viewentity && entnum != cl.viewentity && ch->sfx)
434                         continue;
435
436                 // don't override looped sounds
437                 if ((ch->flags & CHANNELFLAG_FORCELOOP) != 0 ||
438                         (ch->sfx != NULL && ch->sfx->loopstart >= 0))
439                         continue;
440
441                 if (ch->end - paintedtime < life_left)
442                 {
443                         life_left = ch->end - paintedtime;
444                         first_to_die = ch_idx;
445                 }
446         }
447
448         if (first_to_die == -1)
449                 return NULL;
450
451         if (channels[first_to_die].sfx)
452                 channels[first_to_die].sfx = NULL;
453
454         return &channels[first_to_die];
455 }
456
457 /*
458 =================
459 SND_Spatialize
460
461 Spatializes a channel
462 =================
463 */
464 void SND_Spatialize(channel_t *ch, int isstatic)
465 {
466         vec_t dist, scale, pan;
467         vec3_t source_vec;
468
469         // anything coming from the view entity will always be full volume
470         // LordHavoc: make sounds with ATTN_NONE have no spatialization
471         if (ch->entnum == cl.viewentity || ch->dist_mult == 0)
472         {
473                 ch->leftvol = ch->master_vol;
474                 ch->rightvol = ch->master_vol;
475         }
476         else
477         {
478                 // update sound origin if we know about the entity
479                 if (ch->entnum > 0 && cls.state == ca_connected && cl_entities[ch->entnum].state_current.active)
480                 {
481                         //Con_Printf("-- entnum %i origin %f %f %f neworigin %f %f %f\n", ch->entnum, ch->origin[0], ch->origin[1], ch->origin[2], cl_entities[ch->entnum].state_current.origin[0], cl_entities[ch->entnum].state_current.origin[1], cl_entities[ch->entnum].state_current.origin[2]);
482                         VectorCopy(cl_entities[ch->entnum].state_current.origin, ch->origin);
483                         if (cl_entities[ch->entnum].state_current.modelindex && cl.model_precache[cl_entities[ch->entnum].state_current.modelindex]->soundfromcenter)
484                                 VectorMAMAM(1.0f, ch->origin, 0.5f, cl.model_precache[cl_entities[ch->entnum].state_current.modelindex]->normalmins, 0.5f, cl.model_precache[cl_entities[ch->entnum].state_current.modelindex]->normalmaxs, ch->origin);
485                 }
486
487                 // calculate stereo seperation and distance attenuation
488                 VectorSubtract(ch->origin, listener_vieworigin, source_vec);
489                 dist = VectorNormalizeLength(source_vec);
490                 // distance
491                 scale = ch->master_vol * (1.0 - (dist * ch->dist_mult));
492                 // panning
493                 pan = scale * DotProduct(listener_viewleft, source_vec);
494                 // calculate the volumes
495                 ch->leftvol = (int) (scale + pan);
496                 ch->rightvol = (int) (scale - pan);
497         }
498
499         // LordHavoc: allow adjusting volume of static sounds
500         if (isstatic)
501         {
502                 ch->leftvol *= snd_staticvolume.value;
503                 ch->rightvol *= snd_staticvolume.value;
504         }
505
506         // clamp volumes
507         ch->leftvol = bound(0, ch->leftvol, 255);
508         ch->rightvol = bound(0, ch->rightvol, 255);
509 }
510
511
512 // =======================================================================
513 // Start a sound effect
514 // =======================================================================
515
516 int S_StartSound(int entnum, int entchannel, sfx_t *sfx, vec3_t origin, float fvol, float attenuation)
517 {
518         channel_t *target_chan, *check;
519         int             vol;
520         int             ch_idx;
521         size_t  skip;
522
523         if (!sound_started || !sfx || !sfx->fetcher || nosound.integer)
524                 return -1;
525
526         vol = fvol*255;
527
528 // pick a channel to play on
529         target_chan = SND_PickChannel(entnum, entchannel);
530         if (!target_chan)
531                 return -1;
532
533 // spatialize
534         memset (target_chan, 0, sizeof(*target_chan));
535         VectorCopy(origin, target_chan->origin);
536         target_chan->dist_mult = attenuation / sound_nominal_clip_dist;
537         target_chan->master_vol = vol;
538         target_chan->entnum = entnum;
539         target_chan->entchannel = entchannel;
540         SND_Spatialize(target_chan, false);
541
542         // LordHavoc: spawn the sound anyway because the player might teleport to it
543         //if (!target_chan->leftvol && !target_chan->rightvol)
544         //      return;         // not audible at all
545
546         // new channel
547         if (!S_LoadSound (sfx, true))
548         {
549                 target_chan->sfx = NULL;
550                 return -1;              // couldn't load the sound's data
551         }
552
553         target_chan->sfx = sfx;
554         target_chan->flags = CHANNELFLAG_NONE;
555         target_chan->pos = 0.0;
556         target_chan->end = paintedtime + sfx->total_length;
557         target_chan->lastptime = paintedtime;
558
559 // if an identical sound has also been started this frame, offset the pos
560 // a bit to keep it from just making the first one louder
561         check = &channels[NUM_AMBIENTS];
562         for (ch_idx=NUM_AMBIENTS ; ch_idx < NUM_AMBIENTS + MAX_DYNAMIC_CHANNELS ; ch_idx++, check++)
563         {
564                 if (check == target_chan)
565                         continue;
566                 if (check->sfx == sfx && !check->pos)
567                 {
568                         // LordHavoc: fixed skip calculations
569                         skip = 0.1 * sfx->format.speed;
570                         if (skip > sfx->total_length)
571                                 skip = sfx->total_length;
572                         if (skip > 0)
573                                 skip = rand() % skip;
574                         target_chan->pos += skip;
575                         target_chan->end -= skip;
576                         break;
577                 }
578         }
579
580         return (target_chan - channels);
581 }
582
583 void S_StopChannel (unsigned int channel_ind)
584 {
585         channel_t *ch;
586
587         if (channel_ind >= total_channels)
588                 return;
589
590         ch = &channels[channel_ind];
591         if (ch->sfx != NULL)
592         {
593                 if (ch->sfx->fetcher != NULL)
594                 {
595                         snd_fetcher_end_t fetcher_end = ch->sfx->fetcher->end;
596                         if (fetcher_end != NULL)
597                                 fetcher_end (ch);
598                 }
599                 ch->sfx = NULL;
600         }
601         ch->end = 0;
602 }
603
604 void S_PauseChannel (unsigned int channel_ind, qboolean toggle)
605 {
606         if (toggle)
607                 channels[channel_ind].flags |= CHANNELFLAG_PAUSED;
608         else
609                 channels[channel_ind].flags &= ~CHANNELFLAG_PAUSED;
610 }
611
612 void S_LoopChannel (unsigned int channel_ind, qboolean toggle)
613 {
614         if (toggle)
615                 channels[channel_ind].flags |= CHANNELFLAG_FORCELOOP;
616         else
617                 channels[channel_ind].flags &= ~CHANNELFLAG_FORCELOOP;
618 }
619
620 void S_StopSound(int entnum, int entchannel)
621 {
622         unsigned int i;
623
624         for (i = 0; i < MAX_DYNAMIC_CHANNELS; i++)
625                 if (channels[i].entnum == entnum && channels[i].entchannel == entchannel)
626                 {
627                         S_StopChannel (i);
628                         return;
629                 }
630 }
631
632 void S_StopAllSounds(qboolean clear)
633 {
634         unsigned int i;
635
636         for (i = 0; i < total_channels; i++)
637                 S_StopChannel (i);
638
639         total_channels = MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS;   // no statics
640         memset(channels, 0, MAX_CHANNELS * sizeof(channel_t));
641
642         if (clear)
643                 S_ClearBuffer();
644 }
645
646 void S_StopAllSoundsC(void)
647 {
648         S_StopAllSounds(true);
649 }
650
651 void S_PauseGameSounds (void)
652 {
653         unsigned int i;
654
655         for (i = 0; i < total_channels; i++)
656         {
657                 channel_t *ch;
658
659                 ch = &channels[i];
660                 if (ch->sfx != NULL && ! (ch->flags & CHANNELFLAG_LOCALSOUND))
661                         ch->flags |= CHANNELFLAG_PAUSED;
662         }
663 }
664
665 void S_ResumeGameSounds (void)
666 {
667         unsigned int i;
668
669         for (i = 0; i < total_channels; i++)
670         {
671                 channel_t *ch;
672
673                 ch = &channels[i];
674                 if (ch->sfx != NULL && ! (ch->flags & CHANNELFLAG_LOCALSOUND))
675                         ch->flags &= ~CHANNELFLAG_PAUSED;
676         }
677 }
678
679 void S_SetChannelVolume (unsigned int ch_ind, float fvol)
680 {
681         channels[ch_ind].master_vol = fvol * 255;
682 }
683
684
685 void S_ClearBuffer(void)
686 {
687         int             clear;
688
689         if (!sound_started || !shm)
690                 return;
691
692         if (shm->format.width == 1)
693                 clear = 0x80;
694         else
695                 clear = 0;
696
697 #ifdef USE_DSOUND
698         if (pDSBuf)
699         {
700                 DWORD   dwSize;
701                 DWORD   *pData;
702                 int             reps;
703                 HRESULT hresult;
704
705                 reps = 0;
706
707                 while ((hresult = pDSBuf->lpVtbl->Lock(pDSBuf, 0, gSndBufSize, (LPVOID*)&pData, &dwSize, NULL, NULL, 0)) != DS_OK)
708                 {
709                         if (hresult != DSERR_BUFFERLOST)
710                         {
711                                 Con_Print("S_ClearBuffer: DS::Lock Sound Buffer Failed\n");
712                                 S_Shutdown ();
713                                 return;
714                         }
715
716                         if (++reps > 10000)
717                         {
718                                 Con_Print("S_ClearBuffer: DS: couldn't restore buffer\n");
719                                 S_Shutdown ();
720                                 return;
721                         }
722                 }
723
724                 memset(pData, clear, shm->samples * shm->format.width);
725
726                 pDSBuf->lpVtbl->Unlock(pDSBuf, pData, dwSize, NULL, 0);
727
728         }
729         else
730 #endif
731         if (shm->buffer)
732         {
733                 int             setsize = shm->samples * shm->format.width;
734                 char    *buf = shm->buffer;
735
736                 while (setsize--)
737                         *buf++ = clear;
738
739 // on i586/i686 optimized versions of glibc, glibc *wrongly* IMO,
740 // reads the memory area before writing to it causing a seg fault
741 // since the memory is PROT_WRITE only and not PROT_READ|PROT_WRITE
742 //              memset(shm->buffer, clear, shm->samples * shm->samplebits/8);
743         }
744 }
745
746
747 /*
748 =================
749 S_StaticSound
750 =================
751 */
752 void S_StaticSound (sfx_t *sfx, vec3_t origin, float vol, float attenuation)
753 {
754         channel_t       *ss;
755
756         if (!sfx)
757                 return;
758
759         if (total_channels == MAX_CHANNELS)
760         {
761                 Con_Print("total_channels == MAX_CHANNELS\n");
762                 return;
763         }
764
765         if (!S_LoadSound (sfx, true))
766                 return;
767
768         if (sfx->loopstart == -1)
769                 Con_DPrintf("Quake compatibility warning: Static sound \"%s\" is not looped\n", sfx->name);
770
771         ss = &channels[total_channels++];
772         memset(ss, 0, sizeof(*ss));
773         ss->flags = CHANNELFLAG_FORCELOOP;
774         ss->sfx = sfx;
775         VectorCopy (origin, ss->origin);
776         ss->master_vol = vol;
777         ss->dist_mult = (attenuation/64) / sound_nominal_clip_dist;
778         ss->end = paintedtime + sfx->total_length;
779         ss->lastptime = paintedtime;
780
781         SND_Spatialize (ss, true);
782 }
783
784
785 //=============================================================================
786
787 /*
788 ===================
789 S_UpdateAmbientSounds
790 ===================
791 */
792 void S_UpdateAmbientSounds (void)
793 {
794         float           vol;
795         int                     ambient_channel;
796         channel_t       *chan;
797         qbyte           ambientlevels[NUM_AMBIENTS];
798
799         // LordHavoc: kill ambient sounds until proven otherwise
800         for (ambient_channel = 0 ; ambient_channel < NUM_AMBIENTS;ambient_channel++)
801                 channels[ambient_channel].sfx = NULL;
802
803         if (ambient_level.value <= 0 || !cl.worldmodel || !cl.worldmodel->brush.AmbientSoundLevelsForPoint)
804                 return;
805
806         cl.worldmodel->brush.AmbientSoundLevelsForPoint(cl.worldmodel, listener_vieworigin, ambientlevels, sizeof(ambientlevels));
807
808 // calc ambient sound levels
809         for (ambient_channel = 0 ; ambient_channel< NUM_AMBIENTS ; ambient_channel++)
810         {
811                 if (ambient_sfx[ambient_channel] &&
812                         (ambient_sfx[ambient_channel]->flags & SFXFLAG_SILENTLYMISSING))
813                         continue;
814                 chan = &channels[ambient_channel];
815                 chan->flags |= CHANNELFLAG_FORCELOOP;
816                 chan->sfx = ambient_sfx[ambient_channel];
817
818                 vol = ambient_level.value * ambientlevels[ambient_channel];
819                 if (vol < 8)
820                         vol = 0;
821
822         // don't adjust volume too fast
823                 if (chan->master_vol < vol)
824                 {
825                         chan->master_vol += host_realframetime * ambient_fade.value;
826                         if (chan->master_vol > vol)
827                                 chan->master_vol = vol;
828                 }
829                 else if (chan->master_vol > vol)
830                 {
831                         chan->master_vol -= host_realframetime * ambient_fade.value;
832                         if (chan->master_vol < vol)
833                                 chan->master_vol = vol;
834                 }
835
836                 chan->leftvol = chan->rightvol = chan->master_vol;
837         }
838 }
839
840
841 /*
842 ============
843 S_Update
844
845 Called once each time through the main loop
846 ============
847 */
848 void S_Update(vec3_t origin, vec3_t forward, vec3_t left, vec3_t up)
849 {
850         unsigned int i, j, total;
851         channel_t *ch, *combine;
852
853         if (!snd_initialized.integer || (snd_blocked > 0))
854                 return;
855
856         VectorCopy(origin, listener_vieworigin);
857         VectorCopy(forward, listener_viewforward);
858         VectorCopy(left, listener_viewleft);
859         VectorCopy(up, listener_viewup);
860
861 // update general area ambient sound sources
862         S_UpdateAmbientSounds ();
863
864         combine = NULL;
865
866 // update spatialization for static and dynamic sounds
867         ch = channels+NUM_AMBIENTS;
868         for (i=NUM_AMBIENTS ; i<total_channels; i++, ch++)
869         {
870                 if (!ch->sfx)
871                         continue;
872                 SND_Spatialize(ch, i >= MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS);         // respatialize channel
873                 if (!ch->leftvol && !ch->rightvol)
874                         continue;
875
876         // try to combine static sounds with a previous channel of the same
877         // sound effect so we don't mix five torches every frame
878
879                 if (i > MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS)
880                 {
881                 // see if it can just use the last one
882                         if (combine && combine->sfx == ch->sfx)
883                         {
884                                 combine->leftvol += ch->leftvol;
885                                 combine->rightvol += ch->rightvol;
886                                 ch->leftvol = ch->rightvol = 0;
887                                 continue;
888                         }
889                 // search for one
890                         combine = channels+MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS;
891                         for (j=MAX_DYNAMIC_CHANNELS + NUM_AMBIENTS ; j<i; j++, combine++)
892                                 if (combine->sfx == ch->sfx)
893                                         break;
894
895                         if (j == total_channels)
896                                 combine = NULL;
897                         else
898                         {
899                                 if (combine != ch)
900                                 {
901                                         combine->leftvol += ch->leftvol;
902                                         combine->rightvol += ch->rightvol;
903                                         ch->leftvol = ch->rightvol = 0;
904                                 }
905                                 continue;
906                         }
907                 }
908         }
909
910 //
911 // debugging output
912 //
913         if (snd_show.integer)
914         {
915                 total = 0;
916                 ch = channels;
917                 for (i=0 ; i<total_channels; i++, ch++)
918                         if (ch->sfx && (ch->leftvol || ch->rightvol) )
919                                 total++;
920
921                 Con_Printf("----(%u)----\n", total);
922         }
923
924 // mix some sound
925         S_Update_();
926 }
927
928 void GetSoundtime(void)
929 {
930         int             samplepos;
931         static  int             buffers;
932         static  int             oldsamplepos;
933         int             fullsamples;
934
935         fullsamples = shm->samples / shm->format.channels;
936
937 // it is possible to miscount buffers if it has wrapped twice between
938 // calls to S_Update.  Oh well.
939         samplepos = SNDDMA_GetDMAPos();
940
941         if (samplepos < oldsamplepos)
942         {
943                 buffers++;                                      // buffer wrapped
944
945                 if (paintedtime > 0x40000000)
946                 {       // time to chop things off to avoid 32 bit limits
947                         buffers = 0;
948                         paintedtime = fullsamples;
949                         S_StopAllSounds (true);
950                 }
951         }
952         oldsamplepos = samplepos;
953
954         soundtime = buffers * fullsamples + samplepos / shm->format.channels;
955 }
956
957 void IN_Accumulate (void);
958
959 void S_ExtraUpdate (void)
960 {
961
962 #ifdef USE_DSOUND
963         IN_Accumulate ();
964 #endif
965
966         if (snd_noextraupdate.integer)
967                 return;         // don't pollute timings
968         S_Update_();
969 }
970
971 void S_Update_(void)
972 {
973         unsigned        endtime;
974         int                             samps;
975
976         if (!sound_started || (snd_blocked > 0))
977                 return;
978
979 // Updates DMA time
980         GetSoundtime();
981
982 // check to make sure that we haven't overshot
983         if (paintedtime < soundtime)
984                 paintedtime = soundtime;
985
986 // mix ahead of current position
987         endtime = soundtime + _snd_mixahead.value * shm->format.speed;
988         samps = shm->samples >> (shm->format.channels - 1);
989         if (endtime > (unsigned int)(soundtime + samps))
990                 endtime = soundtime + samps;
991
992 #ifdef USE_DSOUND
993 // if the buffer was lost or stopped, restore it and/or restart it
994         {
995                 DWORD   dwStatus;
996
997                 if (pDSBuf)
998                 {
999                         if (pDSBuf->lpVtbl->GetStatus (pDSBuf, &dwStatus) != DS_OK)
1000                                 Con_Print("Couldn't get sound buffer status\n");
1001
1002                         if (dwStatus & DSBSTATUS_BUFFERLOST)
1003                                 pDSBuf->lpVtbl->Restore (pDSBuf);
1004
1005                         if (!(dwStatus & DSBSTATUS_PLAYING))
1006                                 pDSBuf->lpVtbl->Play(pDSBuf, 0, 0, DSBPLAY_LOOPING);
1007                 }
1008         }
1009 #endif
1010
1011         S_PaintChannels (endtime);
1012
1013         SNDDMA_Submit ();
1014 }
1015
1016 /*
1017 ===============================================================================
1018
1019 console functions
1020
1021 ===============================================================================
1022 */
1023
1024 static void S_Play_Common(float fvol, float attenuation)
1025 {
1026         int     i, ch_ind;
1027         char name[256];
1028         sfx_t   *sfx;
1029
1030         i = 1;
1031         while (i<Cmd_Argc())
1032         {
1033                 if (!strrchr(Cmd_Argv(i), '.'))
1034                         snprintf(name, sizeof(name), "%s.wav", Cmd_Argv(i));
1035                 else
1036                         strlcpy(name, Cmd_Argv(i), sizeof(name));
1037                 sfx = S_PrecacheSound(name, true, true);
1038
1039                 // If we need to get the volume from the command line
1040                 if (fvol == -1.0f)
1041                 {
1042                         fvol = atof(Cmd_Argv(i+1));
1043                         i += 2;
1044                 }
1045                 else
1046                         i++;
1047
1048                 ch_ind = S_StartSound(-1, 0, sfx, listener_vieworigin, fvol, attenuation);
1049                 if (ch_ind >= 0)
1050                         channels[ch_ind].flags |= CHANNELFLAG_LOCALSOUND;
1051         }
1052 }
1053
1054 void S_Play(void)
1055 {
1056         S_Play_Common (1.0f, 1.0f);
1057 }
1058
1059 void S_Play2(void)
1060 {
1061         S_Play_Common (1.0f, 0.0f);
1062 }
1063
1064 void S_PlayVol(void)
1065 {
1066         S_Play_Common (-1.0f, 0.0f);
1067 }
1068
1069 void S_SoundList(void)
1070 {
1071         int             i;
1072         sfx_t   *sfx;
1073         int             size, total;
1074
1075         total = 0;
1076         for (sfx=known_sfx, i=0 ; i<num_sfx ; i++, sfx++)
1077         {
1078                 if (sfx->fetcher != NULL)
1079                 {
1080                         size = sfx->mempool->totalsize;
1081                         total += size;
1082                         Con_Printf ("%c%c(%2db, %6s) %8i : %s\n",
1083                                                 (sfx->loopstart >= 0) ? 'L' : ' ',
1084                                                 (sfx->flags & SFXFLAG_STREAMED) ? 'S' : ' ',
1085                                                 sfx->format.width * 8,
1086                                                 (sfx->format.channels == 2) ? "stereo" : "mono",
1087                                                 size,
1088                                                 sfx->name);
1089                 }
1090         }
1091         Con_Printf("Total resident: %i\n", total);
1092 }
1093
1094
1095 void S_LocalSound (const char *sound, qboolean stdpath)
1096 {
1097         sfx_t   *sfx;
1098         int             ch_ind;
1099
1100         if (!snd_initialized.integer || nosound.integer)
1101                 return;
1102
1103         sfx = S_PrecacheSound (sound, true, stdpath);
1104         if (!sfx)
1105         {
1106                 Con_Printf("S_LocalSound: can't precache %s\n", sound);
1107                 return;
1108         }
1109
1110         ch_ind = S_StartSound (cl.viewentity, -1, sfx, vec3_origin, 1, 1);
1111         if (ch_ind >= 0)
1112                 channels[ch_ind].flags |= CHANNELFLAG_LOCALSOUND;
1113 }