From 33fda06c2e23da6c6cd35446eca80cd8ea0aaa43 Mon Sep 17 00:00:00 2001 From: Trilleo Date: Tue, 1 Dec 2026 22:41:36 +0800 Subject: [PATCH 01/14] build(ci): ship macOS .dmg and Windows installer .exe in releases Replace the release archives with platform-native packages. macOS gets an Aktis.app bundle (OIDN dylibs inside, ad-hoc signed) in a .dmg per architecture, built by scripts/package-macos.sh with hdiutil and codesign. Windows gets a per-user Inno Setup installer (scripts/aktis.iss) with Start menu shortcut and uninstaller; the portable .zip stays. The macOS .tar.gz files are dropped. Docs: ADR 0021, docs/dev/ci-and-release.md, README download section, CHANGELOG, roadmap, glossary, CLAUDE.md layout. --- .github/workflows/release.yml | 51 ++++++++++------ CHANGELOG.md | 8 +++ CLAUDE.md | 2 +- README.md | 18 +++++- docs/decisions/0021-release-packaging.md | 68 +++++++++++++++++++++ docs/decisions/README.md | 1 + docs/dev/ci-and-release.md | 75 +++++++++++++++++++----- docs/glossary.md | 2 + docs/roadmap.md | 2 +- scripts/aktis.iss | 57 ++++++++++++++++++ scripts/package-macos.sh | 64 ++++++++++++++++++++ 11 files changed, 309 insertions(+), 39 deletions(-) create mode 100644 docs/decisions/0021-release-packaging.md create mode 100644 scripts/aktis.iss create mode 100755 scripts/package-macos.sh diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index d59c6bf..58ad209 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@v5 @@ -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@v4 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@v2 with: diff --git a/CHANGELOG.md b/CHANGELOG.md index 8cc3d3a..c6bfdd3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,14 @@ uses [Semantic Versioning](https://semver.org/). ## [Unreleased] +### Changed + +- 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 - Path Tracer: the trace shader failed to compile on Windows (DX12/FXC: "array 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/README.md b/README.md index 446768d..e396250 100644 --- a/README.md +++ b/README.md @@ -43,9 +43,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/docs/decisions/0021-release-packaging.md b/docs/decisions/0021-release-packaging.md new file mode 100644 index 0000000..635baf4 --- /dev/null +++ b/docs/decisions/0021-release-packaging.md @@ -0,0 +1,68 @@ +# 0021: Releases ship as a `.dmg` with an ad-hoc-signed `Aktis.app` and an Inno Setup installer `.exe` + +- **Status:** Accepted +- **Date:** 2026-12-01 + +## Context + +Until now, releases were archives: a `.tar.gz` per macOS architecture and a `.zip` for Windows, +each holding the bare `aktis` binary with the OIDN runtime next to it (ADR 0011). That is not how +desktop apps are usually installed. On macOS a bare binary has no Dock icon or app name, can't +be dragged to Applications, and opens a Terminal window when double-clicked. On Windows a +loose folder has no Start menu entry and no uninstaller. The maintainer asked for a `.dmg` on +macOS and an `.exe` on Windows. + +Constraints: no developer certificates yet (Apple Developer ID, Authenticode), the release +runs on GitHub-hosted runners, and no Rust dependencies should be added just for packaging. The +`aktis.exe` can't stand alone either, because it needs the OIDN DLLs beside it. + +## Decision + +1. **macOS: `Aktis.app` in a `.dmg`, one per architecture.** `scripts/package-macos.sh` builds + the bundle: `Info.plist` (`io.github.tribinary.aktis`, macOS 11.0+, version from the tag), + the binary and OIDN dylibs in `Contents/MacOS` (the existing `@executable_path` rpath + finds them, so `build.rs` is unchanged), docs and licences in `Contents/Resources`. The + script then builds a UDZO image with `hdiutil`, with a link to `/Applications` beside the + app. Builds stay separate for arm64 and x86_64. A universal binary would roughly double the + download (OIDN is ~53 MB per architecture). +2. **Ad-hoc signature.** The dylibs and then the bundle are signed with `codesign --sign -`. + This needs no certificate. It is required because Apple Silicon refuses unsigned code, and + because macOS reports a bundle with a missing or broken signature as "damaged". Gatekeeper + still warns on first launch (users click Open Anyway). +3. **Windows: an Inno Setup installer `.exe`**, `scripts/aktis.iss`. It installs per user + (`PrivilegesRequired=lowest`, `%LOCALAPPDATA%\Programs\Aktis`), adds a Start menu shortcut, + an optional desktop shortcut and an uninstaller, and upgrades in place through a fixed + `AppId`. The runner installs Inno Setup with Chocolatey. +4. **The portable Windows `.zip` stays**, built from the same folder as the installer, for + users who don't want to install. The macOS `.tar.gz` files are dropped. + +## Consequences + +- Users install the usual way on both platforms. Release assets are 2 `.dmg`, 1 `.exe`, + 1 `.zip` and `SHA256SUMS.txt`. +- The packaging tools ship with macOS or are installed on the runner, so `Cargo.toml` is unchanged. +- First launch still warns (Gatekeeper, SmartScreen) until real signing arrives. Then the + same scripts gain a Developer ID identity, the hardened runtime and `notarytool` on macOS + (the bundled dylibs must be signed with the same identity), and `signtool` on Windows. +- No app icon yet: the bundle and the installer use generic icons. Adding one means an + `.icns` (`CFBundleIconFile`) and an `.ico` (`SetupIconFile`, plus a resource in the `.exe`). +- `aktis.exe` is a console-subsystem binary, so starting it from the Start menu also opens a + console window. Fixing that is a code change in `aktis-app` (it has a CLI) and isn't part of + this decision. +- Release jobs need macOS runners for the `.dmg` (`hdiutil` and `codesign` exist only on macOS). + +## Alternatives considered + +- **`cargo-bundle` / `cargo-packager`:** they would add a tool and its configuration for steps + that take only a few lines of shell. They also handle bundled dylibs and Inno Setup less + directly than the scripts do. +- **`create-dmg` (Homebrew), with a styled window and background:** a nicer window, but an + extra runner dependency, and it scripts Finder over AppleScript, which can be flaky on CI. + It can come later along with an icon. +- **WiX / MSI on Windows:** good for enterprise deployment, but the user asked for an `.exe`, + and WiX v4+ toolsets are heavier to set up. NSIS would work too, but Inno Setup's script is + simpler and does per-user installs and upgrades out of the box. +- **A bare `aktis.exe` as the `.exe` download:** it can't run without the OIDN DLLs. + Self-extracting or static linking would mean changing how OIDN ships (ADR 0011). +- **A universal macOS `.dmg`:** a single download, but about twice the size. It can come later + if users find the choice confusing. diff --git a/docs/decisions/README.md b/docs/decisions/README.md index 9c81f7c..0735d1e 100644 --- a/docs/decisions/README.md +++ b/docs/decisions/README.md @@ -27,3 +27,4 @@ To add one: copy `0000-template.md` to `NNNN-short-title.md` (next number) and a | [0018](0018-animation-tracks-and-frame-output.md) | Animation is per-property keyframe tracks evaluated in aktis-scene; frames go to disk and the user's own ffmpeg encodes them | Accepted | | [0019](0019-far-terrain-heightfield.md) | Far terrain is a column heightfield in LOD rings, read from chunk heightmaps and drawn by every engine | Accepted | | [0020](0020-memory-budget-and-residency.md) | A memory budget sizes the detail area, and only the engine in use holds its geometry | Accepted | +| [0021](0021-release-packaging.md) | Releases ship as a `.dmg` with an ad-hoc-signed `Aktis.app` and an Inno Setup installer `.exe` | Accepted | diff --git a/docs/dev/ci-and-release.md b/docs/dev/ci-and-release.md index 8e247bf..b91b487 100644 --- a/docs/dev/ci-and-release.md +++ b/docs/dev/ci-and-release.md @@ -5,7 +5,7 @@ | Workflow | Trigger | What it does | |---|---|---| | `ci.yml` | push to `main`, every PR | `fmt --check`, `clippy -D warnings`, `test` on **macOS (arm64)** and **Windows (x64)**; the same clippy and tests with the `denoise` feature against the pinned OIDN package (job `denoise`, package cached); docs check on PRs. The tests build glslang from source for `shaderc` (CMake and Python come with the runners; `Swatinem/rust-cache` keeps the build) | -| `release.yml` | push of tag `v*.*.*` (**upstream only**); manual run (dry run, any fork) | Builds release binaries with `--features denoise`, packages them with the OIDN runtime, creates a GitHub Release with notes taken from `CHANGELOG.md`. A dry run builds and packages every platform as workflow artifacts (`aktis--dryrun-…`) and publishes nothing | +| `release.yml` | push of tag `v*.*.*` (**upstream only**); manual run (dry run, any fork) | Builds release binaries with `--features denoise`, packages them with the OIDN runtime (a `.dmg` on macOS, an installer `.exe` and a `.zip` on Windows), creates a GitHub Release with notes taken from `CHANGELOG.md`. A dry run builds and packages every platform as workflow artifacts (`aktis--dryrun-…`) and publishes nothing | Forks run CI too (useful before opening a PR), but `release.yml` is skipped unless `github.repository == 'TriBinary/aktis'`. @@ -18,21 +18,62 @@ refactor), add the `no-docs` label to the PR. ## Release artifacts +Packaging is described in ADR 0021. + | Platform | Target | File | |---|---|---| -| macOS Apple Silicon | `aarch64-apple-darwin` | `aktis--macos-arm64.tar.gz` | -| macOS Intel | `x86_64-apple-darwin` | `aktis--macos-x64.tar.gz` | -| Windows x64 | `x86_64-pc-windows-msvc` | `aktis--windows-x64.zip` | - -Each archive contains the binary plus `README.md`, `CHANGELOG.md` and the licences, and the -Intel Open Image Denoise runtime next to the binary (`scripts/bundle-oidn.sh`, ADR 0011): -the OIDN core and CPU device libraries (plus the Metal device on macOS), TBB, and OIDN's -licence and third-party notices in `licenses/oidn/`. This adds ~53 MB per archive. The -release job fetches the pinned OIDN package with `scripts/fetch-oidn.sh` and sets +| macOS Apple Silicon | `aarch64-apple-darwin` | `aktis--macos-arm64.dmg` | +| macOS Intel | `x86_64-apple-darwin` | `aktis--macos-x64.dmg` | +| Windows x64 | `x86_64-pc-windows-msvc` | `aktis--windows-x64-setup.exe` (installer) | +| Windows x64 | `x86_64-pc-windows-msvc` | `aktis--windows-x64.zip` (portable) | + +Every package carries the binary, `README.md`, `CHANGELOG.md`, the licences, and the +Intel Open Image Denoise runtime (`scripts/bundle-oidn.sh`, ADR 0011): the OIDN core and +CPU device libraries (plus the Metal device on macOS), TBB, and OIDN's licence and +third-party notices in `licenses/oidn/`. This adds ~53 MB per package. The release job +fetches the pinned OIDN package with `scripts/fetch-oidn.sh` and sets `AKTIS_OIDN_RELEASE=1` so macOS binaries only search `@executable_path`. A -`SHA256SUMS.txt` file is attached as well. Binaries are **not signed or notarized yet**. On -macOS, users must right-click → Open (or `xattr -d com.apple.quarantine aktis`). Signing, -notarization and a `.app` bundle are planned. +`SHA256SUMS.txt` file is attached as well. + +### macOS: `.dmg` (`scripts/package-macos.sh`) + +The disk image holds `Aktis.app` and a link to `/Applications`: + +``` +Aktis.app/Contents/ + Info.plist io.github.tribinary.aktis, macOS 11.0+, version from the tag + MacOS/ aktis + the OIDN/TBB dylibs (found through @executable_path) + Resources/ README, CHANGELOG, licences, licenses/oidn/ +``` + +The script signs the dylibs and then the bundle **ad hoc** (`codesign --sign -`, no +certificate), because Apple Silicon won't run unsigned code, and then builds a compressed +image with `hdiutil` (UDZO). Both tools ship with macOS, so the runner needs nothing extra. +To build one locally after a release build: + +```sh +scripts/package-macos.sh target/release/aktis .oidn/oidn-2.5.1.arm64.macos 0.1.0 dist/aktis.dmg +``` + +### Windows: installer `.exe` (`scripts/aktis.iss`) + +The workflow copies the binary, docs and OIDN DLLs into a folder, zips that folder (the +portable `.zip`), and compiles the same folder into an [Inno Setup](https://jrsoftware.org/isinfo.php) +installer. The runner gets Inno Setup through `choco upgrade innosetup` (the script needs +6.3 or later). The installer: + +- installs per user into `%LOCALAPPDATA%\Programs\Aktis` (no administrator prompt); +- adds a Start menu shortcut, an optional desktop shortcut and an uninstaller + (Settings → Apps); +- upgrades in place, because the `AppId` in `aktis.iss` stays the same. **Never change it.** + +### Signing + +Packages are **not signed with a developer certificate or notarized yet**. On macOS, the +first launch says Apple can't verify the app: users open System Settings → Privacy & +Security → **Open Anyway** (or run `xattr -dr com.apple.quarantine /Applications/Aktis.app`). +On Windows, SmartScreen warns: **More info** → **Run anyway**. Developer ID signing with +notarization, and Authenticode signing, are planned. ## How to release @@ -54,9 +95,11 @@ and `Cargo.toml`, waiting for the `v0.1.0` tag. ### Dry run Actions → Release → Run workflow (on the fork or upstream) builds and packages all three -platforms without the tag check and without publishing. Download the artifacts to check an -archive, e.g. that `aktis` starts and logs `denoiser: Open Image Denoise 2.5.1 (CPU)` with -`RUST_LOG=info`. +platforms without the tag check and without publishing. Download the artifacts to check a +package. For example, mount the `.dmg` and run +`RUST_LOG=info /Volumes/Aktis*/Aktis.app/Contents/MacOS/aktis`, which should log +`denoiser: Open Image Denoise 2.5.1 (CPU)`. On Windows, run the installer and start Aktis +from the Start menu. ## Dependabot diff --git a/docs/glossary.md b/docs/glossary.md index 8c6b4d6..beb7809 100644 --- a/docs/glossary.md +++ b/docs/glossary.md @@ -121,3 +121,5 @@ | **Output resolution** | The fixed pixel size images are rendered at (`[output]` width × height), independent of the viewport; jobs always use it, the viewport too with Render size = Output. | | **Render job** | One animation (frames in to out) or still rendered offscreen at the output resolution to PNG files, from a snapshot of the project taken when it starts. | | **Render size** | Whether the viewport's engines render at the output resolution (shown scaled to fit) or at the viewport's own pixel size. | +| **App bundle** | macOS app folder `Aktis.app` (`Contents/Info.plist`, `MacOS/`, `Resources/`) that Finder shows as one app; releases ship it in a `.dmg` (ADR 0021). | +| **Ad-hoc signature** | A code signature with no certificate (`codesign --sign -`). Apple Silicon needs one to run code, but Gatekeeper still warns because it names no developer (ADR 0021). | diff --git a/docs/roadmap.md b/docs/roadmap.md index 25af229..d35448f 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1167,7 +1167,7 @@ subsystem docs' open questions, roughly by how often they came up: | Area | Item | From | |---|---|---| | Platforms | Windows (DX12/Vulkan) smoke tests by hand for M3–M8 | M3–M8 closes | -| Platforms | Signed and notarized macOS builds, a `.app` bundle | [ci-and-release.md](dev/ci-and-release.md) | +| Platforms | Signed and notarized macOS builds, Authenticode-signed Windows installer, an app icon | [ci-and-release.md](dev/ci-and-release.md) | | World | Biome tints, block entities (chests, signs, …), mobs and armor stands | M1, [world.md](subsystems/world.md), [assets.md](subsystems/assets.md) | | Shader packs | Pack options UI, compute passes, raw/resource-location custom textures, `dh_shadow`, cloud/weather/entity programs | [shader-packs.md](subsystems/shader-packs.md) | | Path tracer | 16-bit PNG/EXR output, motion blur, temporal denoising | M2, M7 | diff --git a/scripts/aktis.iss b/scripts/aktis.iss new file mode 100644 index 0000000..3b157d5 --- /dev/null +++ b/scripts/aktis.iss @@ -0,0 +1,57 @@ +; Inno Setup script for the Windows installer (ADR 0021). The release workflow runs: +; +; iscc /DAppVersion= /DSourceDir= /DOutputDir= +; /DOutputBaseFilename= scripts\aktis.iss +; +; is the packaged release folder: the binary, the OIDN DLLs +; (scripts/bundle-oidn.sh), README, CHANGELOG and the licences. + +#ifndef AppVersion + #error Pass /DAppVersion= +#endif +#ifndef SourceDir + #error Pass /DSourceDir= +#endif +#ifndef OutputDir + #define OutputDir "dist" +#endif +#ifndef OutputBaseFilename + #define OutputBaseFilename "aktis-" + AppVersion + "-windows-x64-setup" +#endif + +[Setup] +; Never change AppId: Windows uses it to recognise upgrades and the uninstaller. +AppId={{D04F1961-2D4E-400A-AA5A-811EF90BC4C5} +AppName=Aktis +AppVersion={#AppVersion} +AppVerName=Aktis {#AppVersion} +AppPublisher=Trilleo +AppPublisherURL=https://github.com/TriBinary/aktis +AppSupportURL=https://github.com/TriBinary/aktis/issues +AppUpdatesURL=https://github.com/TriBinary/aktis/releases +; Per-user install into %LOCALAPPDATA%\Programs\Aktis: no administrator prompt. +PrivilegesRequired=lowest +DefaultDirName={autopf}\Aktis +DisableProgramGroupPage=yes +ArchitecturesAllowed=x64compatible +ArchitecturesInstallIn64BitMode=x64compatible +OutputDir={#OutputDir} +OutputBaseFilename={#OutputBaseFilename} +Compression=lzma2/max +SolidCompression=yes +WizardStyle=modern +UninstallDisplayIcon={app}\aktis.exe +UninstallDisplayName=Aktis + +[Tasks] +Name: "desktopicon"; Description: "{cm:CreateDesktopIcon}"; GroupDescription: "{cm:AdditionalIcons}"; Flags: unchecked + +[Files] +Source: "{#SourceDir}\*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs createallsubdirs + +[Icons] +Name: "{autoprograms}\Aktis"; Filename: "{app}\aktis.exe" +Name: "{autodesktop}\Aktis"; Filename: "{app}\aktis.exe"; Tasks: desktopicon + +[Run] +Filename: "{app}\aktis.exe"; Description: "{cm:LaunchProgram,Aktis}"; Flags: nowait postinstall skipifsilent diff --git a/scripts/package-macos.sh b/scripts/package-macos.sh new file mode 100755 index 0000000..9743e29 --- /dev/null +++ b/scripts/package-macos.sh @@ -0,0 +1,64 @@ +#!/usr/bin/env bash +# Builds the macOS release disk image: an `Aktis.app` bundle with the OIDN runtime inside, +# ad-hoc signed, next to a link to /Applications (ADR 0021). +# +# scripts/package-macos.sh +# +# : a folder printed by scripts/fetch-oidn.sh. Needs macOS (hdiutil, codesign). +set -euo pipefail + +usage="usage: package-macos.sh " +bin="${1:?$usage}" +oidn="${2:?$usage}" +version="${3:?$usage}" +out="${4:?$usage}" +root="$(cd "$(dirname "$0")/.." && pwd)" + +stage="$(mktemp -d)" +trap 'rm -rf "$stage"' EXIT +app="$stage/Aktis.app" +mkdir -p "$app/Contents/MacOS" "$app/Contents/Resources" + +# CFBundleVersion must be numbers and dots: drop a pre-release suffix such as `-beta.1`. +short="${version%%-*}" +cat > "$app/Contents/Info.plist" < + + + + CFBundleDevelopmentRegionen + CFBundleDisplayNameAktis + CFBundleExecutableaktis + CFBundleIdentifierio.github.tribinary.aktis + CFBundleInfoDictionaryVersion6.0 + CFBundleNameAktis + CFBundlePackageTypeAPPL + CFBundleShortVersionString$version + CFBundleVersion$short + LSApplicationCategoryTypepublic.app-category.graphics-design + LSMinimumSystemVersion11.0 + NSHighResolutionCapable + NSSupportsAutomaticGraphicsSwitching + + +EOF + +# The binary's @executable_path rpath (crates/aktis-app/build.rs) finds the dylibs here. +cp "$bin" "$app/Contents/MacOS/aktis" +"$root/scripts/bundle-oidn.sh" "$oidn" "$app/Contents/MacOS" +# Contents/MacOS holds code only (codesign treats every file there as code). +mv "$app/Contents/MacOS/licenses" "$app/Contents/Resources/licenses" +cp "$root/README.md" "$root/CHANGELOG.md" "$root/LICENSE-MIT" "$root/LICENSE-APACHE" \ + "$app/Contents/Resources/" + +# Ad-hoc signature: no certificate, but Apple Silicon refuses to run unsigned code and a +# bundle with a broken signature shows as "damaged". Inner code first, then the bundle. +find "$app/Contents/MacOS" -type f -name '*.dylib' -exec codesign --force --sign - {} \; +codesign --force --sign - "$app" +codesign --verify --strict --verbose=2 "$app" + +ln -s /Applications "$stage/Applications" +mkdir -p "$(dirname "$out")" +rm -f "$out" +hdiutil create -volname "Aktis $version" -srcfolder "$stage" -fs HFS+ -format UDZO -ov "$out" +ls -l "$out" From b33941e23615cf8d042900195f1e7caf89e8deca Mon Sep 17 00:00:00 2001 From: Trilleo Date: Tue, 1 Dec 2026 22:55:07 +0800 Subject: [PATCH 02/14] docs: design M9 projects and workspaces (ADR 0022) Add ADR 0022: the app opens on a Home screen of recent projects; each project is an Image or a Video project, fixed at creation, with its own workspace, a canvas chosen in the New Project dialog and changeable in the workspace, and a project folder (.aktis/) holding the file, thumbnail, renders, exports and autosave. Add M9 to the roadmap with nine tasks, the planned "Projects and workspaces" section in app.md, "Project format 2" with the format-1 migration in scene.md, a Video-only note in animation.md, and new glossary terms. Nothing is built yet; all new sections say Planned. --- .../decisions/0022-projects-and-workspaces.md | 82 ++++++++++++++++ docs/decisions/README.md | 1 + docs/glossary.md | 9 ++ docs/roadmap.md | 62 ++++++++++++- docs/subsystems/animation.md | 4 + docs/subsystems/app.md | 93 +++++++++++++++++++ docs/subsystems/scene.md | 59 ++++++++++++ 7 files changed, 309 insertions(+), 1 deletion(-) create mode 100644 docs/decisions/0022-projects-and-workspaces.md diff --git a/docs/decisions/0022-projects-and-workspaces.md b/docs/decisions/0022-projects-and-workspaces.md new file mode 100644 index 0000000..10bde12 --- /dev/null +++ b/docs/decisions/0022-projects-and-workspaces.md @@ -0,0 +1,82 @@ +# 0022: The app opens on a Home screen of projects; each project is an Image or a Video project with its own workspace + +- **Status:** Accepted +- **Date:** 2026-12-01 + +## Context + +Up to 0.1.0 the app is one window: Project panel, viewport, Render panel and a bottom panel +with the timeline and render queue. Stills and animations share it, so a user who wants a +single wallpaper still sees keyframes, fps and video encoders, and an animation's output +size is a setting buried in the Render panel. The open project lives in `app.ron` as a +session; project files (`*.aktis.toml`, M7) are one file each, with nowhere to keep a +thumbnail, earlier renders or recovery data. There is no list of recent projects. + +The maintainer asked (2026-12-01) for a projects view on start, a choice of Image or Video +mode when creating a project, separate layouts and features per mode, and a canvas size +chosen at creation and changeable in the workspace. The design borrows from mainstream +tools: DaVinci Resolve and Premiere (project home, a separate Deliver page), Photoshop (New +Document presets, canvas size), Lightroom and Blender (render filmstrip, A/B compare, +workspace tabs). + +## Decision + +1. **Screens.** The app has two screens: **Home** (recent projects, New Image, New Video, + Open…, the Minecraft library) and the **workspace** of the one open project. One project + is open at a time; ⌂ Home closes it (asking to save). +2. **Mode is fixed per project.** `[project] mode = "image" | "video"`. Image projects have + no timeline, playback, keyframes, render queue or video encoding; Video projects have no + render history or A/B compare. Switching mode is "Save a copy as Image/Video project": + Video → Image takes the scene at the playhead; Image → Video uses the scene as the base + scene with an empty timeline. +3. **Canvas.** Each project has a canvas (`[canvas] width, height`) chosen in the New + Project dialog from per-mode presets or custom, and changed in the workspace from the + header's canvas chip (an undoable edit). Image canvases may have odd sides; Video + canvases are rounded up to even (codecs need it). The camera's vertical FOV + (`camera.fov_y`, already vertical) stays fixed on a resize, so a wider canvas shows more + at the sides. A **Preview scale** (25 / 50 / 100 % of the canvas) replaces the Render size + Output/Viewport setting. +4. **Project folder.** A project is a folder `.aktis/` holding `project.aktis.toml` + (format 2), `thumbnail.png`, `renders/` (Image render history), `exports/` (default + Video output) and `.autosave.toml` (recovery). Format-1 single files still open; saving + one writes a project folder beside it and leaves the old file alone. +5. **Workspaces.** Both share a header (Home, name, mode, canvas chip, engine, Render), a + World panel on the left and an Inspector on the right (Camera, Light, Render, Post). + - *Image:* composition guides, Views (camera bookmarks), Render Image (background + render to a target sample count), a Renders filmstrip (last 20 kept, pinned ones + never dropped) with A/B compare and Export. + - *Video:* two pages. **Animate**: transport bar, key toggles (◆) in the Inspector, the + existing dope sheet, orbit helper and camera-path overlay. **Deliver**: output + presets, destination and the render queue. +6. **Saving.** The workspace autosaves to `.autosave.toml` in the project folder; going + Home or quitting with unsaved changes asks Save / Don't Save / Cancel; a newer + autosave than the project file is offered for recovery when the project opens. + `app.ron` keeps only app-wide state: the Minecraft library (install folders, per-instance + resource and shader pack lists), the recent-projects list, preferences and window state. +7. **Fixed layouts.** Panels collapse but don't dock or float; no docking dependency. + +## Consequences + +- Each mode shows only what it needs; the timeline and queue stop cluttering stills. +- The project folder gives thumbnails, render history and recovery a home, and makes + projects easy to move or share as one folder. +- `app.rs` (3 600 lines) gets split as part of the change: a shared `Session` (world, + engines, loader), a Home screen and per-mode workspace modules. +- The session no longer lives in `app.ron`, so autosave and a quit prompt replace "quitting + keeps the changes"; old saved state is read once to seed the library. +- The render queue becomes per project (Video only); jobs from several projects can't share + one queue any more (see the open question in `app.md`). +- Users with M7 single-file projects get a folder next to the file on the next save. + +## Alternatives considered + +- **One layout with a mode toggle** (show/hide panels). Cheaper, but the two modes keep + sharing state and the "mixing together" the maintainer wants gone stays. +- **Keep single-file projects** with thumbnails and renders in an app cache. Simpler format, + but moving a project loses its renders and the cache grows without an owner. +- **Switching mode in place.** Image → Video is harmless, but Video → Image silently drops + a timeline; a copy keeps both. +- **Dockable panels (`egui_dock`).** Flexible, but a new dependency and much more layout + state to persist; fixed layouts first, docking can come later. +- **Several open projects in tabs.** Each would hold its own world and engine geometry, + multiplying memory that M8's budget assumes is spent once. diff --git a/docs/decisions/README.md b/docs/decisions/README.md index 0735d1e..d833cff 100644 --- a/docs/decisions/README.md +++ b/docs/decisions/README.md @@ -28,3 +28,4 @@ To add one: copy `0000-template.md` to `NNNN-short-title.md` (next number) and a | [0019](0019-far-terrain-heightfield.md) | Far terrain is a column heightfield in LOD rings, read from chunk heightmaps and drawn by every engine | Accepted | | [0020](0020-memory-budget-and-residency.md) | A memory budget sizes the detail area, and only the engine in use holds its geometry | Accepted | | [0021](0021-release-packaging.md) | Releases ship as a `.dmg` with an ad-hoc-signed `Aktis.app` and an Inno Setup installer `.exe` | Accepted | +| [0022](0022-projects-and-workspaces.md) | The app opens on a Home screen of projects; each project is an Image or a Video project with its own workspace | Accepted | diff --git a/docs/glossary.md b/docs/glossary.md index beb7809..e619e98 100644 --- a/docs/glossary.md +++ b/docs/glossary.md @@ -123,3 +123,12 @@ | **Render size** | Whether the viewport's engines render at the output resolution (shown scaled to fit) or at the viewport's own pixel size. | | **App bundle** | macOS app folder `Aktis.app` (`Contents/Info.plist`, `MacOS/`, `Resources/`) that Finder shows as one app; releases ship it in a `.dmg` (ADR 0021). | | **Ad-hoc signature** | A code signature with no certificate (`codesign --sign -`). Apple Silicon needs one to run code, but Gatekeeper still warns because it names no developer (ADR 0021). | +| **Home screen** | The screen the app opens on (M9, Planned): recent projects, New Image, New Video, Open…, the Minecraft library (ADR 0022). | +| **Image project / Video project** | A project's mode (`[project] mode`, M9, Planned), fixed at creation: an Image project makes stills (render history, Views); a Video project makes animations (timeline, Deliver page). | +| **Project folder** | `.aktis/`: a project's file plus its thumbnail, renders, exports, queue and autosave (M9, Planned). | +| **Canvas** | A project's image size in pixels (`[canvas]`, M9, Planned); replaces the output resolution. Video canvases have even sides. | +| **Workspace** | The layout for the open project, one per mode (M9, Planned). | +| **Preview scale** | The fraction of the canvas (25 / 50 / 100 %) the viewport's engines render at (M9, Planned); replaces Render size. | +| **View** | A saved camera position in an Image project, shown in the left panel (M9, Planned). | +| **Render history** | An Image project's last renders (20, plus pinned ones), shown as a filmstrip with A/B compare (M9, Planned). | +| **Deliver page** | The Video workspace's page for output settings and the render queue (M9, Planned). | diff --git a/docs/roadmap.md b/docs/roadmap.md index d35448f..58651e3 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -14,6 +14,7 @@ finishes. | M6 | Shader-pack compatibility | Shadow pass, custom textures, more built-in inputs; Complementary renders | Done | | M7 | Animation | Keyframe timeline, camera paths, playback, PNG sequences, video via the user's ffmpeg, render queue | Done | | M8 | Big worlds | Memory budget, one geometry copy per engine, far terrain (LOD) in every engine, re-centring the detail area | Done | +| M9 | Projects & workspaces | Home screen of recent projects, Image and Video projects with their own workspaces, canvas size, project folders | In progress | ## Releases @@ -21,7 +22,7 @@ finishes. |---|---|---|---| | 0.1.0 | 2026-12-01 | M1–M8 (first release) | Beta: smoke-tested on macOS; Windows built and tested in CI, smoke test open | -What's planned next is listed under "After 0.1.0" at the end of this file. +M9 is in progress; other planned work is listed under "After 0.1.0" at the end of this file. ## M0: Scaffold (done) @@ -1159,6 +1160,65 @@ counted on its own. Out of scope for M8: chunk-by-chunk streaming, hiding unseen cave faces, a disk cache for far tiles (unless task 4 needs it), overhangs and caves in far terrain, far entities. +## M9: Projects & workspaces (in progress) + +Goal: the app opens on a Home screen of recent projects; a project is created as an Image or +a Video project, each with its own workspace layout and features, and a canvas size chosen +at creation and changeable in the workspace. Design: ADR 0022 and +[app.md → Projects and workspaces](subsystems/app.md#projects-and-workspaces-m9-planned); +format in [scene.md → Project format 2](subsystems/scene.md#project-format-2-m9-planned). + +Decisions (maintainer, 2026-12-01, all defaults): a project is a folder `.aktis/`; +mode is fixed, switching is "Save a copy as …"; the world is optional in the New Project +dialog; autosave to a recovery file and ask on quit and on going Home; fixed layouts (no +`egui_dock`); one project open at a time; the Image render history keeps the last 20 renders +plus pinned ones; the vertical FOV stays fixed when the canvas changes. + +- [x] 1. **Design** (docs): ADR 0022, M9 here, "Projects and workspaces" in `app.md`, + "Project format 2" in `scene.md`, glossary. *Verify:* docs read correctly and agree + with each other. + *Done:* 2026-12-01. Choices made while writing (flagged, open questions in + `app.md`): the render queue becomes per project and is saved in the project folder; + format-1 files open with mode Video when their timeline has keys, else Image; a + saved format-1 file becomes a folder beside it, the old file left alone; Preview + scale is app-wide. +- [ ] 2. **Project format 2** (app, scene): `[project] mode`, `[canvas]`, format 2, + reading format 1 (migration table in `scene.md`), the project folder (create, open, + atomic save, `thumbnail.png`), the recent-projects list and the Minecraft library in + `app.ron`. *Verify:* round-trip and migration unit tests; old saved state seeds the + library. +- [ ] 3. **App shell** (app): `Screen` (Home / Workspace), a shared `Session` (world, + engines, loader, job runner), `app.rs` split into `home/` and `workspace/{common, + image,video}`; today's layout becomes the Video workspace. *Verify:* no visible + change in a Video project; all tests pass. +- [ ] 4. **Home screen** (app): New Image / New Video / Open…, recents grid and list with + thumbnail, mode badge, canvas, world and date; search, mode filter, sort; card menu + (Open, Reveal, Duplicate, Rename, Remove from recents, Move to Trash); missing + projects greyed with Locate…; drag and drop; the Minecraft library settings. + *Verify:* unit tests for the recents list (order, cap, missing); smoke-test rows. +- [ ] 5. **New Project dialog** (app): mode tabs, per-mode presets, width × height with + aspect lock and orientation swap, fps and duration (Video), name and location, + optional instance and world, "Start from" another project. *Verify:* unit tests for + presets, even sides and names; smoke-test rows. +- [ ] 6. **Canvas** (app): header canvas chip and popover (presets, custom, lock, swap) as an + undo step, fixed vertical FOV, Preview scale replacing Render size, frame guide and + composition guides. *Verify:* tests for resize rules and undo; smoke-test rows. +- [ ] 7. **Video workspace** (app): Animate page (transport bar under the viewport, ◆ key + toggles in the Inspector, dope sheet, Library with Orbit…), Deliver page (output + presets, destination, the per-project render queue, ffmpeg). *Verify:* existing + timeline and queue tests; smoke-test rows for playback and a queued video. +- [ ] 8. **Image workspace** (app): Inspector, Views (camera bookmarks), Render Image to a + target sample count in the background, Renders filmstrip (keep 20, pin), A/B compare + slider, Export PNG. *Verify:* unit tests for the history (cap, pins, index file); + smoke-test rows. +- [ ] 9. **Autosave and recovery** (app): `.autosave.toml` every 30 s while dirty, Save / + Don't Save / Cancel on Home and quit, recovery offer on open. *Verify:* unit tests + for dirty tracking and recovery choice; smoke-test rows. + +Out of scope for M9: dockable panels, several open projects, Image variants (one view at +several times of day), 360° panoramas, tiled rendering beyond the GPU's texture limit, +project templates, JPEG/EXR export. + ## After 0.1.0 (planned) No milestones are defined yet. Collected from the milestones' out-of-scope notes and the diff --git a/docs/subsystems/animation.md b/docs/subsystems/animation.md index f2d60ee..091fcd9 100644 --- a/docs/subsystems/animation.md +++ b/docs/subsystems/animation.md @@ -8,6 +8,10 @@ viewport, and render every frame with either engine to a PNG sequence or a video ## Status +**Planned (M9, ADR 0022):** the timeline, playback, Orbit helper and render queue move to +Video projects only (Animate and Deliver pages); Image projects have none of them. See +[app.md → Projects and workspaces](app.md#projects-and-workspaces-m9-planned). + **Working** (M7 closed). Design agreed with the maintainer on 2026-11-30 (five interview rounds; all defaults except per-property keys, which the maintainer asked for explicitly). Built: `camera.roll` in the scene and all three engines (task 1); the timeline model and its diff --git a/docs/subsystems/app.md b/docs/subsystems/app.md index 41d2c5a..5f26588 100644 --- a/docs/subsystems/app.md +++ b/docs/subsystems/app.md @@ -24,6 +24,9 @@ PNG files or a video (your own ffmpeg) through a render queue (see "Render queue "Video encoding"). Only the engine in use keeps world geometry (see "Engine geometry"), and a memory budget lowers the radius of loads that wouldn't fit (see "Memory budget"). +**Planned (M9, ADR 0022):** a Home screen of recent projects and separate Image and Video +workspaces replace the single window described below; see "Projects and workspaces". + ## Design - **eframe 0.37 + wgpu.** Implement `eframe::App::ui`. Engines render into wgpu textures shown @@ -720,6 +723,88 @@ shown again, so long drags never leave it at the edge. Keys are ignored while a text field has keyboard focus. The app redraws continuously only while the camera moves or turns; the frame rate readout shows "idle" otherwise. +### Projects and workspaces (M9, Planned) + +Design for M9 ([roadmap](../roadmap.md#m9-projects--workspaces-in-progress), ADR 0022). +Nothing here is built yet; the sections above describe the app as it is. + +**Screens.** The app starts on **Home**; opening or creating a project enters its +**workspace**; ⌂ Home leaves it (asking to save). One project is open at a time. The command +line's `--world` keeps working: it opens an untitled Video project on that world. + +**Home** + +| Part | Does | +|---|---| +| New Image / New Video | Open the New Project dialog on that mode | +| Open… / drop a file | Open a project folder, or a format-1 `.aktis.toml` | +| Sidebar | Recent, All, Image, Video filters; Minecraft library (install folders, Rescan, per-instance resource and shader packs: today's Project-panel lists); Settings | +| Recents | Grid or list of cards: `thumbnail.png`, mode badge, canvas (`3840×2160`; Video adds `1080p · 60 · 0:45`), world name, last opened. Search by name or world, sort by last opened / name / created | +| Card menu | Open, Reveal in Finder/Explorer, Duplicate, Rename, Remove from recents, Move to Trash (confirmed) | +| Missing project | Greyed, with Locate… and Remove | + +**New Project dialog** + +| Control | Image | Video | +|---|---|---| +| Presets | Wallpaper 1920×1080, 2560×1440, 3840×2160; Ultrawide 3440×1440; Phone 1170×2532; Square 2048×2048; Portrait 1080×1350; Poster A4 2480×3508 (300 dpi); Thumbnail 1280×720; Custom | 720p, 1080p (default), 1440p, 4K; Vertical 1080×1920; Square 1080×1080; Custom | +| Width × height | 16 to the GPU's `max_texture_dimension_2d`, any parity; aspect lock 🔗, orientation swap | Same, rounded up to even | +| Frame rate, duration | — | 24 / 25 / 30 / 60 fps (default 30), duration (default 10 s) | +| Name, location | Folder `.aktis/` under the location (default `~/Aktis Projects`, remembered) | Same | +| World (optional) | Instance and world pickers; empty = choose in the workspace | Same | +| Start from | Blank, or another project's world, packs, engine and lighting | Same | + +**Workspace frame (both modes)** + +| Area | Content | +|---|---| +| Header | ⌂ Home · name (`•` unsaved) · mode badge · canvas chip `3840 × 2160 ▾` (Video adds `30 fps · 0:10 ▾`) · engine (Preview / Path tracer / Shader pack) · ▶ Render | +| Left: World | World and selection (today's Project panel minus the install lists), resource packs, shader pack, memory budget | +| Centre | Viewport showing the canvas frame; Fit / 100 %; Preview scale 25 / 50 / 100 % | +| Right: Inspector | Tabs Camera (FOV, roll, speed), Light (sun, sky, fog), Render (engine settings, samples, denoise), Post (exposure) | + +**Canvas chip:** a popover with the mode's presets, custom width × height, aspect lock and +orientation swap. A change is one undo step. `camera.fov_y` stays, so a wider canvas shows +more at the sides. **Preview scale** (app-wide, saved in `app.ron`) replaces Render size: +the viewport's engines render at that fraction of the canvas, drawn scaled to fit. + +**Image workspace** + +| Part | Does | +|---|---| +| Guides | Off / rule of thirds / golden ratio / centre cross over the canvas frame | +| Views | Left-panel list of saved camera positions (name, thumbnail); click to jump, rename, delete; saved in the project | +| ▶ Render Image | Renders the canvas to the Render tab's sample count in the background (the job runner), with progress in the header; Cancel keeps the partial image | +| Renders filmstrip | Bottom strip of finished renders (`renders/NNNN.png` + `renders/index.toml`: engine, spp, time, view, pinned). Keeps the last 20; pinned ones never drop. Click shows it in the viewport, Esc goes back to live | +| Compare | Pick A and B, drag a split slider | +| Export… | Save the selected render as PNG anywhere | + +**Video workspace** has two pages, switched in the header: + +| Page | Content | +|---|---| +| Animate | Viewport with safe areas and the camera path; transport bar under it (⏮, ◀◆, ▶, ◆▶, ⏭, Loop, timecode); ◆ key toggles next to animatable Inspector fields (today's stopwatches); the dope sheet below (today's Timeline tab); Library in the left panel with Orbit… | +| Deliver | Output presets (PNG sequence, H.264, H.265, ProRes; today's `[output]` settings), destination (default `exports/`), ffmpeg, a preview of the frame at the playhead, and the project's render queue | + +**Saving and recovery.** Save writes the project folder (atomically, plus `thumbnail.png` +from the last render or the viewport). While there are unsaved changes the workspace writes +`.autosave.toml` every 30 s; ⌂ Home and quitting ask Save / Don't Save / Cancel; opening a +project whose autosave is newer than its file offers Recover / Discard. + +**Saved state after M9.** `app.ron` keeps: the Minecraft library (today's `extra_dirs`, +`packs`, `shader_packs` lists and `max_texture_size`), the recent-projects list (path, mode, +name, canvas, world name, last opened; cached so Home doesn't read every project; up to +50), the last location, Preview scale, path-tracer view and denoise view settings, ffmpeg +path, panel state. Scene, timeline, output, queue and selection move into the project. Old +saved state is read once: its lists seed the library, its session is dropped (the open +project file, if any, joins the recents). + +**Modules (planned):** `session.rs` (world, engines, loader, job runner; shared), +`home/` (screen, recents, new-project dialog), `workspace/common.rs` (header, World panel, +Inspector, canvas chip), `workspace/image.rs`, `workspace/video.rs` (Animate, Deliver), +`project_dir.rs` (the folder: create, open, save, thumbnail, autosave), `history_renders.rs` +(the Image filmstrip). + ## Open questions - A world load that moves the camera (Load, Open with another world) is an undo step, so @@ -736,3 +821,11 @@ while the camera moves or turns; the frame rate readout shows "idle" otherwise. feel different on each. (Default: tune with a sensitivity setting if it does.) - Translations (English + Chinese)? (Default: English first, keep strings in one module so i18n can be added later.) +- M9: the render queue becomes per project (saved as `queue.toml` in the project folder) + and runs only while that project is open. (Default: accept; a global queue across + projects can come later if needed.) +- M9: format-1 files open as Video when their timeline has keys, else Image; Save writes + a project folder beside the old file and leaves the file alone. (Default: as written.) +- M9: Preview scale is app-wide, not per project. (Default: app-wide.) +- M9: on macOS the `.aktis` folder could be a document package (one icon in Finder), + which needs a UTI in the app's `Info.plist`. (Default: plain folder first.) diff --git a/docs/subsystems/scene.md b/docs/subsystems/scene.md index addd21f..4fa5112 100644 --- a/docs/subsystems/scene.md +++ b/docs/subsystems/scene.md @@ -12,6 +12,8 @@ defaults). Height fog (M4): both engines read `[fog]`. `camera.roll` (M7): all t apply it; `Camera::basis()` gives the rolled image axes. The timeline (M7): the `timeline` module reads, writes and evaluates `[timeline]` (`Timeline::scene_at`). Project files (M7): read and written by `aktis-app` (`project_file.rs`); see "Project file". +Project format 2 (M9, project folders, Image/Video mode, canvas): Planned; see "Project +format 2". ## Design @@ -174,6 +176,63 @@ into −64…319 and ordered, `max_texture_size` to the cap range, `spp` 1–1 0 loads with a warning and is written back as this build's format. Output `format` is one of `png`, `mp4_h264` (default), `mp4_h265`, `mov_prores`; `quality` defaults to 18. +### Project format 2 (M9, Planned) + +Planned for M9 (ADR 0022, [app.md → Projects and workspaces](app.md#projects-and-workspaces-m9-planned)); +format 1 above is what the code reads and writes today. + +A project becomes a folder: + +``` +Castle.aktis/ + project.aktis.toml # format 2, below + thumbnail.png # longest side 512 px; written on save + renders/ # Image only: NNNN.png + index.toml (the filmstrip) + exports/ # Video only: default output destination + queue.toml # Video only: the render queue + .autosave.toml # recovery copy while there are unsaved changes +``` + +Changes to `project.aktis.toml` from format 1: + +```toml +[project] +format = 2 +mode = "image" # image | video; fixed for the project + +[canvas] # replaces [output] width/height +width = 3840 # 16 … GPU limit; Video rounds up to even +height = 2160 + +[[views]] # Image only: camera bookmarks +name = "Gate" +position = [10.0, 80.0, 10.0] +yaw = 45.0 +pitch = -10.0 +roll = 0.0 +fov_y = 70.0 + +# Video only: [timeline] as in format 1, and [output] without width/height +``` + +| Table | Image | Video | +|---|---|---| +| `[world]`, `[packs]`, `[engine]`, scene tables | ✓ | ✓ | +| `[canvas]` | ✓ | ✓ | +| `[[views]]` | ✓ | ignored | +| `[timeline]`, `[output]` | ignored, not written | ✓ | + +Reading format 1 (migration): + +| Format 1 | Format 2 | +|---|---| +| No `mode` | `video` when `[timeline]` has a key, else `image` | +| `[output] width/height` | `[canvas]` (Image keeps the values as they are) | +| `[output]` other fields | Kept for Video, dropped for Image | +| Single file `name.aktis.toml` | Opens as is; Save writes `name.aktis/` beside it and leaves the file alone | + +A missing or unknown `mode` in a format-2 file reads as `video` with a warning. + ## Open questions - None open for the scene data itself; animation questions are in From 8ee195b57a5ce9bc50a995adb7123a434d67d3b6 Mon Sep 17 00:00:00 2001 From: Trilleo Date: Tue, 1 Dec 2026 23:05:26 +0800 Subject: [PATCH 03/14] feat(app): save projects as folders with mode and canvas (format 2) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Projects are now project folders (.aktis/) holding project.aktis.toml and a thumbnail.png of the view. Project format 2 adds [project] mode (image | video), [canvas] (moved out of [output]) and Image-only [[views]]; format-1 files still open (keys → Video, none → Image) and are saved as a folder beside the old file, which is left alone. Render-queue snapshots are always Video projects so jobs keep their timeline and output. File › Open… picks a project folder; Open Project File… opens a .toml. app.ron gains the recent-projects list and the Minecraft library (install folders, resource and shader pack lists), seeded once from 0.1.0 saved state. Docs: app.md (Project files, Saved state, Modules, Render queue), scene.md (Project format 2), roadmap (M9 task 2), glossary, testing.md (tests, smoke rows 36–38), CHANGELOG. Refs ADR 0022 --- CHANGELOG.md | 17 + crates/aktis-app/src/app.rs | 270 ++++++++++++++-- crates/aktis-app/src/main.rs | 2 + crates/aktis-app/src/output.rs | 37 +++ crates/aktis-app/src/project.rs | 8 +- crates/aktis-app/src/project_dir.rs | 348 +++++++++++++++++++++ crates/aktis-app/src/project_file.rs | 283 ++++++++++++++--- crates/aktis-app/src/project_file/tests.rs | 142 ++++++++- crates/aktis-app/src/queue.rs | 2 +- crates/aktis-app/src/recent.rs | 178 +++++++++++ docs/dev/testing.md | 7 +- docs/glossary.md | 8 +- docs/roadmap.md | 16 +- docs/subsystems/app.md | 65 ++-- docs/subsystems/scene.md | 37 ++- 15 files changed, 1289 insertions(+), 131 deletions(-) create mode 100644 crates/aktis-app/src/project_dir.rs create mode 100644 crates/aktis-app/src/recent.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index c6bfdd3..a9e6308 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,8 +6,25 @@ uses [Semantic Versioning](https://semver.org/). ## [Unreleased] +### Added + +- 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. +- The app remembers recent projects (for the coming Home screen). + ### Changed +- 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 diff --git a/crates/aktis-app/src/app.rs b/crates/aktis-app/src/app.rs index 5954908..8535b8e 100644 --- a/crates/aktis-app/src/app.rs +++ b/crates/aktis-app/src/app.rs @@ -31,11 +31,13 @@ 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_dir; use crate::project_file::{ - self, EngineChoice, EngineSection, PacksSection, ProjectFile, WorldSection, + EngineChoice, EngineSection, PacksSection, ProjectFile, ProjectMode, View, WorldSection, }; use crate::pt_panel::{self, ProgressClock, SavedPtSettings}; use crate::queue::{self, NewJob, QueueStatus, RenderQueue}; +use crate::recent::{self, Library, RecentProject, Recents}; 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}; @@ -68,7 +70,10 @@ const SHORTCUT_REDO: egui::KeyboardShortcut = egui::KeyboardShortcut::new( #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum ReplaceProject { New, + /// Open a project folder. Open, + /// Open a project file: a format-1 file or a folder's `project.aktis.toml`. + OpenFile, /// Open a queued job's snapshot as an untitled project. Job(u64), } @@ -89,17 +94,29 @@ struct PendingAdd { #[serde(default)] struct Saved { project: ProjectSettings, + /// Install folders and pack lists shared by every project; `None` in saved state from + /// before M9, which is seeded from `project` and `shader_packs`. + library: Option, + /// Recent projects, most recent first. + recent: Recents, + /// The open project's mode. + mode: ProjectMode, + /// The open Image project's views. + views: Vec, scene: Scene, speed: Option, engine: EngineChoice, path_tracer: SavedPtSettings, denoise: DenoiseSettings, + /// Shader-pack lists from before M9 (now in `library`); read, never written. + #[serde(skip_serializing)] 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. + /// The open project file (a project folder's `project.aktis.toml`, or a format-1 + /// 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)>, @@ -115,6 +132,21 @@ struct Saved { ffmpeg_path: Option, } +impl Saved { + /// Moves the library into place: from `library`, or for saved state older than M9 from + /// the Project panel's and shader packs' lists (read, never written again). + fn seed_library(&mut self) { + let library = self.library.take().unwrap_or_else(|| Library { + extra_dirs: std::mem::take(&mut self.project.extra_dirs), + packs: std::mem::take(&mut self.project.packs), + shader_packs: std::mem::take(&mut self.shader_packs), + }); + self.project.extra_dirs = library.extra_dirs; + self.project.packs = library.packs; + self.shader_packs = library.shader_packs; + } +} + /// Summary of the uploaded world, for the project panel. struct WorldInfo { name: String, @@ -285,8 +317,15 @@ pub struct AktisApp { timeline: Timeline, /// Output resolution, format and destination (M7; used from task 8 on). output: OutputSettings, - /// The open project file; `None` = untitled. + /// The open project file (a project folder's `project.aktis.toml`, or a format-1 + /// file); `None` = untitled. project_path: Option, + /// The open project's mode (fixed per project; ADR 0022). + mode: ProjectMode, + /// The open Image project's views (kept and saved; edited from M9 task 8). + views: Vec, + /// Recent projects (saved). + recent: Recents, /// 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, @@ -370,10 +409,11 @@ impl AktisApp { device: render_state.device.clone(), queue: render_state.queue.clone(), }; - let saved: Saved = cc + let mut saved: Saved = cc .storage .and_then(|s| eframe::get_value(s, STORAGE_KEY)) .unwrap_or_default(); + saved.seed_library(); let preview = PreviewRenderer::new(&gpu); let history = History::new(&saved.scene, &saved.timeline); let mut path_tracer = PathTracer::new(&gpu); @@ -411,6 +451,9 @@ impl AktisApp { output: saved.output, project_baseline: None, project_path: saved.project_path, + mode: saved.mode, + views: saved.views, + recent: saved.recent, world_override: saved.world_override, project_notes: Vec::new(), confirm: None, @@ -1388,8 +1431,8 @@ impl AktisApp { /// 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); + let name = project_dir::display_name(Some(p)); + let suffix = format!(".{}", crate::project_file::EXTENSION); match name.to_lowercase().strip_suffix(&suffix) { Some(stem) => name[..stem.len()].to_owned(), None => name, @@ -1462,7 +1505,7 @@ impl AktisApp { JobTarget::File(with_png_extension(path)) } }; - let project = self.project_snapshot(); + let project = self.job_snapshot(); let existing = queue::spec_from(&project, kind, frame, target.clone(), false, u32::MAX) .existing_files() .len(); @@ -2042,7 +2085,7 @@ impl AktisApp { /// The current state as a project file: the open project's world when it couldn't be /// loaded, else the world being loaded, else the world on screen, else the Project - /// panel's choices. + /// panel's choices. Normalized for the mode (an Image project has no timeline). fn project_snapshot(&self) -> ProjectFile { let (world, packs) = self .world_override @@ -2051,6 +2094,7 @@ impl AktisApp { let pt = &self.path_tracer.settings; ProjectFile { header: Default::default(), + mode: self.mode, world, packs, engine: EngineSection { @@ -2064,7 +2108,20 @@ impl AktisApp { scene: self.scene.clone(), timeline: self.timeline.clone(), output: self.output.clone(), + views: self.views.clone(), + } + .normalized() + } + + /// The current state as a render-queue snapshot: not normalized, so the timeline and + /// output settings go with the job whatever the project's mode. + fn job_snapshot(&self) -> ProjectFile { + ProjectFile { + timeline: self.timeline.clone(), + output: self.output.clone(), + ..self.project_snapshot() } + .for_job() } /// `[world]` and `[packs]` for the world being loaded or shown, else the panel's choices. @@ -2237,6 +2294,16 @@ impl AktisApp { if item(ui, "Open…", &SHORTCUT_OPEN) { self.request_replace(ReplaceProject::Open); } + if ui + .button("Open Project File…") + .on_hover_text( + "Opens a project file: an older single-file project (.aktis.toml), \ + or the project.aktis.toml inside a project folder.", + ) + .clicked() + { + self.request_replace(ReplaceProject::OpenFile); + } ui.separator(); if item(ui, "Save", &SHORTCUT_SAVE) { self.save_project(); @@ -2303,7 +2370,7 @@ impl AktisApp { /// The "Save changes?" dialog for a pending New/Open. fn confirm_ui(&mut self, ctx: &egui::Context) { let Some(action) = self.confirm else { return }; - let name = project_file::display_name(self.project_path.as_deref()); + let name = project_dir::display_name(self.project_path.as_deref()); let mut answer = None; let modal = egui::Modal::new(egui::Id::unique("unsaved_changes")).show(ctx, |ui| { ui.set_max_width(360.0); @@ -2339,6 +2406,8 @@ impl AktisApp { // Keeps the world, packs, engine and scene: a new animation of this view. self.project_path = None; self.project_baseline = None; + self.mode = ProjectMode::Video; + self.views.clear(); self.timeline = Timeline::default(); self.output = OutputSettings::default(); self.world_override = None; @@ -2349,14 +2418,26 @@ impl AktisApp { self.history.reset(&self.scene, &self.timeline); log::info!("new project"); } - ReplaceProject::Open => { - let picked = rfd::FileDialog::new() - .set_title("Open project") - .add_filter("Aktis project", &["toml"]) - .pick_file(); + ReplaceProject::Open | ReplaceProject::OpenFile => { + let mut dialog = rfd::FileDialog::new(); + if let Some(dir) = self.project_dir_parent() { + dialog = dialog.set_directory(dir); + } + let picked = if action == ReplaceProject::Open { + dialog.set_title("Open project folder").pick_folder() + } else { + dialog + .set_title("Open project file") + .add_filter("Aktis project", &["toml"]) + .pick_file() + }; let Some(path) = picked else { return }; - match ProjectFile::read(&path) { - Ok(file) => self.apply_project(file, Some(path)), + let read = project_dir::locate(&path).and_then(|location| { + let file = location.file(); + ProjectFile::read(&file).map(|project| (project, file)) + }); + match read { + Ok((project, file)) => self.apply_project(project, Some(file)), Err(e) => { log::error!("open failed: {e:#}"); self.project_notes = vec![(true, format!("{e:#}"))]; @@ -2380,6 +2461,15 @@ impl AktisApp { None => log::info!("opening a queued job as an untitled project"), } let mut notes = Vec::new(); + self.mode = file.mode; + self.views = file.views.clone(); + if file.mode == ProjectMode::Image { + // Until the Image workspace (M9 task 8), Image projects open in today's layout. + notes.push( + "Image project: its timeline and Output format aren't saved (Image projects keep only stills)." + .to_owned(), + ); + } self.scene = file.scene.clone(); self.timeline = file.timeline.clone(); self.camera_override = CameraOverride::default(); @@ -2459,46 +2549,85 @@ impl AktisApp { } self.project_notes = notes.into_iter().map(|n| (false, n)).collect(); self.project_baseline = path.is_some().then(|| self.project_snapshot()); + if let Some(p) = &path { + self.recent + .touch(RecentProject::new(p, &file, recent::now())); + } self.project_path = path; } - /// Save: writes the open project, or asks where (Save As) when untitled. Returns whether + /// Save: writes the open project, or asks where (Save As) when untitled. A format-1 + /// file is saved as a project folder beside it, leaving the file alone. Returns whether /// it was written. fn save_project(&mut self) -> bool { match self.project_path.clone() { - Some(path) => self.write_project(path), + Some(path) => match project_dir::root_of(&path) { + Some(root) => self.write_project(root.to_owned()), + None => { + let root = project_dir::folder_for_legacy(&path); + let written = self.write_project(root.clone()); + if written { + self.project_notes.push(( + false, + format!( + "Saved as the project folder {}; the old file {} is unchanged.", + root.display(), + path.display() + ), + )); + } + written + } + }, None => self.save_project_as(), } } - /// Save As: asks for a file, then writes it. Returns whether it was written. + /// The folder holding the open project (its parent folder for a project folder), for + /// file dialogs. + fn project_dir_parent(&self) -> Option { + let path = self.project_path.as_deref()?; + let dir = project_dir::root_of(path).unwrap_or(path).parent()?; + Some(dir.to_owned()) + } + + /// Save As: asks for a name and place, then writes the project folder `.aktis` + /// there. Returns whether it was written. fn save_project_as(&mut self) -> bool { let name = match &self.project_path { - Some(p) => project_file::display_name(Some(p)), + Some(p) => project_dir::display_name(Some(p)), None => { let world = self.world.as_ref().map_or("aktis", |w| w.name.as_str()); - format!("{}.{}", file_stem(world), project_file::EXTENSION) + file_stem(world) } }; let mut dialog = rfd::FileDialog::new() - .set_title("Save project") - .add_filter("Aktis project", &["toml"]) + .set_title("Save project folder") .set_file_name(name); - if let Some(dir) = self.project_path.as_ref().and_then(|p| p.parent()) { + if let Some(dir) = self.project_dir_parent() { dialog = dialog.set_directory(dir); } match dialog.save_file() { - Some(path) => self.write_project(project_file::with_extension(path)), + Some(path) => self.write_project(project_dir::folder_for_pick(&path)), None => false, } } - fn write_project(&mut self, path: PathBuf) -> bool { + /// Writes the project folder `root` (the file, then the thumbnail when an image is + /// shown) and makes it the open project. + fn write_project(&mut self, root: PathBuf) -> bool { let file = self.project_snapshot(); - match file.write(&path) { - Ok(()) => { + match project_dir::save(&root, &file) { + Ok(path) => { log::info!("saved project {}", path.display()); self.project_notes.retain(|(error, _)| !error); + if let Some((w, h, rgba)) = self.shown_pixels() + && let Err(e) = project_dir::write_thumbnail(&root, w, h, &rgba) + { + log::warn!("thumbnail: {e:#}"); + } + self.recent + .touch(RecentProject::new(&path, &file, recent::now())); self.project_path = Some(path); self.project_baseline = Some(file); true @@ -2511,9 +2640,29 @@ impl AktisApp { } } + /// The image the viewport shows for the selected engine, read back from the GPU, or + /// `None` (nothing rendered yet, or a job holds the engines). + fn shown_pixels(&self) -> Option<(u32, u32, Vec)> { + if self.engines_busy() { + return None; + } + let output = match self.engine { + EngineChoice::Preview => self.preview.output(), + EngineChoice::PathTracer => self.path_tracer.output(), + EngineChoice::ShaderPack => self.shader_packs.engine.output(), + }?; + match aktis_render::readback::read_rgba8(&self.gpu, &output.texture) { + Ok(rgba) => Some((output.texture.width(), output.texture.height(), rgba)), + Err(e) => { + log::warn!("thumbnail readback: {e}"); + None + } + } + } + /// "flyover.aktis.toml • — Aktis" (• = unsaved changes). fn update_title(&mut self, ctx: &egui::Context) { - let name = project_file::display_name(self.project_path.as_deref()); + let name = project_dir::display_name(self.project_path.as_deref()); let dot = if self.has_unsaved_changes() { " •" } else { @@ -3451,6 +3600,14 @@ impl eframe::App for AktisApp { project.reopen = self.world.as_ref().is_some_and(|w| w.from_panel); let saved = Saved { project, + library: Some(Library { + extra_dirs: self.project.settings.extra_dirs.clone(), + packs: self.project.settings.packs.clone(), + shader_packs: self.shader_pack_choices.clone(), + }), + recent: self.recent.clone(), + mode: self.mode, + views: self.views.clone(), scene: self.scene.clone(), speed: Some(self.fly.speed), // `--shaderpack` isn't remembered: save the engine chosen before it. @@ -3576,6 +3733,61 @@ mod tests { assert_eq!(ron::ser::to_string(&back).unwrap(), default); } + /// Saved state from before M9 keeps its install folders and pack lists under + /// `project` and `shader_packs`; they seed the library once, and are then only written + /// as `library`. + #[test] + fn old_saved_state_seeds_the_library() { + let mut old = Saved::default(); + old.project.extra_dirs = vec![PathBuf::from("/games/prism")]; + let game = PathBuf::from("/games/prism/instances/26.3/minecraft"); + old.project.packs.insert( + game.clone(), + crate::packs::PackChoice { + enabled: vec![PathBuf::from("/packs/pbr.zip")], + ..Default::default() + }, + ); + old.shader_packs.insert( + game.clone(), + ShaderPackChoice { + selected: Some(PathBuf::from("/packs/BSL.zip")), + added: Vec::new(), + }, + ); + // Written the way a 0.1.0 build wrote it: lists inside `project`, no `library`. + let text = ron::ser::to_string(&old).unwrap(); + assert!(!text.contains("extra_dirs"), "no longer written: {text}"); + let text = text.replacen( + "project:(", + "project:(extra_dirs:[\"/games/prism\"],packs:{\"/games/prism/instances/26.3/minecraft\":(enabled:[\"/packs/pbr.zip\"])},", + 1, + ); + let text = text.replacen( + "denoise:", + "shader_packs:{\"/games/prism/instances/26.3/minecraft\":(selected:Some(\"/packs/BSL.zip\"))},denoise:", + 1, + ); + let mut back: Saved = ron::from_str(&text).unwrap_or_else(|e| panic!("{e}\n{text}")); + assert_eq!(back.library, None); + back.seed_library(); + assert_eq!(back.project.extra_dirs, old.project.extra_dirs); + assert_eq!(back.project.packs, old.project.packs); + assert_eq!(back.shader_packs, old.shader_packs); + + // A saved `library` wins over the old fields. + let mut new = Saved { + library: Some(Library { + extra_dirs: vec![PathBuf::from("/other")], + ..Library::default() + }), + ..Saved::default() + }; + new.project.extra_dirs = vec![PathBuf::from("/ignored")]; + new.seed_library(); + assert_eq!(new.project.extra_dirs, [PathBuf::from("/other")]); + } + #[test] fn file_stems_and_timeline_keys() { assert_eq!(file_stem(" My: World "), "My_ World"); diff --git a/crates/aktis-app/src/main.rs b/crates/aktis-app/src/main.rs index aed9301..35bc337 100644 --- a/crates/aktis-app/src/main.rs +++ b/crates/aktis-app/src/main.rs @@ -16,9 +16,11 @@ mod output; mod packs; mod playback; mod project; +mod project_dir; mod project_file; mod pt_panel; mod queue; +mod recent; mod shader_pack; mod timeline_panel; mod viewport; diff --git a/crates/aktis-app/src/output.rs b/crates/aktis-app/src/output.rs index 988baf5..a0cca6c 100644 --- a/crates/aktis-app/src/output.rs +++ b/crates/aktis-app/src/output.rs @@ -6,6 +6,8 @@ use std::path::PathBuf; use serde::{Deserialize, Serialize}; +use crate::project_file::ProjectMode; + /// Resolution presets offered in the Output section (anything else is "Custom"). pub const PRESETS: [(u32, u32); 4] = [(1280, 720), (1920, 1080), (2560, 1440), (3840, 2160)]; /// Smallest output side in pixels. @@ -20,6 +22,11 @@ pub fn even_side(side: u32) -> u32 { (side.clamp(MIN_SIDE, MAX_SIDE).saturating_add(1) & !1).min(MAX_SIDE) } +/// `side` clamped to [`MIN_SIDE`]–[`MAX_SIDE`]; any parity (Image canvases). +pub fn image_side(side: u32) -> u32 { + side.clamp(MIN_SIDE, MAX_SIDE) +} + /// What size the viewport's engines render at (saved with the app, not in projects). #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] pub enum RenderSize { @@ -130,6 +137,22 @@ impl OutputSettings { self } + /// [`Self::clamped`] for a project of `mode`: an Image canvas keeps odd sides (no + /// video codec needs them even), a Video canvas is rounded up to even. + pub fn clamped_for(self, mode: ProjectMode) -> Self { + match mode { + ProjectMode::Video => self.clamped(), + ProjectMode::Image => { + let (width, height) = (image_side(self.width), image_side(self.height)); + Self { + width, + height, + ..self.clamped() + } + } + } + } + /// `(width, height)`. pub fn size(&self) -> (u32, u32) { (self.width, self.height) @@ -192,6 +215,20 @@ mod tests { assert_eq!(OutputSettings::default().fitted(8192), (1920, 1080)); } + #[test] + fn image_canvases_keep_odd_sides() { + let s = OutputSettings { + width: 1001, + height: 3, + ..OutputSettings::default() + }; + assert_eq!( + s.clone().clamped_for(ProjectMode::Image).size(), + (1001, MIN_SIDE) + ); + assert_eq!(s.clamped_for(ProjectMode::Video).size(), (1002, MIN_SIDE)); + } + #[test] fn presets_are_even() { for (w, h) in PRESETS { diff --git a/crates/aktis-app/src/project.rs b/crates/aktis-app/src/project.rs index bcb8884..c8163fb 100644 --- a/crates/aktis-app/src/project.rs +++ b/crates/aktis-app/src/project.rs @@ -89,7 +89,9 @@ impl SelectionSettings { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(default)] pub struct ProjectSettings { - /// Install folders the user added (scanned with `install::scan_dir`). + /// Install folders the user added (scanned with `install::scan_dir`). Saved in the + /// app's [`crate::recent::Library`]; read here only from saved state older than M9. + #[serde(skip_serializing)] pub extra_dirs: Vec, /// Chosen instance, identified by its game folder. pub instance: Option, @@ -99,7 +101,9 @@ pub struct ProjectSettings { pub selection: SelectionSettings, /// Whether a world from the panel was shown when the app closed (reload it on start). pub reopen: bool, - /// Resource packs per instance, keyed by game folder. + /// Resource packs per instance, keyed by game folder. Saved in the app's + /// [`crate::recent::Library`]; read here only from saved state older than M9. + #[serde(skip_serializing)] pub packs: BTreeMap, /// Largest texture layer size in pixels (clamped on use). pub max_texture_size: u32, diff --git a/crates/aktis-app/src/project_dir.rs b/crates/aktis-app/src/project_dir.rs new file mode 100644 index 0000000..67f40f1 --- /dev/null +++ b/crates/aktis-app/src/project_dir.rs @@ -0,0 +1,348 @@ +//! Project folders (`.aktis/`, M9, ADR 0022): where a project's file, thumbnail and +//! (later) renders, exports, queue and autosave live. Layout: `docs/subsystems/scene.md` → +//! "Project format 2"; behaviour: `docs/subsystems/app.md` → "Project files". + +use std::path::{Path, PathBuf}; + +use anyhow::{Context, bail}; + +use crate::project_file::{self, ProjectFile}; + +/// Extension of a project folder, without the dot. +pub const FOLDER_EXTENSION: &str = "aktis"; +/// The project file inside a project folder. +pub const FILE_NAME: &str = "project.aktis.toml"; +/// The thumbnail inside a project folder. +pub const THUMBNAIL: &str = "thumbnail.png"; +/// Longest side of the thumbnail in pixels. +pub const THUMBNAIL_SIDE: u32 = 512; + +/// Where a project picked by the user lives. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Location { + /// A project folder: its root. + Folder(PathBuf), + /// A format-1 single file, outside any project folder. + Legacy(PathBuf), +} + +impl Location { + /// The project file to read. + pub fn file(&self) -> PathBuf { + match self { + Self::Folder(root) => root.join(FILE_NAME), + Self::Legacy(file) => file.clone(), + } + } +} + +/// Whether `dir` is a project folder (holds `project.aktis.toml`). +pub fn is_project_folder(dir: &Path) -> bool { + dir.join(FILE_NAME).is_file() +} + +/// The project folder `file` is the project file of, if it is one. +pub fn root_of(file: &Path) -> Option<&Path> { + let name = file.file_name()?.to_str()?; + if name.eq_ignore_ascii_case(FILE_NAME) { + file.parent() + } else { + None + } +} + +/// What the user picked: a project folder, the project file inside one, or a format-1 file. +pub fn locate(path: &Path) -> anyhow::Result { + if path.is_dir() { + if is_project_folder(path) { + return Ok(Location::Folder(path.to_owned())); + } + bail!("{} is not an Aktis project folder", path.display()); + } + if !path.is_file() { + bail!("{} doesn't exist", path.display()); + } + Ok(match root_of(path) { + Some(root) => Location::Folder(root.to_owned()), + None => Location::Legacy(path.to_owned()), + }) +} + +/// `name` made safe as a file name: path separators and characters Windows forbids become +/// `_`, surrounding spaces and dots go; empty becomes "Untitled". +pub fn safe_name(name: &str) -> String { + let cleaned: String = name + .chars() + .map(|c| match c { + '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|' => '_', + c if c.is_control() => '_', + c => c, + }) + .collect(); + let trimmed = cleaned.trim().trim_matches('.').trim(); + if trimmed.is_empty() { + "Untitled".to_owned() + } else { + trimmed.to_owned() + } +} + +/// The project folder for `name` in `parent`: `parent/.aktis`. A name already ending +/// in `.aktis` (any case) isn't given a second one. +pub fn folder_path(parent: &Path, name: &str) -> PathBuf { + let name = safe_name(name); + let suffix = format!(".{FOLDER_EXTENSION}"); + if name.to_lowercase().ends_with(&suffix) && name.len() > suffix.len() { + parent.join(name) + } else { + parent.join(format!("{name}{suffix}")) + } +} + +/// The folder a picked "Save As" path names: the dialog returns a file path, whose name +/// (without a `.toml` or `.aktis.toml` ending) becomes the folder's. +pub fn folder_for_pick(picked: &Path) -> PathBuf { + let parent = picked.parent().unwrap_or(Path::new(".")); + let name = picked + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default(); + folder_path(parent, &strip_toml(&name)) +} + +/// The project folder a format-1 file is saved as: `flyover.aktis.toml` → +/// `flyover.aktis/` beside it, or `flyover 2.aktis/` (3, 4 …) when that name is taken by +/// something other than a project folder. +pub fn folder_for_legacy(file: &Path) -> PathBuf { + let parent = file.parent().unwrap_or(Path::new(".")); + let name = file + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default(); + let stem = strip_toml(&name); + let first = folder_path(parent, &stem); + if !first.exists() || is_project_folder(&first) { + return first; + } + (2..) + .map(|n| folder_path(parent, &format!("{stem} {n}"))) + .find(|p| !p.exists()) + .expect("some number is free") +} + +/// `name` without a `.aktis.toml` or `.toml` ending (any case). +fn strip_toml(name: &str) -> String { + let lower = name.to_lowercase(); + for suffix in [format!(".{}", project_file::EXTENSION), ".toml".to_owned()] { + if lower.ends_with(&suffix) && name.len() > suffix.len() { + return name[..name.len() - suffix.len()].to_owned(); + } + } + name.to_owned() +} + +/// The name shown for a project file: the project folder's name without `.aktis` +/// ("Castle"), a format-1 file's name ("flyover.aktis.toml"), or "Untitled". +pub fn display_name(file: Option<&Path>) -> String { + let Some(file) = file else { + return "Untitled".to_owned(); + }; + if let Some(name) = root_of(file).and_then(Path::file_name) { + let name = name.to_string_lossy(); + let suffix = format!(".{FOLDER_EXTENSION}"); + return match name.to_lowercase().strip_suffix(&suffix) { + Some(stem) if !stem.is_empty() => name[..stem.len()].to_owned(), + _ => name.into_owned(), + }; + } + project_file::display_name(Some(file)) +} + +/// Writes `file` into the project folder `root`, creating the folder when it's missing. +/// Refuses a folder that exists, isn't empty and isn't a project folder (so Save As never +/// writes into an unrelated folder). Returns the project file's path. +pub fn save(root: &Path, file: &ProjectFile) -> anyhow::Result { + if root.exists() { + if !root.is_dir() { + bail!("{} exists and is not a folder", root.display()); + } + let empty = std::fs::read_dir(root) + .with_context(|| format!("can't read {}", root.display()))? + .next() + .is_none(); + if !empty && !is_project_folder(root) { + bail!( + "{} already exists and is not an Aktis project folder", + root.display() + ); + } + } else { + std::fs::create_dir_all(root) + .with_context(|| format!("can't create {}", root.display()))?; + } + let path = root.join(FILE_NAME); + file.write(&path)?; + Ok(path) +} + +/// Shrinks tightly packed RGBA8 pixels so the longest side is at most `max_side`, averaging +/// each block of source pixels (a box filter). Smaller images come back unchanged. +pub fn downscale(width: u32, height: u32, rgba: &[u8], max_side: u32) -> (u32, u32, Vec) { + let longest = width.max(height); + if longest <= max_side || width == 0 || height == 0 { + return (width, height, rgba.to_vec()); + } + let scale = f64::from(max_side) / f64::from(longest); + let tw = ((f64::from(width) * scale).round() as u32).max(1); + let th = ((f64::from(height) * scale).round() as u32).max(1); + let mut out = Vec::with_capacity((tw * th * 4) as usize); + for ty in 0..th { + let y0 = (u64::from(ty) * u64::from(height) / u64::from(th)) as u32; + let y1 = ((u64::from(ty + 1) * u64::from(height) / u64::from(th)) as u32).max(y0 + 1); + for tx in 0..tw { + let x0 = (u64::from(tx) * u64::from(width) / u64::from(tw)) as u32; + let x1 = ((u64::from(tx + 1) * u64::from(width) / u64::from(tw)) as u32).max(x0 + 1); + let mut sum = [0u64; 4]; + for y in y0..y1 { + let row = (y * width) as usize * 4; + for x in x0..x1 { + let i = row + x as usize * 4; + for (c, s) in sum.iter_mut().enumerate() { + *s += u64::from(rgba[i + c]); + } + } + } + let n = u64::from((y1 - y0) * (x1 - x0)); + out.extend(sum.iter().map(|s| ((s + n / 2) / n) as u8)); + } + } + (tw, th, out) +} + +/// Writes `thumbnail.png` into `root` from full-size RGBA8 pixels (shrunk to +/// [`THUMBNAIL_SIDE`]), through a temporary file. +pub fn write_thumbnail(root: &Path, width: u32, height: u32, rgba: &[u8]) -> anyhow::Result<()> { + let (w, h, small) = downscale(width, height, rgba, THUMBNAIL_SIDE); + let path = root.join(THUMBNAIL); + let tmp = root.join(format!("{THUMBNAIL}.tmp")); + aktis_render::export::write_png(&tmp, w, h, &small) + .with_context(|| format!("can't write {}", tmp.display()))?; + std::fs::rename(&tmp, &path).with_context(|| format!("can't write {}", path.display())) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::project_file::ProjectMode; + + fn temp(name: &str) -> PathBuf { + let dir = + std::env::temp_dir().join(format!("aktis-projectdir-{}-{name}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir + } + + #[test] + fn names_and_paths() { + let p = Path::new("/p"); + assert_eq!(folder_path(p, "Castle"), PathBuf::from("/p/Castle.aktis")); + assert_eq!( + folder_path(p, "Castle.AKTIS"), + PathBuf::from("/p/Castle.AKTIS") + ); + assert_eq!(folder_path(p, " a/b:c. "), PathBuf::from("/p/a_b_c.aktis")); + assert_eq!(folder_path(p, " "), PathBuf::from("/p/Untitled.aktis")); + assert_eq!( + folder_for_pick(Path::new("/p/Shot.aktis.toml")), + PathBuf::from("/p/Shot.aktis") + ); + assert_eq!( + folder_for_pick(Path::new("/p/Shot.toml")), + PathBuf::from("/p/Shot.aktis") + ); + assert_eq!( + folder_for_pick(Path::new("/p/Shot")), + PathBuf::from("/p/Shot.aktis") + ); + assert_eq!(display_name(None), "Untitled"); + assert_eq!( + display_name(Some(Path::new("/p/Castle.aktis/project.aktis.toml"))), + "Castle" + ); + assert_eq!( + display_name(Some(Path::new("/p/flyover.aktis.toml"))), + "flyover.aktis.toml" + ); + assert_eq!( + root_of(Path::new("/p/C.aktis/project.aktis.toml")), + Some(Path::new("/p/C.aktis")) + ); + assert_eq!(root_of(Path::new("/p/flyover.aktis.toml")), None); + } + + #[test] + fn save_locate_and_legacy_folders() { + let dir = temp("save"); + let root = dir.join("Castle.aktis"); + let file = ProjectFile { + mode: ProjectMode::Image, + ..ProjectFile::default() + }; + let path = save(&root, &file).unwrap(); + assert_eq!(path, root.join(FILE_NAME)); + assert_eq!(ProjectFile::read(&path).unwrap(), file.clone().normalized()); + assert_eq!(locate(&root).unwrap(), Location::Folder(root.clone())); + assert_eq!(locate(&path).unwrap(), Location::Folder(root.clone())); + // Saving again into an existing project folder is fine. + save(&root, &file).unwrap(); + + // A non-empty folder that isn't a project is refused, by Save and by Open. + let other = dir.join("Other.aktis"); + std::fs::create_dir_all(&other).unwrap(); + std::fs::write(other.join("notes.txt"), "mine").unwrap(); + assert!(save(&other, &file).is_err()); + assert!(locate(&other).is_err()); + assert!(locate(&dir.join("missing")).is_err()); + + // A format-1 file opens as legacy and is saved as a folder beside it. + let legacy = dir.join("flyover.aktis.toml"); + std::fs::write(&legacy, "[project]\nformat = 1\n").unwrap(); + assert_eq!(locate(&legacy).unwrap(), Location::Legacy(legacy.clone())); + assert_eq!(folder_for_legacy(&legacy), dir.join("flyover.aktis")); + let other_legacy = dir.join("Other.aktis.toml"); + assert_eq!( + folder_for_legacy(&other_legacy), + dir.join("Other 2.aktis"), + "taken by a non-project folder" + ); + assert_eq!( + folder_for_legacy(&dir.join("Castle.aktis.toml")), + root, + "an existing project folder is reused" + ); + std::fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn thumbnails_are_box_filtered() { + // 4×2 → longest side 2: each output pixel averages a 2×2 block. + let mut rgba = Vec::new(); + for y in 0..2u8 { + for x in 0..4u8 { + rgba.extend([x * 10, y * 100, 0, 255]); + } + } + let (w, h, small) = downscale(4, 2, &rgba, 2); + assert_eq!((w, h), (2, 1)); + assert_eq!(small, [5, 50, 0, 255, 25, 50, 0, 255]); + let (w, h, same) = downscale(4, 2, &rgba, 512); + assert_eq!((w, h, same), (4, 2, rgba.clone())); + + let dir = temp("thumb"); + write_thumbnail(&dir, 4, 2, &rgba).unwrap(); + assert!(dir.join(THUMBNAIL).is_file()); + assert!(!dir.join(format!("{THUMBNAIL}.tmp")).exists()); + std::fs::remove_dir_all(&dir).unwrap(); + } +} diff --git a/crates/aktis-app/src/project_file.rs b/crates/aktis-app/src/project_file.rs index 2087274..9e7689b 100644 --- a/crates/aktis-app/src/project_file.rs +++ b/crates/aktis-app/src/project_file.rs @@ -1,6 +1,8 @@ -//! Project files (`.aktis.toml`): everything a render needs (world, packs, engine, -//! scene, timeline, output) in one TOML file. Format: `docs/subsystems/scene.md` → -//! "Project file"; behaviour: `docs/subsystems/app.md` → "Project files". +//! Project files (`project.aktis.toml` in a project folder, or a format-1 +//! `.aktis.toml`): everything a render needs (mode, canvas, world, packs, engine, +//! scene, and the timeline and output of a Video project or the views of an Image project) +//! in one TOML file. Format: `docs/subsystems/scene.md` → "Project file" and "Project +//! format 2"; behaviour: `docs/subsystems/app.md` → "Project files". use std::path::{Path, PathBuf}; @@ -11,16 +13,70 @@ use anyhow::Context; use serde::{Deserialize, Serialize}; use crate::loader::LoadRequest; -use crate::output::OutputSettings; +use crate::output::{OutputFormat, OutputSettings}; use crate::project::{SelectionSettings, WORLD_MAX_Y, WORLD_MIN_Y}; use crate::pt_panel::{BOUNCE_RANGE, SPP_RANGE}; use aktis_assets::{DEFAULT_MAX_TEXTURE_SIZE, clamp_texture_size_cap}; /// Current format version (`[project] format`). -pub const FORMAT: u32 = 1; +pub const FORMAT: u32 = 2; /// File extension, without the leading dot. pub const EXTENSION: &str = "aktis.toml"; +/// What a project makes; fixed when it's created (ADR 0022). +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum ProjectMode { + /// Stills: views and a render history, no timeline. + Image, + /// Animations: timeline, playback, render queue and video output. + #[default] + Video, +} + +impl ProjectMode { + /// Reads a `mode` value; `None` for anything else. + pub fn parse(s: &str) -> Option { + match s { + "image" => Some(Self::Image), + "video" => Some(Self::Video), + _ => None, + } + } +} + +/// `[[views]]`: a saved camera position in an Image project. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct View { + /// Name shown in the list. + pub name: String, + /// Camera position in block coordinates. + pub position: glam::Vec3, + /// Yaw in degrees. + pub yaw: f32, + /// Pitch in degrees. + pub pitch: f32, + /// Roll in degrees. + pub roll: f32, + /// Vertical field of view in degrees. + pub fov_y: f32, +} + +impl Default for View { + fn default() -> Self { + let camera = aktis_scene::Camera::default(); + Self { + name: String::new(), + position: camera.position, + yaw: camera.yaw, + pitch: camera.pitch, + roll: camera.roll, + fov_y: camera.fov_y, + } + } +} + /// The engine shown in the viewport. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] pub enum EngineChoice { @@ -41,6 +97,39 @@ pub struct Header { pub format: u32, } +/// `[project]` as read: a missing `format` is format 1; `mode` is checked by hand so an +/// unknown value only warns. +#[derive(Default, Deserialize)] +#[serde(default)] +struct RawHeader { + format: Option, + mode: Option, +} + +/// `[project]` as written. +#[derive(Serialize)] +struct HeaderOut { + format: u32, + mode: ProjectMode, +} + +/// `[canvas]`. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +struct Canvas { + width: u32, + height: u32, +} + +/// `[output]` as written in format 2: the size moved to `[canvas]`. +#[derive(Serialize)] +struct OutputOut<'a> { + format: OutputFormat, + quality: u32, + #[serde(skip_serializing_if = "Option::is_none")] + path: &'a Option, + keep_frames: bool, +} + impl Default for Header { fn default() -> Self { Self { format: FORMAT } @@ -166,6 +255,8 @@ impl Default for EngineSection { pub struct ProjectFile { /// `[project]`. pub header: Header, + /// `[project] mode`. + pub mode: ProjectMode, /// `[world]`. pub world: WorldSection, /// `[packs]`. @@ -174,17 +265,22 @@ pub struct ProjectFile { pub engine: EngineSection, /// The base scene: `[camera]`, `[sun]`, `[sky]`, `[fog]` at the top level. pub scene: Scene, - /// `[timeline]`. + /// `[timeline]` (Video projects; default in Image projects). pub timeline: Timeline, - /// `[output]`. + /// `[output]`; its width and height are the `[canvas]`. Image projects keep only the + /// size (the rest is default). pub output: OutputSettings, + /// `[[views]]` (Image projects; empty in Video projects). + pub views: Vec, } /// Reading form: the scene tables sit at the top level. #[derive(Default, Deserialize)] #[serde(default)] struct RawFile { - project: Header, + project: RawHeader, + canvas: Option, + views: Vec, world: WorldSection, packs: PacksSection, engine: EngineSection, @@ -197,7 +293,8 @@ struct RawFile { /// Writing form of everything before `[timeline]`. #[derive(Serialize)] struct Head<'a> { - project: &'a Header, + project: HeaderOut, + canvas: Canvas, world: &'a WorldSection, packs: &'a PacksSection, engine: &'a EngineSection, @@ -205,10 +302,21 @@ struct Head<'a> { scene: &'a Scene, } -/// Writing form of everything after `[timeline]`. +/// Writing form of a Video project's `[output]`. +#[derive(Serialize)] +struct VideoTail<'a> { + output: OutputOut<'a>, +} + +/// Writing form of an Image project's views. #[derive(Serialize)] -struct Tail<'a> { - output: &'a OutputSettings, +struct ImageTail<'a> { + views: &'a [View], +} + +/// Whether any track of `timeline` has a key. +fn has_keys(timeline: &Timeline) -> bool { + timeline.tracks.iter().any(|t| !t.keys.is_empty()) } fn non_empty(p: Option) -> Option { @@ -219,13 +327,55 @@ impl ProjectFile { /// Parses a project file. Missing tables and fields take their defaults; empty paths /// read as none; out-of-range values are clamped. pub fn from_toml(text: &str) -> Result { + Self::parse(text, None) + } + + /// Parses a render-queue job's snapshot: like [`Self::from_toml`], but a format-1 + /// snapshot is always a Video project, so a job without keys keeps its output + /// settings (jobs are written as Video projects, see [`Self::for_job`]). + pub fn from_job_toml(text: &str) -> Result { + Self::parse(text, Some(ProjectMode::Video)) + } + + /// This project as a render-queue snapshot: a Video project with everything kept (a + /// job renders the timeline and writes the output, whatever the editor's mode). + pub fn for_job(mut self) -> Self { + self.mode = ProjectMode::Video; + self.views.clear(); + self + } + + /// `legacy_mode`: the mode of a format-1 file; `None` = decide by its keys. + fn parse(text: &str, legacy_mode: Option) -> Result { let raw: RawFile = toml::from_str(text)?; - if raw.project.format > FORMAT { + // A file without `[project] format` is from before format 2 had one to miss. + let format = raw.project.format.unwrap_or(1); + if format > FORMAT { log::warn!( - "project format {} is newer than this build's {FORMAT}; unknown parts are skipped", - raw.project.format + "project format {format} is newer than this build's {FORMAT}; unknown parts are skipped" ); } + let mode = if format < 2 { + // Format 1 had no mode: an animation if it has keys, else a still. + if let Some(mode) = legacy_mode { + mode + } else if has_keys(&raw.timeline) { + ProjectMode::Video + } else { + ProjectMode::Image + } + } else { + match raw.project.mode.as_deref().map(ProjectMode::parse) { + Some(Some(mode)) => mode, + _ => { + log::warn!( + "project mode {:?} isn't image or video; opening as video", + raw.project.mode + ); + ProjectMode::Video + } + } + }; let mut world = raw.world; world.game_folder = non_empty(world.game_folder); world.jar = non_empty(world.jar); @@ -237,8 +387,27 @@ impl ProjectFile { engine.spp = engine.spp.clamp(SPP_RANGE.0, SPP_RANGE.1); engine.bounces = engine.bounces.clamp(BOUNCE_RANGE.0, BOUNCE_RANGE.1); engine.shader_pack = non_empty(engine.shader_pack); + let mut output = raw.output; + if format >= 2 + && let Some(canvas) = raw.canvas + { + output.width = canvas.width; + output.height = canvas.height; + } + let (timeline, output, views) = match mode { + ProjectMode::Video => (raw.timeline, output.clamped(), Vec::new()), + ProjectMode::Image => { + let canvas = OutputSettings { + width: output.width, + height: output.height, + ..OutputSettings::default() + }; + (Timeline::default(), canvas.clamped_for(mode), raw.views) + } + }; Ok(Self { header: Header { format: FORMAT }, + mode, world, packs: PacksSection { enabled: raw @@ -250,29 +419,71 @@ impl ProjectFile { }, engine, scene: raw.scene, - timeline: raw.timeline, - output: raw.output.clamped(), + timeline, + output, + views, }) } + /// The file as it would read back: an Image project drops its timeline and every + /// output setting but the size, a Video project its views. The app compares projects in + /// this form, so what a project's mode doesn't keep never counts as a change. + pub fn normalized(mut self) -> Self { + match self.mode { + ProjectMode::Video => self.views.clear(), + ProjectMode::Image => { + self.timeline = Timeline::default(); + self.output = OutputSettings { + width: self.output.width, + height: self.output.height, + ..OutputSettings::default() + }; + } + } + self.output = self.output.clamped_for(self.mode); + self + } + /// Writes the file: sections in the documented order, keys one per line. pub fn to_toml(&self) -> Result { let head = toml::to_string_pretty(&Head { - project: &self.header, + project: HeaderOut { + format: FORMAT, + mode: self.mode, + }, + canvas: Canvas { + width: self.output.width, + height: self.output.height, + }, world: &self.world, packs: &self.packs, engine: &self.engine, scene: &self.scene, })?; - let tail = toml::to_string_pretty(&Tail { - output: &self.output, - })?; - Ok(format!( - "{}\n\n{}\n{}", - head.trim_end(), - self.timeline.to_toml_section(), - tail.trim_end() - ) + "\n") + let body = match self.mode { + ProjectMode::Video => { + let tail = toml::to_string_pretty(&VideoTail { + output: OutputOut { + format: self.output.format, + quality: self.output.quality, + path: &self.output.path, + keep_frames: self.output.keep_frames, + }, + })?; + format!( + "{}\n\n{}\n{}", + head.trim_end(), + self.timeline.to_toml_section(), + tail.trim_end() + ) + } + ProjectMode::Image if self.views.is_empty() => head.trim_end().to_owned(), + ProjectMode::Image => { + let tail = toml::to_string_pretty(&ImageTail { views: &self.views })?; + format!("{}\n\n{}", head.trim_end(), tail.trim_end()) + } + }; + Ok(body + "\n") } /// Reads and parses `path`. @@ -326,24 +537,6 @@ impl ProjectFile { } } -/// `path` with `.aktis.toml` added unless it already ends in it (any case). -pub fn with_extension(path: PathBuf) -> PathBuf { - let lower = path.to_string_lossy().to_lowercase(); - if lower.ends_with(&format!(".{EXTENSION}")) { - path - } else { - let mut s = path.into_os_string(); - // "flyover.toml" → "flyover.aktis.toml" rather than "flyover.toml.aktis.toml". - if lower.ends_with(".toml") { - let trimmed = s.to_string_lossy(); - let stem = trimmed[..trimmed.len() - ".toml".len()].to_owned(); - s = stem.into(); - } - s.push(format!(".{EXTENSION}")); - PathBuf::from(s) - } -} - /// The file name shown in the title bar: `flyover.aktis.toml`, or "Untitled". pub fn display_name(path: Option<&Path>) -> String { path.and_then(Path::file_name).map_or_else( diff --git a/crates/aktis-app/src/project_file/tests.rs b/crates/aktis-app/src/project_file/tests.rs index 25a3cb7..a8ab2f6 100644 --- a/crates/aktis-app/src/project_file/tests.rs +++ b/crates/aktis-app/src/project_file/tests.rs @@ -38,6 +38,7 @@ fn full() -> ProjectFile { }); ProjectFile { header: Header::default(), + mode: ProjectMode::Video, world: WorldSection { game_folder: Some(PathBuf::from("/games/26.3/minecraft")), jar: Some(PathBuf::from("/games/libraries/minecraft-26.3-client.jar")), @@ -73,9 +74,37 @@ fn full() -> ProjectFile { path: Some(PathBuf::from("/movies/flyover.mp4")), keep_frames: true, }, + views: Vec::new(), } } +/// An Image project with views and an odd canvas. +fn image() -> ProjectFile { + let mut f = full(); + f.mode = ProjectMode::Image; + f.timeline = Timeline::default(); + f.output = OutputSettings { + width: 2481, + height: 3507, + ..OutputSettings::default() + }; + f.views = vec![ + View { + name: "Gate".to_owned(), + position: Vec3::new(10.0, 80.0, 10.0), + yaw: 45.0, + pitch: -10.0, + roll: 2.0, + fov_y: 50.0, + }, + View { + name: "Tower".to_owned(), + ..View::default() + }, + ]; + f +} + #[test] fn every_section_round_trips() { let file = full(); @@ -84,6 +113,7 @@ fn every_section_round_trips() { // Sections in the documented order, keys one per line. let order: Vec = [ "[project]", + "[canvas]", "[world]", "[packs]", "[engine]", @@ -102,7 +132,14 @@ fn every_section_round_trips() { .collect(); assert!(order.windows(2).all(|w| w[0] < w[1]), "{text}"); assert!(text.contains("interp = \"smooth\" },"), "{text}"); - assert!(text.contains("format = 1"), "{text}"); + assert!(text.contains("format = 2"), "{text}"); + assert!(text.contains("mode = \"video\""), "{text}"); + assert!( + text.contains("[canvas]\nwidth = 2560\nheight = 1440"), + "{text}" + ); + let output = &text[text.find("[output]").unwrap()..]; + assert!(!output.contains("width"), "the size is in [canvas]: {text}"); assert!(text.contains("kind = \"ShaderPack\""), "{text}"); assert!(text.contains("format = \"mp4_h265\""), "{text}"); // Defaults round trip too, and leave optional paths out. @@ -115,6 +152,96 @@ fn every_section_round_trips() { ); } +#[test] +fn image_projects_round_trip_and_keep_only_stills() { + let file = image(); + let text = file.to_toml().unwrap(); + assert_eq!(ProjectFile::from_toml(&text).unwrap(), file, "{text}"); + assert!(text.contains("mode = \"image\""), "{text}"); + assert!(text.contains("width = 2481"), "odd sides stay: {text}"); + assert!(text.contains("[[views]]"), "{text}"); + assert!( + !text.contains("[timeline]") && !text.contains("[output]"), + "{text}" + ); + // What an Image project doesn't keep is dropped by `normalized`, as by a write. + let mut busy = image(); + busy.timeline = full().timeline; + busy.output.format = OutputFormat::MovProres; + assert_eq!(busy.clone().normalized(), file); + assert_eq!( + ProjectFile::from_toml(&busy.to_toml().unwrap()).unwrap(), + file + ); + // And a Video project drops views. + let mut video = full(); + video.views = image().views; + assert_eq!(video.normalized(), full()); +} + +#[test] +fn format_one_files_migrate() { + // With keys: a Video project, the canvas from [output]. + let mut v1 = full().to_toml().unwrap(); + v1 = v1 + .replace("format = 2\nmode = \"video\"", "format = 1") + .replace("[canvas]\nwidth = 2560\nheight = 1440\n", "") + .replace("[output]\n", "[output]\nwidth = 2560\nheight = 1440\n"); + assert!(!v1.contains("[canvas]") && !v1.contains("mode"), "{v1}"); + assert_eq!(ProjectFile::from_toml(&v1).unwrap(), full(), "{v1}"); + + // Without keys: an Image project keeping the size (even then, as format 1 wrote it). + let still = "[project]\nformat = 1\n[timeline]\nfps = 24\n[output]\nwidth = 1280\nheight = 720\nformat = \"png\"\npath = \"/out\"\n"; + let f = ProjectFile::from_toml(still).unwrap(); + assert_eq!(f.mode, ProjectMode::Image); + assert_eq!(f.output.size(), (1280, 720)); + assert_eq!(f.output.path, None, "Image projects keep only the size"); + assert_eq!(f.timeline, Timeline::default()); + + // No [project] at all reads as format 1. + let f = ProjectFile::from_toml("[output]\nwidth = 640\nheight = 480\n").unwrap(); + assert_eq!((f.mode, f.output.size()), (ProjectMode::Image, (640, 480))); + + // Format 2: a missing or unknown mode opens as video; a missing [canvas] falls back + // to [output]'s size. + for head in [ + "[project]\nformat = 2\n", + "[project]\nformat = 2\nmode = \"film\"\n", + ] { + let f = ProjectFile::from_toml(&format!("{head}[output]\nwidth = 800\nheight = 600\n")) + .unwrap(); + assert_eq!( + (f.mode, f.output.size()), + (ProjectMode::Video, (800, 600)), + "{head}" + ); + } + let f = ProjectFile::from_toml( + "[project]\nformat = 2\nmode = \"image\"\n[canvas]\nwidth = 3\nheight = 99999\n", + ) + .unwrap(); + assert_eq!(f.output.size(), (16, 16384), "clamped"); +} + +#[test] +fn job_snapshots_stay_video() { + // A 0.1.0 queued animation without keys keeps its output settings. + let old = "[project]\nformat = 1\n[output]\nwidth = 1280\nheight = 720\nformat = \"png\"\npath = \"/out\"\n"; + let f = ProjectFile::from_job_toml(old).unwrap(); + assert_eq!(f.mode, ProjectMode::Video); + assert_eq!( + (f.output.format, f.output.path), + (OutputFormat::Png, Some(PathBuf::from("/out"))) + ); + // An Image project's snapshot keeps its timeline for the job. + let mut busy = image(); + busy.timeline = full().timeline; + let job = busy.clone().for_job(); + let back = ProjectFile::from_job_toml(&job.to_toml().unwrap()).unwrap(); + assert_eq!(back.timeline, busy.timeline); + assert!(back.views.is_empty()); +} + #[test] fn reads_the_documented_example() { // The example in scene.md → "Project file", with its comments. @@ -277,18 +404,7 @@ fn write_then_read() { } #[test] -fn extension_and_names() { - let p = |s: &str| with_extension(PathBuf::from(s)); - assert_eq!(p("/a/flyover"), PathBuf::from("/a/flyover.aktis.toml")); - assert_eq!( - p("/a/flyover.aktis.toml"), - PathBuf::from("/a/flyover.aktis.toml") - ); - assert_eq!( - p("/a/flyover.AKTIS.TOML"), - PathBuf::from("/a/flyover.AKTIS.TOML") - ); - assert_eq!(p("/a/flyover.toml"), PathBuf::from("/a/flyover.aktis.toml")); +fn display_names() { assert_eq!(display_name(None), "Untitled"); assert_eq!( display_name(Some(Path::new("/a/flyover.aktis.toml"))), diff --git a/crates/aktis-app/src/queue.rs b/crates/aktis-app/src/queue.rs index 88bc690..4a2ad13 100644 --- a/crates/aktis-app/src/queue.rs +++ b/crates/aktis-app/src/queue.rs @@ -106,7 +106,7 @@ pub struct QueuedJob { impl QueuedJob { /// The snapshot as a project. pub fn project(&self) -> Result { - ProjectFile::from_toml(&self.project).map_err(|e| format!("broken job snapshot: {e}")) + ProjectFile::from_job_toml(&self.project).map_err(|e| format!("broken job snapshot: {e}")) } /// What the next run renders, at most `max_dimension` pixels per side. diff --git a/crates/aktis-app/src/recent.rs b/crates/aktis-app/src/recent.rs new file mode 100644 index 0000000..320fbd5 --- /dev/null +++ b/crates/aktis-app/src/recent.rs @@ -0,0 +1,178 @@ +//! Recent projects and the Minecraft library, kept in the app's saved state (M9, ADR 0022). +//! The Home screen (task 4) shows the list; it's cached here so Home doesn't read every +//! project file. See `docs/subsystems/app.md` → "Saved state". + +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +use serde::{Deserialize, Serialize}; + +use crate::packs::PackChoice; +use crate::project_dir; +use crate::project_file::{ProjectFile, ProjectMode}; +use crate::shader_pack::SavedShaderPacks; + +/// Most projects kept in the list. +pub const MAX_RECENT: usize = 50; + +/// One recently opened or saved project, as Home shows it. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct RecentProject { + /// The project folder, or a format-1 file. + pub path: PathBuf, + /// Shown name ("Castle"). + pub name: String, + /// Image or Video. + pub mode: ProjectMode, + /// Canvas width × height in pixels. + pub canvas: (u32, u32), + /// Video: frames per second. + pub fps: Option, + /// Video: duration in seconds. + pub duration: Option, + /// The world's save folder name, if the project names one. + pub world: Option, + /// Last opened or saved, in seconds since the Unix epoch. + pub opened: u64, +} + +impl Default for RecentProject { + fn default() -> Self { + Self { + path: PathBuf::new(), + name: String::new(), + mode: ProjectMode::default(), + canvas: (0, 0), + fps: None, + duration: None, + world: None, + opened: 0, + } + } +} + +impl RecentProject { + /// The entry for `project` read from or written to the project file `file`, at `opened`. + pub fn new(file: &Path, project: &ProjectFile, opened: u64) -> Self { + let path = project_dir::root_of(file).unwrap_or(file).to_owned(); + let video = project.mode == ProjectMode::Video; + Self { + path, + name: project_dir::display_name(Some(file)), + mode: project.mode, + canvas: project.output.size(), + fps: video.then_some(project.timeline.fps), + duration: video.then_some(project.timeline.duration), + world: project + .world + .save + .as_deref() + .and_then(Path::file_name) + .map(|n| n.to_string_lossy().into_owned()), + opened, + } + } +} + +/// The recent-projects list, most recent first, one entry per path. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct Recents { + /// Entries, most recent first. + pub list: Vec, +} + +impl Recents { + /// Puts `entry` first, replacing an older entry for the same path; keeps at most + /// [`MAX_RECENT`]. + pub fn touch(&mut self, entry: RecentProject) { + self.list.retain(|e| e.path != entry.path); + self.list.insert(0, entry); + self.list.truncate(MAX_RECENT); + } +} + +/// Seconds since the Unix epoch now (0 if the clock is before it). +pub fn now() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_secs()) +} + +/// App-wide Minecraft settings, shared by every project: install folders added by hand and, +/// per game folder, the resource and shader packs offered. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct Library { + /// Install folders added with "Add folder…". + pub extra_dirs: Vec, + /// Resource packs per game folder. + pub packs: BTreeMap, + /// Shader packs per game folder. + pub shader_packs: SavedShaderPacks, +} + +#[cfg(test)] +mod tests { + use super::*; + use aktis_scene::timeline::{Interp, Key, Property, Value}; + + fn entry(path: &str, opened: u64) -> RecentProject { + RecentProject { + path: PathBuf::from(path), + opened, + ..RecentProject::default() + } + } + + #[test] + fn touch_orders_dedups_and_caps() { + let mut r = Recents::default(); + r.touch(entry("/a.aktis", 1)); + r.touch(entry("/b.aktis", 2)); + r.touch(entry("/a.aktis", 3)); + let paths: Vec<_> = r.list.iter().map(|e| e.path.clone()).collect(); + assert_eq!( + paths, + [PathBuf::from("/a.aktis"), PathBuf::from("/b.aktis")] + ); + assert_eq!(r.list[0].opened, 3); + for i in 0..60 { + r.touch(entry(&format!("/p{i}.aktis"), 10 + i)); + } + assert_eq!(r.list.len(), MAX_RECENT); + assert_eq!(r.list[0].path, PathBuf::from("/p59.aktis")); + } + + #[test] + fn entries_describe_the_project() { + let mut video = ProjectFile::default(); + video.world.save = Some(PathBuf::from("/saves/Test")); + video.timeline.fps = 60; + video + .timeline + .track_mut(Property::SunAltitude) + .set_key(Key { + time: 1.0, + value: Value::Scalar(1.0), + interp: Interp::Linear, + }); + let e = RecentProject::new(Path::new("/p/Castle.aktis/project.aktis.toml"), &video, 7); + assert_eq!(e.path, PathBuf::from("/p/Castle.aktis")); + assert_eq!(e.name, "Castle"); + assert_eq!( + (e.mode, e.canvas, e.fps), + (ProjectMode::Video, (1920, 1080), Some(60)) + ); + assert_eq!(e.world.as_deref(), Some("Test")); + + let image = ProjectFile { + mode: ProjectMode::Image, + ..ProjectFile::default() + }; + let e = RecentProject::new(Path::new("/p/old.aktis.toml"), &image, 7); + assert_eq!(e.path, PathBuf::from("/p/old.aktis.toml")); + assert_eq!((e.fps, e.duration, e.world), (None, None, None)); + } +} diff --git a/docs/dev/testing.md b/docs/dev/testing.md index 76df798..03a4498 100644 --- a/docs/dev/testing.md +++ b/docs/dev/testing.md @@ -311,7 +311,7 @@ none is found**, logging that they were skipped. | aktis-pt | Quad grid on handmade quads (labelled by layer): empty mesh; single-cube layout (cells, list entries, grid min); every cube face from outside (t, parallelogram coordinates, UV); UV mapping; back faces only with `Faces::Both`, front-only rays pass through back faces; slab; rotated cross plane from both sides; coplanar overlay wins unless the accept callback rejects it; pass order breaks ties; ray along a shared edge; far-away rays across empty bricks; `t_min`/`t_max`; packing round trips; degenerate quads; 3 000 random rays (axis-aligned, from outside, front/both, alpha holes) match brute force; sky (clear sky blue, circumsolar brightening, horizon brighter/whiter than the sky above it, below-horizon directions, night and twilight, low sun dimmer and redder, overhead sun ≈ π, haze, sun disk energy, sky/sun ratio); colour pipeline (ACES bounds/monotonic, sRGB round trip, exposure, emission = max(level, map)); BRDF (default texel = exact Lambert, texel → material, conductor Fresnel against the spec's F0 and at grazing, reciprocity, white-furnace energy ≤ 1, pdf matches the samples, mirror sampling, MIS weights); normal mapping (tangent frames for plain, rotated, mirrored, partial and degenerate UVs; DirectX map axes; back faces; normals facing away from the viewer; meshed faces' frames, no GPU needed); WGSL shader validates with naga; dispatch bands stay within the pixel budget; frame uniform size. GPU: a block display turned 90° renders pixel for pixel like the same block placed with blockstate `y: 90` (with a control showing the unturned block differs); albedo view matches the preview | Far terrain (`far`, M8 task 7): the walk over groups, chunks and cells finds the same nearest hit as testing every column box and water plane, for 800 random rays over a generated ring with two levels, water, empty columns and missing chunks; hits carry the face, colour and water (from above and below; `t_max`, the sky). GPU (`pt_gpu.rs`): `far_terrain_albedo_matches_the_preview` (a generated far ring with water, two views, ≤ 3 % of pixels may differ; 0.05 % do; `AKTIS_TEST_PNG_DIR` saves both) and `far_terrain_shades_the_detail_area` (a 60-block far wall round a floor shadows it from a low sun). `pt_real.rs` takes `AKTIS_TEST_FAR` (far radius for both engines and the timings). | aktis-scene | TOML round-trip; defaults for missing fields (incl. `camera.exposure`, `sun.angular_diameter`, `sky.turbidity`, `camera.roll` in old files); camera forward/right and sun direction conventions; rolled camera basis; default camera looks slightly down. Timeline: every mode hits its keys and holds outside them, midpoints per mode (two `smooth` keys = `ease`), `smooth` never overshoots and stays monotone, no kink at inner keys, angles take the shorter way (unwrapping over several keys, exact 180°, roll/azimuth normalised, pitch not wrapped), disabled/empty tracks, per-component vectors, `set_key`; camera path through keys with holds, `step` and `linear` segments, a smooth corner bulging outward with continuous speed, uneven keys make no loops (fails with uniform Catmull-Rom), constant speed gives equal steps, smooth timing never runs backwards; Look at angles and the camera's forward through the timeline, too-close fallback; frame range excludes `out`; `Track::value_at` matches evaluation; property paths; TOML round trip, the compact `[timeline]` writer reads back equal (shortest floats, empty tracks), the documented example with file clean-up, bad settings fall back, a range missing from TOML covers the whole length; RON round trip (`in`/`out` as plain numbers, as eframe stores the timeline) | | aktis-render | Entity meshing on a handmade pack (paintings: box, orientation, front UVs, unknown variants; item frames: wall placement for each facing, glow/map/invisible variants, framed item position, size, tint and 45° rotation, special-renderer items; block displays: identity equals the placed block, flips, mirroring keeps faces outward, yaw; item displays centred and turned; display light; billboards counted; new sections stay sorted); Packs stacked with `AssetStack::open` override a texture, a model and a blockstate in priority order in the mesh; PNG export (round trip, wrong buffer size, missing folder); Frame clock (still, animation times, `follows`, fps clamp); Camera rig (eye relative to origin, centre ray = forward, every primary ray projects back onto its pixel, aspect, behind-camera, zero size); Meshing on a handmade pack: face counts (single cube, neighbours, section borders, slabs, glass/glass and glass/stone), pass split, tint/shade/emission in vertices, block-state light levels in vertices (glowstone 15, lit/unlit furnace 13/0 over a dimmer model element, model-only emission kept), selection edges, unknown blocks; block light table (always-lit blocks, `lit` on/off/missing, candle counts, sea pickles in and out of water, respawn anchor charges, light block, cave vines); fluids (water box height and tint, culling against water/stone, waterlogged blocks, glowing opaque lava, level → height, face winding; corner heights: the averaging rule, a slope from a source down a flowing line with no cracks between neighbours, a level sea with a covered column lifting its corners to 1 and no top under it, sloped faces following their corners and still facing out); 16-byte vertex round trip; quad index pattern; tint table. GPU: preview render + readback; a coplanar alpha-tested face covers the face below; the camera-path overlay (line over the sky, hidden behind a block, key dots with the highlight colour, gone once cleared); mesh byte counts equal exactly the vertices and quad origins of a one-cube mesh (meshing leaves no growth slack) | Far-terrain colours (`lod`, M8 task 5): a handmade pack checks the topmost up face (a smaller element above a base), linear averaging (half black, half white = 0.5), alpha coverage (a mostly transparent texture), the grass tint, a model without an up face, an always-waterlogged plant and water (plains blue), snowy states (snow texture, or the constant without one), grey for missing models and textures; sRGB conversion. Opt-in `tests/lod_palette_real.rs` (`AKTIS_TEST_CLIENT_JAR` + `AKTIS_TEST_WORLD`, `AKTIS_TEST_FAR` default 32): prints the palette of a real save's far terrain by share of columns and the far mesh's quads and bytes per column (the estimate's input) and checks grass, water, sand, stone and snowy colours and that under 0.1 % of columns are grey. Far-terrain mesh (`lod::mesh`, M8 task 6): a flat chunk is one top per row with walls round it, walls go down only to the lowest neighbour (between chunks, and a coarse cell next to a dip in a finer chunk), water has an opaque floor, a translucent surface and sides (surface flag on the top edge only), tiles are regions (offsets, positions at the tile's far edge), every quad wound counter-clockwise from its direction. GPU (`preview_gpu.rs` → `far_terrain_meets_the_detail_area_without_a_gap`): a flat detail area inside a higher far ring, seen from inside: sky above the projected far top, no sky below it, the far wall above the horizon and the detail ground below (`AKTIS_TEST_PNG_DIR` saves `preview_far_edge.png`). `preview_real.rs` takes `AKTIS_TEST_FAR` (far radius) and `AKTIS_TEST_CAMERA` (`x,y,z,yaw,pitch`). -| aktis-app | Command-line parsing (flags, `=` form, `--pack` order, errors, help); fly camera (movement directions, sprint, diagonal speed, look clamping, scroll speed range); viewport pixel size; viewport scheduling (preview re-renders only on change, one-shot engines, progressive accumulation with reset, preview while moving, holding still, returning to the same view, invalidate, paused engine keeps its image / shows the preview after a camera move); path-tracer panel (saved settings round trip incl. every view and PBR off, clamping and missing fields (PBR defaults to on), PBR hover text, render clock ignores frames without new samples and restarts on reset, progress text); frame-rate readout; selection clamping and chunk count; load request only with an existing instance, client jar and `level.dat`, with the instance's packs lowest priority first and the clamped texture size; old saved settings get the default texture size; loader block reuse (same-blocks check; a rebuild with a pack equals meshing from scratch, switching back gives the first mesh, the save isn't opened; without reuse the save is read); pack list (enable on top, moves, disable, available = `resourcepacks/` + added without enabled ones, forget, saved form with missing fields, missing pack details); overview camera; export file names (file-safe, sample count, `.png` added once). Project files: every section round-trips in the documented order with one line per key, defaults leave optional paths out, the documented example (empty shader pack = none, missing tables default), clamping of hand-edited values and a newer format, the load request names a missing jar or world and orders packs lowest priority first, write then read through a temporary file, `.aktis.toml` naming, timeline and output survive the session's serde; the whole saved state (`Saved`, default and with a keyed timeline and the Shader Pack engine) reads back from RON exactly as eframe writes it; `ProjectPanel::set_choices` (normalised selection, packs outside `resourcepacks/` added once); file stems and the untitled unsaved-work rule. Timeline editing (`animate`): edits auto-key with the stopwatch on (snapped to the playhead's frame) and change the base otherwise, an enabled track without keys still auto-keys, a disabled track edits the base, re-keying keeps the mode, the fly camera never keys (no camera tracks: base; position keyed: override, yaw to the base; flying back clears it; Look at: turning goes to the override), Key camera (position/yaw/pitch, stopwatches on, position only with Look at), stopwatches on/off (Look at 16 blocks ahead, base keeps the shown value), key navigation and ◆, time format and snapping; key editing: drags snap the grabbed key to frames (free with Alt) and stop at 0, moved keys keep values and replace what they land on (the start state untouched), delete keeps the stopwatch, mode change, copy through clipboard text and paste at the playhead's frame with offsets and modes kept (stopwatch on for new tracks, other text ignored). Undo history (`history`): a drag is one step (nothing recorded while the button is held), undo/redo walk scene and timeline steps to the ends, a new edit clears redo (already before it's recorded), an unrecorded edit is what Undo undoes, only the last 100 steps are kept, fly-camera moves are never steps, reset forgets everything. Playback (`playback`): Play starts at the playhead or at in (before in, at out, on the last frame; an empty range doesn't play), advancing follows the wall clock and drops frames (stalls capped), stops on the last frame without Loop and wraps to in with it, toggle and seek, the clock is the playhead's frame, the overlay samples one point per frame between the first and last position key with the playhead's key highlighted (none without an active track). Viewport: playback keeps the path tracer behind the preview until it stops, a new frame clock or overlay renders the preview again, frame guide rectangles (landscape, portrait, same aspect). Orbit helper (`orbit`): keys on the circle at the height (16 per turn, angle 0 south, even times), turns and direction (clockwise = west after a quarter turn, counter-clockwise = east, key counts, a fractional turn ends on its angle), defaults start at the camera (radius floor), smooth constant-speed keys and a Look at key that keeps the camera on the centre, the sampled path within 1.3 % of the circle (0.1 % away from the ends), keys in the range replaced and others kept, the timeline grows (out follows only from the end), invalid values change nothing. Output (`output`): even sides in range, fitting to the GPU limit keeps the aspect, presets are even; viewport `display` fits output images and flags scaling. Render jobs (`job`): frame names (from 1, at least 4 digits, more for long jobs), paths per target, existing files found and skipped on resume, time left, labels and durations. Job runner (`job_runner`, GPU, skips without an adapter): every frame written as a numbered PNG of the output size with the preview and the path tracer (its settings restored afterwards), Pause finishes the frame and holds, Resume, Cancel keeps written frames, a write error fails the job, a resume renders only missing frames (no `.part` files left). Render queue (`queue`): a job is a snapshot (later edits don't reach it; engine, spp, frames, size), stills render their frame and Replace turns skipping off, resume skips frames on disk, the saved queue round-trips (serde) and running jobs come back Interrupted with fresh ids after them, reorder/duplicate/remove/run again/clear finished (the running job stays put), a job loads its world only when world, selection, packs or texture cap differ, Encode again only for finished video jobs (Run again clears it). ffmpeg (`ffmpeg`): the H.264 argument list in full, H.265 and ProRes presets (no CRF or faststart for ProRes, BT.709 tags), CRF clamped, candidates (PATH first without duplicates, then the macOS or Windows folders), version line parsing, a missing executable fails; frame pattern digits match the names. `encodes_a_short_sequence_with_each_preset` runs whenever ffmpeg can be found (skips otherwise, e.g. on CI): encodes 10 frames of 64×36 starting at frame number 5 with a leftover frame after them, with each preset, decodes each video back and counts 10 frames, and checks a failing encode reports ffmpeg's message. Opt-in benchmark `m7_frame_times` (`AKTIS_BENCH=1` plus `AKTIS_TEST_CLIENT_JAR`, `AKTIS_TEST_WORLD`; optional `AKTIS_BENCH_PACKS` (shader packs, separated like `PATH`), `AKTIS_TEST_RADIUS` (8), `AKTIS_BENCH_FRAMES` (30), `AKTIS_BENCH_SPP` (256); `--features denoise` adds a denoised path-tracer run): frame times per engine at 1080p, the longest UI step, the shader-pack warm-up comparison and ffmpeg encode times, printed as tables (numbers in `animation.md` → "Performance"). Run with `--release -- --nocapture --test-threads 1`. Opt-in benchmark `m8_big_world` (`loader::bench`; `AKTIS_BENCH=1` plus `AKTIS_TEST_CLIENT_JAR`, `AKTIS_TEST_WORLD`; optional `AKTIS_TEST_RADIUS` (8), `AKTIS_TEST_CENTER`, `AKTIS_TEST_SHADERPACK`): runs the app's load stage by stage as for the Path Tracer engine (chunks, assets, mesh, quad grid, preview and path-tracer uploads, dropping the CPU mesh and quad grid), then switches to the shader pack (frees the other engines' data, builds the pack, which meshes again) and frees everything; prints time, bytes made and, on macOS, the process footprint split into malloc and GPU with its peak after each step, plus bytes per chunk and per quad (numbers in `far-terrain.md` → "Measurements"). Run `cargo test --release -p aktis-app m8_big_world -- --nocapture`. Opt-in `real_world_ten_frame_job` (`AKTIS_TEST_CLIENT_JAR` + `AKTIS_TEST_WORLD`): a 10-frame 320×180 job on a real world with the preview and the path tracer at 4 spp (names, sizes, frames differ along the camera move; prints the time). The window itself is checked by hand. Re-centring (`loader`, M8 task 9): `recentring_waits_until_the_camera_is_half_a_radius_out` (the max(D/2, 2) chunk rule, small radii, negative coordinates); opt-in `real_world_recentring_flight` (`AKTIS_TEST_CLIENT_JAR` + `AKTIS_TEST_WORLD`, `AKTIS_TEST_RADIUS` 8, `AKTIS_TEST_FAR` 64): flies 640 blocks east of spawn re-centring as the app does, each new area holds the camera, prints load times. Engine geometry (`loader`, M8 task 2a): `Residency` per engine (the path tracer includes the preview, shader packs neither), `residency_plan` for every engine switch (frees unused, builds missing, a failed path tracer isn't retried), a load builds only the wanted geometry (none for a shader pack, no quad grid for the preview), `MeshTask` builds the same mesh as a load and a quad grid only when asked; `released_geometry_is_rebuilt_without_compiling_again` (GPU, skips without an adapter): a handmade pack built for a handmade world, `release_world` frees its vertex buffers and keeps it Ready, the next build restores the same bytes with 0 s compiling. Memory budget (`budget`, M8 task 3): far columns by level and the per-engine far column cost (Shader Pack > Path Tracer > Preview, task 8); Auto is half of the RAM (8 GiB when unknown) and custom budgets are decimal GB clamped to 4096, the costliest engine in use sets the per-chunk cost, `fit_radius` picks the largest radius that fits (sparse rings, never above the request, radii past the counts keep the last count, radius 0 at least), the lowered-radius message; `--memory-budget` parsing (whole GB, range); far terrain in the estimate (`far_bytes` per level, the detail radius shrinks while the far terrain stays); `--far-radius` parsing (0–512); project files read, clamp and pass on `far_radius` (missing = 0); project files read, clamp and pass on `memory_budget_gb` (missing = Auto); opt-in `real_world_budget_lowers_the_radius` (`AKTIS_TEST_WORLD`, `AKTIS_TEST_RADIUS` default 64): with 4 GB and the Path Tracer the radius shrinks, one more ring wouldn't fit, and the counts match an unlimited count | +| aktis-app | Command-line parsing (flags, `=` form, `--pack` order, errors, help); fly camera (movement directions, sprint, diagonal speed, look clamping, scroll speed range); viewport pixel size; viewport scheduling (preview re-renders only on change, one-shot engines, progressive accumulation with reset, preview while moving, holding still, returning to the same view, invalidate, paused engine keeps its image / shows the preview after a camera move); path-tracer panel (saved settings round trip incl. every view and PBR off, clamping and missing fields (PBR defaults to on), PBR hover text, render clock ignores frames without new samples and restarts on reset, progress text); frame-rate readout; selection clamping and chunk count; load request only with an existing instance, client jar and `level.dat`, with the instance's packs lowest priority first and the clamped texture size; old saved settings get the default texture size; loader block reuse (same-blocks check; a rebuild with a pack equals meshing from scratch, switching back gives the first mesh, the save isn't opened; without reuse the save is read); pack list (enable on top, moves, disable, available = `resourcepacks/` + added without enabled ones, forget, saved form with missing fields, missing pack details); overview camera; export file names (file-safe, sample count, `.png` added once). Project files: every section round-trips in the documented order with one line per key, defaults leave optional paths out, the documented example (empty shader pack = none, missing tables default), clamping of hand-edited values and a newer format, the load request names a missing jar or world and orders packs lowest priority first, write then read through a temporary file, shown names, timeline and output survive the session's serde; format 2 (M9 task 2): `[canvas]` and `mode`, `[output]` without the size, Image projects round-trip with odd canvases and views and drop timeline and output (`normalized`), format-1 files migrate (keys → Video, none → Image, no `[project]` = format 1), a missing or unknown mode reads as Video, job snapshots stay Video projects; project folders: names and picked paths, save then locate (folder or its file), refusing a non-project folder, a format-1 file's folder name (`name 2.aktis` when taken), thumbnail box filter and write; recent projects (order, one per path, cap 50, entry fields); 0.1.0 saved state seeds the library and a saved `library` wins; the whole saved state (`Saved`, default and with a keyed timeline and the Shader Pack engine) reads back from RON exactly as eframe writes it; `ProjectPanel::set_choices` (normalised selection, packs outside `resourcepacks/` added once); file stems and the untitled unsaved-work rule. Timeline editing (`animate`): edits auto-key with the stopwatch on (snapped to the playhead's frame) and change the base otherwise, an enabled track without keys still auto-keys, a disabled track edits the base, re-keying keeps the mode, the fly camera never keys (no camera tracks: base; position keyed: override, yaw to the base; flying back clears it; Look at: turning goes to the override), Key camera (position/yaw/pitch, stopwatches on, position only with Look at), stopwatches on/off (Look at 16 blocks ahead, base keeps the shown value), key navigation and ◆, time format and snapping; key editing: drags snap the grabbed key to frames (free with Alt) and stop at 0, moved keys keep values and replace what they land on (the start state untouched), delete keeps the stopwatch, mode change, copy through clipboard text and paste at the playhead's frame with offsets and modes kept (stopwatch on for new tracks, other text ignored). Undo history (`history`): a drag is one step (nothing recorded while the button is held), undo/redo walk scene and timeline steps to the ends, a new edit clears redo (already before it's recorded), an unrecorded edit is what Undo undoes, only the last 100 steps are kept, fly-camera moves are never steps, reset forgets everything. Playback (`playback`): Play starts at the playhead or at in (before in, at out, on the last frame; an empty range doesn't play), advancing follows the wall clock and drops frames (stalls capped), stops on the last frame without Loop and wraps to in with it, toggle and seek, the clock is the playhead's frame, the overlay samples one point per frame between the first and last position key with the playhead's key highlighted (none without an active track). Viewport: playback keeps the path tracer behind the preview until it stops, a new frame clock or overlay renders the preview again, frame guide rectangles (landscape, portrait, same aspect). Orbit helper (`orbit`): keys on the circle at the height (16 per turn, angle 0 south, even times), turns and direction (clockwise = west after a quarter turn, counter-clockwise = east, key counts, a fractional turn ends on its angle), defaults start at the camera (radius floor), smooth constant-speed keys and a Look at key that keeps the camera on the centre, the sampled path within 1.3 % of the circle (0.1 % away from the ends), keys in the range replaced and others kept, the timeline grows (out follows only from the end), invalid values change nothing. Output (`output`): even sides in range, fitting to the GPU limit keeps the aspect, presets are even; viewport `display` fits output images and flags scaling. Render jobs (`job`): frame names (from 1, at least 4 digits, more for long jobs), paths per target, existing files found and skipped on resume, time left, labels and durations. Job runner (`job_runner`, GPU, skips without an adapter): every frame written as a numbered PNG of the output size with the preview and the path tracer (its settings restored afterwards), Pause finishes the frame and holds, Resume, Cancel keeps written frames, a write error fails the job, a resume renders only missing frames (no `.part` files left). Render queue (`queue`): a job is a snapshot (later edits don't reach it; engine, spp, frames, size), stills render their frame and Replace turns skipping off, resume skips frames on disk, the saved queue round-trips (serde) and running jobs come back Interrupted with fresh ids after them, reorder/duplicate/remove/run again/clear finished (the running job stays put), a job loads its world only when world, selection, packs or texture cap differ, Encode again only for finished video jobs (Run again clears it). ffmpeg (`ffmpeg`): the H.264 argument list in full, H.265 and ProRes presets (no CRF or faststart for ProRes, BT.709 tags), CRF clamped, candidates (PATH first without duplicates, then the macOS or Windows folders), version line parsing, a missing executable fails; frame pattern digits match the names. `encodes_a_short_sequence_with_each_preset` runs whenever ffmpeg can be found (skips otherwise, e.g. on CI): encodes 10 frames of 64×36 starting at frame number 5 with a leftover frame after them, with each preset, decodes each video back and counts 10 frames, and checks a failing encode reports ffmpeg's message. Opt-in benchmark `m7_frame_times` (`AKTIS_BENCH=1` plus `AKTIS_TEST_CLIENT_JAR`, `AKTIS_TEST_WORLD`; optional `AKTIS_BENCH_PACKS` (shader packs, separated like `PATH`), `AKTIS_TEST_RADIUS` (8), `AKTIS_BENCH_FRAMES` (30), `AKTIS_BENCH_SPP` (256); `--features denoise` adds a denoised path-tracer run): frame times per engine at 1080p, the longest UI step, the shader-pack warm-up comparison and ffmpeg encode times, printed as tables (numbers in `animation.md` → "Performance"). Run with `--release -- --nocapture --test-threads 1`. Opt-in benchmark `m8_big_world` (`loader::bench`; `AKTIS_BENCH=1` plus `AKTIS_TEST_CLIENT_JAR`, `AKTIS_TEST_WORLD`; optional `AKTIS_TEST_RADIUS` (8), `AKTIS_TEST_CENTER`, `AKTIS_TEST_SHADERPACK`): runs the app's load stage by stage as for the Path Tracer engine (chunks, assets, mesh, quad grid, preview and path-tracer uploads, dropping the CPU mesh and quad grid), then switches to the shader pack (frees the other engines' data, builds the pack, which meshes again) and frees everything; prints time, bytes made and, on macOS, the process footprint split into malloc and GPU with its peak after each step, plus bytes per chunk and per quad (numbers in `far-terrain.md` → "Measurements"). Run `cargo test --release -p aktis-app m8_big_world -- --nocapture`. Opt-in `real_world_ten_frame_job` (`AKTIS_TEST_CLIENT_JAR` + `AKTIS_TEST_WORLD`): a 10-frame 320×180 job on a real world with the preview and the path tracer at 4 spp (names, sizes, frames differ along the camera move; prints the time). The window itself is checked by hand. Re-centring (`loader`, M8 task 9): `recentring_waits_until_the_camera_is_half_a_radius_out` (the max(D/2, 2) chunk rule, small radii, negative coordinates); opt-in `real_world_recentring_flight` (`AKTIS_TEST_CLIENT_JAR` + `AKTIS_TEST_WORLD`, `AKTIS_TEST_RADIUS` 8, `AKTIS_TEST_FAR` 64): flies 640 blocks east of spawn re-centring as the app does, each new area holds the camera, prints load times. Engine geometry (`loader`, M8 task 2a): `Residency` per engine (the path tracer includes the preview, shader packs neither), `residency_plan` for every engine switch (frees unused, builds missing, a failed path tracer isn't retried), a load builds only the wanted geometry (none for a shader pack, no quad grid for the preview), `MeshTask` builds the same mesh as a load and a quad grid only when asked; `released_geometry_is_rebuilt_without_compiling_again` (GPU, skips without an adapter): a handmade pack built for a handmade world, `release_world` frees its vertex buffers and keeps it Ready, the next build restores the same bytes with 0 s compiling. Memory budget (`budget`, M8 task 3): far columns by level and the per-engine far column cost (Shader Pack > Path Tracer > Preview, task 8); Auto is half of the RAM (8 GiB when unknown) and custom budgets are decimal GB clamped to 4096, the costliest engine in use sets the per-chunk cost, `fit_radius` picks the largest radius that fits (sparse rings, never above the request, radii past the counts keep the last count, radius 0 at least), the lowered-radius message; `--memory-budget` parsing (whole GB, range); far terrain in the estimate (`far_bytes` per level, the detail radius shrinks while the far terrain stays); `--far-radius` parsing (0–512); project files read, clamp and pass on `far_radius` (missing = 0); project files read, clamp and pass on `memory_budget_gb` (missing = Auto); opt-in `real_world_budget_lowers_the_radius` (`AKTIS_TEST_WORLD`, `AKTIS_TEST_RADIUS` default 64): with 4 GB and the Path Tracer the radius shrinks, one more ring wouldn't fit, and the counts match an unlimited count | | aktis-world | `level.dat` (26.x and old spawn fields, gzip errors); selection helpers; block-state interning; grid clipping; palette unpacking; loading a generated 26.x world (all palette forms, region grouping, negative coordinates, not-full/missing/corrupt chunks, height and column clipping); `BlockGrid::heap_bytes` (a dense section adds at least 8 KiB, a uniform one almost nothing); parallel loading (M8 task 2b): `parallel_load_matches_the_sequential_loader` loads the fixture world and a generated four-region world (palette order per chunk, lit and unlit chunks, not-full, corrupt and missing chunks, a bad section after a good one) with batches of 1, 3, 7 and 4 096 chunks and compares grid, stats and progress calls with the pre-2b sequential loader (`load/sequential.rs`); `for_each_index` walks the same indices as `unpack`; far terrain (`lod`, M8 task 4): `grid_columns` scans a grid (water over stone, a plant-free top, empty columns, whole chunks only) and `with_detail_area` adds it under an outer ring (task 8); ring levels and far-area counts, heightmaps decoded with the bits their length implies, a handmade region (water over stone, sand, a log above, an empty column, a chunk without heightmaps, a partial and a corrupt chunk, missing ones) read into columns, the chunk without heightmaps scanned to the same columns, coarser levels keep the highest column, block-state ids the same on every run; opt-in `tests/lod_real.rs` (`AKTIS_TEST_WORLD`): `far_columns_match_the_block_grid` (level-0 columns within `AKTIS_TEST_RADIUS`, default 8, of `AKTIS_TEST_CENTER` against the block grid: top and floor blocks, nothing missed above) and `far_terrain_time_and_memory` (`AKTIS_TEST_DETAIL` default 8, `AKTIS_TEST_FAR` default 64; prints time, counts per level and memory); `rings_count_saved_chunks_by_distance` (M8 task 3): saved chunks per Chebyshev ring from region headers, across region edges and off-centre, truncated headers count as empty; opt-in `real_world_parallel_matches_sequential` (`AKTIS_TEST_WORLD`, `AKTIS_TEST_RADIUS` default 8) compares both loaders on a real save and prints their times (run with `--release`) | @@ -355,7 +355,7 @@ cargo run --release | 24 | Render → Shader Pack; choose BSL from the instance's packs (or `--shaderpack`); fly around, stop, Save PNG… | The preview shows with "Preparing BSL…" for about 2 s, then BSL's image; moving stays live (no preview stand-in), the overlay shows "warming up n / 16" briefly after stopping; switching pack or Reload rebuilds; a broken pack shows its error in the Render panel; Save PNG… suggests ` .png` and matches the screen; the pack choice comes back after a restart (not one given with `--shaderpack`) | | 25 | Shader Pack with BSL: fly near trees, stop; move the sun (noon, low in the west, below 0). Then choose Complementary Reimagined (r5.10) and do the same; Save PNG… | BSL: trees and blocks cast shadows away from the sun, longer as it drops, soft-edged, no stripes or acne on flat ground; at night the moon casts them. Complementary: "Preparing…" for 2 s or less (warm), then its image with shadows and its blocky clouds in the sky; light shafts at a low sun; the edge of the loaded area fades into the sky by day. Moving stays live for both; no error in the Render panel; the PNG matches the screen | -| 26 | Timeline: turn on Sun › Altitude's stopwatch, move the playhead, change the altitude (a key appears); add keys with ◆; select, drag (and with Alt), box-select, copy and paste them; right-click → Linear; Cmd/Ctrl-Z and Shift-Cmd/Ctrl-Z; File › Save, then Open the file | Keys appear where expected and the sun follows them while scrubbing; a drag undoes in one step; typing in a field undoes the text, not the project; the reopened project has the same keys | +| 26 | Timeline: turn on Sun › Altitude's stopwatch, move the playhead, change the altitude (a key appears); add keys with ◆; select, drag (and with Alt), box-select, copy and paste them; right-click → Linear; Cmd/Ctrl-Z and Shift-Cmd/Ctrl-Z; File › Save, then Open the project folder | Keys appear where expected and the sun follows them while scrubbing; a drag undoes in one step; typing in a field undoes the text, not the project; the reopened project has the same keys | | 27 | Key camera at three places (or Orbit… → Create), Preview engine; press K, try Loop and in/out; switch to Path Tracer and play; set Output 1920 × 1080 in a wider viewport | The orange path and dots show in the preview with the playhead's key in blue; playback runs at real speed and loops or stops at out; the path tracer shows the preview while playing and accumulates once stopped; dark bars outside the 16:9 frame; Render size Viewport removes them; Save PNG matches the output size and has no path line | | 28 | Render queue: Add animation… (PNG) and Add still… for one world; change the Project panel to another world or radius and Add animation… with BSL; Start; Pause and Resume; then quit mid-job, reopen, Start | Jobs run top to bottom with a progress bar and time left; the queue loads the second world and builds BSL before its job, then loads the first world back; the viewport shows the frame being rendered and can't be flown; after quitting the job shows Interrupted and Start renders only the missing frames | | 29 | Output format MP4 H.264, Add animation… as `test.mp4`, Start; then H.265 and MOV ProRes; one with Keep frames; point Choose… at a non-ffmpeg file, then Automatic | Each job shows Encoding, then Done; the videos play with the same colours as the frames; `test_frames/` is gone unless Keep frames; a wrong ffmpeg greys out the video formats with a hint until Automatic finds it again | @@ -365,5 +365,8 @@ cargo run --release | 33 | Raise Detail radius and Far radius, switch engines; set Memory budget Custom to a small value (e.g. 4 GB) with Detail radius 64; Load | The Estimate line updates with chunks and peak GB (far terrain shown); over budget it warns with the radius Load will use; after Load the Loaded box starts with "Detail radius lowered from 64 to … to fit the 4.0 GB memory budget." | | 34 | Load without a fixed centre (Detail 8, Far 128) and fly the camera a few hundred blocks in one direction | The detail area follows: the Loaded box's Centre says "(follows the camera)" and changes, each move takes well under a second, and the view doesn't jump; a project with a fixed centre doesn't move | | 35 | Quit with a world loaded, keyed camera and Far radius set; reopen | The world, camera, timeline, engine and Far radius come back as they were | +| 36 | With a world shown and a key on the timeline, File › Save As… as `Shot` in a test folder; look at the folder; change something, Save | `Shot.aktis/` holds `project.aktis.toml` (`format = 2`, `mode = "video"`, `[canvas]`) and a `thumbnail.png` matching the view; the title reads `Shot — Aktis`, with `•` after the change and without it after Save | +| 37 | File › Open Project File… an M7 single-file project with keys, then Save; then one without keys | The first opens as before; Save writes `.aktis/` beside the file with a note, the old file unchanged. The second opens with the "Image project" note; adding a key doesn't show `•` | +| 38 | Start this build on saved state from 0.1.0 (install folders added, resource packs enabled, a shader pack chosen); quit and start again | Added install folders, enabled resource packs and the shader-pack choice are still there both times | Record the result (platform, GPU, any failures) in the PR or the milestone's roadmap entry. diff --git a/docs/glossary.md b/docs/glossary.md index e619e98..f5d32fa 100644 --- a/docs/glossary.md +++ b/docs/glossary.md @@ -124,9 +124,11 @@ | **App bundle** | macOS app folder `Aktis.app` (`Contents/Info.plist`, `MacOS/`, `Resources/`) that Finder shows as one app; releases ship it in a `.dmg` (ADR 0021). | | **Ad-hoc signature** | A code signature with no certificate (`codesign --sign -`). Apple Silicon needs one to run code, but Gatekeeper still warns because it names no developer (ADR 0021). | | **Home screen** | The screen the app opens on (M9, Planned): recent projects, New Image, New Video, Open…, the Minecraft library (ADR 0022). | -| **Image project / Video project** | A project's mode (`[project] mode`, M9, Planned), fixed at creation: an Image project makes stills (render history, Views); a Video project makes animations (timeline, Deliver page). | -| **Project folder** | `.aktis/`: a project's file plus its thumbnail, renders, exports, queue and autosave (M9, Planned). | -| **Canvas** | A project's image size in pixels (`[canvas]`, M9, Planned); replaces the output resolution. Video canvases have even sides. | +| **Image project / Video project** | A project's mode (`[project] mode`, M9), fixed at creation: an Image project makes stills (render history, Views); a Video project makes animations (timeline, Deliver page). | +| **Project folder** | `.aktis/`: a project's file (`project.aktis.toml`) and thumbnail (M9), plus its renders, exports, queue and autosave (Planned). | +| **Minecraft library** | The install folders and per-instance resource and shader pack lists shared by every project (`recent::Library` in `app.ron`, M9). | +| **Recent projects** | The list of recently opened or saved projects in `app.ron` that the Home screen shows (`recent::Recents`, M9). | +| **Canvas** | A project's image size in pixels (`[canvas]` in the file since M9; its own control is Planned); replaces the output resolution. Video canvases have even sides. | | **Workspace** | The layout for the open project, one per mode (M9, Planned). | | **Preview scale** | The fraction of the canvas (25 / 50 / 100 %) the viewport's engines render at (M9, Planned); replaces Render size. | | **View** | A saved camera position in an Image project, shown in the left panel (M9, Planned). | diff --git a/docs/roadmap.md b/docs/roadmap.md index 58651e3..df63d17 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1166,7 +1166,7 @@ Goal: the app opens on a Home screen of recent projects; a project is created as a Video project, each with its own workspace layout and features, and a canvas size chosen at creation and changeable in the workspace. Design: ADR 0022 and [app.md → Projects and workspaces](subsystems/app.md#projects-and-workspaces-m9-planned); -format in [scene.md → Project format 2](subsystems/scene.md#project-format-2-m9-planned). +format in [scene.md → Project format 2](subsystems/scene.md#project-format-2-m9). Decisions (maintainer, 2026-12-01, all defaults): a project is a folder `.aktis/`; mode is fixed, switching is "Save a copy as …"; the world is optional in the New Project @@ -1182,11 +1182,23 @@ plus pinned ones; the vertical FOV stays fixed when the canvas changes. format-1 files open with mode Video when their timeline has keys, else Image; a saved format-1 file becomes a folder beside it, the old file left alone; Preview scale is app-wide. -- [ ] 2. **Project format 2** (app, scene): `[project] mode`, `[canvas]`, format 2, +- [x] 2. **Project format 2** (app, scene): `[project] mode`, `[canvas]`, format 2, reading format 1 (migration table in `scene.md`), the project folder (create, open, atomic save, `thumbnail.png`), the recent-projects list and the Minecraft library in `app.ron`. *Verify:* round-trip and migration unit tests; old saved state seeds the library. + *Done:* 2026-12-01. `project_file.rs` (format 2, `ProjectMode`, `View`, + `normalized`), `project_dir.rs`, `recent.rs` (`Recents`, `Library`); File menu: Open… + picks a folder, Open Project File… a `.toml`, Save writes folders (a format-1 file + becomes a folder beside it). In memory the canvas is still `OutputSettings` + width/height (task 6 renames it). Queue snapshots are always Video projects, so + jobs keep their timeline and output. Tests: 10 new (format-2 round trips, Image + projects dropping timeline/output, format-1 migration, job snapshots staying Video, + folder save/locate/refusal, legacy folder names, thumbnail box filter, recents order + and cap, entries, library seeding from 0.1.0 saved state) plus odd Image canvases in + `output.rs`; 591 workspace tests pass. Interim, until task 8: Image + projects open in today's layout and don't save timeline edits (a note says so). + Smoke-test rows 36–38 added; not run by hand yet. - [ ] 3. **App shell** (app): `Screen` (Home / Workspace), a shared `Session` (world, engines, loader, job runner), `app.rs` split into `home/` and `workspace/{common, image,video}`; today's layout becomes the Video workspace. *Verify:* no visible diff --git a/docs/subsystems/app.md b/docs/subsystems/app.md index 5f26588..8ea327c 100644 --- a/docs/subsystems/app.md +++ b/docs/subsystems/app.md @@ -14,7 +14,8 @@ command line can load a world directly. The viewport can show the progressive pa (preview while moving) with its controls, denoise it (builds with the `denoise` feature), and "Save PNG…" saves the current image. The Shader Pack engine renders the world with an OptiFine/Iris pack chosen per instance, built in the background (see "Shader packs"). -Project files (`*.aktis.toml`) open and save from the File menu (see "Project files"). A +Projects open and save from the File menu as project folders (`.aktis/`, M9 task 2), +with an Image or Video mode; older single files still open (see "Project files"). A bottom panel holds the timeline's dope sheet (see "Timeline panel"). Edit › Undo/Redo step through scene and timeline edits (see "Undo and redo"). The timeline plays in real time (K), the preview draws the camera path, and a frame guide shows the output's aspect @@ -24,8 +25,10 @@ PNG files or a video (your own ffmpeg) through a render queue (see "Render queue "Video encoding"). Only the engine in use keeps world geometry (see "Engine geometry"), and a memory budget lowers the radius of loads that wouldn't fit (see "Memory budget"). -**Planned (M9, ADR 0022):** a Home screen of recent projects and separate Image and Video -workspaces replace the single window described below; see "Projects and workspaces". +**M9 (ADR 0022), in progress:** project folders, the mode and canvas in the file, the +recent-projects list and the Minecraft library in `app.ron` are built (task 2); the Home +screen and separate Image and Video workspaces that replace the single window described +below are Planned. See "Projects and workspaces". ## Design @@ -40,7 +43,7 @@ workspaces replace the single window described below; see "Projects and workspac "Advanced" sections. - **Persistence:** window state and the app's choices (the whole session, including the timeline) through eframe `persistence` (see "Saved state"); project files - (`*.aktis.toml`, `scene.md` → "Project file") through the File menu (see "Project + (project folders, `scene.md` → "Project file") through the File menu (see "Project files"). ### Modules @@ -54,7 +57,9 @@ workspaces replace the single window described below; see "Projects and workspac | `budget.rs` | Memory budget (M8 task 3, ADR 0020): system RAM (`sysinfo`), budget bytes (Auto = 50 %), per-chunk peak costs per engine, the estimate and the largest radius that fits (`Budget::fit_radius`), `Fitted` (what a load did) | | `packs.rs` | Resource Packs section: `PackChoice` (saved per instance), `PacksCache` (pack details), the lists and Apply | | `app.rs` | `AktisApp`: panels and viewport; starts loads, uploads the result to the preview; saves state; File menu, project snapshots, unsaved-changes dialog | -| `project_file.rs` | `ProjectFile`: the `*.aktis.toml` format (sections, clamping, compact writer, atomic write), its load request, `EngineChoice` | +| `project_dir.rs` | Project folders (M9): finding a picked project (`locate`: folder, its file, or a format-1 file), folder names, Save into a folder (refuses unrelated folders), a format-1 file's folder, the shown name, `thumbnail.png` (box-filtered to 512 px) | +| `recent.rs` | The recent-projects list (`Recents`, up to 50, most recent first) and the Minecraft `Library` (install folders, resource and shader pack lists), both in `app.ron` | +| `project_file.rs` | `ProjectFile`: the project file format (format 2: mode, canvas, views; reading format 1; sections, clamping, compact writer, atomic write), its load request, `EngineChoice` | | `output.rs` | `OutputSettings` / `OutputFormat` (`[output]`), resolution presets, even sides, fitting to the GPU limit, `RenderSize` | | `animate.rs` | Rules between base scene, timeline and shown scene: auto-key routing, fly-camera override, Key camera, stopwatches, key navigation, labels and field ranges | | `playback.rs` | Play/pause and the wall-clock playhead, the engines' frame clock at the playhead, the camera-path overlay data | @@ -160,21 +165,21 @@ eframe storage (macOS `~/Library/Application Support/Aktis/app.ron`, Windows | Field | Content | |---|---| -| `project.extra_dirs` | Install folders added with "Add folder…" | +| `library` | The Minecraft library (M9): `extra_dirs` (install folders added with "Add folder…"), `packs` (per game folder: `enabled`, highest priority first, and `added` resource packs), `shader_packs` (per game folder: `selected` pack and `added` packs). Saved state from before M9 has none; it's filled once from the old `project.extra_dirs`, `project.packs` and `shader_packs`, which are read but no longer written | +| `recent` | Recent projects (M9), most recent first, up to 50: path (project folder or older file), name, mode, canvas, fps and duration (Video), world folder name, last opened or saved (Unix seconds) | +| `mode`, `views` | The open project's mode and an Image project's views | | `project.instance` / `world` | Chosen game folder and save folder | | `project.selection` | Centre, radius, min/max Y | | `project.reopen` | A world from the panel was shown at exit | -| `project.packs` | Per game folder: `enabled` (highest priority first) and `added` packs | | `project.max_texture_size` | Texture layer cap in px (default 128; clamped on use) | | `scene` | Camera, sun, sky, fog | | `speed` | Fly speed | | `engine` | Selected engine (`Preview`, `PathTracer` or `ShaderPack`; not changed by `--shaderpack`) | -| `shader_packs` | Per game folder (empty path without an instance): `selected` pack and `added` packs | | `path_tracer` | View, samples target, bounces (clamped on load: 1–1 048 576 spp, 0–32 bounces), `pbr` (default true when missing) | | `denoise` | `enabled`, `auto`, `show_denoised` (all default true when missing) | | `timeline` | The timeline being edited (`[timeline]` form) | | `output` | Output settings (`[output]` form) | -| `project_path` | The open project file; missing = untitled | +| `project_path` | The open project file (a folder's `project.aktis.toml`, or an older single file); missing = untitled | | `world_override` | The open project's `[world]` and `[packs]` when its world couldn't be loaded | | `playhead` | Playhead time in seconds (snapped to a frame on start) | | `timeline_panel` | Bottom panel open/collapsed, tab, collapsed groups, zoom (`view`), Loop | @@ -194,17 +199,31 @@ everything. `saved_state_round_trips_through_ron` guards this. (Until the fix in ### Project files -A File menu at the top (M7 task 3). The project file format is in -[scene.md → Project file](scene.md#project-file). +A File menu at the top (M7 task 3; project folders since M9 task 2). The format and the +folder layout are in [scene.md → Project file](scene.md#project-file) and +[Project format 2](scene.md#project-format-2-m9). | Item | Shortcut | Does | |---|---|---| -| New | Cmd/Ctrl-N | Forgets the file and resets the timeline and output; keeps the loaded world, packs, engine and scene (a new animation of this view) | -| Open… | Cmd/Ctrl-O | Reads a project (see below) | -| Save | Cmd/Ctrl-S | Writes the open file; Save As when untitled | -| Save As… | Shift-Cmd/Ctrl-S | Asks for a file (`.aktis.toml` added; `name.toml` becomes `name.aktis.toml`), then writes it | - -- **Title:** `flyover.aktis.toml • — Aktis`, or `Untitled — Aktis`; `•` = unsaved changes. +| New | Cmd/Ctrl-N | Forgets the file and resets the timeline and output; keeps the loaded world, packs, engine and scene (a new animation of this view); a Video project | +| Open… | Cmd/Ctrl-O | Picks a project folder (`.aktis`) and reads it (see below); a folder without `project.aktis.toml` is refused ("… is not an Aktis project folder") | +| Open Project File… | — | Picks a `.toml` file: an older single-file project, or the `project.aktis.toml` inside a project folder (which opens that folder) | +| Save | Cmd/Ctrl-S | Writes the open project folder; Save As when untitled. An older single file `name.aktis.toml` is saved as the folder `name.aktis/` beside it (`name 2.aktis/` … when that name is taken by another folder) and the file is left alone; a note says so | +| Save As… | Shift-Cmd/Ctrl-S | Asks for a name and place, then writes the folder `.aktis` there (a `.toml` or `.aktis.toml` ending is dropped). An existing project folder is overwritten (the dialog asks first); an existing folder that isn't empty and isn't a project folder is refused | + +- **Writing a folder:** creates it if needed, writes `project.aktis.toml` (through a + `.tmp` file), then `thumbnail.png` from the image the viewport shows for the selected + engine (read back from the GPU, longest side 512 px; skipped while a job holds the + engines or nothing is rendered, keeping the old one). `renders/`, `exports/`, `queue.toml` + and `.autosave.toml` are Planned (tasks 7–9). Each open and save puts the project first in + the recent-projects list (see "Saved state"). +- **Mode:** New and Save As keep the open project's mode; new projects are Video projects + until the New Project dialog (task 5). Until the Image workspace (task 8), an Image + project opens in this layout with a note: "Image project: its timeline and Output format + aren't saved (Image projects keep only stills)." Its timeline and output settings other + than the size never count as unsaved changes. Its views are kept and saved. +- **Title:** `Castle • — Aktis` for a project folder, `flyover.aktis.toml • — Aktis` for an + older single file, or `Untitled — Aktis`; `•` = unsaved changes. A saved project has unsaved changes when the current state written as a project differs from what was last opened or saved (moving the camera counts: it is in the file). An untitled project has them only when its timeline has keys. @@ -407,7 +426,10 @@ written). The latest failure's message shows under the list. - **Snapshot** (`queue::QueuedJob`): at Add, the whole project in the `*.aktis.toml` format (world, selection, packs, texture cap, engine and its settings, base scene, timeline, output) plus kind, the still's frame, target, Replace, status and frames - written. Later edits don't change it. The fly camera's unkeyed moves aren't in it. When it + written. Later edits don't change it. The fly camera's unkeyed moves aren't in it. Since + M9 task 2 a snapshot is format-2 text written as a Video project whatever the editor's + mode (`ProjectFile::for_job`), so the timeline and output always go with the job; + format-1 snapshots from 0.1.0 read as Video projects (`ProjectFile::from_job_toml`). When it runs, `job::JobSpec` is made from it: engine, path-tracer spp/bounces/PBR and Denoise, scene, timeline, frames, output size fitted to the GPU, target, and whether to skip frames on disk. @@ -726,7 +748,9 @@ while the camera moves or turns; the frame rate readout shows "idle" otherwise. ### Projects and workspaces (M9, Planned) Design for M9 ([roadmap](../roadmap.md#m9-projects--workspaces-in-progress), ADR 0022). -Nothing here is built yet; the sections above describe the app as it is. +Built so far (task 2): project folders, mode, canvas and views in the file, the +recent-projects list and the library in `app.ron` (see "Project files" and "Saved state"). +The rest is Planned; the sections above describe the app as it is. **Screens.** The app starts on **Home**; opening or creating a project enters its **workspace**; ⌂ Home leaves it (asking to save). One project is open at a time. The command @@ -802,8 +826,7 @@ project file, if any, joins the recents). **Modules (planned):** `session.rs` (world, engines, loader, job runner; shared), `home/` (screen, recents, new-project dialog), `workspace/common.rs` (header, World panel, Inspector, canvas chip), `workspace/image.rs`, `workspace/video.rs` (Animate, Deliver), -`project_dir.rs` (the folder: create, open, save, thumbnail, autosave), `history_renders.rs` -(the Image filmstrip). +`history_renders.rs` (the Image filmstrip); `project_dir.rs` gains autosave (task 9). ## Open questions diff --git a/docs/subsystems/scene.md b/docs/subsystems/scene.md index 4fa5112..b17cad2 100644 --- a/docs/subsystems/scene.md +++ b/docs/subsystems/scene.md @@ -12,8 +12,9 @@ defaults). Height fog (M4): both engines read `[fog]`. `camera.roll` (M7): all t apply it; `Camera::basis()` gives the rolled image axes. The timeline (M7): the `timeline` module reads, writes and evaluates `[timeline]` (`Timeline::scene_at`). Project files (M7): read and written by `aktis-app` (`project_file.rs`); see "Project file". -Project format 2 (M9, project folders, Image/Video mode, canvas): Planned; see "Project -format 2". +Project format 2 (M9 task 2: project folders, Image/Video mode, canvas, views): read and +written by `aktis-app` (`project_file.rs`, `project_dir.rs`); format-1 files still open. See +"Project format 2". ## Design @@ -66,8 +67,10 @@ Breaking changes to this format need a CHANGELOG entry and a migration note here ### Project file -`.aktis.toml` holds everything a render needs; render-queue jobs will store the same -format (ADR 0018). Built in M7 task 3 (`aktis-app/src/project_file.rs`; the File menu is in +`.aktis.toml` holds everything a render needs; render-queue jobs store the same +format (ADR 0018). This section shows **format 1** (M7–M8); since M9 task 2 the app writes +format 2 into a project folder (see "Project format 2"), which differs only in +`[project]`, `[canvas]`, `[output]` and `[[views]]`. Built in M7 task 3 (`aktis-app/src/project_file.rs`; the File menu is in [app.md → Project files](app.md#project-files)). The scene tables above appear unchanged at the top level. Paths are absolute, written with the OS's separators. Every table and field is optional and falls back to its default; an empty path (`""`) means none, and optional @@ -176,21 +179,23 @@ into −64…319 and ordered, `max_texture_size` to the cap range, `spp` 1–1 0 loads with a warning and is written back as this build's format. Output `format` is one of `png`, `mp4_h264` (default), `mp4_h265`, `mov_prores`; `quality` defaults to 18. -### Project format 2 (M9, Planned) +### Project format 2 (M9) -Planned for M9 (ADR 0022, [app.md → Projects and workspaces](app.md#projects-and-workspaces-m9-planned)); -format 1 above is what the code reads and writes today. +M9 task 2 (ADR 0022, [app.md → Projects and workspaces](app.md#projects-and-workspaces-m9-planned)). +The app writes format 2; it reads format 1 too (table below). Render-queue snapshots are +format-2 text since then, always with `mode = "video"`; format-1 snapshots in `app.ron` +read as Video projects whether or not they have keys, so their output settings stay. -A project becomes a folder: +A project is a folder: ``` Castle.aktis/ project.aktis.toml # format 2, below thumbnail.png # longest side 512 px; written on save - renders/ # Image only: NNNN.png + index.toml (the filmstrip) - exports/ # Video only: default output destination - queue.toml # Video only: the render queue - .autosave.toml # recovery copy while there are unsaved changes + renders/ # Planned (task 8), Image only: NNNN.png + index.toml (the filmstrip) + exports/ # Planned (task 7), Video only: default output destination + queue.toml # Planned (task 7), Video only: the render queue + .autosave.toml # Planned (task 9): recovery copy while there are unsaved changes ``` Changes to `project.aktis.toml` from format 1: @@ -226,12 +231,18 @@ Reading format 1 (migration): | Format 1 | Format 2 | |---|---| +| No `[project] format` (or `format = 1`) | Format 1 | | No `mode` | `video` when `[timeline]` has a key, else `image` | | `[output] width/height` | `[canvas]` (Image keeps the values as they are) | | `[output]` other fields | Kept for Video, dropped for Image | | Single file `name.aktis.toml` | Opens as is; Save writes `name.aktis/` beside it and leaves the file alone | -A missing or unknown `mode` in a format-2 file reads as `video` with a warning. +A missing or unknown `mode` in a format-2 file reads as `video` with a warning; a missing +`[canvas]` falls back to `[output]`'s `width`/`height`. Canvas sides are clamped to +16–16 384; Video canvases are then rounded up to even, Image canvases keep odd sides. +`[[views]]` fields missing in a view take the default camera's values. Sections are written +in this order: `[project]`, `[canvas]`, `[world]`, `[packs]`, `[engine]`, the scene tables, +then `[timeline]` and `[output]` (Video) or `[[views]]` (Image, only when there are any). ## Open questions From 3fd94cdc1c053874a58462eff1e88a02a3941f55 Mon Sep 17 00:00:00 2001 From: Trilleo Date: Tue, 1 Dec 2026 23:15:36 +0800 Subject: [PATCH 04/14] refactor(app): split app.rs into a session, Home and the workspace MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Split the 3,853-line app.rs into app/mod.rs (AktisApp, Session, Screen, start-up, saved state), app/session.rs (loads, re-centring, engine geometry, shader-pack builds), app/home.rs and app/workspace/{mod,file,panels,viewport,video}.rs. A Session struct now owns the GPU, engines, viewport, world, loads, denoiser, job runner and encoder, shared by every screen. Methods only moved. Add Screen (Home / Workspace): File › Home lists recent projects to open, with Back to the open project, which keeps its world. The app still starts in the workspace until the full Home screen (task 4). Docs: app.md (Modules, File menu, M9 status), roadmap (M9 task 3), ADR 0022, testing.md (smoke row 39), CHANGELOG. Refs ADR 0022 --- CHANGELOG.md | 3 +- crates/aktis-app/src/app.rs | 3853 ----------------- crates/aktis-app/src/app/home.rs | 65 + crates/aktis-app/src/app/mod.rs | 926 ++++ crates/aktis-app/src/app/session.rs | 464 ++ crates/aktis-app/src/app/workspace/file.rs | 435 ++ crates/aktis-app/src/app/workspace/mod.rs | 245 ++ crates/aktis-app/src/app/workspace/panels.rs | 527 +++ crates/aktis-app/src/app/workspace/video.rs | 1020 +++++ .../aktis-app/src/app/workspace/viewport.rs | 358 ++ .../decisions/0022-projects-and-workspaces.md | 2 +- docs/dev/testing.md | 1 + docs/roadmap.md | 12 +- docs/subsystems/app.md | 34 +- 14 files changed, 4078 insertions(+), 3867 deletions(-) delete mode 100644 crates/aktis-app/src/app.rs create mode 100644 crates/aktis-app/src/app/home.rs create mode 100644 crates/aktis-app/src/app/mod.rs create mode 100644 crates/aktis-app/src/app/session.rs create mode 100644 crates/aktis-app/src/app/workspace/file.rs create mode 100644 crates/aktis-app/src/app/workspace/mod.rs create mode 100644 crates/aktis-app/src/app/workspace/panels.rs create mode 100644 crates/aktis-app/src/app/workspace/video.rs create mode 100644 crates/aktis-app/src/app/workspace/viewport.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index a9e6308..79a20f5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,7 +14,8 @@ uses [Semantic Versioning](https://semver.org/). 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. -- The app remembers recent projects (for the coming Home screen). +- The app remembers recent projects. File › Home lists them with their mode, canvas size and + world, and opens one with a click. The current project stays open while Home is shown. ### Changed diff --git a/crates/aktis-app/src/app.rs b/crates/aktis-app/src/app.rs deleted file mode 100644 index 8535b8e..0000000 --- a/crates/aktis-app/src/app.rs +++ /dev/null @@ -1,3853 +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_dir; -use crate::project_file::{ - EngineChoice, EngineSection, PacksSection, ProjectFile, ProjectMode, View, WorldSection, -}; -use crate::pt_panel::{self, ProgressClock, SavedPtSettings}; -use crate::queue::{self, NewJob, QueueStatus, RenderQueue}; -use crate::recent::{self, Library, RecentProject, Recents}; -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 a project folder. - Open, - /// Open a project file: a format-1 file or a folder's `project.aktis.toml`. - OpenFile, - /// 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, - /// Install folders and pack lists shared by every project; `None` in saved state from - /// before M9, which is seeded from `project` and `shader_packs`. - library: Option, - /// Recent projects, most recent first. - recent: Recents, - /// The open project's mode. - mode: ProjectMode, - /// The open Image project's views. - views: Vec, - scene: Scene, - speed: Option, - engine: EngineChoice, - path_tracer: SavedPtSettings, - denoise: DenoiseSettings, - /// Shader-pack lists from before M9 (now in `library`); read, never written. - #[serde(skip_serializing)] - 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 (a project folder's `project.aktis.toml`, or a format-1 - /// 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, -} - -impl Saved { - /// Moves the library into place: from `library`, or for saved state older than M9 from - /// the Project panel's and shader packs' lists (read, never written again). - fn seed_library(&mut self) { - let library = self.library.take().unwrap_or_else(|| Library { - extra_dirs: std::mem::take(&mut self.project.extra_dirs), - packs: std::mem::take(&mut self.project.packs), - shader_packs: std::mem::take(&mut self.shader_packs), - }); - self.project.extra_dirs = library.extra_dirs; - self.project.packs = library.packs; - self.shader_packs = library.shader_packs; - } -} - -/// 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 (a project folder's `project.aktis.toml`, or a format-1 - /// file); `None` = untitled. - project_path: Option, - /// The open project's mode (fixed per project; ADR 0022). - mode: ProjectMode, - /// The open Image project's views (kept and saved; edited from M9 task 8). - views: Vec, - /// Recent projects (saved). - recent: Recents, - /// 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 mut saved: Saved = cc - .storage - .and_then(|s| eframe::get_value(s, STORAGE_KEY)) - .unwrap_or_default(); - saved.seed_library(); - 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, - mode: saved.mode, - views: saved.views, - recent: saved.recent, - 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_dir::display_name(Some(p)); - let suffix = format!(".{}", crate::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: `