Simulant  21.12-194
A portable game engine for Windows, OSX, Linux, Dreamcast, and PSP
playing_sound.h
1 #pragma once
2 
3 #include <cstdint>
4 #include <vector>
5 #include <memory>
6 
7 #include "../generic/managed.h"
8 #include "../generic/range_value.h"
9 
10 #include "../math/vec3.h"
11 
12 namespace smlt {
13 
14 class Sound;
15 class AudioSource;
16 
17 typedef uint32_t AudioBufferID;
18 typedef uint32_t AudioSourceID;
19 
20 typedef std::function<int32_t (AudioBufferID)> StreamFunc;
21 
22 typedef std::size_t PlayingSoundID;
23 
24 enum AudioRepeat {
25  AUDIO_REPEAT_NONE,
26  AUDIO_REPEAT_FOREVER
27 };
28 
29 enum DistanceModel {
30  DISTANCE_MODEL_POSITIONAL,
31  DISTANCE_MODEL_AMBIENT,
32  DISTANCE_MODEL_DEFAULT = DISTANCE_MODEL_POSITIONAL
33 };
34 
36  public RefCounted<PlayingSound> {
37 
38  friend class AudioSource;
39 
40 private:
41  static PlayingSoundID counter_;
42 
43  PlayingSoundID id_;
44 
45  AudioSource& parent_;
46 
47  AudioSourceID source_;
48  std::vector<AudioBufferID> buffers_;
49  std::weak_ptr<Sound> sound_;
50  StreamFunc stream_func_;
51 
52  AudioRepeat loop_stream_;
53  bool is_dead_;
54 
55  /* This is used to calculate the velocity */
56  smlt::Vec3 previous_position_;
57  bool first_update_ = true;
58 
59  void start();
60  void do_stop();
61 
62 public:
63  PlayingSound(AudioSource& parent, std::weak_ptr<Sound> sound, AudioRepeat loop_stream, DistanceModel model=DISTANCE_MODEL_POSITIONAL);
64  virtual ~PlayingSound();
65 
66  PlayingSoundID id() const {
67  return id_;
68  }
69 
70  void update(float dt);
71  void stop();
72 
73  bool is_playing() const;
74 
75  /* Set the stream function for filling buffers. A -1 return
76  * means the sound has been destroyed */
77  void set_stream_func(StreamFunc func) { stream_func_ = func; }
78 
79  bool is_dead() const { return is_dead_; }
80 
81  void set_gain(RangeValue<0, 1> gain);
82  void set_pitch(RangeValue<0, 1> pitch);
83  void set_reference_distance(float dist);
84 };
85 
87  friend class AudioSource;
88 
89 private:
90  std::weak_ptr<PlayingSound> ptr_;
91 
92  PlayingSoundPtr(PlayingSound::ptr ptr):
93  ptr_(ptr) {}
94 
95 public:
96  PlayingSoundPtr() = default;
97  PlayingSoundPtr(const PlayingSoundPtr& rhs) = default;
98 
99  PlayingSoundPtr& operator=(const PlayingSoundPtr& rhs) {
100  ptr_ = rhs.ptr_;
101  return *this;
102  }
103 
104  PlayingSound* operator->() const {
105  auto lk = ptr_.lock();
106  if(lk) {
107  return lk.get();
108  } else {
109  return nullptr;
110  }
111  }
112 
113  bool is_valid() const {
114  return bool(ptr_.lock());
115  }
116 
117  operator bool() const {
118  return is_valid();
119  }
120 };
121 
122 }
smlt::Vec3
Definition: vec3.h:23
smlt::AudioSource
Definition: sound.h:103
smlt::RefCounted
Definition: managed.h:65
smlt
Definition: animation.cpp:25
smlt::PlayingSound
Definition: playing_sound.h:36
smlt::RangeValue
Definition: range_value.h:24
smlt::PlayingSoundPtr
Definition: playing_sound.h:86