diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index a440079..a70db23 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -72,17 +72,14 @@ jobs: os: macos-latest target: aarch64-apple-darwin oidn: arm64.macos - archive: tar.gz - name: macos-x64 os: macos-latest target: x86_64-apple-darwin oidn: x86_64.macos - archive: tar.gz - name: windows-x64 os: windows-latest target: x86_64-pc-windows-msvc oidn: x64.windows - archive: zip runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v7 @@ -103,23 +100,41 @@ jobs: echo "AKTIS_OIDN_RELEASE=1" >> "$GITHUB_ENV" - name: Build run: cargo build --release --locked -p aktis-app --features denoise --target ${{ matrix.target }} - - name: Package + # macOS: Aktis.app in a .dmg (ADR 0021). + - name: Package (macOS .dmg) + if: runner.os == 'macOS' + run: | + name="aktis-${{ needs.prepare.outputs.version }}-${{ matrix.name }}" + scripts/package-macos.sh "target/${{ matrix.target }}/release/aktis" \ + "$OIDN_POSIX_DIR" "${{ needs.prepare.outputs.version }}" "dist/$name.dmg" + # Windows: a portable folder, zipped, and the same folder as an installer (ADR 0021). + - name: Package (Windows folder and .zip) + if: runner.os == 'Windows' shell: bash run: | name="aktis-${{ needs.prepare.outputs.version }}-${{ matrix.name }}" - mkdir -p "dist/$name" - bin="target/${{ matrix.target }}/release/aktis" - [ "${{ runner.os }}" = "Windows" ] && bin="$bin.exe" - cp "$bin" README.md CHANGELOG.md LICENSE-MIT LICENSE-APACHE "dist/$name/" - scripts/bundle-oidn.sh "$OIDN_POSIX_DIR" "dist/$name" - cd dist - if [ "${{ matrix.archive }}" = "zip" ]; then - 7z a "$name.zip" "$name" > /dev/null - else - tar -czf "$name.tar.gz" "$name" - fi - rm -rf "$name" - ls -l + mkdir -p "stage/$name" dist + cp target/${{ matrix.target }}/release/aktis.exe README.md CHANGELOG.md \ + LICENSE-MIT LICENSE-APACHE "stage/$name/" + scripts/bundle-oidn.sh "$OIDN_POSIX_DIR" "stage/$name" + (cd stage && 7z a "../dist/$name.zip" "$name" > /dev/null) + echo "STAGE_DIR=$(cygpath -w "$PWD/stage/$name")" >> "$GITHUB_ENV" + - name: Package (Windows installer .exe) + if: runner.os == 'Windows' + shell: pwsh + run: | + # Installs Inno Setup, or upgrades a preinstalled one (the script needs 6.3+). + choco upgrade innosetup -y --no-progress + $iscc = (Get-ChildItem "${env:ProgramFiles(x86)}\Inno Setup *\ISCC.exe", ` + "$env:ProgramFiles\Inno Setup *\ISCC.exe" -ErrorAction SilentlyContinue | + Select-Object -First 1).FullName + if (-not $iscc) { throw 'ISCC.exe not found' } + & $iscc "/DAppVersion=${{ needs.prepare.outputs.version }}" "/DSourceDir=$env:STAGE_DIR" ` + "/DOutputDir=$PWD\dist" ` + "/DOutputBaseFilename=aktis-${{ needs.prepare.outputs.version }}-${{ matrix.name }}-setup" ` + scripts\aktis.iss + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + Get-ChildItem dist - uses: actions/upload-artifact@v7 with: name: build-${{ matrix.name }} @@ -137,7 +152,7 @@ jobs: - name: Collect files and checksums run: | mkdir release - find artifacts -type f \( -name '*.tar.gz' -o -name '*.zip' \) -exec cp {} release/ \; + find artifacts -type f \( -name '*.dmg' -o -name '*.exe' -o -name '*.zip' \) -exec cp {} release/ \; cd release && sha256sum * > SHA256SUMS.txt && cat SHA256SUMS.txt - uses: softprops/action-gh-release@v3 with: diff --git a/CHANGELOG.md b/CHANGELOG.md index 8cc3d3a..7542cc7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,8 +6,89 @@ uses [Semantic Versioning](https://semver.org/). ## [Unreleased] +## [0.1.1] - 2026-12-02 + +Projects and workspaces (M9): Aktis opens on a Home screen of recent projects, and each +project is an Image or a Video project with its own workspace. Tested by hand on macOS +(Apple Silicon); Windows is built and tested in CI but not yet smoke-tested by hand. +Projects from 0.1.0 still open; saving one writes a project folder beside it. + +### Added + +- Autosave: while a project has unsaved changes, it is saved every 30 s to + `.autosave.toml` in its folder. If the app quits without saving (a crash, say), opening + the project offers to recover the changes. Quitting with unsaved changes now asks Save / + Don't Save / Cancel. The last project reopens from its file at start-up. + +- Image projects have their own workspace. **Render Image** renders the canvas in the + background (Stop keeps what the path tracer has so far; Cancel discards it). Finished + renders go to a **Renders** strip at the bottom: click one to view it, right-click to + compare two with a split slider, pin, or move it to the Trash. Export… saves one + anywhere. The last 20 are kept (pinned ones too) in the project's `renders/` folder. + **Views** save camera positions to come back to. + +- Video projects have two pages in the header. **Animate** has a transport bar under the + viewport (to in/out, previous/next key, play, loop, frame) and "Camera moves" with + Orbit…. **Deliver** has output presets (Web, Small, Archive, Edit, Frames), a destination + in the project's `exports/` folder by default, and the project's render queue. + Render opens Deliver. +- An Inspector replaces the right panel: Camera, Light, Render and Post tabs. In video + projects a ◆ beside each animatable value adds or removes a key at the playhead. The + engine choice moved to the header; Exposure moved to Post. +- Each project keeps its own render queue in `queue.toml` in its folder. The single queue + from 0.1.0 goes to the project that was open. + +- Workspace header: Home, the project's name, an IMAGE/VIDEO badge and a canvas chip. + Click the chip to change the canvas: the mode's presets, a custom size with aspect lock + and swap. Each change can be undone, and the vertical field of view stays the same. +- Viewport section: Preview scale (25 / 50 / 100 % of the canvas, for a faster viewport) + and composition guides (rule of thirds, golden ratio, centre cross), plus safe areas for + videos. + +- Projects are now saved as project folders, `.aktis/`, holding + `project.aktis.toml` and a `thumbnail.png` of the view. File › Open… picks a project + folder; File › Open Project File… opens a `.toml` file. This is the first step towards a + Home screen and separate Image and Video workspaces (M9). +- Each project has a mode, Image or Video, and a canvas size (`[canvas]`) in its file + (project format 2). Projects saved so far are Video projects. +- A Home screen is now the start screen. It shows recent projects as a grid or list with + thumbnails, mode, canvas size, world and date, and has search, an Image/Video filter and + sort. Each project has Open, Reveal, Duplicate, Rename, Remove from Recents and Move to + Trash (Recycle Bin on Windows). Missing projects can be located again. Drop a project on + the window to open it. New Image and New Video open a New Project dialog: canvas presets per mode, custom + size with aspect lock and swap, frame rate and duration for videos, name and location, an + optional world, and "Start from" another project's world, packs, engine and lighting. + File › New… opens it too. The last + project waits as a Continue card. A Minecraft page lists your installs and lets you add + or remove folders and forget added packs. `--world` on the command line still opens + straight into the workspace. + +### Changed + +- The Output section's resolution became the canvas, set from the header. Render size is + replaced by Preview scale; rendering at the viewport's own pixel size is gone. Save PNG + saves the canvas at the Preview scale. The Output section (format, quality, ffmpeg) now + shows only in Video projects. + +- Saving a project from 0.1.0 (a single `name.aktis.toml` file) writes a `name.aktis/` + folder beside it; the old file is left unchanged. Old files with keys open as Video + projects. Those without keys open as Image projects, which don't save timeline edits + or Output format settings until the Image workspace arrives; a note says so when one opens. +- Saved app state: added install folders and resource and shader pack lists are kept as a + library shared by all projects. Your existing lists carry over. + +- Releases: macOS downloads are now a `.dmg` with an `Aktis.app` to drag into + Applications (Apple Silicon and Intel), instead of a `.tar.gz`. Windows gets an + installer, `aktis--windows-x64-setup.exe`, that installs per user, with no + administrator prompt, and adds a Start menu shortcut and an uninstaller. The + portable `.zip` stays. Packages are still not signed with a developer certificate. + ### Fixed +- Symbols in the resource-pack and shader-pack lists (move up/down, forget, warning) and + the render queue's reorder buttons showed as empty boxes: egui 0.37's default fonts + have no emoji fonts, so they're now enabled. + - Path Tracer: the trace shader failed to compile on Windows (DX12/FXC: "array reference cannot be used as an l-value"), so path-traced renders and jobs failed there. - Docs: `cargo doc` failed on a link to a private item in `aktis-sp`. diff --git a/CLAUDE.md b/CLAUDE.md index 66520d8..ae7308f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -118,7 +118,7 @@ crates/ aktis-sp/ shader-pack engine (OptiFine/Iris pipeline) aktis-app/ egui desktop app, binary name `aktis` docs/ documentation system (index: docs/README.md) -scripts/ build/release helpers (OIDN download and bundling, ADR 0011) +scripts/ build/release helpers (OIDN download and bundling, ADR 0011; .dmg and installer packaging, ADR 0021) .github/ CI, release workflow, templates ``` diff --git a/Cargo.lock b/Cargo.lock index f9554ce..67f8cd9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -44,7 +44,7 @@ dependencies = [ [[package]] name = "aktis-app" -version = "0.1.0" +version = "0.1.1" dependencies = [ "aktis-assets", "aktis-pt", @@ -57,6 +57,7 @@ dependencies = [ "egui", "env_logger", "glam", + "image 0.25.10", "log", "pollster", "rfd", @@ -65,11 +66,12 @@ dependencies = [ "serde_json", "sysinfo", "toml", + "trash", ] [[package]] name = "aktis-assets" -version = "0.1.0" +version = "0.1.1" dependencies = [ "directories", "glam", @@ -83,7 +85,7 @@ dependencies = [ [[package]] name = "aktis-pt" -version = "0.1.0" +version = "0.1.1" dependencies = [ "aktis-assets", "aktis-render", @@ -103,7 +105,7 @@ dependencies = [ [[package]] name = "aktis-render" -version = "0.1.0" +version = "0.1.1" dependencies = [ "aktis-assets", "aktis-scene", @@ -120,7 +122,7 @@ dependencies = [ [[package]] name = "aktis-scene" -version = "0.1.0" +version = "0.1.1" dependencies = [ "glam", "log", @@ -132,7 +134,7 @@ dependencies = [ [[package]] name = "aktis-sp" -version = "0.1.0" +version = "0.1.1" dependencies = [ "aktis-assets", "aktis-render", @@ -153,7 +155,7 @@ dependencies = [ [[package]] name = "aktis-world" -version = "0.1.0" +version = "0.1.1" dependencies = [ "aktis-assets", "fastanvil", @@ -1404,6 +1406,7 @@ dependencies = [ "portable-atomic", "portable-atomic-util", "serde_core", + "windows-link", ] [[package]] @@ -3155,6 +3158,25 @@ version = "0.1.36" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +[[package]] +name = "trash" +version = "5.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7363f9516b65bd2e855f4e6c3338b1a98efc2773c25349c958908897e1170ded" +dependencies = [ + "jiff", + "libc", + "log", + "objc2 0.6.5", + "objc2-foundation 0.3.2", + "once_cell", + "percent-encoding", + "scopeguard", + "urlencoding", + "windows", + "windows-core", +] + [[package]] name = "tree_magic_mini" version = "3.2.2" @@ -3227,6 +3249,12 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557" +[[package]] +name = "urlencoding" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da" + [[package]] name = "utf8parse" version = "0.2.2" diff --git a/Cargo.toml b/Cargo.toml index e7960d9..653ba5a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ members = ["crates/*"] default-members = ["crates/aktis-app"] [workspace.package] -version = "0.1.0" +version = "0.1.1" edition = "2024" rust-version = "1.95" license = "MIT OR Apache-2.0" @@ -25,7 +25,8 @@ aktis-sp = { path = "crates/aktis-sp" } # wgpu must stay on the same major version that eframe uses (egui-wgpu shares the device). wgpu = "30" eframe = { version = "0.37", default-features = false, features = ["wgpu", "default_fonts", "persistence"] } -egui = "0.37" +# monochrome_emoji_fonts: the symbols the UI draws (⏶ ⏷ ✕ ⚠ ▲ ▼); without it they are boxes. +egui = { version = "0.37", features = ["monochrome_emoji_fonts"] } naga = "30" bytemuck = { version = "1", features = ["derive"] } pollster = "1" @@ -53,6 +54,8 @@ env_logger = "0.11" rayon = "1" directories = "6" rfd = "0.18" +# Move project folders to the Trash / Recycle Bin from the Home screen (M9 task 4). +trash = "5" # Total system RAM for the memory budget's Auto setting (ADR 0020); only the memory part. sysinfo = { version = "0.40", default-features = false, features = ["system"] } diff --git a/README.md b/README.md index 446768d..943102c 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ two engines: Runs on **macOS (Apple Silicon)** and **Windows**. -> **Status: beta (0.1.0).** All planned milestones (M1–M8) are done and tested by hand on +> **Status: beta (0.1.1).** All planned milestones (M1–M9) are done and tested by hand on > macOS. Windows is built and tested in CI but not yet smoke-tested by hand. Expect rough > edges; see the [changelog](CHANGELOG.md) for known limitations and the > [roadmap](docs/roadmap.md) for what's next. @@ -31,7 +31,10 @@ Runs on **macOS (Apple Silicon)** and **Windows**. queue, PNG sequences and MP4/MOV video through your own ffmpeg - Big worlds: a memory budget, and far terrain out to 512 chunks in every engine around a detail area that follows the camera -- Project files (`*.aktis.toml`) and a simple UI with sensible defaults +- A Home screen of recent projects; Image projects (views, background renders, a render + history with A/B compare) and Video projects (Animate and Deliver pages, output presets, + a render queue per project); canvas presets; project folders with autosave and recovery +- A simple UI with sensible defaults - Not yet: shader-pack options, biome tints, mobs and block entities, headless rendering ## Requirements @@ -43,9 +46,21 @@ Runs on **macOS (Apple Silicon)** and **Windows**. ## Download -Prebuilt archives for macOS (Apple Silicon and Intel) and Windows x64 are attached to each -[GitHub release](https://github.com/TriBinary/aktis/releases). They aren't signed yet: on -macOS, right-click → Open the first time. +Each [GitHub release](https://github.com/TriBinary/aktis/releases) has: + +| Platform | File | How to install | +|---|---|---| +| macOS Apple Silicon | `aktis--macos-arm64.dmg` | Open it, drag **Aktis** to **Applications** | +| macOS Intel | `aktis--macos-x64.dmg` | Same | +| Windows x64 | `aktis--windows-x64-setup.exe` | Run the installer (no administrator rights needed) | +| Windows x64, portable | `aktis--windows-x64.zip` | Unzip anywhere, run `aktis.exe` | + +They aren't signed with a developer certificate yet, so the first launch shows a warning: + +- **macOS:** "Apple could not verify…". Click **Done**, then open System Settings → + Privacy & Security and click **Open Anyway** next to Aktis. +- **Windows:** SmartScreen's "Windows protected your PC". Click **More info** → + **Run anyway**. ## Building from source diff --git a/crates/aktis-app/Cargo.toml b/crates/aktis-app/Cargo.toml index 453245b..88a6ff7 100644 --- a/crates/aktis-app/Cargo.toml +++ b/crates/aktis-app/Cargo.toml @@ -25,6 +25,8 @@ glam.workspace = true serde.workspace = true rfd.workspace = true sysinfo.workspace = true +trash.workspace = true +image.workspace = true anyhow.workspace = true toml.workspace = true log.workspace = true diff --git a/crates/aktis-app/src/animate.rs b/crates/aktis-app/src/animate.rs index d7effe6..4418ec1 100644 --- a/crates/aktis-app/src/animate.rs +++ b/crates/aktis-app/src/animate.rs @@ -119,6 +119,22 @@ pub fn next_key(timeline: &Timeline, property: Property, t: f64) -> Option .find(|&time| time > t + half) } +/// Time of the last key of any property more than half a frame before `t`. +pub fn previous_any_key(timeline: &Timeline, t: f64) -> Option { + Property::ALL + .iter() + .filter_map(|&p| previous_key(timeline, p, t)) + .max_by(f64::total_cmp) +} + +/// Time of the first key of any property more than half a frame after `t`. +pub fn next_any_key(timeline: &Timeline, t: f64) -> Option { + Property::ALL + .iter() + .filter_map(|&p| next_key(timeline, p, t)) + .min_by(f64::total_cmp) +} + /// Sets the key of `property` at `t` (snapped to a frame) to `value`, keeping the mode of a /// key already there (new keys are `smooth`). Turns the stopwatch on. pub fn set_key(timeline: &mut Timeline, property: Property, t: f64, value: Value) { diff --git a/crates/aktis-app/src/animate/tests.rs b/crates/aktis-app/src/animate/tests.rs index 4b307cf..0459d6e 100644 --- a/crates/aktis-app/src/animate/tests.rs +++ b/crates/aktis-app/src/animate/tests.rs @@ -361,3 +361,24 @@ fn paste_puts_the_earliest_key_at_the_playhead() { assert!(CopiedKeys::from_text("# aktis keys 1\nkeys = []\n").is_none()); assert!(CopiedKeys::copy(&tl, &[(Property::FogDensity, 1.0)]).is_none()); } + +#[test] +fn key_navigation_across_every_property() { + let mut tl = Timeline::default(); + for (p, t) in [ + (Property::SunAltitude, 2.0), + (Property::FogDensity, 5.0), + (Property::CameraRoll, 3.5), + ] { + set_key(&mut tl, p, t, shown_value(p, &Scene::default())); + } + assert_eq!(previous_any_key(&tl, 4.0), Some(3.5)); + assert_eq!( + next_any_key(&tl, 2.0), + Some(3.5), + "not the key at the playhead" + ); + assert_eq!(previous_any_key(&tl, 2.0), None); + assert_eq!(next_any_key(&tl, 5.0), None); + assert_eq!(next_any_key(&tl, 0.0), Some(2.0)); +} diff --git a/crates/aktis-app/src/app.rs b/crates/aktis-app/src/app.rs deleted file mode 100644 index 5954908..0000000 --- a/crates/aktis-app/src/app.rs +++ /dev/null @@ -1,3641 +0,0 @@ -//! Top-level application state and layout: project panel on the left, render and scene -//! settings on the right, viewport in the centre. - -use std::path::{Path, PathBuf}; -use std::sync::Arc; - -use aktis_pt::{PathTracer, PtView}; -use aktis_render::preview::PreviewRenderer; -use aktis_render::{GpuContext, RenderEngine}; -use aktis_scene::timeline::Timeline; -use aktis_scene::{Camera, Scene}; -use anyhow::Context; -use eframe::egui_wgpu; -use glam::Vec3; -use serde::{Deserialize, Serialize}; - -use crate::animate::{self, CameraOverride}; -use crate::budget::{Budget, Fitted}; -use crate::cli::Args; -use crate::denoising::{self, DenoiseSettings, Denoising}; -use crate::ffmpeg::{self, Encoder, Ffmpeg}; -use crate::fly::{FlyCamera, MoveKeys}; -use crate::history::History; -use crate::job::{JobKind, JobStatus, JobTarget}; -use crate::job_runner::{JobEngines, JobRunner}; -use crate::loader::{ - LoadPoll, LoadRequest, LoadStage, LoadTask, LoadedWorld, MeshTask, Residency, Reuse, - residency_plan, -}; -use crate::orbit::Orbit; -use crate::output::{self, OutputFormat, OutputSettings, RenderSize}; -use crate::playback::{self, Playback}; -use crate::project::{PanelAction, ProjectPanel, ProjectSettings, SelectionSettings, Shown}; -use crate::project_file::{ - self, EngineChoice, EngineSection, PacksSection, ProjectFile, WorldSection, -}; -use crate::pt_panel::{self, ProgressClock, SavedPtSettings}; -use crate::queue::{self, NewJob, QueueStatus, RenderQueue}; -use crate::shader_pack::{self, PackWorld, SavedShaderPacks, ShaderPackChoice, ShaderPacks}; -use crate::timeline_panel::{self, PanelState}; -use crate::viewport::{Engines, FrameKey, Source, Viewport, frame_guide, pixel_size}; -use aktis_render::catch_out_of_memory; - -/// eframe storage key for [`Saved`]. -const STORAGE_KEY: &str = "aktis"; - -/// File menu shortcuts. -const SHORTCUT_NEW: egui::KeyboardShortcut = - egui::KeyboardShortcut::new(egui::Modifiers::COMMAND, egui::Key::N); -const SHORTCUT_OPEN: egui::KeyboardShortcut = - egui::KeyboardShortcut::new(egui::Modifiers::COMMAND, egui::Key::O); -const SHORTCUT_SAVE: egui::KeyboardShortcut = - egui::KeyboardShortcut::new(egui::Modifiers::COMMAND, egui::Key::S); -const SHORTCUT_SAVE_AS: egui::KeyboardShortcut = egui::KeyboardShortcut::new( - egui::Modifiers::COMMAND.plus(egui::Modifiers::SHIFT), - egui::Key::S, -); - -/// Edit menu shortcuts. -const SHORTCUT_UNDO: egui::KeyboardShortcut = - egui::KeyboardShortcut::new(egui::Modifiers::COMMAND, egui::Key::Z); -const SHORTCUT_REDO: egui::KeyboardShortcut = egui::KeyboardShortcut::new( - egui::Modifiers::COMMAND.plus(egui::Modifiers::SHIFT), - egui::Key::Z, -); - -/// A File menu action that replaces the project, so it asks about unsaved changes first. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum ReplaceProject { - New, - Open, - /// Open a queued job's snapshot as an untitled project. - Job(u64), -} - -/// An animation job waiting for "frames already there: Replace / Keep / Cancel". -struct PendingAdd { - project: ProjectFile, - name: String, - kind: JobKind, - frame: u32, - target: JobTarget, - video: Option, - existing: usize, -} - -/// State kept between runs (eframe storage). -#[derive(Debug, Default, Serialize, Deserialize)] -#[serde(default)] -struct Saved { - project: ProjectSettings, - scene: Scene, - speed: Option, - engine: EngineChoice, - path_tracer: SavedPtSettings, - denoise: DenoiseSettings, - shader_packs: SavedShaderPacks, - /// The timeline being edited (also in the project file). - timeline: Timeline, - /// Output settings (also in the project file). - output: OutputSettings, - /// The open project file; `None` = untitled. - project_path: Option, - /// The open project's world when it couldn't be loaded (see `AktisApp::world_override`). - world_override: Option<(WorldSection, PacksSection)>, - /// Playhead time in seconds. - playhead: f64, - /// Bottom panel: open, tab, collapsed groups, zoom. - timeline_panel: PanelState, - /// What size the viewport renders at. - render_size: RenderSize, - /// The render queue. - queue: RenderQueue, - /// The ffmpeg chosen with "Choose…"; `None` = search automatically. - ffmpeg_path: Option, -} - -/// Summary of the uploaded world, for the project panel. -struct WorldInfo { - name: String, - /// Radius loaded (lower than the request's when the memory budget lowered it). - radius: i32, - /// What the memory budget did on this load. - fitted: Option, - /// The centre came from re-centring (M8 task 9), so it may move again. - auto_centre: bool, - /// Far-terrain quads in the preview, while they're on the GPU. - far_quads: Option, - /// Quads of the meshed world (`None` until a mesh was built for an engine). - quads: Option, - /// Preview draws per frame and GPU memory, while its geometry is on the GPU. - preview: Option<(u64, f64)>, - /// Path-tracer GPU memory, while its data is on the GPU. - pt_mib: Option, - /// The path tracer couldn't hold this world (not retried until the next load). - pt_failed: bool, - /// Which engines' geometry is on the GPU. - resident: Residency, - /// Resource packs on top of the jar. - packs: usize, - /// Problems with resource packs, shown under the stats. - pack_warnings: Vec, - load_seconds: f32, - /// Loaded from the project panel (not the command line), so it is reopened next run. - from_panel: bool, - /// What was loaded (the packs panel compares and reuses it for Apply). - request: LoadRequest, - /// The world's blocks, kept so Apply skips reading chunks. - blocks: Reuse, - /// This load reused the previous load's blocks. - reused: bool, - /// Texture array: layers, layer size, size without the cap, layers scaled down, bytes. - textures: TextureInfo, - /// What the shader-pack engine builds its geometry from. - pack_world: Arc, -} - -/// Summary of a world's texture array. -#[derive(Debug, Clone, Copy)] -struct TextureInfo { - layers: u32, - size: u32, - natural_size: u32, - downscaled: u32, - bytes: u64, - /// Layers with a LabPBR normal / specular map. - pbr: (u32, u32), -} - -impl TextureInfo { - fn of(t: &aktis_assets::TextureArray) -> Self { - Self { - layers: t.layer_count(), - size: t.size(), - natural_size: t.natural_size(), - downscaled: t.downscaled(), - bytes: t.bytes(), - pbr: t.pbr_layer_counts(), - } - } - - /// "1250 × 128 px · 104 MiB", plus LabPBR map counts and "(37 scaled down from up to - /// 512 px)" when they apply. Memory includes the PBR maps. - fn label(&self) -> String { - let mut s = format!( - "{} × {} px · {:.0} MiB", - self.layers, - self.size, - self.bytes as f64 / 1048576.0 - ); - if self.pbr != (0, 0) { - s.push_str(&format!( - ", LabPBR: {} normal, {} specular maps", - self.pbr.0, self.pbr.1 - )); - } - if self.downscaled > 0 { - s.push_str(&format!( - " ({} scaled down from up to {} px)", - self.downscaled, self.natural_size - )); - } - s - } -} - -/// A load in progress and what to do when it finishes. -struct PendingLoad { - task: LoadTask, - request: LoadRequest, - from_panel: bool, - /// Started by re-centring (M8 task 9): the centre follows the camera, not the user. - recentre: bool, - /// Camera to restore instead of the default placement (reopening the last session). - camera: Option, -} - -/// Smoothed frame rate, measured only while the viewport redraws continuously. -#[derive(Default)] -struct FrameRate { - /// Exponential moving average of the frame time in seconds; `None` when idle. - avg_dt: Option, -} - -impl FrameRate { - fn update(&mut self, active: bool, dt: f32) { - self.avg_dt = match (active, self.avg_dt) { - (false, _) => None, - (true, None) => Some(dt), - (true, Some(avg)) => Some(avg + (dt - avg) * 0.1), - }; - } - - fn label(&self) -> String { - match self.avg_dt { - Some(dt) if dt > 0.0 => format!("{:.0} FPS ({:.1} ms)", 1.0 / dt, dt * 1000.0), - _ => "idle".to_owned(), - } - } -} - -/// Top-level application state. -pub struct AktisApp { - scene: Scene, - fly: FlyCamera, - project: ProjectPanel, - egui_ctx: egui::Context, - render_state: egui_wgpu::RenderState, - gpu: GpuContext, - preview: PreviewRenderer, - path_tracer: PathTracer, - engine: EngineChoice, - /// The shader-pack engine and its background build. - shader_packs: ShaderPacks, - /// Shader-pack choices per instance (saved). - shader_pack_choices: SavedShaderPacks, - /// The chosen instance's `shaderpacks/` contents and the game folder they belong to - /// (`None` = list it again). - shader_packs_found: Option<(PathBuf, Option>)>, - /// `--shaderpack`: the pack for this run (not saved), and the engine to save instead. - shader_pack_override: Option<(PathBuf, EngineChoice)>, - viewport: Viewport, - /// Bumped whenever the preview's world changes. - world_version: u64, - world: Option, - load: Option, - /// Geometry being built for an engine chosen after the load (ADR 0020). - mesh_task: Option, - /// Last load or render error, shown in the viewport. - error: Option, - frame_rate: FrameRate, - /// Where a right-drag look started (points); the cursor is held there while it lasts. - look_anchor: Option, - /// Result of the last "Save PNG…": the file written, or an error message. - export_status: Option>, - /// The path tracer is paused (keeps its image, adds no samples). - pt_paused: bool, - /// Render time of the path tracer's current image. - pt_clock: ProgressClock, - /// Denoise settings (shown only in builds with OIDN). - denoise_settings: DenoiseSettings, - /// The denoiser worker and its latest result. - denoising: Denoising, - /// The keyframe timeline (M7; edited from task 5 on). - timeline: Timeline, - /// Output resolution, format and destination (M7; used from task 8 on). - output: OutputSettings, - /// The open project file; `None` = untitled. - project_path: Option, - /// What the open project file holds (as last opened or saved), to tell whether there - /// are unsaved changes; `None` for an untitled project. - project_baseline: Option, - /// The project's world and packs when they couldn't be loaded: Save writes these - /// instead of the world on screen until the user loads a world. - world_override: Option<(WorldSection, PacksSection)>, - /// Messages about the open project (missing world, read or write errors); `true` = - /// error. Shown under the menu bar until dismissed. - project_notes: Vec<(bool, String)>, - /// New/Open waiting for the "Save changes?" answer. - confirm: Option, - /// The window title last sent. - title: String, - /// Playhead time in seconds (on a frame); the scene shown is the timeline here. - playhead: f64, - /// The fly camera's moves of animated camera values ("Camera not keyed"). - camera_override: CameraOverride, - /// Bottom panel state. - timeline_panel: PanelState, - /// What size the viewport renders at (saved with the app). - render_size: RenderSize, - /// Undo/redo of the base scene and the timeline (not saved). - history: History, - /// Timeline playback. - playback: Playback, - /// When playback last advanced (`None` while paused). - last_tick: Option, - /// The Orbit dialog's values while it is open. - orbit_dialog: Option, - /// The render queue (saved with the app). - queue: RenderQueue, - /// Start was pressed and the queue hasn't stopped. - queue_running: bool, - /// The chunk a re-centring load failed at (not retried until the camera moves on). - recentre_failed: Option<(i32, i32)>, - /// The queue's current job (preparing or rendering). - queue_job: Option, - /// The runner of the current job once it renders. - job: Option, - /// The world load the queue started for its job. - queue_loading: Option, - /// The current job's shader pack (built instead of the editor's while the queue runs). - queue_pack: Option, - /// The current job's engine: its geometry is kept on the GPU while the queue prepares - /// or renders it, whichever engine the viewport shows (ADR 0020). - queue_engine: Option, - /// The editor's world when Start was pressed (loaded back when the queue stops). - editor_world: Option, - /// An animation job waiting for Replace / Keep / Cancel. - queue_add: Option, - /// "Stop rendering and quit?" is open. - quit_confirm: bool, - /// Quit was confirmed: let the window close. - allow_close: bool, - /// The ffmpeg chosen with "Choose…" (saved); `None` = search. - ffmpeg_choice: Option, - /// The ffmpeg in use, or why there is none. - ffmpeg: Result, - /// The running encode and its job. - encoder: Option<(u64, Encoder)>, -} - -/// Cursor grab while looking around. winit can lock the cursor in place on macOS; Windows -/// (and X11) only support confining it to the window, so there the cursor is put back where -/// the drag started when it ends. -const LOOK_GRAB: egui::CursorGrab = if cfg!(target_os = "macos") { - egui::CursorGrab::Locked -} else { - egui::CursorGrab::Confined -}; - -impl AktisApp { - /// Creates the app on eframe's wgpu device, restores saved choices and starts loading: - /// the world from `args` if given, else the last session's world. - pub fn new(cc: &eframe::CreationContext<'_>, args: Args) -> anyhow::Result { - let render_state = cc - .wgpu_render_state - .clone() - .context("Aktis needs eframe's wgpu renderer")?; - let gpu = GpuContext { - device: render_state.device.clone(), - queue: render_state.queue.clone(), - }; - let saved: Saved = cc - .storage - .and_then(|s| eframe::get_value(s, STORAGE_KEY)) - .unwrap_or_default(); - let preview = PreviewRenderer::new(&gpu); - let history = History::new(&saved.scene, &saved.timeline); - let mut path_tracer = PathTracer::new(&gpu); - path_tracer.settings = saved.path_tracer.to_settings(); - let mut app = Self { - scene: saved.scene, - fly: FlyCamera { - speed: saved.speed.unwrap_or(FlyCamera::default().speed), - }, - project: ProjectPanel::new(saved.project), - egui_ctx: cc.egui_ctx.clone(), - render_state, - gpu, - preview, - path_tracer, - engine: saved.engine, - shader_packs: ShaderPacks::default(), - shader_pack_choices: saved.shader_packs, - shader_packs_found: None, - shader_pack_override: None, - viewport: Viewport::default(), - world_version: 0, - world: None, - load: None, - mesh_task: None, - error: None, - frame_rate: FrameRate::default(), - look_anchor: None, - export_status: None, - pt_paused: false, - pt_clock: ProgressClock::default(), - denoise_settings: saved.denoise, - denoising: Denoising::default(), - timeline: saved.timeline, - output: saved.output, - project_baseline: None, - project_path: saved.project_path, - world_override: saved.world_override, - project_notes: Vec::new(), - confirm: None, - title: String::new(), - playhead: saved.playhead, - camera_override: CameraOverride::default(), - timeline_panel: saved.timeline_panel, - render_size: saved.render_size, - history, - playback: Playback::default(), - last_tick: None, - orbit_dialog: None, - queue: saved.queue.restored(), - queue_running: false, - recentre_failed: None, - queue_job: None, - job: None, - queue_loading: None, - queue_pack: None, - queue_engine: None, - editor_world: None, - queue_add: None, - quit_confirm: false, - allow_close: false, - ffmpeg: ffmpeg::find(saved.ffmpeg_path.as_deref()), - ffmpeg_choice: saved.ffmpeg_path, - encoder: None, - }; - match &app.ffmpeg { - Ok(f) => log::info!("ffmpeg {} at {}", f.version, f.path.display()), - Err(e) => log::info!("video encoding unavailable: {e}"), - } - app.playhead = animate::snap( - &app.timeline, - app.playhead.clamp(0.0, app.timeline.duration), - ); - // Compare the restored session with the file on disk (the session may hold unsaved - // changes from the last run). - if let Some(path) = &app.project_path { - match ProjectFile::read(path) { - Ok(file) => app.project_baseline = Some(file), - Err(e) => { - log::warn!("last project: {e:#}"); - app.project_notes.push(( - false, - format!( - "The project file can't be read any more ({e:#}); Save writes it again." - ), - )); - } - } - } - if let Some(pack) = args.shaderpack { - app.shader_pack_override = Some((pack, app.engine)); - app.engine = EngineChoice::ShaderPack; - } - let sel = app.project.settings.selection.normalized(); - if let (Some(jar), Some(world)) = (args.jar, args.world) { - let request = LoadRequest { - jar, - packs: args.packs, - max_texture_size: aktis_assets::clamp_texture_size_cap( - app.project.settings.max_texture_size, - ), - world, - radius: args.radius, - far_radius: args.far_radius.unwrap_or(sel.far_radius), - center: args.center, - min_y: sel.min_y, - max_y: sel.max_y, - memory_budget_gb: args.memory_budget_gb.unwrap_or(sel.memory_budget_gb), - }; - app.start_load(request, false, None, None); - } else if app.project.settings.reopen { - match app.project.settings.request(app.project.instances()) { - Some(request) => { - let camera = Some(app.scene.camera.clone()); - app.start_load(request, true, camera, None); - } - None => log::info!("last world is no longer available; not reopening it"), - } - } - Ok(app) - } - - /// Starts a background load. `camera` is kept instead of the default placement; `reuse` - /// skips reading chunks (only for a request with the same blocks). - fn start_load( - &mut self, - request: LoadRequest, - from_panel: bool, - camera: Option, - reuse: Option, - ) { - log::info!( - "loading {} (radius {}, y {}..{}, {} packs{})", - request.world.display(), - request.radius, - request.min_y, - request.max_y, - request.packs.len(), - if reuse.is_some() { - ", reusing blocks" - } else { - "" - } - ); - let ctx = self.egui_ctx.clone(); - self.error = None; - // Replacing a running load drops (cancels) it. - self.load = Some(PendingLoad { - task: LoadTask::spawn( - request.clone(), - reuse, - self.wanted_residency(), - Some(Budget::new(request.memory_budget_gb, self.engines_in_use())), - move || ctx.request_repaint(), - ), - request, - from_panel, - recentre: false, - camera, - }); - } - - /// Re-centring (M8 task 9, far-terrain.md → "Re-centring"): when the camera is more than - /// half the detail radius (at least 2 chunks) from the detail area's centre, loads a new - /// detail area (and far terrain) around it in the background, keeping the camera; the - /// old world stays on screen until the new one is in. Not while loading, playing back - /// or rendering jobs, and not when the user chose the centre. - fn maybe_recentre(&mut self) { - let Some(w) = &self.world else { return }; - let auto_centre = w.request.center.is_none() || w.auto_centre; - if !auto_centre - || self.load.is_some() - || self.queue_running - || self.job_active() - || self.playback.is_playing() - { - return; - } - let camera = self.shown_scene().camera; - let Some(target) = - crate::loader::recentre_target(camera.position, w.blocks.center, w.radius) - else { - return; - }; - let chunk = (target.0.div_euclid(16), target.1.div_euclid(16)); - if self.recentre_failed == Some(chunk) { - return; - } - let request = LoadRequest { - center: Some(target), - ..w.request.clone() - }; - log::info!( - "re-centring the detail area on {}, {} (camera left it)", - target.0, - target.1 - ); - let from_panel = w.from_panel; - let error = self.error.take(); - self.start_load(request, from_panel, Some(camera), None); - self.error = error; - if let Some(l) = &mut self.load { - l.recentre = true; - } - } - - fn poll_load(&mut self) { - let Some(pending) = &mut self.load else { - return; - }; - if let LoadPoll::Finished(result) = pending.task.poll() { - let pending = self.load.take().expect("load is running"); - match result { - Ok(w) => { - self.recentre_failed = None; - self.install_world(*w, &pending); - } - Err(e) => { - if pending.recentre - && let Some((x, z)) = pending.request.center - { - // Don't retry the same place every frame. - self.recentre_failed = Some((x.div_euclid(16), z.div_euclid(16))); - } - self.error = Some(format!("{e:#}")); - } - } - } - } - - fn install_world(&mut self, w: LoadedWorld, pending: &PendingLoad) { - // The previous world's geometry goes first, so both are never on the GPU together. - self.mesh_task = None; - self.preview.clear_world(); - self.path_tracer.clear_world(); - self.shader_packs.release_world(); - let pack_world = Arc::new(PackWorld { - grid: Arc::clone(&w.grid), - entities: Arc::clone(&w.entities), - assets: w.assets, - celestial: w.celestial, - render_distance: (w.radius as f32 + 0.5) * 16.0, - far: w.far.clone(), - }); - if let Some(camera) = &pending.camera { - self.scene.camera = camera.clone(); - } else { - self.scene.camera = overview_camera(w.center.as_vec3(), &self.scene.camera); - } - log::info!("world '{}' loaded in {:.1} s", w.name, w.seconds); - self.world = Some(WorldInfo { - blocks: Reuse { - name: w.name.clone(), - center: w.center, - grid: w.grid, - entities: w.entities, - radius: w.radius, - fitted: w.fitted.clone(), - far: w.far.clone(), - }, - reused: w.reused, - fitted: w.fitted, - textures: TextureInfo::of(pack_world.assets.textures()), - pack_world, - name: w.name, - radius: w.radius, - auto_centre: pending.recentre, - far_quads: None, - quads: None, - preview: None, - pt_mib: None, - pt_failed: false, - resident: Residency::default(), - packs: w.packs_used, - pack_warnings: w.pack_warnings, - load_seconds: w.seconds, - from_panel: pending.from_panel, - request: pending.request.clone(), - }); - self.world_version += 1; - self.error = None; - if let Some(mesh) = w.mesh { - let wanted = Residency { - preview: true, - path_tracer: w.quad_grid.is_some(), - }; - self.upload_geometry( - wanted, - &mesh, - w.quad_grid.as_ref(), - (w.far_mesh.as_ref(), w.far_field.as_ref()), - ); - } - } - - /// The geometry the viewport's engine and the queue's current job need (ADR 0020). - fn wanted_residency(&self) -> Residency { - self.engines_in_use() - .into_iter() - .map(Residency::for_engine) - .fold(Residency::default(), Residency::union) - } - - /// The engines in use: the viewport's and the queue's current job's (the memory budget - /// sizes a load for the costliest). - fn engines_in_use(&self) -> Vec { - let job = self - .job - .as_ref() - .map(|j| j.spec().engine) - .or(self.queue_engine); - std::iter::once(self.engine).chain(job).collect() - } - - /// Whether `engine`'s geometry for the world on screen is on the GPU (shader packs are - /// checked by the queue with `ShaderPacks::ready_for`). - fn engine_resident(&self, engine: EngineChoice) -> bool { - let need = Residency::for_engine(engine); - self.world.as_ref().is_some_and(|w| { - // Asking only for `need` frees nothing that matters here; only the build counts. - residency_plan(need, w.resident, w.pt_failed).1.is_empty() - }) - } - - /// Uploads freshly built geometry for `wanted` and records what is on the GPU. - fn upload_geometry( - &mut self, - wanted: Residency, - mesh: &aktis_render::mesh::WorldMesh, - quad_grid: Option<&aktis_pt::accel::QuadGrid>, - (far_mesh, far_field): ( - Option<&aktis_render::lod::FarMesh>, - Option<&aktis_pt::far::FarField>, - ), - ) { - let Some(w) = &mut self.world else { - return; - }; - w.quads = Some(mesh.stats.quads as u64); - let textures = w.pack_world.assets.textures(); - // Uploads run in an out-of-memory error scope: a GPU that can't hold the world - // disables that engine with a message instead of ending the app (ADR 0020). - let device = &self.gpu.device; - if wanted.preview { - match catch_out_of_memory(device, || { - self.preview.upload_world(&self.gpu, mesh, textures) - }) - .and_then(|r| r) - { - Ok(()) => { - // Far terrain is drawn by the preview (M8 task 6); without GPU memory - // for it the detail area still shows. - if let Some(far) = far_mesh - && let Err(e) = catch_out_of_memory(device, || { - self.preview.upload_far(&self.gpu, far, mesh.origin) - }) - { - log::error!("far terrain upload failed: {e}"); - self.preview.clear_far(); - self.error = Some(format!("Can't show the far terrain: {e}")); - } - let stats = self.preview.stats(); - w.preview = Some((stats.draws, stats.gpu_bytes as f64 / 1048576.0)); - w.far_quads = (stats.far_quads > 0).then_some(stats.far_quads); - w.resident.preview = true; - } - Err(e) => { - log::error!("upload failed: {e}"); - self.preview.clear_world(); - self.error = Some(format!("Can't show this world: {e}")); - } - } - } - if let (true, Some(grid)) = (wanted.path_tracer, quad_grid) { - // The preview works without the path tracer, so a failure only disables it. - match catch_out_of_memory(device, || { - self.path_tracer - .upload_world(&self.gpu, grid, mesh.origin, textures) - }) - .and_then(|r| r) - { - Ok(()) => { - // Far terrain (M8 task 7); without memory for it the near world still - // renders. - if let Some(field) = far_field - && let Err(e) = catch_out_of_memory(device, || { - self.path_tracer.upload_far(&self.gpu, field) - }) - .and_then(|r| r) - { - log::error!("path tracer far terrain upload failed: {e}"); - self.path_tracer.clear_far(); - self.error = - Some(format!("The path tracer can't show the far terrain: {e}")); - } - w.pt_mib = Some(self.path_tracer.stats().gpu_bytes as f64 / 1048576.0); - w.resident.path_tracer = true; - } - Err(e) => { - log::error!("path tracer upload failed: {e}"); - self.path_tracer.clear_world(); - w.pt_failed = true; - self.error = Some( - "The path tracer can't hold this world (see the log); the preview \ - still works." - .to_owned(), - ); - } - } - } - log::info!( - "world '{}' on the GPU: preview {:?}, path tracer {:?} MiB", - w.name, - w.preview.map(|p| p.1.round()), - w.pt_mib.map(f64::round) - ); - self.viewport.invalidate(); - } - - /// Keeps on the GPU exactly the geometry the engines in use need (ADR 0020): frees the - /// rest and builds what is missing on a worker thread from the kept blocks. - fn sync_residency(&mut self) { - // A finished build for the world on screen. - if let Some(task) = &mut self.mesh_task - && let Some(geometry) = task.poll() - { - let version = task.world_version; - self.mesh_task = None; - if version == self.world_version { - let wanted = geometry - .wanted - .missing_from(self.world.as_ref().map(|w| w.resident).unwrap_or_default()); - self.upload_geometry( - wanted, - &geometry.mesh, - geometry.quad_grid.as_ref(), - (geometry.far_mesh.as_ref(), geometry.far_field.as_ref()), - ); - } - } - let job_engine = self - .job - .as_ref() - .map(|j| j.spec().engine) - .or(self.queue_engine); - let pack_wanted = self.engine == EngineChoice::ShaderPack - || job_engine == Some(EngineChoice::ShaderPack) - || self.queue_pack.is_some(); - if !pack_wanted { - self.shader_packs.release_world(); - } - // A running load brings its own geometry. - if self.load.is_some() { - return; - } - let wanted = self.wanted_residency(); - let Some(w) = &mut self.world else { - self.mesh_task = None; - return; - }; - let (free, missing) = residency_plan(wanted, w.resident, w.pt_failed); - let mut freed = false; - if free.preview { - self.preview.clear_world(); - w.resident.preview = false; - w.preview = None; - w.far_quads = None; - freed = true; - } - if free.path_tracer { - self.path_tracer.clear_world(); - w.resident.path_tracer = false; - w.pt_mib = None; - freed = true; - } - if freed { - log::info!( - "freed engine geometry no longer in use: now {:?}", - w.resident - ); - self.viewport.invalidate(); - } - if missing.is_empty() { - self.mesh_task = None; - } else if self - .mesh_task - .as_ref() - .is_none_or(|t| t.world_version != self.world_version || t.wanted != missing) - { - let ctx = self.egui_ctx.clone(); - self.mesh_task = Some(MeshTask::spawn( - Arc::clone(&w.pack_world), - self.world_version, - missing, - move || ctx.request_repaint(), - )); - } - } - - /// Right-drag look: hides and grabs the cursor for the drag and turns the camera by raw - /// mouse motion (which keeps coming while the cursor is held still), then shows the cursor - /// again where the drag started. Returns whether the camera is being turned. - fn mouse_look(&mut self, ctx: &egui::Context, response: &egui::Response) -> bool { - if self.look_anchor.is_none() && response.drag_started_by(egui::PointerButton::Secondary) { - let anchor = ctx - .input(|i| i.pointer.press_origin()) - .or_else(|| response.interact_pointer_pos()); - if let Some(anchor) = anchor { - self.look_anchor = Some(anchor); - ctx.send_viewport_cmd(egui::ViewportCommand::CursorGrab(LOOK_GRAB)); - ctx.send_viewport_cmd(egui::ViewportCommand::CursorVisible(false)); - } - } - let Some(anchor) = self.look_anchor else { - return false; - }; - let (motion, still_down) = ctx.input(|i| { - let motion: egui::Vec2 = i - .events - .iter() - .filter_map(|e| match e { - egui::Event::MouseMoved(d) => Some(*d), - _ => None, - }) - .fold(egui::Vec2::ZERO, |a, d| a + d); - (motion, i.pointer.secondary_down()) - }); - if motion != egui::Vec2::ZERO { - self.fly_camera(|fly, camera| fly.look(camera, motion)); - } - if !still_down { - self.look_anchor = None; - ctx.send_viewport_cmd(egui::ViewportCommand::CursorGrab(egui::CursorGrab::None)); - ctx.send_viewport_cmd(egui::ViewportCommand::CursorPosition(anchor)); - ctx.send_viewport_cmd(egui::ViewportCommand::CursorVisible(true)); - } - true - } - - /// Game folder of the chosen instance (the key for shader-pack choices; empty without - /// one). - fn instance_key(&self) -> PathBuf { - self.project.settings.instance.clone().unwrap_or_default() - } - - /// The shader pack to render with: `--shaderpack`, else the instance's choice. - fn chosen_shader_pack(&self) -> Option { - if let Some(pack) = &self.queue_pack { - return Some(pack.clone()); - } - match &self.shader_pack_override { - Some((p, _)) => Some(p.clone()), - None => self - .shader_pack_choices - .get(&self.instance_key()) - .and_then(|c| c.selected.clone()), - } - } - - /// Picks up a finished shader-pack build and, with the Shader Pack engine selected, - /// starts one when the pack or the world changed. - fn sync_shader_pack(&mut self) { - let world = self - .world - .as_ref() - .map(|w| (self.world_version, &w.pack_world)); - if self.shader_packs.poll(world) { - self.viewport.invalidate(); - } - // Wait for a running load: its world would make the build start over. - let wanted = self.engine == EngineChoice::ShaderPack || self.queue_pack.is_some(); - if wanted && self.load.is_none() { - let pack = self.chosen_shader_pack(); - let ctx = self.egui_ctx.clone(); - let world = self - .world - .as_ref() - .map(|w| (self.world_version, &w.pack_world)); - self.shader_packs - .sync(&self.gpu, pack.as_deref(), world, move || { - ctx.request_repaint() - }); - } - } - - /// The Render panel's shader-pack section. - fn shader_pack_ui(&mut self, ui: &mut egui::Ui) { - let key = self.instance_key(); - // List the instance's shaderpacks/ when the instance changed or after Rescan. - if self - .shader_packs_found - .as_ref() - .is_none_or(|(k, found)| k != &key || found.is_none() && !k.as_os_str().is_empty()) - { - let found = (!key.as_os_str().is_empty()) - .then(|| aktis_sp::find_packs(&key.join("shaderpacks"))); - self.shader_packs_found = Some((key.clone(), found)); - } - let status = self.shader_packs.status(); - let errors = self.shader_packs.errors().to_vec(); - let found = &mut self.shader_packs_found.as_mut().expect("listed").1; - let choice: &mut ShaderPackChoice = self.shader_pack_choices.entry(key).or_default(); - let action = shader_pack::ui( - ui, - choice, - found, - self.shader_pack_override.as_ref().map(|(p, _)| p.as_path()), - &status, - &errors, - ); - if action.reload { - self.shader_packs.reload(); - } - } - - /// The scene shown: the timeline at the playhead, then the fly camera's override. - fn shown_scene(&self) -> Scene { - animate::shown_scene( - &self.timeline, - &self.scene, - self.playhead, - &self.camera_override, - ) - } - - /// Moves the shown camera with the fly camera; animated values go to the override, the - /// rest to the base (`animate::apply_fly`). - fn fly_camera(&mut self, f: impl FnOnce(&FlyCamera, &mut Camera)) { - let evaluated = self.timeline.scene_at(&self.scene, self.playhead).camera; - let mut camera = evaluated.clone(); - self.camera_override.apply(&mut camera); - f(&self.fly, &mut camera); - animate::apply_fly( - &self.timeline, - &mut self.scene, - &mut self.camera_override, - &evaluated, - &camera, - ); - // Flying isn't an edit: it never becomes an undo step. - self.history.absorb_camera(&self.scene.camera); - } - - /// The camera-path overlay: only with the Preview engine selected and the Timeline tab - /// open. - fn path_overlay(&self) -> Option { - let timeline_shown = - self.timeline_panel.open && self.timeline_panel.tab == timeline_panel::Tab::Timeline; - if self.engine != EngineChoice::Preview || !timeline_shown { - return None; - } - playback::path_overlay(&self.timeline, self.playhead) - } - - /// Opens the Orbit dialog around the selection's centre at the camera's height (without - /// a world: 32 blocks ahead of the camera). - fn open_orbit_dialog(&mut self) { - let camera = self.shown_scene().camera; - let centre = match &self.world { - Some(w) => { - let c = w.blocks.center.as_vec3() + Vec3::new(0.5, 0.0, 0.5); - Vec3::new(c.x, camera.position.y, c.z) - } - None => { - let f = camera.forward(); - let ahead = Vec3::new(f.x, 0.0, f.z).normalize_or(Vec3::Z) * 32.0; - camera.position + ahead - } - }; - self.orbit_dialog = Some(Orbit::around(centre, &camera, self.playhead)); - } - - /// Whether the render queue runs (the engines, world and shader pack belong to it; - /// Render, Output, the Project panel, playback and New/Open are locked). - fn job_active(&self) -> bool { - self.queue_running || self.engines_busy() - } - - /// Whether a job's runner holds the engines (the viewport shows its frame). - fn engines_busy(&self) -> bool { - self.job.as_ref().is_some_and(|j| j.status().is_active()) - } - - /// Runs the queue for this frame: the job's slice of work, its status in the list, and - /// between jobs the next one's world load and shader-pack build. - fn step_queue(&mut self, ctx: &egui::Context) { - if let Some((id, encoder)) = &self.encoder { - match encoder.try_result() { - None => { - ctx.request_repaint_after(std::time::Duration::from_millis(200)); - return; - } - Some(result) => { - let id = *id; - self.encoder = None; - self.finish_encode(id, result); - } - } - } - if let Some(job) = &mut self.job { - let mut engines = JobEngines { - preview: &mut self.preview, - pt: &mut self.path_tracer, - sp: &mut self.shader_packs.engine, - }; - job.step(&self.gpu, &mut engines); - let status = job.status().clone(); - let done = job.done(); - if let Some(entry) = self.queue_job.and_then(|id| self.queue.get_mut(id)) { - entry.frames_done = done; - entry.status = match &status { - JobStatus::Rendering | JobStatus::Pausing => QueueStatus::Rendering, - JobStatus::Paused => QueueStatus::Paused, - JobStatus::Done => QueueStatus::Done, - JobStatus::Failed(e) => QueueStatus::Failed(e.clone()), - JobStatus::Cancelled => QueueStatus::Cancelled, - }; - } - match status { - JobStatus::Rendering | JobStatus::Pausing => { - ctx.request_repaint(); - return; - } - JobStatus::Paused => return, - ended => { - // The viewport's scheduler takes the engines back. - self.job = None; - let id = self.queue_job.take(); - self.viewport.invalidate(); - if ended == JobStatus::Cancelled { - self.finish_queue(); - return; - } - // A video job encodes its frames next. - if let Some(id) = id.filter(|&id| { - ended == JobStatus::Done - && self.queue.get(id).is_some_and(|j| j.video.is_some()) - }) { - self.start_encode(id); - return; - } - } - } - } - if !self.queue_running { - return; - } - ctx.request_repaint_after(std::time::Duration::from_millis(100)); - let id = match self.queue_job.or_else(|| self.queue.next_waiting()) { - Some(id) => id, - None => return self.finish_queue(), - }; - self.queue_job = Some(id); - let Some(entry) = self.queue.get(id).cloned() else { - self.queue_job = None; - return; - }; - let project = match entry.project() { - Ok(p) => p, - Err(e) => return self.fail_queued(id, e), - }; - let request = match project.request() { - Ok(r) => r, - Err(missing) => return self.fail_queued(id, missing.join(" ")), - }; - if entry.encode_only { - // Encode again: the frames are on disk; no world or engine needed. - return self.start_encode(id); - } - if let Some(e) = self.queue.get_mut(id) { - e.status = QueueStatus::Preparing; - } - // The job's world: wait for a running load, else load it if it isn't on screen. - if self.load.is_some() { - return; - } - let shown = self.world.as_ref().map(|w| &w.request); - if queue::needs_load(&request, shown) { - if self.queue_loading.as_ref() == Some(&request) { - // Loaded and still not on screen: the load failed. - let why = self - .error - .clone() - .unwrap_or_else(|| "loading the world failed".to_owned()); - self.queue_loading = None; - return self.fail_queued(id, why); - } - self.start_queue_load(request.clone()); - self.queue_loading = Some(request); - return; - } - self.queue_loading = None; - // The job's engine geometry (built on demand, ADR 0020). - self.queue_engine = Some(project.engine.kind); - if project.engine.kind != EngineChoice::ShaderPack - && !self.engine_resident(project.engine.kind) - { - return; - } - // The job's shader pack: built for this world before rendering. - if project.engine.kind == EngineChoice::ShaderPack { - let Some(pack) = project.engine.shader_pack.clone() else { - return self.fail_queued(id, "The job names no shader pack.".to_owned()); - }; - self.queue_pack = Some(pack.clone()); - match self.shader_packs.ready_for(&pack, self.world_version) { - None => return, - Some(Err(e)) => return self.fail_queued(id, format!("shader pack: {e}")), - Some(Ok(())) => {} - } - } - let max = self.gpu.device.limits().max_texture_dimension_2d; - let spec = match entry.spec(max) { - Ok(spec) => spec, - Err(e) => return self.fail_queued(id, e), - }; - // A video's `_frames/` folder doesn't exist before its first run. - if let JobTarget::Sequence { dir, .. } = &spec.target - && let Err(e) = std::fs::create_dir_all(dir) - { - return self.fail_queued(id, format!("can't create {}: {e}", dir.display())); - } - if let Some(e) = self.queue.get_mut(id) { - e.replace = false; - e.status = QueueStatus::Rendering; - e.frames_done = 0; - } - self.playback.pause(); - let mut engines = JobEngines { - preview: &mut self.preview, - pt: &mut self.path_tracer, - sp: &mut self.shader_packs.engine, - }; - self.job = Some(JobRunner::start(spec, &mut engines)); - self.viewport.invalidate(); - ctx.request_repaint(); - } - - /// Starts ffmpeg over job `id`'s frames (all must be on disk). - fn start_encode(&mut self, id: u64) { - let Some(entry) = self.queue.get(id).cloned() else { - return; - }; - let (project, spec) = match entry.project().and_then(|p| Ok((p, entry.spec(u32::MAX)?))) { - Ok(x) => x, - Err(e) => return self.fail_queued(id, e), - }; - let (Some(video), JobTarget::Sequence { dir, name }) = (entry.video.clone(), &spec.target) - else { - return self.fail_queued(id, "The job has no video to encode.".to_owned()); - }; - if !project.output.format.is_video() { - return self.fail_queued(id, "The job's format isn't a video.".to_owned()); - } - let ffmpeg = match &self.ffmpeg { - Ok(f) => f.path.clone(), - Err(e) => { - let why = format!("{e}. {}", ffmpeg::install_hint()); - return self.fail_queued(id, why); - } - }; - let missing = spec - .frames - .clone() - .filter(|&f| !spec.path(f).is_file()) - .count(); - if missing > 0 { - return self.fail_queued( - id, - format!( - "{missing} frame(s) missing in {}; Run again renders them.", - dir.display() - ), - ); - } - let input = ffmpeg::EncodeInput { - format: project.output.format, - quality: project.output.quality, - fps: project.timeline.fps, - pattern: crate::job::frame_pattern(dir, name, spec.frames.end.saturating_sub(1)), - start_number: u64::from(spec.frames.start) + 1, - frames: spec.frame_count(), - output: video, - }; - match Encoder::spawn(&ffmpeg, &input) { - Ok(encoder) => { - if let Some(e) = self.queue.get_mut(id) { - e.status = QueueStatus::Encoding; - e.encode_only = false; - } - self.queue_job = Some(id); - self.encoder = Some((id, encoder)); - } - Err(e) => self.fail_queued(id, e), - } - } - - /// ffmpeg finished for job `id`: Done (frames deleted unless Keep frames) or Failed (the - /// frames stay for Encode again). - fn finish_encode(&mut self, id: u64, result: Result<(), String>) { - self.queue_job = None; - let Some(entry) = self.queue.get(id).cloned() else { - return; - }; - if let Err(e) = result { - return self.fail_queued(id, e); - } - let keep = entry - .project() - .map(|p| p.output.keep_frames) - .unwrap_or(true); - if let (false, Ok(spec)) = (keep, entry.spec(u32::MAX)) { - for f in spec.frames.clone() { - let _ = std::fs::remove_file(spec.path(f)); - } - if let JobTarget::Sequence { dir, .. } = &spec.target { - // Only if nothing else is in it. - let _ = std::fs::remove_dir(dir); - } - } - log::info!( - "render queue: encoded {}", - entry.video.as_deref().unwrap_or(Path::new("?")).display() - ); - if let Some(e) = self.queue.get_mut(id) { - e.status = QueueStatus::Done; - } - } - - /// Loads a job's world, keeping the editor's camera. - fn start_queue_load(&mut self, request: LoadRequest) { - let from_panel = self.world.as_ref().is_none_or(|w| w.from_panel); - let reuse = self - .world - .as_ref() - .filter(|w| w.request.same_blocks(&request)) - .map(|w| w.blocks.clone()); - let camera = Some(self.scene.camera.clone()); - self.start_load(request, from_panel, camera, reuse); - } - - /// Marks job `id` failed; the queue goes on with the next one. - fn fail_queued(&mut self, id: u64, message: String) { - log::error!("render queue: job failed: {message}"); - if let Some(e) = self.queue.get_mut(id) { - e.status = QueueStatus::Failed(message); - } - self.queue_job = None; - } - - /// Start: runs the waiting jobs from the top. - fn start_queue(&mut self) { - if self.queue_running || self.queue.next_waiting().is_none() { - return; - } - log::info!("render queue: start"); - self.queue_running = true; - self.editor_world = self - .load - .as_ref() - .map(|l| l.request.clone()) - .or_else(|| self.world.as_ref().map(|w| w.request.clone())); - } - - /// The queue stopped (no waiting jobs, or Cancel): the editor's world and shader pack - /// come back if a job changed them. - fn finish_queue(&mut self) { - log::info!("render queue: stopped"); - self.queue_running = false; - self.queue_job = None; - self.queue_loading = None; - self.queue_pack = None; - self.queue_engine = None; - if let Some(e) = self - .queue - .jobs - .iter_mut() - .find(|j| j.status == QueueStatus::Preparing) - { - e.status = QueueStatus::Queued; - } - if let Some(request) = self.editor_world.take() { - let shown = self.world.as_ref().map(|w| &w.request); - let loading = self.load.as_ref().map(|l| &l.request); - if loading != Some(&request) && queue::needs_load(&request, shown) { - self.start_queue_load(request); - } - } - self.viewport.invalidate(); - } - - /// Cancel: stops the running (or preparing) job and the queue. - fn cancel_queue(&mut self) { - if let Some((_, encoder)) = self.encoder.take() { - encoder.kill(); - } - if let Some(job) = &mut self.job { - let mut engines = JobEngines { - preview: &mut self.preview, - pt: &mut self.path_tracer, - sp: &mut self.shader_packs.engine, - }; - job.cancel(&mut engines); - } - if let Some(e) = self.queue_job.and_then(|id| self.queue.get_mut(id)) { - e.status = QueueStatus::Cancelled; - } - self.job = None; - self.finish_queue(); - } - - /// File name for a job's frames: the project's name, else the world's. - fn job_name(&self) -> String { - let project = self.project_path.as_ref().map(|p| { - let name = project_file::display_name(Some(p)); - let suffix = format!(".{}", project_file::EXTENSION); - match name.to_lowercase().strip_suffix(&suffix) { - Some(stem) => name[..stem.len()].to_owned(), - None => name, - } - }); - let world = self.world.as_ref().map(|w| w.name.clone()); - file_stem(&project.or(world).unwrap_or_else(|| "aktis".to_owned())) - } - - /// "Add animation…" / "Add still…": asks where the frames go, then queues a snapshot of - /// the project (asking about frames already there). - fn add_job(&mut self, kind: JobKind) { - let frame = self.timeline.frame_at(self.playhead); - let mut name = self.job_name(); - let mut video = None; - let format = self.output.format; - let target = match kind { - JobKind::Animation if format.is_video() => { - let ext = format.extension(); - let mut dialog = rfd::FileDialog::new() - .set_title("Save video") - .add_filter(format.label(), &[ext]) - .set_file_name(format!("{name}.{ext}")); - if let Some(dir) = self.output.path.as_ref().and_then(|p| p.parent()) { - dialog = dialog.set_directory(dir); - } - let Some(path) = dialog.save_file() else { - return; - }; - let path = with_extension(path, ext); - self.output.path = Some(path.clone()); - // Frames go next to the video: `