forked from sarah/microworlds
95 lines
2.3 KiB
Go
95 lines
2.3 KiB
Go
package graphics
|
|
|
|
import (
|
|
"fmt"
|
|
"git.openprivacy.ca/sarah/microworlds/core"
|
|
"github.com/veandco/go-sdl2/sdl"
|
|
"math"
|
|
"os"
|
|
//"strconv"
|
|
)
|
|
|
|
type Graphics struct {
|
|
window *sdl.Window
|
|
renderer *sdl.Renderer
|
|
width, height, pxsize int32
|
|
t int
|
|
colorMap map[string][4]uint8
|
|
}
|
|
|
|
func NewGraphics(width, height, pxsize int32) *Graphics {
|
|
graphics := new(Graphics)
|
|
graphics.width = width
|
|
graphics.height = height
|
|
graphics.pxsize = pxsize
|
|
window, err := sdl.CreateWindow("Microworlds", sdl.WINDOWPOS_UNDEFINED, sdl.WINDOWPOS_UNDEFINED,
|
|
width * pxsize, height * pxsize, sdl.WINDOW_SHOWN)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
graphics.window = window
|
|
|
|
surface, _ := window.GetSurface()
|
|
renderer, err := sdl.CreateSoftwareRenderer(surface)
|
|
if err != nil {
|
|
fmt.Fprintf(os.Stderr, "Failed to create renderer: %s\n", err)
|
|
panic(err)
|
|
}
|
|
|
|
graphics.colorMap = make(map[string][4]uint8)
|
|
|
|
graphics.renderer = renderer
|
|
return graphics
|
|
}
|
|
|
|
func (g *Graphics) DrawTileColor(x, y int32) {
|
|
g.renderer.FillRect(&sdl.Rect{X: x * g.pxsize, Y: y * g.pxsize, W: g.pxsize, H: g.pxsize})
|
|
}
|
|
|
|
func (g *Graphics) ColorPheromone(name string, color [4]uint8) {
|
|
g.colorMap[name] = color
|
|
}
|
|
|
|
func (g *Graphics) Render(env *core.Environment, turtles []*core.Turtle) {
|
|
g.renderer.SetDrawColor(0x00, 0x00, 0x00, 0x00)
|
|
g.renderer.FillRect(&sdl.Rect{X: 0, Y: 0, W: g.width * g.pxsize, H: g.width * g.pxsize})
|
|
|
|
for x := 0; x < int(g.width); x++ {
|
|
for y := 0; y < int(g.height); y++ {
|
|
for name, color := range g.colorMap {
|
|
amount := math.Min(float64(env.Sniff(name, x, y)), 255)
|
|
|
|
if amount > 0 {
|
|
// TODO explictly define this scale
|
|
scaledamount := uint8(float64(color[0]) * (amount/2))
|
|
g.renderer.SetDrawColor(scaledamount,0,scaledamount, uint8(0xF0))
|
|
g.DrawTileColor(int32(x), int32(y))
|
|
}
|
|
}
|
|
|
|
if env.HasValue(x, y) {
|
|
g.renderer.SetDrawColor(255, 255, 255, uint8(255))
|
|
g.DrawTileColor(int32(x), int32(y))
|
|
}
|
|
}
|
|
}
|
|
|
|
g.renderer.SetDrawColor(0xF3, 0x81, 0, 0x00)
|
|
for _, t := range turtles {
|
|
x, y := t.Pos()
|
|
g.DrawTileColor(int32(x), int32(y))
|
|
t.Run(env)
|
|
}
|
|
|
|
// TODO: Move this into an environment specification
|
|
for name := range g.colorMap {
|
|
env.Evaporate(0.95, name)
|
|
}
|
|
|
|
g.renderer.Present()
|
|
g.window.UpdateSurface()
|
|
// surface, _ := g.window.GetSurface()
|
|
// surface.SaveBMP("./images/" + strconv.Itoa(g.t) + ".bmp")
|
|
g.t++
|
|
}
|