LCOV - code coverage report
Current view: top level - source/soundmanager/scripting - SoundGroup.cpp (source / functions) Hit Total Coverage
Test: 0 A.D. test coverage report Lines: 0 209 0.0 %
Date: 2026-12-03 01:19:39 Functions: 0 13 0.0 %

          Line data    Source code
       1             : /* Copyright (C) 2026 Wildfire Games.
       2             :  * This file is part of 0 A.D.
       3             :  *
       4             :  * 0 A.D. is free software: you can redistribute it and/or modify
       5             :  * it under the terms of the GNU General Public License as published by
       6             :  * the Free Software Foundation, either version 2 of the License, or
       7             :  * (at your option) any later version.
       8             :  *
       9             :  * 0 A.D. is distributed in the hope that it will be useful,
      10             :  * but WITHOUT ANY WARRANTY; without even the implied warranty of
      11             :  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      12             :  * GNU General Public License for more details.
      13             :  *
      14             :  * You should have received a copy of the GNU General Public License
      15             :  * along with 0 A.D.  If not, see <http://www.gnu.org/licenses/>.
      16             :  */
      17             : 
      18             : #include "precompiled.h"
      19             : 
      20             : #include "SoundGroup.h"
      21             : 
      22             : #include "graphics/Camera.h"
      23             : #include "graphics/GameView.h"
      24             : #include "lib/rand.h"
      25             : #include "maths/Vector2D.h"
      26             : #include "ps/CLogger.h"
      27             : #include "ps/ConfigDB.h"
      28             : #include "ps/CStr.h"
      29             : #include "ps/Filesystem.h"
      30             : #include "ps/Game.h"
      31             : #include "ps/Util.h"
      32             : #include "ps/XML/Xeromyces.h"
      33             : #include "simulation2/components/ICmpVisual.h"
      34             : #include "simulation2/system/Component.h"
      35             : #include "soundmanager/items/ISoundItem.h"
      36             : #include "soundmanager/SoundManager.h"
      37             : 
      38             : #include <algorithm>
      39             : 
      40             : extern CGame *g_Game;
      41             : 
      42             : #if CONFIG2_AUDIO
      43             : 
      44             : #include "lib/path.h"
      45             : #include "lib/status.h"
      46             : #include "lib/utf8.h"
      47             : #include "maths/Matrix3D.h"
      48             : #include "maths/Vector3D.h"
      49             : #include "ps/Errors.h"
      50             : #include "ps/XMB/XMBData.h"
      51             : #include "scriptinterface/Interface.h"
      52             : #include "soundmanager/ISoundManager.h"
      53             : #include "soundmanager/data/SoundData.h"
      54             : 
      55             : #include <AL/al.h>
      56             : #include <cmath>
      57             : #include <numbers>
      58             : #include <utility>
      59             : 
      60             : constexpr ALfloat DEFAULT_ROLLOFF = 0.5f;
      61             : constexpr ALfloat MAX_ROLLOFF = 0.7f;
      62             : 
      63             : /**
      64             :  * Low randomness, quite-a-lot-faster-than-std::mt19937 random number generator.
      65             :  * It matches the interface of UniformRandomBitGenerator for use in std::shuffle.
      66             :  */
      67             : class CFastRand
      68             : {
      69             : public:
      70             :     using result_type = std::uint32_t;
      71             : 
      72             :     constexpr static result_type min() { return 0; }
      73             :     constexpr static result_type max() { return 0xFFFF; }
      74             : 
      75           0 :     static result_type Rand(result_type& seed)
      76             :     {
      77             :         // This is a mixed linear congruential random number generator.
      78             :         // The magic numbers are chosen so that they generate pseudo random numbers over a big enough period (0xFFFF).
      79           0 :         seed = 214013 * seed + 2531011;
      80           0 :         return (seed >> 16) & max();
      81             :     }
      82             : 
      83           0 :     static float RandFloat(result_type& seed, float min, float max)
      84             :     {
      85           0 :         return (static_cast<float>(Rand(seed)) / (0xFFFF)) * (max - min) + min;
      86             :     }
      87             : 
      88             :     CFastRand() {};
      89           0 :     CFastRand(result_type init) : m_Seed(init) {};
      90             : 
      91           0 :     result_type operator()()
      92             :     {
      93           0 :         return Rand(m_Seed);
      94             :     }
      95             : 
      96             :     result_type m_Seed;
      97             : };
      98             : #endif
      99             : 
     100           0 : void CSoundGroup::SetGain(float gain)
     101             : {
     102           0 :     m_Gain = std::min(gain, 1.0f);
     103           0 : }
     104             : 
     105           0 : void CSoundGroup::SetDefaultValues()
     106             : {
     107           0 :     m_CurrentSoundIndex = 0;
     108           0 :     m_Flags = 0;
     109           0 :     m_CurTime = 0.f;
     110           0 :     m_Gain = 0.7f;
     111           0 :     m_Pitch = 1.f;
     112           0 :     m_Priority = 60.f;
     113           0 :     m_PitchUpper = 1.1f;
     114           0 :     m_PitchLower = 0.9f;
     115           0 :     m_GainUpper = 1.f;
     116           0 :     m_GainLower = 0.8f;
     117           0 :     m_ConeOuterGain = 0.f;
     118           0 :     m_ConeInnerAngle = 360.f;
     119           0 :     m_ConeOuterAngle = 360.f;
     120           0 :     m_Decay = 3.f;
     121           0 :     m_Seed = 0;
     122           0 :     m_IntensityThreshold = 3.f;
     123             : 
     124           0 :     m_MinDist = CConfigDB::GetIfInitialised("sound.mindistance", 1.f);
     125           0 :     m_MaxDist = CConfigDB::GetIfInitialised("sound.maxdistance", 350.f);
     126             :     // This is more than the default camera FOV: for now, our soundscape is not realistic anyways.
     127           0 :     m_MaxStereoAngle = CConfigDB::GetIfInitialised("sound.maxstereoangle", std::numbers::pi_v<float> / 6.f);
     128           0 : }
     129             : 
     130           0 : CSoundGroup::CSoundGroup()
     131             : {
     132           0 :     SetDefaultValues();
     133           0 : }
     134             : 
     135           0 : CSoundGroup::CSoundGroup(const VfsPath& pathnameXML)
     136             : {
     137           0 :     SetDefaultValues();
     138           0 :     LoadSoundGroup(pathnameXML);
     139           0 : }
     140             : 
     141           0 : CSoundGroup::~CSoundGroup()
     142             : {
     143             :     // clean up all the handles from this group.
     144           0 :     ReleaseGroup();
     145           0 : }
     146             : 
     147           0 : float CSoundGroup::RadiansOffCenter([[maybe_unused]] const CVector3D& position,
     148             :     [[maybe_unused]] bool& onScreen, [[maybe_unused]] float& itemRollOff)
     149             : {
     150             : #if !CONFIG2_AUDIO
     151             :     return 0.f;
     152             : #else
     153           0 :     const int screenWidth = g_Game->GetView()->GetCamera().GetViewPort().m_Width;
     154           0 :     const int screenHeight = g_Game->GetView()->GetCamera().GetViewPort().m_Height;
     155           0 :     const float xBufferSize = screenWidth * 0.1f;
     156           0 :     const float yBufferSize = 15.f;
     157           0 :     const float radianCap = m_MaxStereoAngle;
     158             : 
     159           0 :     const CVector2D screenPos{g_Game->GetView()->GetCamera().GetScreenCoordinates(position)};
     160             : 
     161           0 :     onScreen = true;
     162           0 :     float answer = 0.f;
     163           0 :     if (screenPos.X < -xBufferSize)
     164             :     {
     165           0 :         onScreen = false;
     166           0 :         answer = -radianCap;
     167             :     }
     168           0 :     else if (screenPos.X > screenWidth + xBufferSize)
     169             :     {
     170           0 :         onScreen = false;
     171           0 :         answer = radianCap;
     172             :     }
     173             :     else
     174             :     {
     175           0 :         if (screenPos.X < 0 || screenPos.X > screenWidth)
     176           0 :             itemRollOff = MAX_ROLLOFF;
     177             : 
     178           0 :         answer = radianCap * (screenPos.X * 2 / screenWidth - 1);
     179             :     }
     180             : 
     181           0 :     if (screenPos.Y < -yBufferSize)
     182             :     {
     183           0 :         onScreen = false;
     184             :     }
     185           0 :     else if (screenPos.Y > screenHeight + yBufferSize)
     186             :     {
     187           0 :         onScreen = false;
     188             :     }
     189           0 :     else if (screenPos.Y < 0 || screenPos.Y > screenHeight)
     190             :     {
     191           0 :         itemRollOff = MAX_ROLLOFF;
     192             :     }
     193             : 
     194           0 :     return answer;
     195             : #endif // !CONFIG2_AUDIO
     196             : }
     197             : 
     198           0 : void CSoundGroup::UploadPropertiesAndPlay([[maybe_unused]] size_t index,
     199             :     [[maybe_unused]] const CVector3D& position, [[maybe_unused]] entity_id_t source)
     200             : {
     201             : #if CONFIG2_AUDIO
     202           0 :     if (!g_SoundManager)
     203           0 :         return;
     204             : 
     205           0 :     bool isOnscreen = false;
     206           0 :     ALfloat itemRollOff = DEFAULT_ROLLOFF;
     207           0 :     float offset = RadiansOffCenter(position, isOnscreen, itemRollOff);
     208             : 
     209           0 :     if (!isOnscreen && !TestFlag(eDistanceless) && !TestFlag(eOmnipresent))
     210             :         return;
     211             : 
     212           0 :     if (m_SoundGroups.empty())
     213           0 :         Reload();
     214             : 
     215           0 :     if (m_SoundGroups.size() <= index)
     216             :         return;
     217             : 
     218           0 :     CSoundData* sndData = m_SoundGroups[index];
     219           0 :     if (!sndData)
     220             :         return;
     221             : 
     222           0 :     ISoundItem* hSound = static_cast<CSoundManager*>(g_SoundManager)->ItemForEntity(source, sndData);
     223           0 :     if (!hSound)
     224             :         return;
     225             : 
     226           0 :     if (!TestFlag(eOmnipresent))
     227             :     {
     228           0 :         CVector3D origin = g_Game->GetView()->GetCamera().GetOrientation().GetTranslation();
     229           0 :         float itemDist = (position - origin).Length();
     230             : 
     231           0 :         if (TestFlag(eDistanceless))
     232           0 :             itemRollOff = 0;
     233             : 
     234           0 :         if (sndData->IsStereo())
     235             :         {
     236           0 :             LOGWARNING("OpenAL: stereo sounds can't be positioned: {}",
     237             :                 sndData->GetFileName().string8());
     238             :         }
     239             : 
     240           0 :         hSound->SetLocation(CVector3D(itemDist * sin(offset), 0, -itemDist * cos(offset)));
     241           0 :         hSound->SetRollOff(itemRollOff, m_MinDist, m_MaxDist);
     242             :     }
     243             : 
     244           0 :     CmpPtr<ICmpVisual> cmpVisual(*g_Game->GetSimulation2(), source);
     245           0 :     if (cmpVisual)
     246           0 :         m_Seed = cmpVisual->GetActorSeed();
     247             : 
     248           0 :     hSound->SetPitch(TestFlag(eRandPitch) ? CFastRand::RandFloat(m_Seed, m_PitchLower, m_PitchUpper) : m_Pitch);
     249             : 
     250           0 :     if (TestFlag(eRandGain))
     251           0 :         m_Gain = CFastRand::RandFloat(m_Seed, m_GainLower, m_GainUpper);
     252             : 
     253           0 :     hSound->SetCone(m_ConeInnerAngle, m_ConeOuterAngle, m_ConeOuterGain);
     254           0 :     static_cast<CSoundManager*>(g_SoundManager)->PlayGroupItem(hSound, m_Gain);
     255             : #endif // !CONFIG2_AUDIO
     256             : }
     257             : 
     258           0 : static void HandleError(const std::wstring& message, const VfsPath& pathname, Status err)
     259             : {
     260             :     // Open failed because sound is disabled (don't log this)
     261           0 :     if (err == ERR::AGAIN)
     262             :         return;
     263             : 
     264           0 :     LOGERROR("{}: pathname={}, error={}", utf8_from_wstring(message), pathname.string8(),
     265             :         GetStatusAsString(err));
     266             : }
     267             : 
     268           0 : void CSoundGroup::PlayNext(const CVector3D& position, entity_id_t source)
     269             : {
     270           0 :     if (m_Filenames.empty())
     271             :         return;
     272             : 
     273           0 :     m_CurrentSoundIndex = rand(0, m_Filenames.size());
     274           0 :     UploadPropertiesAndPlay(m_CurrentSoundIndex, position, source);
     275             : }
     276             : 
     277           0 : void CSoundGroup::Reload()
     278             : {
     279           0 :     m_CurrentSoundIndex = 0;
     280             : #if CONFIG2_AUDIO
     281           0 :     ReleaseGroup();
     282             : 
     283           0 :     if (!g_SoundManager)
     284             :         return;
     285             : 
     286           0 :     for (const std::wstring& filename : m_Filenames)
     287             :     {
     288           0 :         VfsPath absolutePath = m_Filepath / filename;
     289           0 :         CSoundData* itemData = CSoundData::SoundDataFromFile(absolutePath);
     290           0 :         if (!itemData)
     291           0 :             HandleError(L"error loading sound", absolutePath, ERR::FAIL);
     292             :         else
     293           0 :             m_SoundGroups.push_back(itemData->IncrementCount());
     294           0 :     }
     295             : 
     296           0 :     if (TestFlag(eRandOrder))
     297           0 :         std::shuffle(m_SoundGroups.begin(), m_SoundGroups.end(), CFastRand(m_Seed));
     298             : #endif
     299             : }
     300             : 
     301           0 : void CSoundGroup::ReleaseGroup()
     302             : {
     303             : #if CONFIG2_AUDIO
     304           0 :     for (CSoundData* soundGroup : m_SoundGroups)
     305           0 :         CSoundData::ReleaseSoundData(soundGroup);
     306             : 
     307           0 :     m_SoundGroups.clear();
     308             : #endif
     309           0 : }
     310             : 
     311           0 : void CSoundGroup::Update(float /*TimeSinceLastFrame*/)
     312             : {
     313           0 : }
     314             : 
     315           0 : bool CSoundGroup::LoadSoundGroup(const VfsPath& pathnameXML)
     316             : {
     317           0 :     CXeromyces XeroFile;
     318           0 :     if (XeroFile.Load(g_VFS, pathnameXML, "sound_group") != PSRETURN_OK)
     319             :     {
     320           0 :         HandleError(L"error loading file", pathnameXML, ERR::FAIL);
     321           0 :         return false;
     322             :     }
     323             : 
     324             : #define EL(x) int el_##x = XeroFile.GetElementID(#x)
     325           0 :     EL(soundgroup);
     326           0 :     EL(gain);
     327           0 :     EL(looping);
     328           0 :     EL(omnipresent);
     329           0 :     EL(heardby);
     330           0 :     EL(distanceless);
     331           0 :     EL(pitch);
     332           0 :     EL(priority);
     333           0 :     EL(randorder);
     334           0 :     EL(randgain);
     335           0 :     EL(randpitch);
     336           0 :     EL(conegain);
     337           0 :     EL(coneinner);
     338           0 :     EL(coneouter);
     339           0 :     EL(sound);
     340           0 :     EL(gainupper);
     341           0 :     EL(gainlower);
     342           0 :     EL(pitchupper);
     343           0 :     EL(pitchlower);
     344           0 :     EL(path);
     345           0 :     EL(threshold);
     346           0 :     EL(decay);
     347             : #undef EL
     348             : 
     349           0 :     XMBElement root = XeroFile.GetRoot();
     350             : 
     351           0 :     if (root.GetNodeName() != el_soundgroup)
     352             :     {
     353           0 :         LOGERROR("Invalid SoundGroup format (unrecognized root element '{}')",
     354             :             XeroFile.GetElementString(root.GetNodeName()));
     355           0 :         return false;
     356             :     }
     357             : 
     358           0 :     for (XMBElement child : root.GetChildNodes())
     359             :     {
     360           0 :         int child_name = child.GetNodeName();
     361             : 
     362           0 :         if (child_name == el_gain)
     363             :         {
     364           0 :             SetGain(child.GetText().ToFloat());
     365             :         }
     366           0 :         else if (child_name == el_looping)
     367             :         {
     368           0 :             if (child.GetText().ToInt() == 1)
     369           0 :                 SetFlag(eLoop);
     370             :         }
     371           0 :         else if (child_name == el_omnipresent)
     372             :         {
     373           0 :             if (child.GetText().ToInt() == 1)
     374           0 :                 SetFlag(eOmnipresent);
     375             :         }
     376           0 :         else if (child_name == el_heardby)
     377             :         {
     378           0 :             if (child.GetText().LowerCase().starts_with("owner"))
     379           0 :                 SetFlag(eOwnerOnly);
     380             :         }
     381           0 :         else if (child_name == el_distanceless)
     382             :         {
     383           0 :             if (child.GetText().ToInt() == 1)
     384           0 :                 SetFlag(eDistanceless);
     385             :         }
     386           0 :         else if (child_name == el_pitch)
     387             :         {
     388           0 :             this->m_Pitch = child.GetText().ToFloat();
     389             :         }
     390           0 :         else if (child_name == el_priority)
     391             :         {
     392           0 :             this->m_Priority = child.GetText().ToFloat();
     393             :         }
     394           0 :         else if (child_name == el_randorder)
     395             :         {
     396           0 :             if (child.GetText().ToInt() == 1)
     397           0 :                 SetFlag(eRandOrder);
     398             :         }
     399           0 :         else if (child_name == el_randgain)
     400             :         {
     401           0 :             if (child.GetText().ToInt() == 1)
     402           0 :                 SetFlag(eRandGain);
     403             :         }
     404           0 :         else if (child_name == el_gainupper)
     405             :         {
     406           0 :             this->m_GainUpper = child.GetText().ToFloat();
     407             :         }
     408           0 :         else if (child_name == el_gainlower)
     409             :         {
     410           0 :             this->m_GainLower = child.GetText().ToFloat();
     411             :         }
     412           0 :         else if (child_name == el_randpitch)
     413             :         {
     414           0 :             if (child.GetText().ToInt() == 1)
     415           0 :                 SetFlag(eRandPitch);
     416             :         }
     417           0 :         else if (child_name == el_pitchupper)
     418             :         {
     419           0 :             this->m_PitchUpper = child.GetText().ToFloat();
     420             :         }
     421           0 :         else if (child_name == el_pitchlower)
     422             :         {
     423           0 :             this->m_PitchLower = child.GetText().ToFloat();
     424             :         }
     425           0 :         else if (child_name == el_conegain)
     426             :         {
     427           0 :             this->m_ConeOuterGain = child.GetText().ToFloat();
     428             :         }
     429           0 :         else if (child_name == el_coneinner)
     430             :         {
     431           0 :             this->m_ConeInnerAngle = child.GetText().ToFloat();
     432             :         }
     433           0 :         else if (child_name == el_coneouter)
     434             :         {
     435           0 :             this->m_ConeOuterAngle = child.GetText().ToFloat();
     436             :         }
     437           0 :         else if (child_name == el_sound)
     438             :         {
     439           0 :             this->m_Filenames.push_back(child.GetText().FromUTF8());
     440             :         }
     441           0 :         else if (child_name == el_path)
     442             :         {
     443           0 :             m_Filepath = child.GetText().FromUTF8();
     444             :         }
     445           0 :         else if (child_name == el_threshold)
     446             :         {
     447           0 :             m_IntensityThreshold = child.GetText().ToFloat();
     448             :         }
     449           0 :         else if (child_name == el_decay)
     450             :         {
     451           0 :             m_Decay = child.GetText().ToFloat();
     452             :         }
     453             :     }
     454           0 :     return true;
     455           0 : }

Generated by: LCOV version 1.16