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(milesaudiodevice): battle voice budget, shot folding, reply limits, occlusion

Olcay Seyganda6d4c173421
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c491e05e9..b478d0c52 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -34,6 +34,9 @@ found and fixed — EA's own, not port damage.**
- 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.
- The command bar's one-key shortcuts used to go dead the moment a Russian or Ukrainian keyboard layout was on: the key marked C typed с, and no button answers to с. The game now reads a key from a non-Latin layout by where it sits on the keyboard, so C is C whichever layout Windows has active, in every language.
- The check that refuses a broken Turkish or German line reads both new files on every build. A tooltip whose blanks would not match the English one is turned away before it can crash the game.
+- A hill or a big building between you and a fight muffles it. Guns firing behind a cliff lose their crack altogether, their middle comes through ten decibels down and their thump four and a half, and the same guns heard across open ground sound as they always did. It eases in over a quarter of a second as the camera moves. Unit replies and the interface are never muffled.
+- A big battle no longer fills every channel with gunfire. At most 16 battle sounds play at once, and when a seventeenth arrives the quietest, furthest one gives way, or the new one is dropped if it matters less than all of them. The same shot fired by several tanks side by side in the same moment is one louder sound instead of a stack. On a 290 unit crowd fight the busiest second went from 25 voices to 17, with the same peak level. Replies, EVA, the interface and looping sounds are never cut for it.
+- Clicking through your army no longer stacks a dozen replies on top of each other. A unit that just answered stays quiet for a second and a half, a new reply waits until the last has had four tenths of a second, and no more than two talk at once.
## Trees cast the shadow of their own crowns
diff --git a/GeneralsMD/Code/BuildFingerprint.manifest b/GeneralsMD/Code/BuildFingerprint.manifest
index 0312a5322..3c8e694c4 100644
--- a/GeneralsMD/Code/BuildFingerprint.manifest
+++ b/GeneralsMD/Code/BuildFingerprint.manifest
@@ -1701,6 +1701,7 @@ GameEngine/Source/GameNetwork/WOLBrowser/WebBrowserPosix.cpp
GameEngine/Source/GameNetwork/udp.cpp
GameEngine/Source/Precompiled/PreRTS.cpp
GameEngineDevice/GameEngineDevice.dsp
+GameEngineDevice/Include/MilesAudioDevice/AudioMixPolicy.h
GameEngineDevice/Include/MilesAudioDevice/MilesAudioManager.h
GameEngineDevice/Include/PosixDevice/Common/PosixFileResolutionDump.h
GameEngineDevice/Include/PosixDevice/Common/PosixGameEngine.h
@@ -3116,6 +3117,7 @@ Tests/shader_cases.h
Tests/terrain_golden.txt
Tests/terrain_grid.h
Tests/terrain_oracle.cpp
+Tests/test_audio_mix_policy.cpp
Tests/test_bigfilesystem.cpp
Tests/test_bigfilesystem_stubs.cpp
Tests/test_binkvideo.cpp
diff --git a/GeneralsMD/Code/CMakeLists.txt b/GeneralsMD/Code/CMakeLists.txt
index f75fbb0c7..92a6bf714 100644
--- a/GeneralsMD/Code/CMakeLists.txt
+++ b/GeneralsMD/Code/CMakeLists.txt
@@ -2186,6 +2186,10 @@ endfunction()
add_lib_test(test_msvc_float_casts)
target_include_directories(test_msvc_float_casts PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/Libraries/Include)
+# MilesAudioDevice/AudioMixPolicy.h: the battle mix's budget, folding and occlusion arithmetic.
+add_lib_test(test_audio_mix_policy)
+target_include_directories(test_audio_mix_policy PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/GameEngineDevice/Include)
+
add_lib_test(test_hazard_cloud_policy)
set_target_properties(test_hazard_cloud_policy PROPERTIES CXX_STANDARD 17)
target_include_directories(test_hazard_cloud_policy PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/Libraries/Include)
diff --git a/GeneralsMD/Code/GameEngine/Include/Common/AudioSettings.h b/GeneralsMD/Code/GameEngine/Include/Common/AudioSettings.h
index 9a6ea4d67..30b2d9cba 100644
--- a/GeneralsMD/Code/GameEngine/Include/Common/AudioSettings.h
+++ b/GeneralsMD/Code/GameEngine/Include/Common/AudioSettings.h
@@ -52,7 +52,20 @@ struct AudioSettings
m_airAbsorptionDistance( 300.0f ),
m_reverbLevel( 1.0f ),
m_duckVolume( 0.15f ),
- m_duckTime( 4000.0f )
+ m_duckTime( 4000.0f ),
+ m_replyUnitCooldown( 1500.0f ),
+ m_replyGap( 400.0f ),
+ m_replyMaxVoices( 2 ),
+ m_battleVoiceBudget( 16 ),
+ m_coalesceRadius( 80.0f ),
+ m_coalesceFrames( 2 ),
+ m_coalesceGainStep( 0.12f ),
+ m_coalesceMaxGain( 1.5f ),
+ m_occlusionStrength( 0.75f ),
+ m_occlusionVolume( 0.6f ),
+ m_occlusionDepth( 20.0f ),
+ m_occlusionTime( 250.0f ),
+ m_occlusionRays( 16 )
{
m_duckSounds.push_back( "ExplosionNeutron" );
m_duckSounds.push_back( "ExplosionDaisyCutter" );
@@ -111,6 +124,41 @@ struct AudioSettings
Real m_duckTime;
std::vector<AsciiString> m_duckSounds;
+ /** The battle mix (MilesAudioManager), none of which the shipped file carries either.
+ *
+ * A unit's reply in the commander's ear: the same unit says nothing again for
+ * `ReplyUnitCooldown` milliseconds, another unit's line waits `ReplyGap` milliseconds after the
+ * last one started, and no more than `ReplyMaxVoices` lines sound at once. Zero switches each off.
+ * EVA and the interface are never held back, and nothing in the battle takes their voices.
+ *
+ * `BattleVoiceBudget`: how many one-shot battle sounds play at once. Past it a new one takes the
+ * place of the least important (lowest priority, then the quietest, which is mostly the farthest),
+ * or is not played if it matters less than all of them. Loops are counted but never taken. Zero
+ * is no budget.
+ *
+ * `CoalesceRadius` (game units) and `CoalesceFrames` (logic frames): the same one-shot sound asked
+ * for that soon after and that close to another is folded into it, which plays `CoalesceGainStep`
+ * louder for each one folded in, at most `CoalesceMaxGain` times. A zero radius folds nothing.
+ *
+ * Occlusion: ground or a building in the line from the microphone muffles a world sound, the low
+ * pass at `OcclusionStrength` of the backend's occlusion and the volume down to `OcclusionVolume`
+ * once `OcclusionDepth` units of hill stand in the line, moving over `OcclusionTime` milliseconds;
+ * `OcclusionRaysPerFrame` playing sounds are looked at again each pass. A zero strength is no
+ * occlusion. */
+ Real m_replyUnitCooldown;
+ Real m_replyGap;
+ Int m_replyMaxVoices;
+ Int m_battleVoiceBudget;
+ Real m_coalesceRadius;
+ Int m_coalesceFrames;
+ Real m_coalesceGainStep;
+ Real m_coalesceMaxGain;
+ Real m_occlusionStrength;
+ Real m_occlusionVolume;
+ Real m_occlusionDepth;
+ Real m_occlusionTime;
+ Int m_occlusionRays;
+
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 5d5d7ace1..78a88a203 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/Audio/GameAudio.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/Audio/GameAudio.cpp
@@ -139,6 +139,19 @@ static const FieldParse audioSettingsFieldParseTable[] =
{ "DuckVolume", INI::parsePercentToReal, NULL, offsetof( AudioSettings, m_duckVolume) },
{ "DuckTime", INI::parseReal, NULL, offsetof( AudioSettings, m_duckTime) },
{ "DuckSounds", INI::parseAsciiStringVector, NULL, offsetof( AudioSettings, m_duckSounds) },
+ { "ReplyUnitCooldown", INI::parseReal, NULL, offsetof( AudioSettings, m_replyUnitCooldown) },
+ { "ReplyGap", INI::parseReal, NULL, offsetof( AudioSettings, m_replyGap) },
+ { "ReplyMaxVoices", INI::parseInt, NULL, offsetof( AudioSettings, m_replyMaxVoices) },
+ { "BattleVoiceBudget", INI::parseInt, NULL, offsetof( AudioSettings, m_battleVoiceBudget) },
+ { "CoalesceRadius", INI::parseReal, NULL, offsetof( AudioSettings, m_coalesceRadius) },
+ { "CoalesceFrames", INI::parseInt, NULL, offsetof( AudioSettings, m_coalesceFrames) },
+ { "CoalesceGainStep", INI::parsePercentToReal, NULL, offsetof( AudioSettings, m_coalesceGainStep) },
+ { "CoalesceMaxGain", INI::parsePercentToReal, NULL, offsetof( AudioSettings, m_coalesceMaxGain) },
+ { "OcclusionStrength", INI::parsePercentToReal, NULL, offsetof( AudioSettings, m_occlusionStrength) },
+ { "OcclusionVolume", INI::parsePercentToReal, NULL, offsetof( AudioSettings, m_occlusionVolume) },
+ { "OcclusionDepth", INI::parseReal, NULL, offsetof( AudioSettings, m_occlusionDepth) },
+ { "OcclusionTime", INI::parseReal, NULL, offsetof( AudioSettings, m_occlusionTime) },
+ { "OcclusionRaysPerFrame", INI::parseInt, NULL, offsetof( AudioSettings, m_occlusionRays) },
{ "GlobalMinRange", INI::parseInt, NULL, offsetof( AudioSettings, m_globalMinRange) },
{ "GlobalMaxRange", INI::parseInt, NULL, offsetof( AudioSettings, m_globalMaxRange) },
{ "TimeBetweenDrawableSounds", INI::parseDurationUnsignedInt, NULL, offsetof( AudioSettings, m_drawableAmbientFrames) },
diff --git a/GeneralsMD/Code/GameEngineDevice/Include/MilesAudioDevice/AudioMixPolicy.h b/GeneralsMD/Code/GameEngineDevice/Include/MilesAudioDevice/AudioMixPolicy.h
new file mode 100644
index 000000000..598bc0dfd
--- /dev/null
+++ b/GeneralsMD/Code/GameEngineDevice/Include/MilesAudioDevice/AudioMixPolicy.h
@@ -0,0 +1,101 @@
+/*
+** Command & Conquer Generals Zero Hour(tm)
+** Copyright 2025 Electronic Arts Inc.
+**
+** This program is free software: you can redistribute it and/or modify
+** it under the terms of the GNU General Public License as published by
+** the Free Software Foundation, either version 3 of the License, or
+** (at your option) any later version.
+**
+** This program is distributed in the hope that it will be useful,
+** but WITHOUT ANY WARRANTY; without even the implied warranty of
+** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+** GNU General Public License for more details.
+**
+** You should have received a copy of the GNU General Public License
+** along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+// Modified 2026 by Olcay Seygan for Zero Hour Reforged; see the git history.
+
+// FILE: AudioMixPolicy.h
+// The arithmetic behind MilesAudioManager's battle mix, kept free of the engine so a test can hold
+// it: which playing sound gives way to a new one, how much louder a shot gets for the identical
+// shots folded into it, how deep a hill or a building stands in the line between the microphone and
+// a sound, and how fast the muffle that follows from it moves. Nothing here reads or writes logic.
+
+#pragma once
+
+#include <math.h>
+
+namespace AudioMixPolicy {
+
+/// How much a sound matters when the voices run out: its priority first (EA's AP_LOWEST .. AP_CRITICAL,
+/// 0 to 4), then how loud it is at the microphone (0 to 1), so among equals the quietest, which is
+/// mostly the farthest, gives way first.
+inline float importance(int priority, float loudness)
+{
+ if (loudness < 0.0f)
+ loudness = 0.0f;
+ if (loudness > 1.0f)
+ loudness = 1.0f;
+ return (float)priority + loudness;
+}
+
+/// The gain a shot plays at for the identical shots folded into it: a step for each, never past the
+/// ceiling. Many guns firing together sound like more than one gun, but not like all of them.
+inline float coalescedGain(int merged, float step, float ceiling)
+{
+ const float gain = 1.0f + step * (float)merged;
+ return gain < ceiling ? gain : ceiling;
+}
+
+/// The deepest that ground or a roof stands above the straight line from the microphone (l) to the
+/// sound (s), in game units, or 0 for a clear line. heightAt(x, y) is the highest blocker at a point.
+/// The line is sampled every step units, leaving out margin units at either end, where the ground the
+/// sound stands on and the slope under the microphone would count as hills.
+template <class HeightAt>
+float rayObstruction(float lx, float ly, float lz, float sx, float sy, float sz, float step, float margin,
+ int maxSamples, HeightAt heightAt)
+{
+ const float dx = sx - lx;
+ const float dy = sy - ly;
+ const float length = sqrtf(dx * dx + dy * dy);
+ if (length <= 2.0f * margin || step <= 0.0f)
+ return 0.0f;
+ int samples = (int)((length - 2.0f * margin) / step) + 1;
+ if (samples > maxSamples)
+ samples = maxSamples;
+ float deepest = 0.0f;
+ for (int i = 0; i < samples; ++i) {
+ const float along = margin + (length - 2.0f * margin) * ((float)i + 0.5f) / (float)samples;
+ const float t = along / length;
+ const float lineZ = lz + (sz - lz) * t;
+ const float depth = heightAt(lx + dx * t, ly + dy * t) - lineZ;
+ if (depth > deepest)
+ deepest = depth;
+ }
+ return deepest;
+}
+
+/// The share of the full muffle a depth earns: none at 0, all of it from fullDepth units of hill on.
+inline float occlusionAmount(float depth, float fullDepth)
+{
+ if (depth <= 0.0f || fullDepth <= 0.0f)
+ return depth > 0.0f ? 1.0f : 0.0f;
+ const float amount = depth / fullDepth;
+ return amount < 1.0f ? amount : 1.0f;
+}
+
+/// One step of a smoothed value towards its target, over elapsedMs, closing 63% of the gap every
+/// timeMs. No time at all leaves it where it is; a zero time jumps.
+inline float approach(float current, float target, float elapsedMs, float timeMs)
+{
+ if (timeMs <= 0.0f)
+ return target;
+ if (elapsedMs <= 0.0f)
+ return current;
+ const float keep = expf(-elapsedMs / timeMs);
+ return target + (current - target) * keep;
+}
+
+} // namespace AudioMixPolicy
diff --git a/GeneralsMD/Code/GameEngineDevice/Include/MilesAudioDevice/MilesAudioManager.h b/GeneralsMD/Code/GameEngineDevice/Include/MilesAudioDevice/MilesAudioManager.h
index 4ed88a60b..41d4f07ea 100644
--- a/GeneralsMD/Code/GameEngineDevice/Include/MilesAudioDevice/MilesAudioManager.h
+++ b/GeneralsMD/Code/GameEngineDevice/Include/MilesAudioDevice/MilesAudioManager.h
@@ -94,6 +94,12 @@ struct PlayingAudio
/// logic milliseconds still to wait, and m_stopHeld stays set once it has gone through.
Bool m_stopHeld;
Real m_stopInMs;
+ /// A world sound behind a hill or a building (MilesAudioManager::updateOcclusion): how muffled it
+ /// is now, 0 to 1, what the last look along the line said it should be, and EA's off-screen low pass
+ /// it was started with, which the muffle never goes under.
+ Real m_occlusion;
+ Real m_occlusionTarget;
+ Real m_offscreenOcclusion;
PlayingAudio() :
m_type(PAT_INVALID),
@@ -108,7 +114,10 @@ struct PlayingAudio
m_framesFaded(0),
m_tracked(false),
m_stopHeld(false),
- m_stopInMs(0.0f)
+ m_stopInMs(0.0f),
+ m_occlusion(0.0f),
+ m_occlusionTarget(0.0f),
+ m_offscreenOcclusion(0.0f)
{
m_lastPosition.zero();
m_velocity.zero();
@@ -247,6 +256,24 @@ class MilesAudioManager : public AudioManager
Bool killLowestPrioritySoundImmediately( AudioEventRTS *event );
AudioEventRTS* findLowestPrioritySound( AudioEventRTS *event );
+ // The battle mix: replies held back as they start (playAudioEvent), identical shots folded
+ // together and a budget for battle voices through doesViolateLimit, the question every sound is
+ // asked before it plays. None of them touches a sound logic asked for (getIsLogicalAudio).
+ Bool doesViolateEventLimit( AudioEventRTS *event ) const;
+ Bool refuseReply( AudioEventRTS *event ) const;
+ Bool coalesceShot( AudioEventRTS *event ) const;
+ void noteShot( AudioEventRTS *event ) const;
+ Bool refuseOverBudget( AudioEventRTS *event ) const;
+ Real getLoudness( AudioEventRTS *event ) const;
+ void logMix( void );
+
+ // Occlusion: the line from the microphone to a world sound, through the ground and the buildings.
+ Real lookForOcclusion( const Coord3D *pos ) const;
+ void updateOcclusion( PlayingAudio *playing, const Coord3D *pos, Bool look );
+ void applyOcclusion( PlayingAudio *playing );
+ void buildBlockers( void );
+ Real getBlockerHeight( Real x, Real y ) const;
+
virtual void adjustVolumeOfPlayingAudio(AsciiString eventName, Real newVolume);
virtual void removePlayingAudio( AsciiString eventName );
@@ -289,7 +316,7 @@ class MilesAudioManager : public AudioManager
void playStream( AudioEventRTS *event, HSTREAM stream );
// Returns the file handle for attachment to the PlayingAudio structure
void *playSample( AudioEventRTS *event, HSAMPLE sample );
- void *playSample3D( AudioEventRTS *event, H3DSAMPLE sample3D );
+ void *playSample3D( PlayingAudio *audio );
protected:
void buildProviderList( void );
@@ -328,7 +355,7 @@ class MilesAudioManager : public AudioManager
protected:
void initFilters( HSAMPLE sample, const AudioEventRTS *eventInfo );
- void initFilters3D( H3DSAMPLE sample, const AudioEventRTS *eventInfo, const Coord3D *pos );
+ void initFilters3D( PlayingAudio *audio, const Coord3D *pos );
protected:
ProviderInfo m_provider3D[MAXPROVIDERS];
@@ -409,6 +436,35 @@ class MilesAudioManager : public AudioManager
std::map<UnsignedIntPtr, UnsignedInt> m_audioStarts;
CriticalSectionClass m_completedAudioCS;
+ /// A one-shot battle sound let through, for the ones asked for right after it to fold into.
+ struct RecentShot
+ {
+ AsciiString name;
+ Coord3D position;
+ UnsignedInt frame;
+ AudioHandle handle;
+ Int merged;
+ Real volume; ///< the volume it was asked at, before anything was folded into it
+ };
+ mutable std::vector<RecentShot> m_recentShots;
+ mutable std::map<UnsignedInt, UnsignedInt> m_replyAtMs; ///< object -> Clock_Milliseconds of its last reply
+ mutable UnsignedInt m_lastReplyAtMs;
+ /// What the mix did since the last AUDIO MIX line, and the most 3D voices heard at once.
+ struct MixCounts
+ {
+ Int started3D, merged, stolen, overBudget, repliesLet, repliesHeld, looks;
+ UnsignedInt peak3D, peakBattle;
+ Real occludedPeak;
+ };
+ mutable MixCounts m_mixCounts;
+ UnsignedInt m_mixLoggedAt;
+ UnsignedInt m_occlusionCursor;
+ /// The tallest roof over each cell, for occlusion, rebuilt now and then from the drawables.
+ std::vector<Real> m_blockers;
+ Int m_blockerColumns;
+ Int m_blockerRows;
+ UnsignedInt m_blockersBuiltAt;
+
AudioFileCache *m_audioCache;
PlayingAudio *m_binkHandle;
UnsignedInt m_num2DSamples;
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/MilesAudioDevice/MilesAudioManager.cpp b/GeneralsMD/Code/GameEngineDevice/Source/MilesAudioDevice/MilesAudioManager.cpp
index 60c798940..af371c735 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/MilesAudioDevice/MilesAudioManager.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/MilesAudioDevice/MilesAudioManager.cpp
@@ -46,6 +46,7 @@
#include "Lib/Clock.h"
#include "Lib/BaseType.h"
#include "MilesAudioDevice/MilesAudioManager.h"
+#include "MilesAudioDevice/AudioMixPolicy.h"
#include "Common/AudioAffect.h"
#include "Common/AudioHandleSpecialValues.h"
@@ -142,11 +143,18 @@ MilesAudioManager::MilesAudioManager() :
m_clockFrame(0),
m_clockElapsedMs(MSEC_PER_LOGICFRAME_REAL),
m_clockMovedAt(0),
+ m_lastReplyAtMs(0),
+ m_mixLoggedAt(0),
+ m_occlusionCursor(0),
+ m_blockerColumns(0),
+ m_blockerRows(0),
+ m_blockersBuiltAt(0),
m_binkHandle(NULL),
m_pref3DProvider(AsciiString::TheEmptyString),
m_prefSpeaker(AsciiString::TheEmptyString)
{
m_audioCache = NEW AudioFileCache;
+ memset(&m_mixCounts, 0, sizeof(m_mixCounts));
}
//-------------------------------------------------------------------------------------------------
@@ -523,6 +531,10 @@ void MilesAudioManager::reset()
AudioManager::reset();
stopAllAudioImmediately();
removeAllAudioRequests();
+ m_recentShots.clear();
+ m_replyAtMs.clear();
+ m_blockers.clear();
+ m_blockersBuiltAt = 0;
// This must come after stopAllAudioImmediately() and removeAllAudioRequests(), to ensure that
// sounds pointing to the temporary AudioEventInfo handles are deleted before their info is deleted
removeLevelSpecificAudioEventInfos();
@@ -606,10 +618,15 @@ void MilesAudioManager::update()
m_roomMap = TheGlobalData->m_mapName;
setRoomFromMap();
}
+ if (TheGameLogic->isInGame() && !TheGameLogic->isLoadingMap())
+ {
+ buildBlockers();
+ }
setDeviceListenerPosition();
processRequestList();
processPlayingList();
processFadingList();
+ logMix();
}
//-------------------------------------------------------------------------------------------------
@@ -793,6 +810,10 @@ void MilesAudioManager::playAudioEvent( AudioEventRTS *event, Bool requestStop,
delete event; // nothing downstream will take it now
return;
}
+ if (!event->getIsLogicalAudio() && refuseReply(event)) {
+ delete event;
+ return;
+ }
std::list<PlayingAudio *>::iterator it;
PlayingAudio *playing = NULL;
@@ -941,8 +962,9 @@ void MilesAudioManager::playAudioEvent( AudioEventRTS *event, Bool requestStop,
}
if (sample3D) {
- audio->m_file = playSample3D(event, sample3D);
+ audio->m_file = playSample3D(audio);
m_sound->notifyOf3DSampleStart();
+ ++m_mixCounts.started3D;
if (audio->m_file && !nextLoop) {
duckForBlast(event, sample3D);
}
@@ -1543,7 +1565,7 @@ void MilesAudioManager::adjustPlayingVolume( PlayingAudio *audio )
AIL_set_sample_volume_pan(audio->m_sample, getVoiceMixedVolume(audio->m_audioEventRTS, m_soundVolume), pan);
} else if (audio->m_type == PAT_3DSample) {
- AIL_set_3D_sample_volume(audio->m_3DSample, getVoiceMixedVolume(audio->m_audioEventRTS, m_sound3DVolume));
+ applyOcclusion(audio);
} else if (audio->m_type == PAT_Stream) {
AIL_stream_volume_pan(audio->m_stream, NULL, &pan);
@@ -1606,11 +1628,10 @@ void MilesAudioManager::initFilters( HSAMPLE sample, const AudioEventRTS *event
}
//-------------------------------------------------------------------------------------------------
-void MilesAudioManager::initFilters3D( H3DSAMPLE sample, const AudioEventRTS *event, const Coord3D *pos )
+void MilesAudioManager::initFilters3D( PlayingAudio *audio, const Coord3D *pos )
{
- // set the sample volume
- Real volume = getVoiceMixedVolume(event, m_sound3DVolume);
- AIL_set_3D_sample_volume(sample, volume);
+ H3DSAMPLE sample = audio->m_3DSample;
+ const AudioEventRTS *event = audio->m_audioEventRTS;
// pitch shift
Real pitchShift = event->getPitchShift();
@@ -1621,10 +1642,15 @@ void MilesAudioManager::initFilters3D( H3DSAMPLE sample, const AudioEventRTS *ev
}
// 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);
- }
+ // (MSS.h's AIL_ex_3D_cutoff), where it used to be a cut in volume. Every pass of the sound asks
+ // again, and a hill in the way muffles it further (updateOcclusion); applyOcclusion sets both, and
+ // the volume, since a new file on the handle has put its occlusion back to none.
+ audio->m_offscreenOcclusion = (event->getAudioEventInfo()->m_lowPassFreq > 0 && !isOnScreen(pos))
+ ? 1.0f - event->getAudioEventInfo()->m_lowPassFreq : 0.0f;
+ if (!audio->m_tracked) {
+ updateOcclusion(audio, pos, TRUE); // the first pass hears its hill from the start
+ }
+ applyOcclusion(audio);
}
//-------------------------------------------------------------------------------------------------
@@ -1960,7 +1986,7 @@ void MilesAudioManager::notifyOfAudioCompletion( UnsignedIntPtr audioCompleted,
return;
}
} else if (playing->m_type == PAT_3DSample) {
- playing->m_file = playSample3D(playing->m_audioEventRTS, playing->m_3DSample);
+ playing->m_file = playSample3D(playing);
// If we don't have a file now, then we should drop to the stopped status so that
// We correctly close this handle.
@@ -2245,7 +2271,266 @@ UnsignedInt MilesAudioManager::getNumStreams( void ) const
}
//-------------------------------------------------------------------------------------------------
+/** Every sound effect is asked this before it is queued (SoundManager::canPlayNow), and again before
+ * it plays when it waited for its distance (checkForSample). Around EA's per-sound Limit sits the
+ * battle mix: a shot folded into an identical one before it, a battle sound over the budget after
+ * it. A sound logic asked for, and waits on, is left exactly as EA had it. Replies are held back
+ * where they start (playAudioEvent), since a unit's second line skips this question altogether. */
Bool MilesAudioManager::doesViolateLimit( AudioEventRTS *event ) const
+{
+ const Bool mixed = !event->getIsLogicalAudio();
+ if (mixed && coalesceShot(event)) {
+ return true;
+ }
+ if (doesViolateEventLimit(event)) {
+ return true;
+ }
+ if (mixed && refuseOverBudget(event)) {
+ return true;
+ }
+ if (mixed) {
+ noteShot(event);
+ }
+ return false;
+}
+
+//-------------------------------------------------------------------------------------------------
+/** A unit's line in the commander's ear (a 2D voice with a speaker), asked as it is about to start.
+ * Clicking through a crowd, a factory emptying, a dozen units promoted in one fight each asked for
+ * one, and they stacked: a unit already talking skips canPlayNow's limits altogether when its line
+ * interrupts, and then played over itself. The same unit is quiet for ReplyUnitCooldown after it
+ * spoke; another waits ReplyGap after the last line began, and no more than ReplyMaxVoices sound at
+ * once. A line held back is dropped, not delayed: by then it answers nothing. */
+Bool MilesAudioManager::refuseReply( AudioEventRTS *event ) const
+{
+ const AudioEventInfo *info = event->getAudioEventInfo();
+ const UnsignedInt objectID = event->getObjectID();
+ if (!BitTest(info->m_type, ST_VOICE) || event->isPositionalAudio() || objectID == 0
+ || info->m_soundType != AT_SoundEffect) {
+ return false;
+ }
+
+ const AudioSettings *settings = m_audioSettings;
+ const UnsignedInt now = Clock_Milliseconds();
+ std::map<UnsignedInt, UnsignedInt>::const_iterator spoke = m_replyAtMs.find(objectID);
+ Bool refuse = spoke != m_replyAtMs.end() && settings->m_replyUnitCooldown > 0.0f
+ && (Real)(now - spoke->second) < settings->m_replyUnitCooldown;
+
+ Int lines = 0;
+ std::list<PlayingAudio *>::const_iterator it;
+ for (it = m_playingSounds.begin(); it != m_playingSounds.end(); ++it) {
+ AudioEventRTS *other = (*it)->m_audioEventRTS;
+ if ((*it)->isPlaying() && other->getObjectID() != 0 && other->getAudioEventInfo()
+ && BitTest(other->getAudioEventInfo()->m_type, ST_VOICE)) {
+ ++lines;
+ }
+ }
+ if (settings->m_replyMaxVoices > 0 && lines >= settings->m_replyMaxVoices) {
+ refuse = true;
+ }
+ if (lines > 0 && settings->m_replyGap > 0.0f && (Real)(now - m_lastReplyAtMs) < settings->m_replyGap) {
+ refuse = true;
+ }
+
+ if (refuse) {
+ ++m_mixCounts.repliesHeld;
+ return true;
+ }
+ m_replyAtMs[objectID] = now;
+ m_lastReplyAtMs = now;
+ ++m_mixCounts.repliesLet;
+ return false;
+}
+
+//-------------------------------------------------------------------------------------------------
+/** The loudness a sound reaches the microphone at, 0 to 1, with the slider taken back out: what the
+ * budget compares when it picks the sound that matters least. */
+Real MilesAudioManager::getLoudness( AudioEventRTS *event ) const
+{
+ const Real slider = isAmbientSound( event->getAudioEventInfo() ) ? getAmbientVolume( TRUE ) : m_sound3DVolume;
+ return getEffectiveVolume(event) / (slider > 0.0f ? slider : 1.0f);
+}
+
+//-------------------------------------------------------------------------------------------------
+/** What the battle mix may fold or take the place of: a one-shot world sound that is not a voice,
+ * not heard map-wide, not critical and not ambience. */
+static Bool isBattleShot( const AudioEventRTS *event )
+{
+ const AudioEventInfo *info = event->getAudioEventInfo();
+ return info != NULL && info->m_soundType == AT_SoundEffect && event->isPositionalAudio()
+ && !BitTest(info->m_type, ST_VOICE | ST_GLOBAL) && info->m_priority != AP_CRITICAL
+ && !BitTest(info->m_control, AC_LOOP) && !AudioManager::isAmbientSound(info);
+}
+
+//-------------------------------------------------------------------------------------------------
+/** Twenty Rangers firing on one frame asked for twenty identical cracks from one patch of ground, and
+ * the voices ran out on the first volley. A one-shot sound asked for within CoalesceFrames logic
+ * frames and CoalesceRadius units of the same sound let through just before folds into that one,
+ * which plays CoalesceGainStep louder for each, at most CoalesceMaxGain. The one let through is
+ * found queued (its travel delay) or playing; once it is neither, the next one takes its place. */
+Bool MilesAudioManager::coalesceShot( AudioEventRTS *event ) const
+{
+ const AudioSettings *settings = m_audioSettings;
+ if (settings->m_coalesceRadius <= 0.0f || !isBattleShot(event)) {
+ return false;
+ }
+ const Coord3D *pos = event->getCurrentPosition();
+ if (pos == NULL) {
+ return false;
+ }
+
+ const UnsignedInt frame = TheGameLogic->getFrame();
+ std::vector<RecentShot>::iterator shot;
+ for (shot = m_recentShots.begin(); shot != m_recentShots.end(); ++shot) {
+ if (shot->handle == event->getPlayingHandle()) {
+ return false; // one let through, asked again on its way to play
+ }
+ }
+ for (shot = m_recentShots.begin(); shot != m_recentShots.end(); ++shot) {
+ if (frame - shot->frame > (UnsignedInt)settings->m_coalesceFrames || shot->name != event->getEventName()) {
+ continue;
+ }
+ Coord3D apart = *pos;
+ apart.sub(&shot->position);
+ if (apart.length() > settings->m_coalesceRadius) {
+ continue;
+ }
+
+ // the survivor, queued or playing
+ AudioEventRTS *survivor = NULL;
+ PlayingAudio *survivorPlaying = NULL;
+ std::list<AudioRequest *>::const_iterator ait;
+ for (ait = m_audioRequests.begin(); ait != m_audioRequests.end() && !survivor; ++ait) {
+ if ((*ait)->m_usePendingEvent && (*ait)->m_pendingEvent->getPlayingHandle() == shot->handle) {
+ survivor = (*ait)->m_pendingEvent;
+ }
+ }
+ std::list<PlayingAudio *>::const_iterator it;
+ for (it = m_playing3DSounds.begin(); it != m_playing3DSounds.end() && !survivor; ++it) {
+ if ((*it)->isPlaying() && (*it)->m_audioEventRTS->getPlayingHandle() == shot->handle) {
+ survivorPlaying = *it;
+ survivor = survivorPlaying->m_audioEventRTS;
+ }
+ }
+ if (!survivor) {
+ continue;
+ }
+
+ ++shot->merged;
+ ++m_mixCounts.merged;
+ survivor->setVolume(shot->volume * AudioMixPolicy::coalescedGain(shot->merged, settings->m_coalesceGainStep,
+ settings->m_coalesceMaxGain));
+ if (survivorPlaying) {
+ const_cast<MilesAudioManager *>(this)->applyOcclusion(survivorPlaying);
+ }
+ return true;
+ }
+ return false;
+}
+
+//-------------------------------------------------------------------------------------------------
+/** A shot let through, for the identical ones asked for after it to fold into; the list keeps only
+ * the last CoalesceFrames' worth. */
+void MilesAudioManager::noteShot( AudioEventRTS *event ) const
+{
+ const AudioSettings *settings = m_audioSettings;
+ if (settings->m_coalesceRadius <= 0.0f || !isBattleShot(event) || event->getCurrentPosition() == NULL) {
+ return;
+ }
+ const UnsignedInt frame = TheGameLogic->getFrame();
+ std::vector<RecentShot>::iterator shot;
+ for (shot = m_recentShots.begin(); shot != m_recentShots.end(); ) {
+ if (shot->handle == event->getPlayingHandle()) {
+ return;
+ }
+ if (frame - shot->frame > (UnsignedInt)settings->m_coalesceFrames || frame < shot->frame) {
+ shot = m_recentShots.erase(shot);
+ continue;
+ }
+ ++shot;
+ }
+ RecentShot recent;
+ recent.name = event->getEventName();
+ recent.position = *event->getCurrentPosition();
+ recent.frame = frame;
+ recent.handle = event->getPlayingHandle();
+ recent.merged = 0;
+ recent.volume = event->getVolume();
+ m_recentShots.push_back(recent);
+}
+
+//-------------------------------------------------------------------------------------------------
+/** BattleVoiceBudget one-shot battle sounds at a time. Past it, a new one takes the place of the one
+ * that matters least (AudioMixPolicy::importance: priority, then loudness at the microphone, so the
+ * quietest and farthest go first) through EA's own handle-to-kill, or is not played when it matters
+ * less than every one of them. Asked only when the sound is about to play: a sound still waiting
+ * for its distance is let into the queue, since what plays by the time it arrives is not known yet.
+ * Voices, ambience, loops and the 2D sounds of the interface are outside the budget, so battle noise
+ * never takes their voices. */
+Bool MilesAudioManager::refuseOverBudget( AudioEventRTS *event ) const
+{
+ const Int budget = m_audioSettings->m_battleVoiceBudget;
+ if (budget <= 0 || !isBattleShot(event) || event->getDelay() >= MSEC_PER_LOGICFRAME_REAL) {
+ return false;
+ }
+
+ Int count = 0;
+ AudioEventRTS *victim = NULL;
+ Real victimImportance = 0.0f;
+ std::list<PlayingAudio *>::const_iterator it;
+ for (it = m_playing3DSounds.begin(); it != m_playing3DSounds.end(); ++it) {
+ AudioEventRTS *other = (*it)->m_audioEventRTS;
+ if (!(*it)->isPlaying() || !isBattleShot(other)) {
+ continue;
+ }
+ ++count;
+ const Real otherImportance = AudioMixPolicy::importance(other->getAudioEventInfo()->m_priority, getLoudness(other));
+ if (!victim || otherImportance < victimImportance) {
+ victim = other;
+ victimImportance = otherImportance;
+ }
+ }
+ if (count < budget) {
+ return false;
+ }
+
+ // EA's limit may already have picked one of the same sound to make room; that keeps the count.
+ if (event->getHandleToKill() != 0) {
+ return false;
+ }
+ if (AudioMixPolicy::importance(event->getAudioEventInfo()->m_priority, getLoudness(event)) <= victimImportance) {
+ ++m_mixCounts.overBudget;
+ return true;
+ }
+ event->setHandleToKill(victim->getPlayingHandle());
+ ++m_mixCounts.stolen;
+ return false;
+}
+
+//-------------------------------------------------------------------------------------------------
+/** Once a second of logic time in a match: what the battle mix did, for the -wav measurements. */
+void MilesAudioManager::logMix( void )
+{
+ if (!TheGameLogic->isInGame() || TheGameLogic->isInShellGame()) {
+ return;
+ }
+ const UnsignedInt frame = TheGameLogic->getFrame();
+ if (frame < m_mixLoggedAt + LOGICFRAMES_PER_SECOND && frame >= m_mixLoggedAt) {
+ return;
+ }
+ m_mixLoggedAt = frame;
+ if (m_mixCounts.started3D == 0 && m_mixCounts.repliesLet == 0 && m_mixCounts.repliesHeld == 0 && m_mixCounts.peak3D == 0) {
+ return;
+ }
+ DEBUG_LOG(("AUDIO MIX frame %u: %d 3D starts, peak %u voices (%u battle), %d folded, %d taken, %d over budget, "
+ "%d replies let %d held, %d looks, most muffled %.2f\n", frame, m_mixCounts.started3D, m_mixCounts.peak3D,
+ m_mixCounts.peakBattle, m_mixCounts.merged, m_mixCounts.stolen, m_mixCounts.overBudget, m_mixCounts.repliesLet,
+ m_mixCounts.repliesHeld, m_mixCounts.looks, m_mixCounts.occludedPeak));
+ memset(&m_mixCounts, 0, sizeof(m_mixCounts));
+}
+
+//-------------------------------------------------------------------------------------------------
+Bool MilesAudioManager::doesViolateEventLimit( AudioEventRTS *event ) const
{
Int limit = event->getAudioEventInfo()->m_limit;
if (limit == 0) {
@@ -2699,9 +2984,14 @@ void MilesAudioManager::processPlayingList( void )
}
}
+ // Occlusion looks along a few lines a pass, taking the playing sounds in turn (updateOcclusion).
+ const UnsignedInt count3D = (UnsignedInt)m_playing3DSounds.size();
+ const UnsignedInt looksThisPass = (UnsignedInt)max(m_audioSettings->m_occlusionRays, 0);
+ UnsignedInt index3D = 0;
for (it = m_playing3DSounds.begin(); it != m_playing3DSounds.end(); ++it)
{
playing = (*it);
+ const Bool lookAgain = (index3D++ + count3D - m_occlusionCursor % count3D) % count3D < looksThisPass;
if (!playing)
continue;
@@ -2769,6 +3059,7 @@ void MilesAudioManager::processPlayingList( void )
}
else
{
+ updateOcclusion( playing, pos, lookAgain );
trackVelocity( playing, pos );
Real x = pos->x;
Real y = pos->y;
@@ -2786,6 +3077,25 @@ void MilesAudioManager::processPlayingList( void )
}
}
+ m_occlusionCursor += looksThisPass;
+
+ // what the AUDIO MIX line reports: the most 3D voices at once, and how many of them were battle
+ UnsignedInt playing3D = 0;
+ UnsignedInt playingBattle = 0;
+ for (it = m_playing3DSounds.begin(); it != m_playing3DSounds.end(); ++it) {
+ playing = (*it);
+ if (playing && playing->isPlaying()) {
+ ++playing3D;
+ const AudioEventInfo *info = playing->m_audioEventRTS->getAudioEventInfo();
+ if (info && !BitTest(info->m_type, ST_VOICE | ST_GLOBAL) && !isAmbientSound(info)) {
+ ++playingBattle;
+ }
+ m_mixCounts.occludedPeak = max(m_mixCounts.occludedPeak, playing->m_occlusion);
+ }
+ }
+ m_mixCounts.peak3D = max(m_mixCounts.peak3D, playing3D);
+ m_mixCounts.peakBattle = max(m_mixCounts.peakBattle, playingBattle);
+
for (it = m_playingStreams.begin(); it != m_playingStreams.end(); ++it) {
playing = (*it);
if (!playing)
@@ -2985,6 +3295,143 @@ void MilesAudioManager::trackVelocity( PlayingAudio *playing, const Coord3D *pos
playing->m_tracked = TRUE;
}
+//-------------------------------------------------------------------------------------------------
+/** A world sound behind a hill or a building is muffled: the line from the microphone to it is looked
+ * along (lookForOcclusion), and the deeper ground or a roof stands in it, the lower the backend's low
+ * pass closes (the occlusion it already takes for EA's off-screen sounds, AIL_ex_3D_cutoff) and the
+ * quieter it plays. A sound's first pass is looked at as it starts; after that OcclusionRaysPerFrame
+ * playing sounds are looked at again a pass, in turn, and the muffle moves towards what they saw over
+ * OcclusionTime of logic time, so a unit walking out from behind a ridge opens up rather than
+ * jumping. Voices and sounds heard map-wide are never muffled. Only the client's view of the
+ * ground and the drawables is read. */
+void MilesAudioManager::updateOcclusion( PlayingAudio *playing, const Coord3D *pos, Bool look )
+{
+ const AudioEventInfo *info = playing->m_audioEventRTS->getAudioEventInfo();
+ if (m_audioSettings->m_occlusionStrength <= 0.0f || info == NULL || BitTest(info->m_type, ST_VOICE | ST_GLOBAL)) {
+ return;
+ }
+ if (look) {
+ playing->m_occlusionTarget = lookForOcclusion(pos);
+ }
+ const Real before = playing->m_occlusion;
+ playing->m_occlusion = playing->m_tracked
+ ? AudioMixPolicy::approach(before, playing->m_occlusionTarget, m_clockElapsedMs, m_audioSettings->m_occlusionTime)
+ : playing->m_occlusionTarget;
+ if (playing->m_occlusion != before) {
+ applyOcclusion(playing);
+ }
+}
+
+//-------------------------------------------------------------------------------------------------
+/** The low pass and the volume of a 3D sound: EA's off-screen low pass or the muffle, whichever is
+ * the closer, and the sliders' volume taken down by the muffle. */
+void MilesAudioManager::applyOcclusion( PlayingAudio *playing )
+{
+ const AudioSettings *settings = m_audioSettings;
+ const Real muffle = playing->m_occlusion * settings->m_occlusionStrength;
+ AIL_set_3D_sample_occlusion(playing->m_3DSample, max(playing->m_offscreenOcclusion, muffle));
+ const Real gain = 1.0f - (1.0f - settings->m_occlusionVolume) * playing->m_occlusion;
+ AIL_set_3D_sample_volume(playing->m_3DSample, getVoiceMixedVolume(playing->m_audioEventRTS, m_sound3DVolume) * gain);
+}
+
+//-------------------------------------------------------------------------------------------------
+/** How much of the full muffle the line from the microphone to pos earns, 0 to 1. */
+Real MilesAudioManager::lookForOcclusion( const Coord3D *pos ) const
+{
+ const Real LIFT = 10.0f; // a sound comes off a unit, not out of the ground under it
+ const Real STEP = 20.0f; // a sample of the line every cell of the blockers' grid
+ const Real MARGIN = 25.0f; // the ground under either end is not a hill between them
+ const Int MAX_SAMPLES = 48;
+ ++m_mixCounts.looks;
+ // A sound from a building, or a microphone over one, starts on its roof: its own roof is not in the way.
+ const Real sourceZ = max(pos->z, getBlockerHeight(pos->x, pos->y)) + LIFT;
+ const Real listenerZ = max(m_listenerPosition.z, getBlockerHeight(m_listenerPosition.x, m_listenerPosition.y) + LIFT);
+ const Real depth = AudioMixPolicy::rayObstruction(m_listenerPosition.x, m_listenerPosition.y, listenerZ,
+ pos->x, pos->y, sourceZ, STEP, MARGIN, MAX_SAMPLES,
+ [this]( Real x, Real y ) { return getBlockerHeight( x, y ); });
+ return AudioMixPolicy::occlusionAmount(depth, m_audioSettings->m_occlusionDepth);
+}
+
+//-------------------------------------------------------------------------------------------------
+static const Real BLOCKER_CELL = 20.0f;
+static const Real NO_ROOF = -100000.0f;
+
+/** The ground, or the roof over it where a building stands. */
+Real MilesAudioManager::getBlockerHeight( Real x, Real y ) const
+{
+ const Real ground = TheTerrainLogic->getGroundHeight( x, y );
+ if (m_blockers.empty()) {
+ return ground;
+ }
+ Region3D extent;
+ TheTerrainLogic->getExtent(&extent);
+ const Int column = (Int)floorf((x - extent.lo.x) / BLOCKER_CELL);
+ const Int row = (Int)floorf((y - extent.lo.y) / BLOCKER_CELL);
+ if (column < 0 || row < 0 || column >= m_blockerColumns || row >= m_blockerRows) {
+ return ground;
+ }
+ return max(ground, m_blockers[row * m_blockerColumns + column]);
+}
+
+//-------------------------------------------------------------------------------------------------
+/** The roofs, once a second of logic time: every structure the client draws, over the cells its
+ * footprint covers, at its top. Bridges are left out (a sound under one is not behind it), and so is
+ * a building the local player has never seen, whose muffle would give it away. */
+void MilesAudioManager::buildBlockers( void )
+{
+ const UnsignedInt frame = TheGameLogic->getFrame();
+ if (m_audioSettings->m_occlusionStrength <= 0.0f
+ || (!m_blockers.empty() && frame >= m_blockersBuiltAt && frame < m_blockersBuiltAt + LOGICFRAMES_PER_SECOND)) {
+ return;
+ }
+ m_blockersBuiltAt = frame;
+
+ Region3D extent;
+ TheTerrainLogic->getExtent(&extent);
+ m_blockerColumns = (Int)ceilf(extent.width() / BLOCKER_CELL);
+ m_blockerRows = (Int)ceilf(extent.height() / BLOCKER_CELL);
+ m_blockers.assign((size_t)(m_blockerColumns * m_blockerRows), NO_ROOF);
+
+ const Int playerIndex = TheObserverCamera.getShroudPlayerIndex();
+ for (Drawable *draw = TheGameClient->firstDrawable(); draw; draw = draw->getNextDrawable())
+ {
+ const ThingTemplate *thing = draw->getTemplate();
+ if (!thing->isKindOf(KINDOF_STRUCTURE) || thing->isKindOf(KINDOF_BRIDGE) || thing->isKindOf(KINDOF_BRIDGE_TOWER)) {
+ continue;
+ }
+ const Coord3D *pos = draw->getPosition();
+ if (ThePartitionManager->getShroudStatusForPlayer(playerIndex, pos) == CELLSHROUD_SHROUDED) {
+ continue;
+ }
+ const GeometryInfo &geometry = thing->getTemplateGeometryInfo();
+ const Real roof = pos->z + geometry.getMaxHeightAbovePosition();
+ const Real reach = geometry.getBoundingCircleRadius();
+ const Real angle = draw->getOrientation();
+ const Real c = cosf(angle);
+ const Real s = sinf(angle);
+ const Int firstColumn = max(0, (Int)floorf((pos->x - reach - extent.lo.x) / BLOCKER_CELL));
+ const Int lastColumn = min(m_blockerColumns - 1, (Int)floorf((pos->x + reach - extent.lo.x) / BLOCKER_CELL));
+ const Int firstRow = max(0, (Int)floorf((pos->y - reach - extent.lo.y) / BLOCKER_CELL));
+ const Int lastRow = min(m_blockerRows - 1, (Int)floorf((pos->y + reach - extent.lo.y) / BLOCKER_CELL));
+ for (Int row = firstRow; row <= lastRow; ++row)
+ {
+ for (Int column = firstColumn; column <= lastColumn; ++column)
+ {
+ // the cell's centre, in the building's own frame
+ const Real dx = extent.lo.x + (column + 0.5f) * BLOCKER_CELL - pos->x;
+ const Real dy = extent.lo.y + (row + 0.5f) * BLOCKER_CELL - pos->y;
+ const Bool inside = geometry.getGeomType() == GEOMETRY_BOX
+ ? fabsf(dx * c + dy * s) <= geometry.getMajorRadius() && fabsf(-dx * s + dy * c) <= geometry.getMinorRadius()
+ : dx * dx + dy * dy <= geometry.getMajorRadius() * geometry.getMajorRadius();
+ Real &cell = m_blockers[row * m_blockerColumns + column];
+ if (inside && roof > cell) {
+ cell = roof;
+ }
+ }
+ }
+ }
+}
+
//-------------------------------------------------------------------------------------------------
/** 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
@@ -3093,8 +3540,15 @@ Bool MilesAudioManager::checkForSample( AudioRequest *req )
// Fill in event info
getInfoForAudioEvent( req->m_pendingEvent );
}
-
- if (req->m_pendingEvent->getAudioEventInfo()->m_type != AT_SoundEffect)
+
+ // A battle shot that waited out its distance meets the voice budget as it lands: when it was asked
+ // for, the voices it would join were still to come. EA's test below compares the ST_ bits with an
+ // AudioType, so most delayed sounds skip canPlayNow here and never reached the budget at all.
+ if (refuseOverBudget(req->m_pendingEvent)) {
+ return false;
+ }
+
+ if (req->m_pendingEvent->getAudioEventInfo()->m_type != AT_SoundEffect)
{
return true;
}
@@ -3183,38 +3637,31 @@ Real MilesAudioManager::getFileLengthMS( AsciiString strToLoad ) const
}
//-------------------------------------------------------------------------------------------------
+/** The cache is throwing a file away to make room, so whatever plays it stops now: its sample is
+ * ended and handed back, and it forgets the file, which is freed when this returns. It stays on its
+ * list, stopped, for processPlayingList's sweep to free.
+ *
+ * It used to be freed here, and this runs from inside the cache's openFile, which is reached from
+ * the middle of playAudioEvent, startNextLoop and notifyOfAudioCompletion, while stopAudioEvent or
+ * processPlayingList are walking the 3D list and holding one of its sounds. Crash 1275 (v3.2.0, a
+ * NULL event read in stopAudioEvent's walk of the 3D list) fits that: in v3.2.0 a sound whose stop
+ * was being processed opened its decay portion still naming the file it had just closed, an eviction
+ * could find it by that file and free it and its list node, and the walk went on through freed
+ * memory. 1bb1e81b made that sound forget its file first; this makes an eviction free nothing under
+ * any caller. */
void MilesAudioManager::closeAnySamplesUsingFile( const void *fileToClose )
{
- std::list<PlayingAudio *>::iterator it;
- PlayingAudio *playing;
-
- for (it = m_playingSounds.begin(); it != m_playingSounds.end(); ) {
- playing = *it;
- if (!playing) {
- continue;
- }
-
- if (playing->m_file == fileToClose) {
- stopPlayingAudio(playing);
- }
- ++it;
- }
-
- for (it = m_playing3DSounds.begin(); it != m_playing3DSounds.end(); ) {
- playing = *it;
- if (!playing) {
- ++it;
- continue;
- }
-
- if (playing->m_file == fileToClose) {
- stopPlayingAudio(playing);
+ std::list<PlayingAudio *> *lists[] = { &m_playingSounds, &m_playing3DSounds };
+ for (Int i = 0; i < 2; ++i) {
+ std::list<PlayingAudio *>::iterator it;
+ for (it = lists[i]->begin(); it != lists[i]->end(); ++it) {
+ PlayingAudio *playing = *it;
+ if (playing->m_file == fileToClose) {
+ stopPlayingAudio(playing);
+ playing->m_file = NULL; // freed by the cache, not to be closed again by the sweep
+ }
}
- ++it;
}
-
- releasePlayingAudioInListIfStopped(m_playingSounds, m_playingSoundsCS);
- releasePlayingAudioInListIfStopped(m_playing3DSounds, m_playing3DSoundsCS);
}
//-------------------------------------------------------------------------------------------------
@@ -3323,18 +3770,19 @@ Bool MilesAudioManager::startNextLoop( PlayingAudio *looping )
looping->m_audioEventRTS->generateFilename();
if (looping->m_audioEventRTS->getDelay() > MSEC_PER_LOGICFRAME_REAL) {
- // fake it out so that this sound appears done, but also so that it will not
- // delete the sound on completion (which would suck)
- looping->m_cleanupAudioEventRTS = false;
+ // This pass is done, and the next waits on the request list for its delay with a copy of
+ // the event. EA handed over the event itself and kept pointing at it until the sweep, so a
+ // stop that dropped the request in the same update freed it under this entry, and the next
+ // walk of the list (stopAudioEvent, the sweep's stopPlayingAudio) read freed memory.
#if defined(_WIN32)
InterlockedCompareExchange( (volatile long *)&looping->m_status, PS_Stopping, PS_Playing );
#else
playingStatusCompareExchange( &looping->m_status, PS_Stopping, PS_Playing );
#endif
-
-
+
+
AudioRequest *req = allocateAudioRequest(true);
- req->m_pendingEvent = looping->m_audioEventRTS;
+ req->m_pendingEvent = MSGNEW("AudioEventRTS") AudioEventRTS(*looping->m_audioEventRTS);
req->m_requiresCheckForSample = true;
req->m_nextLoop = true;
appendAudioRequest(req);
@@ -3342,7 +3790,7 @@ Bool MilesAudioManager::startNextLoop( PlayingAudio *looping )
}
if (looping->m_type == PAT_3DSample) {
- looping->m_file = playSample3D(looping->m_audioEventRTS, looping->m_3DSample);
+ looping->m_file = playSample3D(looping);
} else {
looping->m_file = playSample(looping->m_audioEventRTS, looping->m_sample);
}
@@ -3392,8 +3840,10 @@ void *MilesAudioManager::playSample( AudioEventRTS *event, HSAMPLE sample )
}
//-------------------------------------------------------------------------------------------------
-void *MilesAudioManager::playSample3D( AudioEventRTS *event, H3DSAMPLE sample3D )
+void *MilesAudioManager::playSample3D( PlayingAudio *audio )
{
+ AudioEventRTS *event = audio->m_audioEventRTS;
+ H3DSAMPLE sample3D = audio->m_3DSample;
const Coord3D *pos = getCurrentPositionFromEvent(event);
if (pos) {
// Load the file in
@@ -3420,7 +3870,7 @@ void *MilesAudioManager::playSample3D( AudioEventRTS *event, H3DSAMPLE sample3D
Real y = pos->y;
Real z = pos->z;
AIL_set_3D_position( sample3D, x, y, z );
- initFilters3D(sample3D, event, pos);
+ initFilters3D(audio, pos);
// Start playback
noteAudioStarted((UnsignedIntPtr) sample3D);
diff --git a/GeneralsMD/Code/Tests/test_audio_mix_policy.cpp b/GeneralsMD/Code/Tests/test_audio_mix_policy.cpp
new file mode 100644
index 000000000..77988da45
--- /dev/null
+++ b/GeneralsMD/Code/Tests/test_audio_mix_policy.cpp
@@ -0,0 +1,69 @@
+/*
+ * The arithmetic of MilesAudioManager's battle mix (MilesAudioDevice/AudioMixPolicy.h): which sound
+ * gives way when the voices run out, how much louder a folded shot plays, how deep a hill stands in
+ * the line from the microphone, and how the muffle moves. The manager itself, its lists and the
+ * terrain it reads are measured in the -wav mix (experiments/proofs/2026-10-25/audio-mix).
+ */
+#include "test_harness.h"
+
+#include "MilesAudioDevice/AudioMixPolicy.h"
+
+using namespace AudioMixPolicy;
+
+TEST(importance_puts_priority_first_and_the_quieter_sound_below_its_equal)
+{
+ CHECK(importance(2, 0.9f) < importance(3, 0.0f));
+ CHECK(importance(2, 0.1f) < importance(2, 0.8f));
+ CHECK_NEAR(importance(1, 3.0f), 2.0f, 1e-6f); // loudness is held to 0..1
+ CHECK_NEAR(importance(1, -1.0f), 1.0f, 1e-6f);
+}
+
+TEST(a_folded_shot_grows_a_step_each_and_stops_at_the_ceiling)
+{
+ CHECK_NEAR(coalescedGain(0, 0.12f, 1.5f), 1.0f, 1e-6f);
+ CHECK_NEAR(coalescedGain(2, 0.12f, 1.5f), 1.24f, 1e-6f);
+ CHECK_NEAR(coalescedGain(19, 0.12f, 1.5f), 1.5f, 1e-6f);
+}
+
+// A ridge 100 high between x = 400 and x = 600 on flat ground at 0.
+static float ridge(float x, float)
+{
+ return x >= 400.0f && x <= 600.0f ? 100.0f : 0.0f;
+}
+
+TEST(a_ridge_between_microphone_and_sound_stands_in_the_line_by_its_height)
+{
+ // microphone at 50 over the ground at x 0, the sound at 10 over it at x 1000: the line is near 30 at the ridge
+ const float depth = rayObstruction(0.0f, 0.0f, 50.0f, 1000.0f, 0.0f, 10.0f, 20.0f, 25.0f, 64, ridge);
+ CHECK(depth > 65.0f && depth < 75.0f);
+ CHECK_NEAR(occlusionAmount(depth, 30.0f), 1.0f, 1e-6f);
+
+ // the same ridge seen from high above clears the line
+ CHECK_NEAR(rayObstruction(0.0f, 0.0f, 400.0f, 1000.0f, 0.0f, 10.0f, 20.0f, 25.0f, 64, ridge), 0.0f, 1e-6f);
+}
+
+TEST(the_ground_under_either_end_is_not_a_hill_between_them)
+{
+ // flat ground at 0 and a sound on it at 0: only the margins touch the line, and they are left out
+ struct Flat { float operator()(float, float) const { return 0.0f; } };
+ CHECK_NEAR(rayObstruction(0.0f, 0.0f, 50.0f, 300.0f, 0.0f, 0.0f, 20.0f, 25.0f, 64, Flat()), 0.0f, 1e-6f);
+ // a sound closer than both margins is never looked through
+ CHECK_NEAR(rayObstruction(0.0f, 0.0f, 0.0f, 40.0f, 0.0f, 0.0f, 20.0f, 25.0f, 64, ridge), 0.0f, 1e-6f);
+}
+
+TEST(a_long_line_is_sampled_no_more_than_the_cap)
+{
+ int calls = 0;
+ rayObstruction(0.0f, 0.0f, 50.0f, 5000.0f, 0.0f, 0.0f, 20.0f, 25.0f, 48,
+ [&calls](float, float) { ++calls; return 0.0f; });
+ CHECK_EQ(calls, 48);
+}
+
+TEST(the_muffle_moves_towards_what_was_seen_and_stands_still_without_time)
+{
+ CHECK_NEAR(approach(0.0f, 1.0f, 0.0f, 250.0f), 0.0f, 1e-6f);
+ CHECK_NEAR(approach(0.0f, 1.0f, 250.0f, 250.0f), 0.6321f, 1e-3f);
+ CHECK_NEAR(approach(0.3f, 1.0f, 16.0f, 0.0f), 1.0f, 1e-6f);
+ // two half steps land where one whole step does, so the frame rate does not change how fast it opens
+ CHECK_NEAR(approach(approach(1.0f, 0.0f, 125.0f, 250.0f), 0.0f, 125.0f, 250.0f), approach(1.0f, 0.0f, 250.0f, 250.0f), 1e-5f);
+}