sound_manager.cpp 2.18 KB
Newer Older
Florian Oetke's avatar
Florian Oetke committed
1
2
3
4
5
6
7
8
#include "sound_manager.hpp"

#include "audio_asset.hpp"

#include "../messages.hpp"

#include <mirrage/utils/random.hpp>

Florian Oetke's avatar
Florian Oetke committed
9
10
#include <context.hpp>

Florian Oetke's avatar
Florian Oetke committed
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
namespace phase_shifter::audio {

	struct Effect_file {
		std::unordered_map<std::string, std::vector<std::string>> effects;
	};
	sf2_structDef(Effect_file, effects);

	Sound_manager::Sound_manager(eam::audio&                    audio,
	                             mirrage::util::Message_bus&    bus,
	                             mirrage::asset::Asset_manager& assets)
	  : _audio(audio), _mailbox(bus), _assets(assets), _random_gen(mirrage::util::construct_random_engine())
	{
		_mailbox.subscribe_to([&](Play_sound_msg& e) { play_effect(e.id); });
	}

	void Sound_manager::load_effects_file(const mirrage::asset::AID& aid)
	{
		auto file = _assets.load<Effect_file>(aid, false);

		for(auto&& [id, paths] : file.get_blocking().effects) {
			for(auto&& path : paths)
				register_effect(Sound_effect_id(id), mirrage::asset::AID("audio"_strid, path));
		}
	}

	void Sound_manager::effect_volume(float v) { _effect_volume = v; }

	void Sound_manager::pause()
	{
		// TODO
	}
	void Sound_manager::resume()
	{
		// TODO
	}

	void Sound_manager::update(mirrage::util::Time dt) { _mailbox.update_subscriptions(); }

	void Sound_manager::register_effect(Sound_effect_id id, const mirrage::asset::AID& aid)
	{
		LOG(plog::info) << "Loading sound " << aid.str();
		auto effect = _assets.load<std::shared_ptr<eam::opus>>(aid).get_blocking();

		auto entry = _sound_effects.find(id);
		if(entry != _sound_effects.end())
			entry->second.raw_vector().emplace_back(std::move(effect));
		else {
			auto effects = Sound_effect_set();
			effects.raw_vector().emplace_back(std::move(effect));
			_sound_effects.emplace(id, std::move(effects));
		}
	}
	void Sound_manager::unregister_effect(Sound_effect_id id) { _sound_effects.erase(id); }
	void Sound_manager::play_effect(Sound_effect_id id)
	{
		auto effect = _sound_effects.find(id);
		if(effect != _sound_effects.end()) {
			auto ctx = _audio.generate_context(effect->second.get_random(_random_gen));
			ctx.get_object()->set_loops(0);
			ctx.get_object()->set_volume(_effect_volume * 100);
			ctx.play();
		}
	}

} // namespace phase_shifter::audio