#!/usr/bin/env python

import sys
import math


from gameduino import Gameduino

class GameduinoSynth(Gameduino):
    def __init__(self, *args):
        Gameduino.__init__(self, *args)
        self.nv = 4
        self.g = []
        for i in range(self.nv):
            x = -1.5 + (3 * i / float(self.nv - 1))
            print i, x
            self.g.append(math.exp(-(x ** 2)))
        n = sum(self.g)
        self.g = [y/n for y in self.g]

    def partials(self, f0, spread, amps):
        ia = [(255. * a / sum(amps)) for a in amps]
        print '--->', sum(ia), ia
        for i in range(self.nv):
            half = -0.5 + (i / float(self.nv - 1))
            diverge = 1 + spread * half
            for j in range(len(amps)):
                gd.voice(i + j * self.nv, 0, int(f0 * (j + 1) * diverge), int(ia[j] * self.g[i]))
    
gd = GameduinoSynth(sys.argv[1], 115200)
gd.silence()
gd.putstr(0, "Hello world")

import pygtk
import gtk

def scale_set_default_values(scale):
    scale.set_update_policy(gtk.UPDATE_CONTINUOUS)
    scale.set_digits(2)
    scale.set_value_pos(gtk.POS_TOP)
    scale.set_draw_value(True)
    scale.set_inverted(True)

class MusicWidget:

    def update(self, widget):
        gd.partials(int(4 * self.f.get_value()),
                    self.spread.get_value(),
                    [p.get_value() for p in self.partials])

    def __init__(self):
        self.window = gtk.Window (gtk.WINDOW_TOPLEVEL)
        self.window.connect("destroy", gtk.main_quit)
        self.window.set_title("soundpicker")
        self.window.set_default_size(512, 512)

        box1 = gtk.HBox(False, 0)
        self.window.add(box1)

        adj1 = gtk.Adjustment(110.0, 0.0, 1001.0, 0.25, 1.0, 1.0)
        self.f = gtk.VScale(adj1)
        scale_set_default_values(self.f)
        self.f.connect("value-changed", self.update)
        box1.pack_start(self.f)

        adj1 = gtk.Adjustment(.07, 0.0, 1.0, 0.1, .1, .1)
        self.spread = gtk.VScale(adj1)
        scale_set_default_values(self.spread)
        self.spread.connect("value-changed", self.update)
        box1.pack_start(self.spread)

        self.partials = []
        for i in range(8):
            adj1 = gtk.Adjustment(0.5, 0.0, 1.0, 0.1, 0.1, 0.1)
            vs = gtk.VScale(adj1)
            scale_set_default_values(vs)
            vs.connect("value-changed", self.update)
            box1.pack_start(vs)
            self.partials.append(vs)
        self.update(None)
        self.window.show_all()

def main():
    gtk.main()
    return 0            

if __name__ == "__main__":
    MusicWidget()
    main()

