CMusicHandler.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  1. #include "StdInc.h"
  2. #include <boost/bimap.hpp>
  3. #include <SDL_mixer.h>
  4. #include "CMusicHandler.h"
  5. #include "../lib/CCreatureHandler.h"
  6. #include "../lib/CSpellHandler.h"
  7. #include "../client/CGameInfo.h"
  8. #include "../lib/JsonNode.h"
  9. #include "../lib/GameConstants.h"
  10. #include "../lib/Filesystem/CResourceLoader.h"
  11. /*
  12. * CMusicHandler.cpp, part of VCMI engine
  13. *
  14. * Authors: listed in file AUTHORS in main folder
  15. *
  16. * License: GNU General Public License v2.0 or later
  17. * Full text of license available in license.txt file, in main folder
  18. *
  19. */
  20. using namespace boost::assign;
  21. static boost::bimap<soundBase::soundID, std::string> sounds;
  22. // Not pretty, but there's only one music handler object in the game.
  23. static void soundFinishedCallbackC(int channel)
  24. {
  25. CCS->soundh->soundFinishedCallback(channel);
  26. }
  27. static void musicFinishedCallbackC(void)
  28. {
  29. CCS->musich->musicFinishedCallback();
  30. }
  31. void CAudioBase::init()
  32. {
  33. if (initialized)
  34. return;
  35. if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 1024)==-1)
  36. {
  37. tlog1 << "Mix_OpenAudio error: " << Mix_GetError() << std::endl;
  38. return;
  39. }
  40. initialized = true;
  41. }
  42. void CAudioBase::release()
  43. {
  44. if (initialized)
  45. {
  46. Mix_CloseAudio();
  47. initialized = false;
  48. }
  49. }
  50. void CAudioBase::setVolume(ui32 percent)
  51. {
  52. if (percent > 100)
  53. percent = 100;
  54. volume = percent;
  55. }
  56. void CSoundHandler::onVolumeChange(const JsonNode &volumeNode)
  57. {
  58. setVolume(volumeNode.Float());
  59. }
  60. CSoundHandler::CSoundHandler():
  61. listener(settings.listen["general"]["sound"])
  62. {
  63. listener(boost::bind(&CSoundHandler::onVolumeChange, this, _1));
  64. // Map sound names
  65. #define VCMI_SOUND_NAME(x) ( soundBase::x,
  66. #define VCMI_SOUND_FILE(y) #y )
  67. sounds = boost::assign::list_of<boost::bimap<soundBase::soundID, std::string>::relation>
  68. VCMI_SOUND_LIST;
  69. #undef VCMI_SOUND_NAME
  70. #undef VCMI_SOUND_FILE
  71. // Vectors for helper(s)
  72. pickupSounds += soundBase::pickup01, soundBase::pickup02, soundBase::pickup03,
  73. soundBase::pickup04, soundBase::pickup05, soundBase::pickup06, soundBase::pickup07;
  74. horseSounds += // must be the same order as terrains (see EterrainType);
  75. soundBase::horseDirt, soundBase::horseSand, soundBase::horseGrass,
  76. soundBase::horseSnow, soundBase::horseSwamp, soundBase::horseRough,
  77. soundBase::horseSubterranean, soundBase::horseLava,
  78. soundBase::horseWater, soundBase::horseRock;
  79. battleIntroSounds += soundBase::battle00, soundBase::battle01,
  80. soundBase::battle02, soundBase::battle03, soundBase::battle04,
  81. soundBase::battle05, soundBase::battle06, soundBase::battle07;
  82. };
  83. void CSoundHandler::init()
  84. {
  85. CAudioBase::init();
  86. if (initialized)
  87. {
  88. // Load sounds
  89. Mix_ChannelFinished(soundFinishedCallbackC);
  90. }
  91. }
  92. void CSoundHandler::release()
  93. {
  94. if (initialized)
  95. {
  96. Mix_HaltChannel(-1);
  97. std::map<soundBase::soundID, Mix_Chunk *>::iterator it;
  98. for (it=soundChunks.begin(); it != soundChunks.end(); it++)
  99. {
  100. if (it->second)
  101. Mix_FreeChunk(it->second);
  102. }
  103. }
  104. CAudioBase::release();
  105. }
  106. // Allocate an SDL chunk and cache it.
  107. Mix_Chunk *CSoundHandler::GetSoundChunk(soundBase::soundID soundID)
  108. {
  109. // Find its name
  110. boost::bimap<soundBase::soundID, std::string>::left_iterator it;
  111. it = sounds.left.find(soundID);
  112. if (it == sounds.left.end())
  113. return nullptr;
  114. // Load and insert
  115. try
  116. {
  117. auto data = CResourceHandler::get()->loadData(ResourceID(std::string("SOUNDS/") + it->second, EResType::SOUND));
  118. SDL_RWops *ops = SDL_RWFromMem(data.first.release(), data.second);
  119. Mix_Chunk *chunk;
  120. chunk = Mix_LoadWAV_RW(ops, 1); // will free ops
  121. soundChunks.insert(std::pair<soundBase::soundID, Mix_Chunk *>(soundID, chunk));
  122. return chunk;
  123. }
  124. catch(std::exception &e)
  125. {
  126. tlog3 << "Cannot get sound " << soundID << " chunk: " << e.what() << "\n";
  127. return nullptr;
  128. }
  129. }
  130. Mix_Chunk *CSoundHandler::GetSoundChunk(std::string &sound)
  131. {
  132. if (sound.empty())
  133. return nullptr;
  134. // Load and insert
  135. try
  136. {
  137. auto data = CResourceHandler::get()->loadData(ResourceID(std::string("SOUNDS/") + sound, EResType::SOUND)); //TODO: allow other sound folders?
  138. SDL_RWops *ops = SDL_RWFromMem(data.first.release(), data.second);
  139. Mix_Chunk *chunk;
  140. chunk = Mix_LoadWAV_RW(ops, 1); // will free ops
  141. return chunk;
  142. }
  143. catch(std::exception &e)
  144. {
  145. tlog3 << "Cannot get sound " << sound << " chunk: " << e.what() << "\n";
  146. return nullptr;
  147. }
  148. }
  149. // Get a soundID given a filename
  150. soundBase::soundID CSoundHandler::getSoundID(const std::string &fileName)
  151. {
  152. boost::bimap<soundBase::soundID, std::string>::right_iterator it;
  153. it = sounds.right.find(fileName);
  154. if (it == sounds.right.end())
  155. return soundBase::invalid;
  156. else
  157. return it->second;
  158. }
  159. void CSoundHandler::initCreaturesSounds(const std::vector<ConstTransitivePtr< CCreature> > &creatures)
  160. {
  161. //commented to avoid spurious warnings
  162. /*
  163. // Find creatures without sounds
  164. for(ui32 i=0;i<creatures.size();i++)
  165. {
  166. // Note: this will exclude war machines, but it's better
  167. // than nothing.
  168. if (vstd::contains(CGI->creh->notUsedMonsters, i))
  169. continue;
  170. CCreature &c = creatures[i];
  171. if (c.sounds.killed == soundBase::invalid)
  172. tlog1 << "creature " << c.idNumber << " doesn't have sounds" << std::endl;
  173. }*/
  174. }
  175. void CSoundHandler::initSpellsSounds(const std::vector< ConstTransitivePtr<CSpell> > &spells)
  176. {
  177. const JsonNode config(ResourceID("config/sp_sounds.json"));
  178. if (!config["spell_sounds"].isNull()) {
  179. BOOST_FOREACH(const JsonNode &node, config["spell_sounds"].Vector()) {
  180. int spellid = node["id"].Float();
  181. const CSpell *s = CGI->spellh->spells[spellid];
  182. if (vstd::contains(spellSounds, s))
  183. tlog1 << "Spell << " << spellid << " already has a sound" << std::endl;
  184. soundBase::soundID sound = getSoundID(node["soundfile"].String());
  185. if (sound == soundBase::invalid)
  186. tlog0 << "Error: invalid sound for id "<< spellid << "\n";
  187. spellSounds[s] = sound;
  188. }
  189. }
  190. }
  191. // Plays a sound, and return its channel so we can fade it out later
  192. int CSoundHandler::playSound(soundBase::soundID soundID, int repeats)
  193. {
  194. if (!initialized)
  195. return -1;
  196. int channel;
  197. Mix_Chunk *chunk = GetSoundChunk(soundID);
  198. if (chunk)
  199. {
  200. channel = Mix_PlayChannel(-1, chunk, repeats);
  201. if (channel == -1)
  202. tlog1 << "Unable to play sound file " << soundID << " , error " << Mix_GetError() << std::endl;
  203. else
  204. callbacks[channel];//insert empty callback
  205. }
  206. else
  207. {
  208. channel = -1;
  209. }
  210. return channel;
  211. }
  212. int CSoundHandler::playSound(std::string sound, int repeats)
  213. {
  214. if (!initialized)
  215. return -1;
  216. int channel;
  217. Mix_Chunk *chunk = GetSoundChunk(sound);
  218. if (chunk)
  219. {
  220. channel = Mix_PlayChannel(-1, chunk, repeats);
  221. if (channel == -1)
  222. tlog1 << "Unable to play sound file " << sound << " , error " << Mix_GetError() << std::endl;
  223. else
  224. callbacks[channel];//insert empty callback
  225. }
  226. else
  227. {
  228. channel = -1;
  229. }
  230. return channel;
  231. }
  232. // Helper. Randomly select a sound from an array and play it
  233. int CSoundHandler::playSoundFromSet(std::vector<soundBase::soundID> &sound_vec)
  234. {
  235. return playSound(sound_vec[rand() % sound_vec.size()]);
  236. }
  237. void CSoundHandler::stopSound( int handler )
  238. {
  239. if (initialized && handler != -1)
  240. Mix_HaltChannel(handler);
  241. }
  242. // Sets the sound volume, from 0 (mute) to 100
  243. void CSoundHandler::setVolume(ui32 percent)
  244. {
  245. CAudioBase::setVolume(percent);
  246. if (initialized)
  247. Mix_Volume(-1, (MIX_MAX_VOLUME * volume)/100);
  248. }
  249. void CSoundHandler::setCallback(int channel, boost::function<void()> function)
  250. {
  251. std::map<int, boost::function<void()> >::iterator iter;
  252. iter = callbacks.find(channel);
  253. //channel not found. It may have finished so fire callback now
  254. if(iter == callbacks.end())
  255. function();
  256. else
  257. iter->second = function;
  258. }
  259. void CSoundHandler::soundFinishedCallback(int channel)
  260. {
  261. std::map<int, boost::function<void()> >::iterator iter;
  262. iter = callbacks.find(channel);
  263. assert(iter != callbacks.end());
  264. if (iter->second)
  265. iter->second();
  266. callbacks.erase(iter);
  267. }
  268. void CMusicHandler::onVolumeChange(const JsonNode &volumeNode)
  269. {
  270. setVolume(volumeNode.Float());
  271. }
  272. CMusicHandler::CMusicHandler():
  273. listener(settings.listen["general"]["music"])
  274. {
  275. listener(boost::bind(&CMusicHandler::onVolumeChange, this, _1));
  276. // Map music IDs
  277. // Vectors for helper
  278. const std::string setEnemy[] = {"AITheme0", "AITheme1", "AITheme2"};
  279. const std::string setBattle[] = {"Combat01", "Combat02", "Combat03", "Combat04"};
  280. const std::string setTerrain[] = {"Dirt", "Sand", "Grass", "Snow", "Swamp", "Rough", "Underground", "Lava", "Water"};
  281. auto fillSet = [=](std::string setName, const std::string list[], size_t amount)
  282. {
  283. for (size_t i=0; i < amount; i++)
  284. addEntryToSet(setName, i, std::string("music/") + list[i]);
  285. };
  286. fillSet("enemy-turn", setEnemy, ARRAY_COUNT(setEnemy));
  287. fillSet("battle", setBattle, ARRAY_COUNT(setBattle));
  288. fillSet("terrain", setTerrain, ARRAY_COUNT(setTerrain));
  289. }
  290. void CMusicHandler::addEntryToSet(std::string set, int musicID, std::string musicURI)
  291. {
  292. musicsSet[set][musicID] = musicURI;
  293. }
  294. void CMusicHandler::init()
  295. {
  296. CAudioBase::init();
  297. if (initialized)
  298. Mix_HookMusicFinished(musicFinishedCallbackC);
  299. }
  300. void CMusicHandler::release()
  301. {
  302. if (initialized)
  303. {
  304. boost::mutex::scoped_lock guard(musicMutex);
  305. Mix_HookMusicFinished(NULL);
  306. current.reset();
  307. next.reset();
  308. }
  309. CAudioBase::release();
  310. }
  311. void CMusicHandler::playMusic(std::string musicURI, bool loop)
  312. {
  313. if (current && current->isTrack( musicURI))
  314. return;
  315. queueNext(new MusicEntry(this, "", musicURI, loop));
  316. }
  317. void CMusicHandler::playMusicFromSet(std::string whichSet, bool loop)
  318. {
  319. auto selectedSet = musicsSet.find(whichSet);
  320. if (selectedSet == musicsSet.end())
  321. {
  322. tlog0 << "Error: playing music from non-existing set: " << whichSet << "\n";
  323. return;
  324. }
  325. if (current && current->isSet(whichSet))
  326. return;
  327. queueNext(new MusicEntry(this, whichSet, "", loop));
  328. }
  329. void CMusicHandler::playMusicFromSet(std::string whichSet, int entryID, bool loop)
  330. {
  331. auto selectedSet = musicsSet.find(whichSet);
  332. if (selectedSet == musicsSet.end())
  333. {
  334. tlog0 << "Error: playing music from non-existing set: " << whichSet << "\n";
  335. return;
  336. }
  337. auto selectedEntry = selectedSet->second.find(entryID);
  338. if (selectedEntry == selectedSet->second.end())
  339. {
  340. tlog0 << "Error: playing non-existing entry " << entryID << " from set: " << whichSet << "\n";
  341. return;
  342. }
  343. if (current && current->isTrack( selectedEntry->second))
  344. return;
  345. queueNext(new MusicEntry(this, "", selectedEntry->second, loop));
  346. }
  347. void CMusicHandler::queueNext(MusicEntry *queued)
  348. {
  349. if (!initialized)
  350. return;
  351. boost::mutex::scoped_lock guard(musicMutex);
  352. next.reset(queued);
  353. if (current.get() == nullptr || !current->stop(1000))
  354. {
  355. current.reset(next.release());
  356. current->play();
  357. }
  358. }
  359. void CMusicHandler::stopMusic(int fade_ms)
  360. {
  361. if (!initialized)
  362. return;
  363. boost::mutex::scoped_lock guard(musicMutex);
  364. if (current.get() != NULL)
  365. current->stop(fade_ms);
  366. next.reset();
  367. }
  368. void CMusicHandler::setVolume(ui32 percent)
  369. {
  370. CAudioBase::setVolume(percent);
  371. if (initialized)
  372. Mix_VolumeMusic((MIX_MAX_VOLUME * volume)/100);
  373. }
  374. void CMusicHandler::musicFinishedCallback(void)
  375. {
  376. boost::mutex::scoped_lock guard(musicMutex);
  377. if (current.get() != NULL)
  378. {
  379. //return if current music still not finished
  380. if (current->play())
  381. return;
  382. else
  383. current.reset();
  384. }
  385. if (current.get() == NULL && next.get() != NULL)
  386. {
  387. current.reset(next.release());
  388. current->play();
  389. }
  390. }
  391. MusicEntry::MusicEntry(CMusicHandler *owner, std::string setName, std::string musicURI, bool looped):
  392. owner(owner),
  393. music(nullptr),
  394. loop(looped ? -1 : 1),
  395. setName(setName)
  396. {
  397. if (!musicURI.empty())
  398. load(musicURI);
  399. }
  400. MusicEntry::~MusicEntry()
  401. {
  402. tlog5<<"Del-ing music file "<<currentName<<"\n";
  403. if (music)
  404. Mix_FreeMusic(music);
  405. }
  406. void MusicEntry::load(std::string musicURI)
  407. {
  408. if (music)
  409. {
  410. tlog5<<"Del-ing music file "<<currentName<<"\n";
  411. Mix_FreeMusic(music);
  412. }
  413. currentName = musicURI;
  414. tlog5<<"Loading music file "<<musicURI<<"\n";
  415. music = Mix_LoadMUS(CResourceHandler::get()->getResourceName(ResourceID(musicURI, EResType::MUSIC)).c_str());
  416. if(!music)
  417. {
  418. tlog3 << "Warning: Cannot open " << currentName << ": " << Mix_GetError() << std::endl;
  419. return;
  420. }
  421. #ifdef _WIN32
  422. //The assertion will fail if old MSVC libraries pack .dll is used
  423. assert(Mix_GetMusicType(music) != MUS_MP3);
  424. #endif
  425. }
  426. bool MusicEntry::play()
  427. {
  428. if (!(loop--) && music) //already played once - return
  429. return false;
  430. if (!setName.empty())
  431. {
  432. auto set = owner->musicsSet[setName];
  433. size_t entryID = rand() % set.size();
  434. auto iterator = set.begin();
  435. std::advance(iterator, entryID);
  436. load(iterator->second);
  437. }
  438. tlog5<<"Playing music file "<<currentName<<"\n";
  439. if(Mix_PlayMusic(music, 1) == -1)
  440. {
  441. tlog1 << "Unable to play music (" << Mix_GetError() << ")" << std::endl;
  442. return false;
  443. }
  444. return true;
  445. }
  446. bool MusicEntry::stop(int fade_ms)
  447. {
  448. if (Mix_PlayingMusic())
  449. {
  450. tlog5<<"Stoping music file "<<currentName<<"\n";
  451. loop = 0;
  452. Mix_FadeOutMusic(fade_ms);
  453. return true;
  454. }
  455. return false;
  456. }
  457. bool MusicEntry::isSet(std::string set)
  458. {
  459. return !setName.empty() && set == setName;
  460. }
  461. bool MusicEntry::isTrack(std::string track)
  462. {
  463. return setName.empty() && track == currentName;
  464. }