CMusicHandler.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. #include "../stdafx.h"
  2. #include <sstream>
  3. #include <boost/assign/std/vector.hpp>
  4. #include <boost/assign/list_of.hpp>
  5. #include <boost/bimap.hpp>
  6. #include <SDL_mixer.h>
  7. #include "CSndHandler.h"
  8. #include "CMusicHandler.h"
  9. #include "../lib/CCreatureHandler.h"
  10. #include "../lib/CSpellHandler.h"
  11. #include "../client/CGameInfo.h"
  12. /*
  13. * CMusicHandler.cpp, part of VCMI engine
  14. *
  15. * Authors: listed in file AUTHORS in main folder
  16. *
  17. * License: GNU General Public License v2.0 or later
  18. * Full text of license available in license.txt file, in main folder
  19. *
  20. */
  21. using namespace boost::assign;
  22. static boost::bimap<soundBase::soundID, std::string> sounds;
  23. // Not pretty, but there's only one music handler object in the game.
  24. static void musicFinishedCallbackC(void) {
  25. CCS->musich->musicFinishedCallback();
  26. }
  27. void CAudioBase::init()
  28. {
  29. if (initialized)
  30. return;
  31. if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 1024)==-1)
  32. {
  33. tlog1 << "Mix_OpenAudio error: " << Mix_GetError() << std::endl;
  34. return;
  35. }
  36. initialized = true;
  37. }
  38. void CAudioBase::release()
  39. {
  40. if (initialized) {
  41. Mix_CloseAudio();
  42. initialized = false;
  43. }
  44. }
  45. void CAudioBase::setVolume(unsigned int percent)
  46. {
  47. if (percent > 100)
  48. percent = 100;
  49. volume = percent;
  50. }
  51. CSoundHandler::CSoundHandler(): sndh(NULL)
  52. {
  53. // Map sound names
  54. #define VCMI_SOUND_NAME(x) ( soundBase::x,
  55. #define VCMI_SOUND_FILE(y) #y )
  56. sounds = boost::assign::list_of<boost::bimap<soundBase::soundID, std::string>::relation>
  57. VCMI_SOUND_LIST;
  58. #undef VCMI_SOUND_NAME
  59. #undef VCMI_SOUND_FILE
  60. // Vectors for helper(s)
  61. pickupSounds += soundBase::pickup01, soundBase::pickup02, soundBase::pickup03,
  62. soundBase::pickup04, soundBase::pickup05, soundBase::pickup06, soundBase::pickup07;
  63. horseSounds += // must be the same order as terrains (see EtrrainType);
  64. soundBase::horseDirt, soundBase::horseSand, soundBase::horseGrass,
  65. soundBase::horseSnow, soundBase::horseSwamp, soundBase::horseRough,
  66. soundBase::horseSubterranean, soundBase::horseLava,
  67. soundBase::horseWater, soundBase::horseRock;
  68. };
  69. void CSoundHandler::init()
  70. {
  71. CAudioBase::init();
  72. if (initialized)
  73. // Load sounds
  74. sndh = new CSndHandler(std::string(DATA_DIR "/Data/Heroes3.snd"));
  75. }
  76. void CSoundHandler::release()
  77. {
  78. if (initialized) {
  79. Mix_HaltChannel(-1);
  80. delete sndh;
  81. std::map<soundBase::soundID, Mix_Chunk *>::iterator it;
  82. for (it=soundChunks.begin(); it != soundChunks.end(); it++) {
  83. if (it->second)
  84. Mix_FreeChunk(it->second);
  85. }
  86. }
  87. CAudioBase::release();
  88. }
  89. // Allocate an SDL chunk and cache it.
  90. Mix_Chunk *CSoundHandler::GetSoundChunk(soundBase::soundID soundID)
  91. {
  92. // Find its name
  93. boost::bimap<soundBase::soundID, std::string>::left_iterator it;
  94. it = sounds.left.find(soundID);
  95. if (it == sounds.left.end())
  96. return NULL;
  97. // Load and insert
  98. int size;
  99. const char *data = sndh->extract(it->second, size);
  100. if (!data)
  101. return NULL;
  102. SDL_RWops *ops = SDL_RWFromConstMem(data, size);
  103. Mix_Chunk *chunk;
  104. chunk = Mix_LoadWAV_RW(ops, 1); // will free ops
  105. if (!chunk) {
  106. tlog1 << "Unable to mix sound" << it->second << "(" << Mix_GetError() << ")" << std::endl;
  107. return NULL;
  108. }
  109. soundChunks.insert(std::pair<soundBase::soundID, Mix_Chunk *>(soundID, chunk));
  110. return chunk;
  111. }
  112. // Get a soundID given a filename
  113. soundBase::soundID CSoundHandler::getSoundID(std::string &fileName)
  114. {
  115. boost::bimap<soundBase::soundID, std::string>::right_iterator it;
  116. it = sounds.right.find(fileName);
  117. if (it == sounds.right.end())
  118. return soundBase::invalid;
  119. else
  120. return it->second;
  121. }
  122. void CSoundHandler::initCreaturesSounds(const std::vector<ConstTransitivePtr< CCreature> > &creatures)
  123. {
  124. tlog5 << "\t\tReading config/cr_sounds.txt" << std::endl;
  125. std::ifstream ifs(DATA_DIR "/config/cr_sounds.txt");
  126. std::string line;
  127. CBattleSounds.resize(creatures.size());
  128. while(getline(ifs, line))
  129. {
  130. std::string cname="", attack="", defend="", killed="", move="",
  131. shoot="", wince="", ext1="", ext2="";
  132. std::istringstream str(line);
  133. str >> cname >> attack >> defend >> killed >> move >> shoot >> wince >> ext1 >> ext2;
  134. if (!line.size() || cname[0] == '#')
  135. // That's a comment. Discard.
  136. continue;
  137. if (str.good() || (str.eof() && wince != ""))
  138. {
  139. int id = -1;
  140. bmap<std::string,int>::const_iterator i = CGI->creh->nameToID.find(cname);
  141. if(i != CGI->creh->nameToID.end())
  142. id = i->second;
  143. else
  144. {
  145. tlog1 << "Sound info for an unknown creature: " << cname << std::endl;
  146. continue;
  147. }
  148. if (CBattleSounds[id].killed != soundBase::invalid)
  149. tlog1 << "Creature << " << cname << " already has sounds" << std::endl;
  150. CBattleSounds[id].attack = getSoundID(attack);
  151. CBattleSounds[id].defend = getSoundID(defend);
  152. CBattleSounds[id].killed = getSoundID(killed);
  153. CBattleSounds[id].move = getSoundID(move);
  154. CBattleSounds[id].shoot = getSoundID(shoot);
  155. CBattleSounds[id].wince = getSoundID(wince);
  156. CBattleSounds[id].ext1 = getSoundID(ext1);
  157. CBattleSounds[id].ext2 = getSoundID(ext2);
  158. // Special creatures
  159. if (id == 55 || // Archdevil
  160. id == 62 || // Vampire
  161. id == 62) // Vampire Lord
  162. {
  163. CBattleSounds[id].startMoving = CBattleSounds[id].ext1;
  164. CBattleSounds[id].endMoving = CBattleSounds[id].ext2;
  165. }
  166. }
  167. }
  168. ifs.close();
  169. ifs.clear();
  170. //commented to avoid spurious warnings
  171. /*
  172. // Find creatures without sounds
  173. for(unsigned int i=0;i<creatures.size();i++)
  174. {
  175. // Note: this will exclude war machines, but it's better
  176. // than nothing.
  177. if (vstd::contains(CGI->creh->notUsedMonsters, i))
  178. continue;
  179. CCreature &c = creatures[i];
  180. if (c.sounds.killed == soundBase::invalid)
  181. tlog1 << "creature " << c.idNumber << " doesn't have sounds" << std::endl;
  182. }*/
  183. }
  184. void CSoundHandler::initSpellsSounds(const std::vector< ConstTransitivePtr<CSpell> > &spells)
  185. {
  186. tlog5 << "\t\tReading config/sp_sounds.txt" << std::endl;
  187. std::ifstream ifs(DATA_DIR "/config/sp_sounds.txt");
  188. std::string line;
  189. while(getline(ifs, line))
  190. {
  191. int spellid;
  192. std::string soundfile="";
  193. std::istringstream str(line);
  194. str >> spellid >> soundfile;
  195. if (str.good() || (str.eof() && soundfile != ""))
  196. {
  197. const CSpell *s = CGI->spellh->spells[spellid];
  198. if (vstd::contains(spellSounds, s))
  199. {
  200. tlog1 << "Spell << " << spellid << " already has a sound" << std::endl;
  201. }
  202. spellSounds[s] = getSoundID(soundfile);
  203. }
  204. }
  205. ifs.close();
  206. ifs.clear();
  207. }
  208. // Plays a sound, and return its channel so we can fade it out later
  209. int CSoundHandler::playSound(soundBase::soundID soundID, int repeats)
  210. {
  211. if (!initialized)
  212. return -1;
  213. int channel;
  214. Mix_Chunk *chunk = GetSoundChunk(soundID);
  215. if (chunk)
  216. {
  217. channel = Mix_PlayChannel(-1, chunk, repeats);
  218. if (channel == -1)
  219. tlog1 << "Unable to play sound file " << soundID << " , error " << Mix_GetError() << std::endl;
  220. } else {
  221. channel = -1;
  222. }
  223. return channel;
  224. }
  225. // Helper. Randomly select a sound from an array and play it
  226. int CSoundHandler::playSoundFromSet(std::vector<soundBase::soundID> &sound_vec)
  227. {
  228. return playSound(sound_vec[rand() % sound_vec.size()]);
  229. }
  230. void CSoundHandler::stopSound( int handler )
  231. {
  232. if (initialized && handler != -1)
  233. Mix_HaltChannel(handler);
  234. }
  235. // Sets the sound volume, from 0 (mute) to 100
  236. void CSoundHandler::setVolume(unsigned int percent)
  237. {
  238. CAudioBase::setVolume(percent);
  239. if (initialized)
  240. Mix_Volume(-1, (MIX_MAX_VOLUME * volume)/100);
  241. }
  242. CMusicHandler::CMusicHandler(): currentMusic(NULL), nextMusic(NULL)
  243. {
  244. // Map music IDs
  245. #define VCMI_MUSIC_ID(x) ( musicBase::x ,
  246. #define VCMI_MUSIC_FILE(y) y )
  247. musics = map_list_of
  248. VCMI_MUSIC_LIST;
  249. #undef VCMI_MUSIC_NAME
  250. #undef VCMI_MUSIC_FILE
  251. // Vectors for helper
  252. battleMusics += musicBase::combat1, musicBase::combat2,
  253. musicBase::combat3, musicBase::combat4;
  254. townMusics += musicBase::castleTown, musicBase::rampartTown,
  255. musicBase::towerTown, musicBase::infernoTown,
  256. musicBase::necroTown, musicBase::dungeonTown,
  257. musicBase::strongHoldTown, musicBase::fortressTown,
  258. musicBase::elemTown;
  259. }
  260. void CMusicHandler::init()
  261. {
  262. CAudioBase::init();
  263. if (initialized)
  264. Mix_HookMusicFinished(musicFinishedCallbackC);
  265. }
  266. void CMusicHandler::release()
  267. {
  268. if (initialized) {
  269. Mix_HookMusicFinished(NULL);
  270. musicMutex.lock();
  271. if (currentMusic)
  272. {
  273. Mix_HaltMusic();
  274. Mix_FreeMusic(currentMusic);
  275. }
  276. if (nextMusic)
  277. Mix_FreeMusic(nextMusic);
  278. musicMutex.unlock();
  279. }
  280. CAudioBase::release();
  281. }
  282. // Plays a music
  283. // loop: -1 always repeats, 0=do not play, 1+=number of loops
  284. void CMusicHandler::playMusic(musicBase::musicID musicID, int loop)
  285. {
  286. if (!initialized)
  287. return;
  288. std::string filename = DATA_DIR "/Mp3/";
  289. filename += musics[musicID];
  290. musicMutex.lock();
  291. if (nextMusic)
  292. {
  293. // There's already a music queued, so remove it
  294. Mix_FreeMusic(nextMusic);
  295. nextMusic = NULL;
  296. }
  297. if (currentMusic)
  298. {
  299. // A music is already playing. Stop it and the callback will
  300. // start the new one
  301. nextMusic = LoadMUS(filename.c_str());
  302. nextMusicLoop = loop;
  303. Mix_FadeOutMusic(1000);
  304. }
  305. else
  306. {
  307. currentMusic = LoadMUS(filename.c_str());
  308. PlayMusic(currentMusic,loop);
  309. }
  310. musicMutex.unlock();
  311. }
  312. // Helper. Randomly select a music from an array and play it
  313. void CMusicHandler::playMusicFromSet(std::vector<musicBase::musicID> &music_vec, int loop)
  314. {
  315. playMusic(music_vec[rand() % music_vec.size()], loop);
  316. }
  317. // Stop and free the current music
  318. void CMusicHandler::stopMusic(int fade_ms)
  319. {
  320. if (!initialized)
  321. return;
  322. musicMutex.lock();
  323. if (currentMusic)
  324. {
  325. Mix_FadeOutMusic(fade_ms);
  326. }
  327. musicMutex.unlock();
  328. }
  329. // Sets the music volume, from 0 (mute) to 100
  330. void CMusicHandler::setVolume(unsigned int percent)
  331. {
  332. CAudioBase::setVolume(percent);
  333. if (initialized)
  334. Mix_VolumeMusic((MIX_MAX_VOLUME * volume)/100);
  335. }
  336. // Called by SDL when a music finished.
  337. void CMusicHandler::musicFinishedCallback(void)
  338. {
  339. musicMutex.lock();
  340. if (currentMusic)
  341. {
  342. Mix_FreeMusic(currentMusic);
  343. currentMusic = NULL;
  344. }
  345. if (nextMusic)
  346. {
  347. currentMusic = nextMusic;
  348. nextMusic = NULL;
  349. PlayMusic(currentMusic,nextMusicLoop);
  350. }
  351. musicMutex.unlock();
  352. }
  353. Mix_Music * CMusicHandler::LoadMUS(const char *file)
  354. {
  355. Mix_Music *ret = Mix_LoadMUS(file);
  356. if(!ret) //load music and check for error
  357. tlog1 << "Unable to load music file (" << file <<"). Error: " << Mix_GetError() << std::endl;
  358. return ret;
  359. }
  360. int CMusicHandler::PlayMusic(Mix_Music *music, int loops)
  361. {
  362. int ret = Mix_PlayMusic(music, loops);
  363. if(ret == -1)
  364. tlog1 << "Unable to play music (" << Mix_GetError() << ")" << std::endl;
  365. return ret;
  366. }