Chip-8_Go/cmd/web/main.go

142 lines
2.8 KiB
Go

package main
import (
"image/color"
"sync"
"syscall/js"
"time"
"github.com/llgcode/draw2d/draw2dimg"
"github.com/llgcode/draw2d/draw2dkit"
"github.com/markfarnan/go-canvas/canvas"
"git.jacknet.io/S.D/Chip-8_Go/chip8"
)
var done chan struct{}
var cvs *canvas.Canvas2d
var width, height float64 = 64, 32
var sizeMultiplier = 8
var drawBuf = [64 * 32]byte{}
var drawNeeded = false
var graphicsLock sync.Mutex
var keysLock sync.Mutex
var window js.Value
var keys [16]byte
var keyMap = map[int]int{
88: 0, // x
49: 1, // 1
50: 2, // 2
51: 3, // 3
81: 4, // q
87: 5, // w
69: 6, // e
65: 7, // a
83: 8, // s
68: 9, // d
90: 10, // z
67: 11, // c
52: 12, // 4
82: 13, // r
70: 14, // f
86: 15, // v
}
func keyEventHandle(event js.Value) {
println(event.Get("type").String())
println(event.Get("keyCode").Int())
elem, ok := keyMap[event.Get("keyCode").Int()]
if ok {
keysLock.Lock()
defer keysLock.Unlock()
if event.Get("type").String() == "keydown" {
keys[elem] = 1
} else if event.Get("type").String() == "keyup" {
keys[elem] = 0
}
}
}
func main() {
println("CHIP8 IS HERE!")
window = js.Global()
window.Call("addEventListener", "keydown", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
keyEventHandle(args[0])
return nil
}))
window.Call("addEventListener", "keyup", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
keyEventHandle(args[0])
return nil
}))
cvs, _ = canvas.NewCanvas2d(false)
cvs.Create(int(width)*sizeMultiplier, int(height)*sizeMultiplier)
height = float64(cvs.Height())
width = float64(cvs.Width())
cpu := chip8.NewCHIP8(getSpaceInvaders())
cvs.Start(60, Render)
i := 0
for {
c := make(chan int)
go timeCycle(c)
cpu.PerformCycle()
if cpu.DrawIsNeeded() {
drawNeeded = true
graphicsLock.Lock()
drawBuf = cpu.GetGraphicsBuffer()
graphicsLock.Unlock()
keysLock.Lock()
cpu.UpdateKeys(keys)
keysLock.Unlock()
}
i++
if i > 7 {
cpu.TickTimers()
i = 0
//println("here!")
}
<-c
}
}
func timeCycle(c chan int) {
time.Sleep(2000 * time.Microsecond)
c <- 0
}
func Render(gc *draw2dimg.GraphicContext) bool {
if !drawNeeded {
return false
}
drawNeeded = false
gc.SetFillColor(color.RGBA{0x00, 0x00, 0x00, 0xff})
gc.Clear()
gc.SetFillColor(color.RGBA{0x00, 0xff, 0x00, 0xff})
//gc.SetStrokeColor(color.RGBA{0x00, 0xff, 0x00, 0xff})
gc.BeginPath()
//gc.ArcTo(gs.laserX, gs.laserY, gs.laserSize, gs.laserSize, 0, math.Pi*2)
graphicsLock.Lock()
defer graphicsLock.Unlock()
for i, val := range drawBuf {
if val != 0 {
x := i % 64
y := i / 64
// println("drawing to ", x, y)
draw2dkit.Rectangle(gc, float64(x*sizeMultiplier), float64(y*sizeMultiplier), float64((x*sizeMultiplier)+sizeMultiplier), float64((y*sizeMultiplier)+sizeMultiplier))
}
}
gc.FillStroke()
gc.Close()
//println("drawing")
return true
}