blooblib/Run/run.go

104 lines
2.3 KiB
Go
Raw Normal View History

2024-03-24 01:14:26 +01:00
package run
import (
2024-03-23 10:12:55 +01:00
_ "embed"
"fmt"
2024-03-24 01:14:26 +01:00
. "git.danitheskunk.com/squishy/blooblib"
"git.danitheskunk.com/squishy/blooblib/gui"
"github.com/veandco/go-sdl2/sdl"
"time"
)
type Runnable interface {
2024-03-23 12:35:37 +01:00
Init(bloob *Bloob, settings *Settings)
Render(bloob *Bloob, screen *Image)
2024-03-23 09:41:02 +01:00
Update(bloob *Bloob)
}
2024-03-23 10:12:55 +01:00
//go:embed "cursor.png"
var defaultCursorBytes []byte
func Run(game Runnable) {
_ = sdl.Init(sdl.INIT_EVERYTHING)
defer sdl.Quit()
settings := Settings{
WindowSize: Vec2i{X: 640, Y: 360},
Scale: 3,
TargetFps: 60,
Title: "Blooblib",
}
2024-03-23 10:12:55 +01:00
if DefaultCursor == nil {
DefaultCursor = LoadImageBytes(defaultCursorBytes)
}
bloob := Bloob{
Cursor: DefaultCursor,
}
2024-03-23 09:41:02 +01:00
2024-03-24 01:14:26 +01:00
gui.InitGui(settings.WindowSize)
2024-03-25 01:55:14 +01:00
game.Init(&bloob, &settings)
2024-03-24 01:14:26 +01:00
window, _ := sdl.CreateWindow(
settings.Title,
sdl.WINDOWPOS_CENTERED,
sdl.WINDOWPOS_CENTERED,
int32(settings.WindowSize.X*settings.Scale),
int32(settings.WindowSize.Y*settings.Scale),
sdl.WINDOW_SHOWN,
)
2024-03-24 01:14:26 +01:00
window.SetBordered(false)
surface, _ := window.GetSurface()
windowImage := NewImageFromPointer(surface.Data(), MulScalar(settings.WindowSize, settings.Scale))
screen := NewImage(settings.WindowSize)
screen.Alpha = false
2024-03-23 10:12:55 +01:00
sdl.ShowCursor(sdl.DISABLE)
_ = window.UpdateSurface()
lastSecond := time.Now()
framesSinceLastSecond := 0
2024-03-23 12:35:37 +01:00
frameDuration := time.Second / time.Duration(settings.TargetFps)
lastFrame := lastSecond
running := true
for running {
for event := sdl.PollEvent(); event != nil; event = sdl.PollEvent() {
2024-03-23 09:41:02 +01:00
switch event := event.(type) {
case sdl.QuitEvent:
running = false
break
2024-03-23 09:41:02 +01:00
case sdl.MouseMotionEvent:
bloob.MousePos.X = int(event.X) / settings.Scale
bloob.MousePos.Y = int(event.Y) / settings.Scale
break
}
}
now := time.Now()
delta := now.Sub(lastSecond)
if delta.Seconds() >= 1.0 {
fmt.Printf("FPS: %5d | mspf: %f\n", framesSinceLastSecond, 1000.0/float32(framesSinceLastSecond))
framesSinceLastSecond = 0
lastSecond = lastSecond.Add(time.Second)
}
delta2 := now.Sub(lastFrame)
if delta2 >= frameDuration {
2024-03-23 09:41:02 +01:00
game.Update(&bloob)
2024-03-23 12:35:37 +01:00
game.Render(&bloob, screen)
2024-03-24 01:14:26 +01:00
gui.DrawGui(screen)
2024-03-23 10:12:55 +01:00
if bloob.Cursor != nil {
screen.Draw(bloob.Cursor, bloob.MousePos)
}
windowImage.DrawUpscale(screen)
framesSinceLastSecond += 1
lastFrame = lastFrame.Add(frameDuration)
}
_ = window.UpdateSurface()
}
}