;nyquist plug-in
;version 1
;type generate
;name "SQ1"
;action "Executing SQ1 sequence..."
;info "SQ1 Sequence by Steven Jones pluto@swbell.net  GNU 2004"
;control center "center" real "Hz" 440 0 10000
;control detune "detune" real "" 1.01 0.25 4.00
;control wave "wave" int "0-sine 1-tri 2-square 3-saw" 1 0 3
;control attack "attack" float "sec" 1.0 0.0 10.0
;control sustain "sustain" float "sec" 1.0 0.0 10.0
;control decay "decay" float "sec" 1.0 0.0 10.0
;control f1 "lfo 1 frq" float "hz" 1.0 0.01 10
;control a1 "lfo 1 amp" float "hz" 220 0 1760
;control f2 "lfo 2 frq" float "hz" 2.0 0.01 10
;control a2 "lfo 2 amp" float "hz" 330 0 1760
;control f3 "lfo 3 frq" float "hz" 4.0 0.01 10
;control a3 "lfo 3 amp" float "hz" 55 0 1760

;; SQ1 is an algorithmic "sequencer". Complex pitch sequences are generated by
;; using three square wave LFOs to modulate two FM oscillators. The
;; oscillators may be detuned relative to each other and output one of 4
;; wave-shapes. There is also an overall amplitude envelope. Note the wave
;; tables are exact, IE not band limited, so aliasing will occur at sufficiently
;; high frequencies.


(setq *square-table* (list (pwl 0 1 0.5 1 0.5 -1 1 -1 1)(hz-to-step 1) t))

(defun sq1:lfo (frq amp dur)
  (scale amp (lfo frq dur *square-table*)))

(defun sq1:modulator (f1 a1 f2 a2 f3 a3 dur)
  (sum (sq1:lfo f1 a1 dur)
       (sq1:lfo f2 a2 dur)
       (sq1:lfo f3 a3 dur)))

(defun sq1:env (a s d)
  (pwl a 1 (+ a s) 1 (+ a s d)))

(defun sq1:synth (center wave am fm detune)
  (let ((center2 (* center detune))
	(wtab (cond ((= wave 0) *sine-table*)
		    ((= wave 1) *tri-table*)
		    ((= wave 2) *square-table*)
		    (t *saw-table*))))
    (mult (sim (fmosc (hz-to-step center) fm wtab)
	       (fmosc (hz-to-step center2) fm wtab))
	  am)))



(setq dur (+ attack sustain decay))    
(setq modsig (sq1:modulator f1 a1 f2 a2 f3 a3 dur))
(setq envsig (sq1:env attack sustain decay))
(setq peakval (peak   (sq1:synth center wave envsig modsig detune) ny:all))
(scale (/ 1.0 peakval)(sq1:synth center wave envsig modsig detune))


