listener.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. // Copyright 2016 The G3N Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package audio
  5. import (
  6. "github.com/g3n/engine/audio/al"
  7. "github.com/g3n/engine/core"
  8. "github.com/g3n/engine/gls"
  9. "github.com/g3n/engine/math32"
  10. )
  11. // Listener is an audio listener positioned in space
  12. type Listener struct {
  13. core.Node
  14. }
  15. // NewListener returns a pointer to a new Listener object.
  16. func NewListener() *Listener {
  17. l := new(Listener)
  18. l.Node.Init()
  19. return l
  20. }
  21. // SetVelocity sets the velocity of the listener with x, y, z components
  22. func (l *Listener) SetVelocity(vx, vy, vz float32) {
  23. al.Listener3f(al.Velocity, vx, vy, vz)
  24. }
  25. // SetVelocityVec sets the velocity of the listener with a vector
  26. func (l *Listener) SetVelocityVec(v *math32.Vector3) {
  27. al.Listener3f(al.Velocity, v.X, v.Y, v.Z)
  28. }
  29. // Velocity returns the velocity of the listener as x, y, z components
  30. func (l *Listener) Velocity() (float32, float32, float32) {
  31. return al.GetListener3f(al.Velocity)
  32. }
  33. // VelocityVec returns the velocity of the listener as a vector
  34. func (l *Listener) VelocityVec() math32.Vector3 {
  35. vx, vy, vz := al.GetListener3f(al.Velocity)
  36. return math32.Vector3{vx, vy, vz}
  37. }
  38. // SetGain sets the gain of the listener
  39. func (l *Listener) SetGain(gain float32) {
  40. al.Listenerf(al.Gain, gain)
  41. }
  42. // Gain returns the gain of the listener
  43. func (l *Listener) Gain() float32 {
  44. return al.GetListenerf(al.Gain)
  45. }
  46. // Render is called by the renderer at each frame
  47. // Updates the OpenAL position and orientation of this listener
  48. func (l *Listener) Render(gl *gls.GLS) {
  49. // Sets the listener source world position
  50. var wpos math32.Vector3
  51. l.WorldPosition(&wpos)
  52. al.Listener3f(al.Position, wpos.X, wpos.Y, wpos.Z)
  53. // Get listener current world direction
  54. var vdir math32.Vector3
  55. l.WorldDirection(&vdir)
  56. // Assumes initial UP vector and recalculates current up vector
  57. vup := math32.Vector3{0, 1, 0}
  58. var vright math32.Vector3
  59. vright.CrossVectors(&vdir, &vup)
  60. vup.CrossVectors(&vright, &vdir)
  61. // Sets the listener orientation
  62. orientation := []float32{vdir.X, vdir.Y, vdir.Z, vup.X, vup.Y, vup.Z}
  63. al.Listenerfv(al.Orientation, orientation)
  64. }