|
| 1 | +package component |
| 2 | + |
| 3 | +import ( |
| 4 | + "github.com/gotracker/gomixing/panning" |
| 5 | + |
| 6 | + "github.com/gotracker/voice" |
| 7 | + "github.com/gotracker/voice/envelope" |
| 8 | +) |
| 9 | + |
| 10 | +// PanEnvelope is a spatial modulation envelope |
| 11 | +type PanEnvelope struct { |
| 12 | + enabled bool |
| 13 | + state envelope.State |
| 14 | + pan panning.Position |
| 15 | + keyOn bool |
| 16 | + prevKeyOn bool |
| 17 | +} |
| 18 | + |
| 19 | +// Reset resets the state to defaults based on the envelope provided |
| 20 | +func (e *PanEnvelope) Reset(env *envelope.Envelope) { |
| 21 | + e.state.Reset(env) |
| 22 | + e.keyOn = false |
| 23 | + e.prevKeyOn = false |
| 24 | + e.update() |
| 25 | +} |
| 26 | + |
| 27 | +// SetEnabled sets the enabled flag for the envelope |
| 28 | +func (e *PanEnvelope) SetEnabled(enabled bool) { |
| 29 | + e.enabled = enabled |
| 30 | +} |
| 31 | + |
| 32 | +// IsEnabled returns the enabled flag for the envelope |
| 33 | +func (e *PanEnvelope) IsEnabled() bool { |
| 34 | + return e.enabled |
| 35 | +} |
| 36 | + |
| 37 | +// GetCurrentValue returns the current cached envelope value |
| 38 | +func (e *PanEnvelope) GetCurrentValue() panning.Position { |
| 39 | + return e.pan |
| 40 | +} |
| 41 | + |
| 42 | +// SetEnvelopePosition sets the current position in the envelope |
| 43 | +func (e *PanEnvelope) SetEnvelopePosition(pos int) voice.Callback { |
| 44 | + keyOn := e.keyOn |
| 45 | + prevKeyOn := e.prevKeyOn |
| 46 | + env := e.state.Envelope() |
| 47 | + e.state.Reset(env) |
| 48 | + // TODO: this is gross, but currently the most optimal way to find the correct position |
| 49 | + for i := 0; i < pos; i++ { |
| 50 | + if doneCB := e.Advance(keyOn, prevKeyOn); doneCB != nil { |
| 51 | + return doneCB |
| 52 | + } |
| 53 | + } |
| 54 | + return nil |
| 55 | +} |
| 56 | + |
| 57 | +// Advance advances the envelope state 1 tick and calculates the current envelope value |
| 58 | +func (e *PanEnvelope) Advance(keyOn bool, prevKeyOn bool) voice.Callback { |
| 59 | + e.keyOn = keyOn |
| 60 | + e.prevKeyOn = prevKeyOn |
| 61 | + var doneCB voice.Callback |
| 62 | + if done := e.state.Advance(e.keyOn, e.prevKeyOn); done { |
| 63 | + doneCB = e.state.Envelope().OnFinished |
| 64 | + } |
| 65 | + e.update() |
| 66 | + return doneCB |
| 67 | +} |
| 68 | + |
| 69 | +func (e *PanEnvelope) update() { |
| 70 | + cur, next, t := e.state.GetCurrentValue(e.keyOn) |
| 71 | + |
| 72 | + y0 := panning.CenterAhead |
| 73 | + if cur != nil { |
| 74 | + cur.Value(&y0) |
| 75 | + } |
| 76 | + |
| 77 | + y1 := panning.CenterAhead |
| 78 | + if next != nil { |
| 79 | + next.Value(&y1) |
| 80 | + } |
| 81 | + |
| 82 | + // TODO: perform an angular interpolation instead of a linear one. |
| 83 | + e.pan.Angle = y0.Angle + t*(y1.Angle-y0.Angle) |
| 84 | + e.pan.Distance = y0.Distance + t*(y1.Distance-y0.Distance) |
| 85 | +} |
0 commit comments