GitHubはじめる

このページはまだ日本語訳がないため、英語の原文を表示しています。

2D コア

Loop

game.Loop drives fixed-step updates and interpolated frame draws on an NSGo scope's display frames, pausing automatically while the app is in the background.

import "github.com/nsgo-dev/game"

How the fixed step works

Displays run at different refresh rates (60 Hz, 90 Hz, 120 Hz, or variable). If a game moves physics by raw frame delta times, jump heights and collisions change with the display rate.

Loop decouples simulation from rendering:

type Loop struct {
	Rate        int                    // updates a second, 60 when 0
	MaxSteps    int                    // most updates one frame runs, max(1, Rate/10) when 0
	Paused      bool                   // stops Update from advancing with display time
	PausedAwake time.Duration          // how long to keep the display awake while paused or OnDemand-idle
	TimeScale   float64                // simulated time multiplier, 1 when <= 0 or non-finite
	DrawRate    int                    // caps Draw calls per second, uncapped when <= 0
	MatchDisplayToRate bool             // asks the display to use Rate when DrawRate is uncapped
	OnDemand    bool                   // skips Draw on frames without Update unless MarkDirty was called
	Idle        func() bool            // with OnDemand, skips both Update and Draw while returning true
	Immersive   bool                   // hides phone system bars while unpaused
	Update      func(dt time.Duration) // moves the game on by dt, always 1/Rate seconds
	Draw        func(alpha float64)    // draws the frame, alpha in [0, 1)
	FrameTime   func(dt time.Duration) // receives each frame's length before updates
	OnPause     func(paused bool)      // runs whenever Paused changes
}

func (l *Loop) Run(cx *core.Scope) (stop func())
func (l *Loop) SetPaused(paused bool)
func (l *Loop) SetTimeScale(scale float64)
func (l *Loop) Step(n int)
func (l *Loop) StepOnce()
func (l *Loop) StepNow(n int) int
func (l *Loop) MarkDirty()

On each display frame from NSGo's RequestAnimationFrame:

  1. The loop adds the elapsed time since the previous frame to an accumulator.
  2. While the accumulator holds at least one whole step (time.Second / time.Duration(Rate)), it subtracts one step and calls Update(step). A single display frame may run zero, one or several updates.
  3. Once fewer than one whole step remains, it calls Draw(alpha) with alpha = float64(acc) / float64(step) in [0, 1).

Run reads Rate, MaxSteps, Update and Draw on every frame, so you can swap handlers or adjust the rate while the loop is running.

Interpolating with alpha

When the display rate does not evenly divide Rate (for example, a 60 Hz simulation on a 120 Hz display), drawing the raw state from Update produces visible stutter because some frames run zero updates and some run one.

Keep the previous and current state in Update, pass alpha into a core.Signal[float64] from Draw, and interpolate inside core.Canvas.Draw:

func Ball(cx *core.Scope) core.Node {
	var x, last float32
	alpha := core.NewSignal(cx, 0.0)

	loop := &game.Loop{
		Rate: 60,
		Update: func(dt time.Duration) {
			last = x
			x += 120 * float32(dt.Seconds())
		},
		Draw: func(a float64) {
			alpha.Set(a)
		},
	}
	loop.Run(cx)

	return core.Canvas{
		Style: core.Style{FlexGrow: 1, FlexShrink: 1},
		Draw: func(d *core.Drawing, _ core.Size) {
			at := last + (x-last)*float32(alpha.Get())
			d.SetFillColor(core.RGB(0xff5a1f)).FillRect(at, 40, 16, 16)
		},
	}
}

Because alpha is read only inside Canvas.Draw, setting it redraws the canvas without re-evaluating or committing the surrounding view tree.

Hitch protection and MaxSteps

If a single frame takes much longer than usual (a debugger pause, a slow frame, or a device stall), catching up every missed step would cause an even slower next frame — the classic "spiral of death".

MaxSteps caps how many Update calls one display frame may execute:

  • When MaxSteps <= 0, it defaults to max(1, Rate/10) — one tenth of a second of simulation (6 steps at 60 Hz, 12 steps at 120 Hz).
  • When a frame reaches MaxSteps, the loop drops the remaining whole steps (acc %= step) and moves straight to Draw. The game briefly slows down instead of freezing.

Set MaxSteps explicitly when you need a tighter bound (for example, MaxSteps: 3 for heavy physics):

loop := &game.Loop{
	Rate:     60,
	MaxSteps: 3,
	Update:   stepWorld,
	Draw:     renderWorld,
}

Frame time

Each frame adds the time between its timestamp and the previous frame's, exactly as RequestAnimationFrame gives it. Where the platform stamps its display frames, that is the display's own frame time, so a frame's length is the display's rather than when the engine got to the frame; elsewhere it is the graph clock's. The first frame after the loop starts or resumes adds the time from then to its timestamp, which may lie a frame ahead where the display stamps a frame with when it will show, so the loop's time is the shown frame's. A frame stamped before the time the loop started or resumed adds nothing, so resuming never moves the accumulator backward, and the next frame adds the time from then.

Set FrameTime to read each frame's length, the time it adds, ahead of the frame's updates; a frame that adds nothing passes 0. Frame-time statistics, such as quality's Selector, read it. The first frame back from the background measures from the time the window showed again, not the time away, and FrameTime may call the stop function Run returned, which ends the frame before any update. It also fires while Paused is set, so a caller that should only measure frames that simulate skips them itself.

loop := &game.Loop{
	FrameTime: func(dt time.Duration) { selector.Observe(dt) },
	Update:    stepWorld,
	Draw:      renderWorld,
}

Pausing and syncing subsystems

SetPaused(true) (or setting Paused = true) stops Update from advancing while Draw keeps running, and unpausing resumes without a catch-up backlog. Set OnPause to keep subsystems such as sound.Mixer in sync with the loop's paused state:

mixer.SetPauseExempt("ui", true)
loop := &game.Loop{
	Rate:    60,
	OnPause: mixer.SetPaused,
	Update:  stepWorld,
	Draw:    renderWorld,
}
loop.Run(cx)
  • SetPaused calls OnPause immediately whenever the paused state changes (repeating the same value does nothing).
  • Editing Paused directly calls OnPause on the next frame, or in the same frame when Update changes it.
  • If Paused is already true when Run starts, Run calls OnPause(true).
  • Backgrounding does not call OnPause; both Loop.Run and sound.NewMixer watch core.Env.Lifecycle directly so backgrounding pauses and resumes everything in sync without clearing an open pause menu.

Scaling time (TimeScale)

TimeScale (or SetTimeScale) scales simulated time for slow-motion effects or fast-forward without changing the fixed dt passed to Update:

  • 0.5 runs half as many Update steps per second; 2.0 runs twice as many (still capped by MaxSteps per frame).
  • Values at or below 0 (as well as NaN and ±Inf) default to 1.
loop.SetTimeScale(0.25) // bullet-time slow motion; Update still sees dt == 1/Rate

Single-stepping while paused (Step, StepOnce, StepNow)

While Paused is true, you can advance the simulation by an exact number of fixed steps without unpausing:

  • Step(n) queues n fixed Update steps to run on the next display frame, followed by a Draw(0) (non-positive values do nothing).
  • StepOnce() is shorthand for Step(1).
  • StepNow(n) runs n fixed Update steps and a Draw synchronously right away (whether Paused is true or false) and returns how many steps ran, which suits deterministic tests and editor replay tools.

Capping the draw rate (DrawRate)

Set DrawRate to cap how many times Draw runs per second while keeping Update at Rate (for example, 60 Hz physics with 30 fps rendering under low-power mode). Values at or below 0 leave Draw uncapped at the display's refresh rate.

When OnDemand and DrawRate are both set, a MarkDirty request that arrives before the next draw interval is preserved and drawn once the interval elapses.

Matching the display rate (MatchDisplayToRate)

Loop asks the host to lower the display refresh rate when it can. A positive DrawRate becomes the preferred display rate, so a low-power cap avoids waking the app at the panel's full rate. Set MatchDisplayToRate: true when DrawRate is uncapped and the display should follow the fixed update rate. Paused loops and idle OnDemand loops request a conservative 60 Hz idle rate, which lowers wakeups on high-refresh panels while preserving the usual cadence on 60 Hz displays. The host may choose a different supported rate.

On-demand drawing and idling (OnDemand, Idle, MarkDirty)

Menu-heavy, turn-based and narrative games often sit waiting for the player to tap or press a key. Set OnDemand: true together with Idle so the loop does zero update and draw work while nothing is animating:

  • Without Idle: OnDemand: true skips Draw on frames where no Update ran unless MarkDirty() was called (for example, a 30 Hz simulation on a 60 Hz display draws 30 times a second, and a Paused: true loop draws only on Step or MarkDirty).
  • With Idle: while OnDemand is true, Paused is false and Idle() returns true, the loop skips both Update and Draw on display frames without accumulating elapsed time (so waking later produces no catch-up backlog).
  • Waking on input (MarkDirty): calling MarkDirty() requests a Draw on the next frame; when an unpaused OnDemand loop is idle, MarkDirty() also queues one fixed Update step on that frame so Update can sample input and advance state. Multiple MarkDirty() calls between frames coalesce into a single wake step. If that Update starts ongoing work (so Idle() returns false), fixed-step updates resume normally until Idle() returns true again.
  • Wiring input: assign actions.Wake = loop.MarkDirty on input.Actions (and TouchControls.OnWake or GestureRecognizer.Wake when used without a bound Actions), and call loop.MarkDirty() from view callbacks (such as button OnPress) that mutate state outside Update.
