Print the found file entries after sorting
[openal-soft.git] / examples / almultireverb.c
bloba90b3368d4ac1a633bdf5f0757d771ba9ea18937
1 /*
2 * OpenAL Multi-Zone Reverb Example
4 * Copyright (c) 2018 by Chris Robinson <chris.kcat@gmail.com>
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
25 /* This file contains an example for controlling multiple reverb zones to
26 * smoothly transition between reverb environments. The general concept is to
27 * extend single-reverb by also tracking the closest adjacent environment, and
28 * utilize EAX Reverb's panning vectors to position them relative to the
29 * listener.
32 #include <assert.h>
33 #include <math.h>
34 #include <stdio.h>
35 #include <string.h>
37 #include "SDL_sound.h"
38 #include "SDL_audio.h"
39 #include "SDL_stdinc.h"
41 #include "AL/al.h"
42 #include "AL/alc.h"
43 #include "AL/efx.h"
44 #include "AL/efx-presets.h"
46 #include "common/alhelpers.h"
49 #ifndef M_PI
50 #define M_PI 3.14159265358979323846
51 #endif
54 /* Filter object functions */
55 static LPALGENFILTERS alGenFilters;
56 static LPALDELETEFILTERS alDeleteFilters;
57 static LPALISFILTER alIsFilter;
58 static LPALFILTERI alFilteri;
59 static LPALFILTERIV alFilteriv;
60 static LPALFILTERF alFilterf;
61 static LPALFILTERFV alFilterfv;
62 static LPALGETFILTERI alGetFilteri;
63 static LPALGETFILTERIV alGetFilteriv;
64 static LPALGETFILTERF alGetFilterf;
65 static LPALGETFILTERFV alGetFilterfv;
67 /* Effect object functions */
68 static LPALGENEFFECTS alGenEffects;
69 static LPALDELETEEFFECTS alDeleteEffects;
70 static LPALISEFFECT alIsEffect;
71 static LPALEFFECTI alEffecti;
72 static LPALEFFECTIV alEffectiv;
73 static LPALEFFECTF alEffectf;
74 static LPALEFFECTFV alEffectfv;
75 static LPALGETEFFECTI alGetEffecti;
76 static LPALGETEFFECTIV alGetEffectiv;
77 static LPALGETEFFECTF alGetEffectf;
78 static LPALGETEFFECTFV alGetEffectfv;
80 /* Auxiliary Effect Slot object functions */
81 static LPALGENAUXILIARYEFFECTSLOTS alGenAuxiliaryEffectSlots;
82 static LPALDELETEAUXILIARYEFFECTSLOTS alDeleteAuxiliaryEffectSlots;
83 static LPALISAUXILIARYEFFECTSLOT alIsAuxiliaryEffectSlot;
84 static LPALAUXILIARYEFFECTSLOTI alAuxiliaryEffectSloti;
85 static LPALAUXILIARYEFFECTSLOTIV alAuxiliaryEffectSlotiv;
86 static LPALAUXILIARYEFFECTSLOTF alAuxiliaryEffectSlotf;
87 static LPALAUXILIARYEFFECTSLOTFV alAuxiliaryEffectSlotfv;
88 static LPALGETAUXILIARYEFFECTSLOTI alGetAuxiliaryEffectSloti;
89 static LPALGETAUXILIARYEFFECTSLOTIV alGetAuxiliaryEffectSlotiv;
90 static LPALGETAUXILIARYEFFECTSLOTF alGetAuxiliaryEffectSlotf;
91 static LPALGETAUXILIARYEFFECTSLOTFV alGetAuxiliaryEffectSlotfv;
94 /* LoadEffect loads the given initial reverb properties into the given OpenAL
95 * effect object, and returns non-zero on success.
97 static int LoadEffect(ALuint effect, const EFXEAXREVERBPROPERTIES *reverb)
99 ALenum err;
101 alGetError();
103 /* Prepare the effect for EAX Reverb (standard reverb doesn't contain
104 * the needed panning vectors).
106 alEffecti(effect, AL_EFFECT_TYPE, AL_EFFECT_EAXREVERB);
107 if((err=alGetError()) != AL_NO_ERROR)
109 fprintf(stderr, "Failed to set EAX Reverb: %s (0x%04x)\n", alGetString(err), err);
110 return 0;
113 /* Load the reverb properties. */
114 alEffectf(effect, AL_EAXREVERB_DENSITY, reverb->flDensity);
115 alEffectf(effect, AL_EAXREVERB_DIFFUSION, reverb->flDiffusion);
116 alEffectf(effect, AL_EAXREVERB_GAIN, reverb->flGain);
117 alEffectf(effect, AL_EAXREVERB_GAINHF, reverb->flGainHF);
118 alEffectf(effect, AL_EAXREVERB_GAINLF, reverb->flGainLF);
119 alEffectf(effect, AL_EAXREVERB_DECAY_TIME, reverb->flDecayTime);
120 alEffectf(effect, AL_EAXREVERB_DECAY_HFRATIO, reverb->flDecayHFRatio);
121 alEffectf(effect, AL_EAXREVERB_DECAY_LFRATIO, reverb->flDecayLFRatio);
122 alEffectf(effect, AL_EAXREVERB_REFLECTIONS_GAIN, reverb->flReflectionsGain);
123 alEffectf(effect, AL_EAXREVERB_REFLECTIONS_DELAY, reverb->flReflectionsDelay);
124 alEffectfv(effect, AL_EAXREVERB_REFLECTIONS_PAN, reverb->flReflectionsPan);
125 alEffectf(effect, AL_EAXREVERB_LATE_REVERB_GAIN, reverb->flLateReverbGain);
126 alEffectf(effect, AL_EAXREVERB_LATE_REVERB_DELAY, reverb->flLateReverbDelay);
127 alEffectfv(effect, AL_EAXREVERB_LATE_REVERB_PAN, reverb->flLateReverbPan);
128 alEffectf(effect, AL_EAXREVERB_ECHO_TIME, reverb->flEchoTime);
129 alEffectf(effect, AL_EAXREVERB_ECHO_DEPTH, reverb->flEchoDepth);
130 alEffectf(effect, AL_EAXREVERB_MODULATION_TIME, reverb->flModulationTime);
131 alEffectf(effect, AL_EAXREVERB_MODULATION_DEPTH, reverb->flModulationDepth);
132 alEffectf(effect, AL_EAXREVERB_AIR_ABSORPTION_GAINHF, reverb->flAirAbsorptionGainHF);
133 alEffectf(effect, AL_EAXREVERB_HFREFERENCE, reverb->flHFReference);
134 alEffectf(effect, AL_EAXREVERB_LFREFERENCE, reverb->flLFReference);
135 alEffectf(effect, AL_EAXREVERB_ROOM_ROLLOFF_FACTOR, reverb->flRoomRolloffFactor);
136 alEffecti(effect, AL_EAXREVERB_DECAY_HFLIMIT, reverb->iDecayHFLimit);
138 /* Check if an error occured, and return failure if so. */
139 if((err=alGetError()) != AL_NO_ERROR)
141 fprintf(stderr, "Error setting up reverb: %s\n", alGetString(err));
142 return 0;
145 return 1;
149 /* LoadBuffer loads the named audio file into an OpenAL buffer object, and
150 * returns the new buffer ID.
152 static ALuint LoadSound(const char *filename)
154 Sound_Sample *sample;
155 ALenum err, format;
156 ALuint buffer;
157 Uint32 slen;
159 /* Open the audio file */
160 sample = Sound_NewSampleFromFile(filename, NULL, 65536);
161 if(!sample)
163 fprintf(stderr, "Could not open audio in %s\n", filename);
164 return 0;
167 /* Get the sound format, and figure out the OpenAL format */
168 if(sample->actual.channels == 1)
170 if(sample->actual.format == AUDIO_U8)
171 format = AL_FORMAT_MONO8;
172 else if(sample->actual.format == AUDIO_S16SYS)
173 format = AL_FORMAT_MONO16;
174 else
176 fprintf(stderr, "Unsupported sample format: 0x%04x\n", sample->actual.format);
177 Sound_FreeSample(sample);
178 return 0;
181 else if(sample->actual.channels == 2)
183 if(sample->actual.format == AUDIO_U8)
184 format = AL_FORMAT_STEREO8;
185 else if(sample->actual.format == AUDIO_S16SYS)
186 format = AL_FORMAT_STEREO16;
187 else
189 fprintf(stderr, "Unsupported sample format: 0x%04x\n", sample->actual.format);
190 Sound_FreeSample(sample);
191 return 0;
194 else
196 fprintf(stderr, "Unsupported channel count: %d\n", sample->actual.channels);
197 Sound_FreeSample(sample);
198 return 0;
201 /* Decode the whole audio stream to a buffer. */
202 slen = Sound_DecodeAll(sample);
203 if(!sample->buffer || slen == 0)
205 fprintf(stderr, "Failed to read audio from %s\n", filename);
206 Sound_FreeSample(sample);
207 return 0;
210 /* Buffer the audio data into a new buffer object, then free the data and
211 * close the file. */
212 buffer = 0;
213 alGenBuffers(1, &buffer);
214 alBufferData(buffer, format, sample->buffer, (ALsizei)slen, (ALsizei)sample->actual.rate);
215 Sound_FreeSample(sample);
217 /* Check if an error occured, and clean up if so. */
218 err = alGetError();
219 if(err != AL_NO_ERROR)
221 fprintf(stderr, "OpenAL Error: %s\n", alGetString(err));
222 if(buffer && alIsBuffer(buffer))
223 alDeleteBuffers(1, &buffer);
224 return 0;
227 return buffer;
231 /* Helper to calculate the dot-product of the two given vectors. */
232 static ALfloat dot_product(const ALfloat vec0[3], const ALfloat vec1[3])
234 return vec0[0]*vec1[0] + vec0[1]*vec1[1] + vec0[2]*vec1[2];
237 /* Helper to normalize a given vector. */
238 static void normalize(ALfloat vec[3])
240 ALfloat mag = sqrtf(dot_product(vec, vec));
241 if(mag > 0.00001f)
243 vec[0] /= mag;
244 vec[1] /= mag;
245 vec[2] /= mag;
247 else
249 vec[0] = 0.0f;
250 vec[1] = 0.0f;
251 vec[2] = 0.0f;
256 /* The main update function to update the listener and environment effects. */
257 static void UpdateListenerAndEffects(float timediff, const ALuint slots[2], const ALuint effects[2], const EFXEAXREVERBPROPERTIES reverbs[2])
259 static const ALfloat listener_move_scale = 10.0f;
260 /* Individual reverb zones are connected via "portals". Each portal has a
261 * position (center point of the connecting area), a normal (facing
262 * direction), and a radius (approximate size of the connecting area).
264 const ALfloat portal_pos[3] = { 0.0f, 0.0f, 0.0f };
265 const ALfloat portal_norm[3] = { sqrtf(0.5f), 0.0f, -sqrtf(0.5f) };
266 const ALfloat portal_radius = 2.5f;
267 ALfloat other_dir[3], this_dir[3];
268 ALfloat listener_pos[3];
269 ALfloat local_norm[3];
270 ALfloat local_dir[3];
271 ALfloat near_edge[3];
272 ALfloat far_edge[3];
273 ALfloat dist, edist;
275 /* Update the listener position for the amount of time passed. This uses a
276 * simple triangular LFO to offset the position (moves along the X axis
277 * between -listener_move_scale and +listener_move_scale for each
278 * transition).
280 listener_pos[0] = (fabsf(2.0f - timediff/2.0f) - 1.0f) * listener_move_scale;
281 listener_pos[1] = 0.0f;
282 listener_pos[2] = 0.0f;
283 alListenerfv(AL_POSITION, listener_pos);
285 /* Calculate local_dir, which represents the listener-relative point to the
286 * adjacent zone (should also include orientation). Because EAX Reverb uses
287 * left-handed coordinates instead of right-handed like the rest of OpenAL,
288 * negate Z for the local values.
290 local_dir[0] = portal_pos[0] - listener_pos[0];
291 local_dir[1] = portal_pos[1] - listener_pos[1];
292 local_dir[2] = -(portal_pos[2] - listener_pos[2]);
293 /* A normal application would also rotate the portal's normal given the
294 * listener orientation, to get the listener-relative normal.
296 local_norm[0] = portal_norm[0];
297 local_norm[1] = portal_norm[1];
298 local_norm[2] = -portal_norm[2];
300 /* Calculate the distance from the listener to the portal, and ensure it's
301 * far enough away to not suffer severe floating-point precision issues.
303 dist = sqrtf(dot_product(local_dir, local_dir));
304 if(dist > 0.00001f)
306 const EFXEAXREVERBPROPERTIES *other_reverb, *this_reverb;
307 ALuint other_effect, this_effect;
308 ALfloat magnitude, dir_dot_norm;
310 /* Normalize the direction to the portal. */
311 local_dir[0] /= dist;
312 local_dir[1] /= dist;
313 local_dir[2] /= dist;
315 /* Calculate the dot product of the portal's local direction and local
316 * normal, which is used for angular and side checks later on.
318 dir_dot_norm = dot_product(local_dir, local_norm);
320 /* Figure out which zone we're in. */
321 if(dir_dot_norm <= 0.0f)
323 /* We're in front of the portal, so we're in Zone 0. */
324 this_effect = effects[0];
325 other_effect = effects[1];
326 this_reverb = &reverbs[0];
327 other_reverb = &reverbs[1];
329 else
331 /* We're behind the portal, so we're in Zone 1. */
332 this_effect = effects[1];
333 other_effect = effects[0];
334 this_reverb = &reverbs[1];
335 other_reverb = &reverbs[0];
338 /* Calculate the listener-relative extents of the portal. */
339 /* First, project the listener-to-portal vector onto the portal's plane
340 * to get the portal-relative direction along the plane that goes away
341 * from the listener (toward the farthest edge of the portal).
343 far_edge[0] = local_dir[0] - local_norm[0]*dir_dot_norm;
344 far_edge[1] = local_dir[1] - local_norm[1]*dir_dot_norm;
345 far_edge[2] = local_dir[2] - local_norm[2]*dir_dot_norm;
347 edist = sqrtf(dot_product(far_edge, far_edge));
348 if(edist > 0.0001f)
350 /* Rescale the portal-relative vector to be at the radius edge. */
351 ALfloat mag = portal_radius / edist;
352 far_edge[0] *= mag;
353 far_edge[1] *= mag;
354 far_edge[2] *= mag;
356 /* Calculate the closest edge of the portal by negating the
357 * farthest, and add an offset to make them both relative to the
358 * listener.
360 near_edge[0] = local_dir[0]*dist - far_edge[0];
361 near_edge[1] = local_dir[1]*dist - far_edge[1];
362 near_edge[2] = local_dir[2]*dist - far_edge[2];
363 far_edge[0] += local_dir[0]*dist;
364 far_edge[1] += local_dir[1]*dist;
365 far_edge[2] += local_dir[2]*dist;
367 /* Normalize the listener-relative extents of the portal, then
368 * calculate the panning magnitude for the other zone given the
369 * apparent size of the opening. The panning magnitude affects the
370 * envelopment of the environment, with 1 being a point, 0.5 being
371 * half coverage around the listener, and 0 being full coverage.
373 normalize(far_edge);
374 normalize(near_edge);
375 magnitude = 1.0f - acosf(dot_product(far_edge, near_edge))/(float)(M_PI*2.0);
377 /* Recalculate the panning direction, to be directly between the
378 * direction of the two extents.
380 local_dir[0] = far_edge[0] + near_edge[0];
381 local_dir[1] = far_edge[1] + near_edge[1];
382 local_dir[2] = far_edge[2] + near_edge[2];
383 normalize(local_dir);
385 else
387 /* If we get here, the listener is directly in front of or behind
388 * the center of the portal, making all aperture edges effectively
389 * equidistant. Calculating the panning magnitude is simplified,
390 * using the arctangent of the radius and distance.
392 magnitude = 1.0f - (atan2f(portal_radius, dist) / (float)M_PI);
395 /* Scale the other zone's panning vector. */
396 other_dir[0] = local_dir[0] * magnitude;
397 other_dir[1] = local_dir[1] * magnitude;
398 other_dir[2] = local_dir[2] * magnitude;
399 /* Pan the current zone to the opposite direction of the portal, and
400 * take the remaining percentage of the portal's magnitude.
402 this_dir[0] = local_dir[0] * (magnitude-1.0f);
403 this_dir[1] = local_dir[1] * (magnitude-1.0f);
404 this_dir[2] = local_dir[2] * (magnitude-1.0f);
406 /* Now set the effects' panning vectors and gain. Energy is shared
407 * between environments, so attenuate according to each zone's
408 * contribution (note: gain^2 = energy).
410 alEffectf(this_effect, AL_EAXREVERB_REFLECTIONS_GAIN, this_reverb->flReflectionsGain * sqrtf(magnitude));
411 alEffectf(this_effect, AL_EAXREVERB_LATE_REVERB_GAIN, this_reverb->flLateReverbGain * sqrtf(magnitude));
412 alEffectfv(this_effect, AL_EAXREVERB_REFLECTIONS_PAN, this_dir);
413 alEffectfv(this_effect, AL_EAXREVERB_LATE_REVERB_PAN, this_dir);
415 alEffectf(other_effect, AL_EAXREVERB_REFLECTIONS_GAIN, other_reverb->flReflectionsGain * sqrtf(1.0f-magnitude));
416 alEffectf(other_effect, AL_EAXREVERB_LATE_REVERB_GAIN, other_reverb->flLateReverbGain * sqrtf(1.0f-magnitude));
417 alEffectfv(other_effect, AL_EAXREVERB_REFLECTIONS_PAN, other_dir);
418 alEffectfv(other_effect, AL_EAXREVERB_LATE_REVERB_PAN, other_dir);
420 else
422 /* We're practically in the center of the portal. Give the panning
423 * vectors a 50/50 split, with Zone 0 covering the half in front of
424 * the normal, and Zone 1 covering the half behind.
426 this_dir[0] = local_norm[0] / 2.0f;
427 this_dir[1] = local_norm[1] / 2.0f;
428 this_dir[2] = local_norm[2] / 2.0f;
430 other_dir[0] = local_norm[0] / -2.0f;
431 other_dir[1] = local_norm[1] / -2.0f;
432 other_dir[2] = local_norm[2] / -2.0f;
434 alEffectf(effects[0], AL_EAXREVERB_REFLECTIONS_GAIN, reverbs[0].flReflectionsGain * sqrtf(0.5f));
435 alEffectf(effects[0], AL_EAXREVERB_LATE_REVERB_GAIN, reverbs[0].flLateReverbGain * sqrtf(0.5f));
436 alEffectfv(effects[0], AL_EAXREVERB_REFLECTIONS_PAN, this_dir);
437 alEffectfv(effects[0], AL_EAXREVERB_LATE_REVERB_PAN, this_dir);
439 alEffectf(effects[1], AL_EAXREVERB_REFLECTIONS_GAIN, reverbs[1].flReflectionsGain * sqrtf(0.5f));
440 alEffectf(effects[1], AL_EAXREVERB_LATE_REVERB_GAIN, reverbs[1].flLateReverbGain * sqrtf(0.5f));
441 alEffectfv(effects[1], AL_EAXREVERB_REFLECTIONS_PAN, other_dir);
442 alEffectfv(effects[1], AL_EAXREVERB_LATE_REVERB_PAN, other_dir);
445 /* Finally, update the effect slots with the updated effect parameters. */
446 alAuxiliaryEffectSloti(slots[0], AL_EFFECTSLOT_EFFECT, (ALint)effects[0]);
447 alAuxiliaryEffectSloti(slots[1], AL_EFFECTSLOT_EFFECT, (ALint)effects[1]);
451 int main(int argc, char **argv)
453 static const int MaxTransitions = 8;
454 EFXEAXREVERBPROPERTIES reverbs[2] = {
455 EFX_REVERB_PRESET_CARPETEDHALLWAY,
456 EFX_REVERB_PRESET_BATHROOM
458 ALCdevice *device = NULL;
459 ALCcontext *context = NULL;
460 ALuint effects[2] = { 0, 0 };
461 ALuint slots[2] = { 0, 0 };
462 ALuint direct_filter = 0;
463 ALuint buffer = 0;
464 ALuint source = 0;
465 ALCint num_sends = 0;
466 ALenum state = AL_INITIAL;
467 ALfloat direct_gain = 1.0f;
468 int basetime = 0;
469 int loops = 0;
471 /* Print out usage if no arguments were specified */
472 if(argc < 2)
474 fprintf(stderr, "Usage: %s [-device <name>] [options] <filename>\n\n"
475 "Options:\n"
476 "\t-nodirect\tSilence direct path output (easier to hear reverb)\n\n",
477 argv[0]);
478 return 1;
481 /* Initialize OpenAL, and check for EFX support with at least 2 auxiliary
482 * sends (if multiple sends are supported, 2 are provided by default; if
483 * you want more, you have to request it through alcCreateContext).
485 argv++; argc--;
486 if(InitAL(&argv, &argc) != 0)
487 return 1;
489 while(argc > 0)
491 if(strcmp(argv[0], "-nodirect") == 0)
492 direct_gain = 0.0f;
493 else
494 break;
495 argv++;
496 argc--;
498 if(argc < 1)
500 fprintf(stderr, "No filename spacified.\n");
501 CloseAL();
502 return 1;
505 context = alcGetCurrentContext();
506 device = alcGetContextsDevice(context);
508 if(!alcIsExtensionPresent(device, "ALC_EXT_EFX"))
510 fprintf(stderr, "Error: EFX not supported\n");
511 CloseAL();
512 return 1;
515 num_sends = 0;
516 alcGetIntegerv(device, ALC_MAX_AUXILIARY_SENDS, 1, &num_sends);
517 if(alcGetError(device) != ALC_NO_ERROR || num_sends < 2)
519 fprintf(stderr, "Error: Device does not support multiple sends (got %d, need 2)\n",
520 num_sends);
521 CloseAL();
522 return 1;
525 /* Define a macro to help load the function pointers. */
526 #define LOAD_PROC(T, x) ((x) = (T)alGetProcAddress(#x))
527 LOAD_PROC(LPALGENFILTERS, alGenFilters);
528 LOAD_PROC(LPALDELETEFILTERS, alDeleteFilters);
529 LOAD_PROC(LPALISFILTER, alIsFilter);
530 LOAD_PROC(LPALFILTERI, alFilteri);
531 LOAD_PROC(LPALFILTERIV, alFilteriv);
532 LOAD_PROC(LPALFILTERF, alFilterf);
533 LOAD_PROC(LPALFILTERFV, alFilterfv);
534 LOAD_PROC(LPALGETFILTERI, alGetFilteri);
535 LOAD_PROC(LPALGETFILTERIV, alGetFilteriv);
536 LOAD_PROC(LPALGETFILTERF, alGetFilterf);
537 LOAD_PROC(LPALGETFILTERFV, alGetFilterfv);
539 LOAD_PROC(LPALGENEFFECTS, alGenEffects);
540 LOAD_PROC(LPALDELETEEFFECTS, alDeleteEffects);
541 LOAD_PROC(LPALISEFFECT, alIsEffect);
542 LOAD_PROC(LPALEFFECTI, alEffecti);
543 LOAD_PROC(LPALEFFECTIV, alEffectiv);
544 LOAD_PROC(LPALEFFECTF, alEffectf);
545 LOAD_PROC(LPALEFFECTFV, alEffectfv);
546 LOAD_PROC(LPALGETEFFECTI, alGetEffecti);
547 LOAD_PROC(LPALGETEFFECTIV, alGetEffectiv);
548 LOAD_PROC(LPALGETEFFECTF, alGetEffectf);
549 LOAD_PROC(LPALGETEFFECTFV, alGetEffectfv);
551 LOAD_PROC(LPALGENAUXILIARYEFFECTSLOTS, alGenAuxiliaryEffectSlots);
552 LOAD_PROC(LPALDELETEAUXILIARYEFFECTSLOTS, alDeleteAuxiliaryEffectSlots);
553 LOAD_PROC(LPALISAUXILIARYEFFECTSLOT, alIsAuxiliaryEffectSlot);
554 LOAD_PROC(LPALAUXILIARYEFFECTSLOTI, alAuxiliaryEffectSloti);
555 LOAD_PROC(LPALAUXILIARYEFFECTSLOTIV, alAuxiliaryEffectSlotiv);
556 LOAD_PROC(LPALAUXILIARYEFFECTSLOTF, alAuxiliaryEffectSlotf);
557 LOAD_PROC(LPALAUXILIARYEFFECTSLOTFV, alAuxiliaryEffectSlotfv);
558 LOAD_PROC(LPALGETAUXILIARYEFFECTSLOTI, alGetAuxiliaryEffectSloti);
559 LOAD_PROC(LPALGETAUXILIARYEFFECTSLOTIV, alGetAuxiliaryEffectSlotiv);
560 LOAD_PROC(LPALGETAUXILIARYEFFECTSLOTF, alGetAuxiliaryEffectSlotf);
561 LOAD_PROC(LPALGETAUXILIARYEFFECTSLOTFV, alGetAuxiliaryEffectSlotfv);
562 #undef LOAD_PROC
564 /* Initialize SDL_sound. */
565 Sound_Init();
567 /* Load the sound into a buffer. */
568 buffer = LoadSound(argv[0]);
569 if(!buffer)
571 CloseAL();
572 Sound_Quit();
573 return 1;
576 /* Generate two effects for two "zones", and load a reverb into each one.
577 * Note that unlike single-zone reverb, where you can store one effect per
578 * preset, for multi-zone reverb you should have one effect per environment
579 * instance, or one per audible zone. This is because we'll be changing the
580 * effects' properties in real-time based on the environment instance
581 * relative to the listener.
583 alGenEffects(2, effects);
584 if(!LoadEffect(effects[0], &reverbs[0]) || !LoadEffect(effects[1], &reverbs[1]))
586 alDeleteEffects(2, effects);
587 alDeleteBuffers(1, &buffer);
588 Sound_Quit();
589 CloseAL();
590 return 1;
593 /* Create the effect slot objects, one for each "active" effect. */
594 alGenAuxiliaryEffectSlots(2, slots);
596 /* Tell the effect slots to use the loaded effect objects, with slot 0 for
597 * Zone 0 and slot 1 for Zone 1. Note that this effectively copies the
598 * effect properties. Modifying or deleting the effect object afterward
599 * won't directly affect the effect slot until they're reapplied like this.
601 alAuxiliaryEffectSloti(slots[0], AL_EFFECTSLOT_EFFECT, (ALint)effects[0]);
602 alAuxiliaryEffectSloti(slots[1], AL_EFFECTSLOT_EFFECT, (ALint)effects[1]);
603 assert(alGetError()==AL_NO_ERROR && "Failed to set effect slot");
605 /* For the purposes of this example, prepare a filter that optionally
606 * silences the direct path which allows us to hear just the reverberation.
607 * A filter like this is normally used for obstruction, where the path
608 * directly between the listener and source is blocked (the exact
609 * properties depending on the type and thickness of the obstructing
610 * material).
612 alGenFilters(1, &direct_filter);
613 alFilteri(direct_filter, AL_FILTER_TYPE, AL_FILTER_LOWPASS);
614 alFilterf(direct_filter, AL_LOWPASS_GAIN, direct_gain);
615 assert(alGetError()==AL_NO_ERROR && "Failed to set direct filter");
617 /* Create the source to play the sound with, place it in front of the
618 * listener's path in the left zone.
620 source = 0;
621 alGenSources(1, &source);
622 alSourcei(source, AL_LOOPING, AL_TRUE);
623 alSource3f(source, AL_POSITION, -5.0f, 0.0f, -2.0f);
624 alSourcei(source, AL_DIRECT_FILTER, (ALint)direct_filter);
625 alSourcei(source, AL_BUFFER, (ALint)buffer);
627 /* Connect the source to the effect slots. Here, we connect source send 0
628 * to Zone 0's slot, and send 1 to Zone 1's slot. Filters can be specified
629 * to occlude the source from each zone by varying amounts; for example, a
630 * source within a particular zone would be unfiltered, while a source that
631 * can only see a zone through a window or thin wall may be attenuated for
632 * that zone.
634 alSource3i(source, AL_AUXILIARY_SEND_FILTER, (ALint)slots[0], 0, AL_FILTER_NULL);
635 alSource3i(source, AL_AUXILIARY_SEND_FILTER, (ALint)slots[1], 1, AL_FILTER_NULL);
636 assert(alGetError()==AL_NO_ERROR && "Failed to setup sound source");
638 /* Get the current time as the base for timing in the main loop. */
639 basetime = altime_get();
640 loops = 0;
641 printf("Transition %d of %d...\n", loops+1, MaxTransitions);
643 /* Play the sound for a while. */
644 alSourcePlay(source);
645 do {
646 int curtime;
647 ALfloat timediff;
649 /* Start a batch update, to ensure all changes apply simultaneously. */
650 alcSuspendContext(context);
652 /* Get the current time to track the amount of time that passed.
653 * Convert the difference to seconds.
655 curtime = altime_get();
656 timediff = (float)(curtime - basetime) / 1000.0f;
658 /* Avoid negative time deltas, in case of non-monotonic clocks. */
659 if(timediff < 0.0f)
660 timediff = 0.0f;
661 else while(timediff >= 4.0f*(float)((loops&1)+1))
663 /* For this example, each transition occurs over 4 seconds, and
664 * there's 2 transitions per cycle.
666 if(++loops < MaxTransitions)
667 printf("Transition %d of %d...\n", loops+1, MaxTransitions);
668 if(!(loops&1))
670 /* Cycle completed. Decrease the delta and increase the base
671 * time to start a new cycle.
673 timediff -= 8.0f;
674 basetime += 8000;
678 /* Update the listener and effects, and finish the batch. */
679 UpdateListenerAndEffects(timediff, slots, effects, reverbs);
680 alcProcessContext(context);
682 al_nssleep(10000000);
684 alGetSourcei(source, AL_SOURCE_STATE, &state);
685 } while(alGetError() == AL_NO_ERROR && state == AL_PLAYING && loops < MaxTransitions);
687 /* All done. Delete resources, and close down SDL_sound and OpenAL. */
688 alDeleteSources(1, &source);
689 alDeleteAuxiliaryEffectSlots(2, slots);
690 alDeleteEffects(2, effects);
691 alDeleteFilters(1, &direct_filter);
692 alDeleteBuffers(1, &buffer);
694 Sound_Quit();
695 CloseAL();
697 return 0;