package graphics import ( "bytes" "git.openprivacy.ca/sarah/microworlds/core" "github.com/faiface/pixel" "github.com/faiface/pixel/pixelgl" "github.com/wcharczuk/go-chart" "image" "log" ) type Plot struct { GeneratePlot func(*core.Environment, []*core.Turtle) *chart.Chart async chan chart.Chart width, height int32 window *pixelgl.Window } func NewPlot(title string, width, height, pxsize int32) *Plot { graphics := new(Plot) graphics.width = width graphics.height = height cfg := pixelgl.WindowConfig{ Title: title, Bounds: pixel.R(0, 0, float64(width), float64(height)), VSync: true, Resizable: true, } win, err := pixelgl.NewWindow(cfg) if err != nil { panic(err) } graphics.window = win graphics.async = make(chan chart.Chart) return graphics } func (p *Plot) RenderAsync() { w := p.window.Bounds().W() h := p.window.Bounds().H() for { graph := <-p.async nw := p.window.Bounds().W() nh := p.window.Bounds().H() if nw != w || nh != h { w = nw h = nh } graph.Width = int(w) graph.Height = int(h) buffer := bytes.NewBuffer([]byte{}) err := graph.Render(chart.PNG, buffer) if err != nil { log.Fatal(err) } graphimg, _, _ := image.Decode(buffer) pd := pixel.PictureDataFromImage(graphimg) sprite := pixel.NewSprite(pd, pd.Bounds()) sprite.Draw(p.window, pixel.IM.Moved(p.window.Bounds().Center())) /**for x := 0; x < int(w); x++ { for y := 0; y < int(h); y++ { col := graphimg.At(x, y) r, g, b, a := col.RGBA() if r != 0xff && g != 0xff && b != 0xff { p.renderer.SetDrawColor(uint8(r), uint8(g), uint8(b), uint8(a)) p.renderer.DrawPoint(int32(x), int32(y)) } } }*/ p.window.Update() } } func (p *Plot) Render(env *core.Environment, turtles []*core.Turtle) { graph := p.GeneratePlot(env, turtles) if env.Step > 2 { p.async <- *graph } }