quality

package
v0.4.0-rc.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 4, 2026 License: Apache-2.0 Imports: 14 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package quality is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.

Package quality picks a game's low, medium or high quality preset (resolution scale, particle budget, effects and shadows) from the device it runs on and the frame times it measures, and lets the player override the choice in settings.

A Config, written in YAML, holds the three presets, rules that place known device models, and how frame times move the level. A Selector starts at the level the Config gives the Device, steps down when frames run slower than the target and up when they keep well inside it, and holds whatever level the player picks instead of "auto".

Example
package main

import (
	"fmt"

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

func main() {
	fmt.Println(quality.FormatVersion)
}
Output:
2

Index

Examples

Constants

View Source
const (
	// DefaultTargetFPS is the frame rate the Selector holds when Adapt.TargetFPS is 0.
	DefaultTargetFPS = 30
	// DefaultWindowFrames is how many frames the Selector judges at a time when Adapt.WindowFrames is 0.
	DefaultWindowFrames = 90
	// DefaultUpgradeWindows is how many fast windows in a row the Selector waits for before stepping up when Adapt.UpgradeWindows is 0.
	DefaultUpgradeWindows = 4
)

Defaults that apply when a Config's Adapt leaves a field at 0.

View Source
const FormatVersion = 2

FormatVersion is the schema version of the quality YAML file, the one ParseConfig accepts and EncodeConfig writes.

Version 2 lets a device rule match devices by idiom with no model; version 1 required a model.

View Source
const SettingAuto = "auto"

SettingAuto is the setting that lets the Selector choose the level from the device and its frame times.

Variables

This section is empty.

Functions

func EncodeConfig

func EncodeConfig(c Config) ([]byte, error)

EncodeConfig validates c and writes it as deterministic 2-space YAML in field order, so a file read by ParseConfig and written back is unchanged.

func NormalizeSetting

func NormalizeSetting(s string) (string, error)

NormalizeSetting returns the canonical form of a player's quality setting: "auto" for s empty or "auto", or the name of the level s names, ignoring case and surrounding space. It returns an error for anything else.

Types

type Adapt

type Adapt struct {
	// Off keeps the starting level for the whole run, ignoring frame times.
	Off bool `yaml:"off,omitempty"`
	// TargetFPS is the frame rate to hold, in [3, 240]; below 3 fps a slow frame would be longer than the half second past which the Selector ignores frames, so it could never step down. DefaultTargetFPS when 0. More than a quarter of a window's frames running slower steps the level down.
	TargetFPS int `yaml:"target_fps,omitempty"`
	// WindowFrames is how many frames the Selector judges at a time, in [10, 3600]; DefaultWindowFrames when 0.
	WindowFrames int `yaml:"window_frames,omitempty"`
	// UpgradeWindows is how many windows in a row must run with nine in ten frames inside 60% of the target frame time before the level steps up, in [1, 100]; DefaultUpgradeWindows when 0.
	UpgradeWindows int `yaml:"upgrade_windows,omitempty"`
	// ResolutionSteps lists optional intermediate canvas scales in strictly descending order. Auto tries steps between the current scale and the next lower preset before changing level.
	ResolutionSteps *ResolutionSteps `yaml:"resolution_steps,omitempty"`
}

Adapt controls how the Selector moves the level from measured frame times. Zero fields take the defaults.

type Config

type Config struct {
	// Version is the schema version; it must be FormatVersion.
	Version int `yaml:"version"`
	// Presets holds the preset for each level.
	Presets Presets `yaml:"presets"`
	// Devices places matching devices at a starting level ahead of Classify's heuristic; the first rule that matches wins.
	Devices []DeviceRule `yaml:"devices,omitempty"`
	// Adapt controls how measured frame times move the level while the setting is auto.
	Adapt Adapt `yaml:"adapt,omitempty"`
}

Config is a game's quality configuration: its presets, the device rules that place devices ahead of Classify's heuristic, and how measured frame times move the level. It is written in YAML (see ParseConfig) and validated by Validate.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns the built-in configuration: DefaultPreset for each level, no device rules and the default adaptation.

func ParseConfig

func ParseConfig(data []byte) (Config, error)

ParseConfig decodes a quality YAML document and validates it. Unknown fields, a missing or other version, and trailing documents are refused.

func (Config) StartLevel

func (c Config) StartLevel(d Device) Level

StartLevel returns the level a device starts at: the level of the first device rule that matches it, else Classify's.

func (Config) Validate

func (c Config) Validate() error

Validate reports the first way c breaks the schema: a version other than FormatVersion, a preset scale outside (0, 1], a device rule with neither a model nor an idiom, an unknown OS, idiom or level, the same model, OS and idiom twice, or an adapt field out of range.

type Device

type Device struct {
	// OS is the operating system, such as core.OSAndroid; empty when unknown.
	OS core.OS
	// Idiom is the kind of device, such as core.IdiomPhone.
	Idiom core.Idiom
	// Model is the hardware model as core.Env.DeviceModel reports it, such as "iPhone15,2" or "Google Pixel 8"; empty when unknown.
	Model string
	// OSVersion is the operating system's version; on Android its Major is the API level.
	OSVersion core.OSVersion
	// CPUs is how many logical CPUs the process can use; 0 when unknown.
	CPUs int
	// GPU is the capabilities of the game's gpu.Device (Device.Capabilities), nil when unknown; Classify starts any device at Low whose GPU lacks compute or compressed texture formats.
	GPU *gpu.DeviceCapabilities
}

Device describes the hardware a game runs on, as far as Classify needs it.

func DeviceFromEnv

func DeviceFromEnv(env *core.Env) Device

DeviceFromEnv returns the Device env describes, with CPUs from runtime.NumCPU, or 0 on js/wasm, where it is always 1 and says nothing. It leaves GPU nil: a game whose gpu.View gets a device in OnReady uses DeviceFromView, and one that gets a device another way sets GPU from Device.Capabilities.

func DeviceFromView

func DeviceFromView(env *core.Env, dev *gpu.Device) Device

DeviceFromView returns the Device env describes, with GPU set from the capabilities of dev, the device a gpu.View's OnReady callback receives. It returns DeviceFromEnv(env) when dev is nil.

type DeviceRule

type DeviceRule struct {
	// Model is the start of core.Env.DeviceModel to match, such as "Google Pixel 8" or "iPhone12,"; empty matches any model, which needs an Idiom.
	Model string `yaml:"model,omitempty"`
	// OS limits the rule to one operating system, such as "android" or "ios"; empty matches any.
	OS core.OS `yaml:"os,omitempty"`
	// Idiom limits the rule to one kind of device, such as "phone" or "tablet"; IdiomAny matches any.
	Idiom Idiom `yaml:"idiom,omitempty"`
	// Level is the level matching devices start at.
	Level Level `yaml:"level"`
}

DeviceRule starts every device that matches at Level: whose model begins with Model when set, whose OS is OS when set, and whose idiom is Idiom when set. A rule must set Model or Idiom.

func (DeviceRule) Matches

func (r DeviceRule) Matches(d Device) bool

Matches reports whether d matches r: its model starts with r.Model, ignoring case, when r.Model is set; its OS is r.OS when set; and its idiom is r.Idiom when set. A rule with neither a model nor an idiom matches nothing.

type Idiom

type Idiom string

Idiom is the kind of device a DeviceRule matches: a phone, tablet, desktop or Mac, TV or watch, or IdiomAny for every kind. It is written in YAML as "phone", "tablet", "desktop", "mac", "tv" or "watch".

const (
	// IdiomAny matches every kind of device.
	IdiomAny Idiom = ""
	// IdiomPhone matches phones.
	IdiomPhone Idiom = "phone"
	// IdiomTablet matches tablets.
	IdiomTablet Idiom = "tablet"
	// IdiomDesktop matches desktop windows and browsers with a mouse.
	IdiomDesktop Idiom = "desktop"
	// IdiomMac matches iPhone and iPad apps running on a Mac.
	IdiomMac Idiom = "mac"
	// IdiomTV matches televisions.
	IdiomTV Idiom = "tv"
	// IdiomWatch matches watches.
	IdiomWatch Idiom = "watch"
)

func (Idiom) Valid

func (i Idiom) Valid() bool

Valid reports whether i is IdiomAny or one of the idioms a rule can name.

type Level

type Level uint8

Level is a quality tier, from Low to High.

const (
	// Low is the tier for low-end phones and anything that cannot hold its frame rate higher.
	Low Level = iota
	// Medium is the tier for mid-range devices and for hardware the Selector cannot place.
	Medium
	// High is the tier for capable desktops, recent phones and tablets.
	High
)

func Classify

func Classify(d Device) Level

Classify returns the level a device starts at when no device rule places it.

Android starts Low, since NSGo reports neither its memory nor its GPU and core counts do not tell a budget phone from a flagship; measured frame times step it up. iPhones start High from the iPhone 13 (model iPhone14,x) on, Medium from the iPhone 11 (iPhone12,x) and Low before; iPads High from model iPad13,x on, Medium from iPad11,x and Low before. Desktops start High with 8 or more CPUs, Medium with 4 to 7 and Low with fewer. TVs and watches start Low. A device whose known GPU has no compute or no compressed texture formats starts Low on any OS; otherwise on the web phones start Low and tablets and desktops Medium. Anything unknown starts Medium.

func Levels

func Levels() []Level

Levels returns every level from Low to High.

func ParseLevel

func ParseLevel(s string) (Level, error)

ParseLevel returns the level named s ("low", "medium" or "high"), ignoring case and surrounding space.

func (Level) MarshalText

func (l Level) MarshalText() ([]byte, error)

MarshalText returns the level's name, so YAML and JSON write it as "low", "medium" or "high".

func (Level) String

func (l Level) String() string

String returns the level's name: "low", "medium" or "high".

func (*Level) UnmarshalText

func (l *Level) UnmarshalText(text []byte) error

UnmarshalText reads a level's name as ParseLevel does.

func (Level) Valid

func (l Level) Valid() bool

Valid reports whether l is Low, Medium or High.

type Preset

type Preset struct {
	// ResolutionScale is the preset's render scale in (0, 1]. Use Scale or ScaleSize for game-owned buffers and Selector.CanvasScale for an NSGo canvas.
	ResolutionScale float32 `yaml:"resolution_scale"`
	// ParticleScale scales particle budgets and burst counts, in (0, 1]. Read it through Particles.
	ParticleScale float32 `yaml:"particle_scale"`
	// AtlasScale is the sprite atlas scale in (0, 1] requested when loading atlases (such as through assets.WithAtlasScale); 0 defaults to 1 (full resolution) when omitted from YAML.
	AtlasScale float32 `yaml:"atlas_scale,omitempty"`
	// Effects turns on effects that only decorate the frame, such as screen flashes, parallax backdrops, post effects and trails.
	Effects bool `yaml:"effects"`
	// Shadows turns on shadow casting, such as lights2d's occluder clipping (lights2d.Scene.DisableShadows is its inverse).
	Shadows bool `yaml:"shadows"`
	// Sampling is how a reduced-resolution canvas is enlarged. It is "smooth" (also the default when omitted) or "nearest" for pixel art.
	Sampling string `yaml:"sampling,omitempty"`
	// SSR optionally overrides whether 3D screen-space reflections are allowed at this tier; when nil, AllowSSR follows Effects (disabled on Low, enabled on Medium and High).
	SSR *bool `yaml:"ssr,omitempty"`
	// AutoExposure optionally overrides whether 3D auto exposure is allowed at this tier; when nil, AllowAutoExposure follows Effects (disabled on Low, enabled on Medium and High).
	AutoExposure *bool `yaml:"auto_exposure,omitempty"`
}

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

func DefaultPreset

func DefaultPreset(l Level) Preset

DefaultPreset returns the built-in preset for l: Low renders at half resolution with a quarter of the particles, half-scale atlases and no effects or shadows, Medium at three quarters with 60% of the particles, full-scale atlases and effects, and High at full resolution with everything on. It returns the Medium preset for an invalid level.

func (Preset) AllowAutoExposure

func (p Preset) AllowAutoExposure() bool

AllowAutoExposure reports whether 3D auto exposure is allowed under p: *p.AutoExposure when explicitly configured, otherwise p.Effects (false for DefaultPreset(Low), true for Medium and High).

func (Preset) AllowSSR

func (p Preset) AllowSSR() bool

AllowSSR reports whether 3D screen-space reflections are allowed under p: *p.SSR when explicitly configured, otherwise p.Effects (false for DefaultPreset(Low), true for Medium and High).

func (Preset) Particles

func (p Preset) Particles(n int) int

Particles returns n scaled by ParticleScale and rounded, at least 1 when n is positive, so it can set a particles.Emitter's MaxParticles (where 0 means the default of 256) or a Burst's count. It returns n unchanged when ParticleScale is not a valid scale, and 0 when n is not positive.

func (Preset) Scale

func (p Preset) Scale(n int) int

Scale returns n, a pixel count, scaled by ResolutionScale and rounded, at least 1 when n is positive. It returns n unchanged when ResolutionScale is not a valid scale, and 0 when n is not positive.

func (Preset) ScaleSize

func (p Preset) ScaleSize(size core.Size) core.Size

ScaleSize returns size scaled by ResolutionScale, or size unchanged when ResolutionScale is not a valid scale.

func (Preset) Validate

func (p Preset) Validate() error

Validate reports an error when a scale is not finite or lies outside (0, 1].

type Presets

type Presets struct {
	// Low is the preset for Low.
	Low Preset `yaml:"low"`
	// Medium is the preset for Medium.
	Medium Preset `yaml:"medium"`
	// High is the preset for High.
	High Preset `yaml:"high"`
}

Presets holds one Preset per level.

func (Presets) For

func (p Presets) For(l Level) Preset

For returns the preset for l, or Medium's for an invalid level.

type ResolutionSteps

type ResolutionSteps []float32

ResolutionSteps is a sequence of strictly descending canvas scales in (0, 1].

type Selector

type Selector struct {
	// OnChange, when set, is called with the new level and its preset whenever the level changes, from Observe or SetSetting.
	OnChange func(Level, Preset)
	// OnCanvasChange, when set, receives the active canvas scale and sampling when either changes.
	OnCanvasChange func(float32, core.ImageSampling)
	// contains filtered or unexported fields
}

Selector chooses the quality level a game runs at: the level its Config gives the Device to start, moved by measured frame times while the setting is auto, or the level the player sets.

Feed it each frame's length with Observe, for example from game.Loop.FrameTime. While auto, it judges frames a window at a time. When more than a quarter run slower than the target it tries a configured intermediate canvas scale before stepping down a level. After Adapt.UpgradeWindows windows in a row with nine in ten frames inside 60% of the target frame time it can step up one level. It holds reduced canvas scales and avoids levels it stepped down from until the player resets auto.

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

func NewSelector

func NewSelector(cfg Config, d Device) (*Selector, error)

NewSelector returns a Selector for d that starts at cfg.StartLevel(d) with the setting auto. It returns an error when cfg is not valid.

func (*Selector) AtlasScale

func (s *Selector) AtlasScale() float32

AtlasScale returns the current preset's sprite atlas scale in (0, 1], or 1 when unset or invalid.

func (*Selector) Auto

func (s *Selector) Auto() bool

Auto reports whether the setting is auto, so frame times move the level.

func (*Selector) CanvasSampling

func (s *Selector) CanvasSampling() core.ImageSampling

CanvasSampling returns the current preset's canvas upscale sampling.

func (*Selector) CanvasScale

func (s *Selector) CanvasScale() float32

CanvasScale returns the active linear resolution scale for core.Canvas.

func (*Selector) Level

func (s *Selector) Level() Level

Level returns the current level.

func (*Selector) Observe

func (s *Selector) Observe(dt time.Duration) bool

Observe records one frame's length and reports whether it changed the level. A canvas-only change is reported through OnCanvasChange. Observe does nothing while the setting holds a fixed level or Config.Adapt.Off is set, and ignores lengths that are not positive or longer than half a second.

func (*Selector) Preset

func (s *Selector) Preset() Preset

Preset returns the current level's preset.

func (*Selector) SetSetting

func (s *Selector) SetSetting(setting string) error

SetSetting applies a player's setting as NormalizeSetting reads it: "auto" (or empty) returns to the starting level and lets frame times move it again, and a level's name holds that level. It returns an error, changing nothing, for anything else.

func (*Selector) Setting

func (s *Selector) Setting() string

Setting returns the setting to store in the player's settings: "auto" or the fixed level's name.

func (*Selector) StartLevel

func (s *Selector) StartLevel() Level

StartLevel returns the level the device started at, the one auto returns to.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL