Example #1
0
func Run(g GraphicsContext, width, height, scale int, title string, fps int) error {
	if currentRunContext != nil {
		return errors.New("loop: The game is already running")
	}
	currentRunContext = &runContext{
		fps: fps,
	}
	currentRunContext.startRunning()
	defer currentRunContext.endRunning()

	if err := ui.CurrentUI().Start(width, height, scale, title); err != nil {
		return err
	}
	// TODO: Use the error value
	defer ui.CurrentUI().Terminate()

	n := now()
	currentRunContext.lastUpdated = n
	currentRunContext.lastFPSUpdated = n
	for {
		e, err := ui.CurrentUI().Update()
		if err != nil {
			return err
		}
		switch e := e.(type) {
		case ui.ScreenSizeEvent:
			if err := g.SetSize(e.Width, e.Height, e.ActualScale); err != nil {
				return err
			}
		case ui.CloseEvent:
			return nil
		case ui.RenderEvent:
			if err := currentRunContext.render(g); err != nil {
				return err
			}
			e.Done <- struct{}{}
		default:
			panic("not reach")
		}
	}
}
Example #2
0
func (c *runContext) render(g GraphicsContext) error {
	fps := c.fps
	n := now()
	defer func() {
		// Calc the current FPS.
		if time.Second > time.Duration(n-c.lastFPSUpdated) {
			return
		}
		currentFPS := float64(c.frames) * float64(time.Second) / float64(n-c.lastFPSUpdated)
		c.updateFPS(currentFPS)
		c.lastFPSUpdated = n
		c.frames = 0
	}()

	// If lastUpdated is too old, we assume that screen is not shown.
	if 5*int64(time.Second)/int64(fps) < n-c.lastUpdated {
		c.setRunningSlowly(false)
		c.lastUpdated = n
		return nil
	}

	// Note that generally t is a little different from 1/60[sec].
	t := n - c.lastUpdated
	tt := int(t * int64(fps) / int64(time.Second))

	// As t is not accurate 1/60[sec], errors are accumulated.
	// To make the FPS stable, set tt 1 if t is a little less than 1/60[sec].
	if tt == 0 && (int64(time.Second)/int64(fps)-int64(5*time.Millisecond)) < t {
		tt = 1
	}
	if 1 <= tt {
		for i := 0; i < tt; i++ {
			slow := i < tt-1
			c.setRunningSlowly(slow)
			if err := g.UpdateAndDraw(); err != nil {
				return err
			}
		}
	} else {
		if err := g.Draw(); err != nil {
			return err
		}
	}
	if err := ui.CurrentUI().SwapBuffers(); err != nil {
		return err
	}
	c.lastUpdated += int64(tt) * int64(time.Second) / int64(fps)
	c.frames++
	return nil
}
Example #3
0
func (e *eventDispatcher) SetScreenScale(scale int) {
	ui.CurrentUI().SetScreenScale(scale)
}
Example #4
0
func (t touch) Position() (int, int) {
	// TODO: Is this OK to adjust the position here?
	return t.position.x / ui.CurrentUI().ScreenScale(),
		t.position.y / ui.CurrentUI().ScreenScale()
}
Example #5
0
func (e *eventDispatcher) SetScreenSize(width, height int) {
	ui.CurrentUI().SetScreenSize(width, height)
}