Skip to content

Zero Hour rebuilt from EA's source: x64, Direct3D 11, VS2022/CMake, ~60 original bugs fixed, an AI that builds a base. Bring your own game.

feat(audio): sound delay, air low-pass, doppler, map reverb, blast duck

Olcay Seyganc6b1b0fc8ec5
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 228879f9f..36c6a2c3c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,15 @@ found and fixed — EA's own, not port damage.**
---
+## Sound that travels
+
+- Sound takes time to cross the battlefield now. An explosion at the edge of the screen is heard about a quarter of a second after it is seen, one at the far end of a long view half a second after, at the speed of sound on the scale the units are drawn at. The wait never runs past a second, and unit replies, the interface, music, speech and every sound a mission script waits on still play the moment they are asked for.
+- Distance takes the top off a sound as air does. Fighting near the middle of the screen keeps its crack, a battle across the map arrives as a dull rumble, and a nuke on the far side is mostly low thunder. The muffling EA gave sixteen explosions for when they go off out of view used to be only a drop in volume; it is a real muffling now, so those blasts are no quieter off screen than on it, only duller.
+- Jets, helicopters and the Nuke Cannon's shell rise in pitch as they come in and drop as they pass, by how fast they move towards you. A Raptor run is two semitones up and down; an Aurora at full speed twice that.
+- Every map has an echo of its own, worked out from how much of it is built over. A city map rings for nearly two seconds and throws a slap back off the buildings, open desert gives a faint short tail, and snow deadens whatever the map has. Far sounds carry more of it than near ones.
+- A nuke, a Particle Cannon sweep, a Daisy Cutter, a MOAB or a Nuke Cannon shell that lands within earshot pushes the rest of the battle down for a couple of seconds, by how close it is, and lets it back up.
+- macOS and Linux hear the same, and so does the sound the game records for a video, in step with the picture frame for frame. A mod can retune any of it, or switch a part off, from its audio settings.
+
## Ukrainian and Russian
- The language box under Options, Gameplay goes on past Deutsch to Українська and Русский, each written in its own alphabet, so a player finds their language without reading a word of English first. All 4684 lines the game shows are translated in both, menus, tooltips, briefings and the fork's own options included. The launcher's game language box offers the two as well.
diff --git a/GeneralsMD/Code/BuildFingerprint.manifest b/GeneralsMD/Code/BuildFingerprint.manifest
index df6fa4777..a4c32a601 100644
--- a/GeneralsMD/Code/BuildFingerprint.manifest
+++ b/GeneralsMD/Code/BuildFingerprint.manifest
@@ -3160,6 +3160,7 @@ Tests/test_linux_portable.sh
Tests/test_macos_app.sh
Tests/test_main.cpp
Tests/test_map_ini_rollback.inc
+Tests/test_miles_effects.cpp
Tests/test_miles_miniaudio.cpp
Tests/test_milesaudiomanager.cpp
Tests/test_minimap_input.inc
diff --git a/GeneralsMD/Code/CMakeLists.txt b/GeneralsMD/Code/CMakeLists.txt
index e2c3315ac..42666a4ec 100644
--- a/GeneralsMD/Code/CMakeLists.txt
+++ b/GeneralsMD/Code/CMakeLists.txt
@@ -2465,6 +2465,16 @@ target_link_libraries(miles_smoke PRIVATE milesaudio)
# From Run/, where the FFmpeg DLLs the backend decodes with are.
add_test(NAME miles_smoke COMMAND miles_smoke
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/../Run)
+
+# The air, room and duck of the miniaudio backend, in the offline mix a -wav run records. The
+# backend is compiled in on its own: milesaudio here carries the XAudio2 half and the FFmpeg DLLs
+# that only Run/ has. The source keeps its MA_ prefix (the property above is the directory's), so
+# the test calls it by the same names.
+add_executable(test_miles_effects ${TESTS}/test_miles_effects.cpp ${WW}/Miles6/miniaudio/miles_miniaudio.cpp)
+set_source_files_properties(${TESTS}/test_miles_effects.cpp PROPERTIES COMPILE_DEFINITIONS MSS_BACKEND_PREFIX=MA_)
+target_include_directories(test_miles_effects PRIVATE ${WW}/Miles6/include ${WW}/WWLib)
+target_link_libraries(test_miles_effects PRIVATE test_harness miniaudio)
+add_test(NAME test_miles_effects COMMAND test_miles_effects)
endif() # ZH_PLATFORM_WINDOWS - device and codec smoke tests
if(ZH_PLATFORM_POSIX)
@@ -2492,6 +2502,11 @@ if(ZH_GAME_DATA)
else()
set_tests_properties(test_miles_miniaudio PROPERTIES ENVIRONMENT "ZH_AUDIO_BACKEND=null")
endif()
+# The same file Windows runs: the air, room and duck in the offline mix.
+add_executable(test_miles_effects ${TESTS}/test_miles_effects.cpp)
+target_include_directories(test_miles_effects PRIVATE ${WW}/Miles6/include)
+target_link_libraries(test_miles_effects PRIVATE test_harness milesaudio)
+add_test(NAME test_miles_effects COMMAND test_miles_effects)
# For human ears, not ctest: plays one sound from a .big archive (or a loose file) on the real
# device, through the same API, at a chosen volume and pan.
diff --git a/GeneralsMD/Code/GameEngine/Include/Common/AudioEventRTS.h b/GeneralsMD/Code/GameEngine/Include/Common/AudioEventRTS.h
index 8cfbb8393..81d7cb76f 100644
--- a/GeneralsMD/Code/GameEngine/Include/Common/AudioEventRTS.h
+++ b/GeneralsMD/Code/GameEngine/Include/Common/AudioEventRTS.h
@@ -97,6 +97,7 @@ public:
Real getDelay( void ) const;
void decrementDelay( Real timeToDecrement );
+ void setDelay( Real delay ) { m_delay = delay; } ///< milliseconds, as the INI's Delay
PortionToPlay getNextPlayPortion( void ) const;
void advanceNextPlayPortion( void );
diff --git a/GeneralsMD/Code/GameEngine/Include/Common/AudioSettings.h b/GeneralsMD/Code/GameEngine/Include/Common/AudioSettings.h
index 6ec873c84..3e599a49f 100644
--- a/GeneralsMD/Code/GameEngine/Include/Common/AudioSettings.h
+++ b/GeneralsMD/Code/GameEngine/Include/Common/AudioSettings.h
@@ -34,6 +34,8 @@
#include "Common/AsciiString.h"
+#include <vector>
+
enum { MAX_HW_PROVIDERS = 4 };
struct AudioSettings
@@ -41,7 +43,22 @@ struct AudioSettings
// Every field below is filled in by AudioSettings.ini and nothing gives them a value before
// that, so a key the shipped file does not carry arrives as whatever was on the heap. New
// fields get their default here.
- AudioSettings() : m_rangeVolumeFade( FALSE ) {}
+ AudioSettings() :
+ m_rangeVolumeFade( FALSE ),
+ m_speedOfSound( 1700.0f ),
+ m_maxSoundDelay( 1000.0f ),
+ m_dopplerScale( 1.0f ),
+ m_airAbsorptionDistance( 400.0f ),
+ m_reverbLevel( 1.0f ),
+ m_duckVolume( 0.35f ),
+ m_duckTime( 2500.0f )
+ {
+ m_duckSounds.push_back( "ExplosionNeutron" );
+ m_duckSounds.push_back( "ExplosionDaisyCutter" );
+ m_duckSounds.push_back( "ExplosionMOAB" );
+ m_duckSounds.push_back( "ExplosionMiniNuke" );
+ m_duckSounds.push_back( "ParticleUplinkCannon_GroundAnnihilationSoundLoop" );
+ }
AsciiString m_audioRoot;
AsciiString m_soundsFolder;
@@ -66,6 +83,28 @@ struct AudioSettings
* commented out next to it, which reaches zero exactly where the cut is.
* `RangeVolumeFade` in AudioSettings.ini. */
Bool m_rangeVolumeFade;
+
+ /** Sound in air, none of which the shipped file carries, so the defaults below are what plays.
+ *
+ * `SpeedOfSound`, game units a second: a world sound starts late by its distance to the
+ * microphone over it, never more than `MaxSoundDelay` milliseconds, and a moving one is pitched
+ * by doppler. The ground is drawn at about 0.2 m a unit (a Ranger stands 13 units, a Crusader
+ * is 30 long), so 343 m/s is 1700. Zero is neither. `DopplerScale` multiplies the speed doppler
+ * hears, zero switching doppler alone off.
+ * `AirAbsorptionDistance`, game units: where air has taken the top end down from 20 kHz to 10,
+ * falling with the square of the distance past it. Zero is no air.
+ * `ReverbLevel`: the room's send, as a share of what the map asks for. Zero is no room.
+ * `DuckVolume` and `DuckTime` (milliseconds): when one of `DuckSounds` starts within earshot,
+ * everything else dips to that volume and comes back over that time. 100% is no duck. */
+ Real m_speedOfSound;
+ Real m_maxSoundDelay;
+ Real m_dopplerScale;
+ Real m_airAbsorptionDistance;
+ Real m_reverbLevel;
+ Real m_duckVolume;
+ Real m_duckTime;
+ std::vector<AsciiString> m_duckSounds;
+
Int m_drawableAmbientFrames;
Int m_fadeAudioFrames;
UnsignedInt m_maxCacheSize;
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/Audio/GameAudio.cpp b/GeneralsMD/Code/GameEngine/Source/Common/Audio/GameAudio.cpp
index 44240ce56..6ed67b5c1 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/Audio/GameAudio.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/Audio/GameAudio.cpp
@@ -130,6 +130,14 @@ static const FieldParse audioSettingsFieldParseTable[] =
{ "MinSampleVolume", INI::parsePercentToReal, NULL, offsetof( AudioSettings, m_minVolume) },
{ "RangeVolumeFade", INI::parseBool, NULL, offsetof( AudioSettings, m_rangeVolumeFade) },
+ { "SpeedOfSound", INI::parseReal, NULL, offsetof( AudioSettings, m_speedOfSound) },
+ { "MaxSoundDelay", INI::parseReal, NULL, offsetof( AudioSettings, m_maxSoundDelay) },
+ { "DopplerScale", INI::parseReal, NULL, offsetof( AudioSettings, m_dopplerScale) },
+ { "AirAbsorptionDistance", INI::parseReal, NULL, offsetof( AudioSettings, m_airAbsorptionDistance) },
+ { "ReverbLevel", INI::parsePercentToReal, NULL, offsetof( AudioSettings, m_reverbLevel) },
+ { "DuckVolume", INI::parsePercentToReal, NULL, offsetof( AudioSettings, m_duckVolume) },
+ { "DuckTime", INI::parseReal, NULL, offsetof( AudioSettings, m_duckTime) },
+ { "DuckSounds", INI::parseAsciiStringVector, NULL, offsetof( AudioSettings, m_duckSounds) },
{ "GlobalMinRange", INI::parseInt, NULL, offsetof( AudioSettings, m_globalMinRange) },
{ "GlobalMaxRange", INI::parseInt, NULL, offsetof( AudioSettings, m_globalMaxRange) },
{ "TimeBetweenDrawableSounds", INI::parseDurationUnsignedInt, NULL, offsetof( AudioSettings, m_drawableAmbientFrames) },
@@ -557,6 +565,22 @@ AudioHandle AudioManager::addAudioEventNow(const AudioEventRTS *eventToAdd, Audi
((AudioEventRTS*)eventToAdd)->setPlayingAudioIndex( audioEvent->getPlayingAudioIndex() );
audioEvent->generatePlayInfo(); // generate pitch shift and volume shift now as well
+ // Sound takes time to arrive: a world sound starts late by its distance to the microphone over
+ // SpeedOfSound, at most MaxSoundDelay, on top of the delay its INI gives it. Not a unit's voice,
+ // which answers the player, and not a script's sound, which logic waits on in the same frame. The
+ // request list counts the delay down in logic time (MilesAudioManager::processRequestList).
+ const AudioEventInfo *info = eventToAdd->getAudioEventInfo();
+ const Real speedOfSound = getAudioSettings()->m_speedOfSound;
+ if (info->m_soundType == AT_SoundEffect && audioEvent->isPositionalAudio() && !eventToAdd->getIsLogicalAudio()
+ && !BitTest(info->m_type, ST_VOICE) && speedOfSound > 0.0f)
+ {
+ Coord3D toMicrophone = *audioEvent->getCurrentPosition();
+ toMicrophone.sub(&m_listenerPosition);
+ const Real travelMs = toMicrophone.length() / speedOfSound * MSEC_PER_SECOND;
+ const Real maxMs = getAudioSettings()->m_maxSoundDelay;
+ audioEvent->setDelay(audioEvent->getDelay() + (travelMs < maxMs ? travelMs : maxMs));
+ }
+
std::list<std::pair<AsciiString, Real> >::iterator it;
for (it = m_adjustedVolumes.begin(); it != m_adjustedVolumes.end(); ++it) {
if (it->first == audioEvent->getEventName()) {
diff --git a/GeneralsMD/Code/GameEngineDevice/Include/MilesAudioDevice/MilesAudioManager.h b/GeneralsMD/Code/GameEngineDevice/Include/MilesAudioDevice/MilesAudioManager.h
index 45a15c916..da7baf1b1 100644
--- a/GeneralsMD/Code/GameEngineDevice/Include/MilesAudioDevice/MilesAudioManager.h
+++ b/GeneralsMD/Code/GameEngineDevice/Include/MilesAudioDevice/MilesAudioManager.h
@@ -85,6 +85,11 @@ struct PlayingAudio
/// happens in processPlayingList holding both locks rather than wherever the fade is asked for.
Bool m_fade;
Int m_framesFaded;
+ /// Doppler's velocity for a 3D sound, units a second, and where the source was the last time the
+ /// logic clock had moved (MilesAudioManager::trackVelocity).
+ Bool m_tracked;
+ Coord3D m_lastPosition;
+ Coord3D m_velocity;
PlayingAudio() :
m_type(PAT_INVALID),
@@ -96,8 +101,12 @@ struct PlayingAudio
m_sample(0),
m_3DSample(0),
m_stream(0),
- m_framesFaded(0)
- { }
+ m_framesFaded(0),
+ m_tracked(false)
+ {
+ m_lastPosition.zero();
+ m_velocity.zero();
+ }
/// An entry past PS_Playing is waiting for the sweep that frees it: its Miles handle may already
/// be back in the pool, so it must not be counted, touched or picked as a victim.
@@ -243,6 +252,10 @@ class MilesAudioManager : public AudioManager
Bool shouldProcessRequestThisFrame( AudioRequest *req ) const;
void adjustRequest( AudioRequest *req );
+ void advanceAudioClock( void );
+ void trackVelocity( PlayingAudio *playing, const Coord3D *pos );
+ void setRoomFromMap( void );
+ void duckForBlast( AudioEventRTS *event, H3DSAMPLE sample3D );
Bool checkForSample( AudioRequest *req );
virtual void setHardwareAccelerated(Bool accel);
@@ -325,6 +338,13 @@ class MilesAudioManager : public AudioManager
H3DPOBJECT m_listener;
HPROVIDER m_delayFilter;
+ /// The logic clock as update() last read it, and the milliseconds of logic time since the read
+ /// before: the request list's delays and doppler's velocity run on it, so both keep to the
+ /// picture at any render rate and in a -wav run. Out of a game a pass counts as one frame.
+ UnsignedInt m_clockFrame;
+ Real m_clockElapsedMs;
+ AsciiString m_roomMap; ///< the map setRoomFromMap last set the room for
+
// LOGIC-THREAD.md M7: what the tick asks, as captureForLogic found it at the sync point
std::vector<AudioHandle> m_playingAtSync; ///< every handle isCurrentlyPlaying said yes to, sorted
std::vector< std::pair<AsciiString, Int> > m_musicLoopsAtSync; ///< each music stream and the loops it has finished
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/MilesAudioDevice/MilesAudioManager.cpp b/GeneralsMD/Code/GameEngineDevice/Source/MilesAudioDevice/MilesAudioManager.cpp
index 3aec96877..c6c2c02b2 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/MilesAudioDevice/MilesAudioManager.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/MilesAudioDevice/MilesAudioManager.cpp
@@ -59,6 +59,8 @@
#include "Common/CRCDebug.h"
#include "Common/GlobalData.h"
#include "Common/LogicThread.h"
+#include "Common/MapObject.h"
+#include "Common/ThingTemplate.h"
#include "Common/ScopedMutex.h"
#include <algorithm>
@@ -137,6 +139,8 @@ MilesAudioManager::MilesAudioManager() :
m_num3DSamples(0),
m_numStreams(0),
m_delayFilter(NULL),
+ m_clockFrame(0),
+ m_clockElapsedMs(MSEC_PER_LOGICFRAME_REAL),
m_binkHandle(NULL),
m_pref3DProvider(AsciiString::TheEmptyString),
m_prefSpeaker(AsciiString::TheEmptyString)
@@ -595,6 +599,12 @@ void MilesAudioManager::update()
AudioManager::update();
processCompletedAudio();
updateSoundCapture();
+ advanceAudioClock();
+ if (TheGameLogic->isInGame() && !TheGameLogic->isLoadingMap() && m_roomMap != TheGlobalData->m_mapName)
+ {
+ m_roomMap = TheGlobalData->m_mapName;
+ setRoomFromMap();
+ }
setDeviceListenerPosition();
processRequestList();
processPlayingList();
@@ -932,6 +942,9 @@ void MilesAudioManager::playAudioEvent( AudioEventRTS *event, Bool requestStop )
if (sample3D) {
audio->m_file = playSample3D(event, sample3D);
m_sound->notifyOf3DSampleStart();
+ if (audio->m_file) {
+ duckForBlast(event, sample3D);
+ }
}
if( !audio->m_file )
@@ -1586,7 +1599,8 @@ void MilesAudioManager::initFilters3D( H3DSAMPLE sample, const AudioEventRTS *ev
AIL_set_3D_sample_playback_rate(sample, REAL_TO_INT(AIL_3D_sample_playback_rate(sample) * pitchShift));
}
- // Low pass filter
+ // Low pass filter: a real one now, a ceiling on the cutoff air already lowers with distance
+ // (MSS.h's AIL_ex_3D_cutoff), where it used to be a cut in volume
if (event->getAudioEventInfo()->m_lowPassFreq > 0 && !isOnScreen(pos) ) {
AIL_set_3D_sample_occlusion(sample, 1.0f - event->getAudioEventInfo()->m_lowPassFreq);
}
@@ -1726,6 +1740,7 @@ void MilesAudioManager::openDevice( void )
// AIL_quick_startup should be replaced later with a call to actually pick which device to use, etc
const AudioSettings *audioSettings = getAudioSettings();
AIL_ex_set_3D_linear_falloff(audioSettings->m_rangeVolumeFade);
+ AIL_ex_set_3D_air(audioSettings->m_speedOfSound, audioSettings->m_airAbsorptionDistance);
m_selectedSpeakerType = TheAudio->translateSpeakerTypeToUnsignedInt(m_prefSpeaker);
retval = AIL_quick_startup(audioSettings->m_useDigital, audioSettings->m_useMidi, audioSettings->m_outputRate, audioSettings->m_outputBits, audioSettings->m_outputChannels);
@@ -2720,8 +2735,9 @@ void MilesAudioManager::processPlayingList( void )
stopPlayingAudio( playing );
continue;
}
- else
+ else
{
+ trackVelocity( playing, pos );
Real x = pos->x;
Real y = pos->y;
Real z = pos->z;
@@ -2869,10 +2885,121 @@ void MilesAudioManager::adjustRequest( AudioRequest *req )
return;
}
- req->m_pendingEvent->decrementDelay(MSEC_PER_LOGICFRAME_REAL);
+ // Logic time, not a frame's worth a pass: at 120 fps that ran every delay twice as fast as the
+ // picture, and a sound held back by its distance has to land with what is seen.
+ req->m_pendingEvent->decrementDelay(m_clockElapsedMs);
req->m_requiresCheckForSample = true;
}
+//-------------------------------------------------------------------------------------------------
+/** m_clockElapsedMs: the logic time since the last update, which is nothing on a pass drawn between
+ * two logic frames and several frames' worth on a pass that caught up. Out of a game the logic
+ * clock stands still, and a pass counts as one frame, as every pass used to. */
+void MilesAudioManager::advanceAudioClock( void )
+{
+ if (!TheGameLogic->isInGame())
+ {
+ m_clockElapsedMs = MSEC_PER_LOGICFRAME_REAL;
+ return;
+ }
+
+ // a new match starts its clock at nought again, and the first pass of it counts nothing
+ const UnsignedInt frame = TheGameLogic->getFrame();
+ m_clockElapsedMs = frame > m_clockFrame ? (Real)(frame - m_clockFrame) * MSEC_PER_LOGICFRAME_REAL : 0.0f;
+ m_clockFrame = frame;
+}
+
+//-------------------------------------------------------------------------------------------------
+/** Doppler's velocity: how far the source moved over the logic time since the last pass the clock
+ * moved on. A drawable's position is the smoothed one, read at whatever point between two logic
+ * frames the pass fell, so each reading only takes the velocity half way there, which keeps a flyby's
+ * pitch from warbling. The backend takes the speed towards the microphone (AIL_ex_doppler_ratio). */
+void MilesAudioManager::trackVelocity( PlayingAudio *playing, const Coord3D *pos )
+{
+ if (m_clockElapsedMs <= 0.0f)
+ return;
+
+ if (playing->m_tracked)
+ {
+ const Real perSecond = MSEC_PER_SECOND / m_clockElapsedMs;
+ playing->m_velocity.x += 0.5f * ((pos->x - playing->m_lastPosition.x) * perSecond - playing->m_velocity.x);
+ playing->m_velocity.y += 0.5f * ((pos->y - playing->m_lastPosition.y) * perSecond - playing->m_velocity.y);
+ playing->m_velocity.z += 0.5f * ((pos->z - playing->m_lastPosition.z) * perSecond - playing->m_velocity.z);
+ const Real scale = m_audioSettings->m_dopplerScale;
+ AIL_set_3D_velocity_vector( playing->m_3DSample, playing->m_velocity.x * scale, playing->m_velocity.y * scale,
+ playing->m_velocity.z * scale );
+ }
+ playing->m_lastPosition = *pos;
+ playing->m_tracked = TRUE;
+}
+
+//-------------------------------------------------------------------------------------------------
+/** The room the map's world sounds send into (AIL_ex_set_reverb), from the map itself: how much of
+ * its playable ground the placed structures cover. Supply docks are left out, being on every map at
+ * a third to a full percent of it. The shipped maps measured that way run from about 0.1% (Twilight
+ * Flame, Tournament Tundra) to near 3% (Tournament Urban, El Scorcho), and the room goes from open
+ * ground at 0.3%, a faint, short, dark tail, to a town at 1.9%, a longer and brighter one with an
+ * echo off the walls. Snow takes half the room away and most of its top end. The object list is
+ * the map file's, which the terrain keeps until the next map, so nothing in logic is asked. */
+void MilesAudioManager::setRoomFromMap( void )
+{
+ Real built = 0.0f;
+ for (MapObject *mapObject = MapObject::getFirstMapObject(); mapObject; mapObject = mapObject->getNext())
+ {
+ const ThingTemplate *thing = mapObject->getThingTemplate();
+ // waypoints, lights and other markers have no template
+ if (thing && thing->isKindOf(KINDOF_STRUCTURE) && !thing->isKindOf(KINDOF_SUPPLY_SOURCE))
+ built += thing->getTemplateGeometryInfo().getFootprintArea();
+ }
+ Region3D extent;
+ TheTerrainLogic->getExtent(&extent);
+ const Real cover = built / (extent.width() * extent.height());
+
+ const Real OPEN_COVER = 0.003f;
+ const Real TOWN_COVER = 0.019f;
+ Real town = (cover - OPEN_COVER) / (TOWN_COVER - OPEN_COVER);
+ town = town < 0.0f ? 0.0f : (town > 1.0f ? 1.0f : town);
+
+ Real wet = 0.06f + 0.24f * town;
+ Real decay = 0.7f + 1.1f * town;
+ Real damping = 0.6f - 0.3f * town;
+ const Real echo = town >= 0.3f ? 0.04f + 0.05f * town : 0.0f;
+ if (TheGlobalData->m_weather == WEATHER_SNOWY)
+ {
+ wet *= 0.5f;
+ decay *= 0.7f;
+ damping = damping > 0.85f ? damping : 0.85f;
+ }
+ AIL_ex_set_reverb(wet * m_audioSettings->m_reverbLevel, decay, damping, echo);
+ DEBUG_LOG(("AUDIO: room for %s: %.2f%% built over, town %.2f%s, send %.2f, decay %.2f s, damping %.2f, echo %d ms\n",
+ m_roomMap.str(), cover * 100.0f, town, TheGlobalData->m_weather == WEATHER_SNOWY ? " in snow" : "",
+ wet * m_audioSettings->m_reverbLevel, decay, damping, (Int)(echo * 1000.0f)));
+}
+
+//-------------------------------------------------------------------------------------------------
+/** A big blast (DuckSounds) dips everything else for DuckTime, down to DuckVolume, as far as the blast
+ * is loud at the microphone: by the square root of its distance gain, so a nuke across the map
+ * still leans on the mix and one out of its range does nothing. Asked when the blast starts, so a
+ * far one ducks when it is heard rather than when it is seen; a loop that ducks does so once. */
+void MilesAudioManager::duckForBlast( AudioEventRTS *event, H3DSAMPLE sample3D )
+{
+ const AudioSettings *settings = m_audioSettings;
+ if (settings->m_duckVolume >= 1.0f
+ || std::find(settings->m_duckSounds.begin(), settings->m_duckSounds.end(), event->getEventName()) == settings->m_duckSounds.end())
+ return;
+
+ const AudioEventInfo *info = event->getAudioEventInfo();
+ const Bool global = BitTest(info->m_type, ST_GLOBAL);
+ Coord3D toMicrophone = *getCurrentPositionFromEvent(event);
+ toMicrophone.sub(&m_listenerPosition);
+ const Real nearness = sqrtf(AIL_ex_3D_distance_gain(toMicrophone.length(),
+ global ? (Real)settings->m_globalMinRange : info->m_minDistance,
+ global ? (Real)settings->m_globalMaxRange : info->m_maxDistance, settings->m_rangeVolumeFade));
+ if (nearness <= 0.0f)
+ return;
+ AIL_ex_duck(sample3D, 1.0f - (1.0f - settings->m_duckVolume) * nearness, settings->m_duckTime / MSEC_PER_SECOND);
+}
+
//-------------------------------------------------------------------------------------------------
Bool MilesAudioManager::checkForSample( AudioRequest *req )
{
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/include/MSS/MSS.h b/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/include/MSS/MSS.h
index 70996b9aa..b1dcc43aa 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/include/MSS/MSS.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/include/MSS/MSS.h
@@ -29,6 +29,8 @@
#include "mss_backend_names.h"
#endif
+#include <math.h> /* the inline helpers at the end */
+
/* The real Mss.H pulls in the Windows multimedia headers; WWAudio relies on
* that for LPWAVEFORMAT in its Miles-facing signatures. */
#if defined(_WIN32)
@@ -284,6 +286,24 @@ void AILCALL AIL_ex_capture_length(S32 *frames, S32 *rate);
RangeVolumeFade, so what plays and what getEffectiveVolume culls follow one curve. */
void AILCALL AIL_ex_set_3D_linear_falloff(S32 linear);
+/* ---- air, room and duck ------------------------------------------------ */
+/* Not Miles. What MilesAudioManager hands down from AudioSettings.ini and the map.
+ *
+ * AIL_ex_set_3D_air: the speed of sound in game units a second, for doppler on the velocity
+ * AIL_set_3D_velocity_vector gives a 3D sample (units a second as well), and the distance
+ * AIL_ex_3D_cutoff takes for air absorption. Zero switches either off; both start off.
+ *
+ * AIL_ex_set_reverb: the one room every 3D sample sends to. wet is the send of a sample at full
+ * volume (zero takes the room away), decay the seconds its tail takes to fall 60 dB, damping (0 to 1)
+ * how much sooner the top end dies, echo the seconds before the first reflection comes back.
+ *
+ * AIL_ex_duck: everything but the trigger, and any earlier trigger still sounding, dips to gain and
+ * comes back over seconds, AIL_ex_duck_gain's shape. miniaudio counts that time in frames mixed, so
+ * a -wav run ducks on the picture's clock; XAudio2 counts it on the wall clock it plays on. */
+void AILCALL AIL_ex_set_3D_air(F32 speed_of_sound, F32 absorption_distance);
+void AILCALL AIL_ex_set_reverb(F32 wet, F32 decay, F32 damping, F32 echo);
+void AILCALL AIL_ex_duck(H3DSAMPLE trigger, F32 gain, F32 seconds);
+
/* ---- file format helpers ---------------------------------------------- */
S32 AILCALL AIL_WAV_info(const void *data, AILSOUNDINFO *info);
S32 AILCALL AIL_decompress_ADPCM(const AILSOUNDINFO *info, void **outdata, U32 *outsize);
@@ -308,4 +328,74 @@ static inline F32 AIL_ex_3D_distance_gain(F32 distance, F32 min_dist, F32 max_di
return min_dist / distance;
}
+/* Not Miles, and like the distance curve kept here so the two backends cannot drift: the rest of a
+ 3D sample's sound. Both play the low-pass below as a one-pole filter after the voice's resampler,
+ at the output rate, which is where XAudio2 runs a source voice's filter. */
+#define AIL_EX_OPEN_CUTOFF 20000.0f
+
+/* The cutoff in Hz. Air takes the top off with distance: 20 kHz close, half that at
+ absorption_distance and falling with the square of the distance past it, so a blast across the map
+ is a rumble. Occlusion is EA's LowPassCutoff, which MilesAudioManager hands down as 1 - cutoff for
+ a sound off screen; it used to be a cut in volume and is a ceiling now, 20 kHz times (1 - occlusion)
+ squared: 5 kHz for the shipped 50%. */
+static inline F32 AIL_ex_3D_cutoff(F32 distance, F32 absorption_distance, F32 occlusion)
+{
+ F32 cutoff = AIL_EX_OPEN_CUTOFF;
+ if (absorption_distance > 0.0f) {
+ const F32 ratio = distance / absorption_distance;
+ cutoff /= 1.0f + ratio * ratio;
+ }
+ const F32 open = 1.0f - occlusion;
+ const F32 ceiling = AIL_EX_OPEN_CUTOFF * open * open;
+ return cutoff < ceiling ? cutoff : ceiling;
+}
+
+/* y += a * (x - y) for a cutoff at a rate: XAudio2CutoffFrequencyToOnePoleCoefficient, held at 1 (no
+ filter at all) for an open cutoff and from half the rate up, where that helper turns round and
+ closes again. */
+static inline F32 AIL_ex_one_pole_coefficient(F32 cutoff, F32 rate)
+{
+ if (cutoff >= AIL_EX_OPEN_CUTOFF || cutoff * 2.0f >= rate)
+ return 1.0f;
+ const F32 k = 1.0f - 2.0f * cutoff / rate;
+ return 1.0f - k * k;
+}
+
+/* The pitch ratio of a source moving at (vx, vy, vz), (dx, dy, dz) from the listener. The listener
+ counts as standing still: it is the camera, and a scroll would bend every sound on the map at once.
+ The speed towards the listener is held to half the speed of sound either way, a ratio of 2/3 to 2. */
+static inline F32 AIL_ex_doppler_ratio(F32 dx, F32 dy, F32 dz, F32 vx, F32 vy, F32 vz, F32 speed_of_sound)
+{
+ const F32 distance = sqrtf(dx * dx + dy * dy + dz * dz);
+ if (speed_of_sound <= 0.0f || distance < 0.0001f)
+ return 1.0f;
+ F32 approach = -(vx * dx + vy * dy + vz * dz) / distance;
+ const F32 limit = 0.5f * speed_of_sound;
+ if (approach > limit) approach = limit;
+ if (approach < -limit) approach = -limit;
+ return speed_of_sound / (speed_of_sound - approach);
+}
+
+/* The send into the room: the dry sound falls with the distance gain, the room's share only with its
+ square root, so a far sound is mostly room, and nothing reaches it past the maximum distance. */
+static inline F32 AIL_ex_3D_send(F32 volume, F32 attenuation, F32 wet)
+{
+ return volume * wet * sqrtf(attenuation);
+}
+
+/* The duck's gain `elapsed` seconds after it began: down to `gain` over 50 ms, held for a quarter of
+ `seconds`, then a straight line back to full by `seconds`. */
+static inline F32 AIL_ex_duck_gain(F32 elapsed, F32 gain, F32 seconds)
+{
+ const F32 attack = 0.05f;
+ const F32 hold = 0.25f * seconds > attack ? 0.25f * seconds : attack;
+ if (elapsed < 0.0f || elapsed >= seconds)
+ return 1.0f;
+ if (elapsed < attack)
+ return 1.0f - (1.0f - gain) * elapsed / attack;
+ if (elapsed < hold)
+ return gain;
+ return gain + (1.0f - gain) * (elapsed - hold) / (seconds - hold);
+}
+
#endif /* MSS_H */
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/include/MSS/mss_backend_names.h b/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/include/MSS/mss_backend_names.h
index 5ff7c4a47..e04d6de0d 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/include/MSS/mss_backend_names.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/include/MSS/mss_backend_names.h
@@ -83,6 +83,9 @@
#define AIL_ex_mix_to_frame MSS_BACKEND_NAME(AIL_ex_mix_to_frame)
#define AIL_ex_capture_length MSS_BACKEND_NAME(AIL_ex_capture_length)
#define AIL_ex_set_3D_linear_falloff MSS_BACKEND_NAME(AIL_ex_set_3D_linear_falloff)
+#define AIL_ex_set_3D_air MSS_BACKEND_NAME(AIL_ex_set_3D_air)
+#define AIL_ex_set_reverb MSS_BACKEND_NAME(AIL_ex_set_reverb)
+#define AIL_ex_duck MSS_BACKEND_NAME(AIL_ex_duck)
#define AIL_WAV_info MSS_BACKEND_NAME(AIL_WAV_info)
#define AIL_decompress_ADPCM MSS_BACKEND_NAME(AIL_decompress_ADPCM)
#define AIL_mem_free_lock MSS_BACKEND_NAME(AIL_mem_free_lock)
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/miles_dispatch.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/miles_dispatch.cpp
index f8694afc7..0d2142631 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/miles_dispatch.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/miles_dispatch.cpp
@@ -81,6 +81,9 @@
MSS_API(S32, AIL_ex_start_capture, (const char *pathname), (pathname)) \
MSS_API(void, AIL_ex_stop_capture, (void), ()) \
MSS_API(void, AIL_ex_set_3D_linear_falloff, (S32 linear), (linear)) \
+ MSS_API(void, AIL_ex_set_3D_air, (F32 speed_of_sound, F32 absorption_distance), (speed_of_sound, absorption_distance)) \
+ MSS_API(void, AIL_ex_set_reverb, (F32 wet, F32 decay, F32 damping, F32 echo), (wet, decay, damping, echo)) \
+ MSS_API(void, AIL_ex_duck, (H3DSAMPLE trigger, F32 gain, F32 seconds), (trigger, gain, seconds)) \
MSS_API(S32, AIL_WAV_info, (const void *data, AILSOUNDINFO *info), (data, info)) \
MSS_API(S32, AIL_decompress_ADPCM, (const AILSOUNDINFO *info, void **outdata, U32 *outsize), (info, outdata, outsize)) \
MSS_API(void, AIL_mem_free_lock, (void *ptr), (ptr))
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/miniaudio/miles_miniaudio.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/miniaudio/miles_miniaudio.cpp
index 0e9a2b952..05103802a 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/miniaudio/miles_miniaudio.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/miniaudio/miles_miniaudio.cpp
@@ -32,7 +32,10 @@
* HSTREAM / HAUDIO -> a file decoded by miniaudio through the game's own file callbacks, into
* ~200ms chunks the service thread keeps four ahead of the mixer.
* 3D positioning -> the same distance attenuation and stereo pan miles_xaudio2 computes,
- * not miniaudio's spatializer.
+ * not miniaudio's spatializer. The air, room and duck of MSS.h too, by the
+ * same helpers: a one-pole low-pass where XAudio2 sets the voice's filter,
+ * the resampler's rate for doppler, and a small reverb of its own (Room
+ * below) where XAudio2 has a submix running its built-in one.
* the mix -> done here, in miniaudio's device callback, so that the output matrix is
* exactly XAudio2's: every source channel summed into left and right at
* the pan's two gains.
@@ -299,13 +302,19 @@ unsigned int decodeAdpcm(const WaveImage &wave, std::vector<short> *out)
struct VoiceMix
{
- VoiceMix() : resamplerReady(false), channels(0), gainLeft(0.0f), gainRight(0.0f), passThrough(false), pending(0), pendingAt(0) {}
+ VoiceMix() : resamplerReady(false), channels(0), gainLeft(0.0f), gainRight(0.0f), lowPass(1.0f), lowPassState(0.0f),
+ roomSend(0.0f), passThrough(false), pending(0), pendingAt(0) {}
ma_resampler resampler;
bool resamplerReady;
unsigned channels;
float gainLeft;
float gainRight;
+ // A 3D sample's air and occlusion, XAudio2's LowPassOnePoleFilter on the resampled sum: y += a(x - y),
+ // a = 1 passing it untouched. And its share into the room.
+ float lowPass;
+ float lowPassState;
+ float roomSend;
// An XAudio2 voice with the default matrix rather than a panned Miles one: left to left and right
// to right (a mono source to both), each at its gain. The movies' voice (mss_ex_pcm.h).
bool passThrough;
@@ -350,15 +359,21 @@ void resetResampler(VoiceMix *mix)
}
mix->pending = 0;
mix->pendingAt = 0;
+ mix->lowPassState = 0.0f;
}
// Fills up to maxFrames of float source frames. Returns how many it gave; 0 means the source is dry.
typedef unsigned (*SourceRead)(void *source, float *out, unsigned maxFrames);
-// Mixes up to `frames` output frames of one voice into `output`. Returns true once the source is
-// dry and nothing is left in flight, which is XAudio2's BuffersQueued == 0.
-bool mixVoice(VoiceMix *mix, SourceRead read, void *source, float *output, unsigned frames, bool *sourceDry)
+// Mixes up to `frames` output frames of one voice into `output`, at `duck` (AIL_ex_duck) on top of its
+// gains, and its send into `room` when there is one. Returns true once the source is dry and nothing
+// is left in flight, which is XAudio2's BuffersQueued == 0.
+bool mixVoice(VoiceMix *mix, SourceRead read, void *source, float *output, unsigned frames, bool *sourceDry,
+ float duck, float *room)
{
+ const float left = mix->gainLeft * duck;
+ const float right = mix->gainRight * duck;
+ const float send = mix->roomSend * duck;
float resampled[MIX_CHUNK_FRAMES * 2];
unsigned done = 0;
@@ -380,19 +395,25 @@ bool mixVoice(VoiceMix *mix, SourceRead read, void *source, float *output, unsig
&inFrames, resampled, &outFrames);
for (ma_uint64 frame = 0; mix->passThrough && frame < outFrames; ++frame) {
- const float left = resampled[frame * mix->channels];
- const float right = mix->channels >= 2 ? resampled[frame * mix->channels + 1] : left;
- output[(done + frame) * OUTPUT_CHANNELS + 0] += mix->gainLeft * left;
- output[(done + frame) * OUTPUT_CHANNELS + 1] += mix->gainRight * right;
+ const float sourceLeft = resampled[frame * mix->channels];
+ const float sourceRight = mix->channels >= 2 ? resampled[frame * mix->channels + 1] : sourceLeft;
+ output[(done + frame) * OUTPUT_CHANNELS + 0] += left * sourceLeft;
+ output[(done + frame) * OUTPUT_CHANNELS + 1] += right * sourceRight;
}
for (ma_uint64 frame = 0; !mix->passThrough && frame < outFrames; ++frame) {
// XAudio2's matrix row for each output speaker has every source channel at the same gain.
+ // The filter is linear, so filtering the sum is filtering each channel and summing.
float sum = 0.0f;
for (unsigned channel = 0; channel < mix->channels; ++channel) {
sum += resampled[frame * mix->channels + channel];
}
- output[(done + frame) * OUTPUT_CHANNELS + 0] += mix->gainLeft * sum;
- output[(done + frame) * OUTPUT_CHANNELS + 1] += mix->gainRight * sum;
+ mix->lowPassState += mix->lowPass * (sum - mix->lowPassState);
+ sum = mix->lowPassState;
+ output[(done + frame) * OUTPUT_CHANNELS + 0] += left * sum;
+ output[(done + frame) * OUTPUT_CHANNELS + 1] += right * sum;
+ if (room != NULL) {
+ room[done + frame] += send * sum;
+ }
}
mix->pendingAt += (unsigned)inFrames;
@@ -427,13 +448,16 @@ struct Sample
float positionX, positionY, positionZ;
float minDistance, maxDistance;
float occlusion;
+ float velocityX, velocityY, velocityZ; // units a second, AIL_set_3D_velocity_vector
// What the mix sees, under mixLock. `running` is the voice started, `queued` its one buffer
- // still in it, `cursor` the next source frame.
+ // still in it, `cursor` the next source frame. `unducked`: it started a duck, which leaves it
+ // alone until the duck is over.
bool running;
bool queued;
unsigned int cursor;
bool sourceDry;
+ bool unducked;
VoiceMix mix;
};
@@ -504,10 +528,125 @@ struct Capture
unsigned int sizesWrittenAt;
};
+// ---------------------------------------------------------------------------------------------
+// The room (AIL_ex_set_reverb): the reverb every 3D sample sends to. XAudio2 has one built in and
+// miniaudio has none, so this is a small one of Freeverb's shape, cut to four combs and two
+// all-passes a side. The send goes through the echo first, a delay that is also heard once on its
+// own (a street of buildings answering), then into the combs, damped in their feedback, and out
+// through the all-passes that smear them. Mono in; the right side's lines are 23 samples longer than
+// the left's, Freeverb's spread, for width. Under mixLock.
+// ---------------------------------------------------------------------------------------------
+
+const unsigned ROOM_COMBS = 4;
+const unsigned ROOM_ALLPASSES = 2;
+const unsigned ROOM_COMB_LENGTHS[ROOM_COMBS] = { 1116, 1188, 1277, 1356 }; // Freeverb's, at 44.1 kHz
+const unsigned ROOM_ALLPASS_LENGTHS[ROOM_ALLPASSES] = { 556, 441 };
+const unsigned ROOM_STEREO_SPREAD = 23;
+const float ROOM_TUNING_RATE = 44100.0f;
+const float ROOM_ALLPASS_FEEDBACK = 0.5f;
+const float ROOM_INPUT_GAIN = 0.25f; // four combs at a second-long decay answer at about the send's level
+const float ROOM_ECHO_GAIN = 0.35f;
+const float ROOM_MAX_DAMPING = 0.7f;
+const float ROOM_MAX_ECHO_SECONDS = 0.3f; // I3DL2's ReflectionsDelay limit, where miles_xaudio2 puts the echo
+const float ROOM_DENORMAL_GUARD = 1e-18f; // keeps a dying tail out of the denormals, which x64 does slowly
+
+struct DelayLine
+{
+ DelayLine() : at(0), feedback(0.0f), store(0.0f) {}
+
+ std::vector<float> line;
+ size_t at;
+ float feedback;
+ float store; // a comb's damping filter
+};
+
+struct Room
+{
+ Room() : ready(false), rate(0), damping(0.0f), echoLength(0) {}
+
+ bool ready;
+ unsigned rate;
+ float damping;
+ DelayLine echo;
+ size_t echoLength;
+ DelayLine combs[2][ROOM_COMBS];
+ DelayLine allpasses[2][ROOM_ALLPASSES];
+};
+
+void initRoom(Room *room, unsigned rate)
+{
+ const float scale = (float)rate / ROOM_TUNING_RATE;
+ for (unsigned side = 0; side < 2; ++side) {
+ for (unsigned i = 0; i < ROOM_COMBS; ++i) {
+ room->combs[side][i].line.assign((size_t)((ROOM_COMB_LENGTHS[i] + side * ROOM_STEREO_SPREAD) * scale), 0.0f);
+ }
+ for (unsigned i = 0; i < ROOM_ALLPASSES; ++i) {
+ room->allpasses[side][i].line.assign((size_t)((ROOM_ALLPASS_LENGTHS[i] + side * ROOM_STEREO_SPREAD) * scale), 0.0f);
+ }
+ }
+ room->echo.line.assign((size_t)(ROOM_MAX_ECHO_SECONDS * rate) + 1, 0.0f);
+ room->rate = rate;
+ room->ready = true;
+}
+
+void setRoom(Room *room, float decay, float damping, float echo)
+{
+ if (!room->ready) {
+ return;
+ }
+ // each comb loses 60 dB in `decay` seconds: a gain per trip of 0.001 to the power of trips that long
+ for (unsigned side = 0; side < 2; ++side) {
+ for (unsigned i = 0; i < ROOM_COMBS; ++i) {
+ DelayLine &comb = room->combs[side][i];
+ comb.feedback = powf(0.001f, (float)comb.line.size() / (decay * (float)room->rate));
+ }
+ }
+ room->damping = damping * ROOM_MAX_DAMPING;
+ const size_t echoLength = echo > 0.0f ? (size_t)(echo * (float)room->rate) : 0;
+ room->echoLength = echoLength < room->echo.line.size() ? echoLength : room->echo.line.size() - 1;
+ room->echo.at = room->echoLength > 0 ? room->echo.at % room->echoLength : 0;
+}
+
+// Adds the room's answer to `input` (mono, the sends of one mix pass) into the stereo `output`.
+void processRoom(Room *room, const float *input, float *output, unsigned frames)
+{
+ for (unsigned frame = 0; frame < frames; ++frame) {
+ float in = input[frame];
+ float echoed = 0.0f;
+ if (room->echoLength > 0) {
+ DelayLine &echo = room->echo;
+ echoed = echo.line[echo.at];
+ echo.line[echo.at] = in;
+ echo.at = (echo.at + 1) % room->echoLength;
+ in = echoed;
+ }
+ for (unsigned side = 0; side < 2; ++side) {
+ float sum = 0.0f;
+ for (unsigned i = 0; i < ROOM_COMBS; ++i) {
+ DelayLine &comb = room->combs[side][i];
+ const float out = comb.line[comb.at];
+ comb.store = out + room->damping * (comb.store - out);
+ comb.line[comb.at] = in * ROOM_INPUT_GAIN + comb.store * comb.feedback + ROOM_DENORMAL_GUARD;
+ comb.at = (comb.at + 1) % comb.line.size();
+ sum += out;
+ }
+ for (unsigned i = 0; i < ROOM_ALLPASSES; ++i) {
+ DelayLine &pass = room->allpasses[side][i];
+ const float held = pass.line[pass.at];
+ pass.line[pass.at] = sum + held * ROOM_ALLPASS_FEEDBACK;
+ pass.at = (pass.at + 1) % pass.line.size();
+ sum = held - sum;
+ }
+ output[frame * OUTPUT_CHANNELS + side] += sum + echoed * ROOM_ECHO_GAIN;
+ }
+ }
+}
+
struct Engine
{
Engine() : contextReady(false), deviceReady(false), serviceRunning(false), started(false), deviceRate(0),
- capture(NULL), offline(false), mixAnchored(false), mixedFrames(0), capturedFrames(0), capturedRate(0) {}
+ capture(NULL), duckActive(false), duckFrames(0), duckGain(1.0f), duckSeconds(0.0f), offline(false),
+ mixAnchored(false), mixedFrames(0), capturedFrames(0), capturedRate(0) {}
// A process can end without AIL_shutdown - a test, or a game that exits in a hurry - and a
// std::thread still joinable at destruction calls std::terminate. The Windows build's service
@@ -544,6 +683,15 @@ struct Engine
unsigned deviceRate;
Capture *capture;
+ // Under mixLock: the room and one mix pass's sends into it, and AIL_ex_duck, timed in frames
+ // mixed so that a -wav run ducks on the logic clock.
+ Room room;
+ std::vector<float> roomInput;
+ bool duckActive;
+ long long duckFrames;
+ float duckGain;
+ float duckSeconds;
+
// AIL_ex_offline_mix: the device is opened on the null backend and never started, and the mix
// moves only through AIL_ex_mix_to_frame. mixedFrames is where the logic clock has it, in output
// frames from logic frame zero. Game thread only.
@@ -557,6 +705,9 @@ struct Engine
Engine g_engine;
std::atomic<S32> g_linearFalloff(0); // AIL_ex_set_3D_linear_falloff
+std::atomic<float> g_speedOfSound(0.0f); // AIL_ex_set_3D_air
+std::atomic<float> g_absorptionDistance(0.0f);
+std::atomic<float> g_roomSend(0.0f); // AIL_ex_set_reverb's wet
AILFILEOPENCB g_fileOpen;
AILFILECLOSECB g_fileClose;
@@ -585,7 +736,16 @@ void setGains(VoiceMix *mix, float volume, float pan)
mix->gainRight = voiceVolume * (float)sqrt(clampUnit(pan));
}
-void computeSpatialGain(const Sample &sample, float *volumeOut, float *panOut)
+struct Spatial
+{
+ float volume;
+ float pan;
+ float cutoff; // Hz, AIL_ex_3D_cutoff
+ float send; // into the room, AIL_ex_3D_send
+ float doppler; // pitch ratio, AIL_ex_doppler_ratio
+};
+
+Spatial computeSpatial(const Sample &sample)
{
const Listener &listener = g_engine.listener;
const float dx = sample.positionX - listener.positionX;
@@ -593,8 +753,7 @@ void computeSpatialGain(const Sample &sample, float *volumeOut, float *panOut)
const float dz = sample.positionZ - listener.positionZ;
const float distance = (float)sqrt(dx * dx + dy * dy + dz * dz);
- float attenuation = AIL_ex_3D_distance_gain(distance, sample.minDistance, sample.maxDistance, g_linearFalloff);
- attenuation *= clampUnit(1.0f - sample.occlusion);
+ const float attenuation = AIL_ex_3D_distance_gain(distance, sample.minDistance, sample.maxDistance, g_linearFalloff);
float pan = DEFAULT_PAN;
if (distance > 0.0001f) {
@@ -609,8 +768,13 @@ void computeSpatialGain(const Sample &sample, float *volumeOut, float *panOut)
}
}
- *volumeOut = clampUnit(sample.volume) * attenuation;
- *panOut = pan;
+ Spatial spatial;
+ spatial.volume = clampUnit(sample.volume) * attenuation;
+ spatial.pan = pan;
+ spatial.cutoff = AIL_ex_3D_cutoff(distance, g_absorptionDistance.load(), sample.occlusion);
+ spatial.send = AIL_ex_3D_send(clampUnit(sample.volume), attenuation, g_roomSend.load());
+ spatial.doppler = AIL_ex_doppler_ratio(dx, dy, dz, sample.velocityX, sample.velocityY, sample.velocityZ, g_speedOfSound.load());
+ return spatial;
}
// Called with the engine lock held; takes mixLock for what the mix reads.
@@ -622,19 +786,29 @@ void refreshSampleOutput(Sample *sample)
float volume = sample->volume;
float pan = sample->pan;
+ float doppler = 1.0f;
+ float lowPass = 1.0f;
+ float send = 0.0f;
if (sample->is3D) {
- computeSpatialGain(*sample, &volume, &pan);
+ const Spatial spatial = computeSpatial(*sample);
+ volume = spatial.volume;
+ pan = spatial.pan;
+ doppler = spatial.doppler;
+ lowPass = AIL_ex_one_pole_coefficient(spatial.cutoff, (float)g_engine.deviceRate);
+ send = spatial.send;
}
float ratio = 1.0f;
if (sample->baseRate != 0) {
- ratio = (float)sample->rate / (float)sample->baseRate;
+ ratio = (float)sample->rate / (float)sample->baseRate * doppler;
if (ratio < MIN_FREQ_RATIO) ratio = MIN_FREQ_RATIO;
if (ratio > MAX_FREQ_RATIO) ratio = MAX_FREQ_RATIO;
}
std::lock_guard<std::mutex> mixGuard(g_engine.mixLock);
setGains(&sample->mix, volume, pan);
+ sample->mix.lowPass = lowPass;
+ sample->mix.roomSend = send;
setResampleRate(&sample->mix, (float)sample->baseRate * ratio, g_engine.deviceRate);
}
@@ -1059,12 +1233,34 @@ void dataCallback(ma_device *, void *output, const void *, ma_uint32 frameCount)
memset(out, 0, (size_t)frameCount * OUTPUT_CHANNELS * sizeof(float));
std::lock_guard<std::mutex> mixGuard(g_engine.mixLock);
+
+ // One gain for the whole pass: a pass is ~10 ms and the duck moves over seconds.
+ float duck = 1.0f;
+ if (g_engine.duckActive) {
+ const float elapsed = (float)g_engine.duckFrames / (float)g_engine.deviceRate;
+ duck = AIL_ex_duck_gain(elapsed, g_engine.duckGain, g_engine.duckSeconds);
+ g_engine.duckFrames += frameCount;
+ if (elapsed >= g_engine.duckSeconds) {
+ g_engine.duckActive = false;
+ for (size_t i = 0; i < g_engine.samples.size(); ++i) {
+ g_engine.samples[i]->unducked = false;
+ }
+ }
+ }
+
+ if (g_engine.roomInput.size() < frameCount) {
+ g_engine.roomInput.resize(frameCount);
+ }
+ float *room = &g_engine.roomInput[0];
+ memset(room, 0, (size_t)frameCount * sizeof(float));
+
for (size_t i = 0; i < g_engine.samples.size(); ++i) {
Sample *sample = g_engine.samples[i];
if (!sample->running || !sample->queued || !sample->mix.resamplerReady) {
continue;
}
- if (mixVoice(&sample->mix, readSampleSource, sample, out, frameCount, &sample->sourceDry)) {
+ if (mixVoice(&sample->mix, readSampleSource, sample, out, frameCount, &sample->sourceDry,
+ sample->unducked ? 1.0f : duck, sample->is3D ? room : NULL)) {
sample->queued = false;
}
}
@@ -1075,13 +1271,16 @@ void dataCallback(ma_device *, void *output, const void *, ma_uint32 frameCount)
continue;
}
stream->sourceDry = false;
- mixVoice(&stream->mix, readStreamSource, stream, out, frameCount, &stream->sourceDry);
+ mixVoice(&stream->mix, readStreamSource, stream, out, frameCount, &stream->sourceDry, duck, NULL);
}
for (size_t i = 0; i < g_engine.pcmVoices.size(); ++i) {
PcmVoice *voice = g_engine.pcmVoices[i];
// Dry is only until the owner queues more, so it is asked afresh each pass, as a stream's is.
voice->sourceDry = false;
- mixVoice(&voice->mix, readPcmSource, voice, out, frameCount, &voice->sourceDry);
+ mixVoice(&voice->mix, readPcmSource, voice, out, frameCount, &voice->sourceDry, duck, NULL);
+ }
+ if (g_engine.room.ready) {
+ processRoom(&g_engine.room, room, out, frameCount);
}
if (g_engine.capture != NULL) {
@@ -1146,6 +1345,7 @@ S32 AILCALL AIL_quick_startup(S32 use_digital, S32, U32, S32, S32)
return 0;
}
g_engine.deviceRate = g_engine.device.sampleRate;
+ initRoom(&g_engine.room, g_engine.deviceRate);
g_engine.deviceReady = true;
if (!g_engine.offline && ma_device_start(&g_engine.device) != MA_SUCCESS) {
ma_device_uninit(&g_engine.device);
@@ -1485,10 +1685,12 @@ HSAMPLE AILCALL AIL_allocate_sample_handle(HDIGDRIVER dig)
sample->minDistance = 0.0f;
sample->maxDistance = 1.0f;
sample->occlusion = 0.0f;
+ sample->velocityX = sample->velocityY = sample->velocityZ = 0.0f;
sample->running = false;
sample->queued = false;
sample->cursor = 0;
sample->sourceDry = false;
+ sample->unducked = false;
std::lock_guard<std::recursive_mutex> guard(g_engine.lock);
std::lock_guard<std::mutex> mixGuard(g_engine.mixLock);
@@ -1725,6 +1927,7 @@ S32 AILCALL AIL_set_3D_sample_file(H3DSAMPLE handle, const void *file_image)
Sample *sample = (Sample *)handle;
if (sample != NULL) {
sample->occlusion = 0.0f;
+ sample->velocityX = sample->velocityY = sample->velocityZ = 0.0f;
}
return AIL_set_sample_file((HSAMPLE)handle, file_image, 0);
}
@@ -1790,6 +1993,30 @@ void AILCALL AIL_ex_set_3D_linear_falloff(S32 linear)
g_linearFalloff.store(linear);
}
+void AILCALL AIL_ex_set_3D_air(F32 speed_of_sound, F32 absorption_distance)
+{
+ g_speedOfSound.store(speed_of_sound);
+ g_absorptionDistance.store(absorption_distance);
+}
+
+void AILCALL AIL_ex_set_reverb(F32 wet, F32 decay, F32 damping, F32 echo)
+{
+ g_roomSend.store(wet);
+ std::lock_guard<std::mutex> mixGuard(g_engine.mixLock);
+ setRoom(&g_engine.room, decay, damping, echo);
+}
+
+void AILCALL AIL_ex_duck(H3DSAMPLE trigger, F32 gain, F32 seconds)
+{
+ std::lock_guard<std::recursive_mutex> guard(g_engine.lock);
+ std::lock_guard<std::mutex> mixGuard(g_engine.mixLock);
+ ((Sample *)trigger)->unducked = true;
+ g_engine.duckActive = true;
+ g_engine.duckFrames = 0;
+ g_engine.duckGain = gain;
+ g_engine.duckSeconds = seconds;
+}
+
void AILCALL AIL_set_3D_sample_occlusion(H3DSAMPLE handle, F32 occlusion)
{
Sample *sample = (Sample *)handle;
@@ -1873,9 +2100,18 @@ void AILCALL AIL_set_3D_orientation(H3DPOBJECT obj, F32 X_face, F32 Y_face, F32
g_engine.listener.upZ = Z_up;
}
-void AILCALL AIL_set_3D_velocity_vector(H3DPOBJECT, F32, F32, F32)
+void AILCALL AIL_set_3D_velocity_vector(H3DPOBJECT obj, F32 dX, F32 dY, F32 dZ)
{
- // No doppler: Miles' was off in this game's settings too.
+ // As miles_xaudio2's: units a second, heard at the next refresh, the listener's not kept.
+ if (obj == NULL || obj == LISTENER_OBJECT) {
+ return;
+ }
+
+ std::lock_guard<std::recursive_mutex> guard(g_engine.lock);
+ Sample *sample = (Sample *)obj;
+ sample->velocityX = dX;
+ sample->velocityY = dY;
+ sample->velocityZ = dZ;
}
// =================================================================================================
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/xaudio2/miles_xaudio2.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/xaudio2/miles_xaudio2.cpp
index 435799fcf..49d6c1f46 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/xaudio2/miles_xaudio2.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/xaudio2/miles_xaudio2.cpp
@@ -12,7 +12,10 @@
* a source voice in ~200ms buffers by the service thread below.
* 3D positioning -> distance attenuation and a stereo pan computed here, not by XAudio2's
* X3DAudio: the game only ever asks for a position, a min/max distance
- * pair and an occlusion scalar.
+ * pair and an occlusion scalar. On top of those (MSS.h's AIL_ex_ air,
+ * room and duck): the voice's own one-pole filter for air and occlusion,
+ * its frequency ratio for doppler, and a second send into one submix
+ * running XAudio2's reverb.
* EOS callbacks -> the service thread notices a voice run dry and calls back from there,
* which is the thread context Miles used (MilesAudioManager locks for it).
*/
@@ -20,6 +23,7 @@
#include <windows.h>
#include <mmreg.h>
#include <xaudio2.h>
+#include <xaudio2fx.h>
#include <xapo.h>
#include <math.h>
#include <stdio.h>
@@ -291,6 +295,8 @@ struct Sample
float positionX, positionY, positionZ;
float minDistance, maxDistance;
float occlusion;
+ float velocityX, velocityY, velocityZ; // units a second, AIL_set_3D_velocity_vector
+ bool unducked; // started a duck, so the duck leaves it alone until it is over
};
struct StreamBuffer
@@ -343,6 +349,8 @@ struct Engine
{
IXAudio2 *xaudio;
IXAudio2MasteringVoice *master;
+ unsigned int masterRate;
+ IXAudio2SubmixVoice *room; // XAudio2's reverb, AIL_ex_set_reverb; NULL where it could not be made
CRITICAL_SECTION lock;
HANDLE serviceThread;
volatile LONG serviceRunning;
@@ -355,6 +363,20 @@ struct Engine
Engine g_engine;
S32 g_linearFalloff; // AIL_ex_set_3D_linear_falloff
+float g_speedOfSound; // AIL_ex_set_3D_air
+float g_absorptionDistance;
+float g_roomSend; // AIL_ex_set_reverb's wet
+
+// AIL_ex_duck, under the lock. duckNow is the gain the service thread worked out last.
+struct Duck
+{
+ bool active;
+ ULONGLONG startMs;
+ float gain;
+ float seconds;
+ float duckNow;
+};
+Duck g_duck = { false, 0, 1.0f, 0.0f, 1.0f };
AILFILEOPENCB g_fileOpen;
AILFILECLOSECB g_fileClose;
@@ -397,10 +419,27 @@ void applyPan(IXAudio2SourceVoice *voice, unsigned int sourceChannels, float pan
matrix[(size_t)0 * sourceChannels + channel] = leftGain;
matrix[(size_t)1 * sourceChannels + channel] = rightGain;
}
- voice->SetOutputMatrix(NULL, sourceChannels, masterDetails.InputChannels, &matrix[0]);
+ // the master by name: a 3D sample's voice has a second send, into the room
+ voice->SetOutputMatrix(g_engine.master, sourceChannels, masterDetails.InputChannels, &matrix[0]);
+}
+
+// Every source channel into both of the room's, at one gain relative to the voice's volume.
+void applyRoomSend(IXAudio2SourceVoice *voice, unsigned int sourceChannels, float send)
+{
+ std::vector<float> matrix((size_t)sourceChannels * 2, send);
+ voice->SetOutputMatrix(g_engine.room, sourceChannels, 2, &matrix[0]);
}
-void computeSpatialGain(const Sample &sample, float *volumeOut, float *panOut)
+struct Spatial
+{
+ float volume;
+ float pan;
+ float cutoff; // Hz, AIL_ex_3D_cutoff
+ float send; // into the room, AIL_ex_3D_send
+ float doppler; // pitch ratio, AIL_ex_doppler_ratio
+};
+
+Spatial computeSpatial(const Sample &sample)
{
const Listener &listener = g_engine.listener;
const float dx = sample.positionX - listener.positionX;
@@ -408,8 +447,7 @@ void computeSpatialGain(const Sample &sample, float *volumeOut, float *panOut)
const float dz = sample.positionZ - listener.positionZ;
const float distance = (float)sqrt(dx * dx + dy * dy + dz * dz);
- float attenuation = AIL_ex_3D_distance_gain(distance, sample.minDistance, sample.maxDistance, g_linearFalloff);
- attenuation *= clampUnit(1.0f - sample.occlusion);
+ const float attenuation = AIL_ex_3D_distance_gain(distance, sample.minDistance, sample.maxDistance, g_linearFalloff);
float pan = DEFAULT_PAN;
if (distance > 0.0001f) {
@@ -425,8 +463,13 @@ void computeSpatialGain(const Sample &sample, float *volumeOut, float *panOut)
}
}
- *volumeOut = clampUnit(sample.volume) * attenuation;
- *panOut = pan;
+ Spatial spatial;
+ spatial.volume = clampUnit(sample.volume) * attenuation;
+ spatial.pan = pan;
+ spatial.cutoff = AIL_ex_3D_cutoff(distance, g_absorptionDistance, sample.occlusion);
+ spatial.send = AIL_ex_3D_send(clampUnit(sample.volume), attenuation, g_roomSend);
+ spatial.doppler = AIL_ex_doppler_ratio(dx, dy, dz, sample.velocityX, sample.velocityY, sample.velocityZ, g_speedOfSound);
+ return spatial;
}
void refreshSampleOutput(Sample *sample)
@@ -437,14 +480,28 @@ void refreshSampleOutput(Sample *sample)
float volume = sample->volume;
float pan = sample->pan;
+ float doppler = 1.0f;
if (sample->is3D) {
- computeSpatialGain(*sample, &volume, &pan);
+ const Spatial spatial = computeSpatial(*sample);
+ volume = spatial.volume;
+ pan = spatial.pan;
+ doppler = spatial.doppler;
+ const XAUDIO2_FILTER_PARAMETERS filter = { LowPassOnePoleFilter,
+ AIL_ex_one_pole_coefficient(spatial.cutoff, (float)g_engine.masterRate), 1.0f };
+ sample->voice->SetFilterParameters(&filter);
+ // the voice's volume scales both sends, so the room's is given relative to it
+ if (g_engine.room != NULL) {
+ applyRoomSend(sample->voice, sample->format.nChannels, volume > 0.0f ? spatial.send / volume : 0.0f);
+ }
+ }
+ if (!sample->unducked) {
+ volume *= g_duck.duckNow;
}
sample->voice->SetVolume(clampUnit(volume));
applyPan(sample->voice, sample->format.nChannels, pan);
if (sample->baseRate != 0) {
- float ratio = (float)sample->rate / (float)sample->baseRate;
+ float ratio = (float)sample->rate / (float)sample->baseRate * doppler;
if (ratio < XAUDIO2_MIN_FREQ_RATIO) ratio = XAUDIO2_MIN_FREQ_RATIO;
if (ratio > 4.0f) ratio = 4.0f;
sample->voice->SetFrequencyRatio(ratio);
@@ -492,7 +549,30 @@ bool ensureVoice(Sample *sample, const WAVEFORMATEX &format)
retireVoice(&sample->voice);
sample->format = format;
- return SUCCEEDED(g_engine.xaudio->CreateSourceVoice(&sample->voice, &format, 0, 4.0f, &g_sampleCallback));
+ if (!sample->is3D) {
+ return SUCCEEDED(g_engine.xaudio->CreateSourceVoice(&sample->voice, &format, 0, 4.0f, &g_sampleCallback));
+ }
+ // A 3D sample's voice has the filter for air and occlusion, and sends into the room as well.
+ XAUDIO2_SEND_DESCRIPTOR sends[2] = { { 0, g_engine.master }, { 0, g_engine.room } };
+ XAUDIO2_VOICE_SENDS sendList = { g_engine.room != NULL ? 2u : 1u, sends };
+ return SUCCEEDED(g_engine.xaudio->CreateSourceVoice(&sample->voice, &format, XAUDIO2_VOICE_USEFILTER, 4.0f,
+ &g_sampleCallback, &sendList));
+}
+
+// The room every 3D sample sends to: XAudio2's own reverb, on a stereo submix into the master. The
+// reverb takes 20 to 48 kHz only, and a device outside that plays with no room at all.
+void createRoom()
+{
+ IUnknown *reverb = NULL;
+ if (FAILED(XAudio2CreateReverb(&reverb, 0))) {
+ return;
+ }
+ XAUDIO2_EFFECT_DESCRIPTOR descriptor = { reverb, TRUE, 2 };
+ XAUDIO2_EFFECT_CHAIN chain = { 1, &descriptor };
+ if (FAILED(g_engine.xaudio->CreateSubmixVoice(&g_engine.room, 2, g_engine.masterRate, 0, 0, NULL, &chain))) {
+ g_engine.room = NULL;
+ }
+ reverb->Release();
}
// ---------------------------------------------------------------------------------------------
@@ -759,12 +839,30 @@ DWORD WINAPI serviceThreadMain(LPVOID)
}
}
+ // A duck reaches every voice, 2D ones and streams too, so while it runs all of them are
+ // refreshed, and once more as it ends; the triggers go back to being ducked like the rest.
+ const bool ducking = g_duck.active;
+ if (ducking) {
+ const float elapsed = (float)(GetTickCount64() - g_duck.startMs) / 1000.0f;
+ g_duck.duckNow = AIL_ex_duck_gain(elapsed, g_duck.gain, g_duck.seconds);
+ g_duck.active = elapsed < g_duck.seconds;
+ for (size_t i = 0; i < g_engine.streams.size(); ++i) {
+ Stream *stream = g_engine.streams[i];
+ if (stream->voice != NULL) {
+ stream->voice->SetVolume(clampUnit(stream->volume) * g_duck.duckNow);
+ }
+ }
+ }
+
for (size_t i = 0; i < g_engine.samples.size(); ++i) {
Sample *sample = g_engine.samples[i];
+ if (ducking && !g_duck.active) {
+ sample->unducked = false;
+ }
if (sample->voice == NULL) {
continue;
}
- if (sample->is3D) {
+ if (sample->is3D || ducking) {
refreshSampleOutput(sample);
}
if (!sample->playing) {
@@ -1076,6 +1174,10 @@ S32 AILCALL AIL_quick_startup(S32 use_digital, S32, U32, S32, S32)
g_engine.xaudio = NULL;
return 0;
}
+ XAUDIO2_VOICE_DETAILS masterDetails;
+ g_engine.master->GetVoiceDetails(&masterDetails);
+ g_engine.masterRate = masterDetails.InputSampleRate;
+ createRoom();
InterlockedExchange(&g_engine.serviceRunning, 1);
g_engine.serviceThread = CreateThread(NULL, 0, serviceThreadMain, NULL, 0, NULL);
@@ -1145,6 +1247,10 @@ void AILCALL AIL_shutdown(void)
}
g_engine.retiredVoices.clear();
+ if (g_engine.room != NULL) {
+ g_engine.room->DestroyVoice();
+ g_engine.room = NULL;
+ }
if (g_engine.master != NULL) {
g_engine.master->DestroyVoice();
g_engine.master = NULL;
@@ -1504,6 +1610,7 @@ S32 AILCALL AIL_set_3D_sample_file(H3DSAMPLE handle, const void *file_image)
Sample *sample = (Sample *)handle;
if (sample != NULL) {
sample->occlusion = 0.0f;
+ sample->velocityX = sample->velocityY = sample->velocityZ = 0.0f;
}
return AIL_set_sample_file((HSAMPLE)handle, file_image, 0);
}
@@ -1572,6 +1679,50 @@ void AILCALL AIL_ex_set_3D_linear_falloff(S32 linear)
g_linearFalloff = linear;
}
+void AILCALL AIL_ex_set_3D_air(F32 speed_of_sound, F32 absorption_distance)
+{
+ // No lock, as AIL_ex_set_3D_linear_falloff
+ g_speedOfSound = speed_of_sound;
+ g_absorptionDistance = absorption_distance;
+}
+
+void AILCALL AIL_ex_set_reverb(F32 wet, F32 decay, F32 damping, F32 echo)
+{
+ g_roomSend = wet;
+ if (g_engine.room == NULL) {
+ return;
+ }
+
+ // I3DL2's terms, from its open-air preset: the top end loses up to 30 dB and dies sooner as the
+ // damping rises, and an echo is a strong early reflection that late, less smeared.
+ XAUDIO2FX_REVERB_I3DL2_PARAMETERS room = XAUDIO2FX_I3DL2_PRESET_PLAIN;
+ room.WetDryMix = 100.0f;
+ room.Room = 0;
+ room.RoomHF = -(INT32)(damping * 3000.0f);
+ room.DecayTime = decay;
+ room.DecayHFRatio = 1.0f - 0.9f * damping;
+ room.Reflections = echo > 0.0f ? -200 : -2000;
+ room.ReflectionsDelay = echo;
+ room.Reverb = -600;
+ room.ReverbDelay = echo * 0.5f + 0.01f;
+ room.Diffusion = echo > 0.0f ? 60.0f : 100.0f;
+ XAUDIO2FX_REVERB_PARAMETERS native;
+ ReverbConvertI3DL2ToNative(&room, &native);
+ g_engine.room->SetEffectParameters(0, &native, sizeof(native));
+}
+
+void AILCALL AIL_ex_duck(H3DSAMPLE trigger, F32 gain, F32 seconds)
+{
+ EnterCriticalSection(&g_engine.lock);
+ ((Sample *)trigger)->unducked = true;
+ g_duck.active = true;
+ g_duck.startMs = GetTickCount64();
+ g_duck.gain = gain;
+ g_duck.seconds = seconds;
+ refreshSampleOutput((Sample *)trigger);
+ LeaveCriticalSection(&g_engine.lock);
+}
+
void AILCALL AIL_set_3D_sample_occlusion(H3DSAMPLE handle, F32 occlusion)
{
Sample *sample = (Sample *)handle;
@@ -1659,9 +1810,20 @@ void AILCALL AIL_set_3D_orientation(H3DPOBJECT obj, F32 X_face, F32 Y_face, F32
LeaveCriticalSection(&g_engine.lock);
}
-void AILCALL AIL_set_3D_velocity_vector(H3DPOBJECT, F32, F32, F32)
+void AILCALL AIL_set_3D_velocity_vector(H3DPOBJECT obj, F32 dX, F32 dY, F32 dZ)
{
- // No doppler: Miles' was off in this game's settings too.
+ // Units a second. The listener's is not kept: AIL_ex_doppler_ratio says why. Heard at the
+ // sample's next refresh, which the position update right after it is.
+ if (obj == NULL || obj == LISTENER_OBJECT) {
+ return;
+ }
+
+ EnterCriticalSection(&g_engine.lock);
+ Sample *sample = (Sample *)obj;
+ sample->velocityX = dX;
+ sample->velocityY = dY;
+ sample->velocityZ = dZ;
+ LeaveCriticalSection(&g_engine.lock);
}
// =================================================================================================
diff --git a/GeneralsMD/Code/Tests/test_miles_effects.cpp b/GeneralsMD/Code/Tests/test_miles_effects.cpp
new file mode 100644
index 000000000..f200e3dfc
--- /dev/null
+++ b/GeneralsMD/Code/Tests/test_miles_effects.cpp
@@ -0,0 +1,279 @@
+/*
+ * The air, room and duck of the Miles surface on miniaudio (MSS.h's AIL_ex_set_3D_air,
+ * AIL_ex_set_reverb and AIL_ex_duck), measured in the mix a -wav run records.
+ *
+ * miles_miniaudio.cpp is compiled into this test on its own, without the XAudio2 half, and run on its
+ * offline mix: AIL_ex_offline_mix, then AIL_ex_mix_to_frame moves the mix by logic frames, so every
+ * figure below is the same on every run and on a machine with no sound card. What is heard comes
+ * back through AIL_ex_start_capture, the tap -wav writes its file from. The expected numbers are the
+ * physics the helpers in MSS.h claim, worked out here, not read back from them.
+ *
+ * Not covered: XAudio2's own filter, reverb and duck, which only a player on Windows hears, and the
+ * delay a world sound starts with, which is the game's request list and not this library.
+ */
+#include "test_harness.h"
+
+#include <math.h>
+#include <stdio.h>
+#include <string.h>
+
+#include <string>
+#include <vector>
+
+#include "MSS/MSS.h"
+
+static const unsigned TONE_RATE = 22050;
+static const double TONE_PI = 3.14159265358979323846; // MSVC's math.h gives M_PI only on request
+static const double TONE_AMPLITUDE = 8000.0;
+static const int LOGIC_FRAMES_PER_SECOND = 60; // the logic clock AIL_ex_mix_to_frame counts
+static const char CAPTURE_PATH[] = "test_miles_effects.wav";
+
+static void put16(unsigned char *p, unsigned value) { p[0] = (unsigned char)value; p[1] = (unsigned char)(value >> 8); }
+static void put32(unsigned char *p, unsigned value) { put16(p, value & 0xffff); put16(p + 2, value >> 16); }
+static unsigned get16(const unsigned char *p) { return (unsigned)p[0] | ((unsigned)p[1] << 8); }
+static unsigned get32(const unsigned char *p) { return get16(p) | (get16(p + 2) << 16); }
+
+// A mono 16-bit sine as a WAV image, the shape of the game's effects.
+static std::vector<unsigned char> makeTone(double hz, unsigned milliseconds)
+{
+ const unsigned frames = TONE_RATE * milliseconds / 1000;
+ std::vector<unsigned char> image(44 + frames * 2);
+ memcpy(&image[0], "RIFF", 4);
+ put32(&image[4], 36 + frames * 2);
+ memcpy(&image[8], "WAVEfmt ", 8);
+ put32(&image[16], 16);
+ put16(&image[20], 1);
+ put16(&image[22], 1);
+ put32(&image[24], TONE_RATE);
+ put32(&image[28], TONE_RATE * 2);
+ put16(&image[32], 2);
+ put16(&image[34], 16);
+ memcpy(&image[36], "data", 4);
+ put32(&image[40], frames * 2);
+ for (unsigned frame = 0; frame < frames; ++frame) {
+ put16(&image[44 + frame * 2], (unsigned short)(short)(sin(2.0 * TONE_PI * hz * frame / TONE_RATE) * TONE_AMPLITUDE));
+ }
+ return image;
+}
+
+// The device once, offline; a listener at the origin facing +Y with +Z up, so -X is the right speaker.
+static HPROVIDER g_provider = 0;
+static int g_logicFrame = 0;
+
+static void startAudio()
+{
+ static bool started = false;
+ if (started) {
+ return;
+ }
+ started = true;
+ AIL_ex_offline_mix();
+ AIL_startup();
+ AIL_quick_startup(1, 0, 44100, 16, 2);
+ HPROENUM next = HPROENUM_FIRST;
+ char *name = NULL;
+ AIL_enumerate_3D_providers(&next, &g_provider, &name);
+ H3DPOBJECT listener = AIL_open_3D_listener(g_provider);
+ AIL_set_3D_orientation(listener, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f);
+ AIL_set_3D_position(listener, 0.0f, 0.0f, 0.0f);
+ AIL_ex_mix_to_frame(g_logicFrame); // places the mix
+}
+
+static void runSeconds(double seconds)
+{
+ const int frames = (int)(seconds * LOGIC_FRAMES_PER_SECOND);
+ for (int i = 0; i < frames; ++i) {
+ AIL_ex_mix_to_frame(++g_logicFrame);
+ }
+}
+
+// A 3D sample of `tone` on the X axis, minimum distance 10 and a maximum out of the way.
+static H3DSAMPLE place(const std::vector<unsigned char> &tone, float x, float velocityX, float volume)
+{
+ H3DSAMPLE sample = AIL_allocate_3D_sample_handle(g_provider);
+ AIL_set_3D_sample_file(sample, &tone[0]);
+ AIL_set_3D_sample_volume(sample, volume);
+ AIL_set_3D_sample_distances(sample, 100000.0f, 10.0f);
+ AIL_set_3D_velocity_vector(sample, velocityX, 0.0f, 0.0f);
+ AIL_set_3D_position(sample, x, 0.0f, 0.0f);
+ return sample;
+}
+
+struct Capture
+{
+ std::vector<double> mono; // left plus right over two
+ unsigned rate;
+};
+
+static Capture readCapture()
+{
+ Capture capture;
+ capture.rate = 0;
+ FILE *file = fopen(CAPTURE_PATH, "rb");
+ if (file == NULL) {
+ return capture;
+ }
+ std::vector<unsigned char> bytes;
+ unsigned char buffer[65536];
+ size_t got;
+ while ((got = fread(buffer, 1, sizeof(buffer), file)) > 0) {
+ bytes.insert(bytes.end(), buffer, buffer + got);
+ }
+ fclose(file);
+ remove(CAPTURE_PATH);
+ if (bytes.size() < 44) {
+ return capture;
+ }
+ capture.rate = get32(&bytes[24]);
+ const size_t frames = (bytes.size() - 44) / 4;
+ capture.mono.resize(frames);
+ for (size_t i = 0; i < frames; ++i) {
+ capture.mono[i] = ((double)(short)get16(&bytes[44 + i * 4]) + (double)(short)get16(&bytes[44 + i * 4 + 2])) / 2.0 / 32767.0;
+ }
+ return capture;
+}
+
+// Plays the samples given for `seconds` and returns what came out.
+static Capture listen(const std::vector<H3DSAMPLE> &samples, double seconds)
+{
+ AIL_ex_start_capture(CAPTURE_PATH);
+ for (size_t i = 0; i < samples.size(); ++i) {
+ AIL_start_3D_sample(samples[i]);
+ }
+ runSeconds(seconds);
+ AIL_ex_stop_capture();
+ for (size_t i = 0; i < samples.size(); ++i) {
+ AIL_release_3D_sample_handle(samples[i]);
+ }
+ return readCapture();
+}
+
+static double rms(const Capture &capture, double fromSeconds, double toSeconds)
+{
+ const size_t from = (size_t)(fromSeconds * capture.rate);
+ const size_t to = (size_t)(toSeconds * capture.rate) < capture.mono.size() ? (size_t)(toSeconds * capture.rate) : capture.mono.size();
+ double sum = 0.0;
+ for (size_t i = from; i < to; ++i) {
+ sum += capture.mono[i] * capture.mono[i];
+ }
+ return to > from ? sqrt(sum / (double)(to - from)) : 0.0;
+}
+
+static double frequency(const Capture &capture, double fromSeconds, double toSeconds)
+{
+ const size_t from = (size_t)(fromSeconds * capture.rate);
+ const size_t to = (size_t)(toSeconds * capture.rate);
+ unsigned crossings = 0;
+ for (size_t i = from + 1; i < to && i < capture.mono.size(); ++i) {
+ if ((capture.mono[i - 1] < 0.0) != (capture.mono[i] < 0.0)) {
+ ++crossings;
+ }
+ }
+ return (double)crossings / 2.0 / (toSeconds - fromSeconds);
+}
+
+// The level of an 8 kHz tone at a distance, with the 1/distance falloff taken back out.
+static double brightnessAt(float x)
+{
+ std::vector<unsigned char> tone = makeTone(8000.0, 500);
+ std::vector<H3DSAMPLE> samples(1, place(tone, x, 0.0f, 1.0f));
+ const Capture capture = listen(samples, 0.6);
+ return rms(capture, 0.1, 0.4) / (10.0 / fabs(x));
+}
+
+TEST(air_takes_the_top_off_a_far_sound)
+{
+ startAudio();
+ // No air: distance changes the level and nothing else.
+ AIL_ex_set_3D_air(0.0f, 0.0f);
+ const double nearOpen = brightnessAt(-20.0f);
+ const double farOpen = brightnessAt(-1600.0f);
+ // all of it on the right, half of the mono average: 0.17263 / 2 at full volume
+ CHECK(nearOpen > 0.05);
+ CHECK(fabs(farOpen / nearOpen - 1.0) < 0.05);
+
+ // Air at 400: 1600 out is a cutoff of 20 kHz / 17, 1.2 kHz, where a one-pole leaves an 8 kHz
+ // tone under a fifth of itself; 20 out the cutoff is still near 20 kHz and the tone passes.
+ AIL_ex_set_3D_air(0.0f, 400.0f);
+ const double nearAir = brightnessAt(-20.0f);
+ const double farAir = brightnessAt(-1600.0f);
+ AIL_ex_set_3D_air(0.0f, 0.0f);
+ CHECK(nearAir / nearOpen > 0.9);
+ CHECK(farAir / nearAir < 0.2);
+}
+
+TEST(doppler_raises_what_comes_and_lowers_what_goes)
+{
+ startAudio();
+ // A quarter of the speed of sound towards the listener is 1700 / 1275, a third up; the same away
+ // is 1700 / 2125, a fifth down.
+ AIL_ex_set_3D_air(1700.0f, 0.0f);
+ std::vector<unsigned char> tone = makeTone(440.0, 500);
+ std::vector<H3DSAMPLE> coming(1, place(tone, -500.0f, 425.0f, 1.0f));
+ const Capture up = listen(coming, 0.6);
+ std::vector<H3DSAMPLE> going(1, place(tone, -500.0f, -425.0f, 1.0f));
+ const Capture down = listen(going, 0.6);
+ std::vector<H3DSAMPLE> standing(1, place(tone, -500.0f, 0.0f, 1.0f));
+ const Capture still = listen(standing, 0.6);
+ AIL_ex_set_3D_air(0.0f, 0.0f);
+
+ CHECK_NEAR(frequency(still, 0.05, 0.25), 440.0, 440.0 * 0.02);
+ CHECK_NEAR(frequency(up, 0.05, 0.25), 440.0 * 4.0 / 3.0, 440.0 * 0.02);
+ CHECK_NEAR(frequency(down, 0.05, 0.25), 440.0 * 0.8, 440.0 * 0.02);
+}
+
+TEST(the_room_rings_on_after_the_sound_has_stopped)
+{
+ startAudio();
+ // A tenth of a second of tone, then listen past it: dry is silence, a room is a tail.
+ std::vector<unsigned char> tone = makeTone(440.0, 100);
+ AIL_ex_set_reverb(0.0f, 1.5f, 0.3f, 0.0f);
+ std::vector<H3DSAMPLE> dry(1, place(tone, -20.0f, 0.0f, 1.0f));
+ const Capture dryCapture = listen(dry, 1.0);
+
+ AIL_ex_set_reverb(0.5f, 1.5f, 0.3f, 0.0f);
+ std::vector<H3DSAMPLE> wet(1, place(tone, -20.0f, 0.0f, 1.0f));
+ const Capture wetCapture = listen(wet, 1.0);
+
+ // An echo holds the room back: after a 30 ms blip the room answers within a comb's length, 25 ms,
+ // and with a 90 ms echo nothing comes back before the echo does.
+ // Each waits out the last one's tail first, four seconds being 160 dB at this decay.
+ std::vector<unsigned char> blip = makeTone(440.0, 30);
+ runSeconds(4.0);
+ std::vector<H3DSAMPLE> prompt(1, place(blip, -20.0f, 0.0f, 1.0f));
+ const Capture promptCapture = listen(prompt, 0.3);
+ runSeconds(4.0);
+ AIL_ex_set_reverb(0.5f, 1.5f, 0.3f, 0.09f);
+ std::vector<H3DSAMPLE> echoed(1, place(blip, -20.0f, 0.0f, 1.0f));
+ const Capture echoCapture = listen(echoed, 0.3);
+ AIL_ex_set_reverb(0.0f, 1.0f, 0.0f, 0.0f);
+ runSeconds(3.0); // let the tail die before the next test listens
+
+ CHECK(rms(dryCapture, 0.0, 0.1) > 0.02);
+ CHECK(rms(dryCapture, 0.3, 0.6) < 0.0002);
+ CHECK(rms(wetCapture, 0.3, 0.6) > 0.001);
+ CHECK(rms(wetCapture, 0.3, 0.6) < rms(wetCapture, 0.0, 0.1));
+ CHECK(rms(promptCapture, 0.035, 0.085) > 0.001);
+ CHECK(rms(echoCapture, 0.035, 0.085) < 0.0002);
+ CHECK(rms(echoCapture, 0.095, 0.12) > 0.002);
+}
+
+TEST(a_duck_dips_the_rest_and_spares_the_blast)
+{
+ startAudio();
+ // The rest is a steady tone; the blast is a silent sample, since only its exemption matters.
+ std::vector<unsigned char> steady = makeTone(440.0, 4000);
+ std::vector<unsigned char> blastTone = makeTone(880.0, 4000);
+ std::vector<H3DSAMPLE> samples;
+ samples.push_back(place(steady, -20.0f, 0.0f, 1.0f));
+ samples.push_back(place(blastTone, -20.0f, 0.0f, 0.0f));
+ AIL_ex_duck(samples[1], 0.25f, 2.0f);
+ const Capture capture = listen(samples, 3.0);
+
+ // Held at a quarter for the first half second (the hold is a quarter of the two), back by two.
+ const double full = rms(capture, 2.2, 2.9);
+ CHECK(full > 0.02);
+ CHECK_NEAR(rms(capture, 0.1, 0.45) / full, 0.25, 0.03);
+ CHECK(rms(capture, 1.2, 1.3) / full > 0.4);
+ CHECK(rms(capture, 1.2, 1.3) / full < 0.9);
+}
diff --git a/GeneralsMD/Code/Tests/test_miles_miniaudio.cpp b/GeneralsMD/Code/Tests/test_miles_miniaudio.cpp
index 7ae63b426..bc43a56af 100644
--- a/GeneralsMD/Code/Tests/test_miles_miniaudio.cpp
+++ b/GeneralsMD/Code/Tests/test_miles_miniaudio.cpp
@@ -313,7 +313,7 @@ TEST(playback_rate_is_pitch)
// ---------------------------------------------------------------------------------------------
// 3D: miles_xaudio2's min / distance falloff between the two distances (a straight line with
-// AIL_ex_set_3D_linear_falloff), occlusion as a scale, and a pan along up x face.
+// AIL_ex_set_3D_linear_falloff), occlusion as a low-pass, and a pan along up x face.
// ---------------------------------------------------------------------------------------------
static Heard play3D(float x, float occlusion)
@@ -379,11 +379,13 @@ TEST(linear_falloff_is_a_straight_line_between_the_distances)
CHECK(heard.left < SILENT_RMS);
}
-TEST(occlusion_scales_and_inside_the_minimum_is_full)
+TEST(occlusion_is_a_low_pass_and_inside_the_minimum_is_full)
{
+ // Occlusion was a cut in volume and is a filter now (MSS.h's AIL_ex_3D_cutoff): half occluded is a
+ // one-pole at 5 kHz, which leaves the 440 Hz tone at 0.993 of itself.
Heard heard = play3D(-5.0f, 0.5f);
if (!audio()) return;
- CHECK(near(heard.right, 0.5 * TONE_RMS));
+ CHECK(near(heard.right, TONE_RMS));
CHECK(heard.left < SILENT_RMS);
}