1//************************************ bs::framework - Copyright 2018 Marko Pintera **************************************//
2//*********** Licensed under the MIT license. See LICENSE.md for full terms. This notice is not to be removed. ***********//
3#include "BsOAAudioListener.h"
4#include "BsOAAudio.h"
5#include "AL/al.h"
6
7namespace bs
8{
9 OAAudioListener::OAAudioListener()
10 {
11 gOAAudio()._registerListener(this);
12 rebuild();
13 }
14
15 OAAudioListener::~OAAudioListener()
16 {
17 gOAAudio()._unregisterListener(this);
18 }
19
20 void OAAudioListener::setTransform(const Transform& transform)
21 {
22 AudioListener::setTransform(transform);
23
24 std::array<float, 6> orientation = getOrientation();
25 auto& contexts = gOAAudio()._getContexts();
26
27 if (contexts.size() > 1) // If only one context is available it is guaranteed it is always active, so we can avoid setting it
28 {
29 auto context = gOAAudio()._getContext(this);
30 alcMakeContextCurrent(context);
31 }
32
33 updatePosition();
34 updateOrientation(orientation);
35 }
36
37 void OAAudioListener::setVelocity(const Vector3& velocity)
38 {
39 AudioListener::setVelocity(velocity);
40
41 auto& contexts = gOAAudio()._getContexts();
42 if (contexts.size() > 1)
43 {
44 auto context = gOAAudio()._getContext(this);
45 alcMakeContextCurrent(context);
46 }
47
48 updateVelocity();
49 }
50
51 void OAAudioListener::rebuild()
52 {
53 auto contexts = gOAAudio()._getContexts();
54
55 float globalVolume = gAudio().getVolume();
56 std::array<float, 6> orientation = getOrientation();
57
58 if (contexts.size() > 1)
59 {
60 auto context = gOAAudio()._getContext(this);
61 alcMakeContextCurrent(context);
62 }
63
64 updatePosition();
65 updateOrientation(orientation);
66 updateVelocity();
67 updateVolume(globalVolume);
68 }
69
70 std::array<float, 6> OAAudioListener::getOrientation() const
71 {
72 Vector3 direction = getTransform().getForward();
73 Vector3 up = getTransform().getUp();
74
75 return
76 {{
77 direction.x,
78 direction.y,
79 direction.z,
80 up.x,
81 up.y,
82 up.z
83 }};
84 }
85
86 void OAAudioListener::updatePosition()
87 {
88 Vector3 position = getTransform().getPosition();
89
90 alListener3f(AL_POSITION, position.x, position.y, position.z);
91 }
92
93 void OAAudioListener::updateOrientation(const std::array<float, 6>& orientation)
94 {
95 alListenerfv(AL_ORIENTATION, orientation.data());
96 }
97
98 void OAAudioListener::updateVelocity()
99 {
100 alListener3f(AL_VELOCITY, mVelocity.x, mVelocity.y, mVelocity.z);
101 }
102
103 void OAAudioListener::updateVolume(float volume)
104 {
105 alListenerf(AL_GAIN, volume);
106 }
107}