GitHub시작하기

이 페이지는 아직 한국어로 번역되지 않아 영문 원문을 표시하고 있습니다.

2D 시스템

quality

game/quality picks a low, medium or high quality preset for the device a game runs on, moves it with the frame times the game measures, and holds whatever the player picks in settings instead.

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

Presets

A Preset is what one level turns on and how far it scales the game's costs:

Field Low Medium High Meaning
ResolutionScale 0.5 0.75 1 Sets the base canvas scale and scales game-owned buffers through Scale and ScaleSize
ParticleScale 0.25 0.6 1 Scales particle budgets and burst counts; read it with Particles
Effects off on on Effects that only decorate the frame: screen flashes, parallax backdrops, post effects, trails
Shadows off off on Shadow casting, such as lights2d.Scene.DisableShadows
Sampling smooth smooth smooth Use smooth or nearest when enlarging a reduced-resolution canvas

DefaultPreset(level) returns these values. Particles(n) and Scale(n) round and never return less than 1 for a positive n, so a scaled budget never switches an emitter off:

p := quality.DefaultPreset(quality.Low)
emitter.MaxParticles = p.Particles(512) // 128
emitter.Burst(p.Particles(24))          // 6
lights.DisableShadows = !p.Shadows
foliage := world3d.DefaultQualityProfile(world3d.QualityLevelFor(quality.Low))

With NSGo v0.4.0, Selector.CanvasScale() gives a core.Canvas its current resolution scale. At 0.5 the canvas renders at half the pixel density in each direction and stretches the result to its layout box. Layout, touch coordinates and the draw callback's size stay in points. For a canvas that follows quality changes, feed signals into ResolutionScaleFunc and SamplingFunc.

scale := core.NewSignal(cx, sel.CanvasScale())
sampling := core.NewSignal(cx, sel.CanvasSampling())
sel.OnCanvasChange = func(s float32, filter core.ImageSampling) {
	scale.Set(s)
	sampling.Set(filter)
}
canvas := core.Canvas{
	ResolutionScaleFunc: scale.Get,
	SamplingFunc:        sampling.Get,
	Draw:                drawScene,
}

The starting level

DeviceFromEnv(cx.Env()) reads the operating system, idiom, device model, OS version and CPU count; the count is 0 on the web, where Go always reports 1. It leaves Device.GPU nil: a game that has its gpu.Device sets the field from Capabilities() before calling Classify. Classify places a device no rule names:

Device Starts at
Android Low; NSGo reports neither its memory nor its GPU, so measured frame times step it up
iPhone High from the iPhone 13 (iPhone14,x), Medium from the iPhone 11 (iPhone12,x), Low before
iPad High from iPad13,x, Medium from iPad11,x, Low before
macOS, Windows, Linux High with 8 or more CPUs, Medium with 4 to 7, Low with fewer
TV and watch Low
Web, when Device.GPU has no compute or no compressed texture formats Low
Web phone Low
Web tablet and desktop Medium
Anything unknown Medium

A configuration's device rules come first: the first rule whose model is a prefix of the device's model, ignoring case, and whose OS matches when it names one, gives the starting level.

Adapting to frame times

A Selector starts at the configured level and, while the setting is auto, judges frames a window at a time (90 by default). It skips 30 frames after starting or changing the level or canvas scale.

  • When more than a quarter of a window's frames miss the target (30 fps by default), the selector tries the next configured canvas scale between the current scale and the next lower preset. Low can use any configured scale below its current scale. When there are no more steps to try, the selector drops to the next preset if there is one.
  • Several windows in a row (4 by default) with nine in ten frames inside 60% of the target frame time step it up a level.
  • It never steps back up to a level it stepped down from, so it settles instead of swinging between two levels.
  • The selector holds a reduced canvas scale at its current level. Selecting a fixed preset or resetting to Auto restores that preset's base scale.
  • Frames longer than half a second, such as loading or the first frame back from the background, do not count.

Feed it the loop's raw frame lengths through Loop.FrameTime, and apply each new preset in OnChange:

sel, err := quality.NewSelector(quality.DefaultConfig(), quality.DeviceFromEnv(cx.Env()))
if err != nil {
	panic(err) // DefaultConfig always validates
}
sel.OnChange = func(_ quality.Level, p quality.Preset) { arena.ApplyQuality(p) }
arena.ApplyQuality(sel.Preset())

