tins2021/animatedtexture.go
2021-08-10 22:36:42 +02:00

55 lines
1.6 KiB
Go

package tins2021
import (
"opslag.de/schobers/geom"
"opslag.de/schobers/zntg/ui"
)
type AnimatedTexture struct {
texture NamedTexture
animation ui.Texture
frames []geom.RectangleF32
}
func newAnimatedTexture(texture NamedTexture, animation ui.Texture, n int) AnimatedTexture {
frames := make([]geom.RectangleF32, 0, n)
height := float32(animation.Height())
width := float32(animation.Width())
for i := 0; i < n; i++ {
left := width * float32(i) / float32(n)
right := width * float32(i+1) / float32(n)
frames = append(frames, geom.RectF32(left, 0, right, height))
}
return AnimatedTexture{texture: texture, animation: animation, frames: frames}
}
func NewAnimatedTexture(texture NamedTexture, n int) AnimatedTexture {
return newAnimatedTexture(texture, texture.Texture(), n)
}
func FitAnimatedTexture(texture NamedTexture, scale float32, n int) AnimatedTexture {
height := float32(texture.Texture().Height())
scale = ScaleRound(height, scale)
return newAnimatedTexture(texture, texture.Scaled(scale), n)
}
func (t AnimatedTexture) Draw(renderer ui.Renderer, pos geom.PointF32, frame int) {
renderer.DrawTexturePointOptions(t.animation, pos, ui.DrawOptions{Source: &t.frames[frame]})
}
func (t AnimatedTexture) FrameSize(i int) geom.PointF32 { return t.frames[i].Size() }
func (t AnimatedTexture) Frames() int { return len(t.frames) }
func (t AnimatedTexture) Scale(scale float32) AnimatedTexture {
return FitAnimatedTexture(t.texture, scale, t.Frames())
}
func FindScaleRound(length, desired float32) float32 {
return ScaleRound(length, desired/length)
}
func ScaleRound(length, scale float32) float32 {
return geom.Round32(length*scale) / length
}