loop := &game.Loop{
	Rate:     60,
	OnDemand: true,
	Idle: func() bool {
		return fadeLeft == 0 && typewriter.Done() && !autoMode
	},
	Update: func(dt time.Duration) {
		actions.Step()
		handleInput()
		stepAnimations(dt)
	},
	Draw: func(float64) {
		frame.Update(func(v uint64) uint64 { return v + 1 })
	},
}
actions.Wake = loop.MarkDirty
loop.Run(cx)

Background pause and stopping

Loop.Run watches cx.Env().Lifecycle():

  • core.LifecycleBackground (minimized, hidden or covered on desktop; app backgrounded on iOS or Android): the loop cancels its pending frame request and runs no updates.
  • core.LifecycleActive or core.LifecycleInactive (visible, even without focus on desktop): the loop runs normally. When returning from the background, it resets its clock anchor to cx.Now(), so time spent away produces zero catch-up steps.
  • Set PauseOnLeave: LeaveInactive to pause once on any focus loss, or LeaveBackground to pause only when the app is backgrounded. The pause stays set until SetPaused(false) is called. OnLeave runs once for every transition away from the active lifecycle and receives whether the transition was backgrounding, which is a suitable place to save progress. The signals it reads do not subscribe the loop, so a change to them never calls it again.
  • A live run also calls OnLeave during scope quit when it has not already handled the current background transition. The stop function returned by Run ends that run’s lifecycle and quit callbacks.
  • The shmup2d template pauses a running game on focus loss or backgrounding. The pause menu stays open until the player chooses Resume.

The loop ends permanently when either:

  • The cx scope is disposed (for example, navigating away or hiding the component with core.Show), or
  • You call the stop function returned by Run.

Calling stop() is safe to repeat and safe from inside Update: if Update stops the loop, no further updates and no Draw run for that frame, and returning from the background will not restart it.

var stop func()
loop := &game.Loop{
	Update: func(dt time.Duration) {
		if gameOver {
			stop()
		}
	},
	Draw: func(alpha float64) {
		frame.Set(alpha)
	},
}
stop = loop.Run(cx)

Keeping the display awake

While the loop runs in the foreground and is active (not Paused, and not idle under OnDemand and Idle), Loop.Run holds a display keep-awake lock (core.Scope.KeepAwake with Display: true) so the device does not dim or auto-lock mid-game:

  • Background, stop, or scope disposal: the display hold is released immediately.
  • Paused or idle OnDemand loops: once the loop is Paused or OnDemand-idle (Idle() returns true, with no pending Step updates or MarkDirty wake/draw), the hold is released after PausedAwake. The default 0 (or any non-positive value) releases the hold immediately so the OS auto-lock timer runs normally on pause, title, waiting-dialogue, and game-over screens.
  • Grace period (PausedAwake): set PausedAwake (for example 30 * time.Second) to keep the display awake briefly after pausing, going idle, or after the last Step / MarkDirty before releasing the hold.
  • Resuming and stepping: calling SetPaused(false) takes the hold again immediately (changing Paused = false directly or having Idle() return false takes it on the next frame). Queuing Step updates while paused or calling MarkDirty on a paused or idle OnDemand loop keeps the hold while those updates or draws run and resets the PausedAwake timer.
  • Cutscenes: cutscene.Player takes its own display hold while a cutscene plays, so pausing the game loop underneath a cutscene does not let the screen sleep.
loop := &game.Loop{
	Rate:        60,
	PausedAwake: 30 * time.Second, // optional grace period on pause menus
	Update:      stepWorld,
	Draw:        renderWorld,
}
loop.Run(cx)

Immersive mode on phones

Set Immersive to hide a phone's system bars while the game plays and bring them back in menus. The loop calls NSGo's mobile.Immersive: Android hides its status and navigation bars and shows them briefly on an edge swipe, iOS hides the status bar and lets the home indicator fade, and HarmonyOS hides its status bar, navigation bar and navigation indicator. Desktop and web targets ignore it.

loop := &game.Loop{
	Immersive: true,
	Update:    stepWorld,
	Draw:      renderWorld,
}
loop.Run(cx)