loop := &game.Loop{
	FrameTime: func(dt time.Duration) {
		if !arena.Paused {
			sel.Observe(dt)
		}
	},
	Update: arena.Step,
	Draw:   draw,
}

FrameTime keeps firing while the loop or the game is paused. Skip observing frames that simulate nothing, such as a pause or game-over screen: they are cheap and would step the level up toward one gameplay cannot hold.

A Selector is not safe for concurrent use; call it from the scope that runs the loop.

The player's setting

save.DisplaySettings.Quality stores the player's choice: "auto" (the default) or "low", "medium" or "high". Settings.Validate normalizes it and turns anything else into "auto". Selector.SetSetting applies it: a level's name holds that level whatever the frame times, and "auto" returns to the starting level and adapts again. Selector.Setting returns the value to store.

store := save.NewStorageSettingsStore(cx.Storage(), "mygame")
if s, err := store.Load(); err == nil {
	_ = sel.SetSetting(s.Display.Quality) // Load has validated it
}

// From the settings menu:
if err := sel.SetSetting("high"); err == nil {
	// Load returns the defaults when nothing is stored yet; any other error, such as settings a newer build wrote, keeps the setting for this run only.
	if s, err := store.Load(); err == nil {
		s.Display.Quality = sel.Setting()
		_ = store.Save(s)
	}
}

The configuration file

A game can keep its presets, device rules and adaptation in a YAML file. ParseConfig refuses unknown fields, a missing or other version, scales outside (0, 1], duplicate device rules, device models with leading or trailing spaces, unknown levels or operating systems, and trailing documents. EncodeConfig writes fields in a fixed order, so a file read and written back is unchanged.

version: 1
presets:
  low:
    resolution_scale: 0.5
    particle_scale: 0.25
    effects: false
    shadows: false
  medium:
    resolution_scale: 0.75
    particle_scale: 0.6
    effects: true
    shadows: false
  high:
    resolution_scale: 1
    particle_scale: 1
    effects: true
    shadows: true
devices:
  - model: Google Pixel 8
    os: android
    level: high
adapt:
  target_fps: 30
  window_frames: 120
  upgrade_windows: 3
adapt field Range Default
off true keeps the starting level for the whole run false
target_fps 3 to 240 (below 3 fps a slow frame would be over the half second the selector ignores) 30
window_frames 10 to 3600 90
upgrade_windows 1 to 100 4
resolution_steps Optional list of strictly descending scales in (0, 1], such as [0.85, 0.65] No intermediate steps

To configure the same steps in Go, set cfg.Adapt.ResolutionSteps = &quality.ResolutionSteps{0.85, 0.65}.

In the Starburst example

examples/starburst starts Android phones on Low at half canvas resolution with a quarter of the particles and without parallax, floor grid or screen flashes. Auto tries 0.85 between High and Medium and 0.65 between Medium and Low. The HUD's quality button steps through Auto, Low, Medium and High and stores the choice in the player's settings. BenchmarkArenaPresets measures one stress-mode step and the cost of recording its draw operations at each level.

cd examples/starburst
go tool nsgo test -bench BenchmarkArenaPresets ./...

Performance regression checks

Unit tests assert deterministic correctness, never wall-clock speed alone. Do not fail a test because time.Since exceeds a frame budget, an average latency, or a speedup ratio; keep assertions such as HPA*'s path-cost bound and put the performance claim in a tracked benchmark, or use a deterministic proxy such as nodes expanded. For example, BenchmarkAStar1024 and BenchmarkHPA1024 measure the two searches without making the unit test depend on runner load, and the Performance baselines job checks them against benchmarks/hpa-baseline.yaml:

go tool nsgo test -run '^$' -bench 'Benchmark(AStar|HPA)1024$' ./pkg/pathfind

game bench runs each benchmark three times by default and compares the median with its baseline. If the median ns/op regresses while B/op and allocs/op are identical to the baseline, it retries the measurement once. A first failure that does not reproduce is reported as a warning; a reproduced regression still fails. Missing benchmarks and allocation regressions fail immediately. -in only evaluates the supplied results and cannot retry them.

이 페이지 편집