CMusicHandler.cpp 12 KB

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