// Opening the pause menu shows the bars on the next frame; closing it hides them again.
openMenu := func() { loop.SetPaused(true) }
closeMenu := func() { loop.SetPaused(false) }
  • The bars hide while the loop runs and is not Paused, and come back while it is Paused, when stop is called and when cx is disposed, so a menu screen that replaces the game's view brings them back too.
  • The loop hides them as it starts or returns from the background, applies a change to Immersive or Paused on its next frame (in the same frame when Update pauses), and asks the platform only when the state changes. It leaves the bars as they are while the app is in the background.
  • Hiding and showing the bars can change the safe-area insets the platform reports (HarmonyOS, for one, keeps only the display cutout while they are hidden), so lay HUDs out with screen.Viewport.SafeGameRectForEnv, which follows the insets as they change.
  • Loops in the same window share the bars: they stay hidden while any loop with Immersive set plays, and come back once the last of them pauses or ends. A scene that starts its own loop while the previous scene's loop is still alive, as under a scene transition, keeps the bars hidden when the old loop is disposed, and a pushed scene's loop keeps them hidden when the scene below pauses its own. A menu shown as an NSGo page or dialog can also set StatusBar: core.StatusBarSetting{Immersive: core.ToggleOff}, which overrides the window's setting while it is shown.

Testing with nsgotest

nsgotest runs display frames deterministically on a virtual clock (one frame every 16.667 ms, 60 frames a second), so you can test gameplay loops, MaxSteps hitches and background pauses without sleeping.

package mygame_test

import (
	"testing"
	"time"

	"github.com/nsgo-dev/game"
	"github.com/nsgo-dev/nsgo/core"
	"github.com/nsgo-dev/nsgo/nsgotest"
)

func TestMain(m *testing.M) { nsgotest.Main(m) }

func TestLoopSimulation(t *testing.T) {
	updates := 0
	l := &game.Loop{
		Rate:     60,
		MaxSteps: 4,
		Update: func(dt time.Duration) {
			updates++
		},
	}

	app := nsgotest.Start(t, func(cx *core.Scope) core.Node {
		l.Run(cx)
		return core.View{}
	})

	// Advance steps frame by frame for one full second.
	app.Advance(time.Second)
	if updates != 60 {
		t.Fatalf("got %d updates, want 60", updates)
	}

	// FastForward jumps in a single frame, exercising MaxSteps.
	app.FastForward(500 * time.Millisecond)
	if updates != 64 {
		t.Fatalf("got %d updates after hitch, want 64", updates)
	}

	// Background pauses the loop with no catch-up on resume.
	app.SetEnvironment(core.Environment{Lifecycle: core.LifecycleBackground})
	app.Advance(time.Second)
	app.SetEnvironment(core.Environment{Lifecycle: core.LifecycleActive})
	if updates != 64 {
		t.Fatalf("got %d updates while backgrounded, want 64", updates)
	}
}

Guarding unsaved progress on quit

save.QuitGuard centralizes the decision used by close and quit adapters: a clean request closes, an ordinary request with unsaved progress saves first when the game can save now (QuitSave) and asks the player otherwise (QuitAsk), and a forced shutdown saves best effort with SaveForced and closes even when saving fails (QuitSaveAndAllow). See Unsaved progress on close.

Register gameui.GuardQuit once in the game's window scope with a gameui.QuitGuardOptions. The adapter handles both system Quit and the window close button, including the close button on macOS. Ask opens the game's confirmation UI. Call its answer with true to close or false to keep playing, on the same scope. Use Pause to suspend simulation while the question is open and combine that pause with the game's existing pause state. Report can display or log a save error. A failed ordinary save falls back to confirmation and a forced quit proceeds after a best-effort save.

Mount gameui.QuitConfirmation alongside the game view. Give its Open the signal set by Pause and forward OnAnswer to the reply from Ask. The dialog initially focuses Cancel. Set Save to offer Save and quit, and optionally CanSave to control when the action is available. A failed save keeps the dialog open for retry. To use a controller, call gamepad.EnableFocusNavigation on the window scope and release any gameplay input capture while the question is open. For Restart or Quit to title, supply the action's own copy and handle OnAnswer directly.

Loop.PauseOnLeave and HandleLeave provide a shared leave-policy hook for pausing and save callbacks when a game loses focus or backgrounds.

Fixed-step interpolation

tilemap.Camera keeps its previous fixed-step pose: call BeginStep before each Update that moves it, ResetInterpolation after a teleport or a cut, and InterpolatedPose(alpha) in Draw for the position and rotation to draw (rotation turns along the shortest arc; Zoom is not interpolated). It never changes the camera, so simulation state stays the same. Physics bodies and scene objects keep no previous pose yet; interpolate them by hand as in Interpolating with alpha.

このページを編集