Debian Codegraph @

src/cdogs/sounds.c

raw symbols SCIP
1 /*
2 C-Dogs SDL
3 A port of the legendary (and fun) action/arcade cdogs.
4 Copyright (C) 1995 Ronny Wester
5 Copyright (C) 2003 Jeremy Chin
6 Copyright (C) 2003-2007 Lucas Martin-King
7
8 This program is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
12
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with this program; if not, write to the Free Software
20 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21
22 This file incorporates work covered by the following copyright and
23 permission notice:
24
25 Copyright (c) 2013-2017, 2019-2020, 2023 Cong Xu
26 All rights reserved.
27
28 Redistribution and use in source and binary forms, with or without
29 modification, are permitted provided that the following conditions are met:
30
31 Redistributions of source code must retain the above copyright notice, this
32 list of conditions and the following disclaimer.
33 Redistributions in binary form must reproduce the above copyright notice,
34 this list of conditions and the following disclaimer in the documentation
35 and/or other materials provided with the distribution.
36
37 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
38 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
39 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
40 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
41 LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
42 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
43 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
44 INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
45 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
46 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
47 POSSIBILITY OF SUCH DAMAGE.
48 */
49 #include "sounds.h"
50
51 #include <ctype.h>
52 #include <math.h>
53 #include <memory.h>
54 #include <stdio.h>
55 #include <stdlib.h>
56 #include <string.h>
57 #include <sys/stat.h>
58
59 #include <SDL.h>
60
61 #include <tinydir/tinydir.h>
62
63 #include "algorithms.h"
64 #include "files.h"
65 #include "log.h"
66 #include "map.h"
67 #include "music.h"
68 #include "vector.h"
69
70 SoundDevice gSoundDevice;
71
72 int OpenAudio(int frequency, Uint16 format, int channels, int chunkSize)
73 {
74 int qFrequency;
75 Uint16 qFormat;
76 int qChannels;
77
78 if (Mix_OpenAudioDevice(frequency, format, channels, chunkSize, NULL, 0) !=
79 0)
80 {
81 printf("Couldn't open audio!: %s\n", SDL_GetError());
82 return 1;
83 }
84
85 // Check that we got the specs we wanted
86 #ifndef __EMSCRIPTEN__
87 Mix_QuerySpec(&qFrequency, &qFormat, &qChannels);
88 if (qFrequency != frequency || qFormat != format || qChannels != channels)
89 {
90 printf("Audio not what we want.\n");
91 return 1;
92 }
93 #endif
94
95 return 0;
96 }
97
98 static Mix_Chunk *LoadSound(const char *path);
99 static void SoundLoad(map_t sounds, const char *name, const char *path)
100 {
101 // If the sound basename is a number, it is part of a group of random
102 // sounds
103 char basename[CDOGS_FILENAME_MAX];
104 PathGetBasenameWithoutExtension(basename, name);
105 char nameNoExt[CDOGS_PATH_MAX];
106 PathGetWithoutExtension(nameNoExt, name);
107 bool isNumber = true;
108 for (const char *c = basename; *c != '\0'; c++)
109 {
110 if (!isdigit(*c))
111 {
112 isNumber = false;
113 break;
114 }
115 }
116 if (isNumber)
117 {
118 // Sound is random
119 // Only add the 0 number
120 const int n = atoi(basename);
121 if (n != 0)
122 {
123 return;
124 }
125 SoundData *sound;
126 CCALLOC(sound, sizeof *sound);
127 sound->Type = SOUND_RANDOM;
128 CArrayInit(&sound->u.random.sounds, sizeof(Mix_Chunk *));
129 // Remove "0.<ext>" from path
130 const char *ext = StrGetFileExt(path);
131 const int len = (int)(ext - path - 2);
132 char fmt[CDOGS_FILENAME_MAX];
133 strncpy(fmt, path, len);
134 // Create format string path/to/sound/%d.<ext>
135 sprintf(fmt + len, "%%d.%s", ext);
136 for (int i = 0;; i++)
137 {
138 char buf[CDOGS_PATH_MAX];
139 sprintf(buf, fmt, i);
140 Mix_Chunk *data = LoadSound(buf);
141 if (data == NULL)
142 break;
143 CArrayPushBack(&sound->u.random.sounds, &data);
144 }
145 // Remove "/0" from name and add
146 *strrchr(nameNoExt, '/') = '\0';
147 SoundAdd(sounds, nameNoExt, sound);
148 }
149 else
150 {
151 Mix_Chunk *data = LoadSound(path);
152 if (data != NULL)
153 {
154 SoundData *sound;
155 CMALLOC(sound, sizeof *sound);
156 sound->Type = SOUND_NORMAL;
157 sound->u.normal = data;
158 SoundAdd(sounds, nameNoExt, sound);
159 }
160 }
161 }
162 static Mix_Chunk *LoadSound(const char *path)
163 {
164 // Only load sounds from known extensions
165 const char *ext = strrchr(path, '.');
166 if (ext == NULL ||
167 !(strcmp(ext, ".ogg") == 0 || strcmp(ext, ".OGG") == 0 ||
168 strcmp(ext, ".wav") == 0 || strcmp(ext, ".WAV") == 0 ||
169 strcmp(ext, ".mp3") == 0 || strcmp(ext, ".MP3") == 0))
170 {
171 return NULL;
172 }
173 LOG(LM_MAIN, LL_TRACE, "loading sound file %s", path);
174 return Mix_LoadWAV(path);
175 }
176 static void SoundDataTerminate(any_t data);
177 void SoundAdd(map_t sounds, const char *name, SoundData *sound)
178 {
179 const int error = hashmap_put(sounds, name, sound);
180 if (error != MAP_OK)
181 {
182 LOG(LM_MAIN, LL_ERROR, "failed to add sound %s: %d", name, error);
183 SoundDataTerminate((any_t)sound);
184 }
185 }
186
187 void SoundInitialize(SoundDevice *device, const char *path)
188 {
189 memset(device, 0, sizeof *device);
190 SoundReopen(device);
191
192 device->sounds = hashmap_new();
193 device->customSounds = hashmap_new();
194 char buf[CDOGS_PATH_MAX];
195 GetDataFilePath(buf, path);
196 SoundLoadDir(device->sounds, buf, NULL);
197 MusicPlayerInit(&device->music);
198 }
199 void SoundLoadDir(map_t sounds, const char *path, const char *prefix)
200 {
201 if (sounds == NULL)
202 {
203 return;
204 }
205 tinydir_dir dir;
206 if (tinydir_open(&dir, path) == -1)
207 {
208 if (errno != ENOENT)
209 {
210 LOG(LM_MAIN, LL_ERROR, "Cannot open sound dir '%s': %s", path,
211 strerror(errno));
212 }
213 goto bail;
214 }
215 for (; dir.has_next; tinydir_next(&dir))
216 {
217 tinydir_file file;
218 if (tinydir_readfile(&dir, &file) == -1)
219 {
220 LOG(LM_MAIN, LL_ERROR, "Cannot read sound file '%s'", file.path);
221 continue;
222 }
223 if (file.name[0] == '.')
224 {
225 continue;
226 }
227 char buf[CDOGS_PATH_MAX];
228 if (prefix != NULL)
229 {
230 sprintf(buf, "%s/%s", prefix, file.name);
231 }
232 else
233 {
234 strcpy(buf, file.name);
235 }
236 if (file.is_reg)
237 {
238 SoundLoad(sounds, buf, file.path);
239 }
240 else if (file.is_dir)
241 {
242 SoundLoadDir(sounds, file.path, buf);
243 }
244 }
245
246 bail:
247 tinydir_close(&dir);
248 }
249
250 static void SoundClose(SoundDevice *s, const bool waitForSoundsComplete)
251 {
252 if (!s->isInitialised)
253 {
254 return;
255 }
256
257 if (waitForSoundsComplete)
258 {
259 Uint32 waitStart = SDL_GetTicks();
260 while (Mix_Playing(-1) > 0 && SDL_GetTicks() - waitStart < 1000)
261 ;
262 // Don't stop the music unless we're reopening
263 MusicStop(&s->music);
264 }
265 while (Mix_Init(0))
266 {
267 Mix_Quit();
268 }
269 Mix_CloseAudio();
270 }
271
272 void SoundReconfigure(SoundDevice *s)
273 {
274 s->isInitialised = false;
275 s->music.isInitialised = false;
276
277 if (Mix_AllocateChannels(s->channels) != s->channels)
278 {
279 printf("Couldn't allocate channels!\n");
280 return;
281 }
282
283 const int sVol = ConfigGetInt(&gConfig, "Sound.SoundVolume");
284 Mix_Volume(-1, sVol);
285 const int mVol = ConfigGetInt(&gConfig, "Sound.MusicVolume");
286 Mix_VolumeMusic(mVol);
287 MusicSetPlaying(&s->music, mVol > 0);
288
289 s->isInitialised = true;
290 s->music.isInitialised = true;
291 }
292
293 void SoundReopen(SoundDevice *s)
294 {
295 SoundClose(s, false);
296 if (OpenAudio(CDOGS_SND_RATE, CDOGS_SND_FMT, CDOGS_SND_CHANNELS, 1024) !=
297 0)
298 {
299 return;
300 }
301
302 s->channels = 64;
303 SoundReconfigure(s);
304 }
305
306 void SoundClear(map_t sounds)
307 {
308 hashmap_clear(sounds, SoundDataTerminate);
309 }
310 void SoundTerminate(SoundDevice *device, const bool waitForSoundsComplete)
311 {
312 SoundClose(device, waitForSoundsComplete);
313
314 hashmap_destroy(device->sounds, SoundDataTerminate);
315 hashmap_destroy(device->customSounds, SoundDataTerminate);
316
317 MusicPlayerTerminate(&device->music);
318 }
319 static void SoundDataTerminate(any_t data)
320 {
321 SoundData *s = data;
322 switch (s->Type)
323 {
324 case SOUND_NORMAL:
325 Mix_FreeChunk(s->u.normal);
326 break;
327 case SOUND_RANDOM:
328 CA_FOREACH(Mix_Chunk *, chunk, s->u.random.sounds)
329 Mix_FreeChunk(*chunk);
330 CA_FOREACH_END()
331 CArrayTerminate(&s->u.random.sounds);
332 break;
333 default:
334 CASSERT(false, "Unknown sound data type");
335 break;
336 }
337 CFREE(s);
338 }
339
340 #define OUT_OF_SIGHT_DISTANCE_PLUS 100
341 static int GetChannel(SoundDevice *s, Mix_Chunk *data);
342 static void MuffleEffect(int chan, void *stream, int len, void *udata)
343 {
344 UNUSED(chan);
345 UNUSED(udata);
346 const int channels = 2;
347 const int chunk = channels * 2;
348 for (int i = 0; i < len / chunk - 2; i++)
349 {
350 int16_t *samples = (int16_t *)((char *)stream + i * chunk);
351 samples[0] = (samples[0] + samples[2] + samples[4]) / 3;
352 samples[1] = (samples[1] + samples[3] + samples[5]) / 3;
353 }
354 }
355 static void SetSoundEffect(
356 const int channel, const Sint16 bearingDegrees, const Uint8 distance,
357 const bool isMuffled);
358 static void SoundPlayAtPosition(
359 SoundDevice *device, Mix_Chunk *data, const struct vec2 dp,
360 const bool isMuffled)
361 {
362 if (!device->isInitialised || data == NULL)
363 {
364 return;
365 }
366
367 int distance = 0;
368 Sint16 bearingDegrees = 0;
369 const float screen = (float)gGraphicsDevice.cachedConfig.Res.x;
370 const float halfScreen = screen / 2;
371 if (!svec2_is_zero(dp))
372 {
373 // Calculate distance and bearing
374 // Sound position is calculated from an imaginary camera that's half as
375 // distant from the centre of the screen as the screen width, i.e.
376 //
377 // centre-+
378 // v
379 // Screen: |------+------|
380 // |
381 // |
382 // camera---> +
383 // Calculate real distance using Pythagoras
384 const float d = svec2_length(dp);
385 // Scale so that sounds more than a full screen from centre have
386 // maximum distance (255)
387 const float maxDistance =
388 sqrtf(screen * screen + halfScreen * halfScreen);
389 distance = (int)(d * 255 / maxDistance);
390
391 // Calculate bearing
392 const double bearing = atan((double)dp.x / halfScreen);
393 bearingDegrees = (Sint16)(bearing * 180 / MPI);
394 if (bearingDegrees < 0)
395 {
396 bearingDegrees += 360;
397 }
398 }
399 if (isMuffled)
400 {
401 distance += OUT_OF_SIGHT_DISTANCE_PLUS;
402 }
403 // Don't play anything if it's too distant
404 // This means we don't waste sound channels
405 if (distance > 255)
406 {
407 return;
408 }
409
410 LOG(LM_SOUND, LL_TRACE, "distance(%d) bearing(%d)", distance,
411 bearingDegrees);
412
413 // Get sound channel to play sound
414 const int channel = GetChannel(device, data);
415 if (channel < 0)
416 {
417 return;
418 }
419
420 SetSoundEffect(channel, bearingDegrees, (Uint8)distance, isMuffled);
421 }
422 static int GetChannel(SoundDevice *s, Mix_Chunk *data)
423 {
424 for (;;)
425 {
426 const int channel = Mix_PlayChannel(-1, data, 0);
427 if (channel >= 0 || s->channels > 128)
428 {
429 return channel;
430 }
431 // Check if we cannot play the sound; allocate more channels
432 s->channels *= 2;
433 if (Mix_AllocateChannels(s->channels) != s->channels)
434 {
435 LOG(LM_SOUND, LL_ERROR, "Cannot allocate channels");
436 return -1;
437 }
438 // When allocating new channels, need to reset their volume
439 Mix_Volume(-1, ConfigGetInt(&gConfig, "Sound.SoundVolume"));
440 }
441 }
442 static void SetSoundEffect(
443 const int channel, const Sint16 bearingDegrees, const Uint8 distance,
444 const bool isMuffled)
445 {
446 #ifndef __EMSCRIPTEN__
447 Mix_SetPosition(channel, bearingDegrees, (Uint8)distance);
448 if (isMuffled)
449 {
450 if (!Mix_RegisterEffect(channel, MuffleEffect, NULL, NULL))
451 {
452 fprintf(stderr, "Mix_RegisterEffect: %s\n", Mix_GetError());
453 }
454 }
455 #else
456 // Mix_SetPosition and Mix_RegisterEffect not supported by emscripten;
457 // use plain panning instead
458
459 // Calculate left/right channel as values from 0-180
460 int left;
461 if (bearingDegrees < 90)
462 left = 90 - bearingDegrees;
463 else if (bearingDegrees < 270)
464 left = bearingDegrees - 90;
465 else
466 left = 450 - bearingDegrees;
467 const int right = 180 - left;
468 Mix_SetPanning(
469 channel, (Uint8)(left * distance / 180),
470 (Uint8)(right * distance / 180));
471 #endif
472 }
473
474 void SoundPlay(SoundDevice *device, Mix_Chunk *data)
475 {
476 if (!device->isInitialised)
477 {
478 return;
479 }
480
481 SoundPlayAtPosition(device, data, svec2_zero(), false);
482 }
483
484 void SoundSetEar(const bool isLeft, const int idx, const struct vec2 pos)
485 {
486 if (isLeft)
487 {
488 if (idx == 0)
489 {
490 gSoundDevice.earLeft1 = pos;
491 }
492 else
493 {
494 gSoundDevice.earLeft2 = pos;
495 }
496 }
497 else
498 {
499 if (idx == 0)
500 {
501 gSoundDevice.earRight1 = pos;
502 }
503 else
504 {
505 gSoundDevice.earRight2 = pos;
506 }
507 }
508 }
509
510 void SoundSetEarsSide(const bool isLeft, const struct vec2 pos)
511 {
512 SoundSetEar(isLeft, 0, pos);
513 SoundSetEar(isLeft, 1, pos);
514 }
515
516 void SoundSetEars(const struct vec2 pos)
517 {
518 SoundSetEarsSide(true, pos);
519 SoundSetEarsSide(false, pos);
520 }
521
522 void SoundPlayAt(SoundDevice *device, Mix_Chunk *data, const struct vec2 pos)
523 {
524 SoundPlayAtPlusDistance(device, data, pos, 0);
525 }
526
527 static bool IsPosNoSee(void *data, struct vec2i pos)
528 {
529 const Tile *t = MapGetTile(data, Vec2iToTile(pos));
530 return t != NULL && TileIsOpaque(t);
531 }
532 void SoundPlayAtPlusDistance(
533 SoundDevice *device, Mix_Chunk *data, const struct vec2 pos,
534 const int plusDistance)
535 {
536 if (device == NULL || !device->isInitialised)
537 {
538 return;
539 }
540 struct vec2 closestLeftEar, closestRightEar;
541
542 // Find closest set of ears to the sound
543 if (svec2_distance_squared(pos, device->earLeft1) <
544 svec2_distance_squared(pos, device->earLeft2))
545 {
546 closestLeftEar = device->earLeft1;
547 }
548 else
549 {
550 closestLeftEar = device->earLeft2;
551 }
552 if (svec2_distance_squared(pos, device->earRight1) <
553 svec2_distance_squared(pos, device->earRight2))
554 {
555 closestRightEar = device->earRight1;
556 }
557 else
558 {
559 closestRightEar = device->earRight2;
560 }
561
562 const struct vec2 origin = CalcClosestPointOnLineSegmentToPoint(
563 closestLeftEar, closestRightEar, pos);
564 bool isMuffled = false;
565 // Don't bother checking muffled if the distance is really close
566 // This is for player's own sounds like footsteps
567 if (svec2_distance_squared(pos, origin) > SQUARED(TILE_WIDTH))
568 {
569 HasClearLineData lineData;
570 lineData.IsBlocked = IsPosNoSee;
571 lineData.data = &gMap;
572 if (!HasClearLineJMRaytrace(
573 svec2i_assign_vec2(pos), svec2i_assign_vec2(origin),
574 &lineData))
575 {
576 isMuffled = true;
577 }
578 }
579 const struct vec2 dp = svec2_subtract(pos, origin);
580 SoundPlayAtPosition(
581 &gSoundDevice, data, svec2(dp.x, fabsf(dp.y) + plusDistance),
582 isMuffled);
583 }
584
585 static Mix_Chunk *SoundDataGet(SoundData *s);
586 Mix_Chunk *StrSound(const char *s)
587 {
588 if (s == NULL || strlen(s) == 0 || !gSoundDevice.isInitialised)
589 {
590 return NULL;
591 }
592 SoundData *sound;
593 int error = hashmap_get(gSoundDevice.customSounds, s, (any_t *)&sound);
594 if (error == MAP_OK)
595 {
596 return SoundDataGet(sound);
597 }
598 error = hashmap_get(gSoundDevice.sounds, s, (any_t *)&sound);
599 if (error == MAP_OK)
600 {
601 return SoundDataGet(sound);
602 }
603 return NULL;
604 }
605 static Mix_Chunk *SoundDataGet(SoundData *s)
606 {
607 switch (s->Type)
608 {
609 case SOUND_NORMAL:
610 return s->u.normal;
611 case SOUND_RANDOM:
612 if (s->u.random.sounds.size == 0)
613 {
614 return NULL;
615 }
616 else
617 {
618 // Don't get the last sound used
619 int idx = s->u.random.lastPlayed;
620 while ((int)s->u.random.sounds.size > 1 &&
621 idx == s->u.random.lastPlayed)
622 {
623 idx = rand() % s->u.random.sounds.size;
624 }
625 Mix_Chunk **sound = CArrayGet(&s->u.random.sounds, idx);
626 s->u.random.lastPlayed = idx;
627 return *sound;
628 }
629 default:
630 CASSERT(false, "Unknown sound data type");
631 return NULL;
632 }
633 }