whispervis/animate.go

85 lines
2.1 KiB
Go
Raw Normal View History

2018-09-05 16:53:09 +03:00
package main
2018-09-17 22:11:04 +03:00
import (
2018-09-20 22:16:21 +03:00
"time"
2018-09-20 15:41:24 +03:00
2018-09-17 22:11:04 +03:00
"github.com/gopherjs/gopherjs/js"
"github.com/gopherjs/vecty"
2018-09-17 22:11:04 +03:00
)
2018-09-05 16:53:09 +03:00
// TODO(divan): move this as variables to the frontend
const (
FPS = 60 // default FPS
)
2018-09-20 22:16:21 +03:00
// animate fires up as an requestAnimationFrame handler.
2018-09-17 22:11:04 +03:00
func (w *WebGLScene) animate() {
if w.renderer == nil {
2018-09-05 16:53:09 +03:00
return
}
2018-09-17 22:11:04 +03:00
w.controls.Update()
2018-09-05 16:53:09 +03:00
if FPS == 60 {
js.Global.Call("requestAnimationFrame", w.animate)
} else {
time.AfterFunc((1000/FPS)*time.Millisecond, func() {
js.Global.Call("requestAnimationFrame", w.animate)
})
}
2018-09-05 16:53:09 +03:00
2018-09-17 22:11:04 +03:00
if w.autoRotate {
pos := w.graphGroup.Object.Get("rotation")
2018-10-20 21:38:33 +02:00
coeff := 60 / FPS * 0.001 // rotate faster on lower FPS
pos.Set("y", pos.Get("y").Float()+coeff)
2018-10-22 14:03:32 +02:00
w.graphGroup.UpdateMatrix()
2018-09-05 16:53:09 +03:00
}
2018-10-12 22:34:30 +02:00
if w.wobble {
w.wobbling.Animate()
w.updatePositions()
}
// some render throttling magic to prevent wasting CPU/GPU while idle
// if auto rotation or other effects are active, render always
var needRendering bool = w.wobble || w.autoRotate
if !needRendering {
// else, consult render throttler
needRendering = w.rt.NeedRendering()
}
if needRendering {
w.renderer.Render(w.scene, w.camera)
w.rt.ReenableIfNeeded()
}
2018-09-05 16:53:09 +03:00
}
2018-09-17 22:11:04 +03:00
// ToggleAutoRotation switches auto rotation option.
func (w *WebGLScene) ToggleAutoRotation() {
w.autoRotate = !w.autoRotate
2018-09-05 16:53:09 +03:00
}
2018-09-20 15:41:24 +03:00
2018-10-12 22:34:30 +02:00
// ToggleWobbling switches wobbling option.
func (w *WebGLScene) ToggleWobbling() {
w.wobble = !w.wobble
}
// ToggleRenderThrottler switches render throttling option.
func (w *WebGLScene) ToggleRenderThrottler() {
w.rt.Toggle()
}
// MouseMoveListener implements listener for mousemove events.
// We use it for disabling render throttling, as mousemove events
// correlates with user moving inside of the WebGL canvas. We
// may switch to use mousedown or drag events, but let's see how
// mousemove works.
// This is sort of a hack, as the proper approach would be to get
// data from controls code (w.controls.Update), but it's currently
// a JS code, so it's easier use this hack.
func (p *Page) MouseMoveListener(e *vecty.Event) {
if !p.webgl.rt.NeedRendering() {
p.webgl.rt.EnableRendering()
}
}