diff --git a/README.en.md b/README.en.md index d4688e36..2b1c6b19 100644 --- a/README.en.md +++ b/README.en.md @@ -62,8 +62,8 @@ modavd [--root ] [--json] [--quiet] [--verbose] [args] | --- | --- | | `list` | All instances and their status | | `info ` / `status ` | Details of one instance / its status | -| `create [--index N] [--title T] [--memory 6G] [--cpu N] [--data-gb auto\|N] [--fps 1-60] [--resolution 1080\|720] [--dpi auto\|N] [--orientation landscape\|portrait] [--no-bridge] [--timeout 1200]`, `create --resume N` | Create an instance (automatic data disk by default, see below), then start it once in the background, headless, to finish initialization, and shut it down (see below). The arm64 execution bridge is included by default; `--no-bridge` records that this instance does not want the bridge, so it is not installed on later starts either. New instances never get the Google Play Store; add it afterwards with `playstore install`. `--resume N` redoes the initialization of an instance whose creation failed | -| `set [--title T] [--memory M] [--cpu N] [--fps F] [--resolution 1080\|720] [--dpi auto\|N] [--orientation landscape\|portrait] [--data-gb auto\|N] [--diagnostics on\|off] [--sound on\|off] [--app-keepalive on\|off] [--boss-key combination\|none]` | Change settings. Diagnostics and the boss key apply immediately; other settings take effect at the next start. `--data-gb auto` makes the data disk automatic, `--data-gb N` gives it a fixed size (see below); the size can only be increased, and game data is untouched: the emulator (from 0.36) grows the disk image at start and grows the file system online after boot. A disk created before 0.36 at 16 GB or smaller can only be grown to just below the next backup group (a 16 GB disk to about 30 GB). `--sound on` gives this instance sound from its next start (windowed and headless, at some extra CPU); the default `off` boots without a sound card; stored as `instances..sound` in `mas-avd.json`. `--boss-key` is this instance's boss key (see the ModAVD.exe manager section), for example `Ctrl+Alt+Shift+1`; `none` means no boss key; Windows only. | +| `create [--index N] [--title T] [--memory 6G] [--cpu N] [--data-gb auto\|N] [--fps 15\|30\|60] [--resolution 1080\|720] [--dpi auto\|N] [--orientation landscape\|portrait] [--no-bridge] [--timeout 1200]`, `create --resume N` | Create an instance (automatic data disk by default, see below), then start it once in the background, headless, to finish initialization, and shut it down (see below). The arm64 execution bridge is included by default; `--no-bridge` records that this instance does not want the bridge, so it is not installed on later starts either. New instances never get the Google Play Store; add it afterwards with `playstore install`. `--resume N` redoes the initialization of an instance whose creation failed | +| `set [--title T] [--memory M] [--cpu N] [--fps 15\|30\|60] [--resolution 1080\|720] [--dpi auto\|N] [--orientation landscape\|portrait] [--data-gb auto\|N] [--diagnostics on\|off] [--sound on\|off] [--app-keepalive on\|off] [--boss-key combination\|none]` | Change settings. Diagnostics and the boss key apply immediately; other settings take effect at the next start. `--data-gb auto` makes the data disk automatic, `--data-gb N` gives it a fixed size (see below); the size can only be increased, and game data is untouched: the emulator (from 0.36) grows the disk image at start and grows the file system online after boot. A disk created before 0.36 at 16 GB or smaller can only be grown to just below the next backup group (a 16 GB disk to about 30 GB). `--sound on` gives this instance sound from its next start (windowed and headless, at some extra CPU); the default `off` boots without a sound card; stored as `instances..sound` in `mas-avd.json`. `--boss-key` is this instance's boss key (see the ModAVD.exe manager section), for example `Ctrl+Alt+Shift+1`; `none` means no boss key; Windows only. | | `proxy [on\|off\|test] [--server URL\|auto] [--add PKG] [--remove PKG] [--apps PKG]` | Per-app proxy: the listed apps go through a proxy, the others direct (see below) | | `delete --yes` | Delete a stopped instance, together with its game data | | `clone [--title T]` | Copy a stopped instance whole into a new one (games, logins and settings included): the new one takes the smallest free index and its ports, everything else follows the source. The data disk is copied whole, so the two do not affect each other; without enough free space the command fails (`precheck_failed`) and copies nothing, and a failed or canceled copy is deleted. Both have the same Android device IDs (Android ID, GSF ID) | @@ -87,7 +87,7 @@ The instance setting **Keep background apps** takes effect at the next boot. Wit Apple Silicon macOS supports `report-config` and `collect-info`, including hardware, macOS, HVF, Metal and component versions. Game lists are queried only through an existing private ADB server and running instances with verified ownership; no service is started. The package contains an allowlist of local instance settings and at most eight emulator logs, capped at 2 MiB each and 20 MiB of text in total. Common credential fields, paths and device identifiers are filtered. macOS does not collect screenshots, system dumps or other applications' logs. Review the package before sharing it. Clipboard copying and Finder reveal can be disabled with `--no-clipboard` and `--no-explorer`. -- Write `` as `3` or `mas_3` (0-9, except 5). Memory is written as `6144`, `6144M` or `6G`, with only five tiers: 3 / 4 / 5 / 6 / 8 GB. Cores are 2 / 4 / 6, and the frame rate is any whole number from 1 to 60 (default 60). +- Write `` as `3` or `mas_3` (0-9, except 5). Memory is written as `6144`, `6144M` or `6G`, with only five tiers: 3 / 4 / 5 / 6 / 8 GB. Cores are 2 / 4 / 6, and the frame rate has three steps, 15 / 30 / 60 (default 60; 30 for games locked at 30 fps, the most even frame times; 15 only for idling, the whole system runs at 15 fps). Another frame rate given on the command line, over MCP or the HTTP API is not refused: it goes to the nearest step below (31-59 becomes 30, 16-29 becomes 15, 1-14 becomes 15, above 60 becomes 60) and the output says so. An instance set to another value earlier is changed the same way at its next start, with a line in the log. - Root folder: `--root`; if not given, the environment variable `MODAVD_ROOT`; otherwise the folder containing `modavd.exe`, or its parent. - From 0.3.0 there is no `restart`: `stop`, then `start`. An old call gets a usage error (exit code 2) that says so. diff --git a/README.md b/README.md index c7dffff8..1e45d511 100644 --- a/README.md +++ b/README.md @@ -62,8 +62,8 @@ modavd [--root <目录>] [--json] [--quiet] [--verbose] <命令> [参数] | --- | --- | | `list` | 全部实例和状态 | | `info ` / `status ` | 一台实例的详细信息 / 状态 | -| `create [--index N] [--title T] [--memory 6G] [--cpu N] [--data-gb auto\|N] [--fps 1-60] [--resolution 1080\|720] [--dpi auto\|N] [--orientation landscape\|portrait] [--no-bridge] [--timeout 1200]`、`create --resume N` | 新建(数据盘默认自动扩盘,见下),并在后台无头开机一次把初始化做完再关机(见下)。默认带 arm64 执行桥;`--no-bridge` 记下这台不要桥,以后开机也不装。新建的实例不带 Google Play 商店,要的话建好后用 `playstore install`。`--resume N` 重做新建失败的那台的初始化 | -| `set [--title T] [--memory M] [--cpu N] [--fps F] [--resolution 1080\|720] [--dpi auto\|N] [--orientation landscape\|portrait] [--data-gb auto\|N] [--diagnostics on\|off] [--sound on\|off] [--app-keepalive on\|off] [--boss-key 组合\|none]` | 修改;诊断模式和老板键立即生效,其余设置下次开机生效。`--data-gb auto` 改成自动扩盘,`--data-gb N` 改成指定大小(见下);大小只能改大,游戏数据不动:模拟器(0.36 起)开机时扩磁盘镜像,开机后在线扩文件系统。0.36 之前按 16 GB 及以下建的盘只能扩到下一个备份组之前(16 GB 约到 30 GB)。`--sound on` 让这台下次开机起有声音(带窗口和无头都是,会多占一些 CPU),默认 `off` 不带声卡;记在 `mas-avd.json` 的 `instances..sound`。`--boss-key` 是这台的老板键(见「管理器 ModAVD.exe」一节),比如 `Ctrl+Alt+Shift+1`,`none` 是不要,只有 Windows。 | +| `create [--index N] [--title T] [--memory 6G] [--cpu N] [--data-gb auto\|N] [--fps 15\|30\|60] [--resolution 1080\|720] [--dpi auto\|N] [--orientation landscape\|portrait] [--no-bridge] [--timeout 1200]`、`create --resume N` | 新建(数据盘默认自动扩盘,见下),并在后台无头开机一次把初始化做完再关机(见下)。默认带 arm64 执行桥;`--no-bridge` 记下这台不要桥,以后开机也不装。新建的实例不带 Google Play 商店,要的话建好后用 `playstore install`。`--resume N` 重做新建失败的那台的初始化 | +| `set [--title T] [--memory M] [--cpu N] [--fps 15\|30\|60] [--resolution 1080\|720] [--dpi auto\|N] [--orientation landscape\|portrait] [--data-gb auto\|N] [--diagnostics on\|off] [--sound on\|off] [--app-keepalive on\|off] [--boss-key 组合\|none]` | 修改;诊断模式和老板键立即生效,其余设置下次开机生效。`--data-gb auto` 改成自动扩盘,`--data-gb N` 改成指定大小(见下);大小只能改大,游戏数据不动:模拟器(0.36 起)开机时扩磁盘镜像,开机后在线扩文件系统。0.36 之前按 16 GB 及以下建的盘只能扩到下一个备份组之前(16 GB 约到 30 GB)。`--sound on` 让这台下次开机起有声音(带窗口和无头都是,会多占一些 CPU),默认 `off` 不带声卡;记在 `mas-avd.json` 的 `instances..sound`。`--boss-key` 是这台的老板键(见「管理器 ModAVD.exe」一节),比如 `Ctrl+Alt+Shift+1`,`none` 是不要,只有 Windows。 | | `proxy [on\|off\|test] [--server URL\|auto] [--add 包名] [--remove 包名] [--apps 包名]` | 按应用走代理:名单里的应用走代理,其余直连(见下) | | `delete --yes` | 删除已关机的实例,连同游戏数据 | | `clone [--title T]` | 把已关机的实例整份复制成一台新实例(游戏、登录状态、设置都带上):新实例用最小的空闲编号和它的端口,其余设置照源实例;数据盘整份复制,两台互不影响,可用空间不够时报错(`precheck_failed`)、什么都不复制;失败或取消时复制到一半的会删掉。两台的安卓设备标识(Android ID、GSF ID)相同 | @@ -89,7 +89,7 @@ modavd [--root <目录>] [--json] [--quiet] [--verbose] <命令> [参数] Apple Silicon macOS 支持 `report-config` 和 `collect-info`:读取硬件、macOS、HVF、Metal 和组件版本;游戏列表只向归属已确认的运行实例与现有私有 ADB 查询,不启动服务。问题包只收本目录的实例配置白名单和最多 8 份模拟器日志,每份最多 2 MiB、总文本最多 20 MiB,过滤常见凭据字段、路径和设备标识。macOS 不收截图、系统转储或其他应用日志;分享前请检查问题包。默认复制配置到剪贴板、用 Finder 显示问题包,自动化可用 `--no-clipboard` / `--no-explorer`。 -- `` 写成 `3` 或 `mas_3`(0–9,5 除外);内存写成 `6144`、`6144M` 或 `6G`,只有 3 / 4 / 5 / 6 / 8 GB 五档,核数 2 / 4 / 6,帧率 1–60 的整数(默认 60)。 +- `` 写成 `3` 或 `mas_3`(0–9,5 除外);内存写成 `6144`、`6144M` 或 `6G`,只有 3 / 4 / 5 / 6 / 8 GB 五档,核数 2 / 4 / 6,帧率 15 / 30 / 60 三档(默认 60;30 给锁 30 帧的游戏,帧间隔最匀;15 只适合纯挂机,整个系统都是 15 帧)。命令行、MCP、HTTP 接口给了别的帧率不报错,落到往下最近的一档(31–59 取 30,16–29 取 15,1–14 取 15,高于 60 取 60),并在输出里说明;以前设成别的值的实例,下次开机时自动改成这样取到的一档并记一行日志。 - 根目录:`--root`,没给就用环境变量 `MODAVD_ROOT`,再没有就用 `modavd.exe` 所在目录或它的上一级。 - 0.3.0 起没有 `restart`:先 `stop` 再 `start`。旧的调用报用法错误(退出码 2),提示改用这两步。 diff --git a/changelog.d/286-fps-steps.change.md b/changelog.d/286-fps-steps.change.md new file mode 100644 index 00000000..f34dcf48 --- /dev/null +++ b/changelog.d/286-fps-steps.change.md @@ -0,0 +1,2 @@ +帧率只有 15 / 30 / 60 三档,原来设的其他值开机时自动调整(比如 36 调成 30) (ModAVD/ModAVD#286) +Frame rate has three steps, 15 / 30 / 60; another value set earlier is changed at the next start (36 becomes 30) diff --git a/internal/avd/avd.go b/internal/avd/avd.go index 11acfadc..739730ac 100644 --- a/internal/avd/avd.go +++ b/internal/avd/avd.go @@ -32,6 +32,9 @@ var ( DPIChoices = []int{160, 240, 280, 320, 400, 480} // OrientationChoices: landscape (the default; what AUTO-MAS and MAA expect) or portrait (the same wide canvas, turned). OrientationChoices = []string{OrientationLandscape, OrientationPortrait} + // FPSChoices are the frame rates an instance can have (ModAVD/ModAVD#286): 60 (the default), 30 for games locked + // at 30 (every frame shown for the same time; at 36 or 45 they alternate one and two refreshes), 15 for idling. + FPSChoices = []int{60, 30, 15} ) const ( @@ -46,7 +49,8 @@ const ( DefaultMemoryMB = 6144 DefaultCPU = 6 DefaultFPS = 60 - // Any whole frame rate in MinFPS..MaxFPS (ModAVD#180); written as hw.lcd.vsync. + // The frame rate (hw.lcd.vsync, the display's refresh rate) is one of FPSChoices (ModAVD/ModAVD#286; 1–60 since + // ModAVD#180 before that). Any other value from MinFPS up is taken to a step (SnapFPS), above MaxFPS to MaxFPS. MinFPS = 1 MaxFPS = 60 // AutoDataPartitionGB is the data partition of an instance whose data disk grows by itself (自动扩盘, the default, @@ -316,11 +320,13 @@ func parseRAMSize(raw string) (int, bool) { func (in *Instance) MemoryMB() (int, bool) { return parseRAMSize(in.Config.Value("hw.ramSize")) } // 4096 / 4096M / 4096MB / 4G func (in *Instance) CPU() (int, bool) { return intOrNone(in.Config.Value("hw.cpu.ncore")) } // hw.cpu.ncore -// FPS is hw.lcd.vsync, DefaultFPS when absent / bad (and when 0: AUTO-MAS writes `or DEFAULT_FPS`); the emulator -// boots at 60 Hz without the key. -func (in *Instance) FPS() int { - if v, ok := intOrNone(in.Config.Value("hw.lcd.vsync")); ok && v != 0 { - return v +// FPS is hw.lcd.vsync taken to its step (SnapFPS; the next boot writes that, ApplyFPS), DefaultFPS when absent / bad / +// below 1 (and when 0: AUTO-MAS writes `or DEFAULT_FPS`); the emulator boots at 60 Hz without the key. +func (in *Instance) FPS() int { return fpsFor(in.Config) } + +func fpsFor(cfg *Ini) int { + if v, ok := intOrNone(cfg.Value("hw.lcd.vsync")); ok && v >= MinFPS { + return SnapFPS(v) } return DefaultFPS } @@ -605,16 +611,36 @@ func ValidateOptions(memoryMB, cpu, dataGB *int) (int, int, int, error) { return memory, cores, data, nil } -// ValidateFPS: nil means DefaultFPS; anything outside MinFPS..MaxFPS is errs.InvalidArgument. -func ValidateFPS(fps *int) (int, error) { - value := DefaultFPS +// SnapFPS is the step of FPSChoices a frame rate of at least MinFPS falls to (ModAVD/ModAVD#286): down to the nearest +// step (31–59 -> 30, 16–29 -> 15), 1–14 up to 15, above MaxFPS MaxFPS. +func SnapFPS(v int) int { + switch { + case v >= 60: + return 60 + case v >= 30: + return 30 + } + return 15 +} + +// FPSAdjusted is the note said when a frame rate was moved to a step: "帧率 36 已调整为 30(只有 15 / 30 / 60 三档)". +func FPSAdjusted(from, to int) string { + return fmt.Sprintf("帧率 %d 已调整为 %d(只有 15 / 30 / 60 三档)", from, to) +} + +// ValidateFPS: nil means DefaultFPS; below MinFPS is errs.InvalidArgument; any other value is taken to its step +// (SnapFPS) without an error, so a tool that still writes another frame rate keeps working. adjusted: the value given +// was not one of FPSChoices. +func ValidateFPS(fps *int) (value int, adjusted bool, err error) { + value = DefaultFPS if fps != nil { value = *fps } - if value < MinFPS || value > MaxFPS { - return 0, errs.Newf(errs.InvalidArgument, "帧率只能在 %d–%d 之间", MinFPS, MaxFPS) + if value < MinFPS { + return 0, false, errs.Newf(errs.InvalidArgument, "帧率只能是 15、30 或 60") } - return value, nil + snapped := SnapFPS(value) + return snapped, snapped != value, nil } // ValidateResolution defaults new instances to 1080p; DPI is part of the preset. @@ -705,7 +731,7 @@ func Create(r *root.Root, i int, opt CreateOptions) (*Instance, error) { if err != nil { return nil, err } - fps, err := ValidateFPS(&opt.FPS) + fps, _, err := ValidateFPS(&opt.FPS) if err != nil { return nil, err } @@ -1009,7 +1035,7 @@ func Update(r *root.Root, i int, opt UpdateOptions) (map[string]any, error) { } var fps int if opt.FPS != nil { - if fps, err = ValidateFPS(opt.FPS); err != nil { + if fps, _, err = ValidateFPS(opt.FPS); err != nil { return nil, err } } @@ -1323,3 +1349,36 @@ func ApplyDisplay(r *root.Root, i int) (bool, error) { } return true, nil } + +// ApplyFPS takes a frame rate that is not one of FPSChoices (an instance from before ModAVD/ModAVD#286 set to 36, or +// a tool that wrote config.ini itself) to its step (SnapFPS) in config.ini: from is the value found, to the one +// written, wrote whether it wrote. An absent, 0 or unreadable hw.lcd.vsync is left alone (the emulator boots at 60 +// Hz, FPS says DefaultFPS). Only while stopped. Under the instance's root.LockInstanceConfig, like Update. +func ApplyFPS(r *root.Root, i int) (from, to int, wrote bool, err error) { + l, noDir, err := lockInstance(r, i) + if err != nil { + return 0, 0, false, err + } + if noDir { + return 0, 0, false, configUnreadable(i, notFound(i)) + } + defer l.Unlock() + path := ConfigPath(r, i) + cfg, err := ReadIni(path) + if err != nil || cfg.Len() == 0 { + return 0, 0, false, configUnreadable(i, err) + } + v, ok := intOrNone(cfg.Value("hw.lcd.vsync")) + if !ok || v < MinFPS { + return v, DefaultFPS, false, nil + } + to = SnapFPS(v) + if to == v { + return v, v, false, nil + } + cfg.Set("hw.lcd.vsync", strconv.Itoa(to)) + if err := WriteIni(path, cfg); err != nil { + return v, to, false, err + } + return v, to, true, nil +} diff --git a/internal/avd/avd_test.go b/internal/avd/avd_test.go index 2e722a39..264f13cd 100644 --- a/internal/avd/avd_test.go +++ b/internal/avd/avd_test.go @@ -213,7 +213,7 @@ func goRun(r *root.Root, op refOp) (any, error) { if err != nil { return nil, err } - fps, err := ValidateFPS(optInt(op, "fps")) + fps, _, err := ValidateFPS(optInt(op, "fps")) if err != nil { return nil, err } @@ -257,7 +257,7 @@ func goRun(r *root.Root, op refOp) (any, error) { if err != nil { return nil, err } - f, err := ValidateFPS(optInt(op, "fps")) + f, _, err := ValidateFPS(optInt(op, "fps")) if err != nil { return nil, err } @@ -365,13 +365,18 @@ func TestCreateUpdateDeleteMatchPython(t *testing.T) { {"op": "create", "index": 3, "data_gb": 15, "created_at": "x", "same_error": true}, {"op": "create", "index": 3, "data_gb": 513, "created_at": "x", "same_error": true}, {"op": "create", "index": 3, "fps": 0, "created_at": "x", "same_error": true}, - {"op": "create", "index": 3, "fps": 61, "created_at": "x", "same_error": true}, + {"op": "create", "index": 3, "fps": -1, "created_at": "x", "same_error": true}, + // ModAVD/ModAVD#286: not refused, taken to a step + {"op": "create", "index": 3, "fps": 61, "created_at": "2026-10-16T07:41:43"}, + {"op": "create", "index": 4, "fps": 36, "created_at": "2026-10-16T07:41:44"}, + {"op": "create", "index": 6, "fps": 14, "created_at": "2026-10-16T07:41:45"}, {"op": "list"}, {"op": "update", "index": 1, "changes": map[string]any{"memoryMb": 4096}}, {"op": "update", "index": 0, "changes": map[string]any{"cpu": 4, "fps": 30}}, {"op": "update", "index": 9, "changes": map[string]any{}}, {"op": "update", "index": 7, "changes": map[string]any{"cpu": 4}, "same_error": true}, - {"op": "update", "index": 0, "changes": map[string]any{"fps": 61}, "same_error": true}, + {"op": "update", "index": 0, "changes": map[string]any{"fps": 61}}, + {"op": "update", "index": 0, "changes": map[string]any{"fps": 0}, "same_error": true}, {"op": "update", "index": 9, "changes": map[string]any{"fps": 45}}, {"op": "update", "index": 0, "changes": map[string]any{"cpu": 3}, "same_error": true}, {"op": "update", "index": 0, "changes": map[string]any{"memoryMb": 8192}, "same_error": true}, @@ -785,18 +790,24 @@ func TestValidate(t *testing.T) { if _, _, d, err := ValidateOptions(nil, nil, ip(512)); err != nil || d != 512 { t.Error("512 GB") } - if f, err := ValidateFPS(nil); err != nil || f != 60 { + if f, adjusted, err := ValidateFPS(nil); err != nil || f != 60 || adjusted { t.Error("fps default") } - for _, v := range []int{1, 15, 30, 45, 60} { - if f, err := ValidateFPS(ip(v)); err != nil || f != v { - t.Errorf("fps %d: %d %v", v, f, err) + // ModAVD/ModAVD#286: every value from 1 up is taken to a step, adjusted when it was not one already + for v, want := range map[int]int{1: 15, 14: 15, 15: 15, 16: 15, 29: 15, 30: 30, 31: 30, 36: 30, 45: 30, 59: 30, + 60: 60, 61: 60, 120: 60} { + f, adjusted, err := ValidateFPS(ip(v)) + if err != nil || f != want || adjusted != (v != want) { + t.Errorf("fps %d: %d adjusted %v %v, want %d", v, f, adjusted, err, want) + } + if SnapFPS(v) != want { + t.Errorf("SnapFPS(%d) = %d, want %d", v, SnapFPS(v), want) } } - for _, v := range []int{0, 61, -1} { - _, err = ValidateFPS(ip(v)) + for _, v := range []int{0, -1} { + _, _, err = ValidateFPS(ip(v)) wantCode(t, err, errs.InvalidArgument) - if err.Error() != "帧率只能在 1–60 之间" { + if err.Error() != "帧率只能是 15、30 或 60" { t.Errorf("fps %d message %q", v, err.Error()) } } @@ -878,7 +889,7 @@ func TestCreateRefusals(t *testing.T) { _, err := Create(r, 0, CreateOptions{}) wantCode(t, err, errs.InvalidArgument) bad := ok - for _, fps := range []int{0, 61} { // 0 = unset in CreateOptions; Create never defaults it + for _, fps := range []int{0, -1} { // 0 = unset in CreateOptions; Create never defaults it bad.FPS = fps _, err = Create(r, 0, bad) wantCode(t, err, errs.InvalidArgument) @@ -1238,6 +1249,61 @@ func TestApplyDisplay(t *testing.T) { } } +// ModAVD/ModAVD#286: a frame rate from before the three steps is taken to its step in config.ini before the boot; +// one of the steps, and an absent / 0 / unreadable one (the emulator boots at 60), are left alone. +func TestApplyFPS(t *testing.T) { + r := newRoot(t) + if _, _, _, err := ApplyFPS(r, 0); errs.CodeOf(err) != errs.NotFound { + t.Fatalf("no instance: %v", err) + } + for _, c := range []struct { + vsync string // "" = no key + from, to int + wrote bool + }{ + {"36", 36, 30, true}, {"45", 45, 30, true}, {"59", 59, 30, true}, {"31", 31, 30, true}, + {"29", 29, 15, true}, {"16", 16, 15, true}, {"14", 14, 15, true}, {"1", 1, 15, true}, + {"61", 61, 60, true}, {"120", 120, 60, true}, + {"60", 60, 60, false}, {"30", 30, 30, false}, {"15", 15, 15, false}, + {"0", 0, 60, false}, {"", 0, 60, false}, {"abc", 0, 60, false}, {"-5", -5, 60, false}, + } { + cfg := "hw.lcd.width=1280\r\n" + if c.vsync != "" { + cfg += "hw.lcd.vsync=" + c.vsync + "\r\n" + } + cfg += "x=1\r\n" + writeFile(t, ConfigPath(r, 0), []byte(cfg)) + from, to, wrote, err := ApplyFPS(r, 0) + if err != nil || from != c.from || to != c.to || wrote != c.wrote { + t.Errorf("%q: %d -> %d wrote %v %v", c.vsync, from, to, wrote, err) + continue + } + want := cfg + if c.wrote { + // in place: the key keeps its line + want = "hw.lcd.width=1280\r\nhw.lcd.vsync=" + strconv.Itoa(c.to) + "\r\nx=1\r\n" + } + if got := string(readFile(t, ConfigPath(r, 0))); got != want { + t.Errorf("%q: config %q, want %q", c.vsync, got, want) + } + cfgNow, err := ReadIni(ConfigPath(r, 0)) + if err != nil { + t.Fatal(err) + } + if got := (&Instance{Config: cfgNow}).FPS(); got != c.to { + t.Errorf("%q: FPS %d after ApplyFPS, want %d", c.vsync, got, c.to) + } + if c.wrote { + if _, _, again, err := ApplyFPS(r, 0); err != nil || again { + t.Errorf("%q: second ApplyFPS wrote %v %v", c.vsync, again, err) + } + } + } + if got := FPSAdjusted(36, 30); got != "帧率 36 已调整为 30(只有 15 / 30 / 60 三档)" { + t.Errorf("note %q", got) + } +} + func TestCreateKeepsOtherMetadata(t *testing.T) { r := newRoot(t) writeFile(t, r.MetadataPath(), []byte("{\"a\": 1, \"instances\": {\"2\": {\"x\": true}}, \"b\": [1e3]}")) diff --git a/internal/avd/testdata/instances_ref.py b/internal/avd/testdata/instances_ref.py index c70cbbd3..38ddb22b 100644 --- a/internal/avd/testdata/instances_ref.py +++ b/internal/avd/testdata/instances_ref.py @@ -3,8 +3,9 @@ # so it runs without the app package. Keep it a copy: when AUTO-MAS changes, copy again. # # Intentional differences: created_at is injected for byte comparisons. ModAVD#100 -# defaults new instances to 1080p and preserves either preset on existing instances. ModAVD#180 takes any -# frame rate in 1–60 instead of 30 / 60. ModAVD#153: no data partition size given is 自动扩盘 (256 GB, +# defaults new instances to 1080p and preserves either preset on existing instances. ModAVD#180 took any +# frame rate in 1–60 instead of 30 / 60; ModAVD/ModAVD#286 takes every one of those to 15 / 30 / 60 (down to the +# nearest step, 1–14 up to 15, above 60 to 60), also when reading config.ini. ModAVD#153: no data partition size given is 自动扩盘 (256 GB, # dataDiskMode "auto"); a given size is dataDiskMode "manual". # # python -I instances_ref.py @@ -38,7 +39,7 @@ DEFAULT_DATA_PARTITION_GB = 256 DATA_PARTITION_RANGE_GB = (16, 512) SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_DENSITY = 1920, 1080, 280 -FPS_RANGE = (1, 60) +MIN_FPS = 1 DEFAULT_FPS = 60 @@ -168,7 +169,8 @@ def cpu(self): @property def fps(self): - return _int_or_none(self.config.get("hw.lcd.vsync")) or DEFAULT_FPS + value = _int_or_none(self.config.get("hw.lcd.vsync")) + return snap_fps(value) if value is not None and value >= MIN_FPS else DEFAULT_FPS @property def data_partition_gb(self): @@ -343,12 +345,15 @@ def validate_options(memory_mb, cpu, data_partition_gb): return memory, cores, data_gb +def snap_fps(value): + return 60 if value >= 60 else 30 if value >= 30 else 15 + + def validate_fps(fps): value = DEFAULT_FPS if fps is None else int(fps) - low, high = FPS_RANGE - if not low <= value <= high: - raise ValueError(f"帧率只能在 {low}–{high} 之间") - return value + if value < MIN_FPS: + raise ValueError("帧率只能是 15、30 或 60") + return snap_fps(value) def create_instance_files( @@ -447,7 +452,10 @@ def write_instance_settings(root, idx, changes): config_changes["hw.lcd.vsync"] = str(fps) write_instance_config(root, idx, config_changes) update_instance_meta(root, idx, memoryMb=memory) - return {k: v for k, v in changes.items() if k in ("cpu", "memoryMb", "fps")} + applied = {k: v for k, v in changes.items() if k in ("cpu", "memoryMb", "fps")} + if fps is not None: + applied["fps"] = fps + return applied # ---- driver ---------------------------------------------------------------------------------------------------- diff --git a/internal/cli/cli.go b/internal/cli/cli.go index eff721cf..38420118 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -10,8 +10,8 @@ // list emu.ListResult // info emu.InstanceInfo // status StatusResult {index,name,status,running,booted,window,busy,pid,creation,creation_error,creation_log,creation_progress,setup_step,setup_progress,setup_unfinished,serial,adb_address,ports,data_space} -// create [--index N] [--title T] [--memory M] [--cpu N] [--data-gb auto|N] [--fps 1-60] emu.InstanceInfo -// set [--title T] [--memory M] [--cpu N] [--fps F] emu.UpdateResult (at least one option) +// create [--index N] [--title T] [--memory M] [--cpu N] [--data-gb auto|N] [--fps 15|30|60] emu.InstanceInfo +// set [--title T] [--memory M] [--cpu N] [--fps 15|30|60] emu.UpdateResult (at least one option) // proxy [on|off] [--server URL|auto] [--add P] [--remove P] [--apps P] emu.AppProxyResult // proxy test emu.AppProxyTestResult // delete --yes emu.DeleteResult (without --yes: usage error) diff --git a/internal/cli/commands.go b/internal/cli/commands.go index 06597a2a..1feb2993 100644 --- a/internal/cli/commands.go +++ b/internal/cli/commands.go @@ -92,7 +92,7 @@ var ( optResolution = flagSpec{"resolution", kindInt, "", "分辨率:1080 / 720,DPI 随档位切换;新建默认 1080"} optDPI = flagSpec{"dpi", kindString, "auto|N", "DPI:auto 跟随分辨率(720p 240、1080p 280,默认),或 160 / 240 / 280 / 320 / 400 / 480"} optOrientation = flagSpec{"orientation", kindString, "landscape|portrait", "方向:landscape 横屏(默认),portrait 竖屏(MAA 等自动化任务要横屏)"} - optFPS = flagSpec{"fps", kindInt, "F", "帧率:1–60 的整数,默认 60"} + optFPS = flagSpec{"fps", kindInt, "F", "帧率:15、30 或 60,默认 60;别的值落到往下最近的一档(1–14 取 15,高于 60 取 60)"} optLanguage = flagSpec{"language", kindString, "host|preserve|语言", "Windows:host 按宿主界面语言设置一次,preserve 保持安卓语言,或指定 zh-CN、en-US 等语言"} optTimeZone = flagSpec{"timezone", kindString, "host|preserve|IANA", "Windows:host 每次冷启动跟随宿主,preserve 沿用原行为,或指定 Asia/Shanghai、Etc/UTC 等 IANA 时区"} optDiagnostics = flagSpec{"diagnostics", kindString, "on|off", "诊断模式:即时增加日志保留;off 立即删回平常规则"} @@ -208,7 +208,7 @@ func init() { run: runStatus, human: humanOf(formatStatus), }, { - name: "create", args: "[--index N | --count N] [--title T] [--memory 6G] [--cpu N] [--data-gb auto|N] [--fps 1-60] [--resolution 1080|720] [--dpi auto|N] [--orientation landscape|portrait] [--language host|preserve|语言] [--timezone host|preserve|IANA] [--no-bridge] [--timeout 1200] | --resume N", + name: "create", args: "[--index N | --count N] [--title T] [--memory 6G] [--cpu N] [--data-gb auto|N] [--fps 15|30|60] [--resolution 1080|720] [--dpi auto|N] [--orientation landscape|portrait] [--language host|preserve|语言] [--timezone host|preserve|IANA] [--no-bridge] [--timeout 1200] | --resume N", summary: "新建一台实例,后台开机做完初始化后关机", details: "不给的选项用默认值:内存 6 GB、6 核、数据盘自动扩盘、60 帧、1080p(1920×1080 / DPI 280)。内存和核数只能取列出的档位,不会自动凑整。" + dataDiskHelp + @@ -225,7 +225,7 @@ func init() { run: runCreate, human: humanCreate, exit: exitBatch, }, { - name: "set", args: " [--title T] [--memory M] [--cpu N] [--fps F] [--resolution 1080|720] [--dpi auto|N] [--orientation landscape|portrait] [--data-gb auto|N] [--language host|preserve|语言] [--timezone host|preserve|IANA] [--diagnostics on|off] [--sound on|off] [--app-keepalive on|off] [--boss-key 组合|none]", + name: "set", args: " [--title T] [--memory M] [--cpu N] [--fps 15|30|60] [--resolution 1080|720] [--dpi auto|N] [--orientation landscape|portrait] [--data-gb auto|N] [--language host|preserve|语言] [--timezone host|preserve|IANA] [--diagnostics on|off] [--sound on|off] [--app-keepalive on|off] [--boss-key 组合|none]", summary: "修改实例设置、诊断模式和老板键", details: "至少给一个选项。诊断模式和老板键立即生效;其它改动下次开机生效。诊断模式最多多用约 4 GiB 磁盘和 48 MiB 客体内存,日志可能含账号信息,只存本机;关闭立即删回平常保留规则。" + dataDiskHelp + "数据盘只能改大,游戏数据不动:下次开机时模拟器(0.36 起)扩大磁盘镜像,开机后再在线扩大文件系统。" + diff --git a/internal/cli/format_test.go b/internal/cli/format_test.go index ecb423ca..f9923a11 100644 --- a/internal/cli/format_test.go +++ b/internal/cli/format_test.go @@ -8,6 +8,7 @@ import ( "strings" "testing" + "modavd/internal/avd" "modavd/internal/emu" "modavd/internal/errs" "modavd/internal/i18n" @@ -333,6 +334,13 @@ func TestFormatUpdateAndOthers(t *testing.T) { if buf.String() != "已修改实例 3:内存 6 GB\n" { t.Errorf("update float: %q", buf.String()) } + // ModAVD/ModAVD#286: --fps 36 is taken to 30, said after the change (the result's warnings) + buf.Reset() + formatUpdate(&buf, &emu.UpdateResult{Instance: sampleInstance(3), Applied: map[string]any{"fps": 30}, + Warnings: []string{avd.FPSAdjusted(36, 30)}}) + if buf.String() != "已修改实例 3:帧率 30\n帧率 36 已调整为 30(只有 15 / 30 / 60 三档)\n" { + t.Errorf("update fps: %q", buf.String()) + } buf.Reset() formatWindow(&buf, &emu.WindowResult{Index: 3, Visible: true, Windows: 0}) diff --git a/internal/emu/crud.go b/internal/emu/crud.go index 158b5870..29e64f68 100644 --- a/internal/emu/crud.go +++ b/internal/emu/crud.go @@ -50,7 +50,7 @@ func (m *Manager) Create(ctx context.Context, req CreateRequest) (_ *InstanceInf if err != nil { return nil, err } - fps, err := avd.ValidateFPS(req.FPS) + fps, fpsAdjusted, err := avd.ValidateFPS(req.FPS) if err != nil { return nil, err } @@ -133,6 +133,10 @@ func (m *Manager) Create(ctx context.Context, req CreateRequest) (_ *InstanceInf if manualDisk { disk = fmt.Sprintf("%d GB", dataGB) } + if fpsAdjusted { + // ModAVD/ModAVD#286: not an error, so a tool that still writes another frame rate keeps creating instances + m.Log.Warnf("实例 %d 的%s", i, avd.FPSAdjusted(*req.FPS, fps)) + } m.Log.Infof("已新建 ModAVD 实例 %d(内存 %d MB / %d 核 / 数据盘 %s / 帧率 %d)", i, memory, cpu, disk, fps) if req.NoBridge { // recorded, so no start installs it (bridge.go) @@ -327,13 +331,19 @@ func (m *Manager) Update(ctx context.Context, i int, req UpdateRequest) (*Update nextBoot := len(applied) > 0 var cleanup *DiagnosticsCleanup var warnings []string + if req.FPS != nil { + // ModAVD/ModAVD#286: taken to a step, not refused (avd.ValidateFPS); said with the result + if v, ok := applied["fps"].(int); ok && v != *req.FPS { + warnings = append(warnings, avd.FPSAdjusted(*req.FPS, v)) + } + } if req.Diagnostics != nil { col := &logx.Collector{} cleanup, err = m.withLog(col.Sink()).SetDiagnostics(ctx, i, *req.Diagnostics) if err != nil { return nil, err } - warnings = col.Messages() + warnings = append(warnings, col.Messages()...) applied["diagnostics"] = *req.Diagnostics } if req.BossKey != nil { diff --git a/internal/emu/launch.go b/internal/emu/launch.go index 726c21d4..e239e5b4 100644 --- a/internal/emu/launch.go +++ b/internal/emu/launch.go @@ -198,6 +198,13 @@ func (m *Manager) launchPlanFor(ctx context.Context, inst *avd.Instance, memoryM w, h, dpi := inst.Display(avd.DPIMeta(m.Root.InstanceMeta(i))) m.Log.Infof("实例 %d 显示设为 %d×%d、DPI %d、不显示导航栏(已写入 config.ini)", i, w, h, dpi) } + // ModAVD/ModAVD#286: a frame rate from before the three steps (36, 45 ...) is taken to its step now. A failure + // only means this boot runs at the old rate: said, not stopping the start. + if from, to, wrote, err := avd.ApplyFPS(m.Root, i); err != nil { + m.Log.Warnf("实例 %d 的帧率没能调整到 15 / 30 / 60 中的一档(config.ini 里是 %d),这次照原样开机: %v", i, from, err) + } else if wrote { + m.Log.Infof("实例 %d 的%s,已写入 config.ini", i, avd.FPSAdjusted(from, to)) + } headless := !window sound := avd.SoundMeta(m.Root.InstanceMeta(i)) diff --git a/internal/emu/ops_root_test.go b/internal/emu/ops_root_test.go index 4c25a393..b84411cc 100644 --- a/internal/emu/ops_root_test.go +++ b/internal/emu/ops_root_test.go @@ -49,6 +49,52 @@ func opsSkipIfNotImplemented(t *testing.T, err error) { } } +// TestOpsFPSSteps: create and update take a frame rate that is not 15 / 30 / 60 to its step (ModAVD/ModAVD#286) +// without an error, so tools that still write 36 keep working: create says so in the log, update in the result's +// warnings (the --json shape stays). One of the steps says nothing; 0 stays refused. +func TestOpsFPSSteps(t *testing.T) { + m, col := opsTestManager(t) + ctx := context.Background() + fps := 36 + created, err := m.Create(ctx, CreateRequest{filesOnly: true, FPS: &fps}) + opsSkipIfNotImplemented(t, err) + if err != nil { + t.Fatal(err) + } + i := created.Index + if created.Config.FPS != 30 { + t.Fatalf("created fps %d, want 30", created.Config.FPS) + } + in, err := avd.Get(m.Root, i) + if err != nil { + t.Fatal(err) + } + if v := in.Config.Value("hw.lcd.vsync"); v != "30" { + t.Fatalf("hw.lcd.vsync %q", v) + } + if msgs := col.Messages(); len(msgs) != 1 || !strings.Contains(msgs[0], "帧率 36 已调整为 30") { + t.Fatalf("create log: %q", msgs) + } + for v, want := range map[int]int{45: 30, 14: 15, 61: 60} { + up, err := m.Update(ctx, i, UpdateRequest{FPS: &v}) + if err != nil { + t.Fatalf("fps %d: %v", v, err) + } + if up.Applied["fps"] != want || up.Instance.Config.FPS != want || len(up.Warnings) != 1 || + up.Warnings[0] != avd.FPSAdjusted(v, want) { + t.Fatalf("fps %d: %+v", v, up) + } + } + thirty := 30 + if up, err := m.Update(ctx, i, UpdateRequest{FPS: &thirty}); err != nil || up.Applied["fps"] != 30 || len(up.Warnings) != 0 { + t.Fatalf("fps 30: %+v %v", up, err) + } + zero := 0 + if _, err := m.Update(ctx, i, UpdateRequest{FPS: &zero}); errs.CodeOf(err) != errs.InvalidArgument { + t.Fatalf("fps 0: %v", err) + } +} + func TestOpsInstanceLifecycle(t *testing.T) { m, _ := opsTestManager(t) ctx := context.Background() diff --git a/internal/emu/portplan_test.go b/internal/emu/portplan_test.go index 57c9956a..ac12d4c3 100644 --- a/internal/emu/portplan_test.go +++ b/internal/emu/portplan_test.go @@ -586,6 +586,71 @@ func TestLaunchPlanPorts(t *testing.T) { } } +// TestLaunchPlanFPS: a frame rate from before the three steps (ModAVD/ModAVD#286; here 36, as 1–60 allowed) is +// written as its step into config.ini before the emulator starts, with one line in the log; the next boot finds 30 +// and says nothing, and the instance shows 30 throughout. +func TestLaunchPlanFPS(t *testing.T) { + r, _ := portPlanRoot(t) + var logBuf strings.Builder + m := New(r, logx.New(logx.TextSink(&logBuf, logx.Info))) + six := 6 + if _, err := m.Create(context.Background(), CreateRequest{filesOnly: true, Index: &six}); err != nil { + t.Fatal(err) + } + path := avd.ConfigPath(r, 6) + cfg, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(strings.Replace(string(cfg), "hw.lcd.vsync=60", "hw.lcd.vsync=36", 1)), 0o644); err != nil { + t.Fatal(err) + } + inst, err := m.instance(6) + if err != nil { + t.Fatal(err) + } + if inst.FPS() != 30 { + t.Fatalf("FPS before the boot %d, want 30", inst.FPS()) + } + boot := func() { + t.Helper() + inst, err := m.instance(6) + if err != nil { + t.Fatal(err) + } + if _, err := m.launchPlanFor(context.Background(), inst, 3072, false); errs.CodeOf(err) == errs.Busy { + t.Skipf("ports of instance 6 in use on this machine: %v", err) + } else if err != nil { + t.Fatal(err) + } + } + adjusted := func() int { + return strings.Count(logBuf.String(), "实例 6 的帧率 36 已调整为 30") + } + boot() + in, err := avd.Get(r, 6) + if err != nil { + t.Fatal(err) + } + if v := in.Config.Value("hw.lcd.vsync"); v != "30" { + t.Fatalf("hw.lcd.vsync after the boot %q, want 30", v) + } + if adjusted() != 1 { + t.Fatalf("log: %s", logBuf.String()) + } + boot() + if adjusted() != 1 { + t.Fatalf("second boot logged the change again: %s", logBuf.String()) + } + list, err := m.List(context.Background()) + if err != nil { + t.Fatal(err) + } + if len(list.Instances) != 1 || list.Instances[0].Config.FPS != 30 { + t.Fatalf("list: %+v", list.Instances) + } +} + // TestLaunchPlanSound: a boot follows the instance's sound switch (ModAVD/ModAVD#226) as set through Update, which // also writes config.ini's hw.audio* and shows it in the instance's info; every boot gets -save-path // \ModAVD, made first (ModAVD/ModAVD#231). diff --git a/internal/i18n/locales/en/avd.json b/internal/i18n/locales/en/avd.json index 4314e15a..f93a0d11 100644 --- a/internal/i18n/locales/en/avd.json +++ b/internal/i18n/locales/en/avd.json @@ -18,7 +18,6 @@ "实例目录 %s 不存在": "The instance folder %s does not exist", "实例目录 %s 是链接,不能跟着它删除": "Instance folder %s is a link; it will not be deleted through the link", "实例编号 %d 不可用(只能是 0–9,5 除外)": "Instance number %d is not available (must be 0-9, except 5)", - "帧率只能在 %d–%d 之间": "Frame rate must be between %d and %d", "建不了目录 %s:%v": "Cannot create folder %s: %v", "拒绝访问(可能正被别的程序独占)": "Access denied (it may be locked by another program)", "数据盘上限只能在 %d–%d GB 之间": "The data disk limit must be between %d and %d GB", @@ -28,5 +27,7 @@ "方向只能选 landscape(横屏)或 portrait(竖屏)": "Orientation must be landscape or portrait", "替换 %s 失败:%v": "Failed to replace %s: %v", "请手动删除这个链接和它指向的数据": "Delete this link and the data it points to by hand", - "读不了实例目录 %s:%v": "Cannot read instance folder %s: %v" + "读不了实例目录 %s:%v": "Cannot read instance folder %s: %v", + "帧率 %d 已调整为 %d(只有 15 / 30 / 60 三档)": "Frame rate %d changed to %d (only the steps 15 / 30 / 60)", + "帧率只能是 15、30 或 60": "Frame rate must be 15, 30 or 60" } diff --git a/internal/i18n/locales/en/cli.json b/internal/i18n/locales/en/cli.json index c7f81c84..b7d56b2f 100644 --- a/internal/i18n/locales/en/cli.json +++ b/internal/i18n/locales/en/cli.json @@ -48,7 +48,7 @@ "0.3.0 起没有重启:先 modavd stop ,再 modavd start (要窗口加 --window)": "There is no restart since 0.3.0: run modavd stop , then modavd start (add --window for a window)", " [--] ": " [--] ", " [--timeout 秒] <命令...>": " [--timeout SECONDS] ", - " [--title T] [--memory M] [--cpu N] [--fps F] [--resolution 1080|720] [--dpi auto|N] [--orientation landscape|portrait] [--data-gb auto|N] [--language host|preserve|语言] [--timezone host|preserve|IANA] [--diagnostics on|off] [--sound on|off] [--app-keepalive on|off] [--boss-key 组合|none]": " [--title T] [--memory M] [--cpu N] [--fps F] [--resolution 1080|720] [--dpi auto|N] [--orientation landscape|portrait] [--data-gb auto|N] [--language host|preserve|language] [--timezone host|preserve|IANA] [--diagnostics on|off] [--sound on|off] [--app-keepalive on|off] [--boss-key combo|none]", + " [--title T] [--memory M] [--cpu N] [--fps 15|30|60] [--resolution 1080|720] [--dpi auto|N] [--orientation landscape|portrait] [--data-gb auto|N] [--language host|preserve|语言] [--timezone host|preserve|IANA] [--diagnostics on|off] [--sound on|off] [--app-keepalive on|off] [--boss-key 组合|none]": " [--title T] [--memory M] [--cpu N] [--fps 15|30|60] [--resolution 1080|720] [--dpi auto|N] [--orientation landscape|portrait] [--data-gb auto|N] [--language host|preserve|language] [--timezone host|preserve|IANA] [--diagnostics on|off] [--sound on|off] [--app-keepalive on|off] [--boss-key combo|none]", " [--window | --headless] [--timeout 300] [--no-bridge] [--launch 包名[/Activity]]": " [--window | --headless] [--timeout 300] [--no-bridge] [--launch PACKAGE[/ACTIVITY]]", " [on|off|test] [--server URL|auto] [--add 包名] [--remove 包名] [--apps 包名]": " [on|off|test] [--server URL|auto] [--add PACKAGE] [--remove PACKAGE] [--apps PACKAGE]", "APK 路径": "APK path", @@ -72,7 +72,7 @@ "UDP:失败(%v)": "UDP: failed (%v)", "Windows:host 按宿主界面语言设置一次,preserve 保持安卓语言,或指定 zh-CN、en-US 等语言": "Windows: host sets it once from the host UI language, preserve keeps the Android language, or give a language such as zh-CN or en-US", "Windows:host 每次冷启动跟随宿主,preserve 沿用原行为,或指定 Asia/Shanghai、Etc/UTC 等 IANA 时区": "Windows: host follows the host on every cold start, preserve keeps the previous behavior, or give an IANA time zone such as Asia/Shanghai or Etc/UTC", - "[--index N | --count N] [--title T] [--memory 6G] [--cpu N] [--data-gb auto|N] [--fps 1-60] [--resolution 1080|720] [--dpi auto|N] [--orientation landscape|portrait] [--language host|preserve|语言] [--timezone host|preserve|IANA] [--no-bridge] [--timeout 1200] | --resume N": "[--index N | --count N] [--title T] [--memory 6G] [--cpu N] [--data-gb auto|N] [--fps 1-60] [--resolution 1080|720] [--dpi auto|N] [--orientation landscape|portrait] [--language host|preserve|language] [--timezone host|preserve|IANA] [--no-bridge] [--timeout 1200] | --resume N", + "[--index N | --count N] [--title T] [--memory 6G] [--cpu N] [--data-gb auto|N] [--fps 15|30|60] [--resolution 1080|720] [--dpi auto|N] [--orientation landscape|portrait] [--language host|preserve|语言] [--timezone host|preserve|IANA] [--no-bridge] [--timeout 1200] | --resume N": "[--index N | --count N] [--title T] [--memory 6G] [--cpu N] [--data-gb auto|N] [--fps 15|30|60] [--resolution 1080|720] [--dpi auto|N] [--orientation landscape|portrait] [--language host|preserve|language] [--timezone host|preserve|IANA] [--no-bridge] [--timeout 1200] | --resume N", "[--out-dir 目录] [--stage-dir 目录] [--keep-stage] [--no-explorer]": "[--out-dir DIR] [--stage-dir DIR] [--keep-stage] [--no-explorer]", "[status|check|prepare|install|recover] [--source github|mirrorchyan] [--cdk-dpapi BASE64] [--automas-version V] [--package ZIP --sha256 HEX] [--after-pid PID --reopen 程序 [--reopen-arg 参数]... [--handoff-id ID]]": "[status|check|prepare|install|recover] [--source github|mirrorchyan] [--cdk-dpapi BASE64] [--automas-version V] [--package ZIP --sha256 HEX] [--after-pid PID --reopen PROGRAM [--reopen-arg ARG]... [--handoff-id ID]]", "[命令]": "[command]", @@ -308,7 +308,7 @@ "带窗口开机(默认无头);实例已经无头运行时报错,不接管": "Start with a window (headless by default); reports an error if the instance is already running headless, and does not take it over", "帧率": "Frame rate", "帧率 %v": "Frame rate %v", - "帧率:1–60 的整数,默认 60": "Frame rate: an integer from 1 to 60, default 60", + "帧率:15、30 或 60,默认 60;别的值落到往下最近的一档(1–14 取 15,高于 60 取 60)": "Frame rate: 15, 30 or 60, default 60; any other value goes to the nearest step below (1-14 becomes 15, over 60 becomes 60)", "序列号": "Serial number", "应用保活": "Keep background apps", "应用保活 %v": "Keep background apps %v", diff --git a/internal/i18n/locales/en/emu.json b/internal/i18n/locales/en/emu.json index e6c1a7b0..07c2dab9 100644 --- a/internal/i18n/locales/en/emu.json +++ b/internal/i18n/locales/en/emu.json @@ -1055,5 +1055,8 @@ "实例 %d 已有未受管理的 KernelSU 数据或应用": "Instance %d already has unmanaged KernelSU data or an app", "ModAVD 实例 %d 启动失败:Windows 拒绝了创建虚拟机(WHPX 返回拒绝访问,hr=80070005),多半是电脑上开着带内核级反作弊的游戏,或者安全软件在阻止(emulator.exe 退出码 %s):%s": "ModAVD instance %d failed to start: Windows refused to create the virtual machine (WHPX returned access denied, hr=80070005), most likely because a game with kernel-level anti-cheat is running or security software is blocking it (emulator.exe exit code %s): %s", "ModAVD 实例 %d 启动超时(%.0f 秒内安卓没有启动完成):模拟器日志里 Windows 拒绝了创建虚拟机(WHPX 返回拒绝访问,hr=80070005),多半是电脑上开着带内核级反作弊的游戏,或者安全软件在阻止;日志见 %s": "ModAVD instance %d timed out starting (Android did not finish booting within %.0f s): the emulator log says Windows refused to create the virtual machine (WHPX returned access denied, hr=80070005), most likely because a game with kernel-level anti-cheat is running or security software is blocking it. See log %s", - "先退出带反作弊的游戏(比如用 EA AntiCheat 的),它的反作弊后台服务还在的话也关掉,再开机,不用重启电脑;没开这类游戏的话,看看安全软件有没有拦着虚拟化": "Quit the game with anti-cheat first (such as one using EA AntiCheat), and close its anti-cheat background service too if it is still running, then start again; no need to restart the computer. If no such game is running, check whether security software is blocking virtualization" + "先退出带反作弊的游戏(比如用 EA AntiCheat 的),它的反作弊后台服务还在的话也关掉,再开机,不用重启电脑;没开这类游戏的话,看看安全软件有没有拦着虚拟化": "Quit the game with anti-cheat first (such as one using EA AntiCheat), and close its anti-cheat background service too if it is still running, then start again; no need to restart the computer. If no such game is running, check whether security software is blocking virtualization", + "实例 %d 的%s": "Instance %d: %s", + "实例 %d 的%s,已写入 config.ini": "Instance %d: %s, written to config.ini", + "实例 %d 的帧率没能调整到 15 / 30 / 60 中的一档(config.ini 里是 %d),这次照原样开机: %v": "Instance %d: could not change the frame rate to one of 15 / 30 / 60 (config.ini has %d); starting with it unchanged this time: %v" } diff --git a/internal/i18n/locales/en/web.json b/internal/i18n/locales/en/web.json index 2eff404e..b980662a 100644 --- a/internal/i18n/locales/en/web.json +++ b/internal/i18n/locales/en/web.json @@ -5,6 +5,7 @@ "2 核": "2 cores", "4 核": "4 cores", "6 核": "6 cores", + "60 是默认;30 给锁 30 帧的游戏,帧间隔最匀;15 只适合纯挂机,整个系统都是 15 帧": "60 is the default; 30 for games locked at 30 fps, the most even frame times; 15 only for idling, the whole system runs at 15 fps", "720p 更省资源": "720p saves more resources", "Android 软件开发套件许可协议": "Android Software Development Kit License Agreement", "Google Play 商店": "Google Play Store", @@ -38,7 +39,6 @@ "{kind}:只转 TCP,UDP 不通(换成代理软件的 SOCKS5 或混合端口就都能用)": "{kind}: forwards TCP only, UDP does not work (use the SOCKS5 or mixed port of your proxy software for both)", "{message}。这个窗口会自己关掉。": "{message}. This window will close by itself.", "{min}–{max} GB,以后只能改大;快满时会提醒": "{min}–{max} GB; it can only be enlarged later; you are warned when it is nearly full", - "{min}–{max} 的整数,越低越省资源": "A whole number from {min} to {max}; lower saves resources", "{m} 分 {s} 秒": "{m} min {s} s", "{m} 分钟": "{m} min", "{name} 是空文件": "{name} is an empty file", @@ -102,6 +102,7 @@ "上次补全组件已取消。": "The last fetch of components was canceled.", "上次补全组件没有成功:{reason}": "The last fetch of components failed: {reason}", "上次设置为 {last_language},之后保留安卓里的修改。": "Last set to {last_language}; changes made inside Android are kept afterwards.", + "下次开机生效。60 是默认;30 给锁 30 帧的游戏,帧间隔最匀;15 只适合纯挂机,整个系统都是 15 帧": "Takes effect at the next start. 60 is the default; 30 for games locked at 30 fps, the most even frame times; 15 only for idling, the whole system runs at 15 fps", "下次开机生效。MAA 等自动化任务要横屏,竖屏只适合自己玩": "Takes effect at the next start. Automation such as MAA needs landscape; portrait is for playing yourself", "下次开机生效。关闭时,第三方应用退到后台满 60 秒后结束,切回前台会取消计时。": "Takes effect at the next boot. When off, third-party apps stop after 60 seconds in the background. Returning to an app cancels its timer.", "下次开机生效,带窗口和无头都有声音。开了会多占一些 CPU。": "Takes effect at the next start; sound works with a window and headless. It uses some more CPU.", @@ -668,7 +669,6 @@ "要冷启动一次,几分钟,期间这台实例不能用。{how}": "It needs one cold start, a few minutes, during which this instance cannot be used. {how}", "要几秒:硬件加速检查和 Vulkan 探测": "Takes a few seconds: hardware acceleration check and Vulkan probe", "要填 1–{n} 之间的整数": "Enter a whole number from 1 to {n}", - "要填 {min}–{max} 之间的整数": "Enter a whole number from {min} to {max}", "要填 {min}–{max} 之间的整数(单位 GB)": "Enter a whole number from {min} to {max} (in GB)", "要执行桥": "Needs the execution bridge", "要求 AUTO-MAS": "AUTO-MAS required", diff --git a/internal/mcp/tools.go b/internal/mcp/tools.go index 3f11b8d5..91c45886 100644 --- a/internal/mcp/tools.go +++ b/internal/mcp/tools.go @@ -90,8 +90,8 @@ func cpuProp(desc string) prop { } func fpsProp(desc string) prop { - return prop{"fps", false, map[string]any{"type": "integer", "minimum": avd.MinFPS, "maximum": avd.MaxFPS, - "description": desc}} + // no enum and no maximum: another value is taken to a step (avd.ValidateFPS), not refused (ModAVD/ModAVD#286) + return prop{"fps", false, map[string]any{"type": "integer", "minimum": avd.MinFPS, "description": desc}} } func resolutionProp(desc string) prop { @@ -201,7 +201,7 @@ func toolDefs() []*toolDef { "failed setup leaves create_failed (retry with the CLI's create --resume, or delete it). "+ "Omitted options take the defaults (%d MB memory, %d CPU "+ "cores, automatic data disk, %d fps); index defaults to the smallest free one. Memory and CPU "+ - "only accept the listed steps, fps any whole number in its range; the data partition can later only be made larger (update_instance).", + "only accept the listed steps; the data partition can later only be made larger (update_instance).", avd.DefaultMemoryMB, avd.DefaultCPU, avd.DefaultFPS), mutating(false, false), reflect.TypeFor[emu.InstanceInfo](), []prop{ {"title", false, map[string]any{"type": "string", @@ -213,7 +213,8 @@ func toolDefs() []*toolDef { "maximum": avd.MaxDataPartitionGB, "description": fmt.Sprintf("A fixed size of the data partition (games) "+ "in GB. Omitted: automatic data disk (%d GB from the start; the disk image is sparse, so the host only "+ "pays for what is written).", avd.AutoDataPartitionGB)}}, - fpsProp("Display refresh rate in Hz, 1-60."), + fpsProp("Display refresh rate in Hz: 15, 30 or 60 (default 60; 30 for games locked at 30 fps, 15 for idling). " + + "Another value goes to the nearest step below (1-14: 15, above 60: 60) and is logged."), resolutionProp("Display preset: 1080 = 1920×1080 / DPI 280 (default), 720 = 1280×720 / DPI 240."), dpiProp("Display density; 0 (default) = the resolution's own (720p 240, 1080p 280)."), orientationProp("landscape (default) or portrait. Automation such as MAA needs landscape."), @@ -270,7 +271,8 @@ func toolDefs() []*toolDef { {"title", false, map[string]any{"type": "string", "description": "New display name."}}, memoryProp("New guest memory in MB."), cpuProp("New CPU core count."), - fpsProp("New display refresh rate in Hz, 1-60."), + fpsProp("New display refresh rate in Hz: 15, 30 or 60. Another value goes to the nearest step below " + + "(1-14: 15, above 60: 60); the result's warnings say so."), resolutionProp("Display preset: 1080 = 1920×1080 / DPI 280, 720 = 1280×720 / DPI 240. Preserves orientation and DPI; next boot."), dpiProp("New display density; 0 = the resolution's own again (720p 240, 1080p 280). Next boot."), orientationProp("New orientation: landscape or portrait. Automation such as MAA needs landscape. Next boot."), diff --git a/internal/ui/API.en.md b/internal/ui/API.en.md index 249e97f8..dfa12287 100644 --- a/internal/ui/API.en.md +++ b/internal/ui/API.en.md @@ -42,8 +42,8 @@ HTTP 4xx / 5xx with the body `{"error":{"code":"…","message":"…","advice":" | GET | `/api/instances` | | `ListResult` | | GET | `/api/instances/{i}` | | `InstanceInfo` | | GET | `/api/instances/{i}/regional` | | `RegionalResult` | -| POST | `/api/instances` | `{title?, index?, count?, memory_mb?, cpu?, data_partition_gb?, fps?, resolution?, dpi?, orientation?: string, language?: string, time_zone?: string}` | 202 `Job` (`kind` is `create`: without `data_partition_gb` the data disk is automatic (256 GB), with it a fixed size; it boots in the background, finishes the initial setup and shuts down again, which takes a few minutes. When `index` is not given, the server picks the number first, and `Job.index` is the new instance's; the result is an `InstanceInfo`). A new instance comes without the Google Play store (there is no `play_store` field; sending one returns 400). If you want it, use `playstore-install` below after the instance is created. `count` creates several at once (1–9, 1 when not given, not together with `index`): above 1 the server takes that many free numbers first (409 `busy` and nothing created when there are fewer), starts a `create` job for each at once and answers 202 `{jobs: [Job…]}`; the jobs run one after another in number order (a waiting one has `progress.step` `queued` and can be cancelled on its own), each checks the free space of the instances' disk before it starts and fails (`precheck_failed`) when it is too low; `title` gets a number (`T 1`, `T 2` …); one failing or cancelled does not stop the others | -| PATCH | `/api/instances/{i}` | `{title?, memory_mb?, cpu?, fps?, resolution?, dpi?, orientation?: string, data_partition_gb?, data_disk_auto?: bool, diagnostics?: bool, sound?: bool, app_keepalive?: bool, boss_key?: string, language?: string, time_zone?: string}` | `UpdateResult`; the diagnostics setting and the boss key take effect immediately, ordinary configuration (including `sound` and `app_keepalive`) at the next boot. `data_partition_gb` gives the data disk a fixed size (only larger), `data_disk_auto: true` makes it automatic; not both. When `boss_key` is given, the result has one more field `boss_key_taken` (bool): the new key was tried at once, and `true` means another program holds it (see "Boss keys and the tray" below) | +| POST | `/api/instances` | `{title?, index?, count?, memory_mb?, cpu?, data_partition_gb?, fps?, resolution?, dpi?, orientation?: string, language?: string, time_zone?: string}` | 202 `Job` (`kind` is `create`: without `data_partition_gb` the data disk is automatic (256 GB), with it a fixed size; it boots in the background, finishes the initial setup and shuts down again, which takes a few minutes. When `index` is not given, the server picks the number first, and `Job.index` is the new instance's; the result is an `InstanceInfo`). A new instance comes without the Google Play store (there is no `play_store` field; sending one returns 400). If you want it, use `playstore-install` below after the instance is created. `count` creates several at once (1–9, 1 when not given, not together with `index`): above 1 the server takes that many free numbers first (409 `busy` and nothing created when there are fewer), starts a `create` job for each at once and answers 202 `{jobs: [Job…]}`; the jobs run one after another in number order (a waiting one has `progress.step` `queued` and can be cancelled on its own), each checks the free space of the instances' disk before it starts and fails (`precheck_failed`) when it is too low; `title` gets a number (`T 1`, `T 2` …); one failing or cancelled does not stop the others. `fps` has three steps, 15 / 30 / 60: another value is not refused but goes to the nearest step below (1-14 becomes 15, above 60 becomes 60), with a line in the log | +| PATCH | `/api/instances/{i}` | `{title?, memory_mb?, cpu?, fps?, resolution?, dpi?, orientation?: string, data_partition_gb?, data_disk_auto?: bool, diagnostics?: bool, sound?: bool, app_keepalive?: bool, boss_key?: string, language?: string, time_zone?: string}` | `UpdateResult`; the diagnostics setting and the boss key take effect immediately, ordinary configuration (including `sound` and `app_keepalive`) at the next boot. `data_partition_gb` gives the data disk a fixed size (only larger), `data_disk_auto: true` makes it automatic; not both. When `boss_key` is given, the result has one more field `boss_key_taken` (bool): the new key was tried at once, and `true` means another program holds it (see "Boss keys and the tray" below). An `fps` that is not 15 / 30 / 60 goes to a step as in create, said in `warnings` | | GET | `/api/instances/{i}/diagnostics/preview` | | `{"index","files","bytes"}`: the number of files and bytes that would be cleaned up when diagnostics is turned off; it changes no configuration and deletes no files | | DELETE | `/api/instances/{i}?confirm=1` | without `confirm=1` the server returns 400 `usage` | `DeleteResult` | | POST | `/api/instances/{i}/start` | `{launch?: string}` | 202 `Job`: always boots with a window (the manager never boots headless; headless boot is command line only). If the instance is already running headless, the job fails with code `busy` (no switching while running). `launch` (`` or `/`, as in `modavd start --launch`) also opens that app once the instance is up and waits up to 30 seconds for it to be in front; a malformed name (an explicit empty string included) is 400 `invalid_argument` and no job is created, while an absent or `null` field opens no app; an app that cannot be opened does not fail the job: the `StartResult` has `app` (`{package, component, ok, seconds, code?, message?, advice?}`, `code` is `app_not_installed`, `app_launch_failed` or `timeout`) and the job's warnings say so. `ModAVD.exe --start` sends this request to a manager that is already running | diff --git a/internal/ui/API.md b/internal/ui/API.md index 70864395..e93b69c1 100644 --- a/internal/ui/API.md +++ b/internal/ui/API.md @@ -42,8 +42,8 @@ HTTP 4xx / 5xx,体为 `{"error":{"code":"…","message":"…","advice":"…"," | GET | `/api/instances` | | `ListResult` | | GET | `/api/instances/{i}` | | `InstanceInfo` | | GET | `/api/instances/{i}/regional` | | `RegionalResult` | -| POST | `/api/instances` | `{title?, index?, count?, memory_mb?, cpu?, data_partition_gb?, fps?, resolution?, dpi?, orientation?: string, language?: string, time_zone?: string}` | 202 `Job`(`kind` 是 `create`:不给 `data_partition_gb` 是自动扩盘(256 GB),给了是指定大小;后台开机做完初始化再关机,要几分钟;没给 `index` 时服务端先选好编号,`Job.index` 就是新实例的;结果是 `InstanceInfo`)。新建的实例不带 Google Play 商店(没有 `play_store` 字段,给了回 400),要的话建好后用下面的 `playstore-install`。`count` 是一次建几台(1–9,不给是 1,不能和 `index` 一起给):大于 1 时服务端先取好这么多个空闲编号(不够就 409 `busy`,一台不建),每台当场开一个 `create` 任务,回 202 `{jobs: [Job…]}`;任务按编号一台做完再做下一台(排着的 `progress.step` 是 `queued`,可以单独取消),每台开建前查实例所在盘的剩余空间,不够那一台失败(`precheck_failed`);`title` 后面加序号(`T 1`、`T 2`…);一台失败或取消不影响别的 | -| PATCH | `/api/instances/{i}` | `{title?, memory_mb?, cpu?, fps?, resolution?, dpi?, orientation?: string, data_partition_gb?, data_disk_auto?: bool, diagnostics?: bool, sound?: bool, app_keepalive?: bool, boss_key?: string, language?: string, time_zone?: string}` | `UpdateResult`;诊断和老板键立即生效,普通配置(包括 `sound` 和 `app_keepalive`)下次开机生效。`data_partition_gb` 把数据盘改成指定大小(只能改大),`data_disk_auto: true` 改成自动扩盘,两个不能同时给。给了 `boss_key` 时多一个 `boss_key_taken`(bool):新键当场试注册过,被别的程序占着是 `true`(见下「老板键和托盘」) | +| POST | `/api/instances` | `{title?, index?, count?, memory_mb?, cpu?, data_partition_gb?, fps?, resolution?, dpi?, orientation?: string, language?: string, time_zone?: string}` | 202 `Job`(`kind` 是 `create`:不给 `data_partition_gb` 是自动扩盘(256 GB),给了是指定大小;后台开机做完初始化再关机,要几分钟;没给 `index` 时服务端先选好编号,`Job.index` 就是新实例的;结果是 `InstanceInfo`)。新建的实例不带 Google Play 商店(没有 `play_store` 字段,给了回 400),要的话建好后用下面的 `playstore-install`。`count` 是一次建几台(1–9,不给是 1,不能和 `index` 一起给):大于 1 时服务端先取好这么多个空闲编号(不够就 409 `busy`,一台不建),每台当场开一个 `create` 任务,回 202 `{jobs: [Job…]}`;任务按编号一台做完再做下一台(排着的 `progress.step` 是 `queued`,可以单独取消),每台开建前查实例所在盘的剩余空间,不够那一台失败(`precheck_failed`);`title` 后面加序号(`T 1`、`T 2`…);一台失败或取消不影响别的。`fps` 只有 15 / 30 / 60 三档,给了别的值不报错,落到往下最近的一档(1–14 取 15,高于 60 取 60),日志里记一行 | +| PATCH | `/api/instances/{i}` | `{title?, memory_mb?, cpu?, fps?, resolution?, dpi?, orientation?: string, data_partition_gb?, data_disk_auto?: bool, diagnostics?: bool, sound?: bool, app_keepalive?: bool, boss_key?: string, language?: string, time_zone?: string}` | `UpdateResult`;诊断和老板键立即生效,普通配置(包括 `sound` 和 `app_keepalive`)下次开机生效。`data_partition_gb` 把数据盘改成指定大小(只能改大),`data_disk_auto: true` 改成自动扩盘,两个不能同时给。给了 `boss_key` 时多一个 `boss_key_taken`(bool):新键当场试注册过,被别的程序占着是 `true`(见下「老板键和托盘」)。`fps` 不在 15 / 30 / 60 三档里时同新建一样落到一档,`warnings` 里说明 | | GET | `/api/instances/{i}/diagnostics/preview` | | `{"index","files","bytes"}`:关闭诊断时预计清理的份数、字节,不改配置、不删文件 | | DELETE | `/api/instances/{i}?confirm=1` | 不带 `confirm=1` 回 400 `usage` | `DeleteResult` | | POST | `/api/instances/{i}/start` | `{launch?: string}` | 202 `Job`:一律带窗口开机(管理器不开无头的,无头开机只走命令行);实例要先装执行桥时,装桥这几次准备用的开机都无头,装好后正常关机,最后一次带窗口开机(同 `modavd start --window`);实例已经以无头方式在运行时,任务失败,code 是 `busy`(运行中不切换)。`launch`(`<包名>` 或 `<包名>/`,同 `modavd start --launch`)让实例开好后再打开这个应用,并等它到前台(最多 30 秒);名字格式不对(包括显式给空串)是 400 `invalid_argument`、不建任务,不给这个字段或给 `null` 就不打开应用;应用打不开不算任务失败:`StartResult` 里有 `app`(`{package, component, ok, seconds, code?, message?, advice?}`,`code` 是 `app_not_installed`、`app_launch_failed` 或 `timeout`),任务的警告里也会写。`ModAVD.exe --start` 在管理器已运行时就是把这个请求发给它 | diff --git a/internal/ui/web/app.css b/internal/ui/web/app.css index b229e596..8df292ca 100644 --- a/internal/ui/web/app.css +++ b/internal/ui/web/app.css @@ -372,10 +372,6 @@ button { -webkit-tap-highlight-color: transparent; } .with-suffix .input { padding-right: 40px; } /* the native spinner would sit on top of 「GB」; arrow keys still step the value */ .with-suffix .input::-webkit-inner-spin-button, .with-suffix .input::-webkit-outer-spin-button { appearance: none; margin: 0; } -/* frame rate: the number box (name="fps", the value sent) and a slider kept in step */ -.fps-ctl { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; } -.fps-ctl .with-suffix { width: 96px; } -.fps-ctl input[type="range"] { flex: 1; min-width: 120px; margin: 0; accent-color: var(--accent); cursor: pointer; } .suffix { position: absolute; right: 12px; color: var(--text-3); font-size: 13px; pointer-events: none; } /* the boss key: the input that takes a key combination, its clear button and the warning when another program has it */ .bosskey { display: flex; align-items: center; gap: 6px; } diff --git a/internal/ui/web/dev/mock.js b/internal/ui/web/dev/mock.js index 555409d7..fa15c2a5 100644 --- a/internal/ui/web/dev/mock.js +++ b/internal/ui/web/dev/mock.js @@ -11,6 +11,8 @@ const ROOT = 'X:\\ModAVD'; const INDEXES = [0, 1, 2, 3, 4, 6, 7, 8, 9]; const MEM = [3072, 4096, 5120, 6144, 8192]; +// the server's avd.SnapFPS (ModAVD#286): 15 / 30 / 60, another value down to the nearest step, 1–14 up to 15 +const snapFPS = (v) => (v >= 60 ? 60 : v >= 30 ? 30 : 15); const db = { insts: new Map(), jobs: [], streams: new Set(), seq: 40, check: 'ok', offline: false, drop: false, ready: true, diagMode: '', componentsReady: false, componentSource: { source: 'auto', mirror: '', mirror_urls: [], configured: false }, // the root's Google Play Store files (sdk\playstore): source is download | import once they are there @@ -874,7 +876,7 @@ function validate(b, create) { if (b.resolution != null && ![1080, 720].includes(b.resolution)) return ['invalid_argument', '分辨率只能是 1080 或 720', '']; if (b.dpi != null && ![0, 160, 240, 280, 320, 400, 480].includes(b.dpi)) return ['invalid_argument', 'DPI 只能选 160 / 240 / 280 / 320 / 400 / 480,或 0(跟随分辨率)', '']; if (b.orientation != null && !['landscape', 'portrait'].includes(b.orientation)) return ['invalid_argument', '方向只能选 landscape(横屏)或 portrait(竖屏)', '']; - if (b.fps != null && !(Number.isInteger(b.fps) && b.fps >= 1 && b.fps <= 60)) return ['invalid_argument', '帧率只能在 1–60 之间', '']; + if (b.fps != null && !(Number.isInteger(b.fps) && b.fps >= 1)) return ['invalid_argument', '帧率只能是 15、30 或 60', '']; if (create && b.data_partition_gb != null && (!Number.isInteger(b.data_partition_gb) || b.data_partition_gb < 16 || b.data_partition_gb > 512)) { return ['invalid_argument', `数据盘上限只能是 16–512 GB 的整数(收到 ${b.data_partition_gb})`, '']; } @@ -908,7 +910,7 @@ async function handle(url, init) { if (!INDEXES.includes(i)) return errResp('invalid_argument', `实例编号 ${i} 不可用(只能是 0–9,5 除外)`); if (db.insts.has(i)) return errResp('already_exists', `实例 mas_${i} 已存在`); await sleep(500); - const inst = mk(i, body.title, { mem: body.memory_mb, cpu: body.cpu, fps: body.fps, resolution: body.resolution || 1080, dpi: body.dpi, orientation: body.orientation, disk: body.data_partition_gb, initialized: false, scene: i }); + const inst = mk(i, body.title, { mem: body.memory_mb, cpu: body.cpu, fps: body.fps && snapFPS(body.fps), resolution: body.resolution || 1080, dpi: body.dpi, orientation: body.orientation, disk: body.data_partition_gb, initialized: false, scene: i }); log('info', `已新建 ModAVD 实例 ${i}(内存 ${inst.config.memory_mb} MB / ${inst.config.cpu} 核 / 数据盘 ${body.data_partition_gb ? inst.config.data_partition_gb + ' GB' : '自动扩盘'} / 帧率 ${inst.config.fps})`); emit('instances', list()); return json(pub(inst), 201); @@ -1029,7 +1031,7 @@ async function handle(url, init) { Object.assign(inst.config, { orientation: body.orientation, width: w, height: inst.config.resolution }); applied.orientation = body.orientation; } - for (const k of ['memory_mb', 'cpu', 'fps', 'sound', 'app_keepalive']) if (body[k] != null) { inst.config[k] = body[k]; applied[k] = body[k]; } + for (const k of ['memory_mb', 'cpu', 'fps', 'sound', 'app_keepalive']) if (body[k] != null) { inst.config[k] = k === 'fps' ? snapFPS(body[k]) : body[k]; applied[k] = inst.config[k]; } // the data disk: 自动扩盘, or a size that can only grow if (body.data_disk_auto && body.data_partition_gb != null) return errResp('invalid_argument', '数据盘只能二选一:自动扩盘,或者指定大小'); if (body.data_disk_auto) { diff --git a/internal/ui/web/js/forms.js b/internal/ui/web/js/forms.js index bbae9a23..060a49b0 100644 --- a/internal/ui/web/js/forms.js +++ b/internal/ui/web/js/forms.js @@ -11,8 +11,8 @@ import { regionalFields, guestRegionalText } from './regional.js'; const MEM = [[3072, '3 GB'], [4096, '4 GB'], [5120, '5 GB'], [6144, '6 GB'], [8192, '8 GB']]; const CPU = [[2, t('2 核')], [4, t('4 核')], [6, t('6 核')]]; -const FPS_MIN = 1; -const FPS_MAX = 60; +// Frame rate (ModAVD#286): three steps. At 36 or 45 a game locked at 30 shows its frames one and two refreshes long. +const FPS = [[60, '60 Hz'], [30, '30 Hz'], [15, '15 Hz']]; const RESOLUTION = [[1080, '1080p'], [720, '720p']]; // DPI (ModAVD#247): 0 follows the resolution (720p 240, 1080p 280) const DPI = [[0, t('跟随分辨率')], [160, '160'], [240, '240'], [280, '280'], [320, '320'], [400, '400'], [480, '480']]; @@ -88,44 +88,6 @@ function diskField(prefix, mode, gb, minGB) { return { rows: [h('span', { class: 'f-label', id: labelId, text: t('数据盘') }), cell(seg, size, hintEl, err)], value }; } -// Frame rate 1–60 (ModAVD#180): a number box named fps (what the form sends) and a slider moving with it. -// check() returns the value, or shows the error under the field and returns null. -function fpsField(prefix, value) { - const id = prefix + '-fps'; - const v0 = Number.isInteger(value) && value >= FPS_MIN && value <= FPS_MAX ? value : FPS_MAX; - const num = h('input', { class: 'input', id, name: 'fps', type: 'number', min: String(FPS_MIN), max: String(FPS_MAX), step: '1', value: String(v0), inputmode: 'numeric', 'aria-describedby': id + '-h' }); - const range = h('input', { type: 'range', min: String(FPS_MIN), max: String(FPS_MAX), step: '1', value: String(v0), 'aria-label': t('帧率'), tabindex: '-1' }); - const hintEl = hint(t('{min}–{max} 的整数,越低越省资源', { min: FPS_MIN, max: FPS_MAX }), id + '-h'); - const err = h('p', { class: 'f-err', id: id + '-e', role: 'alert', hidden: true }); - const clear = () => { - if (err.hidden) return; - err.hidden = true; - hintEl.hidden = false; - attr(num, 'aria-invalid', null); - attr(num, 'aria-describedby', id + '-h'); - }; - // the slider's input event bubbles to the form after this, so the settings drawer sees the new number - range.addEventListener('input', () => { num.value = range.value; clear(); }); - num.addEventListener('input', () => { - const n = Number(num.value); - if (num.value.trim() && Number.isInteger(n) && n >= FPS_MIN && n <= FPS_MAX) range.value = String(n); - clear(); - }); - const check = () => { - const n = Number(num.value); - if (num.value.trim() && Number.isInteger(n) && n >= FPS_MIN && n <= FPS_MAX) return n; - err.replaceChildren(icon('alert'), h('span', { text: t('要填 {min}–{max} 之间的整数', { min: FPS_MIN, max: FPS_MAX }) })); - err.hidden = false; - hintEl.hidden = true; - attr(num, 'aria-invalid', true); - attr(num, 'aria-describedby', id + '-e'); - num.focus(); - return null; - }; - const ctl = h('div', { class: 'fps-ctl' }, h('span', { class: 'with-suffix' }, num, h('span', { class: 'suffix', text: 'Hz' })), range); - return { rows: inputRow(t('帧率'), ctl, hintEl, err), check }; -} - export const errorBox = () => h('div', { class: 'form-error', role: 'alert', hidden: true }); export function setBusy(b, busy, text) { @@ -173,7 +135,6 @@ export function openCreate() { const countHint = hint(countHintText, 'c-count-h'); count.addEventListener('input', () => { attr(count, 'aria-invalid', null); countHint.textContent = countHintText; }); const disk = diskField('c', 'auto', 64, 16); - const fps = fpsField('c', 60); const regional = S.list.regional_supported ? regionalFields('c', null, true) : null; const box = errorBox(); const ok = h('button', { class: 'btn btn-primary', type: 'submit' }, icon('plus'), h('span', { text: t('新建') })); @@ -184,7 +145,7 @@ export function openCreate() { free.length > 1 && inputRow(t('数量'), count, countHint), segRow(t('内存'), 'memory', MEM, 6144), segRow('CPU', 'cpu', CPU, 6), - fps.rows, + segRow(t('帧率'), 'fps', FPS, 60, hint(t('60 是默认;30 给锁 30 帧的游戏,帧间隔最匀;15 只适合纯挂机,整个系统都是 15 帧'))), segRow(t('分辨率'), 'resolution', RESOLUTION, 1080, hint(t('720p 更省资源'))), segRow('DPI', 'dpi', DPI, 0, hint(t('默认跟随分辨率:720p 是 240,1080p 是 280'))), segRow(t('方向'), 'orientation', ORIENTATION, 'landscape', hint(ORIENTATION_HINT)), @@ -194,8 +155,6 @@ export function openCreate() { const f = ctl.form.elements; const d = disk.value(); if (d === null) return; - const fpsValue = fps.check(); - if (fpsValue === null) return; const n = free.length > 1 ? Number(count.value) : 1; if (!Number.isInteger(n) || n < 1 || n > free.length) { attr(count, 'aria-invalid', true); @@ -209,7 +168,7 @@ export function openCreate() { ...(regional ? regional.values() : {}), title: title.value.trim() || undefined, memory_mb: Number(f.memory.value), cpu: Number(f.cpu.value), // no size: 自动扩盘 - fps: fpsValue, resolution: Number(f.resolution.value), dpi: Number(f.dpi.value) || undefined, + fps: Number(f.fps.value), resolution: Number(f.resolution.value), dpi: Number(f.dpi.value) || undefined, orientation: f.orientation.value === 'portrait' ? 'portrait' : undefined, data_partition_gb: d.auto ? undefined : d.gb, count: n > 1 ? n : undefined, }); @@ -242,7 +201,6 @@ export function openSettings(i, field) { const boss = bossKeyField(inst0.boss_key || '', () => dirty()); const runNote = h('div', { class: 'note-box tone-warn', role: 'status' }, icon('info'), h('span', { text: t('实例运行中,内存、CPU、帧率、分辨率、DPI、方向、数据盘和声音在下次开机生效。诊断设置立即生效。') })); const kv = h('dl', { class: 'kv' }); - const fps = fpsField('s', cfg.fps); const diskAuto0 = cfg.data_disk_mode !== 'manual'; const diskGB0 = cfg.data_partition_gb || 16; // the size can only grow @@ -262,7 +220,7 @@ export function openSettings(i, field) { inputRow(t('名称'), title, hint(t('不填就显示「{name}」', { name: defaultName(i) }))), segRow(t('内存'), 'memory', MEM, cfg.memory_mb), segRow('CPU', 'cpu', CPU, cfg.cpu), - fps.rows, + segRow(t('帧率'), 'fps', FPS, cfg.fps, hint(t('下次开机生效。60 是默认;30 给锁 30 帧的游戏,帧间隔最匀;15 只适合纯挂机,整个系统都是 15 帧'))), segRow(t('分辨率'), 'resolution', RESOLUTION, cfg.resolution, hint(t('下次开机生效,自动化工具里的分辨率也要跟着改'))), segRow('DPI', 'dpi', DPI, cfg.dpi_setting || 0, hint(t('下次开机生效;跟随分辨率时 720p 是 240,1080p 是 280'))), segRow(t('方向'), 'orientation', ORIENTATION, cfg.orientation || 'landscape', hint(t('下次开机生效。MAA 等自动化任务要横屏,竖屏只适合自己玩'))), @@ -321,7 +279,7 @@ export function openSettings(i, field) { async function saveSettings() { if (ctl.busy || save.getAttribute('aria-disabled') === 'true') return; - if (fps.check() === null || disk.value() === null) return; + if (disk.value() === null) return; const pending = changes(); if (pending.diagnostics === false) { ctl.busy = true; diff --git a/scripts/test_create_cancel.mjs b/scripts/test_create_cancel.mjs index 6bb02942..f5177e34 100644 --- a/scripts/test_create_cancel.mjs +++ b/scripts/test_create_cancel.mjs @@ -515,3 +515,46 @@ test('cards mark an instance that has the Google Play Store', async () => { assert.equal(h.makeCard({ ...h.inst }).smark.hidden, true); assert.equal(h.updateCard({ ...h.inst, play_store: true }).smark.hidden, false); }); + +// ---- frame rate (ModAVD/ModAVD#286): three steps, 15 / 30 / 60, chosen like the resolution + +const fpsRadios = (form) => descendants(form).filter((x) => x.tagName === 'INPUT' && x.name === 'fps'); + +test('settings offer the frame rate as three steps with what each is for, and patch the chosen one', async () => { + const h = await settingsHarness(); + const radios = fpsRadios(h.settings.form); + assert.deepEqual(radios.map((x) => x.value), ['60', '30', '15']); + assert.deepEqual(radios.filter((x) => x.checked).map((x) => x.value), ['60']); + assert.equal(descendants(h.settings.form).filter((x) => x.tagName === 'INPUT' && (x.type === 'number' || x.type === 'range') && x.id === 's-fps').length, 0); + const text = h.settings.options.body.textContent; + for (const expected of ['60 Hz', '30 Hz', '15 Hz', '60 是默认', '30 给锁 30 帧的游戏,帧间隔最匀', '15 只适合纯挂机,整个系统都是 15 帧']) assert.ok(text.includes(expected), text); + assert.doesNotMatch(text, /1–60/); + h.radio('fps', 30); + await h.submit(); + assert.deepEqual(h.requests, [{ method: 'PATCH', path: '/api/instances/3', body: { fps: 30 } }]); +}); + +test('settings show the step an instance has, and an unchanged step sends nothing', async () => { + const h = await settingsHarness(); + h.settings.close(); + h.inst.config.fps = 15; + h.forms.openSettings(3); + const again = h.dialogs.at(-1); + assert.deepEqual(fpsRadios(again.form).filter((x) => x.checked).map((x) => x.value), ['15']); + assert.equal(again.options.actions.ok.getAttribute('aria-disabled'), 'true'); +}); + +test('the new-instance dialog has the same three steps, 60 by default, and sends the chosen one', async () => { + const h = await settingsHarness({ running: false }); + h.forms.openCreate(); + const create = h.dialogs.at(-1); + const radios = fpsRadios(create.form); + assert.deepEqual(radios.map((x) => x.value), ['60', '30', '15']); + assert.deepEqual(radios.filter((x) => x.checked).map((x) => x.value), ['60']); + assert.match(create.options.body.textContent, /15 只适合纯挂机/); + for (const el of radios) el.checked = el.value === '15'; + create.options.onSubmit(); + await turn(); + const post = h.requests.find((x) => x.method === 'POST' && x.path === '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/api/instances'); + assert.equal(post.body.fps, 15); +});