NVIDIA VFG/VSR setup, frame multiplier, upscaling off, and a mouse-first overlay
NVIDIA VFG and RTX VSR - Settings > NVIDIA VFG and RTX VSR: status, NVIDIA's licences, and a download that only starts once they're accepted; `summit nvidia status|install|remove` - NVIDIA's runtime lives per user (~/.local/share/summit/nvidia-vfx); every engine start gets FRAMEGEN_VFX_PATH - The installer falls back to uv when the engine's venv has no pip Frame multiplier - 2x..10x of a 30 fps game instead of 60/90/120 Hz: the editor's Frame multiplier (2x, 3x, 4x, 5x, 6x, 8x) and Custom multiplier, the overlay's slider, `summit profile set --multiplier`, the engine's --hz (any multiple of 30 from 60 to 300) - The pipeline spaces N in-between frames evenly for any N (cadence_steps); 60/90/120 keep their exact cadence - Older profiles keep their rate (target_hz 120 reads as 4x) Upscaling off - Upscaler "Off": the picture at its own size, never enlarged (the profile's "None" used to fall back to FSR) In-game overlay - A window: dragged by its title bar, kept inside the picture, opens where it was left - The wheel scrolls the page (or an open list); the highlight stays put; the scrollbar drags and its track jumps - Native controls: switches, buttons, sliders for ordered numbers (multiplier, sizes, opacity, sharpening), drop-down lists for long lists; pointer shapes Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
072a071e3c
commit
d44502447b
17 files changed
+1033
-130
No files matched your search
@@ -55,6 +55,8 @@ enum Cmd {
|
||||
/// Check this machine: session, monitors, and whether the engine, torch with CUDA, the model, ffmpeg, xrandr
|
||||
/// and a file dialog are there (with an id: the display commands that game's profile would run)
|
||||
Doctor { id: Option<String> },
|
||||
/// NVIDIA VFG frame generation and RTX VSR: NVIDIA's runtime (about 540 MB, from NVIDIA), per user
|
||||
Nvidia { #[command(subcommand)] cmd: NvidiaCmd },
|
||||
/// The windows open now, and the rule Enhance would save for each (`summit profile set <id> --window <rule>`)
|
||||
Windows,
|
||||
/// Look up names for Steam games you own but have not installed (cached)
|
||||
@@ -106,6 +108,19 @@ enum ConsoleCmd {
|
||||
Remove { id: String },
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum NvidiaCmd {
|
||||
/// Installed? Can this graphics card run it? Which licences it comes under
|
||||
Status,
|
||||
/// Download it from NVIDIA's package index (pinned version and hash). You must accept NVIDIA's licences first
|
||||
Install {
|
||||
/// You have read and accept the licences `summit nvidia status` lists
|
||||
#[arg(long)] accept_nvidia_licence: bool,
|
||||
},
|
||||
/// Delete it again
|
||||
Remove,
|
||||
}
|
||||
|
||||
/// Profiles are layered: `default` holds the launcher's defaults, a game's own profile only what it changes.
|
||||
#[derive(Subcommand)]
|
||||
enum ProfileCmd {
|
||||
@@ -136,6 +151,7 @@ enum ProfileCmd {
|
||||
#[arg(long)] vsr_quality: Option<u8>,
|
||||
/// "" (engine default), none or rife
|
||||
#[arg(long)] framegen: Option<String>,
|
||||
/// Frame multiplier: frames shown for each real one of a 30 fps game, 2 to 10 (2 = 60 fps, 4 = 120 fps)
|
||||
#[arg(long)] multiplier: Option<u8>,
|
||||
/// Engine output rate: 60, 90 or 120
|
||||
#[arg(long)] target_hz: Option<u32>,
|
||||
@@ -264,6 +280,35 @@ fn main() -> Result<()> {
|
||||
let text = state::path_text(&image.canonicalize()?)?;
|
||||
state::update(|st| { st.artwork.insert(id.clone(), text); })?; println!("artwork set for {id}");
|
||||
}
|
||||
Cmd::Nvidia { cmd } => {
|
||||
let eng = engine::find_engine().ok_or_else(|| anyhow::anyhow!("engine not found: run install.sh"))?;
|
||||
let dir = engine::vfx_dir().map(|d| d.display().to_string()).unwrap_or_default();
|
||||
match cmd {
|
||||
NvidiaCmd::Status => {
|
||||
let st = engine::vfx_status(&eng).map_err(|e| anyhow::anyhow!(e))?;
|
||||
println!("NVIDIA VFG + RTX VSR: {}", if st.installed { format!("installed ({}) in {dir}", st.version) } else { format!("not installed (about {} MB, into {dir})", st.size_mb) });
|
||||
println!("graphics card: {}{}", if st.gpu.is_empty() { "no NVIDIA card found" } else { &st.gpu }, if st.unsupported.is_empty() { String::new() } else { format!(" - {}", st.unsupported) });
|
||||
if !st.installed {
|
||||
println!("It comes under NVIDIA's licences:");
|
||||
for l in &st.licences { println!(" {}: {}", l.name, l.url); }
|
||||
println!("If you accept them: summit nvidia install --accept-nvidia-licence");
|
||||
}
|
||||
}
|
||||
NvidiaCmd::Install { accept_nvidia_licence } => {
|
||||
if !accept_nvidia_licence {
|
||||
let st = engine::vfx_status(&eng).map_err(|e| anyhow::anyhow!(e))?;
|
||||
let list: Vec<String> = st.licences.iter().map(|l| format!(" {}: {}", l.name, l.url)).collect();
|
||||
anyhow::bail!("NVIDIA's runtime comes under these licences; read them, and if you accept them run this again with --accept-nvidia-licence:\n{}", list.join("\n"));
|
||||
}
|
||||
let st = engine::vfx_command(&eng, false).ok_or_else(|| anyhow::anyhow!("no data folder"))?.status()?;
|
||||
anyhow::ensure!(st.success(), "the download did not finish ({st})");
|
||||
}
|
||||
NvidiaCmd::Remove => {
|
||||
let st = engine::vfx_command(&eng, true).ok_or_else(|| anyhow::anyhow!("no data folder"))?.status()?;
|
||||
anyhow::ensure!(st.success(), "it could not be removed ({st})");
|
||||
}
|
||||
}
|
||||
}
|
||||
Cmd::Windows => {
|
||||
let (s, d) = (display::detect_session(), display::detect_desktop());
|
||||
let ws = summit_core::winmode::list_windows(s, d).map_err(|e| anyhow::anyhow!("can't list windows here: {e}"))?;
|
||||
@@ -471,7 +516,8 @@ fn main() -> Result<()> {
|
||||
};
|
||||
if let Some(v) = fsr_sharpness { anyhow::ensure!(pr::FSR_SHARPNESS.contains(&v), "--fsr-sharpness is 0, 0.25, 0.5, 1 or 2"); }
|
||||
if let Some(v) = vsr_quality { anyhow::ensure!(pr::VSR_QUALITIES.contains(&v), "--vsr-quality is 1, 2, 3 or 4"); }
|
||||
if let Some(v) = target_hz { anyhow::ensure!(v == 0 || pr::TARGET_HZ.contains(&v), "--target-hz is 60, 90 or 120 (0: the engine's setting)"); }
|
||||
if let Some(v) = target_hz { anyhow::ensure!(v == 0 || pr::TARGET_HZ.contains(&v), "--target-hz is 60, 90 or 120 (0: the engine's setting); --multiplier takes 2 to 10"); }
|
||||
if let Some(v) = multiplier { anyhow::ensure!(pr::MULTIPLIER_RANGE.contains(&v), "--multiplier is a whole number from 2 to 10 (2x = 60 fps, 4x = 120 fps)"); }
|
||||
let upscaler = upscaler.map(|v| pick("upscaler", v, pr::UPSCALERS, true)).transpose()?;
|
||||
let framegen = framegen.map(|v| pick("framegen", v, pr::FRAMEGENS, true)).transpose()?;
|
||||
let model = model.map(|v| pick("model", v, pr::MODELS, true)).transpose()?;
|
||||
@@ -497,8 +543,9 @@ fn main() -> Result<()> {
|
||||
if fsr_sharpness.is_some() { l.fsr_sharpness = fsr_sharpness; }
|
||||
if vsr_quality.is_some() { l.vsr_quality = vsr_quality; }
|
||||
if framegen.is_some() { l.framegen = framegen; }
|
||||
if multiplier.is_some() { l.framegen_multiplier = multiplier; }
|
||||
if target_hz.is_some() { l.target_hz = target_hz; }
|
||||
// one or the other: the multiplier replaces an older output rate in the same profile
|
||||
if multiplier.is_some() { l.framegen_multiplier = multiplier; l.target_hz = None; }
|
||||
if target_hz.is_some() { l.target_hz = target_hz; if multiplier.is_none() { l.framegen_multiplier = None; } }
|
||||
if model.is_some() { l.model = model; }
|
||||
if vfg_quality.is_some() { l.vfg_quality = vfg_quality; }
|
||||
if motion.is_some() { l.motion = motion; }
|
||||
|
||||
@@ -54,6 +54,8 @@ pub fn scaler_arg(upscaler: &str) -> Option<&'static str> {
|
||||
"fsr" => Some("fsr"),
|
||||
"rtx-vsr" | "vsr" => Some("vsr"),
|
||||
"bilinear" => Some("bilinear"),
|
||||
// no upscaling: the picture at its own size (the profile editor's "None")
|
||||
"none" | "off" => Some("off"),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -84,8 +86,9 @@ pub fn plan(engine: &Path, src: &Source, p: &Profile, display: bool, out: Option
|
||||
}
|
||||
if display {
|
||||
a.push("--display".into());
|
||||
let hz = p.target_hz.unwrap_or(60);
|
||||
if [60, 90, 120].contains(&hz) { a.push("--hz".into()); a.push(hz.to_string()); }
|
||||
// the frame multiplier N: the engine shows N frames for each real one of a 30 fps game, 30 x N fps
|
||||
let hz = 30 * u32::from(p.multiplier().unwrap_or(2));
|
||||
a.push("--hz".into()); a.push(hz.to_string());
|
||||
match p.window_mode.as_str() {
|
||||
"windowed" => a.push("--no-fullscreen".into()),
|
||||
_ if p.fullscreen() => a.push("--fullscreen".into()),
|
||||
@@ -103,11 +106,61 @@ pub fn plan(engine: &Path, src: &Source, p: &Profile, display: bool, out: Option
|
||||
/// (GLFW's, an always-on-top window exactly over the monitor), "borderless" for a borderless window over it
|
||||
/// (engine/framegen/io.py FULLSCREEN_STYLE). Over a live game window the engine always uses a borderless window.
|
||||
pub fn engine_env(p: &Profile) -> Vec<(String, String)> {
|
||||
match p.window_mode.as_str() {
|
||||
let mut v: Vec<(String, String)> = match p.window_mode.as_str() {
|
||||
"fullscreen" => vec![("FRAMEGEN_FULLSCREEN_STYLE".into(), "monitor".into())],
|
||||
"borderless" => vec![("FRAMEGEN_FULLSCREEN_STYLE".into(), "borderless".into())],
|
||||
_ => vec![],
|
||||
};
|
||||
// where NVIDIA VFG and RTX VSR live once downloaded (`summit nvidia install`, Settings)
|
||||
if std::env::var_os("FRAMEGEN_VFX_PATH").is_none() {
|
||||
if let Some(d) = vfx_dir() { v.push(("FRAMEGEN_VFX_PATH".into(), d.to_string_lossy().into_owned())); }
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// NVIDIA's runtime for VFG frame generation and RTX VSR (the `nvidia-vfx` package, ~540 MB): downloaded from
|
||||
/// NVIDIA's own package index by the engine (framegen/vfg_setup.py) once the user accepts NVIDIA's licences. Per
|
||||
/// user, so it needs no sudo and an update of Summit keeps it. $FRAMEGEN_VFX_PATH wins.
|
||||
pub fn vfx_dir() -> Option<PathBuf> {
|
||||
if let Some(d) = std::env::var_os("FRAMEGEN_VFX_PATH").filter(|d| !d.is_empty()) { return Some(d.into()); }
|
||||
Some(dirs::data_dir()?.join("summit").join("nvidia-vfx"))
|
||||
}
|
||||
|
||||
/// What `framegen.vfg_setup --status --json` says: installed or not, and whether this graphics card can run it.
|
||||
#[derive(Debug, Clone, Default, PartialEq, serde::Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct VfxStatus {
|
||||
pub installed: bool,
|
||||
pub version: String,
|
||||
pub gpu: String,
|
||||
/// Why this PC can't run it ("" if it can).
|
||||
pub unsupported: String,
|
||||
pub size_mb: u32,
|
||||
pub licences: Vec<Licence>,
|
||||
}
|
||||
#[derive(Debug, Clone, Default, PartialEq, serde::Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct Licence { pub name: String, pub url: String }
|
||||
|
||||
/// The engine's word on NVIDIA VFG / RTX VSR here (a second or so: it asks nvidia-smi).
|
||||
pub fn vfx_status(engine: &Path) -> Result<VfxStatus, String> {
|
||||
let dir = vfx_dir().ok_or("no data folder")?;
|
||||
let out = std::process::Command::new(python(engine)).current_dir(engine).args(["-m", "framegen.vfg_setup", "--status", "--json"])
|
||||
.env("FRAMEGEN_VFX_PATH", &dir).output().map_err(|e| format!("could not run the engine: {e}"))?;
|
||||
serde_json::from_slice(&out.stdout).map_err(|e| format!("the engine's answer was not understood ({e}): {}", String::from_utf8_lossy(&out.stderr).trim()))
|
||||
}
|
||||
|
||||
/// The command that downloads and installs NVIDIA's runtime into [`vfx_dir`]. Only to be run once the user has
|
||||
/// accepted NVIDIA's licences ([`VfxStatus::licences`]): the flag says they did. `remove`: delete it again.
|
||||
pub fn vfx_command(engine: &Path, remove: bool) -> Option<std::process::Command> {
|
||||
let dir = vfx_dir()?;
|
||||
let mut c = std::process::Command::new(python(engine));
|
||||
c.current_dir(engine).env("FRAMEGEN_VFX_PATH", &dir).env("PYTHONUNBUFFERED", "1").args(["-m", "framegen.vfg_setup"]);
|
||||
if remove { c.arg("--remove"); } else {
|
||||
if let Some(parent) = dir.parent() { let _ = std::fs::create_dir_all(parent); }
|
||||
c.args(["--install", "--accept-nvidia-licence"]);
|
||||
}
|
||||
Some(c)
|
||||
}
|
||||
|
||||
/// The input file as the engine's positional argument: a relative name starting with '-' gets a "./" so argparse
|
||||
@@ -343,9 +396,10 @@ mod tests {
|
||||
assert_eq!(a[1..].join(" "), "--chiaki --model=4.25 --scaler vsr --display --hz 120 --fullscreen --monitor=HDMI-A-1");
|
||||
}
|
||||
#[test] fn file_to_out_plan() {
|
||||
// upscaler "none" (the editor's Off): the engine shows the picture at its own size
|
||||
let pr = Profile { framegen: "rife".into(), upscaler: "none".into(), ..Default::default() };
|
||||
let a = plan(Path::new("/e"), &Source::File("c.mp4".into()), &pr, false, Some(Path::new("o.mp4")), Some(120));
|
||||
assert_eq!(a[1..].join(" "), "c.mp4 --out=o.mp4 --max-ticks 120");
|
||||
assert_eq!(a[1..].join(" "), "c.mp4 --scaler off --out=o.mp4 --max-ticks 120");
|
||||
}
|
||||
#[test] fn overlay_key_goes_as_one_argument() {
|
||||
assert_eq!(overlay_args("Insert"), vec!["--overlay-key=Insert"]);
|
||||
@@ -511,8 +565,8 @@ mod tests {
|
||||
// VSR quality only with VSR, VFG quality only with VFG
|
||||
let a = plan(Path::new("/e"), &Source::Ps5, &Profile { upscaler: "rtx-vsr".into(), vsr_quality: Some(3), vfg_quality: Some("low".into()), ..Default::default() }, true, None, None);
|
||||
assert!(a.contains(&"--vsr-quality=3".to_string()) && !a.iter().any(|x| x.starts_with("--vfg-quality")), "{a:?}");
|
||||
assert_eq!(engine_env(&Profile { window_mode: "fullscreen".into(), ..Default::default() }), vec![("FRAMEGEN_FULLSCREEN_STYLE".to_string(), "monitor".to_string())]);
|
||||
assert!(engine_env(&Profile::default()).is_empty());
|
||||
assert_eq!(engine_env(&Profile { window_mode: "fullscreen".into(), ..Default::default() })[0], ("FRAMEGEN_FULLSCREEN_STYLE".to_string(), "monitor".to_string()));
|
||||
assert!(engine_env(&Profile::default()).iter().all(|(k, _)| k == "FRAMEGEN_VFX_PATH"));
|
||||
// the profile's watermark, unless the command line says otherwise
|
||||
let w = Profile { watermark: Some(false), ..Default::default() };
|
||||
assert!(run_enhance_plan(Path::new("/e"), 1, None, &w, &Live::default()).ends_with(&["--watermark".to_string(), "off".to_string()]));
|
||||
|
||||
@@ -31,6 +31,10 @@ pub const FILLS: &[&str] = &["fit", "zoom", "stretch", "panorama"];
|
||||
pub const FSR_SHARPNESS: &[f32] = &[0.0, 0.25, 0.5, 1.0, 2.0];
|
||||
pub const VSR_QUALITIES: &[u8] = &[1, 2, 3, 4];
|
||||
pub const TARGET_HZ: &[u32] = &[60, 90, 120];
|
||||
/// Frame generation's multiplier: frames shown for each real frame of a 30 fps game (the engine's output is 30 x N
|
||||
/// fps). These are the editor's choices; any whole number in MULTIPLIER_RANGE works (a custom one).
|
||||
pub const MULTIPLIERS: &[u8] = &[2, 3, 4, 5, 6, 8];
|
||||
pub const MULTIPLIER_RANGE: std::ops::RangeInclusive<u8> = 2..=10;
|
||||
|
||||
/// The settings a game launches with, after the layers are put together. `None` (and "") everywhere means "not
|
||||
/// chosen": the monitor is not switched, the window is left alone, the engine uses its own saved setting.
|
||||
@@ -55,9 +59,9 @@ pub struct Profile {
|
||||
pub vsr_quality: Option<u8>,
|
||||
/// "" (engine default, on) | "none" | "rife" (older files: "lsfg": stored, not used)
|
||||
pub framegen: String,
|
||||
/// 1 = off, 2..4 = multiplier. Stored only: the engine picks the multiplier from `target_hz`.
|
||||
/// Frame multiplier, 2..=10 (0: not set; see [`Profile::multiplier`]). The engine shows 30 x N fps.
|
||||
pub framegen_multiplier: u8,
|
||||
/// Output rate for the engine: 60, 90 or 120.
|
||||
/// Older files: the output rate (60, 90 or 120), which is the multiplier x 30. A layer sets one or the other.
|
||||
pub target_hz: Option<u32>,
|
||||
/// Interpolation model, e.g. "4.22.lite" or "vfg".
|
||||
pub model: Option<String>,
|
||||
@@ -82,6 +86,12 @@ pub struct Profile {
|
||||
}
|
||||
|
||||
impl Profile {
|
||||
/// The frame multiplier in use: the profile's, else its old output rate / 30, else None (the engine's own).
|
||||
pub fn multiplier(&self) -> Option<u8> {
|
||||
if MULTIPLIER_RANGE.contains(&self.framegen_multiplier) { return Some(self.framegen_multiplier); }
|
||||
self.target_hz.map(|hz| (hz / 30).clamp(*MULTIPLIER_RANGE.start() as u32, *MULTIPLIER_RANGE.end() as u32) as u8)
|
||||
}
|
||||
|
||||
/// The engine's picture covers the monitor (borderless or fullscreen), rather than sitting over the game's window.
|
||||
pub fn fullscreen(&self) -> bool { matches!(self.window_mode.as_str(), "borderless" | "fullscreen") }
|
||||
}
|
||||
@@ -163,8 +173,11 @@ impl Layer {
|
||||
if let Some(v) = self.fsr_sharpness { p.fsr_sharpness = Some(v).filter(|v| *v >= 0.0); }
|
||||
if let Some(v) = self.vsr_quality { p.vsr_quality = Some(v).filter(|v| *v > 0); }
|
||||
if let Some(v) = &self.framegen { p.framegen = v.clone(); }
|
||||
if let Some(v) = self.framegen_multiplier { p.framegen_multiplier = v; }
|
||||
if let Some(v) = self.target_hz { p.target_hz = Some(v).filter(|v| *v > 0); }
|
||||
// the multiplier and the older output rate say the same thing: what a later layer sets wins
|
||||
if let Some(v) = self.target_hz { p.target_hz = Some(v).filter(|v| *v > 0); p.framegen_multiplier = 0; }
|
||||
// A layer with both is an older file, where the multiplier was stored only and the rate was what counted
|
||||
// (this Summit writes one or the other).
|
||||
if let (Some(v), None) = (self.framegen_multiplier, self.target_hz) { p.framegen_multiplier = v; if MULTIPLIER_RANGE.contains(&v) { p.target_hz = None; } }
|
||||
if let Some(v) = &self.model { p.model = text(v); }
|
||||
if let Some(v) = &self.vfg_quality { p.vfg_quality = text(v); }
|
||||
if let Some(v) = &self.motion { p.motion = text(v); }
|
||||
@@ -397,4 +410,19 @@ mod tests {
|
||||
assert!(parse_env_line("1X=2").is_err());
|
||||
assert!(parse_env_line("A-B=2").is_err());
|
||||
}
|
||||
#[test]
|
||||
fn the_multiplier_and_the_older_output_rate() {
|
||||
let defaults = Layer { target_hz: Some(120), ..Default::default() }; // files from before: 120 Hz is 4x
|
||||
assert_eq!(resolve(&[&defaults]).multiplier(), Some(4));
|
||||
let game = Layer { framegen_multiplier: Some(6), ..Default::default() };
|
||||
let p = resolve(&[&defaults, &game]); // the game's own wins
|
||||
assert_eq!((p.multiplier(), p.target_hz), (Some(6), None));
|
||||
let custom = Layer { framegen_multiplier: Some(7), ..Default::default() };
|
||||
assert_eq!(resolve(&[&custom]).multiplier(), Some(7));
|
||||
assert_eq!(resolve(&[&custom, &Layer { target_hz: Some(90), ..Default::default() }]).multiplier(), Some(3));
|
||||
assert_eq!(resolve(&[]).multiplier(), None);
|
||||
// an older file with both: its rate is what it ran at
|
||||
let old = Layer { framegen_multiplier: Some(2), target_hz: Some(120), ..Default::default() };
|
||||
assert_eq!(resolve(&[&old]).multiplier(), Some(4));
|
||||
}
|
||||
}
|
||||
@@ -97,7 +97,7 @@ pub fn unfiltered(entries: &[Entry]) -> Vec<Row> {
|
||||
pub struct ProfileSummary { pub monitor: String, pub mode: String, pub upscaler: String, pub framegen: String, pub window: String, pub set: bool }
|
||||
|
||||
pub fn upscaler_label(u: &str) -> String {
|
||||
match u { "" => "Engine setting".into(), "none" => "None".into(), "fsr" => "FSR".into(), "nis" => "NIS".into(), "rtx-vsr" | "vsr" => "RTX Video Super Resolution".into(), "bilinear" => "Bilinear".into(), "dlss" => "DLSS".into(), o => o.to_string() }
|
||||
match u { "" => "Engine setting".into(), "none" => "Off (no upscaling)".into(), "fsr" => "FSR".into(), "nis" => "NIS".into(), "rtx-vsr" | "vsr" => "RTX Video Super Resolution".into(), "bilinear" => "Bilinear".into(), "dlss" => "DLSS".into(), o => o.to_string() }
|
||||
}
|
||||
|
||||
pub fn window_mode_label(m: &str) -> &'static str {
|
||||
@@ -120,11 +120,9 @@ pub fn profile_summary(p: &Profile, own: usize) -> ProfileSummary {
|
||||
("lsfg", _) => "lsfg-vk".to_string(),
|
||||
(f, _) => f.to_string(),
|
||||
};
|
||||
match (p.framegen_multiplier, p.target_hz) {
|
||||
(m, Some(hz)) if m > 1 => format!("{name} ×{m}, {hz} Hz out"),
|
||||
(m, None) if m > 1 => format!("{name} ×{m}"),
|
||||
(_, Some(hz)) => format!("{name}, {hz} Hz out"),
|
||||
_ => name,
|
||||
match p.multiplier() {
|
||||
Some(m) => format!("{name} {m}×, {} fps out", 30 * u32::from(m)),
|
||||
None => name,
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -206,6 +204,13 @@ pub fn enc_get(l: &Layer, key: &str) -> Option<String> {
|
||||
"vsr_quality" => l.vsr_quality.map(|v| if v == 0 { String::new() } else { v.to_string() }),
|
||||
"framegen" => l.framegen.clone(),
|
||||
"target_hz" => l.target_hz.map(|v| if v == 0 { String::new() } else { v.to_string() }),
|
||||
// the multiplier, or an older file's output rate read as one (120 Hz is 4x); "" a game's "engine setting"
|
||||
"framegen_multiplier" => match (l.framegen_multiplier, l.target_hz) {
|
||||
(Some(m), _) if summit_core::profile::MULTIPLIER_RANGE.contains(&m) => Some(m.to_string()),
|
||||
(_, Some(0)) | (Some(_), None) => Some(String::new()),
|
||||
(_, Some(hz)) => Some((hz / 30).to_string()),
|
||||
(None, None) => None,
|
||||
},
|
||||
"model" => l.model.clone(), "vfg_quality" => l.vfg_quality.clone(), "motion" => l.motion.clone(),
|
||||
"ai_engine" => l.ai_engine.clone(), "fill" => l.fill.clone(),
|
||||
_ => None,
|
||||
@@ -235,6 +240,11 @@ pub fn enc_set(l: &mut Layer, key: &str, v: Option<&str>) {
|
||||
"vsr_quality" => l.vsr_quality = v.map(|t| t.parse().unwrap_or(0)),
|
||||
"framegen" => l.framegen = s(v),
|
||||
"target_hz" => l.target_hz = v.map(|t| t.parse().unwrap_or(0)),
|
||||
"framegen_multiplier" => match v.map(str::parse::<u8>) {
|
||||
None => { l.framegen_multiplier = None; l.target_hz = None; }
|
||||
Some(Ok(m)) => { l.framegen_multiplier = Some(m); l.target_hz = None; }
|
||||
Some(Err(_)) => { l.framegen_multiplier = None; l.target_hz = Some(0); } // "": the engine's own
|
||||
},
|
||||
"model" => l.model = s(v), "vfg_quality" => l.vfg_quality = s(v), "motion" => l.motion = s(v),
|
||||
"ai_engine" => l.ai_engine = s(v), "fill" => l.fill = s(v),
|
||||
_ => {}
|
||||
@@ -289,7 +299,7 @@ fn choices(key: &str, eff: &Profile, base: &Profile, outs: &[Output], own: &Laye
|
||||
"window_mode" => (vec![unset("As the game opens it"), c("windowed", "Windowed"), c("borderless", "Borderless window"), c("fullscreen", "Fullscreen")], opt(Some(base.window_mode.clone()))),
|
||||
"focus" => (vec![unset("Off"), c("on", "On")], Some(if base.focus { "on".into() } else { String::new() })),
|
||||
"enhance" => (vec![unset("Off"), c("on", "On")], Some(if base.enhance { "on".into() } else { String::new() })),
|
||||
"upscaler" => (vec![unset("Engine setting (FSR)"), c("none", "None"), c("fsr", "AMD FSR 1"), c("rtx-vsr", "NVIDIA RTX VSR"), c("bilinear", "Bilinear")], opt(Some(if base.upscaler == "vsr" { "rtx-vsr".into() } else { base.upscaler.clone() }))),
|
||||
"upscaler" => (vec![unset("Engine setting (FSR)"), c("none", "Off (no upscaling)"), c("fsr", "AMD FSR 1"), c("rtx-vsr", "NVIDIA RTX VSR"), c("bilinear", "Bilinear")], opt(Some(if base.upscaler == "vsr" { "rtx-vsr".into() } else { base.upscaler.clone() }))),
|
||||
"fsr_sharpness" => (vec![unset("Engine setting"), c("0", "Max"), c("0.25", "High"), c("0.5", "Medium"), c("1", "Low"), c("2", "Minimal")], opt(base.fsr_sharpness.map(|v| format!("{v}")))),
|
||||
"vsr_quality" => (vec![unset("Engine setting"), c("1", "Low"), c("2", "Medium"), c("3", "High"), c("4", "Ultra")], opt(enc_num(base.vsr_quality))),
|
||||
"framegen" => (vec![unset("Engine setting (on)"), c("none", "Off"), c("rife", "On")], opt(Some(base.framegen.clone()))),
|
||||
@@ -298,6 +308,11 @@ fn choices(key: &str, eff: &Profile, base: &Profile, outs: &[Output], own: &Laye
|
||||
"motion" => (vec![unset("Auto"), c("full", "Full"), c("half", "Half")], opt(base.motion.clone())),
|
||||
"ai_engine" => (vec![unset("Engine setting"), c("auto", "Auto"), c("trt", "TensorRT"), c("torch", "PyTorch")], opt(base.ai_engine.clone())),
|
||||
"target_hz" => (vec![unset("Engine setting"), c("60", "60 Hz"), c("90", "90 Hz"), c("120", "120 Hz")], opt(enc_num(base.target_hz))),
|
||||
"framegen_multiplier" => {
|
||||
let mut v = vec![unset("Engine setting (2×)")];
|
||||
v.extend(summit_core::profile::MULTIPLIERS.iter().map(|m| c(&m.to_string(), &multiplier_label(*m))));
|
||||
(v, opt(base.multiplier().map(|m| m.to_string())))
|
||||
}
|
||||
"steady_hud" => (bool3("Engine setting"), Some(base.steady_hud.map(|b| if b { "on" } else { "off" }.to_string()).unwrap_or_default())),
|
||||
"fill" => (vec![unset("Engine setting"), c("fit", "Fit (bars)"), c("zoom", "Zoom (crop)"), c("stretch", "Stretch"), c("panorama", "Panorama")], opt(base.fill.clone())),
|
||||
"vsync" => (bool3("Engine setting"), Some(base.vsync.map(|b| if b { "on" } else { "off" }.to_string()).unwrap_or_default())),
|
||||
@@ -320,6 +335,14 @@ fn layer_choices(key: &str, mut ch: Vec<Choice>, defaults: bool, base_label: &st
|
||||
ch
|
||||
}
|
||||
|
||||
/// "4× (120 fps)": a frame multiplier and the rate it makes of a 30 fps game.
|
||||
pub fn multiplier_label(m: u8) -> String { format!("{m}× ({} fps)", 30 * u32::from(m)) }
|
||||
|
||||
/// The layer's multiplier when it isn't one of the editor's choices (typed in Custom multiplier).
|
||||
fn custom_multiplier(l: &Layer) -> Option<u8> {
|
||||
l.framegen_multiplier.filter(|m| summit_core::profile::MULTIPLIER_RANGE.contains(m) && !summit_core::profile::MULTIPLIERS.contains(m))
|
||||
}
|
||||
|
||||
/// Text rows: launch arguments and environment variables, as one line each.
|
||||
fn text_of(l: &Layer, key: &str) -> Option<String> {
|
||||
match key {
|
||||
@@ -363,7 +386,8 @@ pub fn edit_rows(cx: &EditCtx) -> Vec<EditRow> {
|
||||
("motion", "Motion detail", "How finely RIFE tracks movement. Half is about 40% faster and a little softer.".into()),
|
||||
("ai_engine", "AI engine", "TensorRT is about 12% faster at full motion detail; its first start takes a minute or two.".into()),
|
||||
("steady_hud", "Steady HUD", "Keeps still parts of the picture (map, health bar) exactly as the game drew them.".into()),
|
||||
("target_hz", "Output rate", "The engine's output rate. 60 Hz was tested; 90 and 120 Hz are wired, not tested.".into()),
|
||||
("framegen_multiplier", "Frame multiplier", "Frames shown for each real one of a 30 fps game: 2× is 60 fps, 4× is 120. Needs a display that fast; more needs a faster card.".into()),
|
||||
("multiplier_custom", "Custom multiplier", "Any whole number from 2 to 10 (7× is 210 fps). Enter to type it, Enter to save; empty goes back to the choice above.".into()),
|
||||
("#", "ENGINE WINDOW", String::new()),
|
||||
("vsync", "VSync", "Sync the engine's picture to the display (G-Sync/FreeSync).".into()),
|
||||
("watermark", "Watermark", "The \"summit - git.molberg.cloud/alex/summit\" line in a corner of the picture.".into()),
|
||||
@@ -381,12 +405,24 @@ pub fn edit_rows(cx: &EditCtx) -> Vec<EditRow> {
|
||||
"fsr_sharpness" => !matches!(up, "" | "fsr"),
|
||||
"vsr_quality" => !matches!(up, "rtx-vsr" | "vsr"),
|
||||
"vfg_quality" => eff.model.as_deref() != Some("vfg") || eff.framegen == "none",
|
||||
"model" | "target_hz" | "steady_hud" => eff.framegen == "none",
|
||||
"model" | "framegen_multiplier" | "multiplier_custom" | "steady_hud" => eff.framegen == "none",
|
||||
"motion" | "ai_engine" => !rife,
|
||||
_ => false,
|
||||
};
|
||||
if skip && !cx.own.has(key) { continue; }
|
||||
let own = !cx.defaults && match key { "resolution" => cx.own.width.is_some() || cx.own.height.is_some(), k => cx.own.has(k) };
|
||||
if skip && !cx.own.has(key) && key != "multiplier_custom" { continue; }
|
||||
if skip && key == "multiplier_custom" { continue; }
|
||||
let own = !cx.defaults && match key {
|
||||
"resolution" => cx.own.width.is_some() || cx.own.height.is_some(),
|
||||
"framegen_multiplier" => cx.own.framegen_multiplier.is_some() || cx.own.target_hz.is_some(),
|
||||
"multiplier_custom" => custom_multiplier(cx.own).is_some(),
|
||||
k => cx.own.has(k),
|
||||
};
|
||||
if key == "multiplier_custom" {
|
||||
let text = custom_multiplier(cx.own).map(|m| m.to_string()).unwrap_or_default();
|
||||
let placeholder = match eff.multiplier() { Some(m) => format!("Now {}", multiplier_label(m)), None => "e.g. 7".into() };
|
||||
rows.push(EditRow { key, kind: RowKind::Text, label: label.into(), hint, options: vec![], value: 0, text, placeholder, own });
|
||||
continue;
|
||||
}
|
||||
if key == "window" {
|
||||
let placeholder = match cx.auto_window { Some(q) => format!("Automatic: {q}"), None => "Automatic: asks you to pick it".into() };
|
||||
rows.push(EditRow { key, kind: RowKind::Text, label: label.into(), hint, options: vec![], value: 0, text: text_of(cx.own, key).unwrap_or_default(), placeholder, own });
|
||||
@@ -405,7 +441,14 @@ pub fn edit_rows(cx: &EditCtx) -> Vec<EditRow> {
|
||||
let cur = if cx.defaults { cur.filter(|v| !v.is_empty()) } else { cur };
|
||||
let value = match ch.iter().position(|c| c.0 == cur || (key == "refresh_hz" && c.0.as_deref().zip(cur.as_deref()).is_some_and(|(a, b)| a.parse::<f32>().ok().zip(b.parse::<f32>().ok()).is_some_and(|(a, b)| same_rate(a, b))))) {
|
||||
Some(i) => i,
|
||||
None => { let l = cur.clone().unwrap_or_default(); ch.push((cur, l)); ch.len() - 1 }
|
||||
None => {
|
||||
// a value the list doesn't have: a custom multiplier, or something a newer Summit (or the CLI) wrote
|
||||
let l = match (key, cur.as_deref().and_then(|c| c.parse::<u8>().ok())) {
|
||||
("framegen_multiplier", Some(m)) => format!("{} (custom)", multiplier_label(m)),
|
||||
_ => cur.clone().unwrap_or_default(),
|
||||
};
|
||||
ch.push((cur, l)); ch.len() - 1
|
||||
}
|
||||
};
|
||||
rows.push(EditRow { key, kind: RowKind::Choice, label: label.into(), hint, options: ch.iter().map(|c| c.1.clone()).collect(), value, text: String::new(), placeholder: String::new(), own });
|
||||
}
|
||||
@@ -430,6 +473,16 @@ pub fn edit_text(own: &Layer, key: &str, text: &str) -> Result<Layer, String> {
|
||||
"launch_args" => l.launch_args = if t.is_empty() { None } else { Some(summit_core::profile::split_args(t)) },
|
||||
"env" => l.env = if t.is_empty() { None } else { Some(summit_core::profile::parse_env_line(t)?) },
|
||||
"window" => l.window = if t.is_empty() { None } else { Some(t.to_string()) },
|
||||
"multiplier_custom" => {
|
||||
if t.is_empty() {
|
||||
if custom_multiplier(&l).is_some() { l.framegen_multiplier = None; } // back to the choice above
|
||||
} else {
|
||||
let m = t.trim_end_matches(['x', 'X', '×']).trim().parse::<u8>().ok().filter(|m| summit_core::profile::MULTIPLIER_RANGE.contains(m))
|
||||
.ok_or_else(|| "The multiplier is a whole number from 2 to 10".to_string())?;
|
||||
l.framegen_multiplier = Some(m);
|
||||
l.target_hz = None;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Ok(l)
|
||||
@@ -584,9 +637,9 @@ mod tests {
|
||||
fn profile_summary_says_default_when_unset() {
|
||||
let s = profile_summary(&Profile::default(), 0);
|
||||
assert_eq!((s.monitor.as_str(), s.mode.as_str(), s.upscaler.as_str(), s.framegen.as_str(), s.window.as_str(), s.set), ("Default", "Default", "Engine setting", "RIFE", "Default", false));
|
||||
let p = Profile { monitor: Some("HDMI-A-1".into()), width: Some(3840), height: Some(2160), refresh_hz: Some(59.94), window_mode: "borderless".into(), focus: true, upscaler: "fsr".into(), framegen: "rife".into(), framegen_multiplier: 2, target_hz: Some(120), ..Default::default() };
|
||||
let p = Profile { monitor: Some("HDMI-A-1".into()), width: Some(3840), height: Some(2160), refresh_hz: Some(59.94), window_mode: "borderless".into(), focus: true, upscaler: "fsr".into(), framegen: "rife".into(), target_hz: Some(120), ..Default::default() };
|
||||
let s = profile_summary(&p, 3);
|
||||
assert_eq!((s.monitor.as_str(), s.mode.as_str(), s.upscaler.as_str(), s.framegen.as_str(), s.window.as_str(), s.set), ("HDMI-A-1", "3840 × 2160 at 59.94 Hz", "FSR", "RIFE ×2, 120 Hz out", "Borderless window, focused", true));
|
||||
assert_eq!((s.monitor.as_str(), s.mode.as_str(), s.upscaler.as_str(), s.framegen.as_str(), s.window.as_str(), s.set), ("HDMI-A-1", "3840 × 2160 at 59.94 Hz", "FSR", "RIFE 4×, 120 fps out", "Borderless window, focused", true));
|
||||
assert_eq!(profile_summary(&Profile { framegen: "none".into(), ..Default::default() }, 0).framegen, "None");
|
||||
}
|
||||
#[test]
|
||||
@@ -723,4 +776,30 @@ mod tests {
|
||||
assert_eq!(window_wait("[window] waiting for a window matching 'class:a' (up to 300 s)\n"), WindowWait::Waiting { asking: false });
|
||||
assert_eq!(window_wait("[window] waiting for a window matching 'class:a'\nError: no window matches 'class:a' after 300 s\n"), WindowWait::GaveUp);
|
||||
}
|
||||
#[test]
|
||||
fn frame_multiplier_rows() {
|
||||
let base = Profile { framegen: "rife".into(), target_hz: Some(120), ..Default::default() }; // the defaults: 4x
|
||||
let g = Layer::default();
|
||||
let rows = edit_rows(&cx(&g, &base, false, &[]));
|
||||
let r = row(&rows, "framegen_multiplier");
|
||||
assert_eq!(r.options[r.value], "Default · 4× (120 fps)");
|
||||
assert!(r.options.contains(&"8× (240 fps)".to_string()));
|
||||
// picking 6x: the game's own, and no older output rate left beside it
|
||||
let six = r.options.iter().position(|o| o.starts_with("6×")).unwrap();
|
||||
let g = edit_apply(&cx(&g, &base, false, &[]), "framegen_multiplier", six);
|
||||
assert_eq!((g.framegen_multiplier, g.target_hz), (Some(6), None));
|
||||
// a custom 7x: typed, shown as custom in the choice row, cleared again with an empty line
|
||||
let g = edit_text(&g, "multiplier_custom", " 7x ").unwrap();
|
||||
assert_eq!(g.framegen_multiplier, Some(7));
|
||||
let rows = edit_rows(&cx(&g, &base, false, &[]));
|
||||
assert_eq!(row(&rows, "multiplier_custom").text, "7");
|
||||
let r = row(&rows, "framegen_multiplier");
|
||||
assert_eq!(r.options[r.value], "7× (210 fps) (custom)");
|
||||
assert!(edit_text(&g, "multiplier_custom", "11").is_err() && edit_text(&g, "multiplier_custom", "1.5").is_err());
|
||||
assert_eq!(edit_text(&g, "multiplier_custom", "").unwrap().framegen_multiplier, None);
|
||||
// frame generation off: neither row
|
||||
let off = Profile { framegen: "none".into(), ..Default::default() };
|
||||
let rows = edit_rows(&cx(&Layer::default(), &off, false, &[]));
|
||||
assert!(!rows.iter().any(|r| r.key == "framegen_multiplier" || r.key == "multiplier_custom"));
|
||||
}
|
||||
}
|
||||
@@ -706,6 +706,88 @@ impl App {
|
||||
lib.set_play_can_stop(false);
|
||||
}
|
||||
|
||||
// ---- NVIDIA VFG and RTX VSR (Settings) ----
|
||||
/// Ask the engine whether NVIDIA's runtime is here and this card can run it (off the UI thread: it runs nvidia-smi).
|
||||
fn nvidia_refresh(&self) {
|
||||
let lib = self.ui.global::<Lib>();
|
||||
let Some(eng) = summit_core::engine::find_engine() else {
|
||||
lib.set_nvidia_ok(false);
|
||||
return lib.set_nvidia_status("Needs Summit's engine, which was not found: run install.sh.".into());
|
||||
};
|
||||
if self.headless { return self.nvidia_show(summit_core::engine::vfx_status(&eng)); }
|
||||
lib.set_nvidia_status("Checking...".into());
|
||||
std::thread::spawn(move || {
|
||||
let st = summit_core::engine::vfx_status(&eng);
|
||||
let _ = slint::invoke_from_event_loop(move || with_app(|a| a.nvidia_show(st)));
|
||||
});
|
||||
}
|
||||
|
||||
fn nvidia_show(&self, st: Result<summit_core::engine::VfxStatus, String>) {
|
||||
let lib = self.ui.global::<Lib>();
|
||||
let dir = summit_core::engine::vfx_dir().map(|d| tilde(&d)).unwrap_or_default();
|
||||
match st {
|
||||
Err(e) => { lib.set_nvidia_ok(false); lib.set_nvidia_status(format!("Could not ask the engine: {e}").into()); }
|
||||
Ok(st) => {
|
||||
lib.set_nvidia_installed(st.installed);
|
||||
lib.set_nvidia_ok(st.unsupported.is_empty());
|
||||
let text = if st.installed { format!("Installed (nvidia-vfx {}) in {dir}. Pick NVIDIA VFG or RTX VSR in a game's profile or the in-game overlay.", st.version) }
|
||||
else if !st.unsupported.is_empty() { format!("Not for this PC: {}{}", st.unsupported, if st.gpu.is_empty() { String::new() } else { format!(" ({})", st.gpu) }) }
|
||||
else { format!("Not installed: about {} MB from NVIDIA, for the {}. Needed for NVIDIA VFG frame generation and RTX VSR upscaling.", st.size_mb, if st.gpu.is_empty() { "NVIDIA card".into() } else { st.gpu.clone() }) };
|
||||
lib.set_nvidia_status(text.into());
|
||||
let l: Vec<SharedString> = st.licences.iter().map(|l| format!("{}: {}", l.name, l.url).into()).collect();
|
||||
lib.set_nvidia_licences(ModelRc::new(VecModel::from(l)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The dialog's buttons: 0 open NVIDIA's licences in the browser, 1 accept them and download (or remove what was
|
||||
/// downloaded), 2 close.
|
||||
fn nvidia_act(&self, i: i32) {
|
||||
let lib = self.ui.global::<Lib>();
|
||||
match i {
|
||||
0 => {
|
||||
let urls: Vec<String> = lib.get_nvidia_licences().iter().filter_map(|l| l.split(": ").nth(1).map(String::from)).collect();
|
||||
if self.headless { return; }
|
||||
for u in urls {
|
||||
let _ = std::process::Command::new("xdg-open").arg(&u).stdin(std::process::Stdio::null()).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null()).spawn();
|
||||
}
|
||||
lib.set_nvidia_btn(1);
|
||||
}
|
||||
1 => {
|
||||
if lib.get_nvidia_busy() { return; }
|
||||
let remove = lib.get_nvidia_installed();
|
||||
if !remove && lib.get_nvidia_licences().row_count() == 0 { return; } // the licences were never shown
|
||||
let Some(eng) = summit_core::engine::find_engine() else { return self.toast("Summit's engine was not found: run install.sh") };
|
||||
let Some(mut cmd) = summit_core::engine::vfx_command(&eng, remove) else { return self.toast("No data folder to put it in") };
|
||||
if self.headless { return; }
|
||||
lib.set_nvidia_busy(true);
|
||||
lib.set_nvidia_open(false);
|
||||
lib.set_nvidia_status(if remove { "Removing...".into() } else { "Downloading from NVIDIA (about 540 MB); this takes a few minutes. Summit can be used meanwhile.".into() });
|
||||
self.toast(if remove { "Removing NVIDIA VFG and RTX VSR".to_string() } else { "Downloading NVIDIA VFG and RTX VSR from NVIDIA".to_string() });
|
||||
std::thread::spawn(move || {
|
||||
let out = cmd.stdin(std::process::Stdio::null()).output();
|
||||
let result = match out {
|
||||
Ok(o) if o.status.success() => Ok(()),
|
||||
Ok(o) => {
|
||||
let text = format!("{}{}", String::from_utf8_lossy(&o.stdout), String::from_utf8_lossy(&o.stderr));
|
||||
Err(text.lines().rev().find(|l| l.contains("[vfg]") || l.contains("error")).unwrap_or("it failed").trim().to_string())
|
||||
}
|
||||
Err(e) => Err(e.to_string()),
|
||||
};
|
||||
let _ = slint::invoke_from_event_loop(move || with_app(|a| {
|
||||
a.ui.global::<Lib>().set_nvidia_busy(false);
|
||||
match result {
|
||||
Ok(()) => a.toast(if remove { "NVIDIA VFG and RTX VSR removed".to_string() } else { "NVIDIA VFG and RTX VSR are ready: pick them in a game's profile or the in-game overlay".to_string() }),
|
||||
Err(e) => a.toast(format!("NVIDIA VFG and RTX VSR: {e}")),
|
||||
}
|
||||
a.nvidia_refresh();
|
||||
}));
|
||||
});
|
||||
}
|
||||
_ => lib.set_nvidia_open(false),
|
||||
}
|
||||
}
|
||||
|
||||
/// Settings > Clips folder: open it in the file manager (made first, so there is something to open).
|
||||
fn open_clips(&self) {
|
||||
let Some(dir) = summit_core::engine::clips_dir() else { return self.toast("No Videos folder found") };
|
||||
@@ -1343,6 +1425,7 @@ pub fn build(headless: bool) -> Rc<App> {
|
||||
lib.on_play_back(|| with_app(|a| a.play_back()));
|
||||
lib.on_play_stop(|| with_app(|a| a.play_stop()));
|
||||
lib.on_pick_show(|| with_app(|a| a.pick_show()));
|
||||
lib.on_nvidia_act(|i| with_app(|a| a.nvidia_act(i)));
|
||||
lib.on_pick_choose(|i| with_app(|a| a.pick_choose(i)));
|
||||
lib.on_pick_close(|| with_app(|a| a.ui.global::<Lib>().set_pick_open(false)));
|
||||
let session = display::detect_session();
|
||||
@@ -1358,8 +1441,9 @@ pub fn build(headless: bool) -> Rc<App> {
|
||||
if let Some(v) = env("SUMMIT_SCALE").and_then(|v| v.parse::<f32>().ok()) { app.settings.borrow_mut().ui_scale = v.clamp(0.5, 3.0); }
|
||||
app.rebuild_shelves();
|
||||
app.requery();
|
||||
app.nvidia_refresh();
|
||||
if let Some(v) = env("SUMMIT_VIEW").or_else(|| env("SUMMIT_TAB")).and_then(|v| pick(&v, &names(&["home", "library", "unfiltered", "settings"]))) { app.ui.invoke_goto(v.clamp(0, 3)); }
|
||||
if let Some(v) = env("SUMMIT_FOCUS").and_then(|v| v.parse::<i32>().ok()) { app.ui.set_lib_focus(v); app.ui.set_unf_focus(v); app.ui.set_settings_row(v.clamp(0, 11)); }
|
||||
if let Some(v) = env("SUMMIT_FOCUS").and_then(|v| v.parse::<i32>().ok()) { app.ui.set_lib_focus(v); app.ui.set_unf_focus(v); app.ui.set_settings_row(v.clamp(0, 12)); }
|
||||
if let Some(want) = env("SUMMIT_DETAIL") {
|
||||
let w = want.to_lowercase();
|
||||
let hit = app.entries.borrow().iter().position(|e| e.id.to_lowercase() == w).or_else(|| app.entries.borrow().iter().position(|e| e.title.to_lowercase().contains(&w)));
|
||||
|
||||
@@ -50,7 +50,7 @@ export component SettingsView inherits Rectangle {
|
||||
property <length> cw: Math.min(root.width - 2 * Theme.pad, 1040px);
|
||||
property <length> cx: Math.max(Theme.pad, (root.width - root.cw) / 2);
|
||||
pure function ry(i: int) -> length {
|
||||
return i == 0 ? 136px : i == 1 ? 216px : i == 2 ? 384px : i == 3 ? 520px : i == 4 ? 600px : i == 5 ? 736px : i == 6 ? 816px : i == 7 ? 896px : i == 8 ? 1032px : i == 9 ? 1168px : i == 10 ? 1248px : 1328px;
|
||||
return i == 0 ? 136px : i == 1 ? 216px : i == 2 ? 384px : i == 3 ? 520px : i == 4 ? 600px : i == 5 ? 736px : i == 6 ? 816px : i == 7 ? 896px : i == 8 ? 1032px : i == 9 ? 1168px : i == 10 ? 1248px : i == 11 ? 1328px : 1464px;
|
||||
}
|
||||
pure function rh(i: int) -> length { return i == 1 ? 160px : 72px; }
|
||||
function reveal() {
|
||||
@@ -76,7 +76,15 @@ export component SettingsView inherits Rectangle {
|
||||
}
|
||||
public function key(e: KeyEvent) -> bool {
|
||||
if (Lib.editor-open && Lib.editor-defaults) { return editor.key(e); }
|
||||
if (e.text == Key.DownArrow) { root.srow = Math.min(11, root.srow + 1); }
|
||||
if (Lib.nvidia-open) {
|
||||
if (e.text == Key.Escape || e.text == Key.Backspace) { Lib.nvidia-open = false; }
|
||||
else if (e.text == Key.LeftArrow) { Lib.nvidia-btn = Math.max(0, Lib.nvidia-btn - 1); }
|
||||
else if (e.text == Key.RightArrow) { Lib.nvidia-btn = Math.min(2, Lib.nvidia-btn + 1); }
|
||||
else if (e.text == Key.Return || e.text == " ") { Lib.nvidia-act(Lib.nvidia-btn); }
|
||||
return true;
|
||||
}
|
||||
if ((e.text == Key.Return || e.text == " " || e.text == Key.RightArrow) && root.srow == 12) { Lib.nvidia-btn = Lib.nvidia-installed ? 2 : 0; Lib.nvidia-open = true; return true; }
|
||||
if (e.text == Key.DownArrow) { root.srow = Math.min(12, root.srow + 1); }
|
||||
else if ((e.text == Key.Return || e.text == " ") && root.srow == 7) { Lib.open-clips(); }
|
||||
else if ((e.text == Key.Return || e.text == " " || e.text == Key.RightArrow) && root.srow == 11) { Lib.open-defaults(); }
|
||||
else if (e.text == Key.UpArrow) { if (root.srow == 0) { root.exit-up(); } else { root.srow -= 1; } }
|
||||
@@ -88,7 +96,7 @@ export component SettingsView inherits Rectangle {
|
||||
}
|
||||
|
||||
flick := Flickable {
|
||||
width: root.width; height: root.height; content-width: root.width; content-height: 1476px;
|
||||
width: root.width; height: root.height; content-width: root.width; content-height: 1612px;
|
||||
animate content-y { duration: Theme.ms(220); easing: ease-out; }
|
||||
Text { x: root.cx; y: 20px; text: "Settings"; color: Theme.p.text; font-size: Theme.t-xl; font-weight: 800; }
|
||||
Text { x: root.cx; y: 58px; width: root.cw; text: "Saved to " + Prefs.file + " as you change them."; color: Theme.p.dim; font-size: Theme.t-sm; overflow: elide; }
|
||||
@@ -146,7 +154,13 @@ export component SettingsView inherits Rectangle {
|
||||
Row { x: root.cx; y: root.ry(11); width: root.cw; label: "Every default setting"; hint: Prefs.defaults-note; focused: root.active && root.srow == 11; hit => { root.srow = 11; }
|
||||
Btn { x: parent.width - self.width - 16px; y: 12px; width: 160px; text: "Edit"; icon: Icons.sliders; focused: root.active && root.srow == 11; clicked => { root.srow = 11; Lib.open-defaults(); } }
|
||||
}
|
||||
Text { x: root.cx; y: 1420px; width: root.cw; text: Lib.stats + " · " + Lib.session + " · " + Lib.renderer; color: Theme.p.faint; font-size: Theme.t-xs; overflow: elide; }
|
||||
Section { x: root.cx; y: 1416px; width: root.cw; title: "NVIDIA"; icon: Icons.download; }
|
||||
Row { x: root.cx; y: root.ry(12); width: root.cw; label: "NVIDIA VFG and RTX VSR"; hint: Lib.nvidia-status; focused: root.active && root.srow == 12; hit => { root.srow = 12; }
|
||||
Btn { x: parent.width - self.width - 16px; y: 12px; width: 200px; enabled: !Lib.nvidia-busy && (Lib.nvidia-ok || Lib.nvidia-installed);
|
||||
text: Lib.nvidia-busy ? "Working..." : Lib.nvidia-installed ? "Manage" : "Set up"; icon: Icons.download; focused: root.active && root.srow == 12;
|
||||
clicked => { root.srow = 12; Lib.nvidia-btn = Lib.nvidia-installed ? 2 : 0; Lib.nvidia-open = true; } }
|
||||
}
|
||||
Text { x: root.cx; y: 1556px; width: root.cw; text: Lib.stats + " · " + Lib.session + " · " + Lib.renderer; color: Theme.p.faint; font-size: Theme.t-xs; overflow: elide; }
|
||||
}
|
||||
|
||||
editor := ProfileEditor {
|
||||
@@ -155,4 +169,34 @@ export component SettingsView inherits Rectangle {
|
||||
close => { Lib.editor-open = false; Lib.editor-typing = false; }
|
||||
refocus => { root.refocus(); }
|
||||
}
|
||||
|
||||
// ---- NVIDIA's licences, then the download: nothing is fetched until the player accepts ----
|
||||
if Lib.nvidia-open: Rectangle {
|
||||
background: Theme.p.bg.with-alpha(0.88);
|
||||
TouchArea { clicked => { Lib.nvidia-open = false; } }
|
||||
Rectangle {
|
||||
width: Math.min(root.width - 2 * Theme.pad, 820px); height: col.preferred-height;
|
||||
x: (parent.width - self.width) / 2; y: (parent.height - self.height) / 2;
|
||||
background: Theme.p.surface; border-radius: Theme.r-md; border-width: Theme.p.border-w; border-color: Theme.p.border;
|
||||
TouchArea { }
|
||||
col := VerticalLayout {
|
||||
padding: 28px; spacing: 14px;
|
||||
Text { text: "NVIDIA VFG AND RTX VSR"; color: Theme.p.accent; font-size: Theme.t-xs; font-weight: 800; letter-spacing: 2.4px; }
|
||||
Text { text: Lib.nvidia-installed ? "Installed. NVIDIA VFG (frame generation) and RTX VSR (upscaling) can be picked in a game's profile and in the in-game overlay."
|
||||
: "NVIDIA VFG (AI frame generation) and RTX VSR (AI upscaling) run on NVIDIA's own runtime, which Summit can't ship. Summit downloads it for you from NVIDIA's package index (about 540 MB, an exact version checked by its hash) into your home folder."; color: Theme.p.text; font-size: Theme.t-md; wrap: word-wrap; }
|
||||
if !Lib.nvidia-installed: Text { text: "It comes under these NVIDIA licences. Read them; downloading means you accept them:"; color: Theme.p.dim; font-size: Theme.t-sm; wrap: word-wrap; }
|
||||
if !Lib.nvidia-installed: VerticalLayout { spacing: 6px;
|
||||
for l in Lib.nvidia-licences: Text { text: "• " + l; color: Theme.p.dim; font-size: Theme.t-sm; wrap: word-wrap; }
|
||||
}
|
||||
Text { text: Lib.nvidia-status; color: Theme.p.faint; font-size: Theme.t-sm; wrap: word-wrap; }
|
||||
HorizontalLayout { alignment: end; spacing: 12px; padding-top: 8px;
|
||||
if !Lib.nvidia-installed: Btn { text: "Read the licences"; icon: Icons.link; focused: Lib.nvidia-btn == 0; clicked => { Lib.nvidia-btn = 0; Lib.nvidia-act(0); } }
|
||||
Btn { text: Lib.nvidia-installed ? "Remove it" : "I accept, download"; icon: Lib.nvidia-installed ? Icons.close : Icons.download; primary: !Lib.nvidia-installed;
|
||||
// never accepted unseen: downloading needs the licences on screen
|
||||
enabled: !Lib.nvidia-busy && (Lib.nvidia-installed || (Lib.nvidia-ok && Lib.nvidia-licences.length > 0)); focused: Lib.nvidia-btn == 1; clicked => { Lib.nvidia-btn = 1; Lib.nvidia-act(1); } }
|
||||
Btn { text: "Cancel"; focused: Lib.nvidia-btn == 2; clicked => { Lib.nvidia-btn = 2; Lib.nvidia-act(2); } }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -177,6 +177,15 @@ export global Lib {
|
||||
in property <[PickRow]> pick-rows;
|
||||
in property <string> pick-note; // "Listing windows...", or why they can't be listed
|
||||
in-out property <int> pick-sel;
|
||||
// NVIDIA VFG and RTX VSR: NVIDIA's runtime (Settings); downloaded only once the player accepts NVIDIA's licences
|
||||
in property <string> nvidia-status; // "Installed", "Not installed: about 540 MB from NVIDIA", "Downloading..."
|
||||
in property <bool> nvidia-installed;
|
||||
in property <bool> nvidia-busy;
|
||||
in property <bool> nvidia-ok: true; // this PC can run it (an RTX 40/50 card)
|
||||
in property <[string]> nvidia-licences;
|
||||
in-out property <bool> nvidia-open;
|
||||
in-out property <int> nvidia-btn; // dialog: 0 read the licences, 1 accept and download (or remove), 2 cancel
|
||||
callback nvidia-act(int);
|
||||
callback pick-show();
|
||||
callback pick-choose(int);
|
||||
callback pick-close();
|
||||
|
||||
+72
-9
@@ -561,7 +561,7 @@ class GLWindowSink:
|
||||
every key but that one the rest of the time.
|
||||
"""
|
||||
|
||||
NAMES = {"fsr": "FSR 1", "vsr": "RTX VSR", "bilinear": "bilinear"}
|
||||
NAMES = {"fsr": "FSR 1", "vsr": "RTX VSR", "bilinear": "bilinear", "off": "no upscaling"}
|
||||
|
||||
# Shown when the window opens, and again when the mouse moves over it (set in __init__, with the overlay's key).
|
||||
KEYS_HINT = "Insert: Summit's overlay F: fullscreen Ctrl+Q: quit"
|
||||
@@ -691,11 +691,11 @@ class GLWindowSink:
|
||||
self.vsr_why = why
|
||||
if why is not None and scaler == "vsr":
|
||||
print(f"[display] RTX VSR unavailable ({why})")
|
||||
self.modes = [m for m, ok in (("fsr", self.fsr), ("vsr", self._vsr_args), ("bilinear", True)) if ok]
|
||||
self.modes = [m for m, ok in (("fsr", self.fsr), ("vsr", self._vsr_args), ("bilinear", True), ("off", True)) if ok]
|
||||
self.mode = scaler if scaler in self.modes else self.modes[0]
|
||||
if self.mode == "vsr" and not self._vsr_ready():
|
||||
self.mode = self.modes[0]
|
||||
details = {"fsr": f" (sharpness {sharpness:g})", "vsr": f" (quality {vsr_quality})", "bilinear": ""}
|
||||
details = {"fsr": f" (sharpness {sharpness:g})", "vsr": f" (quality {vsr_quality})", "bilinear": "", "off": ""}
|
||||
print(f"[display] upscaling with {self._name(self.mode)}{details[self.mode]}; u cycles "
|
||||
+ " / ".join(self._name(m) for m in self.modes))
|
||||
self.timer = GpuTimer(GL) # GPU time of the scale/draw step, reported on close
|
||||
@@ -736,6 +736,11 @@ class GLWindowSink:
|
||||
self._frametimes, self._last_write, self._graph_drawn, self._gpu = collections.deque(maxlen=480), 0.0, 0.0, None
|
||||
self._menu_top = None # (GL y of the menu's top, the picture's (y0, height) it was placed in, on the left?) while open
|
||||
self._menu_at = None # (x, GL y of the top) the menu was last drawn at, for the mouse
|
||||
self._menu_off = (0, 0) # where the player dragged the overlay to, from where it opens (framebuffer px; kept
|
||||
# for the session, so it opens where it was left)
|
||||
self._menu_move: tuple | None = None # dragging it by its title: (cursor x, y, offset x, y) at the press
|
||||
self._cursors: dict = {} # the mouse pointers made so far (arrow, hand, move)
|
||||
self._cursor_shape = "arrow"
|
||||
self._cursor = (0.0, 0.0) # the mouse, in window coordinates
|
||||
self._menu_state = self._toast_state = None
|
||||
self._status_at = 0.0 # when the overlay's header last got new numbers
|
||||
@@ -848,18 +853,53 @@ class GLWindowSink:
|
||||
self.settle_hook = None
|
||||
|
||||
def _on_mouse(self, win, x, y) -> None:
|
||||
"""Moving the mouse over the video shows the keys for a moment (not over the menu or another message)."""
|
||||
"""Moving the mouse over the video shows the keys for a moment (not over the menu or another message). Over
|
||||
the overlay: it highlights what's under it, and drags whatever was pressed (the overlay by its title, a
|
||||
slider, the scrollbar)."""
|
||||
self._cursor = (x, y)
|
||||
if self.menu.open:
|
||||
if self._menu_move is not None:
|
||||
cx, cy, ox, oy = self._menu_move
|
||||
fx, fy = self._fb_scale()
|
||||
self._menu_off = (ox + round((x - cx) * fx), oy + round((y - cy) * fy))
|
||||
self._set_cursor("move")
|
||||
return
|
||||
p = self._menu_xy()
|
||||
if p is not None:
|
||||
self.menu.hover(*p)
|
||||
inside = 0 <= p[0] < self.menu_panel.w and 0 <= p[1] < self.menu_panel.h
|
||||
self._set_cursor(self.menu.cursor(*p) if inside else "arrow")
|
||||
return
|
||||
now = time.perf_counter()
|
||||
if now >= self._hint_next and not self.menu.open and now >= self._toast_until:
|
||||
self._hint_next = now + 20.0
|
||||
self.toast(self.KEYS_HINT, 3.0 if self.hotkeys is None else 6.0)
|
||||
|
||||
def _fb_scale(self) -> tuple[float, float]:
|
||||
"""Framebuffer pixels per window coordinate (2 on a HiDPI screen)."""
|
||||
glfw = self.glfw
|
||||
ww, wh = glfw.get_window_size(self.win)
|
||||
fw, fh = glfw.get_framebuffer_size(self.win)
|
||||
return (fw / ww if ww else 1.0), (fh / wh if wh else 1.0)
|
||||
|
||||
def _set_cursor(self, shape: str) -> None:
|
||||
"""The mouse pointer over the overlay: an arrow, a hand over things to click, the move cross on its title."""
|
||||
if shape == self._cursor_shape:
|
||||
return
|
||||
glfw = self.glfw
|
||||
self._cursor_shape = shape
|
||||
std = {"hand": getattr(glfw, "POINTING_HAND_CURSOR", getattr(glfw, "HAND_CURSOR", None)),
|
||||
"move": getattr(glfw, "RESIZE_ALL_CURSOR", getattr(glfw, "HAND_CURSOR", None))}.get(shape)
|
||||
try:
|
||||
if std is None:
|
||||
glfw.set_cursor(self.win, None)
|
||||
return
|
||||
if shape not in self._cursors:
|
||||
self._cursors[shape] = glfw.create_standard_cursor(std)
|
||||
glfw.set_cursor(self.win, self._cursors[shape])
|
||||
except Exception: # noqa: BLE001 - a plain arrow then
|
||||
pass
|
||||
|
||||
def _menu_xy(self) -> tuple[float, float] | None:
|
||||
"""The mouse as a pixel of the menu's image (from its top-left), or None while the menu isn't on screen."""
|
||||
if self._menu_at is None or not self.menu.open:
|
||||
@@ -878,6 +918,10 @@ class GLWindowSink:
|
||||
right-click on a row: the choice before), and a click outside closes it. Over a game (window capture) clicks
|
||||
belong to the game: they come here only while the overlay is open (_sync_modal)."""
|
||||
glfw = self.glfw
|
||||
if action == glfw.RELEASE: # the end of a drag (the overlay by its title, a slider, the scrollbar)
|
||||
self._menu_move = None
|
||||
self.menu.release()
|
||||
return
|
||||
if action != glfw.PRESS or (self.overlay_of is not None and not self.menu.open):
|
||||
return
|
||||
right = button == glfw.MOUSE_BUTTON_RIGHT
|
||||
@@ -890,10 +934,18 @@ class GLWindowSink:
|
||||
if not inside:
|
||||
self.menu.open = False
|
||||
return
|
||||
if not right:
|
||||
grabbed = self.menu.grab(*p)
|
||||
if grabbed == "move":
|
||||
self._menu_move = (*self._cursor, *self._menu_off)
|
||||
self._set_cursor("move")
|
||||
return
|
||||
if grabbed == "drag":
|
||||
return
|
||||
self._menu_result(self.menu.click(*p, right=right))
|
||||
|
||||
def _on_scroll(self, win, dx, dy) -> None:
|
||||
"""The wheel moves the highlight in the overlay."""
|
||||
"""The wheel scrolls the overlay's page (or its open list); the highlight stays where it is."""
|
||||
if self.menu.open and dy:
|
||||
self.menu.scroll(dy)
|
||||
|
||||
@@ -1483,7 +1535,8 @@ class GLWindowSink:
|
||||
ui = max(0.5, dh / 1080) * self.settings.ui_scale
|
||||
op = self.settings.ui_opacity
|
||||
if not self.menu.open:
|
||||
self._menu_top = self._menu_at = None
|
||||
self._menu_top = self._menu_at = self._menu_move = None
|
||||
self._set_cursor("arrow")
|
||||
else:
|
||||
state = (self.menu.state(), round(ui, 3), op)
|
||||
if state != self._menu_state:
|
||||
@@ -1496,8 +1549,13 @@ class GLWindowSink:
|
||||
where = (y0, dh)
|
||||
if self._menu_top is None or self._menu_top[1] != where:
|
||||
self._menu_top = (y0 + (dh + p.h) // 2, where, self.settings.overlay_corner.endswith("right"))
|
||||
top = min(y0 + dh, max(self._menu_top[0], y0 + p.h))
|
||||
mx = x0 + int(32 * ui) if self._menu_top[2] else max(x0, x0 + dw - p.w - int(32 * ui))
|
||||
ox, oy = self._menu_off # where the player dragged it (framebuffer px, y down)
|
||||
base_x = x0 + int(32 * ui) if self._menu_top[2] else max(x0, x0 + dw - p.w - int(32 * ui))
|
||||
# inside the picture whatever happens: a drag past its edge stops there (and is kept as stopped, so
|
||||
# dragging back moves it at once)
|
||||
top = min(y0 + dh, max(self._menu_top[0] - oy, y0 + p.h))
|
||||
mx = max(x0, min(base_x + ox, x0 + dw - p.w))
|
||||
self._menu_off = (mx - base_x, self._menu_top[0] - top)
|
||||
self._menu_at = (mx, top) # where the mouse finds it (see _menu_xy)
|
||||
self.menu_panel.blit(mx, top, self._target())
|
||||
if time.perf_counter() < self._toast_until: # a message: top middle, clear of the stats' corner
|
||||
@@ -1609,8 +1667,13 @@ class GLWindowSink:
|
||||
self.panorama = Panorama(GL)
|
||||
target, x0, y0 = self.panorama.target(dw, dh), 0, 0
|
||||
GL.glBindFramebuffer(GL.GL_DRAW_FRAMEBUFFER, target)
|
||||
upscale = dw > self.w or dh > self.h
|
||||
mode = self.mode
|
||||
if mode == "off" and (dw > self.w or dh > self.h):
|
||||
# Upscaling off: the picture at its own size (never enlarged), in the middle of where it would go
|
||||
k = min(1.0, dw / self.w, dh / self.h)
|
||||
ow, oh = round(self.w * k), round(self.h * k)
|
||||
x0, y0, dw, dh = x0 + (dw - ow) // 2, y0 + (dh - oh) // 2, ow, oh
|
||||
upscale = dw > self.w or dh > self.h
|
||||
if mode == "vsr" and not on_gpu: # a CPU frame: VSR needs it on the GPU
|
||||
mode = "fsr" if self.fsr is not None else "bilinear"
|
||||
ss = SUPERSAMPLE if (mode == "vsr" and not upscale) else 1.0
|
||||
|
||||
+317
-41
@@ -4,10 +4,14 @@ Settings page picks the key). Drawn as an image the GL window blits over the gam
|
||||
Rows come from settings.SPECS, so a new setting shows up here without changes to this file. Tabs along the top: Home
|
||||
(the big choices that apply live, the performance overlay, and Restart / Save a clip / Quit), then one for each section
|
||||
(Spec.group, as on the launcher's Settings page). Keys: Up and Down pick a row (Up from the first row goes to the
|
||||
tabs, where Left and Right change tab), Left and Right change the value, Enter is the next value (or does the row's
|
||||
action), Tab and Shift+Tab change tab, Esc or Backspace closes the overlay. Esc never closes the game or Summit's
|
||||
picture: Quit is a row on Home, and asks twice. The mouse works too: click a tab, a choice or an arrow, right-click a
|
||||
row for the choice before, wheel to move.
|
||||
tabs, where Left and Right change tab), Left and Right change the value, Enter is the next value (or opens a row's
|
||||
list, or does its action), Tab and Shift+Tab change tab, Esc or Backspace closes the overlay (or an open list). Esc
|
||||
never closes the game or Summit's picture: Quit is a row on Home, and asks twice.
|
||||
|
||||
The mouse works as in any desktop program: the overlay is a window, moved by dragging its title bar (framegen/io.py
|
||||
keeps where it was put). On/off settings are switches, a few short choices are buttons side by side, numbers that go
|
||||
in order (the frame multiplier, qualities, sizes) are sliders to click or drag, and longer lists open a drop-down
|
||||
list. The wheel scrolls the page (the highlighted row stays where it is), and the scrollbar can be dragged.
|
||||
|
||||
Drawing happens only when something on the overlay changes (the window caches the image), so an open overlay costs
|
||||
nothing per frame.
|
||||
@@ -24,6 +28,7 @@ from . import ui_draw as U
|
||||
from .settings import SPECS, Settings, Spec
|
||||
|
||||
VISIBLE = 8 # rows shown at once; longer tabs scroll
|
||||
DROP_VISIBLE = 7 # choices shown at once in a drop-down list
|
||||
HOME = "Home"
|
||||
TAB_NAMES = {"Instant replay": "Clips", "PS5 Remote Play": "Remote Play"} # shorter, for the tab strip
|
||||
|
||||
@@ -84,6 +89,11 @@ class Menu:
|
||||
self._at = 0
|
||||
self._left: dict[str | None, str] = {} # each tab's highlighted row when the player last left it
|
||||
self._scroll = 0
|
||||
self._wheel = 0.0 # wheel movement not yet a whole row (a touchpad's small steps add up)
|
||||
self._drop: str | None = None # the row whose drop-down list is open (its key)
|
||||
self._drop_index = 0 # the highlighted choice in it
|
||||
self._drop_scroll = 0
|
||||
self._drag: tuple | None = None # what the mouse is dragging inside: ("slider", row index) or ("scrollbar", y0, scroll0)
|
||||
self._hover: tuple | None = None # ("tab", i), ("close",): what the mouse is over, besides rows
|
||||
self._hit: dict = {} # render()'s layout in the image's pixels, for the mouse
|
||||
self._drawn: tuple = (None, None) # render()'s last picture and what it showed (see there)
|
||||
@@ -94,8 +104,8 @@ class Menu:
|
||||
|
||||
@open.setter
|
||||
def open(self, on: bool) -> None:
|
||||
if on != self._open: # (what the mouse was over, and a half-asked Quit, don't outlive a visit)
|
||||
self._open, self._hover, self.armed = on, None, False
|
||||
if on != self._open: # (what the mouse was over, an open list and a half-asked Quit don't outlive a visit)
|
||||
self._open, self._hover, self.armed, self._drop, self._drag = on, None, False, None, None
|
||||
|
||||
# ---- what there is ---------------------------------------------------------
|
||||
def sections(self) -> list[str]:
|
||||
@@ -168,8 +178,17 @@ class Menu:
|
||||
self.settings.set(row.key, value)
|
||||
|
||||
def step(self, row: Row, delta: int) -> None:
|
||||
"""The next (or previous) choice that can be picked, going round."""
|
||||
choices = self.choices(row)
|
||||
"""The next (or previous) choice that can be picked, going round (a slider: rightwards is up, and it stops
|
||||
at its ends instead)."""
|
||||
choices = self.ordered(row)
|
||||
if self.kind_of(row) == "slider" and choices and self.value(row) in choices:
|
||||
i = choices.index(self.value(row)) + delta
|
||||
while 0 <= i < len(choices):
|
||||
if self.can(row, choices[i]):
|
||||
self.set_value(row, choices[i])
|
||||
return
|
||||
i += delta
|
||||
return
|
||||
if not choices or self.off(row):
|
||||
return
|
||||
i = choices.index(self.value(row))
|
||||
@@ -188,23 +207,30 @@ class Menu:
|
||||
self.index = max(0, min(self.index, len(rows) - 1))
|
||||
self._sel, self._at = keys[self.index], self.index
|
||||
self._scroll = max(0, min(self._scroll, len(rows) - VISIBLE))
|
||||
if self._drop is not None and self._drop not in keys:
|
||||
self._drop = None
|
||||
|
||||
def _reveal(self) -> None:
|
||||
"""Scrolls the highlighted row into view (the keyboard moved it; the mouse never needs this)."""
|
||||
if self.index < self._scroll:
|
||||
self._scroll = self.index
|
||||
elif self.index >= self._scroll + VISIBLE:
|
||||
self._scroll = self.index - VISIBLE + 1
|
||||
|
||||
def _select(self, i: int, rows: list[Row] | None = None) -> None:
|
||||
def _select(self, i: int, rows: list[Row] | None = None, reveal: bool = True) -> None:
|
||||
rows = self.rows() if rows is None else rows
|
||||
self.index = max(0, min(i, len(rows) - 1))
|
||||
self._sel, self._at = rows[self.index].key, self.index
|
||||
self._follow(rows)
|
||||
if reveal:
|
||||
self._reveal()
|
||||
|
||||
def show(self, tab: str | None) -> None:
|
||||
"""Goes to a tab, on the row it was left on."""
|
||||
if tab == self.tab:
|
||||
return
|
||||
self._left[self.tab] = self._sel
|
||||
self.tab, self.armed, self._scroll = tab, False, 0
|
||||
self.tab, self.armed, self._scroll, self._drop = tab, False, 0, None
|
||||
rows = self.rows()
|
||||
keys = [r.key for r in rows]
|
||||
want = self._left.get(self.tab)
|
||||
@@ -233,6 +259,18 @@ class Menu:
|
||||
row = rows[self.index]
|
||||
if not (name == "enter" and self.focus == "rows" and row.key == "quit"):
|
||||
self.armed = False
|
||||
if self._drop is not None: # an open list has the keys
|
||||
drow = next((r for r in rows if r.key == self._drop), None)
|
||||
choices = self.choices(drow) if drow else ()
|
||||
if name in ("back", "next_tab", "prev_tab") or not choices:
|
||||
self._drop = None
|
||||
elif name in ("up", "down", "left", "right"):
|
||||
self._drop_index = max(0, min(len(choices) - 1, self._drop_index + (-1 if name in ("up", "left") else 1)))
|
||||
self._drop_reveal(len(choices))
|
||||
elif name == "enter":
|
||||
self.set_value(drow, choices[self._drop_index])
|
||||
self._drop = None
|
||||
return None
|
||||
if name == "back":
|
||||
return "close"
|
||||
if name in ("next_tab", "prev_tab"):
|
||||
@@ -254,14 +292,66 @@ class Menu:
|
||||
elif row.kind == "action":
|
||||
if name == "enter":
|
||||
return self._act(row)
|
||||
elif name == "enter" and self.kind_of(row) == "list" and not self.off(row):
|
||||
self._open_drop(row)
|
||||
elif name in ("left", "right", "enter"):
|
||||
self.step(row, -1 if name == "left" else 1)
|
||||
return None
|
||||
|
||||
# ---- controls: which one a row gets ---------------------------------------
|
||||
def kind_of(self, row: Row) -> str:
|
||||
""""switch" (on/off), "buttons" (a few short choices side by side), "slider" (numbers that go in order) or
|
||||
"list" (a drop-down list)."""
|
||||
choices = self.choices(row)
|
||||
if row.kind != "setting" and row.kind != PERF:
|
||||
return ""
|
||||
if set(choices) == {True, False}:
|
||||
return "switch"
|
||||
numeric = all(isinstance(v, (int, float)) and not isinstance(v, bool) for v in choices)
|
||||
if numeric and len(choices) >= 3 and list(choices) in (sorted(choices), sorted(choices, reverse=True)):
|
||||
return "slider"
|
||||
if len(choices) <= 4 and sum(len(self.name(row, v)) for v in choices) <= 34:
|
||||
return "buttons"
|
||||
return "list"
|
||||
|
||||
def _open_drop(self, row: Row) -> None:
|
||||
choices = self.choices(row)
|
||||
value = self.value(row)
|
||||
self._drop = row.key
|
||||
self._drop_index = choices.index(value) if value in choices else 0
|
||||
self._drop_scroll = 0
|
||||
self._drop_reveal(len(choices))
|
||||
|
||||
def _drop_reveal(self, n: int) -> None:
|
||||
if self._drop_index < self._drop_scroll:
|
||||
self._drop_scroll = self._drop_index
|
||||
elif self._drop_index >= self._drop_scroll + DROP_VISIBLE:
|
||||
self._drop_scroll = self._drop_index - DROP_VISIBLE + 1
|
||||
self._drop_scroll = max(0, min(self._drop_scroll, n - DROP_VISIBLE))
|
||||
|
||||
def ordered(self, row: Row) -> list:
|
||||
"""A slider's choices from its left end to its right: smallest first, whichever order the setting lists them."""
|
||||
choices = list(self.choices(row))
|
||||
return sorted(choices) if self.kind_of(row) == "slider" else choices
|
||||
|
||||
def _slide(self, row: Row, x: float, track: tuple[float, float]) -> None:
|
||||
"""A slider pressed or dragged at x: the nearest choice that can be picked."""
|
||||
choices = self.ordered(row)
|
||||
if not choices or self.off(row):
|
||||
return
|
||||
t = 0.0 if track[1] <= track[0] else min(1.0, max(0.0, (x - track[0]) / (track[1] - track[0])))
|
||||
want = t * (len(choices) - 1)
|
||||
for i in sorted(range(len(choices)), key=lambda i: abs(i - want)):
|
||||
if self.can(row, choices[i]):
|
||||
if choices[i] != self.value(row):
|
||||
self.set_value(row, choices[i])
|
||||
return
|
||||
|
||||
# ---- mouse (x, y: pixels in the image render() made, from its top-left corner)
|
||||
@staticmethod
|
||||
def _in(box, x: float, y: float) -> bool:
|
||||
return box[0] <= x < box[2] and box[1] <= y < box[3]
|
||||
"""Whether (x, y) is in box; None (no scrollbar on a short tab, no open list) holds nothing."""
|
||||
return box is not None and box[0] <= x < box[2] and box[1] <= y < box[3]
|
||||
|
||||
def _row_at(self, x: float, y: float) -> int | None:
|
||||
h = self._hit
|
||||
@@ -271,8 +361,20 @@ class Menu:
|
||||
return i if 0 <= i < len(self.rows()) else None
|
||||
|
||||
def hover(self, x: float, y: float) -> None:
|
||||
"""Moving the mouse over a row highlights it; over a tab or Close, lights that up."""
|
||||
"""The mouse over a row highlights it (and shows its help); over a tab, Close or a list's choice, lights that
|
||||
up. Nothing scrolls: the page moves only with the wheel or the scrollbar."""
|
||||
if self._drag is not None:
|
||||
return self.drag(x, y)
|
||||
self._hover = None
|
||||
if self._drop is not None:
|
||||
for box, value, ok in self._hit.get("drop_items", ()):
|
||||
if self._in(box, x, y):
|
||||
self._hover = ("drop", value)
|
||||
if ok:
|
||||
self._drop_index = self.choices(self._drop_row()).index(value)
|
||||
return
|
||||
if self._in(self._hit.get("drop", (0, 0, 0, 0)), x, y):
|
||||
return
|
||||
for i, box in enumerate(self._hit.get("tabs", ())):
|
||||
if self._in(box, x, y):
|
||||
self._hover = ("tab", i)
|
||||
@@ -281,17 +383,104 @@ class Menu:
|
||||
i = self._row_at(x, y)
|
||||
if i is not None and (i != self.index or self.focus != "rows"):
|
||||
self.focus, self.armed = "rows", False
|
||||
self._select(i)
|
||||
self._select(i, reveal=False)
|
||||
|
||||
def cursor(self, x: float, y: float) -> str:
|
||||
"""The mouse pointer to show here: "move" on the title bar, "hand" on something to click, else "arrow"."""
|
||||
if self._drag is not None:
|
||||
return "hand"
|
||||
if self._drop is not None and self._in(self._hit.get("drop", (0, 0, 0, 0)), x, y):
|
||||
return "hand"
|
||||
if self._in(self._hit.get("close", (0, 0, 0, 0)), x, y) or any(self._in(b, x, y) for b in self._hit.get("tabs", ())):
|
||||
return "hand"
|
||||
if self._in(self._hit.get("title", (0, 0, 0, 0)), x, y):
|
||||
return "move"
|
||||
i = self._row_at(x, y)
|
||||
if i is not None and any(self._in(b, x, y) for b, _, _ in self._hit.get("controls", {}).get(i, ())):
|
||||
return "hand"
|
||||
if self._in(self._hit.get("scrollbar", (0, 0, 0, 0)), x, y):
|
||||
return "hand"
|
||||
return "arrow"
|
||||
|
||||
def scroll(self, dy: float) -> None:
|
||||
"""The wheel moves the highlight (and the list with it)."""
|
||||
if dy:
|
||||
self.focus, self.armed = "rows", False
|
||||
self._select(self.index + (-1 if dy > 0 else 1))
|
||||
"""The wheel scrolls the page (or an open list) a row a step; the highlight stays on its row."""
|
||||
if not dy:
|
||||
return
|
||||
self._wheel += dy
|
||||
steps = int(self._wheel) # whole rows; a touchpad's fractions wait until they add up to one
|
||||
if not steps:
|
||||
return
|
||||
self._wheel -= steps
|
||||
if self._drop is not None:
|
||||
n = len(self.choices(self._drop_row()))
|
||||
self._drop_scroll = max(0, min(self._drop_scroll - steps, n - DROP_VISIBLE))
|
||||
return
|
||||
n = len(self.rows())
|
||||
self._scroll = max(0, min(self._scroll - steps, n - VISIBLE))
|
||||
|
||||
def _drop_row(self) -> Row | None:
|
||||
return next((r for r in self.rows() if r.key == self._drop), None)
|
||||
|
||||
def grab(self, x: float, y: float) -> str | None:
|
||||
"""A press that may start a drag: "move" on the title bar (the window moves the overlay: framegen/io.py),
|
||||
"drag" on a slider or the scrollbar (followed here by drag() until release()), else None (then click())."""
|
||||
if self._drop is not None:
|
||||
return None # a list is open: a press picks from it or closes it (click)
|
||||
if self._in(self._hit.get("close", (0, 0, 0, 0)), x, y):
|
||||
return None
|
||||
if self._in(self._hit.get("title", (0, 0, 0, 0)), x, y):
|
||||
return "move"
|
||||
sb = self._hit.get("scrollbar")
|
||||
if sb and self._in(sb, x, y):
|
||||
thumb = self._hit.get("thumb", sb)
|
||||
if not (thumb[1] <= y < thumb[3]): # on the track: the page jumps there, then follows the drag
|
||||
frac = (y - sb[1]) / max(1, sb[3] - sb[1])
|
||||
self._scroll = max(0, min(len(self.rows()) - VISIBLE, round(frac * len(self.rows()) - VISIBLE / 2)))
|
||||
self._drag = ("scrollbar", y, self._scroll)
|
||||
return "drag"
|
||||
i = self._row_at(x, y)
|
||||
if i is not None:
|
||||
for box, what, arg in self._hit.get("controls", {}).get(i, ()):
|
||||
if what == "slider" and self._in(box, x, y):
|
||||
rows = self.rows()
|
||||
self.focus, self.armed = "rows", False
|
||||
self._select(i, rows, reveal=False)
|
||||
self._drag = ("slider", i, arg)
|
||||
self._slide(rows[i], x, arg)
|
||||
return "drag"
|
||||
return None
|
||||
|
||||
def drag(self, x: float, y: float) -> None:
|
||||
d = self._drag
|
||||
if d is None:
|
||||
return
|
||||
if d[0] == "slider":
|
||||
rows = self.rows()
|
||||
if d[1] < len(rows):
|
||||
self._slide(rows[d[1]], x, d[2])
|
||||
elif d[0] == "scrollbar":
|
||||
sb = self._hit.get("scrollbar", (0, 0, 0, 1))
|
||||
n = len(self.rows())
|
||||
per_px = n / max(1, sb[3] - sb[1])
|
||||
self._scroll = max(0, min(n - VISIBLE, d[2] + round((y - d[1]) * per_px)))
|
||||
|
||||
def release(self) -> None:
|
||||
self._drag = None
|
||||
|
||||
def click(self, x: float, y: float, right: bool = False) -> str | None:
|
||||
"""A click: Close, a tab, an action row, or a setting: on one of its choices picks that one, on an arrow
|
||||
steps, anywhere else on the row is the next choice (right-click: the one before). Returns as key()."""
|
||||
"""A click: Close, a tab, a choice in an open list (outside it: the list closes), an action row, or a
|
||||
setting's control: a switch flips, a button picks its choice, a list opens; anywhere else on a setting's row
|
||||
is the next choice (right-click: the one before). Returns as key()."""
|
||||
if self._drop is not None:
|
||||
for box, value, ok in self._hit.get("drop_items", ()):
|
||||
if self._in(box, x, y):
|
||||
if ok:
|
||||
self.set_value(self._drop_row(), value)
|
||||
self._drop = None
|
||||
return None
|
||||
if not self._in(self._hit.get("drop", (0, 0, 0, 0)), x, y):
|
||||
self._drop = None
|
||||
return None
|
||||
if self._in(self._hit.get("close", (0, 0, 0, 0)), x, y):
|
||||
return "close"
|
||||
tabs = self.tabs()
|
||||
@@ -306,7 +495,7 @@ class Menu:
|
||||
return None
|
||||
rows = self.rows()
|
||||
self.focus = "rows"
|
||||
self._select(i, rows)
|
||||
self._select(i, rows, reveal=False)
|
||||
row = rows[i]
|
||||
if row.kind == "action":
|
||||
if right:
|
||||
@@ -316,19 +505,29 @@ class Menu:
|
||||
self.armed = False
|
||||
return self._act(row)
|
||||
self.armed = False
|
||||
if self.off(row):
|
||||
return None
|
||||
for box, what, arg in self._hit.get("controls", {}).get(i, ()):
|
||||
if self._in(box, x, y):
|
||||
if what == "set":
|
||||
self.set_value(row, arg)
|
||||
elif what == "list":
|
||||
self._open_drop(row)
|
||||
elif what == "slider":
|
||||
self._slide(row, x, arg)
|
||||
else:
|
||||
self.step(row, arg)
|
||||
return None
|
||||
self.step(row, -1 if right else 1)
|
||||
if self.kind_of(row) == "list" and not right:
|
||||
self._open_drop(row)
|
||||
else:
|
||||
self.step(row, -1 if right else 1)
|
||||
return None
|
||||
|
||||
def _shown(self) -> tuple:
|
||||
"""What the drawing depends on, but for the header's live numbers."""
|
||||
return (self.tab, self.focus, self.index, self._scroll, self.armed, self._hover, self.title, self.toggle_key,
|
||||
self._drop, self._drop_index, self._drop_scroll, self._drag and self._drag[0],
|
||||
tuple(self.settings.values().items()), tuple(self.restart_reasons()),
|
||||
tuple(self.disabled(s.key) for s in self.specs))
|
||||
|
||||
@@ -446,13 +645,16 @@ class Menu:
|
||||
controls[i] = self._control(c, row, xr, mid, lit, px, f_value)
|
||||
|
||||
n = len(rows)
|
||||
if n > VISIBLE: # a scrollbar, at the right edge
|
||||
scrollbar = thumb = None
|
||||
if n > VISIBLE: # a scrollbar at the right edge: drag its thumb, or click the track to jump
|
||||
top, span = y_rows + px(4), VISIBLE * row_h - px(8)
|
||||
bx = W - px(9)
|
||||
c.rrect(bx, top, bx + px(3), top + span, px(2), fill=U.SURFACE)
|
||||
th = max(px(24), span * VISIBLE // n)
|
||||
bx = W - px(12)
|
||||
c.rrect(bx, top, bx + px(6), top + span, px(3), fill=U.SURFACE)
|
||||
th = max(px(28), span * VISIBLE // n)
|
||||
ty = top + (span - th) * self._scroll // (n - VISIBLE)
|
||||
c.rrect(bx, ty, bx + px(3), ty + th, px(2), fill=U.FAINT)
|
||||
dragging = self._drag is not None and self._drag[0] == "scrollbar"
|
||||
c.rrect(bx, ty, bx + px(6), ty + th, px(3), fill=U.DIM if dragging else U.FAINT)
|
||||
scrollbar, thumb = (bx - px(6), top, W, top + span), (bx - px(6), ty, W, ty + th)
|
||||
|
||||
# -- what the highlighted row does
|
||||
row = rows[self.index]
|
||||
@@ -500,10 +702,51 @@ class Menu:
|
||||
x += c.text(x, fy, what, f_hint, U.DIM) + px(18)
|
||||
x = x1 - px(4)
|
||||
x -= c.text(x, fy, "Show / hide", f_hint, U.DIM, "rm") + px(8)
|
||||
cap(x, self.toggle_key, right=True)
|
||||
x = cap(x, self.toggle_key, right=True) - px(18)
|
||||
c.text(x, fy, "Drag the title to move", f_hint, U.FAINT, "rm")
|
||||
|
||||
# -- an open drop-down list, over everything below its row
|
||||
drop_box, drop_items = None, []
|
||||
drow = next((r for r in rows if r.key == self._drop), None)
|
||||
di = rows.index(drow) if drow is not None else -1
|
||||
if drow is not None and self._scroll <= di < self._scroll + VISIBLE and di in controls:
|
||||
anchor = next((b for b, what, _ in controls[di] if what == "list"), None)
|
||||
if anchor is not None:
|
||||
choices = self.choices(drow)
|
||||
item_h = px(36)
|
||||
shown = min(len(choices), DROP_VISIBLE)
|
||||
lw = max(anchor[2] - anchor[0], max(U.text_w(self.name(drow, v), f_value) for v in choices) + px(52))
|
||||
lx1 = anchor[2]
|
||||
lx0 = max(px(8), lx1 - lw)
|
||||
lh = shown * item_h + px(12)
|
||||
ly0 = anchor[3] + px(4)
|
||||
if ly0 + lh > H - px(8): # no room below: above the row instead
|
||||
ly0 = max(px(8), anchor[1] - px(4) - lh)
|
||||
drop_box = (lx0, ly0, lx1, ly0 + lh)
|
||||
c.rrect(lx0 + px(2), ly0 + px(4), lx1 + px(2), ly0 + lh + px(4), px(12), fill=(6, 8, 12)) # shadow
|
||||
c.rrect(*drop_box, px(12), fill=U.RAISED, outline=U.BORDER)
|
||||
value = self.value(drow)
|
||||
for k in range(self._drop_scroll, min(len(choices), self._drop_scroll + shown)):
|
||||
v = choices[k]
|
||||
iy = ly0 + px(6) + (k - self._drop_scroll) * item_h
|
||||
box = (lx0 + px(6), iy, lx1 - px(6), iy + item_h)
|
||||
ok = self.can(drow, v)
|
||||
if k == self._drop_index and ok:
|
||||
c.rrect(*box, px(8), fill=U.HILITE)
|
||||
if v == value:
|
||||
c.chevron(box[0] + px(16), iy + item_h // 2, px(9), "right", U.ACCENT) # the one in use
|
||||
c.text(box[0] + px(30), iy + item_h // 2, self.name(drow, v), f_value,
|
||||
(U.ACCENT if v == value else U.TEXT) if ok else U.OFF)
|
||||
drop_items.append((box, v, ok))
|
||||
if len(choices) > shown: # more below or above: a thin bar
|
||||
span = lh - px(16)
|
||||
th = max(px(18), span * shown // len(choices))
|
||||
ty = ly0 + px(8) + (span - th) * self._drop_scroll // (len(choices) - shown)
|
||||
c.rrect(lx1 - px(6), ty, lx1 - px(3), ty + th, px(2), fill=U.FAINT)
|
||||
|
||||
self._hit = {"w": W, "h": H, "rows": (x0, y_rows, x1, y_rows + VISIBLE * row_h), "row_h": row_h,
|
||||
"tabs": tab_boxes, "close": close, "controls": controls}
|
||||
"tabs": tab_boxes, "close": close, "controls": controls, "title": (0, 0, W, head_h),
|
||||
"scrollbar": scrollbar, "thumb": thumb, "drop": drop_box, "drop_items": drop_items}
|
||||
self._drawn = (key, c)
|
||||
return c.rgba(opacity, (U.SURFACE,))
|
||||
|
||||
@@ -539,11 +782,12 @@ class Menu:
|
||||
return close
|
||||
|
||||
def _control(self, c: U.Canvas, row: Row, xr: int, mid: int, lit: bool, px, f) -> list:
|
||||
"""Draws a row's value, ending at xr: a switch for on/off, the choices side by side when they're few and
|
||||
short, else the value between two arrows. Returns what a click does where: [(box, "set" | "step", arg)]."""
|
||||
"""Draws a row's control, ending at xr (kind_of): a switch, buttons side by side, a slider, or a drop-down
|
||||
button. Returns what a click does where: [(box, "set" | "step" | "slider" | "list", arg)]."""
|
||||
choices, value = self.choices(row), self.value(row)
|
||||
kind = self.kind_of(row)
|
||||
hits: list = []
|
||||
if set(choices) == {True, False}:
|
||||
if kind == "switch":
|
||||
w, h = px(42), px(24)
|
||||
on = bool(value)
|
||||
box = (xr - w, mid - h // 2, xr, mid - h // 2 + h)
|
||||
@@ -552,9 +796,9 @@ class Menu:
|
||||
c.circle(xr - h // 2 if on else xr - w + h // 2, mid, r, (255, 255, 255) if on else U.DIM)
|
||||
c.text(xr - w - px(12), mid, self.name(row, value), f, U.TEXT if on else U.DIM, "rm")
|
||||
return [((xr - w - px(60), mid - h, xr, mid + h), "step", 1)]
|
||||
names = [self.name(row, v) for v in choices]
|
||||
widths = [U.text_w(n, f) + 2 * px(13) for n in names]
|
||||
if len(choices) <= 4 and sum(widths) <= px(440):
|
||||
if kind == "buttons":
|
||||
names = [self.name(row, v) for v in choices]
|
||||
widths = [U.text_w(n, f) + 2 * px(13) for n in names]
|
||||
h = px(30)
|
||||
x = xr - sum(widths)
|
||||
c.rrect(x - px(3), mid - h // 2 - px(3), xr + px(3), mid + h // 2 + px(3), px(10), fill=U.BG, outline=U.BORDER)
|
||||
@@ -570,13 +814,45 @@ class Menu:
|
||||
hits.append(((x, mid - h, x + w, mid + h), "set", v))
|
||||
x += w
|
||||
return hits
|
||||
col = U.ACCENT if lit else U.FAINT
|
||||
c.chevron(xr - px(6), mid, px(11), "right", col)
|
||||
tw = c.text(xr - px(24), mid, self.name(row, value), f, U.TEXT if lit else U.DIM, "rm")
|
||||
left = xr - px(24) - tw - px(18)
|
||||
c.chevron(left, mid, px(11), "left", col)
|
||||
return [((left - px(14), mid - px(18), left + px(14), mid + px(18)), "step", -1),
|
||||
((xr - px(20), mid - px(18), xr + px(8), mid + px(18)), "step", 1)]
|
||||
if kind == "slider":
|
||||
# A track with a mark for each choice (the ones that can't be picked are dim), the value before it
|
||||
choices = self.ordered(row)
|
||||
tw, knob = px(220), px(9)
|
||||
tx1 = xr - knob
|
||||
tx0 = tx1 - tw
|
||||
n = len(choices)
|
||||
i = choices.index(value) if value in choices else None
|
||||
pos = (tx0 + tw * i / (n - 1)) if i is not None else None
|
||||
if pos is None and isinstance(value, (int, float)): # a value between the choices (a custom one)
|
||||
lo, hi = choices[0], choices[-1]
|
||||
k = 0.0 if hi == lo else (value - lo) / (hi - lo)
|
||||
below = [j for j, v in enumerate(choices) if v <= value]
|
||||
j = below[-1] if below else 0
|
||||
if j < n - 1:
|
||||
k = j + (value - choices[j]) / (choices[j + 1] - choices[j])
|
||||
pos = tx0 + tw * k / (n - 1)
|
||||
else:
|
||||
pos = tx1
|
||||
pos = tx0 if pos is None else pos
|
||||
c.rrect(tx0, mid - px(3), tx1, mid + px(3), px(3), fill=U.HILITE)
|
||||
c.rrect(tx0, mid - px(3), max(tx0 + px(6), int(pos)), mid + px(3), px(3), fill=U.ACCENT if lit else U.DIM)
|
||||
for j, v in enumerate(choices):
|
||||
mx = int(tx0 + tw * j / (n - 1))
|
||||
c.circle(mx, mid, px(2), U.TEXT if j <= (i if i is not None else -1) else (U.FAINT if self.can(row, v) else U.OFF))
|
||||
dragging = self._drag is not None and self._drag[0] == "slider" and self._drag[1] == self.index and lit
|
||||
c.circle(int(pos), mid, knob + (px(2) if dragging else 0), (255, 255, 255))
|
||||
c.circle(int(pos), mid, knob - px(4), U.ACCENT if lit else U.DIM)
|
||||
c.text(tx0 - px(16), mid, self.name(row, value), f, U.TEXT if lit else U.DIM, "rm")
|
||||
return [((tx0 - knob - px(4), mid - px(16), tx1 + knob + px(4), mid + px(16)), "slider", (tx0, tx1))]
|
||||
# a drop-down list: the value in a box with a down arrow; a click opens the list (drawn in render)
|
||||
text = self.name(row, value)
|
||||
bw = max(px(190), U.text_w(text, f) + px(56))
|
||||
box = (xr - bw, mid - px(16), xr, mid + px(16))
|
||||
is_open = self._drop == row.key
|
||||
c.rrect(*box, px(8), fill=U.RAISED if (lit or is_open) else U.SURFACE, outline=U.ACCENT if is_open else U.BORDER)
|
||||
c.text(box[0] + px(14), mid, U.fit(text, f, bw - px(48)), f, U.TEXT if lit or is_open else U.DIM)
|
||||
c.chevron(xr - px(18), mid, px(10), "up" if is_open else "down", U.ACCENT if lit or is_open else U.FAINT)
|
||||
return [(box, "list", None)]
|
||||
|
||||
|
||||
def _span(seconds: int) -> str:
|
||||
|
||||
+29
-11
@@ -29,6 +29,16 @@ HUD_OFF_LEVELS = 12
|
||||
VISIBLE_LEVELS = HUD_OFF_LEVELS
|
||||
|
||||
|
||||
|
||||
def cadence_steps(hz: int) -> tuple[list[float], list[float]]:
|
||||
"""Where between two real frames of a 30 fps game the generated frames go at output rate `hz` (N = hz / 30 frames
|
||||
per real one, the frame multiplier): the first list on the real frame's own 60 Hz tick (the last of them ends
|
||||
that tick), the second on the next tick, before the real frame itself. 60: [1/2] and []; 90: [1/3, 2/3] and [];
|
||||
120: [1/4, 1/2] and [3/4]; 180: [1/6, 2/6, 3/6] and [4/6, 5/6]."""
|
||||
n = max(2, hz // 30)
|
||||
h = (n + 1) // 2
|
||||
return [j / n for j in range(1, h + 1)], [j / n for j in range(h + 1, n)]
|
||||
|
||||
def pct(share: float) -> str:
|
||||
"""0.062 -> "6.2%", 0.12 -> "12%": a share as people read it."""
|
||||
v = 100 * share
|
||||
@@ -228,7 +238,7 @@ class Stats:
|
||||
f"{sum(b > TICK * 1000 for b in self.busy_ms)}")
|
||||
if self.quarter_shown or self.quarter_skipped:
|
||||
due = self.quarter_shown + self.quarter_skipped
|
||||
lines.append(f"extra in-between frames (90/120 Hz) shown {self.quarter_shown} of {due} "
|
||||
lines.append(f"extra in-between frames (above 60 fps) shown {self.quarter_shown} of {due} "
|
||||
f"({100 * self.quarter_shown / due:.0f}%); the rest fell back to 60 Hz because it was behind")
|
||||
if self.dedup:
|
||||
lines.append(f"dedup vs truth: {dict(self.dedup)}")
|
||||
@@ -273,7 +283,7 @@ class Stats:
|
||||
"was still busy with earlier ones")
|
||||
due = self.quarter_shown + self.quarter_skipped
|
||||
if due:
|
||||
lines.append(f"Extra frames for 90/120 fps: {100 * self.quarter_shown / due:.0f}% shown; the rest fell "
|
||||
lines.append(f"Extra frames above 60 fps: {100 * self.quarter_shown / due:.0f}% shown; the rest fell "
|
||||
"back to 60 fps because the PC was behind")
|
||||
if delay:
|
||||
lines.append(f"Delay: a real frame reached the screen {np.median(delay):.0f} ms after it arrived (median)")
|
||||
@@ -419,8 +429,8 @@ class Pipeline:
|
||||
at 1/3 and 2/3, where a 60 fps game has no real frame to compare against."""
|
||||
text = "TEST: 60 fps game played as 30 fps"
|
||||
q = list(zip(st.off_interp[-30:], st.off_repeat[-30:]))
|
||||
if enabled and hz == 90:
|
||||
text += " quality: measured at 60 and 120 fps"
|
||||
if enabled and cadence_steps(hz)[0][-1] != 0.5: # odd multipliers have no frame at 1/2 to score
|
||||
text += " quality: measured at even multipliers (2x, 4x...)"
|
||||
elif enabled and q:
|
||||
text += (f" quality: {pct(np.mean([x for x, _ in q]))} visibly off from the real frames"
|
||||
f" (no AI {pct(np.mean([y for _, y in q]))})")
|
||||
@@ -631,7 +641,7 @@ class Pipeline:
|
||||
if not extra_ok:
|
||||
st.quarter_skipped += 1
|
||||
return False
|
||||
early_cmd = present(self._generated(it.interpolate(slot, t), gpu_out), ov_text)
|
||||
early_cmd = present(self._generated(it.interpolate(slot, t), gpu_out), ov_text) or early_cmd
|
||||
st.quarter_shown += 1
|
||||
return True
|
||||
|
||||
@@ -700,12 +710,20 @@ class Pipeline:
|
||||
else:
|
||||
out, reached = frame, pl.reached
|
||||
action = Action.INTERP if pl.b is not None else Action.CURRENT
|
||||
elif hz == 120 and action is Action.INTERP:
|
||||
show_early(0.25)
|
||||
elif hz == 120 and quarter_due and action is Action.CURRENT and not is_new:
|
||||
show_early(0.75)
|
||||
elif hz == 90 and action is Action.INTERP and show_early(1 / 3):
|
||||
mid_t = 2 / 3
|
||||
elif hz > 60 and action is Action.INTERP:
|
||||
# N frames for each real one (N = hz / 30): its own tick shows 1/N .. h/N, the next tick the
|
||||
# rest and then the real frame (cadence_steps). Behind: the rest of them are left out, and the
|
||||
# tick ends on the 60 fps frame (1/2).
|
||||
first = cadence_steps(hz)[0]
|
||||
for t in first[:-1]:
|
||||
if not show_early(t):
|
||||
break
|
||||
else:
|
||||
mid_t = first[-1]
|
||||
elif hz > 60 and quarter_due and action is Action.CURRENT and not is_new:
|
||||
for t in cadence_steps(hz)[1]:
|
||||
if not show_early(t):
|
||||
break
|
||||
quarter_due = action is Action.INTERP
|
||||
if timed:
|
||||
pass # shown above
|
||||
|
||||
@@ -88,8 +88,8 @@ def vfx_reason() -> str | None:
|
||||
return ("it comes with NVIDIA VFG's download from NVIDIA, which SmoovPlay offers on RTX 40 and 50 series "
|
||||
"cards. AMD FSR 1 works on any card")
|
||||
if not installed():
|
||||
return ("it comes with NVIDIA VFG's download from NVIDIA: set up NVIDIA VFG on SmoovPlay's Settings page "
|
||||
"(Interpolation model). AMD FSR 1 works on any card")
|
||||
return ("it comes with NVIDIA's VFG download: Summit's Settings, NVIDIA VFG and RTX VSR, downloads it "
|
||||
"(or `summit nvidia install`). AMD FSR 1 works on any card")
|
||||
return None
|
||||
|
||||
|
||||
|
||||
+38
-11
@@ -45,8 +45,14 @@ class Spec:
|
||||
elsewhere: dict = field(default_factory=dict) # source kind -> why it isn't used there ("": any other source)
|
||||
|
||||
def name(self, value: Any) -> str:
|
||||
if self.key == "hz" and value not in self.names and valid_hz(value): # a custom multiplier
|
||||
return f"{value // 30}x ({value} fps)"
|
||||
return self.names.get(value, str(value))
|
||||
|
||||
def accepts(self, value: Any) -> bool:
|
||||
"""One of the choices, or (Frame multiplier) any multiple of 30 fps that valid_hz takes."""
|
||||
return value in self.choices or (self.key == "hz" and valid_hz(value))
|
||||
|
||||
def applies_to(self, values: dict) -> bool:
|
||||
"""Whether this setting is used with these values (e.g. VFG quality only while NVIDIA VFG is picked)."""
|
||||
return not self.applies or values.get(self.applies[0]) in self.applies[1]
|
||||
@@ -58,6 +64,14 @@ class Spec:
|
||||
return self.elsewhere.get(source) or self.elsewhere.get("") or "Not used with this source."
|
||||
|
||||
|
||||
HZ_MIN, HZ_MAX = 60, 300 # Frame multiplier 2x .. 10x (of a 30 fps game)
|
||||
|
||||
|
||||
def valid_hz(value: Any) -> bool:
|
||||
"""An output rate the pipeline can show: a whole multiplier (2x to 10x) of a 30 fps game."""
|
||||
return isinstance(value, int) and not isinstance(value, bool) and HZ_MIN <= value <= HZ_MAX and value % 30 == 0
|
||||
|
||||
|
||||
ON_OFF = {True: "On", False: "Off"}
|
||||
OPACITY = (1.0, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3) # menu and stats opacity choices
|
||||
PCT = {v: f"{round(v * 100)}%" for v in OPACITY}
|
||||
@@ -77,16 +91,23 @@ SPECS: tuple[Spec, ...] = (
|
||||
help="Draws new frames between the ones the game sends, so a 30 fps game moves like 60, 90 or 120 fps. "
|
||||
"Off shows the stream exactly as it arrives. In the video window, I turns it off and on for this "
|
||||
"session only, to compare."),
|
||||
Spec("hz", "Output frame rate", (60, 90, 120), 60, {60: "60 fps", 90: "90 fps", 120: "120 fps"},
|
||||
# Frame generation's multiplier: N frames shown for each real frame of a 30 fps game, so N x 30 fps out (the value
|
||||
# is that rate). Any multiple of 30 from 60 to 300 works (HZ_MIN..HZ_MAX: `--hz`, a game's Summit profile); the
|
||||
# menu steps through these.
|
||||
Spec("hz", "Frame multiplier", (60, 90, 120, 150, 180, 240), 60,
|
||||
{hz: f"{hz // 30}x ({hz} fps)" for hz in (60, 90, 120, 150, 180, 240)},
|
||||
group="Smoothness", quick=True,
|
||||
hints={60: "One new frame for each real one. Any supported graphics card, any display. Adds about 20\u00a0ms of delay.",
|
||||
90: "Two new frames for each real one. Needs a 90\u00a0Hz or faster display. Adds about 40\u00a0ms of "
|
||||
"delay.",
|
||||
120: "Three for each real one. Needs a 120\u00a0Hz display and a fast card. Adds about 40\u00a0ms of "
|
||||
"delay."},
|
||||
help="How many frames you see each second. Higher is smoother, but needs a faster graphics card and a "
|
||||
"display that runs at least that fast (G-Sync or FreeSync helps). Auto-detect, on SmoovPlay's "
|
||||
"Settings page, picks the most this PC keeps up with."),
|
||||
"delay.",
|
||||
150: "Four for each real one. Needs a 144\u00a0Hz or faster display and a fast card.",
|
||||
180: "Five for each real one. Needs a 180\u00a0Hz or faster display and a very fast card.",
|
||||
240: "Seven for each real one. Needs a 240\u00a0Hz display and a very fast card."},
|
||||
help="How many frames you see for each one the game draws (of a 30 fps game: 2x is 60 fps, 4x is 120). "
|
||||
"Higher is smoother, but needs a faster graphics card and a display that runs at least that fast "
|
||||
"(G-Sync or FreeSync helps). When the card can't keep up, the extra frames are left out for a moment."),
|
||||
# framegen/cadence.py FrameTimeline. Tried on simulated 40-55 fps games (tests/test_timeline.py), not a real one yet.
|
||||
Spec("even_out", "Even out 40-60 fps", (True, False), True, ON_OFF, group="Smoothness",
|
||||
applies=("interp", (True,)),
|
||||
@@ -170,13 +191,14 @@ SPECS: tuple[Spec, ...] = (
|
||||
"1440p capture at 90, a quarter for a 4K capture, and Full otherwise. Only used with RIFE.",
|
||||
impact={"picture": "Half is a little softer on small, fast details.",
|
||||
"speed": "Half takes about 40% less time per AI frame."}),
|
||||
Spec("scaler", "Upscaler", ("fsr", "vsr", "bilinear"), "fsr",
|
||||
{"fsr": "AMD FSR 1", "vsr": "NVIDIA RTX VSR", "bilinear": "Bilinear"}, group="Picture", quick=True,
|
||||
Spec("scaler", "Upscaler", ("off", "fsr", "vsr", "bilinear"), "fsr",
|
||||
{"off": "Off", "fsr": "AMD FSR 1", "vsr": "NVIDIA RTX VSR", "bilinear": "Bilinear"}, group="Picture", quick=True,
|
||||
later="Support for other upscalers may come in a later version.",
|
||||
hints={"fsr": "Sharp and almost free: about 0.1\u00a0ms a frame. Recommended.",
|
||||
"vsr": "NVIDIA's AI upscaler, Experimental. It comes with NVIDIA VFG's download (RTX 40 and 50 "
|
||||
"series); without it, FSR\u00a01 is used. Heavier.",
|
||||
"bilinear": "Plain resizing, the softest. For comparison."},
|
||||
"bilinear": "Plain resizing, the softest. For comparison.",
|
||||
"off": "No upscaling: the picture at its own size, in the middle of the screen. Never enlarged."},
|
||||
help="Enlarges the picture from the game (usually 1080p) to fill your window or screen, so it only "
|
||||
"matters when that's bigger than 1080p, like a 1440p or 4K display. Key: U.",
|
||||
impact={"picture": "Only matters on a display bigger than the stream, like 1440p or 4K.",
|
||||
@@ -392,7 +414,7 @@ class Settings:
|
||||
self._v = {s.key: s.default for s in SPECS}
|
||||
self._saved = dict(self._v) # what the file holds (or would)
|
||||
for k, v in (values or {}).items():
|
||||
if k in BY_KEY and BY_KEY[k].saved and v in BY_KEY[k].choices:
|
||||
if k in BY_KEY and BY_KEY[k].saved and BY_KEY[k].accepts(v):
|
||||
self._v[k] = self._saved[k] = v
|
||||
|
||||
@classmethod
|
||||
@@ -425,7 +447,7 @@ class Settings:
|
||||
self._put(key, value, save=True)
|
||||
|
||||
def _put(self, key: str, value: Any, save: bool) -> None:
|
||||
if value not in BY_KEY[key].choices:
|
||||
if not BY_KEY[key].accepts(value):
|
||||
raise ValueError(f"{key}: {value!r} is not one of {BY_KEY[key].choices}")
|
||||
changed = self._v[key] != value
|
||||
self._v[key] = value
|
||||
@@ -439,7 +461,12 @@ class Settings:
|
||||
def step(self, key: str, delta: int, allowed=None) -> Any:
|
||||
"""Move to the next/previous choice (wrapping), skipping values `allowed(key, value)` rejects."""
|
||||
choices = BY_KEY[key].choices
|
||||
i = choices.index(self._v[key])
|
||||
cur = self._v[key]
|
||||
if cur in choices:
|
||||
i = choices.index(cur)
|
||||
else: # a custom value (Frame multiplier): step from where it falls among the choices
|
||||
below = [j for j, c in enumerate(choices) if c < cur]
|
||||
i = (below[-1] + (1 if delta < 0 else 0)) if below else (len(choices) if delta < 0 else -1)
|
||||
for _ in range(len(choices)):
|
||||
i = (i + delta) % len(choices)
|
||||
if allowed is None or allowed(key, choices[i]):
|
||||
|
||||
@@ -20,7 +20,8 @@ import torch
|
||||
from .vfg_setup import MIN_COMPUTE, add_to_path, installed
|
||||
|
||||
QUALITY = {"low": 0, "medium": 1, "high": 2}
|
||||
NOT_SET_UP = "NVIDIA VFG isn't set up on this PC. SmoovPlay's Settings page downloads it from NVIDIA."
|
||||
NOT_SET_UP = ("NVIDIA VFG isn't set up on this PC. Summit's Settings (NVIDIA VFG and RTX VSR) downloads it from "
|
||||
"NVIDIA, or `summit nvidia install`.")
|
||||
|
||||
|
||||
def import_vfx():
|
||||
|
||||
@@ -111,6 +111,19 @@ def status(folder: str) -> dict:
|
||||
}
|
||||
|
||||
|
||||
def has_pip() -> bool:
|
||||
return importlib.util.find_spec("pip") is not None
|
||||
|
||||
|
||||
def find_uv() -> str | None:
|
||||
"""uv, which made Summit's venv (install.sh): on PATH, or where its installer puts it."""
|
||||
home = Path.home()
|
||||
for c in (shutil.which("uv"), home / ".local/bin/uv", home / ".cargo/bin/uv"):
|
||||
if c and Path(c).is_file() and os.access(c, os.X_OK):
|
||||
return str(c)
|
||||
return None
|
||||
|
||||
|
||||
def install(folder: str, proxy: str = "") -> int:
|
||||
"""Download and install the pinned package into `folder` (replacing an earlier install of ours). pip's output
|
||||
goes to stdout as it comes (--progress-bar raw: "Progress <bytes> of <total>" lines for the launcher)."""
|
||||
@@ -135,16 +148,22 @@ def install(folder: str, proxy: str = "") -> int:
|
||||
with tempfile.TemporaryDirectory(dir=target.parent) as tmp:
|
||||
req = Path(tmp) / "vfg-requirements.txt"
|
||||
req.write_text(f"{PACKAGE}=={VERSION} --hash=sha256:{WHEEL_SHA256}\n", encoding="utf-8")
|
||||
cmd = [sys.executable, "-m", "pip", "install", "--target", str(staging), "--only-binary", ":all:",
|
||||
"--no-deps", "--require-hashes", "--index-url", INDEX, "--no-cache-dir", "--progress-bar", "raw",
|
||||
"--disable-pip-version-check", "--no-warn-script-location", "-r", str(req)]
|
||||
uv = None if has_pip() else find_uv()
|
||||
if uv: # a venv made by uv has no pip: uv installs the same pinned file, hash checked the same way
|
||||
cmd = [uv, "pip", "install", "--python", sys.executable, "--target", str(staging), "--only-binary", ":all:",
|
||||
"--no-deps", "--require-hashes", "--index-url", INDEX, "--no-cache", "-r", str(req)]
|
||||
else:
|
||||
cmd = [sys.executable, "-m", "pip", "install", "--target", str(staging), "--only-binary", ":all:",
|
||||
"--no-deps", "--require-hashes", "--index-url", INDEX, "--no-cache-dir", "--progress-bar", "raw",
|
||||
"--disable-pip-version-check", "--no-warn-script-location", "-r", str(req)]
|
||||
if proxy:
|
||||
cmd += ["--proxy", proxy]
|
||||
cmd += ["--proxy", proxy] if not uv else []
|
||||
env = dict(os.environ, **({"HTTPS_PROXY": proxy, "HTTP_PROXY": proxy} if proxy and uv else {}))
|
||||
print(f"[vfg] downloading {PACKAGE} {VERSION} from {INDEX} (about {SIZE_MB} MB)", flush=True)
|
||||
rc = subprocess.run(cmd).returncode
|
||||
rc = subprocess.run(cmd, env=env).returncode
|
||||
if rc != 0:
|
||||
shutil.rmtree(staging, ignore_errors=True)
|
||||
print(f"[vfg] pip failed (exit code {rc})")
|
||||
print(f"[vfg] {'uv' if uv else 'pip'} failed (exit code {rc})")
|
||||
return rc
|
||||
# Check it loads, in another process: a loaded DLL would keep the folder from being renamed or removed.
|
||||
check = subprocess.run([sys.executable, "-c", f"import sys; sys.path.append({str(staging)!r}); import nvvfx"],
|
||||
|
||||
+12
-9
@@ -63,7 +63,7 @@ from framegen.interpolator import MODELS, RifeInterpolator
|
||||
from framegen.io import (TICK, CaptureSource, FileSink, FileSource, GLWindowSink, MultiSink, Ps5SimSource,
|
||||
WindowSink)
|
||||
from framegen.pipeline import Pipeline
|
||||
from framegen.settings import BY_KEY, DEFAULT_PATH, SPECS, Settings
|
||||
from framegen.settings import BY_KEY, DEFAULT_PATH, SPECS, Settings, valid_hz
|
||||
from framegen.sources import TestMode, make_detector
|
||||
from framegen.vfg import vfg_unavailable
|
||||
|
||||
@@ -333,17 +333,18 @@ def main() -> int:
|
||||
"delay in a window, G-Sync in a window). Default: the saved setting")
|
||||
ap.add_argument("--steady-hud", action=argparse.BooleanOptionalAction, default=None,
|
||||
help="keep unchanged parts of the picture (HUD, map) as the game drew them. Default: the saved setting")
|
||||
ap.add_argument("--scaler", default=None, choices=["fsr", "vsr", "bilinear"],
|
||||
help="how the window upscales when it is bigger than the frame (cycle live with 'u'); "
|
||||
ap.add_argument("--scaler", default=None, choices=["off", "fsr", "vsr", "bilinear"],
|
||||
help="how the window upscales when it is bigger than the frame (cycle live with 'u'); off = "
|
||||
"no upscaling, the picture at its own size; "
|
||||
"vsr = NVIDIA RTX Video Super Resolution, needs the RTX Video SDK (framegen/rtxvsr.py)")
|
||||
ap.add_argument("--vsr-quality", type=int, default=None, choices=[1, 2, 3, 4],
|
||||
help="RTX VSR quality: 1 low ... 4 ultra (more GPU time per frame)")
|
||||
ap.add_argument("--fsr-sharpness", type=float, default=None, choices=BY_KEY["fsr_sharpness"].choices,
|
||||
help="FSR 1 sharpening, in stops below maximum: 0 = sharpest, 1 = half, 2 = quarter")
|
||||
ap.add_argument("--hz", type=int, default=None, choices=[60, 90, 120],
|
||||
help="output rate for a 30 fps game: 120 = 3 generated frames per real one (half-res flow by "
|
||||
"default), 90 = 2 (needs a VRR/G-Sync screen or a 90 Hz mode to look even). Needs --display; "
|
||||
"falls back to 60 Hz output whenever it can't keep up")
|
||||
ap.add_argument("--hz", type=int, default=None, metavar="FPS",
|
||||
help="output rate, the frame multiplier for a 30 fps game: 60 (2x), 90 (3x), 120 (4x) ... 300 "
|
||||
"(10x), any multiple of 30. Above 60 needs --display; the extra frames are left out for a "
|
||||
"moment whenever it can't keep up")
|
||||
ap.add_argument("--display-cv", action="store_true", help="use the (slow) OpenCV window instead of OpenGL")
|
||||
ap.add_argument("--out", help="write output video")
|
||||
ap.add_argument("--score", action="store_true", help="[sim] PSNR of interpolated frames vs real dropped frames")
|
||||
@@ -355,6 +356,8 @@ def main() -> int:
|
||||
help="when test mode (a simulated 30 fps game) or --score was used, write a plain-language report "
|
||||
"of performance and quality here: every 10 s while playing, and at the end")
|
||||
a = ap.parse_args()
|
||||
if a.hz is not None and not valid_hz(a.hz):
|
||||
ap.error(f"--hz {a.hz}: a multiple of 30 from 60 to 300 (the frame multiplier 2x to 10x)")
|
||||
if a.monitor:
|
||||
import framegen.io as _io
|
||||
_io.MONITOR = a.monitor
|
||||
@@ -467,7 +470,7 @@ def main() -> int:
|
||||
settings.watch(lambda key: test.set_on(settings.simulate_30) if key == "simulate_30" else None)
|
||||
if settings.hz > 60 and (a.out or not a.display):
|
||||
if a.hz is not None:
|
||||
ap.error("--hz 90/120 needs --display, and doesn't write --out yet")
|
||||
ap.error("--hz above 60 needs --display, and doesn't write --out yet")
|
||||
print(f"[run] output {settings.hz} Hz needs --display without --out; 60 Hz this run")
|
||||
settings.override("hz", 60)
|
||||
|
||||
@@ -518,7 +521,7 @@ def main() -> int:
|
||||
# quarter (full 52 ms, half 36, quarter 30: its motion worked out at 960x540, as half's is at 1080p).
|
||||
scale = {"full": 1.0, "half": 0.5}.get(settings.motion) or (
|
||||
0.25 if src.h > 1440 else
|
||||
0.5 if settings.hz == 120 or (src.h > 1080 and settings.hz >= 90) else 1.0)
|
||||
0.5 if settings.hz >= 120 or (src.h > 1080 and settings.hz >= 90) else 1.0)
|
||||
engine = auto_engine(scale) if settings.engine == "auto" else settings.engine
|
||||
if dml_mode:
|
||||
engine = "dml"
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
"""Frame multiplier: N generated-frame positions per real frame of a 30 fps game (pipeline.cadence_steps), and the
|
||||
settings that take any multiple of 30 fps from 60 to 300 (2x to 10x)."""
|
||||
import pathlib
|
||||
import sys
|
||||
from fractions import Fraction
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
from framegen.settings import BY_KEY, Settings, valid_hz
|
||||
|
||||
pipeline = pytest.importorskip("framegen.pipeline")
|
||||
|
||||
|
||||
def test_the_old_rates_keep_their_cadence():
|
||||
assert pipeline.cadence_steps(60) == ([0.5], [])
|
||||
assert pipeline.cadence_steps(90) == ([1 / 3, 2 / 3], [])
|
||||
assert pipeline.cadence_steps(120) == ([0.25, 0.5], [0.75])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("n", range(2, 11))
|
||||
def test_every_multiplier_shows_n_evenly_spaced_frames_per_real_one(n):
|
||||
first, second = pipeline.cadence_steps(30 * n)
|
||||
shown = first + second + [1.0] # the real frame closes the pair
|
||||
assert [Fraction(t).limit_denominator(100) for t in shown] == [Fraction(j, n) for j in range(1, n + 1)]
|
||||
# the real frame's tick carries half of them (one more for an odd N): the next tick never has more to show
|
||||
assert len(first) - (len(second) + 1) in (0, 1)
|
||||
|
||||
|
||||
def test_settings_take_any_multiple_of_30_from_2x_to_10x():
|
||||
assert all(valid_hz(h) for h in (60, 90, 210, 300))
|
||||
assert not any(valid_hz(h) for h in (30, 100, 330, True, "120", 120.0))
|
||||
s = Settings()
|
||||
s.override("hz", 210) # 7x, not a menu choice
|
||||
assert s.hz == 210 and BY_KEY["hz"].name(210) == "7x (210 fps)"
|
||||
with pytest.raises(ValueError):
|
||||
s.override("hz", 100)
|
||||
assert s.step("hz", 1) == 240 and s.step("hz", -1) == 180 # from a custom value, to the menu's neighbours
|
||||
assert BY_KEY["hz"].name(120) == "4x (120 fps)"
|
||||
@@ -224,11 +224,14 @@ def test_clicks_pick_tabs_choices_and_close():
|
||||
m.show(None)
|
||||
m.render(1.0)
|
||||
hz_row = [r.key for r in m.rows()].index("hz")
|
||||
sets = {arg: b for b, what, arg in m._hit["controls"][hz_row] if what == "set"}
|
||||
assert set(sets) == {60, 90, 120}
|
||||
b = sets[120]
|
||||
m.click((b[0] + b[2]) / 2, (b[1] + b[3]) / 2)
|
||||
assert m.settings.hz == 120 and m.index == hz_row
|
||||
# Frame multiplier is a slider: a click picks the nearest step
|
||||
box, what, track = m._hit["controls"][hz_row][0]
|
||||
assert what == "slider" and m.kind_of(m.rows()[hz_row]) == "slider"
|
||||
mid = (box[1] + box[3]) / 2
|
||||
m.click(track[1], mid)
|
||||
assert m.settings.hz == 240 and m.index == hz_row
|
||||
m.click(track[0] + (track[1] - track[0]) * 2 / 5, mid) # 3rd of 6 steps: 4x
|
||||
assert m.settings.hz == 120
|
||||
row_y = m._hit["rows"][1] + m._hit["row_h"] * 0.5 # the first row, away from its switch: next, then back
|
||||
m.click(m._hit["rows"][0] + 20, row_y)
|
||||
assert m.settings.interp is False
|
||||
@@ -236,10 +239,9 @@ def test_clicks_pick_tabs_choices_and_close():
|
||||
assert m.settings.interp is True
|
||||
c = m._hit["close"]
|
||||
assert m.click(c[0] + 2, c[1] + 2) == "close"
|
||||
m.hover(box[0] + 5, box[1] + 5)
|
||||
tab_box = m._hit["tabs"][m.tabs().index("Picture")]
|
||||
m.hover(tab_box[0] + 5, tab_box[1] + 5)
|
||||
assert m._hover == ("tab", m.tabs().index("Picture"))
|
||||
m.scroll(-1)
|
||||
assert m.index == 1
|
||||
|
||||
|
||||
def test_stats_toast_and_graphs_draw():
|
||||
@@ -259,3 +261,113 @@ def test_stats_toast_and_graphs_draw():
|
||||
assert hud.graphs(MiniText.make(parts, graph={"hz": 60}), [], 1.0).shape[2] == 4 # nothing measured yet
|
||||
one, three = hud.toast("Saved"), hud.toast("Saved\nto a file\nsomewhere")
|
||||
assert three.shape[0] > one.shape[0] and one[0, 0, 3] == 0
|
||||
|
||||
|
||||
# ---- a window for the mouse ---------------------------------------------------------------------------------------
|
||||
def long_tab(m: Menu) -> str:
|
||||
"""A tab with more rows than fit, so it scrolls."""
|
||||
for tab in sorted(m.sections(), key=lambda t: -len(m.tab_rows(t))):
|
||||
if len(m.tab_rows(tab)) > VISIBLE + 2:
|
||||
return tab
|
||||
pytest.skip("no tab is long enough to scroll")
|
||||
|
||||
|
||||
def test_the_wheel_scrolls_the_page_not_the_highlight():
|
||||
m = menu()
|
||||
m.show(long_tab(m))
|
||||
m.render(1.0)
|
||||
m.index = 0
|
||||
m.scroll(-1)
|
||||
assert m._scroll == 1 and m.index == 0 # the page moved; the highlighted row is the same one
|
||||
m.scroll(-0.4)
|
||||
m.scroll(-0.4)
|
||||
assert m._scroll == 1 # a touchpad's small steps wait until they make a row...
|
||||
m.scroll(-0.4)
|
||||
assert m._scroll == 2
|
||||
m.scroll(+50)
|
||||
assert m._scroll == 0 # ...and the page stops at its ends
|
||||
m.key("down")
|
||||
assert m.index == 1
|
||||
|
||||
|
||||
def test_the_scrollbar_drags_and_the_title_bar_moves_the_window():
|
||||
m = menu()
|
||||
m.show(long_tab(m))
|
||||
m.render(1.0)
|
||||
sb, thumb = m._hit["scrollbar"], m._hit["thumb"]
|
||||
x = (sb[0] + sb[2]) / 2
|
||||
assert m.grab(x, (thumb[1] + thumb[3]) / 2) == "drag"
|
||||
m.drag(x, sb[3] + 500)
|
||||
assert m._scroll == len(m.rows()) - VISIBLE
|
||||
m.release()
|
||||
assert m._drag is None
|
||||
title = m._hit["title"]
|
||||
assert m.grab(title[0] + 200, title[1] + 10) == "move" and m.cursor(title[0] + 200, title[1] + 10) == "move"
|
||||
c = m._hit["close"]
|
||||
assert m.grab(c[0] + 2, c[1] + 2) is None and m.click(c[0] + 2, c[1] + 2) == "close"
|
||||
|
||||
|
||||
def test_sliders_drag_and_long_lists_drop_down():
|
||||
m = menu()
|
||||
m.render(1.0)
|
||||
rows = m.rows()
|
||||
hz_row = [r.key for r in rows].index("hz")
|
||||
box, _, track = m._hit["controls"][hz_row][0]
|
||||
mid = (box[1] + box[3]) / 2
|
||||
assert m.grab(track[0], mid) == "drag" and m.settings.hz == 60
|
||||
m.drag(track[1], mid)
|
||||
assert m.settings.hz == 240
|
||||
m.release()
|
||||
# a setting with a long list of choices: a drop-down
|
||||
lists = [(t, r) for t in m.tabs() for r in m.tab_rows(t) if m.kind_of(r) == "list"]
|
||||
assert lists, "some setting should have a drop-down list"
|
||||
tab, row = lists[0]
|
||||
m.show(tab)
|
||||
m.render(1.0)
|
||||
i = [r.key for r in m.rows()].index(row.key)
|
||||
m._scroll = max(0, i - VISIBLE + 1) if i >= VISIBLE else 0
|
||||
m.render(1.0)
|
||||
b = next(b for b, what, _ in m._hit["controls"][i] if what == "list")
|
||||
m.click(b[0] + 5, (b[1] + b[3]) / 2)
|
||||
assert m._drop == row.key
|
||||
m.render(1.0)
|
||||
items = m._hit["drop_items"]
|
||||
target = next((it for it in items if it[2] and it[1] != m.value(row)), None)
|
||||
assert target is not None
|
||||
m.scroll(-1) # the wheel scrolls the list while it's open, not the page
|
||||
m.render(1.0)
|
||||
items = m._hit["drop_items"]
|
||||
target = next(it for it in items if it[2] and it[1] != m.value(row))
|
||||
m.click(target[0][0] + 5, target[0][1] + 5)
|
||||
assert m.value(row) == target[1] and m._drop is None
|
||||
# keys work in an open list too, and Esc closes the list before the overlay
|
||||
m.key("enter")
|
||||
assert m._drop == row.key
|
||||
assert m.key("back") is None and m._drop is None
|
||||
assert m.key("back") == "close"
|
||||
|
||||
|
||||
def test_slider_keys_go_the_way_the_slider_does():
|
||||
m = menu()
|
||||
m.show("Display")
|
||||
rows = m.rows()
|
||||
op = next(r for r in rows if r.key == "ui_opacity") # stored 100% .. 30%, drawn 30% .. 100%
|
||||
assert m.kind_of(op) == "slider" and m.ordered(op) == sorted(m.choices(op))
|
||||
m.settings.set("ui_opacity", 0.5)
|
||||
m.step(op, 1)
|
||||
assert m.settings.ui_opacity == 0.6 # Right: more
|
||||
m.settings.set("ui_opacity", 1.0)
|
||||
m.step(op, 1)
|
||||
assert m.settings.ui_opacity == 1.0 # and it stops at the end
|
||||
|
||||
|
||||
def test_the_mouse_anywhere_on_a_tab_without_a_scrollbar_or_list():
|
||||
m = menu() # Home: short, so no scrollbar; no list open
|
||||
m.render(1.0)
|
||||
assert m._hit["scrollbar"] is None and m._hit["drop"] is None
|
||||
for x in range(0, m._hit["w"], 37):
|
||||
for y in range(0, m._hit["h"], 29):
|
||||
m.cursor(x, y)
|
||||
m.hover(x, y)
|
||||
m.grab(x, y)
|
||||
m.release()
|
||||
Reference in new issue
Block a user