CMusicHandler.cpp 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  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 "CCreatureHandler.h"
  10. #include "CSpellHandler.h"
  11. #include "../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. CGI->audioh->musicFinishedCallback();
  26. }
  27. void CSoundHandler::initSounds()
  28. {
  29. // Map sound names
  30. #define VCMI_SOUND_NAME(x) ( soundBase::x,
  31. #define VCMI_SOUND_FILE(y) #y )
  32. sounds = boost::assign::list_of<boost::bimap<soundBase::soundID, std::string>::relation>
  33. VCMI_SOUND_LIST;
  34. #undef VCMI_SOUND_NAME
  35. #undef VCMI_SOUND_FILE
  36. // Vectors for helper(s)
  37. pickupSounds += soundBase::pickup01, soundBase::pickup02, soundBase::pickup03,
  38. soundBase::pickup04, soundBase::pickup05, soundBase::pickup06, soundBase::pickup07;
  39. horseSounds += // must be the same order as terrains (see EtrrainType);
  40. soundBase::horseDirt, soundBase::horseSand, soundBase::horseGrass,
  41. soundBase::horseSnow, soundBase::horseSwamp, soundBase::horseRough,
  42. soundBase::horseSubterranean, soundBase::horseLava,
  43. soundBase::horseWater, soundBase::horseRock;
  44. // Load sounds
  45. sndh = new CSndHandler(std::string(DATA_DIR "Data" PATHSEPARATOR "Heroes3.snd"));
  46. }
  47. void CSoundHandler::freeSounds()
  48. {
  49. Mix_HaltChannel(-1);
  50. delete sndh;
  51. std::map<soundBase::soundID, Mix_Chunk *>::iterator it;
  52. for (it=soundChunks.begin(); it != soundChunks.end(); it++) {
  53. if (it->second)
  54. Mix_FreeChunk(it->second);
  55. }
  56. }
  57. // Allocate an SDL chunk and cache it.
  58. Mix_Chunk *CSoundHandler::GetSoundChunk(soundBase::soundID soundID)
  59. {
  60. // Find its name
  61. boost::bimap<soundBase::soundID, std::string>::left_iterator it;
  62. it = sounds.left.find(soundID);
  63. if (it == sounds.left.end())
  64. return NULL;
  65. // Load and insert
  66. int size;
  67. const char *data = sndh->extract(it->second, size);
  68. if (!data)
  69. return NULL;
  70. SDL_RWops *ops = SDL_RWFromConstMem(data, size);
  71. Mix_Chunk *chunk;
  72. chunk = Mix_LoadWAV_RW(ops, 1); // will free ops
  73. if (!chunk) {
  74. tlog1 << "Unable to mix sound" << it->second << "(" << Mix_GetError() << ")" << std::endl;
  75. return NULL;
  76. }
  77. soundChunks.insert(std::pair<soundBase::soundID, Mix_Chunk *>(soundID, chunk));
  78. return chunk;
  79. }
  80. // Get a soundID given a filename
  81. soundBase::soundID CSoundHandler::getSoundID(std::string &fileName)
  82. {
  83. boost::bimap<soundBase::soundID, std::string>::right_iterator it;
  84. it = sounds.right.find(fileName);
  85. if (it == sounds.right.end())
  86. return soundBase::invalid;
  87. else
  88. return it->second;
  89. }
  90. void CSoundHandler::initCreaturesSounds(std::vector<CCreature> &creatures)
  91. {
  92. tlog5 << "\t\tReading config/cr_sounds.txt" << std::endl;
  93. std::ifstream ifs("config/cr_sounds.txt");
  94. std::string line;
  95. while(getline(ifs, line))
  96. {
  97. std::string cname="", attack="", defend="", killed="", move="",
  98. shoot="", wince="", ext1="", ext2="";
  99. std::stringstream str(line);
  100. str >> cname >> attack >> defend >> killed >> move >> shoot >> wince >> ext1 >> ext2;
  101. if (cname[0] == '#')
  102. // That's a comment. Discard.
  103. continue;
  104. if (str.good() || (str.eof() && wince != ""))
  105. {
  106. int id = CGI->creh->nameToID[cname];
  107. CCreature &c = creatures[id];
  108. if (c.sounds.killed != soundBase::invalid)
  109. tlog1 << "Creature << " << cname << " already has sounds" << std::endl;
  110. c.sounds.attack = getSoundID(attack);
  111. c.sounds.defend = getSoundID(defend);
  112. c.sounds.killed = getSoundID(killed);
  113. c.sounds.move = getSoundID(move);
  114. c.sounds.shoot = getSoundID(shoot);
  115. c.sounds.wince = getSoundID(wince);
  116. c.sounds.ext1 = getSoundID(ext1);
  117. c.sounds.ext2 = getSoundID(ext2);
  118. // Special creatures
  119. if (c.idNumber == 55 || // Archdevil
  120. c.idNumber == 62 || // Vampire
  121. c.idNumber == 62) // Vampire Lord
  122. {
  123. c.sounds.startMoving = c.sounds.ext1;
  124. c.sounds.endMoving = c.sounds.ext2;
  125. }
  126. }
  127. }
  128. ifs.close();
  129. ifs.clear();
  130. // Find creatures without sounds
  131. for(unsigned int i=0;i<creatures.size();i++)
  132. {
  133. // Note: this will exclude war machines, but it's better
  134. // than nothing.
  135. if (vstd::contains(CGI->creh->notUsedMonsters, i))
  136. continue;
  137. CCreature &c = creatures[i];
  138. if (c.sounds.killed == soundBase::invalid)
  139. tlog1 << "creature " << c.idNumber << " doesn't have sounds" << std::endl;
  140. }
  141. }
  142. void CSoundHandler::initSpellsSounds(std::vector<CSpell> &spells)
  143. {
  144. tlog5 << "\t\tReading config/sp_sounds.txt" << std::endl;
  145. std::ifstream ifs("config/sp_sounds.txt");
  146. std::string line;
  147. while(getline(ifs, line))
  148. {
  149. int spellid;
  150. std::string soundfile="";
  151. std::stringstream str(line);
  152. str >> spellid >> soundfile;
  153. if (str.good() || (str.eof() && soundfile != ""))
  154. {
  155. CSpell &s = CGI->spellh->spells[spellid];
  156. if (s.soundID != soundBase::invalid)
  157. tlog1 << "Spell << " << spellid << " already has a sound" << std::endl;
  158. s.soundID = getSoundID(soundfile);
  159. }
  160. }
  161. ifs.close();
  162. ifs.clear();
  163. }
  164. // Plays a sound, and return its channel so we can fade it out later
  165. int CSoundHandler::playSound(soundBase::soundID soundID, int repeats)
  166. {
  167. int channel;
  168. Mix_Chunk *chunk;
  169. if (!sndh)
  170. return -1;
  171. chunk = GetSoundChunk(soundID);
  172. if (chunk)
  173. {
  174. channel = Mix_PlayChannel(-1, chunk, repeats);
  175. if (channel == -1)
  176. tlog1 << "Unable to play sound file " << soundID << std::endl;
  177. } else {
  178. channel = -1;
  179. }
  180. return channel;
  181. }
  182. // Helper. Randomly select a sound from an array and play it
  183. int CSoundHandler::playSoundFromSet(std::vector<soundBase::soundID> &sound_vec)
  184. {
  185. return playSound(sound_vec[rand() % sound_vec.size()]);
  186. }
  187. void CSoundHandler::stopSound( int handler )
  188. {
  189. if (handler != -1)
  190. Mix_HaltChannel(handler);
  191. }
  192. // Sets the sound volume, from 0 (mute) to 100
  193. void CSoundHandler::setSoundVolume(unsigned int percent)
  194. {
  195. if (percent > 100)
  196. percent = 100;
  197. volume = percent;
  198. Mix_Volume(-1, (MIX_MAX_VOLUME * percent)/100);
  199. }
  200. // Returns the current sound volume, from 0 (mute) to 100
  201. unsigned int CSoundHandler::getSoundVolume()
  202. {
  203. return volume;
  204. }
  205. void CMusicHandler::initMusics()
  206. {
  207. // Map music IDs
  208. #define VCMI_MUSIC_ID(x) ( musicBase::x ,
  209. #define VCMI_MUSIC_FILE(y) y )
  210. musics = map_list_of
  211. VCMI_MUSIC_LIST;
  212. #undef VCMI_MUSIC_NAME
  213. #undef VCMI_MUSIC_FILE
  214. Mix_HookMusicFinished(musicFinishedCallbackC);
  215. // Vector for helper
  216. battleMusics += musicBase::combat1, musicBase::combat2,
  217. musicBase::combat3, musicBase::combat4;
  218. }
  219. void CMusicHandler::freeMusics()
  220. {
  221. Mix_HookMusicFinished(NULL);
  222. musicMutex.lock();
  223. if (currentMusic) {
  224. Mix_HaltMusic();
  225. Mix_FreeMusic(currentMusic);
  226. }
  227. if (nextMusic)
  228. Mix_FreeMusic(nextMusic);
  229. musicMutex.unlock();
  230. }
  231. // Plays a music
  232. // loop: -1 always repeats, 0=do not play, 1+=number of loops
  233. void CMusicHandler::playMusic(musicBase::musicID musicID, int loop)
  234. {
  235. std::string filename = DATA_DIR "Mp3" PATHSEPARATOR;
  236. filename += musics[musicID];
  237. musicMutex.lock();
  238. if (nextMusic) {
  239. // There's already a music queued, so remove it
  240. Mix_FreeMusic(nextMusic);
  241. nextMusic = NULL;
  242. }
  243. if (currentMusic) {
  244. // A music is already playing. Stop it and the callback will
  245. // start the new one
  246. nextMusic = Mix_LoadMUS(filename.c_str());
  247. nextMusicLoop = loop;
  248. Mix_FadeOutMusic(1000);
  249. } else {
  250. currentMusic = Mix_LoadMUS(filename.c_str());
  251. if (Mix_PlayMusic(currentMusic, loop) == -1)
  252. tlog1 << "Unable to play sound file " << musicID << "(" << Mix_GetError() << ")" << std::endl;
  253. }
  254. musicMutex.unlock();
  255. }
  256. // Helper. Randomly select a music from an array and play it
  257. void CMusicHandler::playMusicFromSet(std::vector<musicBase::musicID> &music_vec, int loop)
  258. {
  259. playMusic(music_vec[rand() % music_vec.size()], loop);
  260. }
  261. // Stop and free the current music
  262. void CMusicHandler::stopMusic(int fade_ms)
  263. {
  264. musicMutex.lock();
  265. if (currentMusic) {
  266. Mix_FadeOutMusic(fade_ms);
  267. }
  268. musicMutex.unlock();
  269. }
  270. // Sets the music volume, from 0 (mute) to 100
  271. void CMusicHandler::setMusicVolume(unsigned int percent)
  272. {
  273. if (percent > 100)
  274. percent = 100;
  275. volume = percent;
  276. Mix_VolumeMusic((MIX_MAX_VOLUME * percent)/100);
  277. }
  278. // Returns the current music volume, from 0 (mute) to 100
  279. unsigned int CMusicHandler::getMusicVolume()
  280. {
  281. return volume;
  282. }
  283. // Called by SDL when a music finished.
  284. void CMusicHandler::musicFinishedCallback(void)
  285. {
  286. musicMutex.lock();
  287. if (currentMusic) {
  288. Mix_FreeMusic(currentMusic);
  289. currentMusic = NULL;
  290. }
  291. if (nextMusic) {
  292. currentMusic = nextMusic;
  293. nextMusic = NULL;
  294. if (Mix_PlayMusic(currentMusic, nextMusicLoop) == -1)
  295. tlog1 << "Unable to play music (" << Mix_GetError() << ")" << std::endl;
  296. }
  297. musicMutex.unlock();
  298. }
  299. void CAudioHandler::initAudio(unsigned int volume)
  300. {
  301. if (audioInitialized)
  302. return;
  303. if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 1024)==-1)
  304. {
  305. tlog1 << "Mix_OpenAudio error: %s!!!" << Mix_GetError() << std::endl;
  306. return;
  307. }
  308. audioInitialized = true;
  309. initSounds();
  310. setSoundVolume(volume);
  311. initMusics();
  312. setMusicVolume(volume);
  313. }
  314. CAudioHandler::~CAudioHandler()
  315. {
  316. if (!audioInitialized)
  317. return;
  318. freeSounds();
  319. freeMusics();
  320. Mix_CloseAudio();
  321. }