s.boot;

MIDIClient.init;
MIDIIn.connectAll;
MIDIClient.sources.do;

(
SynthDef(\rhubarb, {
    |freq = 440, gate = 1, cutoff = 1e4, rq = 0.3, amp = 0.05, modDepth = 0.3, detune = 0|
    var env, osc1, osc2, filt1, filt2, lfo, sig, sig1, sig2;

	osc1 = LFTri.ar(freq + detune);
	osc2 = Pulse.ar(freq + detune);

    lfo = LFNoise2.kr(20).range(1 - modDepth, 1 + modDepth);

	filt1 = SVF.ar(osc1, cutoff * lfo, rq);
    filt2 = RLPF.ar(osc2, cutoff * lfo, rq);

    env = EnvGen.kr(Env.adsr(0, 0.3, 0.3, 0.1), gate, doneAction: 2);

	sig1 = Pan2.ar(filt1 * amp * env, -0.3);
    sig2 = Pan2.ar(filt2 * amp * env, 0.3);

	sig = sig1 + sig2;

    Out.ar(0, sig);
}).add;
)




(
// MIDI
// EMF: one major issue here is that ~notes is never actually initialized as an array, so it's nil. when you try to store a Synth at index nn, SC throws an error, because you can't put an item into nil. So, we first initialize ~notes as an array of size 128. After I add this line, your polyphonic MIDI code seems to work fine (no stuck notes)

~notes = Array.newClear(128);

MIDIdef.noteOn(\noteOnTest, {
	arg vel, nn, chan, src;
	// [vel, nn].postln;

	if (chan == 0, {
		~notes[nn] = Synth.new(
			\rhubarb,
			[
				\freq, nn.midicps,
				\amp, vel.linexp(1,127,0.01,0.3),
				\gate, 1,
				\detune, 0,
				\cutoff, 400,
				\rq, 0.5,
			]
		);
	});
});

MIDIdef.noteOff(\noteOffTest, {
	arg vel, nn, chan;
	// [vel, nn].postln;

	if (chan == 0, {
		~notes[nn].set(\gate, 0);
		~notes[nn] = nil;
	});
});
)









