mirror of
https://github.com/storytold/texturecraft.git
synced 2026-11-28 17:19:24 +01:00
Merge upstream main into feat/assets-pass-2
Main's Resources Updater replaces the shelf's own resource.update and resource.reload: the shelf menu's Reload and the refresh popup's updates now run main's resource.status and resource.update, and Show in reads the project's saved source path. A renamed image keeps its source record, so it still follows its file.
This commit is contained in:
commit
97bc67f943
188 files changed
+10285
-1415
No files matched your search
@@ -4,10 +4,10 @@
|
||||
"repository_id": 1419654881,
|
||||
"producer_workflow_id": 429738073,
|
||||
"producer_workflow_path": ".github/workflows/nightly.yml",
|
||||
"producer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
|
||||
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
|
||||
"producer_tooling_revision": "f94a43818dabb2e85f2f4d5cd768bb8e5662600a",
|
||||
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@f94a43818dabb2e85f2f4d5cd768bb8e5662600a",
|
||||
"signer_workflow_path": ".github/workflows/nightly-sign.yml",
|
||||
"signer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
|
||||
"signer_tooling_revision": "f94a43818dabb2e85f2f4d5cd768bb8e5662600a",
|
||||
"release_branch": "nightly-signer",
|
||||
"manual_actors": [
|
||||
"bflatastic",
|
||||
|
||||
@@ -36,7 +36,7 @@ jobs:
|
||||
RUST_BACKTRACE: 1
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
@@ -44,12 +44,12 @@ jobs:
|
||||
persist-credentials: false
|
||||
# The release's pin (release.yml craft-fonts-ref), so the bundle's notices match a shipped build.
|
||||
- name: Check out craft-fonts
|
||||
uses: storytold/craft-common-actions/actions/checkout-craft-fonts@605d58766e8f536564da8fc81d3676ac86816dea
|
||||
uses: storytold/craft-common-actions/actions/checkout-craft-fonts@f94a43818dabb2e85f2f4d5cd768bb8e5662600a
|
||||
with:
|
||||
ref: aced4137c022f1f587624d48e81ec77e1914a9cc
|
||||
- uses: storytold/craft-common-actions/actions/checkout-craft-i18n@605d58766e8f536564da8fc81d3676ac86816dea
|
||||
- uses: storytold/craft-common-actions/actions/checkout-craft-i18n@f94a43818dabb2e85f2f4d5cd768bb8e5662600a
|
||||
- id: rust
|
||||
uses: storytold/craft-common-actions/actions/rust-channel@605d58766e8f536564da8fc81d3676ac86816dea
|
||||
uses: storytold/craft-common-actions/actions/rust-channel@f94a43818dabb2e85f2f4d5cd768bb8e5662600a
|
||||
with:
|
||||
targets: aarch64-apple-darwin
|
||||
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
|
||||
|
||||
@@ -34,9 +34,9 @@ jobs:
|
||||
checks: read
|
||||
attestations: write
|
||||
id-token: write
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@f94a43818dabb2e85f2f4d5cd768bb8e5662600a
|
||||
with:
|
||||
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
|
||||
tooling-revision: f94a43818dabb2e85f2f4d5cd768bb8e5662600a
|
||||
app-name: texturecraft
|
||||
producer_run_id: ${{ inputs.producer_run_id }}
|
||||
producer_run_attempt: ${{ inputs.producer_run_attempt }}
|
||||
|
||||
@@ -22,9 +22,9 @@ jobs:
|
||||
actions: read
|
||||
attestations: write
|
||||
id-token: write
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@f94a43818dabb2e85f2f4d5cd768bb8e5662600a
|
||||
with:
|
||||
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
|
||||
tooling-revision: f94a43818dabb2e85f2f4d5cd768bb8e5662600a
|
||||
app-name: texturecraft
|
||||
manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]'
|
||||
craft-fonts-ref: aced4137c022f1f587624d48e81ec77e1914a9cc
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
name: Notify Services on Release Change
|
||||
|
||||
on:
|
||||
release:
|
||||
types:
|
||||
- published
|
||||
- unpublished
|
||||
- created
|
||||
- edited
|
||||
- deleted
|
||||
- prereleased
|
||||
- released
|
||||
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
notify:
|
||||
uses: storytold/craft-common-actions/.github/workflows/notify-services.yml@main
|
||||
secrets:
|
||||
ARTCRAFT_SERVICES_DISPATCH_TOKEN: ${{ secrets.ARTCRAFT_SERVICES_DISPATCH_TOKEN }}
|
||||
@@ -28,6 +28,7 @@ licensed and keep their license file next to them.
|
||||
| `assets/hdr/studio_small_09_512.hdr` | Studio Small 09: a small photo studio with octaboxes on a white infinity cyc, equirect HDR reduced to 512×256 (2×2 box filter, Radiance RLE); lights the Properties panel's material orbs | Sergej Majboroda (Poly Haven) | [Poly Haven release](https://polyhaven.com/a/studio_small_09), [1K Radiance HDR](https://dl.polyhaven.org/file/ph-assets/HDRIs/hdr/1k/studio_small_09_1k.hdr) (MD5 `d5d7eb9d26d341d6aa4d11c1a54fd97c`) | [CC0 1.0 Universal](https://creativecommons.org/publicdomain/zero/1.0/) |
|
||||
| `docs/brand/artcraft-*.svg`, `docs/brand/artcraft-*.png` | ArtCraft logo and mark | ArtCraft Team | storytold/craftrules `assets/brand/` | ArtCraft brand terms, not open source ([`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt)) |
|
||||
| `crates/formats/src/mesh_import/usd/fixtures/crafted-references.usdc` | Synthetic USDC class/reference/time-sample acceptance fixture | ArtCraft Team and craft-libs contributors | [Pinned generator and provenance](crates/formats/src/mesh_import/usd/fixtures/README.md) | MIT (`crates/formats/src/mesh_import/usd/fixtures/LICENSE-MIT`) |
|
||||
| `apps/texturecraft/src/xwayland_pen.rs` | Pen on Wayland opens the window through Xwayland: pen detection, the Xwayland decision and the X11 library check (adapted, reduced to the pen decision) | PhotoCraft contributors | storytold/photocraft `830316b775f1f6734498ac6e39fd1298955ff93f`: [`apps/photocraft/src/tablet.rs`](https://github.com/storytold/photocraft/blob/830316b775f1f6734498ac6e39fd1298955ff93f/apps/photocraft/src/tablet.rs), [`apps/photocraft/src/linux_libs.rs`](https://github.com/storytold/photocraft/blob/830316b775f1f6734498ac6e39fd1298955ff93f/apps/photocraft/src/linux_libs.rs) | MIT OR Apache-2.0 |
|
||||
|
||||
## Third-party assets compiled into the binary
|
||||
|
||||
@@ -52,6 +53,8 @@ time (nothing is bundled); see [docs/localization-parity.md](docs/localization-p
|
||||
| `xcap` | Windows screen pixel capture | https://github.com/nashaofu/xcap | Apache-2.0 |
|
||||
| `widestring` | Windows string handling through `xcap` | https://github.com/VoidStarKat/widestring-rs | MIT OR Apache-2.0 |
|
||||
| `x11rb` | X11 pointer and pixel capture | https://github.com/psychon/x11rb | MIT OR Apache-2.0 |
|
||||
| `x11rb-protocol` | X11 setup and Xauthority for the Linux pen startup probe | https://github.com/psychon/x11rb | MIT OR Apache-2.0 |
|
||||
| `rustix` | Linux socket and hostname APIs for the X11 setup probe | https://github.com/bytecodealliance/rustix | Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT |
|
||||
| `zbus` | Wayland desktop color-picker portal | https://github.com/z-galaxy/zbus | MIT |
|
||||
|
||||
## Procedural content (no asset files)
|
||||
|
||||
Generated
+4
@@ -5819,6 +5819,7 @@ dependencies = [
|
||||
name = "texturecraft"
|
||||
version = "0.6.1"
|
||||
dependencies = [
|
||||
"craft-host",
|
||||
"craft-image-codecs",
|
||||
"craft-menu",
|
||||
"craft-update",
|
||||
@@ -5829,6 +5830,7 @@ dependencies = [
|
||||
"log",
|
||||
"rfd",
|
||||
"ron",
|
||||
"rustix 1.1.6",
|
||||
"serde_json",
|
||||
"texturecraft-automation",
|
||||
"texturecraft-engine",
|
||||
@@ -5836,6 +5838,7 @@ dependencies = [
|
||||
"winit",
|
||||
"winresource",
|
||||
"winsafe",
|
||||
"x11rb-protocol",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6005,6 +6008,7 @@ dependencies = [
|
||||
"texturecraft-bake",
|
||||
"texturecraft-compose",
|
||||
"texturecraft-core",
|
||||
"texturecraft-formats",
|
||||
"texturecraft-geom",
|
||||
"texturecraft-texel",
|
||||
"wasm-bindgen-futures",
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 ArtCraft Team and the TextureCraft contributors
|
||||
Copyright (c) 2026 ArtCraft Team and the PhotoCraft contributors (adapted Linux pen and display probing code)
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
|
||||
@@ -12,6 +12,16 @@ Third-party material
|
||||
This product bundles third-party material under its own licenses, listed below. The per-file
|
||||
list (author, source, license) is in ATTRIBUTION.md.
|
||||
|
||||
PhotoCraft Linux pen and display probing code, adapted in apps/texturecraft/src/xwayland_pen.rs
|
||||
from storytold/photocraft at 830316b775f1f6734498ac6e39fd1298955ff93f.
|
||||
Copyright (c) 2026 ArtCraft Team and the PhotoCraft contributors.
|
||||
Licensed under the MIT License or the Apache License, Version 2.0, at your option
|
||||
(LICENSE-MIT, LICENSE-APACHE).
|
||||
|
||||
Linux X11 setup probe components:
|
||||
- rustix — Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT.
|
||||
- x11rb-protocol — MIT OR Apache-2.0. Copyright 2019 x11rb contributors.
|
||||
|
||||
Studio Small 09 HDR environment (assets/hdr/studio_small_09_512.hdr),
|
||||
by Sergej Majboroda (Poly Haven) — CC0-1.0.
|
||||
Source: https://polyhaven.com/a/studio_small_09 (1K HDR, reduced to 512x256).
|
||||
|
||||
+2
-2
@@ -82,7 +82,7 @@ The evidence column includes the November 16 scores for comparison.
|
||||
| UI/UX fidelity | ~75% | 20 | TBD | Layer targeting, the workspace, Bake Mode and export dialogs changed. Live task, layout, shortcut and accessibility checks remain. November 16 estimate ~65% |
|
||||
| File formats / interchange | ~70% | 10 | TBD | Shared import/export codecs, rebuilt UV persistence and linked `.mcmat` v3 have landed. Project/output contracts, `.spp` and destination-tool coverage remain open. November 16 estimate ~60% |
|
||||
| Hardware (GPU, pen, displays) | ~50% | 8 | TBD | One Windows GPU exercised; pen tilt, pressure across platforms and display coverage remain incomplete. November 16 estimate ~50% |
|
||||
| Localization | ~35% | 4 | TBD | Ten picker languages in source; optional shared catalogs/fonts and native-language review need current measurement. November 16 estimate ~35% |
|
||||
| Localization | ~35% | 4 | TBD | Eleven picker languages in source; optional shared catalogs/fonts and native-language review need current measurement. November 16 estimate ~35% |
|
||||
| Performance | ~45% | 10 | TBD | Main added dirty-region uploads, cheaper undo snapshots and faster glTF lookups. Establish response-time and memory budgets with representative large projects. November 16 estimate ~40% |
|
||||
| Stability | ~60% | 10 | TBD | The live baseline covered small save/reopen and undo/redo. Rebuilt UV layouts gained persistence checks. Recovery, large projects and long sessions remain open. November 16 estimate ~55% |
|
||||
| Platforms | ~70% | 3 | TBD | Desktop and web build paths exist. Nightly packaging and supervised signing workflows landed for Windows, Linux and macOS. Install, update and hardware checks remain. November 16 estimate ~65% |
|
||||
@@ -151,7 +151,7 @@ signed release installation remain outside the November 25 test evidence.
|
||||
|
||||
## Languages
|
||||
|
||||
The [picker](crates/ui-egui/src/i18n.rs) contains ten languages. Shared catalogs are optional at
|
||||
The [picker](crates/ui-egui/src/i18n.rs) contains eleven languages. Shared catalogs are optional at
|
||||
build time; missing entries fall back to English, and builds without catalogs offer English only.
|
||||
The older [coverage table](docs/localization-parity.md) predates catalog migration, so its “100%”
|
||||
rows are not a current measurement. The November 16 live audit ran an English build without external catalogs.
|
||||
|
||||
@@ -23,6 +23,8 @@ serde_json = { workspace = true }
|
||||
log = { workspace = true }
|
||||
# The message box for errors that end the app (a Windows release build has no console).
|
||||
rfd = { workspace = true }
|
||||
# Pass the selected window backend to the title bar and UI runtime
|
||||
craft-host = { workspace = true }
|
||||
# Reads the saved System title bar setting before the window opens (eframe's settings format).
|
||||
ron = "0.12"
|
||||
|
||||
@@ -35,6 +37,12 @@ winsafe = { version = "0.0.29", default-features = false, features = ["user", "s
|
||||
# The update helper is a copy of this program (`main`).
|
||||
craft-update = { workspace = true }
|
||||
|
||||
# X11 setup probing and event loop selection for Wayland pen support
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
rustix = { workspace = true, features = ["net", "system"] }
|
||||
winit = { version = "0.30", default-features = false, features = ["x11"] }
|
||||
x11rb-protocol = "0.13"
|
||||
|
||||
# Quit (Cmd+Q) asks about unsaved changes (src/main.rs); winit's own Quit does not.
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
craft-menu = { workspace = true }
|
||||
|
||||
@@ -15,6 +15,8 @@ mod nightly_session;
|
||||
mod process_identity;
|
||||
mod profile_root;
|
||||
mod window_frame;
|
||||
#[cfg(target_os = "linux")]
|
||||
mod xwayland_pen;
|
||||
|
||||
use std::ffi::OsString;
|
||||
|
||||
@@ -334,8 +336,7 @@ fn launch_arguments(arguments: Vec<OsString>) -> Result<Vec<String>, String> {
|
||||
}
|
||||
|
||||
fn main() {
|
||||
// Windows: the update helper is a copy of this program started with `--finish-update`. A
|
||||
// Nightly install is updated by ArtCraft Launcher, so it never installs an update itself.
|
||||
// Stable handles --finish-update on Windows while the launcher updates Nightly
|
||||
#[cfg(windows)]
|
||||
if build_flavor::COMPILED == build_flavor::BuildFlavor::Stable
|
||||
&& let Some(result) = craft_update::self_update::finish(&texturecraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::<Vec<_>>())
|
||||
@@ -343,15 +344,16 @@ fn main() {
|
||||
std::process::exit(i32::from(result.is_err()));
|
||||
}
|
||||
|
||||
// Windows: the eyedropper's pointer keeper (screen_pick) is a copy of this program started with
|
||||
// its own argument. It reads no user state and is started without the profile tokens, so it
|
||||
// runs before the launch protocol would refuse it.
|
||||
// Dispatch the Windows pointer keeper before launch validation because it has no profile tokens
|
||||
#[cfg(windows)]
|
||||
if std::env::args_os().nth(1).is_some_and(|arg| arg == texturecraft_ui_egui::screen_pick::KEEPER_ARG) {
|
||||
std::process::exit(texturecraft_ui_egui::screen_pick::keep_pointer());
|
||||
}
|
||||
|
||||
let Some(arguments) = prepare_launch() else { return };
|
||||
let Some(arguments) = prepare_launch() else {
|
||||
return;
|
||||
};
|
||||
|
||||
let nightly = launch_profile::current().is_nightly();
|
||||
let args = match launch_arguments(arguments).and_then(parse_args_from) {
|
||||
Ok(Some(a)) => a,
|
||||
@@ -361,8 +363,8 @@ fn main() {
|
||||
std::process::exit(2);
|
||||
}
|
||||
};
|
||||
// The control server is a stable-install service: a Nightly window is driven by the Launcher,
|
||||
// and its token file would sit in the shared temp folder rather than its private profile.
|
||||
|
||||
// Keep the control token out of the shared temp folder for a private Nightly profile
|
||||
if nightly && args.control.is_some() {
|
||||
eprintln!("texturecraft: TextureCraft Nightly cannot start a control server (--control); use the stable app or texturecraft-cli");
|
||||
std::process::exit(2);
|
||||
@@ -377,9 +379,8 @@ fn main() {
|
||||
previous_hook(info);
|
||||
}));
|
||||
|
||||
// Scripted runs use temporary files so they cannot overwrite saved settings. Otherwise eframe
|
||||
// is told the file explicitly, so `with_app_id` cannot move Stable's `app.ron` out of the
|
||||
// folder `storage_dir` keeps `ui.json` and `errors.log` in (see `settings_folder`).
|
||||
// Scripted runs use temporary files to protect saved settings
|
||||
// An explicit eframe path keeps app.ron with ui.json and errors.log despite the app ID
|
||||
let no_prefs_path =
|
||||
std::env::var_os("TEXTURECRAFT_NO_PREFS").map(|_| std::env::temp_dir().join(format!("texturecraft-noprefs-{}.ron", std::process::id())));
|
||||
let persistence_path = no_prefs_path.clone().or_else(|| storage_dir().map(|dir| dir.join("app.ron")));
|
||||
@@ -393,8 +394,16 @@ fn main() {
|
||||
prefs.apply_work_threads();
|
||||
prefs.apply_resource_limits();
|
||||
let session = initial_session(&args);
|
||||
let frame_decision = TitleBar::decide(prefs.system_title_bar);
|
||||
|
||||
// Xwayland can forward pen input as pointer events on Wayland desktops
|
||||
#[cfg(target_os = "linux")]
|
||||
let use_xwayland_for_pen = xwayland_pen::opens_through_xwayland();
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
let use_xwayland_for_pen = false;
|
||||
let backend = if use_xwayland_for_pen { craft_host::target::Backend::X11 } else { craft_host::target::Backend::from_env() };
|
||||
let frame_decision = TitleBar::decide(prefs.system_title_bar, backend);
|
||||
let title_bar = TitleBar::of(&frame_decision.frame);
|
||||
|
||||
let mut viewport = egui::ViewportBuilder::default()
|
||||
.with_app_id(os_window::app_id())
|
||||
.with_title(os_window::name())
|
||||
@@ -403,15 +412,32 @@ fn main() {
|
||||
if let Some(i) = icon() {
|
||||
viewport = viewport.with_icon(i);
|
||||
}
|
||||
|
||||
let viewport = texturecraft_ui_egui::titlebar::viewport(&frame_decision, viewport);
|
||||
let mut options = eframe::NativeOptions { viewport, renderer: eframe::Renderer::Wgpu, persistence_path, ..Default::default() };
|
||||
#[cfg(target_os = "linux")]
|
||||
if use_xwayland_for_pen {
|
||||
use winit::platform::x11::EventLoopBuilderExtX11 as _;
|
||||
|
||||
options.event_loop_builder = Some(Box::new(|builder| {
|
||||
builder.with_x11();
|
||||
}));
|
||||
let notice = texturecraft_ui_egui::i18n::trf(
|
||||
"Opening the window through Xwayland for pen input. Set {variable}=1 to keep Wayland.",
|
||||
&[("variable", &xwayland_pen::NATIVE_WAYLAND_VARIABLE)],
|
||||
);
|
||||
eprintln!("texturecraft: {notice}");
|
||||
}
|
||||
|
||||
if let Err(e) = gpu::configure(&mut options, args.gpu, args.power_pref) {
|
||||
fatal(&e.to_string(), true);
|
||||
std::process::exit(2);
|
||||
}
|
||||
|
||||
let control = args.control;
|
||||
// The Nightly session record: one owner per profile, an unclean exit reported by the next
|
||||
// start, and no document name, path or diagnostic payload collected.
|
||||
|
||||
// Nightly records one owner per profile so the next launch can report an unclean exit
|
||||
// The record carries no document name, path or diagnostics
|
||||
let (nightly_session, session_health_warning) = match nightly_session::Session::begin_with_health(
|
||||
launch_profile::current().root(),
|
||||
build_flavor::BUILT_VERSION,
|
||||
@@ -424,12 +450,13 @@ fn main() {
|
||||
}
|
||||
};
|
||||
let previous_nightly_unclean = nightly_session.as_ref().is_some_and(nightly_session::Session::previous_unclean);
|
||||
// Set once a window has posted the interruption notice; until then the record must survive.
|
||||
|
||||
// Keep the record until a window has posted the interruption notice
|
||||
let unclean_notice_shown = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let notice_shown_in_window = unclean_notice_shown.clone();
|
||||
let nightly_session: nightly_session::Shared = std::sync::Arc::new(std::sync::Mutex::new(nightly_session));
|
||||
// The exit hook is the controlled return on macOS, where every quit ends the process inside
|
||||
// AppKit's terminate and `run_native` never returns. Elsewhere the return path below finishes.
|
||||
|
||||
// AppKit terminates the process without returning from run_native, so macOS needs the exit hook
|
||||
let finish_at_exit = {
|
||||
let shared = nightly_session.clone();
|
||||
let shown = unclean_notice_shown.clone();
|
||||
@@ -450,7 +477,8 @@ fn main() {
|
||||
if let Err(e) = craft_menu::mac::install_app_menu(&cc.egui_ctx, window_name) {
|
||||
log::warn!("the app menu could not be installed: {e}");
|
||||
}
|
||||
texturecraft_ui_egui::framework::install(&cc.egui_ctx, frame_decision)?;
|
||||
|
||||
texturecraft_ui_egui::framework::install(&cc.egui_ctx, frame_decision, backend)?;
|
||||
let frame_guard = window_frame::service(cc, matches!(title_bar, TitleBar::App(_)));
|
||||
let mut app = TextureCraftApp::new(cc, session);
|
||||
app.title_bar = title_bar;
|
||||
@@ -470,8 +498,8 @@ fn main() {
|
||||
Ok(Box::new(Shell { app, window_frame: frame_guard, exit_hook: Some(Box::new(finish_at_exit)) }))
|
||||
}),
|
||||
);
|
||||
// A controlled return, including a handled startup error. On macOS a window already finished in
|
||||
// its exit hook, so this is then a no-op.
|
||||
|
||||
// Close the session record on controlled return, including handled startup errors
|
||||
nightly_session::finish_once(&nightly_session, unclean_notice_shown.load(std::sync::atomic::Ordering::Relaxed));
|
||||
if let Err(e) = result {
|
||||
fatal(&e.to_string(), true);
|
||||
|
||||
@@ -0,0 +1,264 @@
|
||||
//! A pen on a Wayland desktop opens the window through Xwayland (#816).
|
||||
//!
|
||||
//! Copyright (c) 2026 ArtCraft Team and the PhotoCraft contributors for the adapted code.
|
||||
//! Licensed under the MIT License or the Apache License, Version 2.0, at your option.
|
||||
//!
|
||||
//! Wayland compositors give a pen only to clients that bind the tablet protocol (`zwp_tablet_v2`),
|
||||
//! which winit 0.30 doesn't (and binding it on winit's connection needs `unsafe`, which this app
|
||||
//! forbids). Some compositors (KWin) then send the window nothing from the pen: no cursor, no
|
||||
//! painting. Xwayland binds the protocol and serves the pen as an X11 pointer, so with a pen
|
||||
//! attached the window opens there. `TEXTURECRAFT_NATIVE_WAYLAND=1` keeps native Wayland.
|
||||
//!
|
||||
//! Adapted from PhotoCraft (storytold/photocraft `830316b7`, MIT OR Apache-2.0):
|
||||
//! `apps/photocraft/src/tablet.rs` (`display_session`, `pen_needs_xwayland`, `has_pen`, `bit_set`)
|
||||
//! and `apps/photocraft/src/linux_libs.rs` (`session_from_env`, `ldconfig_has`, the library
|
||||
//! search), reduced to the pen decision. See the repository's NOTICE for the port.
|
||||
|
||||
use std::io::{Read as _, Write as _};
|
||||
use std::os::unix::net::UnixStream;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use x11rb_protocol::connect::Connect;
|
||||
use x11rb_protocol::xauth::{Family, get_auth};
|
||||
|
||||
/// Set (and not `0`) to keep native Wayland with a pen attached
|
||||
pub(super) const NATIVE_WAYLAND_VARIABLE: &str = "TEXTURECRAFT_NATIVE_WAYLAND";
|
||||
|
||||
/// `BTN_TOOL_PEN` (linux/input-event-codes.h): the key a tablet's stylus, a pen display's or a
|
||||
/// pen-enabled touchscreen's pen reports
|
||||
const BTN_TOOL_PEN: u32 = 0x140;
|
||||
|
||||
/// `ABS_X` and `ABS_Y` (linux/input-event-codes.h): the absolute axes every pen reports
|
||||
const ABS_X: u32 = 0x00;
|
||||
const ABS_Y: u32 = 0x01;
|
||||
|
||||
/// What winit 0.30 loads at run time for an X11 window: Xlib, Xlib-xcb, xcb, Xcursor, XInput2 and
|
||||
/// xkbcommon with its X11 part
|
||||
const X11_LIBRARIES: &[&str] =
|
||||
&["libX11.so.6", "libX11-xcb.so.1", "libxcb.so.1", "libXcursor.so.1", "libXi.so.6", "libxkbcommon.so.0", "libxkbcommon-x11.so.0"];
|
||||
|
||||
// Give local Xwayland time to answer while bounding the wait before falling back to Wayland
|
||||
const X11_SETUP_TIMEOUT: Duration = Duration::from_secs(1);
|
||||
|
||||
/// Whether the window opens through Xwayland: a pen is attached on a Wayland desktop and Xwayland
|
||||
/// has the required libraries and accepts an X11 client setup.
|
||||
pub fn opens_through_xwayland() -> bool {
|
||||
let var = |name: &str| std::env::var(name).ok();
|
||||
let pen = || std::fs::read_to_string("/proc/bus/input/devices").is_ok_and(|devices| has_pen(&devices));
|
||||
pen_needs_xwayland(var, pen, |display| x11_libraries_available() && x_server_accepts_setup(display))
|
||||
}
|
||||
|
||||
/// [`opens_through_xwayland`]'s decision. winit picks Wayland when `WAYLAND_DISPLAY` or
|
||||
/// `WAYLAND_SOCKET` is set; Xwayland needs `DISPLAY`. The system probes run only on Wayland.
|
||||
fn pen_needs_xwayland(var: impl Fn(&str) -> Option<String>, pen: impl FnOnce() -> bool, xwayland_ready: impl FnOnce(&str) -> bool) -> bool {
|
||||
let set = |name: &str| var(name).is_some_and(|value| !value.is_empty());
|
||||
let wayland = set("WAYLAND_DISPLAY") || set("WAYLAND_SOCKET");
|
||||
let keeps_wayland = var(NATIVE_WAYLAND_VARIABLE).is_some_and(|value| !value.is_empty() && value != "0");
|
||||
wayland && !keeps_wayland && var("DISPLAY").filter(|display| !display.is_empty()).is_some_and(|display| pen() && xwayland_ready(&display))
|
||||
}
|
||||
|
||||
/// winit commits to its forced backend, so require an accepted X11 setup before forcing X11.
|
||||
fn x_server_accepts_setup(display: &str) -> bool {
|
||||
let Some((display_number, screen)) = local_display(display) else {
|
||||
return false;
|
||||
};
|
||||
|
||||
let Some(socket) = connect_local_x_server(display_number) else {
|
||||
return false;
|
||||
};
|
||||
|
||||
let hostname = rustix::system::uname();
|
||||
let auth_hostname = std::env::var_os("XAUTHLOCALHOSTNAME");
|
||||
let auth_address = auth_hostname.as_ref().map_or(hostname.nodename().to_bytes(), |name| name.as_encoded_bytes());
|
||||
let (auth_name, auth_data) = get_auth(Family::LOCAL, auth_address, display_number).ok().flatten().unwrap_or_default();
|
||||
let (setup, request) = Connect::with_authorization(auth_name, auth_data);
|
||||
exchange_x11_setup(socket, setup, &request, screen)
|
||||
}
|
||||
|
||||
/// Parse the display and screen of a local X server such as `:0`, `:0.0` or `unix:0`.
|
||||
fn local_display(display: &str) -> Option<(u16, usize)> {
|
||||
let local = display.strip_prefix(':').or_else(|| display.strip_prefix("unix:"))?;
|
||||
let (display_number, screen) = local.split_once('.').unwrap_or((local, "0"));
|
||||
Some((display_number.parse().ok()?, screen.parse().ok()?))
|
||||
}
|
||||
|
||||
fn connect_local_x_server(display_number: u16) -> Option<UnixStream> {
|
||||
use rustix::net::{AddressFamily, SocketAddrUnix, SocketFlags, SocketType, connect, socket_with};
|
||||
|
||||
let path = format!("/tmp/.X11-unix/X{display_number}");
|
||||
|
||||
// Try the abstract socket first, as Xlib does on Linux
|
||||
[SocketAddrUnix::new_abstract_name(path.as_bytes()), SocketAddrUnix::new(&path)].into_iter().find_map(|address| {
|
||||
let address = address.ok()?;
|
||||
|
||||
// A full Unix socket backlog must not block app startup
|
||||
let socket = UnixStream::from(socket_with(AddressFamily::UNIX, SocketType::STREAM, SocketFlags::NONBLOCK | SocketFlags::CLOEXEC, None).ok()?);
|
||||
connect(&socket, &address).ok()?;
|
||||
socket.set_nonblocking(false).ok()?;
|
||||
Some(socket)
|
||||
})
|
||||
}
|
||||
|
||||
fn exchange_x11_setup(mut socket: UnixStream, mut setup: Connect, request: &[u8], screen: usize) -> bool {
|
||||
let start = Instant::now();
|
||||
if socket.set_write_timeout(Some(X11_SETUP_TIMEOUT)).is_err() || socket.write_all(request).is_err() {
|
||||
return false;
|
||||
}
|
||||
|
||||
while !setup.buffer().is_empty() {
|
||||
let remaining = X11_SETUP_TIMEOUT.saturating_sub(start.elapsed());
|
||||
if remaining.is_zero() || socket.set_read_timeout(Some(remaining)).is_err() {
|
||||
return false;
|
||||
}
|
||||
|
||||
let Ok(received) = socket.read(setup.buffer()) else {
|
||||
return false;
|
||||
};
|
||||
|
||||
if received == 0 {
|
||||
return false;
|
||||
}
|
||||
|
||||
if setup.advance(received) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
setup.into_setup().is_ok_and(|reply| screen < reply.roots.len())
|
||||
}
|
||||
|
||||
/// Is a pen among the input devices `/proc/bus/input/devices` lists? A pen's `B: KEY=` bitmap has
|
||||
/// `BTN_TOOL_PEN` and its `B: ABS=` bitmap has `ABS_X` and `ABS_Y`, as libinput asks of a tablet
|
||||
/// tool. The key alone isn't enough: a virtual keyboard made with uinput claims every key code.
|
||||
fn has_pen(devices: &str) -> bool {
|
||||
devices.split("\n\n").any(|device| {
|
||||
let bitmap = |name: &str| device.lines().find_map(|line| line.strip_prefix(name));
|
||||
bitmap("B: KEY=").is_some_and(|keys| bit_set(keys, BTN_TOOL_PEN)) && bitmap("B: ABS=").is_some_and(|axes| bit_set(axes, ABS_X) && bit_set(axes, ABS_Y))
|
||||
})
|
||||
}
|
||||
|
||||
/// Bit `bit` of a `/proc/bus/input/devices` bitmap: hex words of the kernel's `long`, most
|
||||
/// significant first. Short or malformed bitmaps have no bits set.
|
||||
fn bit_set(bitmap: &str, bit: u32) -> bool {
|
||||
let word_bits = usize::BITS;
|
||||
let word = usize::try_from(bit / word_bits).unwrap_or(usize::MAX);
|
||||
bitmap.split_whitespace().rev().nth(word).and_then(|hex| u64::from_str_radix(hex, 16).ok()).is_some_and(|value| (value >> (bit % word_bits)) & 1 == 1)
|
||||
}
|
||||
|
||||
/// Are the libraries an X11 window needs installed? The linker cache (`ldconfig -p`) or the usual
|
||||
/// library directories must list each; one that can't be found counts as missing.
|
||||
fn x11_libraries_available() -> bool {
|
||||
let cache = linker_cache();
|
||||
let dirs = library_dirs(std::env::var("LD_LIBRARY_PATH").ok().as_deref());
|
||||
X11_LIBRARIES.iter().all(|soname| cache.as_deref().is_some_and(|cache| ldconfig_has(cache, soname)) || dirs.iter().any(|dir| dir.join(soname).exists()))
|
||||
}
|
||||
|
||||
/// `ldconfig -p` in English (it is parsed), from where distributions put it
|
||||
fn linker_cache() -> Option<String> {
|
||||
["/sbin/ldconfig", "/usr/sbin/ldconfig", "ldconfig"].into_iter().find_map(|command| {
|
||||
let output = std::process::Command::new(command).arg("-p").env("LC_ALL", "C").output().ok()?;
|
||||
output.status.success().then(|| String::from_utf8_lossy(&output.stdout).into_owned())
|
||||
})
|
||||
}
|
||||
|
||||
/// Does an `ldconfig -p` listing have `soname` for this build's architecture? Lines look like
|
||||
/// `\tlibXi.so.6 (libc6,x86-64) => /lib/x86_64-linux-gnu/libXi.so.6`.
|
||||
fn ldconfig_has(cache: &str, soname: &str) -> bool {
|
||||
let architecture = if cfg!(target_arch = "x86_64") {
|
||||
Some("x86-64")
|
||||
} else if cfg!(target_arch = "aarch64") {
|
||||
Some("AArch64")
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
cache.lines().any(|line| {
|
||||
let Some((name, rest)) = line.trim_start().split_once(' ') else {
|
||||
return false;
|
||||
};
|
||||
|
||||
let flags = rest.split_once('(').and_then(|(_, after)| after.split_once(')')).map_or("", |(flags, _)| flags);
|
||||
name == soname && architecture.is_none_or(|tag| flags.split(',').any(|flag| flag.trim() == tag))
|
||||
})
|
||||
}
|
||||
|
||||
/// `LD_LIBRARY_PATH`, then the usual system and Flatpak library directories
|
||||
fn library_dirs(ld_library_path: Option<&str>) -> Vec<PathBuf> {
|
||||
let triplet = if cfg!(target_arch = "aarch64") { "aarch64-linux-gnu" } else { "x86_64-linux-gnu" };
|
||||
let mut dirs: Vec<PathBuf> = ld_library_path.into_iter().flat_map(|value| value.split(':')).filter(|dir| !dir.is_empty()).map(PathBuf::from).collect();
|
||||
dirs.extend(["/app/lib", "/usr/local/lib", "/usr/lib64", "/lib64", "/usr/lib", "/lib"].map(PathBuf::from));
|
||||
dirs.extend([Path::new("/usr/lib").join(triplet), Path::new("/lib").join(triplet)]);
|
||||
dirs
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
// Capabilities from /proc/bus/input/devices for a touchpad and a Wacom pen
|
||||
const TOUCHPAD: &str = "N: Name=\"SYNA2B33:00 06CB:CE26 Touchpad\"\nB: KEY=e520 10000 0 0 0 0\nB: ABS=2e0800000000003\n";
|
||||
const PEN: &str = "N: Name=\"Wacom Intuos Pro M Pen\"\nB: KEY=1c03 0 0 0 0 0\nB: ABS=1000f000003\n";
|
||||
|
||||
// The uinput keyboard claims the pen key but reports no axes
|
||||
const VIRTUAL_KEYBOARD: &str = "N: Name=\"RustDesk UInput Keyboard\"\nB: EV=20013\nB: KEY=ffffffffff 0 7ffffff000301ff 1000f7fffffff 7fe001fffff000f 7ffffffffffffff ffffffff0003fdff 7fff8fff00ff03ff 1ffffffffffff07 ffffffffffffffff ffffffffffefffff fffffffffffffffe\n";
|
||||
|
||||
#[test]
|
||||
fn a_pen_is_a_device_with_the_pen_key_and_absolute_axes() {
|
||||
assert!(has_pen(&format!("{TOUCHPAD}\n{PEN}")));
|
||||
assert!(!has_pen(TOUCHPAD), "a touchpad is no pen");
|
||||
assert!(!has_pen(&format!("{VIRTUAL_KEYBOARD}\n{TOUCHPAD}")), "a keyboard claiming the pen key has no pen axes");
|
||||
assert!(!has_pen("B: KEY=zz 0 0 0 0 0\nB: ABS=3\n"), "a malformed bitmap is no pen");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pen_on_wayland_opens_the_window_through_xwayland() {
|
||||
fn env(pairs: &'static [(&'static str, &'static str)]) -> impl Fn(&str) -> Option<String> {
|
||||
move |name: &str| pairs.iter().find(|(key, _)| *key == name).map(|(_, value)| value.to_string())
|
||||
}
|
||||
const WAYLAND: &[(&str, &str)] = &[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0")];
|
||||
|
||||
assert!(pen_needs_xwayland(env(WAYLAND), || true, |display| display == ":0"));
|
||||
assert!(!pen_needs_xwayland(env(WAYLAND), || false, |_| true), "no pen");
|
||||
assert!(!pen_needs_xwayland(env(WAYLAND), || true, |_| false), "Xwayland can't run the window");
|
||||
assert!(!pen_needs_xwayland(env(&[("WAYLAND_DISPLAY", "wayland-0")]), || true, |_| true), "no Xwayland");
|
||||
assert!(!pen_needs_xwayland(env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0"), (NATIVE_WAYLAND_VARIABLE, "1")]), || true, |_| true), "kept");
|
||||
assert!(pen_needs_xwayland(env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0"), (NATIVE_WAYLAND_VARIABLE, "0")]), || true, |_| true));
|
||||
assert!(!pen_needs_xwayland(env(&[("DISPLAY", ":0")]), || panic!("probed off Wayland"), |_| panic!("probed off Wayland")), "X11 already has the pen");
|
||||
assert_eq!([":1.2", "unix:0", "remote:0", ":0.bad"].map(local_display), [Some((1, 2)), Some((0, 0)), None, None]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pen_keeps_wayland_when_the_x_server_rejects_setup() -> std::io::Result<()> {
|
||||
use x11rb_protocol::protocol::xproto::{Screen, Setup, SetupFailed};
|
||||
use x11rb_protocol::x11_utils::Serialize as _;
|
||||
|
||||
const REPLY_HEADER_BYTES: usize = 8;
|
||||
const BYTES_PER_X11_WORD: usize = 4;
|
||||
let reason = b"Setup denied".to_vec();
|
||||
let rejected = SetupFailed { protocol_major_version: 11, length: (reason.len() / BYTES_PER_X11_WORD) as u16, reason, ..Default::default() };
|
||||
let mut accepted = Setup { status: 1, protocol_major_version: 11, roots: vec![Screen::default()], ..Default::default() };
|
||||
accepted.length = ((accepted.serialize().len() - REPLY_HEADER_BYTES) / BYTES_PER_X11_WORD) as u16;
|
||||
|
||||
for (reply, screen, selects_xwayland) in [(rejected.serialize(), 0, false), (accepted.serialize(), 1, false), (accepted.serialize(), 0, true)] {
|
||||
let (client, mut server) = UnixStream::pair()?;
|
||||
server.write_all(&reply)?;
|
||||
let (setup, request) = Connect::with_authorization(Vec::new(), Vec::new());
|
||||
let var = |name: &str| match name {
|
||||
"WAYLAND_DISPLAY" => Some("wayland-0".into()),
|
||||
"DISPLAY" => Some(format!(":0.{screen}")),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
let xwayland = pen_needs_xwayland(
|
||||
var,
|
||||
|| true,
|
||||
|display| local_display(display).is_some_and(|(_, screen)| exchange_x11_setup(client, setup, &request, screen)),
|
||||
);
|
||||
|
||||
assert_eq!(xwayland, selects_xwayland);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -225,9 +225,9 @@ impl Headless {
|
||||
|
||||
/// Export the working mesh to `path` (obj, glb, usda, usdc or usdz, from `format` or the
|
||||
/// extension); obj writes its .mtl and textures, usda and usdc their textures, next to it.
|
||||
pub fn export_mesh(&mut self, path: &str, format: Option<&str>) -> Result<Value, AutomationError> {
|
||||
pub fn export_mesh(&mut self, path: &str, format: Option<&str>, recompute_normals: bool) -> Result<Value, AutomationError> {
|
||||
self.require_project()?;
|
||||
let out = self.session.mesh_export(path, format)?;
|
||||
let out = self.session.mesh_export_with_normals(path, format, recompute_normals)?;
|
||||
let dir = Path::new(&out.path).parent().and_then(|d| d.to_str()).filter(|d| !d.is_empty()).unwrap_or(".");
|
||||
self.create_dir_all(dir)?;
|
||||
let mut textures = Vec::new();
|
||||
|
||||
@@ -4,8 +4,9 @@
|
||||
//!
|
||||
//! Methods: the app's `ping`, `command.run {id, params?}`, `command.list {filter?}`,
|
||||
//! `session.inspect`, plus `command.batch {steps}`, `project.open {path}`,
|
||||
//! `project.save {path?}`, `mesh.import {path, resolution?, name?}`, `mesh.reimport {path?,
|
||||
//! preserveStrokes?}`, `mesh.export {path, format?}`, `bake.mesh.add {path, cage?}`,
|
||||
//! `project.save {path?}`, `mesh.import {path, resolution?, name?}`,
|
||||
//! `mesh.reimport {path?, preserveStrokes?}`, `mesh.export {path, format?, recomputeNormals?}`,
|
||||
//! `bake.mesh.add {path, cage?}`,
|
||||
//! `resource.import {path}`, `material.save {path, layer?, name?}`, `material.load {path}`
|
||||
//! (workspace-scoped versions of the engine commands),
|
||||
//! `textures.export {dir, …}`, `render {view?, width?, height?, yaw?, pitch?}` (PNG base64, the
|
||||
@@ -88,13 +89,14 @@ impl Headless {
|
||||
if steps.len() > MAX_BATCH_STEPS {
|
||||
return Err(bad(format!("at most {MAX_BATCH_STEPS} steps per batch")));
|
||||
}
|
||||
|
||||
Ok(self.batch(steps))
|
||||
}
|
||||
"project.open" => self.open(required(p, "path")?),
|
||||
"project.save" => self.save(str_of(p, "path")),
|
||||
"mesh.import" => self.import_mesh(required(p, "path")?, u32_of(p, "resolution")?, str_of(p, "name")),
|
||||
"mesh.reimport" => self.reimport_mesh(str_of(p, "path"), bool_of(p, "preserveStrokes")?),
|
||||
"mesh.export" => self.export_mesh(required(p, "path")?, str_of(p, "format")),
|
||||
"mesh.export" => self.export_mesh(required(p, "path")?, str_of(p, "format"), bool_of(p, "recomputeNormals")?),
|
||||
"bake.mesh.add" => self.add_bake_mesh(required(p, "path")?, bool_of(p, "cage")?),
|
||||
"resource.import" => self.import_resource(required(p, "path")?),
|
||||
"material.save" => self.material_save(p),
|
||||
|
||||
@@ -141,6 +141,9 @@ pub struct MeshExportParams {
|
||||
/// written next to it) or usdz (textures packaged); default: from the extension, else obj.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub format: Option<String>,
|
||||
/// Replace stored normals with smooth area-weighted normals on the exported copy (default false).
|
||||
#[serde(default, rename = "recomputeNormals", skip_serializing_if = "Option::is_none")]
|
||||
pub recompute_normals: Option<bool>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
|
||||
|
||||
@@ -132,6 +132,13 @@ const HOST_PATH_KEYS: [&str; 2] = ["path", "dir"];
|
||||
|
||||
/// Refuses engine commands that would reach host paths around the workspace roots, so clients use the workspace tools
|
||||
pub fn authorize_command(id: &str, params: &Value) -> Result<(), AutomationError> {
|
||||
// The Resources Updater reads the files a project names, which may lie outside the read root
|
||||
if matches!(id, "resource.status" | "resource.update" | "resource.relink") {
|
||||
return Err(bad(format!(
|
||||
"`{id}` reads the image files the project names on this machine, so it is disabled for automation; re-import changed files with resource_import"
|
||||
)));
|
||||
}
|
||||
|
||||
let has_path = names_host_path(params) || params.get("files").and_then(Value::as_array).is_some_and(|files| files.iter().any(names_host_path));
|
||||
|
||||
// `file.save` is refused even without a path: a headless session's path is workspace-relative, not a host path
|
||||
@@ -245,6 +252,10 @@ mod tests {
|
||||
assert!(authorize_command("file.reimportMesh", &json!({"path": "/etc/x.obj"})).is_err());
|
||||
assert!(authorize_command("file.reimportMesh", &json!({})).is_ok());
|
||||
assert!(authorize_command("file.close", &json!({})).is_ok());
|
||||
for id in ["resource.status", "resource.update", "resource.relink"] {
|
||||
let error = authorize_command(id, &json!({})).unwrap_err().to_string();
|
||||
assert!(error.contains("reads the image files"), "{id}: {error}");
|
||||
}
|
||||
assert!(authorize_command("layer.add.fill", &json!({"color": "#ff0000", "path": null})).is_ok());
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use crate::cage::RayFrame;
|
||||
use crate::map::BakeContext;
|
||||
use crate::tracing::{CpuTracer, Tracer};
|
||||
use crate::{BakeError, BakeOutput, BakeRequest, MeshExtent, Progress};
|
||||
use crate::{BakeError, BakeOutput, BakeRequest, MeshExtent, Progress, RegionBake};
|
||||
use std::sync::atomic::Ordering::Relaxed;
|
||||
use texturecraft_core::{BakeSettings, BakedMap};
|
||||
|
||||
@@ -23,10 +23,22 @@ impl<'a> BakePasses<'a> {
|
||||
progress: &Progress,
|
||||
excluded_tiles: &[(u32, u32)],
|
||||
tracer: Option<&dyn Tracer>,
|
||||
) -> Result<BakeOutput, BakeError> {
|
||||
self.bake_map_in(map, progress, excluded_tiles, None, tracer)
|
||||
}
|
||||
|
||||
/// [`BakePasses::bake_map`] sampling only `region`'s texels, as [`crate::bake_tiles_in`] does
|
||||
pub fn bake_map_in(
|
||||
&mut self,
|
||||
map: BakedMap,
|
||||
progress: &Progress,
|
||||
excluded_tiles: &[(u32, u32)],
|
||||
region: Option<RegionBake>,
|
||||
tracer: Option<&dyn Tracer>,
|
||||
) -> Result<BakeOutput, BakeError> {
|
||||
let mut settings = self.request.settings.clone();
|
||||
settings.maps.select([map]);
|
||||
self.run(&settings, progress, excluded_tiles, tracer, super::STRIP_TEXELS)
|
||||
self.run(&settings, progress, excluded_tiles, region, tracer, super::STRIP_TEXELS)
|
||||
}
|
||||
|
||||
pub(super) fn run(
|
||||
@@ -34,6 +46,7 @@ impl<'a> BakePasses<'a> {
|
||||
settings: &BakeSettings,
|
||||
progress: &Progress,
|
||||
excluded_tiles: &[(u32, u32)],
|
||||
region: Option<RegionBake>,
|
||||
tracer: Option<&dyn Tracer>,
|
||||
strip_texels: usize,
|
||||
) -> Result<BakeOutput, BakeError> {
|
||||
@@ -56,7 +69,7 @@ impl<'a> BakePasses<'a> {
|
||||
}
|
||||
};
|
||||
let context = BakeContext::with_frame(&request, *extent, frame);
|
||||
let bake = |tracer: &dyn Tracer| super::bake_prepared(&request, &context, progress, strip_texels, tracer, excluded_tiles);
|
||||
let bake = |tracer: &dyn Tracer| super::bake_prepared(&request, &context, progress, strip_texels, tracer, excluded_tiles, region);
|
||||
match tracer {
|
||||
Some(tracer) => match bake(tracer) {
|
||||
Err(BakeError::Tracer(error)) => {
|
||||
|
||||
+55
-6
@@ -12,6 +12,8 @@ mod high_poly;
|
||||
mod mesh_extent;
|
||||
mod name_pair;
|
||||
mod progress;
|
||||
mod region_bake;
|
||||
mod texel_box;
|
||||
|
||||
pub use bake_error::BakeError;
|
||||
pub use bake_output::BakeOutput;
|
||||
@@ -22,6 +24,8 @@ pub use high_poly::HighPoly;
|
||||
pub(crate) use mesh_extent::MeshExtent;
|
||||
pub use name_pair::NamePair;
|
||||
pub use progress::Progress;
|
||||
pub use region_bake::{RegionBake, region_keeps_pixels};
|
||||
pub use texel_box::TexelBox;
|
||||
|
||||
mod map;
|
||||
mod skew;
|
||||
@@ -50,6 +54,8 @@ const STRIP_TEXELS: usize = 1 << 24;
|
||||
const BATCH: usize = 1 << 18;
|
||||
// Curvature batches stay small so progress and cancellation remain responsive
|
||||
const CURVATURE_BATCH: usize = 1 << 15;
|
||||
/// Smallest mesh extent the maps are normalized by, so a flat mesh never divides by zero
|
||||
const MIN_MESH_EXTENT: f32 = 1e-6;
|
||||
|
||||
fn validate(request: &BakeRequest) -> Result<(), BakeError> {
|
||||
let settings = request.settings;
|
||||
@@ -161,7 +167,18 @@ pub fn bake_on(request: &BakeRequest, progress: &Progress, tracer: &dyn Tracer)
|
||||
|
||||
/// Excluded atlas blocks produce no samples; their geometry still participates in ray tracing
|
||||
pub fn bake_tiles(request: &BakeRequest, progress: &Progress, excluded_tiles: &[(u32, u32)], tracer: Option<&dyn Tracer>) -> Result<BakeOutput, BakeError> {
|
||||
BakePasses::new(*request).run(request.settings, progress, excluded_tiles, tracer, STRIP_TEXELS)
|
||||
bake_tiles_in(request, progress, excluded_tiles, None, tracer)
|
||||
}
|
||||
|
||||
/// [`bake_tiles`] sampling only `region`'s texels and padding a whole map; equal to a whole bake for [`region_keeps_pixels`] maps
|
||||
pub fn bake_tiles_in(
|
||||
request: &BakeRequest,
|
||||
progress: &Progress,
|
||||
excluded_tiles: &[(u32, u32)],
|
||||
region: Option<RegionBake>,
|
||||
tracer: Option<&dyn Tracer>,
|
||||
) -> Result<BakeOutput, BakeError> {
|
||||
BakePasses::new(*request).run(request.settings, progress, excluded_tiles, region, tracer, STRIP_TEXELS)
|
||||
}
|
||||
|
||||
type OutRow<'a> = Vec<&'a mut [f32]>;
|
||||
@@ -173,8 +190,9 @@ fn bake_in_strips(
|
||||
strip_texels: usize,
|
||||
tracer: &dyn Tracer,
|
||||
excluded_tiles: &[(u32, u32)],
|
||||
region: Option<RegionBake>,
|
||||
) -> Result<BakeOutput, BakeError> {
|
||||
BakePasses::new(*request).run(request.settings, progress, excluded_tiles, Some(tracer), strip_texels)
|
||||
BakePasses::new(*request).run(request.settings, progress, excluded_tiles, region, Some(tracer), strip_texels)
|
||||
}
|
||||
|
||||
fn bake_prepared(
|
||||
@@ -184,6 +202,7 @@ fn bake_prepared(
|
||||
strip_texels: usize,
|
||||
tracer: &dyn Tracer,
|
||||
excluded_tiles: &[(u32, u32)],
|
||||
region: Option<RegionBake>,
|
||||
) -> Result<BakeOutput, BakeError> {
|
||||
if progress.cancel.load(Relaxed) {
|
||||
return Err(BakeError::Cancelled);
|
||||
@@ -211,7 +230,7 @@ fn bake_prepared(
|
||||
let mut padding_map = None;
|
||||
let total_rows = height.max(1) as u64;
|
||||
let mut rows_done = 0u64;
|
||||
let strip_error = || BakeError::Invalid("strip output of range".into());
|
||||
let strip_error = || BakeError::Invalid("strip output out of range".into());
|
||||
|
||||
let (sample_width, sample_height) = (width * samples_per_axis, height * samples_per_axis);
|
||||
let rows_per_strip = (strip_texels / (sample_width * samples_per_axis)).max(1).min(height);
|
||||
@@ -250,6 +269,16 @@ fn bake_prepared(
|
||||
}
|
||||
});
|
||||
|
||||
// Coverage stays the whole map's, so padding matches a whole bake; only the region is sampled
|
||||
if let Some(region) = region {
|
||||
for (row_index, row) in gbuffer.tri.chunks_mut(sample_width).enumerate() {
|
||||
let y = (sample_start_y + row_index) / samples_per_axis;
|
||||
for outside in region.texels.outside_row(y, samples_per_axis, row.len()) {
|
||||
row.get_mut(outside).unwrap_or_default().fill(NO_TRI);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut output_rows: Vec<OutRow> = (0..rows).map(|_| Vec::with_capacity(maps.len())).collect();
|
||||
for (map, data) in maps.iter().zip(buffers.iter_mut()) {
|
||||
let component_count = map.components();
|
||||
@@ -258,6 +287,7 @@ fn bake_prepared(
|
||||
row.push(chunk);
|
||||
}
|
||||
}
|
||||
|
||||
let mut bake_strip = || {
|
||||
for (batch_index, batch) in output_rows.chunks_mut(rows_per_batch).enumerate() {
|
||||
if progress.cancel.load(Relaxed) {
|
||||
@@ -276,10 +306,11 @@ fn bake_prepared(
|
||||
(width, samples_per_axis, sample_start_y * sample_width),
|
||||
)?;
|
||||
rows_done += batch.len() as u64;
|
||||
progress.done.store((rows_done.saturating_mul(10_000) / total_rows).min(10_000) as u32, Relaxed);
|
||||
progress.done.store((rows_done.saturating_mul(u64::from(Progress::DONE)) / total_rows).min(u64::from(Progress::DONE)) as u32, Relaxed);
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
|
||||
if strip_start + rows < height || (settings.common.dilation == 0 && !settings.common.apply_diffusion) {
|
||||
bake_strip()?;
|
||||
} else {
|
||||
@@ -291,6 +322,22 @@ fn bake_prepared(
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(region) = region {
|
||||
for (map, pixels) in maps.iter().zip(buffers.iter_mut()) {
|
||||
let previous = region.previous.get(map).filter(|previous| previous.len() == pixels.len());
|
||||
let previous = previous.ok_or_else(|| BakeError::Invalid(format!("no whole {} map of this size to bake a region of", map.id())))?;
|
||||
let components = map.components();
|
||||
let row_len = (width * components).max(1);
|
||||
for (y, (row, kept)) in pixels.chunks_exact_mut(row_len).zip(previous.chunks_exact(row_len)).enumerate() {
|
||||
for outside in region.texels.outside_row(y, components, row_len) {
|
||||
if let (Some(row), Some(kept)) = (row.get_mut(outside.clone()), kept.get(outside)) {
|
||||
row.copy_from_slice(kept);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut output: BTreeMap<BakedMap, Vec<f32>> = maps.into_iter().zip(buffers).collect();
|
||||
if from_normal {
|
||||
let world_normal =
|
||||
@@ -306,7 +353,8 @@ fn bake_prepared(
|
||||
}
|
||||
|
||||
let (bounds_min, bounds_max) = request.mesh.bounds();
|
||||
map::normalize(&mut output, &covered, width, tile_size, settings, (bounds_max - bounds_min).max_element().max(1e-6));
|
||||
map::normalize(&mut output, &covered, width, tile_size, settings, (bounds_max - bounds_min).max_element().max(MIN_MESH_EXTENT));
|
||||
|
||||
if let Some(padding_map) = padding_map {
|
||||
for (map, data) in output.iter_mut() {
|
||||
padding_map.apply(data, map.components());
|
||||
@@ -315,11 +363,12 @@ fn bake_prepared(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if progress.cancel.load(Relaxed) {
|
||||
return Err(BakeError::Cancelled);
|
||||
}
|
||||
|
||||
progress.done.store(10_000, Relaxed);
|
||||
progress.done.store(Progress::DONE, Relaxed);
|
||||
Ok(BakeOutput { resolution: width as u32, height: height as u32, maps: output, tracer: tracer.name() })
|
||||
}
|
||||
|
||||
|
||||
@@ -8,12 +8,15 @@ pub struct Progress {
|
||||
}
|
||||
|
||||
impl Progress {
|
||||
/// The basis points of a finished bake
|
||||
pub const DONE: u32 = 10_000;
|
||||
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
pub fn fraction(&self) -> f32 {
|
||||
self.done.load(Relaxed).min(10_000) as f32 / 10_000.0
|
||||
self.done.load(Relaxed).min(Self::DONE) as f32 / Self::DONE as f32
|
||||
}
|
||||
|
||||
pub fn cancel(&self) {
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
use texturecraft_core::BakedMap;
|
||||
|
||||
use crate::TexelBox;
|
||||
|
||||
/// A bake that samples only `texels` and takes every other texel from `previous`, a whole bake of the same size
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct RegionBake<'a> {
|
||||
pub texels: TexelBox,
|
||||
pub previous: &'a BTreeMap<BakedMap, Arc<Vec<f32>>>,
|
||||
}
|
||||
|
||||
/// Whether a region bake gives `map` a whole bake's pixels: not for maps scaled by their whole range or read from neighbours
|
||||
pub fn region_keeps_pixels(map: BakedMap) -> bool {
|
||||
!matches!(map, BakedMap::Curvature | BakedMap::Height | BakedMap::Thickness)
|
||||
}
|
||||
@@ -28,11 +28,13 @@ fn excluded_tiles_match_across_strips_antialiasing_and_cpu_fallback() {
|
||||
cage_paint: None,
|
||||
tiles: (2, 1),
|
||||
};
|
||||
|
||||
let full = bake(&request, &Progress::new()).unwrap();
|
||||
for excluded in [[(0, 0)], [(1, 0)]] {
|
||||
let partial = bake_tiles(&request, &Progress::new(), &excluded, None).unwrap();
|
||||
let strips = bake_in_strips(&request, &Progress::new(), 512, &CpuTracer, &excluded).unwrap();
|
||||
let strips = bake_in_strips(&request, &Progress::new(), 512, &CpuTracer, &excluded, None).unwrap();
|
||||
let fallback = bake_tiles(&request, &Progress::new(), &excluded, Some(&Broken)).unwrap();
|
||||
|
||||
assert_eq!(strips.maps, partial.maps);
|
||||
assert_eq!(fallback.maps, partial.maps);
|
||||
assert!(fallback.tracer.contains("Broken unavailable"));
|
||||
|
||||
+14
-12
@@ -365,9 +365,9 @@ fn two_runs_are_identical_and_sized() {
|
||||
|
||||
#[test]
|
||||
fn strips_match_a_single_pass() {
|
||||
let m = primitives::material_ball();
|
||||
let bvh = Bvh::new(&m);
|
||||
let s = with_rays(
|
||||
let mesh = primitives::material_ball();
|
||||
let bvh = Bvh::new(&mesh);
|
||||
let bake_settings = with_rays(
|
||||
{
|
||||
let mut base = settings(64, &[]);
|
||||
base.common = CommonBakeSettings { antialiasing: BakeAntialiasing::Subsampling2x2, ..base.common };
|
||||
@@ -377,24 +377,26 @@ fn strips_match_a_single_pass() {
|
||||
4,
|
||||
0.25,
|
||||
);
|
||||
let req = BakeRequest {
|
||||
let request = BakeRequest {
|
||||
low_base_color: &[],
|
||||
mesh: &m,
|
||||
mesh: &mesh,
|
||||
bvh: &bvh,
|
||||
material: 0,
|
||||
settings: &s,
|
||||
settings: &bake_settings,
|
||||
high: None,
|
||||
cage: None,
|
||||
skew: None,
|
||||
cage_paint: None,
|
||||
tiles: (1, 1),
|
||||
};
|
||||
let whole = bake(&req, &Progress::new()).unwrap();
|
||||
let strips = bake_in_strips(&req, &Progress::new(), 128 * 2, &CpuTracer, &[]).unwrap();
|
||||
for (map, a) in &whole.maps {
|
||||
let b = &strips.maps[map];
|
||||
let off = a.iter().zip(b).filter(|(a, b)| (*a - *b).abs() > 1e-3).count();
|
||||
assert!(off * 200 < a.len(), "{map:?}: {off} of {} differ", a.len());
|
||||
|
||||
let whole = bake(&request, &Progress::new()).unwrap();
|
||||
let strips = bake_in_strips(&request, &Progress::new(), 128 * 2, &CpuTracer, &[], None).unwrap();
|
||||
|
||||
for (map, whole_pixels) in &whole.maps {
|
||||
let strip_pixels = &strips.maps[map];
|
||||
let differences = whole_pixels.iter().zip(strip_pixels).filter(|(whole, strip)| (*whole - *strip).abs() > 1e-3).count();
|
||||
assert!(differences * 200 < whole_pixels.len(), "{map:?}: {differences} of {} differ", whole_pixels.len());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
use std::ops::Range;
|
||||
|
||||
/// A rectangle of output texels, from `min` (inclusive) to `max` (exclusive), in atlas pixels
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct TexelBox {
|
||||
pub min: (u32, u32),
|
||||
pub max: (u32, u32),
|
||||
}
|
||||
|
||||
impl TexelBox {
|
||||
/// Whether texel (`x`, `y`) lies inside the box
|
||||
pub fn contains(&self, x: usize, y: usize) -> bool {
|
||||
(self.min.0 as usize..self.max.0 as usize).contains(&x) && (self.min.1 as usize..self.max.1 as usize).contains(&y)
|
||||
}
|
||||
|
||||
/// The items of texel row `y` outside the box, in a row of `len` items with `scale` items per texel: those before the box and those after it
|
||||
pub fn outside_row(&self, y: usize, scale: usize, len: usize) -> [Range<usize>; 2] {
|
||||
let (start, end) = match (self.min.1 as usize..self.max.1 as usize).contains(&y) {
|
||||
true => ((self.min.0 as usize * scale).min(len), (self.max.0 as usize * scale).min(len)),
|
||||
false => (len, len),
|
||||
};
|
||||
[0..start, end.max(start)..len]
|
||||
}
|
||||
|
||||
/// The box grown by `texels` on every side, kept inside a `width` x `height` image
|
||||
pub fn grown(&self, texels: u32, width: u32, height: u32) -> TexelBox {
|
||||
TexelBox {
|
||||
min: (self.min.0.saturating_sub(texels), self.min.1.saturating_sub(texels)),
|
||||
max: (self.max.0.saturating_add(texels).min(width), self.max.1.saturating_add(texels).min(height)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_items_outside_a_row_are_the_ones_contains_leaves_out() {
|
||||
let (width, scale) = (6, 2);
|
||||
let boxes = [
|
||||
TexelBox { min: (1, 1), max: (4, 3) },
|
||||
TexelBox { min: (0, 0), max: (6, 4) },
|
||||
TexelBox { min: (3, 1), max: (9, 2) },
|
||||
TexelBox { min: (4, 1), max: (2, 3) },
|
||||
];
|
||||
for texels in boxes {
|
||||
for y in 0..4 {
|
||||
let outside = texels.outside_row(y, scale, width * scale);
|
||||
for item in 0..width * scale {
|
||||
let is_outside = outside.iter().any(|range| range.contains(&item));
|
||||
assert_eq!(is_outside, !texels.contains(item / scale, y), "{texels:?} row {y} item {item}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,9 +4,11 @@ mod ambient_occlusion_attenuation;
|
||||
mod ambient_occlusion_settings;
|
||||
mod backface_mode;
|
||||
mod bake_antialiasing;
|
||||
mod bake_change;
|
||||
mod bake_paint_target;
|
||||
mod bake_resolution;
|
||||
mod bake_settings;
|
||||
mod bake_source;
|
||||
mod bake_sync;
|
||||
mod bake_sync_group;
|
||||
mod mesh_match_mode;
|
||||
@@ -45,8 +47,10 @@ pub use ambient_occlusion_attenuation::AmbientOcclusionAttenuation;
|
||||
pub use ambient_occlusion_settings::AmbientOcclusionSettings;
|
||||
pub use backface_mode::BackfaceMode;
|
||||
pub use bake_antialiasing::BakeAntialiasing;
|
||||
pub use bake_change::BakeChange;
|
||||
pub use bake_resolution::BakeResolution;
|
||||
pub use bake_settings::BakeSettings;
|
||||
pub use bake_source::{BakeSource, fingerprint, fingerprint_words};
|
||||
pub use bake_sync::BakeSync;
|
||||
pub use bake_sync_group::BakeSyncGroup;
|
||||
pub use baked_map::BakedMap;
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// What changed since a mesh map was baked, which makes it out of date
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum BakeChange {
|
||||
LowPoly,
|
||||
HighPoly,
|
||||
Cage,
|
||||
Settings,
|
||||
MapSettings,
|
||||
}
|
||||
|
||||
impl BakeChange {
|
||||
/// Identifier in automation replies
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
BakeChange::LowPoly => "lowPoly",
|
||||
BakeChange::HighPoly => "highPoly",
|
||||
BakeChange::Cage => "cage",
|
||||
BakeChange::Settings => "settings",
|
||||
BakeChange::MapSettings => "mapSettings",
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
use super::BakeChange;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Fingerprints of what one mesh map was baked from: a later change to any of them shows the map out of date
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct BakeSource {
|
||||
/// The low poly's geometry
|
||||
pub low_poly: u64,
|
||||
/// The embedded mesh file when this map reads its material colors.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub low_material_file: Option<u64>,
|
||||
/// The high poly files, in list order (0: none, the set bakes from the low poly)
|
||||
pub high_poly: u64,
|
||||
/// The cage file (0: none)
|
||||
pub cage: u64,
|
||||
/// The settings every map of the set shares (size, high poly, cage, skew) and its UV tiles
|
||||
pub settings: u64,
|
||||
/// The map's own settings
|
||||
pub map_settings: u64,
|
||||
}
|
||||
|
||||
impl BakeSource {
|
||||
/// What differs in `current` from this record, in [`BakeChange`] order (empty: up to date)
|
||||
pub fn changes(&self, current: &BakeSource) -> Vec<BakeChange> {
|
||||
// Switching color source is already reported under high poly or map settings
|
||||
let material_changed = match (self.low_material_file, current.low_material_file) {
|
||||
(Some(previous), Some(now)) => previous != now,
|
||||
(None, None) => false,
|
||||
_ => self.high_poly == current.high_poly && self.map_settings == current.map_settings,
|
||||
};
|
||||
|
||||
[
|
||||
(self.low_poly != current.low_poly || material_changed, BakeChange::LowPoly),
|
||||
(self.high_poly != current.high_poly, BakeChange::HighPoly),
|
||||
(self.cage != current.cage, BakeChange::Cage),
|
||||
(self.settings != current.settings, BakeChange::Settings),
|
||||
(self.map_settings != current.map_settings, BakeChange::MapSettings),
|
||||
]
|
||||
.into_iter()
|
||||
.filter_map(|(changed, change)| changed.then_some(change))
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// A fingerprint of `bytes` that stays the same across runs, platforms and Rust versions (unlike `std::hash`)
|
||||
pub fn fingerprint(bytes: &[u8]) -> u64 {
|
||||
let words = bytes.chunks(8).map(|chunk| {
|
||||
let mut word_bytes = [0; 8];
|
||||
word_bytes[..chunk.len()].copy_from_slice(chunk);
|
||||
u64::from_le_bytes(word_bytes)
|
||||
});
|
||||
fingerprint_words(words.chain([bytes.len() as u64]))
|
||||
}
|
||||
|
||||
/// [`fingerprint`] of a sequence of words: FNV-1a taking a 64-bit word per step
|
||||
pub fn fingerprint_words(words: impl IntoIterator<Item = u64>) -> u64 {
|
||||
// FNV-1a 64-bit offset basis and prime
|
||||
const OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325;
|
||||
const PRIME: u64 = 0x0000_0100_0000_01b3;
|
||||
|
||||
words.into_iter().fold(OFFSET_BASIS, |hash, word| (hash ^ word).wrapping_mul(PRIME))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_fingerprint_changes_with_any_byte_and_with_the_length() {
|
||||
let bytes: Vec<u8> = (0..=20).collect();
|
||||
let mut changed = bytes.clone();
|
||||
changed[17] ^= 1;
|
||||
|
||||
assert_ne!(fingerprint(&bytes), fingerprint(&changed));
|
||||
assert_ne!(fingerprint(&bytes), fingerprint(&bytes[..20]));
|
||||
assert_ne!(fingerprint(&[]), fingerprint(&[0]));
|
||||
}
|
||||
}
|
||||
@@ -37,6 +37,11 @@ impl Default for MeshMapSettings {
|
||||
}
|
||||
|
||||
impl MeshMapSettings {
|
||||
/// Whether this map reads the source mesh's material colors, independently of its enabled flag.
|
||||
pub fn reads_material_colors(&self, map: BakedMap) -> bool {
|
||||
map == BakedMap::Opacity || (map == BakedMap::Id && self.id.parameters.source == super::IdColorSource::MaterialColor)
|
||||
}
|
||||
|
||||
pub fn is_enabled(&self, map: BakedMap) -> bool {
|
||||
match map {
|
||||
BakedMap::Normal => self.normal.is_enabled,
|
||||
@@ -84,6 +89,22 @@ impl MeshMapSettings {
|
||||
}
|
||||
}
|
||||
|
||||
/// `map`'s typed parameters as JSON
|
||||
pub fn parameters_json(&self, map: BakedMap) -> serde_json::Value {
|
||||
let parameters = match map {
|
||||
// These maps have no parameters of their own
|
||||
BakedMap::Normal | BakedMap::WorldNormal | BakedMap::Opacity => return serde_json::Value::Null,
|
||||
BakedMap::Id => serde_json::to_value(self.id.parameters),
|
||||
BakedMap::AmbientOcclusion => serde_json::to_value(self.ao.parameters),
|
||||
BakedMap::Curvature => serde_json::to_value(self.curvature.parameters),
|
||||
BakedMap::Position => serde_json::to_value(self.position.parameters),
|
||||
BakedMap::Thickness => serde_json::to_value(self.thickness.parameters),
|
||||
BakedMap::Height => serde_json::to_value(self.height.parameters),
|
||||
BakedMap::BentNormal => serde_json::to_value(self.bent_normal.parameters),
|
||||
};
|
||||
parameters.unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn enabled(&self) -> impl Iterator<Item = BakedMap> {
|
||||
BakedMap::ALL.into_iter().filter(|map| self.is_enabled(*map))
|
||||
}
|
||||
|
||||
@@ -1283,6 +1283,14 @@ impl Generator {
|
||||
if reads_geometry { &[] } else { self.kind.inputs() }
|
||||
}
|
||||
|
||||
/// The mesh maps the generator reads that a bake makes: its inputs in use, and the occlusion Dripping Rust reads whole, which no input replaces
|
||||
pub fn baked_maps_read(&self) -> &'static [BakedMap] {
|
||||
match self.kind {
|
||||
GeneratorKind::DrippingRust => &[BakedMap::AmbientOcclusion],
|
||||
_ => self.inputs_in_use(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The texture the generator blends over its signal: only on the section controls, turned on with some opacity
|
||||
pub fn texture_in_use(&self) -> Option<&TextureLayer> {
|
||||
self.texture.as_deref().filter(|texture| texture.in_use() && self.section_controls().is_some())
|
||||
|
||||
+10
-5
@@ -39,6 +39,7 @@ pub mod image_input;
|
||||
pub mod layer;
|
||||
pub mod lighting_output;
|
||||
pub mod mask_outline;
|
||||
pub mod mesh_map_slot;
|
||||
pub mod mirror;
|
||||
pub mod mirror_corner;
|
||||
pub mod mirror_mode;
|
||||
@@ -51,6 +52,7 @@ pub mod project;
|
||||
pub mod projector;
|
||||
pub mod ramp_curve;
|
||||
pub mod randomized_seed;
|
||||
pub mod resource_source;
|
||||
mod saved_decal;
|
||||
mod saved_projection;
|
||||
pub mod selection_background;
|
||||
@@ -80,11 +82,12 @@ pub const FULL_TURN_DEGREES: f32 = 360.0;
|
||||
pub use anisotropic_kuwahara::AnisotropicKuwahara;
|
||||
pub use backface::Backface;
|
||||
pub use bake::{
|
||||
AmbientOcclusionAttenuation, AmbientOcclusionSettings, BackfaceMode, BakeAntialiasing, BakePaintTarget, BakeResolution, BakeSettings, BakeSync,
|
||||
BakeSyncGroup, BakedMap, BentNormalSettings, CageSettings, CageType, CommonBakeSettings, CurvatureMethod, CurvatureSettings, GroundPlaneSettings,
|
||||
HeightNormalization, HeightSettings, HighPolySettings, IdColorGenerator, IdColorSource, IdSettings, MapSettings, MeshCurvatureSettings, MeshMapSettings,
|
||||
MeshMatchMode, NormalMapCurvatureSettings, PositionAxis, PositionMode, PositionNormalizationScale, PositionSettings, RayDistribution, RaySettings,
|
||||
SelfOcclusion, SkewCorrectionMethod, SkewSettings, ThicknessNormalization, ThicknessSettings,
|
||||
AmbientOcclusionAttenuation, AmbientOcclusionSettings, BackfaceMode, BakeAntialiasing, BakeChange, BakePaintTarget, BakeResolution, BakeSettings,
|
||||
BakeSource, BakeSync, BakeSyncGroup, BakedMap, BentNormalSettings, CageSettings, CageType, CommonBakeSettings, CurvatureMethod, CurvatureSettings,
|
||||
GroundPlaneSettings, HeightNormalization, HeightSettings, HighPolySettings, IdColorGenerator, IdColorSource, IdSettings, MapSettings,
|
||||
MeshCurvatureSettings, MeshMapSettings, MeshMatchMode, NormalMapCurvatureSettings, PositionAxis, PositionMode, PositionNormalizationScale,
|
||||
PositionSettings, RayDistribution, RaySettings, SelfOcclusion, SkewCorrectionMethod, SkewSettings, ThicknessNormalization, ThicknessSettings, fingerprint,
|
||||
fingerprint_words,
|
||||
};
|
||||
pub use bevel::Bevel;
|
||||
pub use bevel_blur::BevelBlur;
|
||||
@@ -121,6 +124,7 @@ pub use layer::{
|
||||
};
|
||||
pub use lighting_output::LightingOutput;
|
||||
pub use mask_outline::MaskOutline;
|
||||
pub use mesh_map_slot::MeshMapSlot;
|
||||
pub use mirror::Mirror;
|
||||
pub use mirror_corner::MirrorCorner;
|
||||
pub use mirror_mode::MirrorMode;
|
||||
@@ -135,6 +139,7 @@ pub use project::{
|
||||
pub use projector::Projector;
|
||||
pub use ramp_curve::RampCurve;
|
||||
pub use randomized_seed::RandomizedSeed;
|
||||
pub use resource_source::ResourceSource;
|
||||
pub use selection_background::SelectionBackground;
|
||||
pub use shape_crop::ShapeCrop;
|
||||
pub use slope_blending::SlopeBlending;
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
//! The mesh map an imported image file was resampled into
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::BakedMap;
|
||||
|
||||
/// A mesh map of a texture set, and the UV tile one image of it covers.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
pub struct MeshMapSlot {
|
||||
/// Index of the texture set.
|
||||
pub texture_set: usize,
|
||||
pub map: BakedMap,
|
||||
/// The UV tile the image covers (1001 on a set without UV tiles).
|
||||
pub tile: u32,
|
||||
}
|
||||
@@ -4,7 +4,7 @@ use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{BakeSettings, BakeSyncGroup, BakedMap, Channel, ChannelFormat, ContentsOffset, CoreError, Effect, Layer, LayerId, LayerKind, Result};
|
||||
use crate::{BakeSettings, BakeSource, BakeSyncGroup, BakedMap, Channel, ChannelFormat, ContentsOffset, CoreError, Effect, Layer, LayerId, LayerKind, Result};
|
||||
|
||||
pub use crate::env_alignment::EnvAlignment;
|
||||
pub use crate::shadow_mode::ShadowMode;
|
||||
@@ -69,6 +69,12 @@ pub struct TextureSet {
|
||||
/// Mesh maps that have been baked (pixels live with the engine / project file).
|
||||
#[serde(default)]
|
||||
pub baked: BTreeSet<BakedMap>,
|
||||
/// What each baked map was baked from; a map without a record (imported, or older project) is never out of date
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub bake_sources: BTreeMap<BakedMap, BakeSource>,
|
||||
/// The one mesh map the app rebakes by itself when what it is baked from changes
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub auto_rebake: Option<BakedMap>,
|
||||
#[serde(default = "yes")]
|
||||
pub visible: bool,
|
||||
/// UDIM numbers of the UV tiles this set paints, ascending (UV tiles mode);
|
||||
@@ -171,6 +177,8 @@ impl TextureSet {
|
||||
height_strength: 1.0,
|
||||
bake: BakeSettings::default(),
|
||||
baked: BTreeSet::new(),
|
||||
bake_sources: BTreeMap::new(),
|
||||
auto_rebake: None,
|
||||
visible: true,
|
||||
uv_tiles: Vec::new(),
|
||||
bake_excluded_tiles: BTreeSet::new(),
|
||||
@@ -187,6 +195,19 @@ impl TextureSet {
|
||||
self.uv_tiles.is_empty() || self.uv_tiles.iter().any(|tile| !self.bake_excluded_tiles.contains(tile))
|
||||
}
|
||||
|
||||
/// Fingerprint of the shared bake settings (not the set's check) and baked UV tiles (not their working resolutions)
|
||||
pub fn bake_settings_fingerprint(&self) -> u64 {
|
||||
let mut common = self.bake.common;
|
||||
common.is_enabled = true;
|
||||
let shared = (common, &self.bake.high_poly, &self.bake.cage, &self.bake.skew, &self.uv_tiles, &self.bake_excluded_tiles);
|
||||
crate::fingerprint(serde_json::to_string(&shared).unwrap_or_default().as_bytes())
|
||||
}
|
||||
|
||||
/// Fingerprint of `map`'s own bake settings (not whether it is checked)
|
||||
pub fn map_settings_fingerprint(&self, map: BakedMap) -> u64 {
|
||||
crate::fingerprint(self.bake.maps.parameters_json(map).to_string().as_bytes())
|
||||
}
|
||||
|
||||
/// Height strength for slopes measured over the whole texture width (the viewport shader,
|
||||
/// the path tracer): a UV tile atlas is one tile per column wide.
|
||||
pub fn atlas_height_strength(&self) -> f32 {
|
||||
@@ -316,8 +337,10 @@ pub struct DisplaySettings {
|
||||
pub scatter_color: [f32; 3],
|
||||
/// Subsurface scattering mean free path as a fraction of the mesh's bounding radius.
|
||||
pub scatter_radius: f32,
|
||||
/// Index of refraction of transmissive surfaces (where the Transmission channel is painted).
|
||||
/// Index of refraction for transmission and, when enabled, dielectric reflectance.
|
||||
pub ior: f32,
|
||||
/// Use IOR to determine dielectric reflectance at normal incidence in Metallic/Roughness.
|
||||
pub ior_specular: bool,
|
||||
/// Depth of field of the viewport and the path tracer (thin lens).
|
||||
pub dof: DepthOfField,
|
||||
/// The selected fill's projection gizmos show in the 3D view (the Projection row's eye)
|
||||
@@ -381,11 +404,35 @@ pub const ENVIRONMENTS: [&str; 6] = ["Studio Soft", "Studio Contrast", "Overcast
|
||||
/// Prefix of [`DisplaySettings::environment`] naming an image resource.
|
||||
pub const ENV_RESOURCE_PREFIX: &str = "resource:";
|
||||
|
||||
/// Original dielectric F0 multiplier for the Specular Level channel.
|
||||
pub const LEGACY_DIELECTRIC_F0_SCALE: f32 = 0.08;
|
||||
|
||||
/// Project limits for the index of refraction.
|
||||
pub const MIN_INDEX_OF_REFRACTION: f32 = 1.0;
|
||||
pub const MAX_INDEX_OF_REFRACTION: f32 = 3.0;
|
||||
|
||||
impl DisplaySettings {
|
||||
/// The image resource used as the environment, if any.
|
||||
pub fn environment_resource(&self) -> Option<&str> {
|
||||
self.environment.strip_prefix(ENV_RESOURCE_PREFIX)
|
||||
}
|
||||
|
||||
/// Multiplier for Specular Level in the Metallic/Roughness model.
|
||||
pub fn dielectric_f0_scale(&self) -> f32 {
|
||||
if !self.ior_specular || self.spec_gloss || !self.ior.is_finite() {
|
||||
return LEGACY_DIELECTRIC_F0_SCALE;
|
||||
}
|
||||
|
||||
const AIR_INDEX_OF_REFRACTION: f32 = 1.0;
|
||||
// Specular Level 0.5 corresponds to OpenPBR specular weight 1
|
||||
const SPECULAR_LEVEL_TO_WEIGHT_SCALE: f32 = 2.0;
|
||||
let ior = self.ior.clamp(MIN_INDEX_OF_REFRACTION, MAX_INDEX_OF_REFRACTION);
|
||||
let contrast = ior - AIR_INDEX_OF_REFRACTION;
|
||||
let index_sum = ior + AIR_INDEX_OF_REFRACTION;
|
||||
|
||||
// Square before dividing so IOR 1.5 rounds to the legacy multiplier
|
||||
SPECULAR_LEVEL_TO_WEIGHT_SCALE * contrast.powi(2) / index_sum.powi(2)
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for DisplaySettings {
|
||||
@@ -416,6 +463,7 @@ impl Default for DisplaySettings {
|
||||
scatter_color: [1.0, 0.4, 0.25],
|
||||
scatter_radius: 0.1,
|
||||
ior: 1.5,
|
||||
ior_specular: false,
|
||||
dof: DepthOfField::default(),
|
||||
projection_gizmos: true,
|
||||
}
|
||||
@@ -452,6 +500,10 @@ pub struct Project {
|
||||
/// The project's colour swatches (linear RGB), in the order they were added; projects without any save none
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub swatches: Vec<[f32; 3]>,
|
||||
/// The files image resources were imported from, by resource name (the Resources Updater
|
||||
/// reads them again). Resources made in the app or imported without a file path have none.
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub resource_sources: BTreeMap<String, crate::ResourceSource>,
|
||||
}
|
||||
|
||||
impl Project {
|
||||
@@ -470,6 +522,7 @@ impl Project {
|
||||
display: DisplaySettings::default(),
|
||||
cameras: Vec::new(),
|
||||
swatches: Vec::new(),
|
||||
resource_sources: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -817,6 +870,28 @@ mod tests {
|
||||
p
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enabling_ior_at_the_default_preserves_legacy_reflectance() {
|
||||
let mut display = DisplaySettings::default();
|
||||
let legacy = display.dielectric_f0_scale();
|
||||
|
||||
display.ior_specular = true;
|
||||
|
||||
assert_eq!(display.dielectric_f0_scale(), legacy);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dielectric_reflectance_clamps_ior_and_falls_back_for_non_finite_values() {
|
||||
let scale_at = |ior| DisplaySettings { ior, ior_specular: true, ..DisplaySettings::default() }.dielectric_f0_scale();
|
||||
|
||||
assert_eq!(scale_at(0.5), scale_at(1.0));
|
||||
assert_eq!(scale_at(1.0), 0.0);
|
||||
assert!(scale_at(1.5) < scale_at(3.0));
|
||||
assert_eq!(scale_at(4.0), scale_at(3.0));
|
||||
assert_eq!(scale_at(f32::NAN), LEGACY_DIELECTRIC_F0_SCALE);
|
||||
assert_eq!(scale_at(f32::INFINITY), LEGACY_DIELECTRIC_F0_SCALE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sync_takes_settings_from_a_staying_member_else_the_active_set_else_the_first() {
|
||||
let group = BakeSyncGroup::Common;
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
//! Where an image resource was imported from, so the Resources Updater can read it again
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// The file an image resource was read from and its modification time then.
|
||||
///
|
||||
/// The resource's stored bytes are the file's bytes at that time, so a file whose size or
|
||||
/// contents differ from them has changed on disk.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ResourceSource {
|
||||
/// Path of the file on the machine that imported it.
|
||||
pub path: String,
|
||||
/// The file's modification time when it was read, in milliseconds since the Unix epoch
|
||||
/// (0 when unknown). An unchanged time and size skip reading the file again.
|
||||
#[serde(default)]
|
||||
pub modified_ms: u64,
|
||||
/// The mesh map the file was imported as (`textureSet.meshMap.import`): an update resamples it
|
||||
/// again while the map still holds what this file gave it.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub mesh_map: Option<crate::MeshMapSlot>,
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
//! Auto-rebake: the one mesh map per texture set that is baked again whenever what it is baked from changes
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_core::{BakeSource, BakedMap};
|
||||
|
||||
use crate::commands::{CommandSpec, always, bad, strp, u64p};
|
||||
use crate::{Result, Session, cmd};
|
||||
|
||||
pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
"bake.autoRebake",
|
||||
"Auto-rebake",
|
||||
[],
|
||||
None,
|
||||
"{ts?: index (default: the active set), map: id | null} → {ts, autoRebake: id | null}. Turn on Auto-rebake for one mesh map of the set (it replaces the set's previous one), or turn it off with null. The app then rebakes that map in the background once what it is baked from changes",
|
||||
always,
|
||||
set_auto_rebake
|
||||
)]
|
||||
}
|
||||
|
||||
fn set_auto_rebake(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
const COMMAND: &str = "bake.autoRebake";
|
||||
let texture_set = match params.get("ts") {
|
||||
None => session.ts(),
|
||||
Some(_) => u64p(params, "ts")
|
||||
.and_then(|index| usize::try_from(index).ok())
|
||||
.filter(|index| *index < session.set_count())
|
||||
.ok_or_else(|| bad(COMMAND, "invalid `ts`"))?,
|
||||
};
|
||||
let map = match params.get("map") {
|
||||
Some(Value::Null) => None,
|
||||
Some(_) => Some(strp(params, "map").and_then(BakedMap::parse).ok_or_else(|| bad(COMMAND, "`map` must be a mesh map id or null"))?),
|
||||
None => return Err(bad(COMMAND, "`map` is required (a mesh map id or null)")),
|
||||
};
|
||||
|
||||
if session.doc.project.texture_set(texture_set)?.auto_rebake != map {
|
||||
session.edit("Auto-rebake", |session| {
|
||||
session.doc.project.texture_set_mut(texture_set)?.auto_rebake = map;
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
|
||||
Ok(json!({ "ts": texture_set, "autoRebake": map.map(BakedMap::id) }))
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// The auto-rebake maps that are out of date now, as (texture set, map, what a bake would read now)
|
||||
pub fn auto_rebake_due(&self) -> Vec<(usize, BakedMap, BakeSource)> {
|
||||
let sets = self.doc.project.texture_sets.iter().enumerate();
|
||||
sets.filter_map(|(index, set)| {
|
||||
let map = set.auto_rebake?;
|
||||
let record = set.bake_sources.get(&map).filter(|_| set.baked.contains(&map))?;
|
||||
let current = self.bake_source(index, map).ok()?;
|
||||
(*record != current).then_some((index, map, current))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Bake the selected map alone, or include every checked map if the atlas changed size
|
||||
pub fn auto_rebake_maps(&self, texture_set: usize, map: BakedMap) -> Vec<BakedMap> {
|
||||
let Ok(set) = self.doc.project.texture_set(texture_set) else { return vec![map] };
|
||||
|
||||
let (tile_width, tile_height) = set.bake.common.output_size();
|
||||
let (columns, rows) = set.tile_grid().map_or((1, 1), |grid| (grid.cols, grid.rows));
|
||||
let (width, height) = (tile_width * columns, tile_height * rows);
|
||||
let stored = self.doc.baked.get(&texture_set);
|
||||
let resized = stored.is_some_and(|stored| stored.resolution != width || stored.maps.keys().any(|baked| stored.height(*baked) != height));
|
||||
match resized {
|
||||
true => BakedMap::ALL.into_iter().filter(|baked| *baked == map || set.bake.maps.is_enabled(*baked)).collect(),
|
||||
false => vec![map],
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
use serde::Serialize;
|
||||
|
||||
/// Where one high poly file of a bake stands, as the Baking Log shows it
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase", tag = "state", content = "reason")]
|
||||
pub enum BakeHighState {
|
||||
/// Its texture set has not started baking
|
||||
Waiting,
|
||||
Loading,
|
||||
Loaded,
|
||||
/// Its texture set's bake failed while getting the high polys ready; the reason is the error
|
||||
Failed(String),
|
||||
/// The bake stopped before the file was loaded
|
||||
Canceled,
|
||||
}
|
||||
|
||||
impl BakeHighState {
|
||||
/// Whether the file can still change in this bake
|
||||
pub fn is_pending(&self) -> bool {
|
||||
matches!(self, Self::Waiting | Self::Loading)
|
||||
}
|
||||
|
||||
/// Whether the file counts as an issue in the log
|
||||
pub fn is_issue(&self) -> bool {
|
||||
matches!(self, Self::Failed(_) | Self::Canceled)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
use std::collections::HashSet;
|
||||
|
||||
use texturecraft_bake::NamePair;
|
||||
use texturecraft_core::{BakedMap, MeshMatchMode, Project};
|
||||
|
||||
use super::{BakeHighState, BakeLogHigh, BakeLogMap, BakeLogMatching, BakeMapState, BakeMesh};
|
||||
use crate::Session;
|
||||
|
||||
/// The latest bake map by map for the Baking Log, kept from the bake's own state, never from Log lines
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct BakeLog {
|
||||
pub maps: Vec<BakeLogMap>,
|
||||
/// Each high poly file of each texture set that bakes from the high polys, in bake order
|
||||
pub highs: Vec<BakeLogHigh>,
|
||||
/// How the parts paired by name; `None` when no set of the bake matches "By Mesh Name"
|
||||
pub matching: Option<BakeLogMatching>,
|
||||
}
|
||||
|
||||
impl BakeLog {
|
||||
/// Start over for a bake of `sets`: every checked map of each set and the `high_polys` of each set that bakes from them, waiting, in bake order
|
||||
pub fn begin(&mut self, project: &Project, high_polys: &[BakeMesh], sets: &[usize]) {
|
||||
self.maps = sets
|
||||
.iter()
|
||||
.filter_map(|index| project.texture_sets.get(*index).map(|set| (*index, set)))
|
||||
.flat_map(|(index, set)| {
|
||||
set.bake.maps.enabled().map(move |map| BakeLogMap { texture_set: index, set_name: set.name.clone(), map, state: BakeMapState::Waiting })
|
||||
})
|
||||
.collect();
|
||||
self.highs = sets
|
||||
.iter()
|
||||
.filter_map(|index| project.texture_sets.get(*index).map(|set| (*index, set)))
|
||||
.filter(|(_, set)| !set.bake.high_poly.use_low_as_high)
|
||||
.flat_map(|(index, set)| {
|
||||
high_polys.iter().map(move |high| BakeLogHigh {
|
||||
texture_set: index,
|
||||
set_name: set.name.clone(),
|
||||
file: high.name.clone(),
|
||||
state: BakeHighState::Waiting,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
self.matching = None;
|
||||
}
|
||||
|
||||
/// `set` starts baking: its high polys load and its first map is the one in progress
|
||||
pub fn set_started(&mut self, set: usize) {
|
||||
for row in self.highs.iter_mut().filter(|row| row.texture_set == set && row.state == BakeHighState::Waiting) {
|
||||
row.state = BakeHighState::Loading;
|
||||
}
|
||||
self.start_next(set);
|
||||
}
|
||||
|
||||
/// `set`'s bake has its high polys ready
|
||||
pub fn high_polys_loaded(&mut self, set: usize) {
|
||||
for row in self.highs.iter_mut().filter(|row| row.texture_set == set && row.state == BakeHighState::Loading) {
|
||||
row.state = BakeHighState::Loaded;
|
||||
}
|
||||
}
|
||||
|
||||
/// `map` of `set` is baked; the set's next map starts
|
||||
pub fn map_baked(&mut self, set: usize, map: BakedMap) {
|
||||
if let Some(row) = self.maps.iter_mut().find(|row| row.texture_set == set && row.map == map) {
|
||||
row.state = BakeMapState::Baked;
|
||||
}
|
||||
self.start_next(set);
|
||||
}
|
||||
|
||||
/// `set`'s bake was kept: a map it did not hand over is not baked
|
||||
pub fn set_finished(&mut self, set: usize) {
|
||||
for row in self.maps.iter_mut().filter(|row| row.texture_set == set && row.state.is_pending()) {
|
||||
row.state = BakeMapState::Canceled;
|
||||
}
|
||||
}
|
||||
|
||||
/// Nothing of `set` was kept: every one of its maps failed for `reason`
|
||||
pub fn set_failed(&mut self, set: usize, reason: &str) {
|
||||
for row in self.maps.iter_mut().filter(|row| row.texture_set == set) {
|
||||
row.state = BakeMapState::Failed(reason.to_owned());
|
||||
}
|
||||
|
||||
// A file that loaded is not what failed
|
||||
for row in self.highs.iter_mut().filter(|row| row.texture_set == set && row.state.is_pending()) {
|
||||
row.state = BakeHighState::Failed(reason.to_owned());
|
||||
}
|
||||
}
|
||||
|
||||
/// The bake stopped: every map still waiting or baking is canceled, and so are the finished maps of `discarded` (the set being baked, when they were not kept)
|
||||
pub fn cancel(&mut self, discarded: Option<usize>) {
|
||||
for row in &mut self.maps {
|
||||
if row.state.is_pending() || (Some(row.texture_set) == discarded && row.state == BakeMapState::Baked) {
|
||||
row.state = BakeMapState::Canceled;
|
||||
}
|
||||
}
|
||||
self.cancel_pending_highs();
|
||||
}
|
||||
|
||||
/// The whole bake was rolled back: every map that did not fail is canceled
|
||||
pub fn discard(&mut self) {
|
||||
for row in self.maps.iter_mut().filter(|row| !matches!(row.state, BakeMapState::Failed(_))) {
|
||||
row.state = BakeMapState::Canceled;
|
||||
}
|
||||
self.cancel_pending_highs();
|
||||
}
|
||||
|
||||
/// Whether a map is still waiting or baking
|
||||
pub fn is_running(&self) -> bool {
|
||||
self.maps.iter().any(|row| row.state.is_pending())
|
||||
}
|
||||
|
||||
/// Whether a high poly file is still waiting or loading
|
||||
pub fn is_loading_high_polys(&self) -> bool {
|
||||
self.highs.iter().any(|row| row.state.is_pending())
|
||||
}
|
||||
|
||||
fn cancel_pending_highs(&mut self) {
|
||||
for row in self.highs.iter_mut().filter(|row| row.state.is_pending()) {
|
||||
row.state = BakeHighState::Canceled;
|
||||
}
|
||||
}
|
||||
|
||||
fn start_next(&mut self, set: usize) {
|
||||
if self.maps.iter().any(|row| row.texture_set == set && row.state == BakeMapState::Baking) {
|
||||
return;
|
||||
}
|
||||
|
||||
if let Some(row) = self.maps.iter_mut().find(|row| row.texture_set == set && row.state == BakeMapState::Waiting) {
|
||||
row.state = BakeMapState::Baking;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Start the Baking Log over for a bake of `sets` ([`BakeLog::begin`]), with how their parts pair by name
|
||||
pub fn begin_bake_log(&mut self, sets: &[usize]) {
|
||||
let matching = self.bake_log_matching(sets);
|
||||
self.bake_log.begin(&self.doc.project, &self.doc.bake_meshes.high, sets);
|
||||
self.bake_log.matching = matching;
|
||||
}
|
||||
|
||||
/// Start the Baking Log for a bake of only `maps` of each of `sets`, checked or not
|
||||
pub fn begin_map_bake_log(&mut self, sets: &[usize], maps: &[BakedMap]) {
|
||||
self.begin_bake_log(sets);
|
||||
let project = &self.doc.project;
|
||||
self.bake_log.maps = sets
|
||||
.iter()
|
||||
.filter_map(|&texture_set| Some((texture_set, project.texture_sets.get(texture_set)?.name.clone())))
|
||||
.flat_map(|(texture_set, set_name)| {
|
||||
maps.iter().map(move |&map| BakeLogMap { texture_set, set_name: set_name.clone(), map, state: BakeMapState::Waiting })
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
|
||||
/// The name pairs of each of `sets` that matches "By Mesh Name"; a high poly part counts as unpaired only when none of them pairs with it and no set matching "Always" bakes from every part
|
||||
fn bake_log_matching(&self, sets: &[usize]) -> Option<BakeLogMatching> {
|
||||
let mut matching: Option<BakeLogMatching> = None;
|
||||
let (mut paired_highs, mut unpaired_highs) = (HashSet::new(), Vec::new());
|
||||
let mut every_high_used = false;
|
||||
for &set in sets {
|
||||
let Ok(texture_set) = self.doc.project.texture_set(set) else { continue };
|
||||
|
||||
let settings = &texture_set.bake.high_poly;
|
||||
every_high_used |= !settings.use_low_as_high && settings.match_mode == MeshMatchMode::Always;
|
||||
let Ok(Some(pairs)) = self.bake_name_pairs(set) else { continue };
|
||||
|
||||
let matching = matching.get_or_insert_with(|| BakeLogMatching {
|
||||
low_suffix: settings.low_suffix.clone(),
|
||||
high_suffix: settings.high_suffix.clone(),
|
||||
pairs: Vec::new(),
|
||||
});
|
||||
for pair in pairs {
|
||||
match (&pair.low, &pair.high) {
|
||||
(None, Some(high)) if !unpaired_highs.contains(high) => unpaired_highs.push(high.clone()),
|
||||
(None, _) => {}
|
||||
(Some(_), high) => {
|
||||
paired_highs.extend(high.clone());
|
||||
matching.pairs.push(pair);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(matching) = matching.as_mut().filter(|_| !every_high_used) {
|
||||
let unpaired = unpaired_highs.into_iter().filter(|high| !paired_highs.contains(high));
|
||||
matching.pairs.extend(unpaired.map(|high| NamePair { low: None, high: Some(high) }));
|
||||
}
|
||||
matching
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
use super::BakeHighState;
|
||||
|
||||
/// One row of the Baking Log's high poly list: a high poly file a texture set bakes from in the latest bake
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct BakeLogHigh {
|
||||
pub texture_set: usize,
|
||||
pub set_name: String,
|
||||
/// The file's name as the project keeps it (the project carries the file itself, not where it came from)
|
||||
pub file: String,
|
||||
pub state: BakeHighState,
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
use texturecraft_core::BakedMap;
|
||||
|
||||
use super::BakeMapState;
|
||||
|
||||
/// One row of the Baking Log's process list: a map of a texture set in the latest bake
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct BakeLogMap {
|
||||
pub texture_set: usize,
|
||||
pub set_name: String,
|
||||
pub map: BakedMap,
|
||||
pub state: BakeMapState,
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
use texturecraft_bake::NamePair;
|
||||
|
||||
/// The Baking Log's matching list: how the latest bake paired low poly parts with high poly parts by name
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct BakeLogMatching {
|
||||
/// The suffixes the first set matching by name strips, for the column captions
|
||||
pub low_suffix: String,
|
||||
pub high_suffix: String,
|
||||
/// Each low poly part with the high poly part it bakes from, then the high poly parts no set of the bake pairs with
|
||||
pub pairs: Vec<NamePair>,
|
||||
}
|
||||
|
||||
impl BakeLogMatching {
|
||||
/// How many parts found no partner
|
||||
pub fn issue_count(&self) -> usize {
|
||||
self.pairs.iter().filter(|pair| pair.unpaired()).count()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
use serde::Serialize;
|
||||
|
||||
/// Where one map of a bake stands, as the Baking Log shows it
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase", tag = "state", content = "reason")]
|
||||
pub enum BakeMapState {
|
||||
Waiting,
|
||||
Baking,
|
||||
Baked,
|
||||
/// The bake of its texture set failed; the reason is the error
|
||||
Failed(String),
|
||||
/// The bake stopped before this map was kept
|
||||
Canceled,
|
||||
}
|
||||
|
||||
impl BakeMapState {
|
||||
/// Whether the map can still change in this bake
|
||||
pub fn is_pending(&self) -> bool {
|
||||
matches!(self, Self::Waiting | Self::Baking)
|
||||
}
|
||||
|
||||
/// Whether the map counts as an issue in the log
|
||||
pub fn is_issue(&self) -> bool {
|
||||
matches!(self, Self::Failed(_) | Self::Canceled)
|
||||
}
|
||||
}
|
||||
@@ -11,4 +11,6 @@ pub struct BakeMesh {
|
||||
pub bytes: Arc<Vec<u8>>,
|
||||
pub mesh: Arc<Mesh>,
|
||||
pub base_color: Vec<Option<Arc<BaseColor>>>,
|
||||
/// [`texturecraft_core::fingerprint`] of `bytes`: what bakes from this file record
|
||||
pub fingerprint: u64,
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
//! What each baked map was baked from, and which maps are out of date since
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use texturecraft_core::{BakeChange, BakeSource, BakedMap, CageType, TextureSet, fingerprint, fingerprint_words};
|
||||
|
||||
use crate::{Result, Session};
|
||||
|
||||
impl Session {
|
||||
/// What a bake of `map` on texture set `texture_set` would read now
|
||||
pub fn bake_source(&self, texture_set: usize, map: BakedMap) -> Result<BakeSource> {
|
||||
let set = self.doc.project.texture_set(texture_set)?;
|
||||
Ok(self.map_bake_source(set, map, self.set_bake_source(set)))
|
||||
}
|
||||
|
||||
/// The inputs of the maps selected for one task.
|
||||
pub(super) fn task_bake_sources(&self, set: &TextureSet, maps: impl Iterator<Item = BakedMap>) -> BTreeMap<BakedMap, BakeSource> {
|
||||
let shared = std::cell::LazyCell::new(|| self.set_bake_source(set));
|
||||
maps.map(|map| (map, self.map_bake_source(set, map, *shared))).collect()
|
||||
}
|
||||
|
||||
/// The inputs shared by every map in a texture set.
|
||||
fn set_bake_source(&self, set: &TextureSet) -> BakeSource {
|
||||
let from_high = !set.bake.high_poly.use_low_as_high && !self.doc.bake_meshes.high.is_empty();
|
||||
let high_poly = match from_high {
|
||||
true => fingerprint_words(self.doc.bake_meshes.high.iter().map(|high| high.fingerprint)),
|
||||
false => 0,
|
||||
};
|
||||
let reads_cage = from_high && set.bake.cage.kind == CageType::CustomFile;
|
||||
let cage = self.doc.bake_meshes.cage.as_ref().filter(|_| reads_cage).map_or(0, |cage| cage.fingerprint);
|
||||
|
||||
BakeSource {
|
||||
low_poly: self.low_poly_fingerprint(),
|
||||
low_material_file: None,
|
||||
high_poly,
|
||||
cage,
|
||||
settings: set.bake_settings_fingerprint(),
|
||||
map_settings: 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn map_bake_source(&self, set: &TextureSet, map: BakedMap, shared: BakeSource) -> BakeSource {
|
||||
let reads_low_colors = shared.high_poly == 0 && set.bake.maps.reads_material_colors(map);
|
||||
let low_material_file =
|
||||
self.mesh_source.as_ref().filter(|_| reads_low_colors).map(|(_, bytes)| *self.low_material_file_fingerprint.get_or_init(|| fingerprint(bytes)));
|
||||
|
||||
BakeSource { low_material_file, map_settings: set.map_settings_fingerprint(map), ..shared }
|
||||
}
|
||||
|
||||
/// What changed since `map` of texture set `texture_set` was baked; empty when up to date, not baked or without a record
|
||||
pub fn bake_changes(&self, texture_set: usize, map: BakedMap) -> Vec<BakeChange> {
|
||||
let Ok(set) = self.doc.project.texture_set(texture_set) else { return Vec::new() };
|
||||
|
||||
let Some(record) = set.bake_sources.get(&map).filter(|_| set.baked.contains(&map)) else { return Vec::new() };
|
||||
|
||||
self.bake_source(texture_set, map).map(|current| record.changes(¤t)).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The out-of-date maps of texture set `texture_set`, each with what changed
|
||||
pub fn out_of_date_maps(&self, texture_set: usize) -> BTreeMap<BakedMap, Vec<BakeChange>> {
|
||||
let Ok(set) = self.doc.project.texture_set(texture_set) else { return BTreeMap::new() };
|
||||
|
||||
let mut records = set.bake_sources.iter().filter(|(map, _)| set.baked.contains(map)).peekable();
|
||||
|
||||
if records.peek().is_none() {
|
||||
return BTreeMap::new();
|
||||
}
|
||||
|
||||
let shared = self.set_bake_source(set);
|
||||
let changes = records.map(|(map, record)| (*map, record.changes(&self.map_bake_source(set, *map, shared))));
|
||||
changes.filter(|(_, changes)| !changes.is_empty()).collect()
|
||||
}
|
||||
|
||||
/// Fingerprint of the low poly's geometry, tangent frame, vertex colors and part assignments (computed once per loaded mesh)
|
||||
fn low_poly_fingerprint(&self) -> u64 {
|
||||
*self.low_poly_fingerprint.get_or_init(|| {
|
||||
let source = &self.source;
|
||||
let floats = source
|
||||
.positions
|
||||
.iter()
|
||||
.chain(&source.normals)
|
||||
.flat_map(|vector| vector.to_array())
|
||||
.chain(source.tangents.iter().flat_map(|tangent| tangent.to_array()))
|
||||
.chain(source.uvs.iter().flat_map(|uv| uv.to_array()))
|
||||
.chain(source.colors.iter().flat_map(|color| color.to_array()));
|
||||
let indices = source.indices.iter().copied().map(u64::from);
|
||||
let parts =
|
||||
source.submeshes.iter().flat_map(|part| [fingerprint(part.name.as_bytes()), part.material as u64, part.start.into(), part.count.into()]);
|
||||
|
||||
fingerprint_words(floats.map(|float| u64::from(float.to_bits())).chain(indices).chain(parts))
|
||||
})
|
||||
}
|
||||
|
||||
/// Keep what the `stored` maps of `texture_set` were baked from and the newest stroke their bake saw; without it they lose their record
|
||||
pub(super) fn record_bake_sources(
|
||||
&mut self,
|
||||
texture_set: usize,
|
||||
recorded: Option<(&BTreeMap<BakedMap, BakeSource>, u64)>,
|
||||
stored: &[BakedMap],
|
||||
) -> Result<()> {
|
||||
let set = self.doc.project.texture_set_mut(texture_set)?;
|
||||
match recorded {
|
||||
Some((sources, _)) => set.bake_sources.extend(sources),
|
||||
None => set.bake_sources.retain(|map, _| !stored.contains(map)),
|
||||
}
|
||||
|
||||
let baked = &set.baked;
|
||||
set.bake_sources.retain(|map, _| baked.contains(map));
|
||||
if let Some((_, painted_stroke)) = recorded {
|
||||
self.forget_painted_region(texture_set, stored, painted_stroke);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,12 @@
|
||||
use super::{MergedHigh, StreamedBake, StreamedMap};
|
||||
use crate::{EngineError, Result};
|
||||
use std::sync::Arc;
|
||||
use texturecraft_bake::{BakeOutput, BakePaintMap, BakePasses, BakeRequest, HighPoly, Progress, bake_tiles, tracing::Tracer};
|
||||
use texturecraft_bake::{BakeOutput, BakePaintMap, BakePasses, BakeRequest, HighPoly, Progress, RegionBake, TexelBox, bake_tiles_in, tracing::Tracer};
|
||||
use texturecraft_compose::BakedMaps;
|
||||
use texturecraft_core::{BakeSettings, BakedMap};
|
||||
use texturecraft_geom::{Bvh, Mesh};
|
||||
|
||||
/// A self-contained bake task that can run on another thread.
|
||||
/// A self-contained bake task that can run on another thread
|
||||
pub struct BakeTask {
|
||||
pub low_base_color: super::MaterialColors,
|
||||
pub ts: usize,
|
||||
@@ -14,18 +14,24 @@ pub struct BakeTask {
|
||||
pub bvh: Arc<Bvh>,
|
||||
pub material: usize,
|
||||
pub settings: BakeSettings,
|
||||
/// The merged high polys, unless the set bakes from the low poly.
|
||||
/// The merged high polys, unless the set bakes from the low poly
|
||||
pub high: Option<MergedHigh>,
|
||||
pub cage: Option<Arc<Mesh>>,
|
||||
pub skew: Option<Arc<BakePaintMap>>,
|
||||
pub cage_paint: Option<Arc<BakePaintMap>>,
|
||||
/// UV tile grid (columns, rows) of the set; (1, 1) without UV tiles.
|
||||
/// UV tile grid (columns, rows) of the set; (1, 1) without UV tiles
|
||||
pub tiles: (u32, u32),
|
||||
/// Snapshot of tile selection and pixels to retain while the worker runs
|
||||
pub excluded_tiles: Vec<(u32, u32)>,
|
||||
pub previous_maps: BakedMaps,
|
||||
/// The GPU ray tracer, if installed and not turned off (`bake.run {cpu: true}`).
|
||||
/// The GPU ray tracer, if installed and not turned off (`bake.run {cpu: true}`)
|
||||
pub tracer: Option<Arc<dyn Tracer>>,
|
||||
/// What each map this task makes is baked from, taken when the task was made
|
||||
pub sources: std::collections::BTreeMap<BakedMap, texturecraft_core::BakeSource>,
|
||||
/// The newest skew or cage stroke when the task was made; a later stroke still needs a rebake
|
||||
pub painted_stroke: u64,
|
||||
/// Sample only these texels and take the rest from `previous_maps` (the same size); `None` samples every texel
|
||||
pub region: Option<TexelBox>,
|
||||
}
|
||||
|
||||
impl BakeTask {
|
||||
@@ -34,13 +40,7 @@ impl BakeTask {
|
||||
self.settings.maps.enabled().collect()
|
||||
}
|
||||
|
||||
/// Bake the maps one after another, handing each one to `on_map` as soon as it is padded,
|
||||
/// and return all of them together. Each map is a bake of its own, so with a high poly
|
||||
/// the transfer rays are cast once per map: slower than [`BakeTask::run`] with several
|
||||
/// maps, in exchange for showing them as they land. The pixels are the same as `run`'s.
|
||||
/// The handed-over buffers are the returned ones too (no copy is made), so a preview that
|
||||
/// keeps them costs no second set of maps. A cancel or an error leaves the maps already
|
||||
/// handed over whole.
|
||||
/// Bake the maps one by one (same pixels as [`BakeTask::run`], rays cast per map), handing each padded map's shared buffer to `on_map`, then return them all
|
||||
pub fn run_streaming(&self, progress: &Progress, on_map: &mut dyn FnMut(StreamedMap)) -> Result<StreamedBake> {
|
||||
let maps = self.maps();
|
||||
let total = maps.len();
|
||||
@@ -48,7 +48,7 @@ impl BakeTask {
|
||||
|
||||
let mut passes = BakePasses::new(self.request());
|
||||
for (index, map) in maps.iter().copied().enumerate() {
|
||||
let mut output = passes.bake_map(map, progress, &self.excluded_tiles, self.tracer.as_deref()).map_err(bake_error)?;
|
||||
let mut output = passes.bake_map_in(map, progress, &self.excluded_tiles, self.region(), self.tracer.as_deref()).map_err(bake_error)?;
|
||||
super::preserve_tiles::restore(&mut output, &self.previous_maps, &self.excluded_tiles, self.tiles)?;
|
||||
let Some(data) = output.maps.remove(&map) else { continue };
|
||||
if combined.is_none() {
|
||||
@@ -66,7 +66,14 @@ impl BakeTask {
|
||||
// A resized partial bake also returns unchecked maps that must survive application
|
||||
let mut retained: std::collections::BTreeMap<_, _> = output.maps.into_iter().map(|(map, pixels)| (map, Arc::new(pixels))).collect();
|
||||
retained.insert(map, data);
|
||||
combined = Some(StreamedBake { resolution: output.resolution, height: output.height, maps: retained, tracer: output.tracer });
|
||||
combined = Some(StreamedBake {
|
||||
resolution: output.resolution,
|
||||
height: output.height,
|
||||
maps: retained,
|
||||
tracer: output.tracer,
|
||||
sources: self.sources.clone(),
|
||||
painted_stroke: self.painted_stroke,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -80,18 +87,25 @@ impl BakeTask {
|
||||
height: output.height,
|
||||
maps: output.maps.into_iter().map(|(map, pixels)| (map, Arc::new(pixels))).collect(),
|
||||
tracer: output.tracer,
|
||||
sources: self.sources.clone(),
|
||||
painted_stroke: self.painted_stroke,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn run(&self, progress: &Progress) -> Result<BakeOutput> {
|
||||
let mut output = bake_tiles(&self.request(), progress, &self.excluded_tiles, self.tracer.as_deref()).map_err(bake_error)?;
|
||||
let mut output = bake_tiles_in(&self.request(), progress, &self.excluded_tiles, self.region(), self.tracer.as_deref()).map_err(bake_error)?;
|
||||
super::preserve_tiles::restore(&mut output, &self.previous_maps, &self.excluded_tiles, self.tiles)?;
|
||||
super::preserve_tiles::restore_unchecked(&mut output, &self.previous_maps, &self.excluded_tiles, &[])?;
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
/// The texels to sample, with the stored maps to take the rest from; `None` samples every texel
|
||||
fn region(&self) -> Option<RegionBake<'_>> {
|
||||
self.region.map(|texels| RegionBake { texels, previous: &self.previous_maps.maps })
|
||||
}
|
||||
|
||||
fn request(&self) -> BakeRequest<'_> {
|
||||
let high =
|
||||
self.high.as_ref().map(|source| HighPoly { file_ids: &source.file_ids, mesh: &source.mesh, bvh: &source.bvh, base_color: &source.base_color });
|
||||
@@ -111,7 +125,10 @@ impl BakeTask {
|
||||
}
|
||||
|
||||
fn bake_error(error: texturecraft_bake::BakeError) -> EngineError {
|
||||
EngineError::Other(format!("bake failed: {error}"))
|
||||
match error {
|
||||
texturecraft_bake::BakeError::Cancelled => EngineError::BakeCancelled,
|
||||
error => EngineError::Other(format!("bake failed: {error}")),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
//! A canceled bake keeps the maps it finished: the Baking Log ticked them and the 3D view may have shown them
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use texturecraft_compose::BakedMaps;
|
||||
use texturecraft_core::{BakeSource, BakedMap};
|
||||
|
||||
use crate::{Result, Session};
|
||||
|
||||
impl Session {
|
||||
/// Store the maps the canceled bake of `texture_set` `finished` as one undo step and return them; none at a new output size, which would drop the set's other maps
|
||||
pub fn keep_canceled_bake(
|
||||
&mut self,
|
||||
texture_set: usize,
|
||||
finished: BakedMaps,
|
||||
sources: &BTreeMap<BakedMap, BakeSource>,
|
||||
painted_stroke: u64,
|
||||
) -> Result<Vec<BakedMap>> {
|
||||
let Some(height) = finished.maps.keys().next().map(|map| finished.height(*map)) else { return Ok(Vec::new()) };
|
||||
|
||||
let resized = self.doc.baked.get(&texture_set).is_some_and(|stored| {
|
||||
!stored.maps.is_empty() && (stored.resolution != finished.resolution || stored.maps.keys().any(|map| stored.height(*map) != height))
|
||||
});
|
||||
if resized {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
||||
// A map the bake did not finish keeps the record of what its stored pixels were baked from
|
||||
let kept_sources: BTreeMap<BakedMap, BakeSource> =
|
||||
sources.iter().filter(|(map, _)| finished.maps.contains_key(*map)).map(|(map, source)| (*map, *source)).collect();
|
||||
let kept: Vec<BakedMap> = finished.maps.keys().copied().collect();
|
||||
self.edit("Bake mesh maps", |session| {
|
||||
session.store_bake_maps(texture_set, finished.resolution, height, finished.maps, Some((&kept_sources, painted_stroke)))
|
||||
})?;
|
||||
|
||||
// Named like the Texture Set List and the progress footer, which count sets from 1
|
||||
let name = self.doc.project.texture_sets.get(texture_set).map_or_else(|| format!("{}", texture_set + 1), |set| set.name.clone());
|
||||
self.log.info("Baker", format!("Kept {} baked maps of texture set {name} from the canceled bake", kept.len()));
|
||||
Ok(kept)
|
||||
}
|
||||
}
|
||||
@@ -15,8 +15,8 @@ use serde_json::{Value, json};
|
||||
use texturecraft_bake::tracing::Tracer;
|
||||
use texturecraft_bake::{BakeOutput, BakePaintMap, MAX_RAYS, Progress};
|
||||
use texturecraft_core::{
|
||||
BackfaceMode, BakeAntialiasing, BakeResolution, BakeSettings, BakeSyncGroup, BakedMap, CurvatureMethod, PositionMode, RayDistribution, RaySettings,
|
||||
SelfOcclusion,
|
||||
BackfaceMode, BakeAntialiasing, BakeResolution, BakeSettings, BakeSource, BakeSyncGroup, BakedMap, CurvatureMethod, PositionMode, RayDistribution,
|
||||
RaySettings, SelfOcclusion,
|
||||
};
|
||||
use texturecraft_geom::Mesh;
|
||||
|
||||
@@ -121,7 +121,8 @@ pub(super) fn parse_mesh(file_name: &str, bytes: Vec<u8>) -> Result<BakeMesh> {
|
||||
let imported = texturecraft_formats::import_high_poly_bytes(file_name, &bytes).map_err(|e| EngineError::Other(format!("{file_name}: {e}")))?;
|
||||
let base_color = imported.base_color.into_iter().map(|c| c.map(Arc::new)).collect();
|
||||
let folder = std::path::Path::new(file_name).parent().map(|folder| folder.display().to_string()).filter(|folder| !folder.is_empty());
|
||||
Ok(BakeMesh { name: file_name.to_string(), folder, bytes: Arc::new(bytes), mesh: Arc::new(imported.mesh), base_color })
|
||||
let fingerprint = texturecraft_core::fingerprint(&bytes);
|
||||
Ok(BakeMesh { name: file_name.to_string(), folder, bytes: Arc::new(bytes), mesh: Arc::new(imported.mesh), base_color, fingerprint })
|
||||
}
|
||||
|
||||
impl Session {
|
||||
@@ -130,9 +131,14 @@ impl Session {
|
||||
self.bake_task_of(texture_set, None)
|
||||
}
|
||||
|
||||
/// A task that bakes only `maps` of texture set `texture_set`, checked or not; its other baked maps stay as they are
|
||||
pub fn bake_task_for(&self, texture_set: usize, maps: &[BakedMap]) -> Result<BakeTask> {
|
||||
self.bake_task_of(texture_set, Some(maps))
|
||||
}
|
||||
|
||||
/// The bake of texture set `texture_set`'s map `map` alone, checked or not
|
||||
pub fn bake_task_only(&self, texture_set: usize, map: BakedMap) -> Result<BakeTask> {
|
||||
self.bake_task_of(texture_set, Some(map))
|
||||
self.bake_task_of(texture_set, Some(&[map]))
|
||||
}
|
||||
|
||||
/// Prepare a display-only bake, retaining previous pixels only for the displayed map's excluded UV tiles
|
||||
@@ -142,20 +148,19 @@ impl Session {
|
||||
Ok(task)
|
||||
}
|
||||
|
||||
fn bake_task_of(&self, texture_set: usize, only: Option<BakedMap>) -> Result<BakeTask> {
|
||||
fn bake_task_of(&self, texture_set: usize, only: Option<&[BakedMap]>) -> Result<BakeTask> {
|
||||
let set = self.doc.project.texture_set(texture_set)?;
|
||||
if !set.has_enabled_bake_tiles() {
|
||||
return Err(EngineError::Other(format!("texture set {} has no UV tiles selected for baking", set.name)));
|
||||
}
|
||||
|
||||
let mut settings = set.bake.clone();
|
||||
if let Some(map) = only {
|
||||
settings.maps.select([map]);
|
||||
if let Some(maps) = only {
|
||||
settings.maps.select(maps.iter().copied());
|
||||
}
|
||||
|
||||
// Read from the maps that bake, so a map baked alone while unchecked still gets the colours
|
||||
let needs_low_color = settings.maps.opacity.is_enabled
|
||||
|| (settings.maps.id.is_enabled && settings.maps.id.parameters.source == texturecraft_core::IdColorSource::MaterialColor);
|
||||
let needs_low_color = settings.maps.enabled().any(|map| settings.maps.reads_material_colors(map));
|
||||
let low_base_color = if needs_low_color && (settings.high_poly.use_low_as_high || self.doc.bake_meshes.high.is_empty()) {
|
||||
self.doc
|
||||
.bake_meshes
|
||||
@@ -183,6 +188,8 @@ impl Session {
|
||||
let previous_maps = if excluded_tiles.is_empty() { Default::default() } else { self.doc.baked.get(&texture_set).cloned().unwrap_or_default() };
|
||||
|
||||
let tracer = chosen_tracer(GPU_TRACER.get(), GPU_RAYTRACING.load(Ordering::Relaxed));
|
||||
let sources = self.task_bake_sources(set, settings.maps.enabled());
|
||||
|
||||
Ok(BakeTask {
|
||||
low_base_color,
|
||||
ts: texture_set,
|
||||
@@ -198,6 +205,9 @@ impl Session {
|
||||
excluded_tiles,
|
||||
previous_maps,
|
||||
tracer,
|
||||
sources,
|
||||
painted_stroke: self.painted_strokes,
|
||||
region: None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -260,46 +270,60 @@ impl Session {
|
||||
/// Store a finished bake as one undo step
|
||||
pub fn apply_bake(&mut self, texture_set: usize, output: BakeOutput) -> Result<()> {
|
||||
let tracer = output.tracer.clone();
|
||||
self.edit("Bake mesh maps", |session| session.store_bake(texture_set, output))?;
|
||||
self.edit("Bake mesh maps", |session| session.store_bake(texture_set, output, None))?;
|
||||
self.log.info("Baker", format!("Baked texture set {texture_set} ({tracer})"));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Apply a streamed bake like [`Session::apply_bake`], keeping the maps' shared buffers (the
|
||||
/// preview that showed them holds the same ones)
|
||||
/// Apply a streamed bake like [`Session::apply_bake`], keeping the buffers the preview that showed them shares
|
||||
pub fn apply_streamed_bake(&mut self, texture_set: usize, output: StreamedBake) -> Result<()> {
|
||||
let tracer = output.tracer.clone();
|
||||
self.edit("Bake mesh maps", |session| session.store_bake_maps(texture_set, output.resolution, output.height, output.maps))?;
|
||||
self.edit("Bake mesh maps", |session| {
|
||||
session.store_bake_maps(texture_set, output.resolution, output.height, output.maps, Some((&output.sources, output.painted_stroke)))
|
||||
})?;
|
||||
self.log.info("Baker", format!("Baked texture set {texture_set} ({tracer})"));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn store_bake(&mut self, texture_set: usize, output: BakeOutput) -> Result<()> {
|
||||
/// Store `output`, recording what its maps were baked from when known (see [`Session::record_bake_sources`])
|
||||
fn store_bake(&mut self, texture_set: usize, output: BakeOutput, recorded: Option<(&BTreeMap<BakedMap, BakeSource>, u64)>) -> Result<()> {
|
||||
let maps = output.maps.into_iter().map(|(map, pixels)| (map, Arc::new(pixels))).collect();
|
||||
self.store_bake_maps(texture_set, output.resolution, output.height, maps)
|
||||
self.store_bake_maps(texture_set, output.resolution, output.height, maps, recorded)
|
||||
}
|
||||
|
||||
fn store_bake_maps(&mut self, texture_set: usize, resolution: u32, height: u32, maps: std::collections::BTreeMap<BakedMap, Arc<Vec<f32>>>) -> Result<()> {
|
||||
pub(super) fn store_bake_maps(
|
||||
&mut self,
|
||||
texture_set: usize,
|
||||
resolution: u32,
|
||||
height: u32,
|
||||
maps: BTreeMap<BakedMap, Arc<Vec<f32>>>,
|
||||
recorded: Option<(&BTreeMap<BakedMap, BakeSource>, u64)>,
|
||||
) -> Result<()> {
|
||||
let stored: Vec<BakedMap> = maps.keys().copied().collect();
|
||||
let entry = self.doc.baked.entry(texture_set).or_default();
|
||||
if entry.resolution != resolution || entry.maps.keys().any(|map| entry.height(*map) != height) {
|
||||
let size_changed = entry.resolution != resolution || entry.maps.keys().any(|map| entry.height(*map) != height);
|
||||
crate::meshmap_cmds::detach_imported_sources(&mut self.doc.project, texture_set, |map| size_changed || maps.contains_key(&map));
|
||||
if size_changed {
|
||||
entry.maps.clear();
|
||||
}
|
||||
|
||||
entry.resolution = resolution;
|
||||
entry.maps.extend(maps);
|
||||
self.doc.project.texture_set_mut(texture_set)?.baked = entry.maps.keys().copied().collect();
|
||||
Ok(())
|
||||
self.record_bake_sources(texture_set, recorded, &stored)
|
||||
}
|
||||
|
||||
/// Bake texture set `ts` now (blocking), on the CPU when `cpu`; returns where the rays ran.
|
||||
pub fn bake_now(&mut self, ts: usize, cpu: bool) -> Result<String> {
|
||||
let mut task = self.bake_task(ts)?;
|
||||
/// Bake texture set `texture_set` now (blocking), on the CPU when `cpu`; returns where the rays ran
|
||||
pub fn bake_now(&mut self, texture_set: usize, cpu: bool) -> Result<String> {
|
||||
let mut task = self.bake_task(texture_set)?;
|
||||
if cpu {
|
||||
task.tracer = None;
|
||||
}
|
||||
let out = task.run(&Progress::new())?;
|
||||
let tracer = out.tracer.clone();
|
||||
self.apply_bake(ts, out)?;
|
||||
|
||||
let output = task.run(&Progress::new())?;
|
||||
let tracer = output.tracer.clone();
|
||||
self.edit("Bake mesh maps", |session| session.store_bake(texture_set, output, Some((&task.sources, task.painted_stroke))))?;
|
||||
self.log.info("Baker", format!("Baked texture set {texture_set} ({tracer})"));
|
||||
Ok(tracer)
|
||||
}
|
||||
|
||||
@@ -395,20 +419,6 @@ impl Session {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn saved_bake_paint(&self) -> BTreeMap<(usize, BakePaintTarget), texturecraft_formats::BakePaintData> {
|
||||
self.doc
|
||||
.bake_paint
|
||||
.iter()
|
||||
.map(|(key, map)| (*key, texturecraft_formats::BakePaintData { width: map.width, height: map.height, values: map.values.clone() }))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The bake meshes for a project file: (high polys, cage)
|
||||
pub(crate) fn saved_bake_meshes(&self) -> (Vec<MeshFile>, Option<MeshFile>) {
|
||||
let entry = |mesh: &BakeMesh| (mesh.name.clone(), mesh.bytes.as_ref().clone());
|
||||
(self.doc.bake_meshes.high.iter().map(entry).collect(), self.doc.bake_meshes.cage.as_ref().map(entry))
|
||||
}
|
||||
}
|
||||
|
||||
/// `bake.highPoly.list`: the high polys and the cage (also part of `project.inspect`).
|
||||
@@ -857,16 +867,21 @@ fn bake_run(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
for (index, settings) in next {
|
||||
session.doc.project.texture_set_mut(index)?.bake = settings;
|
||||
}
|
||||
session.begin_bake_log(&sets);
|
||||
|
||||
let mut tracers = Vec::with_capacity(sets.len());
|
||||
for &index in &sets {
|
||||
let mut task = session.bake_task(index)?;
|
||||
if cpu {
|
||||
task.tracer = None;
|
||||
session.bake_log.set_started(index);
|
||||
let baked = bake_one_set(session, index, cpu);
|
||||
match baked {
|
||||
Ok(tracer) => tracers.push(tracer),
|
||||
Err(error) => {
|
||||
session.bake_log.set_failed(index, &error.to_string());
|
||||
// The edit rolls back the sets baked before this one too
|
||||
session.bake_log.discard();
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
let output = task.run(&Progress::new())?;
|
||||
tracers.push(output.tracer.clone());
|
||||
session.store_bake(index, output)?;
|
||||
}
|
||||
Ok(tracers)
|
||||
})?;
|
||||
@@ -877,6 +892,24 @@ fn bake_run(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
Ok(json!({ "baked": sets, "tracer": tracers }))
|
||||
}
|
||||
|
||||
/// Bake every checked map of texture set `index` at once, store them and mark them baked in the Baking Log
|
||||
fn bake_one_set(session: &mut Session, index: usize, cpu: bool) -> Result<String> {
|
||||
let mut task = session.bake_task(index)?;
|
||||
session.bake_log.high_polys_loaded(index);
|
||||
if cpu {
|
||||
task.tracer = None;
|
||||
}
|
||||
|
||||
let maps = task.maps();
|
||||
let output = task.run(&Progress::new())?;
|
||||
let tracer = output.tracer.clone();
|
||||
session.store_bake(index, output, Some((&task.sources, task.painted_stroke)))?;
|
||||
for map in maps {
|
||||
session.bake_log.map_baked(index, map);
|
||||
}
|
||||
Ok(tracer)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod named_tracer;
|
||||
|
||||
|
||||
@@ -1,10 +1,19 @@
|
||||
//! Baking tasks, commands, settings helpers, and the mesh-map baking API
|
||||
|
||||
mod auto_rebake;
|
||||
mod bake_cage_inputs;
|
||||
mod bake_checks;
|
||||
mod bake_high_state;
|
||||
mod bake_log;
|
||||
mod bake_log_high;
|
||||
mod bake_log_map;
|
||||
mod bake_log_matching;
|
||||
mod bake_map_state;
|
||||
mod bake_mesh;
|
||||
mod bake_meshes;
|
||||
mod bake_sources;
|
||||
mod bake_task;
|
||||
mod canceled_bake;
|
||||
mod high_poly_load;
|
||||
mod high_poly_missed;
|
||||
mod layout;
|
||||
@@ -12,6 +21,7 @@ mod merged_high;
|
||||
mod mesh_map_command;
|
||||
mod model_patch;
|
||||
mod paint_command;
|
||||
mod painted_region;
|
||||
mod preserve_tiles;
|
||||
mod streamed_bake;
|
||||
mod streamed_map;
|
||||
@@ -19,6 +29,12 @@ mod sync_command;
|
||||
mod tile_command;
|
||||
|
||||
pub use bake_cage_inputs::BakeCageInputs;
|
||||
pub use bake_high_state::BakeHighState;
|
||||
pub use bake_log::BakeLog;
|
||||
pub use bake_log_high::BakeLogHigh;
|
||||
pub use bake_log_map::BakeLogMap;
|
||||
pub use bake_log_matching::BakeLogMatching;
|
||||
pub use bake_map_state::BakeMapState;
|
||||
pub use bake_mesh::BakeMesh;
|
||||
pub use bake_meshes::BakeMeshes;
|
||||
pub use bake_task::BakeTask;
|
||||
@@ -27,6 +43,7 @@ pub use high_poly_missed::{HIDDEN_HIGH_POLY_VERTEX, high_poly_missed};
|
||||
pub use merged_high::MergedHigh;
|
||||
pub use mesh_map_command::{install_gpu_tracer, meshes_json, set_gpu_raytracing, settings_params};
|
||||
pub use model_patch::settings_patch;
|
||||
pub use painted_region::PaintedRegion;
|
||||
pub use streamed_bake::StreamedBake;
|
||||
pub use streamed_map::StreamedMap;
|
||||
pub use texturecraft_bake::*;
|
||||
@@ -38,6 +55,7 @@ type MaterialColors = std::sync::Arc<Vec<Option<std::sync::Arc<texturecraft_geom
|
||||
pub(crate) fn specs() -> Vec<CommandSpec> {
|
||||
let mut commands = mesh_map_command::specs();
|
||||
commands.extend(paint_command::specs());
|
||||
commands.extend(auto_rebake::specs());
|
||||
commands.extend(tile_command::specs());
|
||||
commands.extend(sync_command::specs());
|
||||
commands
|
||||
|
||||
@@ -3,7 +3,7 @@ use crate::{Result, Session, cmd};
|
||||
use serde_json::Value;
|
||||
use std::sync::Arc;
|
||||
use texturecraft_bake::BakePaintMap;
|
||||
use texturecraft_core::BakePaintTarget;
|
||||
use texturecraft_core::{BakePaintTarget, BakedMap};
|
||||
use texturecraft_geom::glam::Vec2;
|
||||
|
||||
pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
@@ -61,10 +61,13 @@ fn set(session: &mut Session, parameters: &Value, target: BakePaintTarget) -> Re
|
||||
None => BakePaintMap::constant(number(parameters, "value", 1.0, 0.0, 1.0)?),
|
||||
};
|
||||
map.validate().map_err(|error| bad("bake.paint", error.to_string()))?;
|
||||
|
||||
session.edit("Set Bake Paint Map", |session| {
|
||||
session.doc.bake_paint.insert((texture_set, target), Arc::new(map));
|
||||
Ok(())
|
||||
})?;
|
||||
session.note_bake_paint(texture_set, None);
|
||||
|
||||
Ok(super::meshes_json(session))
|
||||
}
|
||||
|
||||
@@ -75,18 +78,31 @@ fn clear(session: &mut Session, parameters: &Value, target: BakePaintTarget) ->
|
||||
session.doc.bake_paint.remove(&(texture_set, target));
|
||||
Ok(())
|
||||
})?;
|
||||
session.note_bake_paint(texture_set, None);
|
||||
}
|
||||
|
||||
Ok(super::meshes_json(session))
|
||||
}
|
||||
|
||||
/// Most UV points one `bake.paint` call takes
|
||||
const MAX_STROKE_POINTS: usize = 100_000;
|
||||
/// Brush radius in UV units: the default, and the smallest that still paints
|
||||
const DEFAULT_RADIUS: f32 = 0.03;
|
||||
const MIN_RADIUS: f32 = 0.00001;
|
||||
/// Brush hardness when a call gives none: halfway between a soft and a hard edge
|
||||
const DEFAULT_HARDNESS: f32 = 0.5;
|
||||
/// Side of a new paint map in texels: the default, and the range a call may ask for
|
||||
const DEFAULT_PAINT_SIZE_TEXELS: u64 = 1024;
|
||||
const PAINT_SIZE_RANGE_TEXELS: std::ops::RangeInclusive<u64> = 16..=4096;
|
||||
|
||||
fn paint(session: &mut Session, parameters: &Value, target: BakePaintTarget) -> Result<Value> {
|
||||
const MAX_POINTS: usize = 100_000;
|
||||
let texture_set = texture_set(session, parameters)?;
|
||||
let points = parameters
|
||||
.get("points")
|
||||
.and_then(Value::as_array)
|
||||
.filter(|points| !points.is_empty() && points.len() <= MAX_POINTS)
|
||||
.ok_or_else(|| bad("bake.paint", "points must contain 1 to 100000 UV coordinates"))?;
|
||||
.filter(|points| !points.is_empty() && points.len() <= MAX_STROKE_POINTS)
|
||||
.ok_or_else(|| bad("bake.paint", format!("points must contain 1 to {MAX_STROKE_POINTS} UV coordinates")))?;
|
||||
|
||||
let points = points
|
||||
.iter()
|
||||
.map(|point| {
|
||||
@@ -97,17 +113,19 @@ fn paint(session: &mut Session, parameters: &Value, target: BakePaintTarget) ->
|
||||
}
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
|
||||
let value = number(parameters, "value", 1.0, 0.0, 1.0)?;
|
||||
let radius = number(parameters, "radius", 0.03, 0.00001, 1.0)?;
|
||||
let hardness = number(parameters, "hardness", 0.5, 0.0, 1.0)?;
|
||||
let radius = number(parameters, "radius", DEFAULT_RADIUS, MIN_RADIUS, 1.0)?;
|
||||
let hardness = number(parameters, "hardness", DEFAULT_HARDNESS, 0.0, 1.0)?;
|
||||
let strength = number(parameters, "strength", 1.0, 0.0, 1.0)?;
|
||||
let size = match parameters.get("size") {
|
||||
None => 1024,
|
||||
None => DEFAULT_PAINT_SIZE_TEXELS,
|
||||
Some(_) => u64p(parameters, "size").ok_or_else(|| bad("bake.paint", "size must be an integer"))?,
|
||||
};
|
||||
if !(16..=4096).contains(&size) {
|
||||
return Err(bad("bake.paint", "size must be between 16 and 4096"));
|
||||
if !PAINT_SIZE_RANGE_TEXELS.contains(&size) {
|
||||
return Err(bad("bake.paint", format!("size must be between {} and {}", PAINT_SIZE_RANGE_TEXELS.start(), PAINT_SIZE_RANGE_TEXELS.end())));
|
||||
}
|
||||
|
||||
let default = match target {
|
||||
BakePaintTarget::Cage => 1.0,
|
||||
BakePaintTarget::Skew => 0.0,
|
||||
@@ -116,13 +134,30 @@ fn paint(session: &mut Session, parameters: &Value, target: BakePaintTarget) ->
|
||||
BakePaintTarget::Cage => "Paint Cage",
|
||||
BakePaintTarget::Skew => "Paint Skew Correction",
|
||||
};
|
||||
|
||||
session.edit_merging(label, boolp(parameters, "continue") == Some(true), |session| {
|
||||
// Skew painting starts with Auto-rebake on for the Normal map, which shows the skew best, unless the set picked one
|
||||
let first_skew = target == BakePaintTarget::Skew && !session.doc.bake_paint.contains_key(&(texture_set, target));
|
||||
let set = session.doc.project.texture_set_mut(texture_set)?;
|
||||
if first_skew && set.auto_rebake.is_none() {
|
||||
set.auto_rebake = Some(BakedMap::Normal);
|
||||
}
|
||||
|
||||
let map = session.doc.bake_paint.entry((texture_set, target)).or_insert_with(|| Arc::new(BakePaintMap::constant(default)));
|
||||
if map.values.len() == 1 {
|
||||
*map = Arc::new(map.resized(size as u32, size as u32).map_err(|error| bad("bake.paint", error.to_string()))?);
|
||||
}
|
||||
Arc::make_mut(map).paint(&points, radius, value, hardness, strength).map_err(|error| bad("bake.paint", error.to_string()))
|
||||
})?;
|
||||
|
||||
// Bilinear sampling extends each dab's reach by one paint texel
|
||||
let paint_texel = session.doc.bake_paint.get(&(texture_set, target)).map_or(0.0, |map| 1.0 / map.width.min(map.height).max(1) as f32);
|
||||
let reach = Vec2::splat(radius + paint_texel);
|
||||
let uv_min = points.iter().fold(Vec2::INFINITY, |min, point| min.min(*point)) - reach;
|
||||
let uv_max = points.iter().fold(Vec2::NEG_INFINITY, |max, point| max.max(*point)) + reach;
|
||||
|
||||
session.note_bake_paint(texture_set, Some((uv_min, uv_max)));
|
||||
|
||||
Ok(super::meshes_json(session))
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
//! Where skew or cage painting changed what a texture set's transfer rays read since its maps were baked
|
||||
|
||||
use texturecraft_bake::{TexelBox, region_keeps_pixels};
|
||||
use texturecraft_core::{BakeSource, BakedMap};
|
||||
use texturecraft_geom::glam::Vec2;
|
||||
|
||||
use crate::{Result, Session};
|
||||
|
||||
/// The UV box painted since the last bake of a texture set's auto-rebake map
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct PaintedRegion {
|
||||
pub uv_min: Vec2,
|
||||
pub uv_max: Vec2,
|
||||
/// Counts up with every stroke, so a rebake can tell a newer stroke from the one it bakes
|
||||
pub stroke: u64,
|
||||
}
|
||||
|
||||
/// Texels added around a painted box: bilinear sampling of the paint map and antialiasing samples reach one texel past it
|
||||
const MARGIN_TEXELS: u32 = 1;
|
||||
|
||||
impl Session {
|
||||
/// Note that the bake paint of `texture_set` changed inside `uv_min`..`uv_max` (the whole map when `None`)
|
||||
pub(super) fn note_bake_paint(&mut self, texture_set: usize, uv_box: Option<(Vec2, Vec2)>) {
|
||||
let (uv_min, uv_max) = uv_box.unwrap_or((Vec2::ZERO, Vec2::ONE));
|
||||
let (uv_min, uv_max) = match self.doc.painted_regions.get(&texture_set) {
|
||||
Some(region) => (region.uv_min.min(uv_min), region.uv_max.max(uv_max)),
|
||||
None => (uv_min, uv_max),
|
||||
};
|
||||
self.painted_strokes += 1;
|
||||
self.doc.painted_regions.insert(texture_set, PaintedRegion { uv_min, uv_max, stroke: self.painted_strokes });
|
||||
}
|
||||
|
||||
/// Forget the painted box of `texture_set` once its auto-rebake map is baked again, unless a stroke came after `painted_stroke`
|
||||
pub(super) fn forget_painted_region(&mut self, texture_set: usize, stored: &[BakedMap], painted_stroke: u64) {
|
||||
let auto = self.doc.project.texture_sets.get(texture_set).and_then(|set| set.auto_rebake);
|
||||
let painted_since = self.doc.painted_regions.get(&texture_set).is_some_and(|region| region.stroke > painted_stroke);
|
||||
if !painted_since && auto.is_none_or(|map| stored.contains(&map)) {
|
||||
self.doc.painted_regions.remove(&texture_set);
|
||||
}
|
||||
}
|
||||
|
||||
/// Baked auto-rebake maps changed only by painting since, as (set, map, what a bake reads now, newest stroke)
|
||||
pub fn auto_rebake_painted(&self) -> Vec<(usize, BakedMap, BakeSource, u64)> {
|
||||
let regions = self.doc.painted_regions.iter();
|
||||
regions
|
||||
.filter_map(|(index, region)| {
|
||||
let set = self.doc.project.texture_sets.get(*index)?;
|
||||
let map = set.auto_rebake.filter(|map| set.baked.contains(map))?;
|
||||
let from_high = !set.bake.high_poly.use_low_as_high && !self.doc.bake_meshes.high.is_empty();
|
||||
from_high.then_some(())?;
|
||||
let current = self.bake_source(*index, map).ok()?;
|
||||
|
||||
// Only painting changed it: a map without a record is never out of date
|
||||
let up_to_date = set.bake_sources.get(&map).is_none_or(|record| *record == current);
|
||||
up_to_date.then_some((*index, map, current, region.stroke))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A task that bakes `map` again only where painting changed it, keeping the rest; else the whole map
|
||||
pub fn bake_painted_task(&self, texture_set: usize, map: BakedMap) -> Result<crate::BakeTask> {
|
||||
let mut task = self.bake_task_for(texture_set, &self.auto_rebake_maps(texture_set, map))?;
|
||||
let Some(region) = self.doc.painted_regions.get(&texture_set) else { return Ok(task) };
|
||||
|
||||
let (width, height) = task.settings.common.output_size();
|
||||
let stored =
|
||||
self.doc.baked.get(&texture_set).filter(|stored| stored.resolution == width && stored.height(map) == height && stored.maps.contains_key(&map));
|
||||
let Some(stored) = stored.filter(|_| task.tiles == (1, 1) && region_keeps_pixels(map)) else { return Ok(task) };
|
||||
|
||||
let texel = |uv: f32, size: u32, round: fn(f32) -> f32| (round(uv.clamp(0.0, 1.0) * size as f32) as u32).min(size);
|
||||
let painted = TexelBox {
|
||||
min: (texel(region.uv_min.x, width, f32::floor), texel(region.uv_min.y, height, f32::floor)),
|
||||
max: (texel(region.uv_max.x, width, f32::ceil), texel(region.uv_max.y, height, f32::ceil)),
|
||||
};
|
||||
task.previous_maps = stored.clone();
|
||||
task.region = Some(painted.grown(MARGIN_TEXELS, width, height));
|
||||
Ok(task)
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use texturecraft_core::BakedMap;
|
||||
use texturecraft_core::{BakeSource, BakedMap};
|
||||
|
||||
/// The result of a streamed bake: the finished maps stay shared (`Arc`) with whoever was shown them,
|
||||
/// so the preview and the document hold one buffer per map, never two
|
||||
@@ -11,4 +11,8 @@ pub struct StreamedBake {
|
||||
pub height: u32,
|
||||
pub maps: BTreeMap<BakedMap, Arc<Vec<f32>>>,
|
||||
pub tracer: String,
|
||||
/// What the baked maps were baked from (the task's [`crate::BakeTask::sources`])
|
||||
pub sources: BTreeMap<BakedMap, BakeSource>,
|
||||
/// The task's [`crate::BakeTask::painted_stroke`]
|
||||
pub painted_stroke: u64,
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
//! The `bake.log` query: the Baking Log's rows for automation
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::commands::{CommandSpec, always, bad};
|
||||
use crate::{Result, Session, cmd};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
"bake.log",
|
||||
"Baking log",
|
||||
[],
|
||||
None,
|
||||
"{} → {running, maps: [{textureSet, setName, map, state: \"waiting\" | \"baking\" | \"baked\" | \"failed\" | \"canceled\", reason?}], highPolys: [{textureSet, setName, file, state: \"waiting\" | \"loading\" | \"loaded\" | \"failed\" | \"canceled\", reason?}], matching: null | {lowSuffix, highSuffix, pairs: [{low: name | null, high: name | null}]}}. The latest bake map by map in bake order, the high poly files each set bakes from, and how parts paired by name, as the Baking Log shows them; `reason` says why a map or file failed; a `null` side of a pair is a part with no partner; `matching` is null when no set matched by mesh name. Empty before the first bake",
|
||||
always,
|
||||
log
|
||||
)]
|
||||
}
|
||||
|
||||
fn log(session: &mut Session, _: &Value) -> Result<Value> {
|
||||
let log = &session.bake_log;
|
||||
let maps = log.maps.iter().map(|row| entry(&row.state, row.texture_set, &row.set_name, "map", json!(row.map.id()))).collect::<Result<Vec<Value>>>()?;
|
||||
let high_polys = log.highs.iter().map(|row| entry(&row.state, row.texture_set, &row.set_name, "file", json!(row.file))).collect::<Result<Vec<Value>>>()?;
|
||||
let matching = log.matching.as_ref().map(|matching| {
|
||||
let pairs: Vec<Value> = matching.pairs.iter().map(|pair| json!({ "low": pair.low, "high": pair.high })).collect();
|
||||
json!({ "lowSuffix": matching.low_suffix, "highSuffix": matching.high_suffix, "pairs": pairs })
|
||||
});
|
||||
|
||||
Ok(json!({ "running": log.is_running() || log.is_loading_high_polys(), "maps": maps, "highPolys": high_polys, "matching": matching }))
|
||||
}
|
||||
|
||||
/// One row: its `state` (and `reason`), its texture set, and an item identified by `key`
|
||||
fn entry(state: &impl serde::Serialize, texture_set: usize, set_name: &str, key: &str, value: Value) -> Result<Value> {
|
||||
let mut entry = serde_json::to_value(state).map_err(|error| bad("bake.log", error.to_string()))?;
|
||||
|
||||
if let Some(fields) = entry.as_object_mut() {
|
||||
fields.insert("textureSet".into(), json!(texture_set));
|
||||
fields.insert("setName".into(), json!(set_name));
|
||||
fields.insert(key.into(), value);
|
||||
}
|
||||
|
||||
Ok(entry)
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
//! Live bake preview: while the app bakes, the 3D view shows each mesh map on the model as soon
|
||||
//! as it is finished ([`crate::BakeTask::run_streaming`]). The streamed maps live here, not in
|
||||
//! the document: nothing enters the undo history until a texture set's bake is applied
|
||||
//! ([`Session::apply_streamed_bake`]). Cancellation leaves the current set unchanged; sets already
|
||||
//! applied keep their results and undo steps. The preview shows one map at a time, raw on the
|
||||
//! model; maps and texture sets not baked yet show their neutral value.
|
||||
//! ([`Session::apply_streamed_bake`]). The UI can apply eligible finished maps on cancellation.
|
||||
//! Already applied sets keep their results and undo steps. The preview shows one raw map at a time.
|
||||
//! Maps and texture sets that are still pending show their neutral value.
|
||||
|
||||
mod preview_set;
|
||||
mod preview_show;
|
||||
|
||||
@@ -31,7 +31,7 @@ impl CommandSpec {
|
||||
/// that only return data or do nothing without parameters, and the ones that replace the
|
||||
/// open project (the menu asks to save first).
|
||||
pub fn bindable(&self) -> bool {
|
||||
const NOT_FROM_A_KEY: [&str; 13] = [
|
||||
const NOT_FROM_A_KEY: &[&str] = &[
|
||||
"project.inspect",
|
||||
"project.templates",
|
||||
"project.new",
|
||||
@@ -43,8 +43,10 @@ impl CommandSpec {
|
||||
"textureSet.parts",
|
||||
"bake.settings",
|
||||
"bake.preview",
|
||||
"bake.log",
|
||||
"camera.set",
|
||||
"textureSet.settings",
|
||||
"resource.status",
|
||||
];
|
||||
const NOTHING_WITHOUT_PARAMS: [&str; 4] = ["layer.blend", "tool.stencil", "tool.fillSelection", "tool.path"];
|
||||
!(self.id.ends_with(".list") || NOT_FROM_A_KEY.contains(&self.id) || NOTHING_WITHOUT_PARAMS.contains(&self.id)) && params_all_optional(self.params)
|
||||
@@ -139,11 +141,13 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(crate::project_cmds::specs());
|
||||
v.extend(crate::bake::specs());
|
||||
v.extend(crate::bake_preview::specs());
|
||||
v.extend(crate::bake_log_cmds::specs());
|
||||
v.extend(crate::materialx_cmds::specs());
|
||||
v.extend(crate::pbr_cmds::specs());
|
||||
v.extend(crate::file_cmds::specs());
|
||||
v.extend(crate::preset_cmds::specs());
|
||||
v.extend(crate::resource_cmds::specs());
|
||||
v.extend(crate::resource_update_cmds::specs());
|
||||
v.extend(crate::material_lib::specs());
|
||||
v.extend(crate::link_cmds::specs());
|
||||
v.extend(crate::smart_masks::specs());
|
||||
@@ -371,7 +375,18 @@ mod tests {
|
||||
] {
|
||||
assert!(!bindable(id), "{id} needs a parameter");
|
||||
}
|
||||
for id in ["layer.move", "layer.list", "project.inspect", "edit.history", "export.presets", "tool.state", "project.new", "camera.set", "layer.blend"] {
|
||||
for id in [
|
||||
"layer.move",
|
||||
"layer.list",
|
||||
"project.inspect",
|
||||
"edit.history",
|
||||
"export.presets",
|
||||
"tool.state",
|
||||
"project.new",
|
||||
"camera.set",
|
||||
"layer.blend",
|
||||
"bake.log",
|
||||
] {
|
||||
assert!(!bindable(id), "{id} is a query or has several forms");
|
||||
}
|
||||
}
|
||||
|
||||
+206
-70
@@ -21,6 +21,28 @@ use crate::commands::{CommandSpec, always, bad, normal_format_param, strp, u64p}
|
||||
use crate::session::{Document, Session};
|
||||
use crate::{EngineError, Result, cmd};
|
||||
|
||||
type BakePaintMaps = BTreeMap<(usize, texturecraft_core::BakePaintTarget), Arc<texturecraft_bake::BakePaintMap>>;
|
||||
|
||||
fn prepare_archive<Bytes>(archive: &mut ProjectFile<Bytes, Bytes>, uv_source: Option<&Mesh>, bake_paint: &BakePaintMaps) {
|
||||
let project = &mut archive.project;
|
||||
project.format_version = project.save_format_version();
|
||||
|
||||
// Drop pixel images whose size no longer matches their texture set
|
||||
let size_of = |id: texturecraft_core::LayerId| {
|
||||
project.locate(id).and_then(|(ts, _, _)| project.texture_sets.get(ts)).map(TextureSet::size).or_else(|| {
|
||||
project.effect(id).and_then(|(owner, _)| project.locate(owner)).and_then(|(ts, _, _)| project.texture_sets.get(ts)).map(TextureSet::size)
|
||||
})
|
||||
};
|
||||
archive.pixels.layers.retain(|(id, _), img| size_of(*id) == Some((img.width(), img.height())));
|
||||
archive.pixels.masks.retain(|id, img| size_of(*id) == Some((img.width(), img.height())));
|
||||
|
||||
archive.mesh_uvs = uv_source.map(texturecraft_formats::mesh_import::corner_uvs);
|
||||
archive.bake_paint = bake_paint
|
||||
.iter()
|
||||
.map(|(key, map)| (*key, texturecraft_formats::BakePaintData { width: map.width, height: map.height, values: map.values.clone() }))
|
||||
.collect();
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
@@ -69,7 +91,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export Mesh...",
|
||||
["File"],
|
||||
None,
|
||||
"{path: .obj, .glb, .usda, .usdc or .usdz file, format?: obj|glb|usda|usdc|usdz (default: from the extension, else obj); obj writes its .mtl and textures, usda/usdc their textures, next to the file} → {path, textures?}",
|
||||
"{path: .obj, .glb, .usda, .usdc or .usdz file, format?: obj|glb|usda|usdc|usdz (default: from the extension, else obj), recomputeNormals?: bool (default false: smooth area-weighted normals replace the stored normals on the exported copy only); obj writes its .mtl and textures, usda/usdc their textures, next to the file} → {path, textures?}",
|
||||
always,
|
||||
export_mesh
|
||||
),
|
||||
@@ -115,19 +137,38 @@ fn read_stored_mesh(project: &Project, ext: &str, bytes: &[u8], saved_layout: Op
|
||||
impl Session {
|
||||
/// The working mesh as Wavefront OBJ (with its own UVs, UDIM tiles included).
|
||||
pub fn mesh_obj_bytes(&self) -> Result<Vec<u8>> {
|
||||
texturecraft_formats::obj_bytes(&self.source_mesh(), &self.doc.project.name).map_err(fe)
|
||||
self.mesh_obj_bytes_with_normals(false)
|
||||
}
|
||||
|
||||
/// [`Session::mesh_obj_bytes`], optionally replacing normals on the exported copy only.
|
||||
pub fn mesh_obj_bytes_with_normals(&self, recompute_normals: bool) -> Result<Vec<u8>> {
|
||||
let mut mesh = self.source_mesh();
|
||||
if recompute_normals {
|
||||
mesh.compute_smooth_normals();
|
||||
}
|
||||
texturecraft_formats::obj_bytes(&mesh, &self.doc.project.name).map_err(fe)
|
||||
}
|
||||
|
||||
/// [`Session::mesh_obj_bytes`] with an MTL material library and each material's maps (like
|
||||
/// [`Session::mesh_usd`]'s), to write next to it, named after `stem` (the OBJ file's).
|
||||
pub fn mesh_obj_with_mtl(&mut self, stem: &str) -> Result<(Vec<u8>, texturecraft_formats::NamedFiles)> {
|
||||
// shortcut: UV-tiled sets get no maps (the OBJ keeps the mesh's UDIM UVs and an MTL map is
|
||||
// one image); their tiles export through Export textures with `$udim` names.
|
||||
self.mesh_obj_with_mtl_and_normals(stem, false)
|
||||
}
|
||||
|
||||
/// [`Session::mesh_obj_with_mtl`], optionally replacing normals on the exported copy only.
|
||||
pub fn mesh_obj_with_mtl_and_normals(&mut self, stem: &str, recompute_normals: bool) -> Result<(Vec<u8>, texturecraft_formats::NamedFiles)> {
|
||||
// OBJ keeps UDIM UVs, while each MTL map can hold only one image
|
||||
// Export tiled textures separately with `$udim` names
|
||||
let mut mesh = self.source_mesh();
|
||||
// A mesh without materials has one implicit material (and texture set).
|
||||
if recompute_normals {
|
||||
mesh.compute_smooth_normals();
|
||||
}
|
||||
|
||||
// A mesh without materials has one implicit material and texture set
|
||||
if mesh.materials.is_empty() {
|
||||
mesh.materials.push("default".into());
|
||||
}
|
||||
|
||||
let files = self.material_files(texturecraft_formats::usd_export_options(), false, mesh.materials.len())?;
|
||||
texturecraft_formats::obj_with_mtl(&mesh, &self.doc.project.name, stem, &files).map_err(fe)
|
||||
}
|
||||
@@ -136,16 +177,36 @@ impl Session {
|
||||
/// composite, through the texture export pipeline) embedded. glTF has no UV tiles: a
|
||||
/// UV-tiled set embeds its tile atlas, with the mesh's UVs in atlas space.
|
||||
pub fn mesh_glb_bytes(&mut self) -> Result<Vec<u8>> {
|
||||
self.mesh_glb_bytes_with_normals(false)
|
||||
}
|
||||
|
||||
/// [`Session::mesh_glb_bytes`], optionally replacing normals on the exported copy only.
|
||||
pub fn mesh_glb_bytes_with_normals(&mut self, recompute_normals: bool) -> Result<Vec<u8>> {
|
||||
let files = self.material_files(texturecraft_formats::glb_export_options(), true, self.mesh.materials.len())?;
|
||||
let textures: Vec<_> = files.into_iter().map(texturecraft_formats::GlbTextures::from_files).collect();
|
||||
texturecraft_formats::glb_bytes(&self.mesh, &self.doc.project.name, &textures).map_err(fe)
|
||||
let mut mesh = Cow::Borrowed(self.mesh.as_ref());
|
||||
if recompute_normals {
|
||||
mesh.to_mut().compute_smooth_normals();
|
||||
}
|
||||
|
||||
texturecraft_formats::glb_bytes(&mesh, &self.doc.project.name, &textures).map_err(fe)
|
||||
}
|
||||
|
||||
/// The working mesh as USD with a UsdPreviewSurface per material (textures like
|
||||
/// [`Session::mesh_glb_bytes`]): usdz packages them, usda / usdc list them to write alongside.
|
||||
pub fn mesh_usd(&mut self, format: texturecraft_formats::UsdFormat) -> Result<texturecraft_formats::UsdExport> {
|
||||
self.mesh_usd_with_normals(format, false)
|
||||
}
|
||||
|
||||
/// [`Session::mesh_usd`], optionally replacing normals on the exported copy only.
|
||||
pub fn mesh_usd_with_normals(&mut self, format: texturecraft_formats::UsdFormat, recompute_normals: bool) -> Result<texturecraft_formats::UsdExport> {
|
||||
let files = self.material_files(texturecraft_formats::usd_export_options(), true, self.mesh.materials.len())?;
|
||||
texturecraft_formats::usd_bytes(&self.mesh, &self.doc.project.name, &files, format).map_err(fe)
|
||||
let mut mesh = Cow::Borrowed(self.mesh.as_ref());
|
||||
if recompute_normals {
|
||||
mesh.to_mut().compute_smooth_normals();
|
||||
}
|
||||
|
||||
texturecraft_formats::usd_bytes(&mesh, &self.doc.project.name, &files, format).map_err(fe)
|
||||
}
|
||||
|
||||
/// The texture sets of the first `materials` materials rendered with `opts` (as a tile atlas
|
||||
@@ -184,7 +245,7 @@ impl Session {
|
||||
// Packed mesh files can have spare capacity that the project would otherwise retain
|
||||
let mut source = bytes.into_owned();
|
||||
source.shrink_to_fit();
|
||||
session.mesh_source = Some((extension, source));
|
||||
session.mesh_source = Some((extension, Arc::new(source)));
|
||||
session.doc.project.mesh_file = leaf_of(file_name);
|
||||
session.doc.project.mesh_rebuild_uvs = rebuild_uvs;
|
||||
session.doc.project.cameras = imported.cameras;
|
||||
@@ -232,6 +293,7 @@ impl Session {
|
||||
pixels: project_file.pixels,
|
||||
baked: project_file.baked,
|
||||
resources,
|
||||
painted_regions: Default::default(),
|
||||
},
|
||||
mesh,
|
||||
project_file.mesh,
|
||||
@@ -245,58 +307,44 @@ impl Session {
|
||||
Ok(session)
|
||||
}
|
||||
|
||||
/// The project with independently owned resource bytes.
|
||||
pub fn project_file(&self) -> ProjectFile {
|
||||
let resources = self.doc.resources.iter().map(|(name, bytes)| (name.clone(), bytes.as_ref().clone())).collect();
|
||||
self.project_with_resources(resources)
|
||||
}
|
||||
|
||||
/// A save snapshot that shares immutable resource payloads with the document.
|
||||
pub fn project_snapshot(&self) -> ProjectFile<Arc<Vec<u8>>> {
|
||||
self.project_with_resources(self.doc.resources.clone())
|
||||
}
|
||||
|
||||
/// The layout a project with rebuilt mesh UVs saves, so reopening it never runs the unwrapper.
|
||||
fn saved_uv_layout(&self) -> Option<Vec<Vec2>> {
|
||||
(self.doc.project.mesh_rebuild_uvs && self.mesh_source.is_some()).then(|| texturecraft_formats::mesh_import::corner_uvs(&self.source))
|
||||
}
|
||||
|
||||
fn project_with_resources<Resource>(&self, resources: BTreeMap<String, Resource>) -> ProjectFile<Resource> {
|
||||
let mut pixels = self.doc.pixels.clone();
|
||||
|
||||
// Drop pixel images whose size no longer matches their texture set
|
||||
let size_of = |id: texturecraft_core::LayerId| {
|
||||
self.doc.project.locate(id).and_then(|(ts, _, _)| self.doc.project.texture_sets.get(ts)).map(TextureSet::size).or_else(|| {
|
||||
self.doc
|
||||
.project
|
||||
.effect(id)
|
||||
.and_then(|(owner, _)| self.doc.project.locate(owner))
|
||||
.and_then(|(ts, _, _)| self.doc.project.texture_sets.get(ts))
|
||||
.map(TextureSet::size)
|
||||
})
|
||||
};
|
||||
pixels.layers.retain(|(id, _), img| size_of(*id) == Some((img.width(), img.height())));
|
||||
pixels.masks.retain(|id, img| size_of(*id) == Some((img.width(), img.height())));
|
||||
|
||||
let (high_poly, cage) = self.saved_bake_meshes();
|
||||
let mut project = self.doc.project.clone();
|
||||
project.format_version = project.save_format_version();
|
||||
|
||||
/// Capture just the archive inputs. The caller prepares derived data before writing.
|
||||
fn capture_archive<Bytes>(&self, resources: BTreeMap<String, Bytes>, store_mesh_bytes: impl Fn(&Arc<Vec<u8>>) -> Bytes) -> ProjectFile<Bytes, Bytes> {
|
||||
let bake_mesh = |mesh: &crate::BakeMesh| (mesh.name.clone(), store_mesh_bytes(&mesh.bytes));
|
||||
ProjectFile {
|
||||
project,
|
||||
pixels,
|
||||
project: self.doc.project.clone(),
|
||||
pixels: self.doc.pixels.clone(),
|
||||
baked: self.doc.baked.clone(),
|
||||
mesh: self.mesh_source.clone(),
|
||||
mesh_uvs: self.saved_uv_layout(),
|
||||
high_poly,
|
||||
cage,
|
||||
bake_paint: self.saved_bake_paint(),
|
||||
mesh: self.mesh_source.as_ref().map(|(extension, bytes)| (extension.clone(), store_mesh_bytes(bytes))),
|
||||
mesh_uvs: None,
|
||||
high_poly: self.doc.bake_meshes.high.iter().map(bake_mesh).collect(),
|
||||
cage: self.doc.bake_meshes.cage.as_ref().map(bake_mesh),
|
||||
bake_paint: BTreeMap::new(),
|
||||
thumbnail: None,
|
||||
resources,
|
||||
warnings: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The project with independently owned resource and mesh bytes.
|
||||
pub fn project_file(&self) -> ProjectFile {
|
||||
let resources = self.doc.resources.iter().map(|(name, bytes)| (name.clone(), bytes.as_ref().clone())).collect();
|
||||
let mut archive = self.capture_archive(resources, |bytes| bytes.as_ref().clone());
|
||||
prepare_archive(&mut archive, self.saved_uv_source().map(Arc::as_ref), &self.doc.bake_paint);
|
||||
archive
|
||||
}
|
||||
|
||||
/// A save snapshot that shares immutable resource and mesh payloads with the document.
|
||||
pub fn project_snapshot(&self) -> ProjectFile<Arc<Vec<u8>>, Arc<Vec<u8>>> {
|
||||
let mut archive = self.capture_archive(self.doc.resources.clone(), Arc::clone);
|
||||
prepare_archive(&mut archive, self.saved_uv_source().map(Arc::as_ref), &self.doc.bake_paint);
|
||||
archive
|
||||
}
|
||||
|
||||
/// The imported geometry needed to save rebuilt corner UVs and skip unwrapping on reopen.
|
||||
fn saved_uv_source(&self) -> Option<&Arc<Mesh>> {
|
||||
(self.doc.project.mesh_rebuild_uvs && self.mesh_source.is_some()).then_some(&self.source)
|
||||
}
|
||||
|
||||
pub fn to_project_bytes(&self) -> Result<Vec<u8>> {
|
||||
let mut reservation = texturecraft_formats::RamReservation::for_save().map_err(fe)?;
|
||||
reservation.save_bytes(&self.project_snapshot()).map_err(fe)
|
||||
@@ -537,21 +585,22 @@ mod native {
|
||||
}
|
||||
|
||||
pub fn save_to(s: &mut Session, path: &str, adopt: bool) -> Result<Value> {
|
||||
let path = if ext_of(path) == PROJECT_EXT { path.to_string() } else { format!("{path}.{PROJECT_EXT}") };
|
||||
let mut reservation = texturecraft_formats::RamReservation::for_save().map_err(fe)?;
|
||||
reservation.save(Path::new(&path), &s.project_snapshot()).map_err(fe)?;
|
||||
|
||||
if adopt {
|
||||
s.path = Some(path.clone());
|
||||
s.modified = false;
|
||||
}
|
||||
s.log.info("Project", format!("Saved {path}"));
|
||||
Ok(json!({ "path": path }))
|
||||
let output = s.save_task(path, adopt).run(None)?;
|
||||
output.apply(s);
|
||||
Ok(json!({ "path": output.path }))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub use native::{absolute, open_path, read_mesh};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
mod save_output;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
mod save_target;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
mod save_task;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub use {save_output::SaveOutput, save_task::SaveTask};
|
||||
|
||||
/// `file.new {mesh, name?, resolution?, uvTiles?, rebuildUvs?, template?, importCameras?}`: a new project from the
|
||||
/// mesh file `mesh`, remembering its path for Reimport mesh.
|
||||
@@ -661,7 +710,7 @@ impl Session {
|
||||
}
|
||||
None => match &self.mesh_source {
|
||||
Some((ext, bytes)) => {
|
||||
let layout = self.saved_uv_layout();
|
||||
let layout = self.saved_uv_source().map(|source| texturecraft_formats::mesh_import::corner_uvs(source));
|
||||
let mesh = read_stored_mesh(&self.doc.project, ext, bytes, layout.as_deref())?;
|
||||
(mesh, None, Vec::new(), self.doc.project.mesh_file.clone())
|
||||
}
|
||||
@@ -671,7 +720,8 @@ impl Session {
|
||||
|
||||
check_materials(&self.doc.project, &mesh)?;
|
||||
let mut doc = self.doc.clone();
|
||||
if let Some((ext, _)) = replacement_source.as_ref().or(self.mesh_source.as_ref()) {
|
||||
let extension = replacement_source.as_ref().map(|(extension, _)| extension).or_else(|| self.mesh_source.as_ref().map(|(extension, _)| extension));
|
||||
if let Some(ext) = extension {
|
||||
doc.project.mesh = format!("mesh.{ext}");
|
||||
doc.project.mesh_file = mesh_file;
|
||||
doc.project.mesh_rebuild_uvs = rebuild_uvs;
|
||||
@@ -695,6 +745,10 @@ impl Session {
|
||||
|
||||
next.modified = true;
|
||||
next.project_id = self.project_id;
|
||||
|
||||
// Keep the stroke counter aligned with the painted regions in the cloned document
|
||||
next.painted_strokes = self.painted_strokes;
|
||||
|
||||
let preserved = preserve_strokes.then(|| crate::preserve::preserve_strokes(self, &mut next));
|
||||
|
||||
// Keep the stored source in the current session until reimport succeeds
|
||||
@@ -703,6 +757,7 @@ impl Session {
|
||||
}
|
||||
|
||||
self.switch_to(next);
|
||||
|
||||
Ok(preserved.map_or(Value::Null, |n| json!({ "preserved": n })))
|
||||
}
|
||||
}
|
||||
@@ -1159,7 +1214,7 @@ fn write_materialx(
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn export_mesh(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = native::path_param(p, "path", "file.exportMesh")?;
|
||||
let out = s.mesh_export(path, strp(p, "format"))?;
|
||||
let out = s.mesh_export_with_normals(path, strp(p, "format"), crate::commands::boolp(p, "recomputeNormals").unwrap_or(false))?;
|
||||
let dir = std::path::Path::new(&out.path).parent().unwrap_or(std::path::Path::new(""));
|
||||
let texture_paths: Vec<std::path::PathBuf> = out.textures.iter().map(|(name, _)| dir.join(name)).collect();
|
||||
let main_path = std::path::PathBuf::from(&out.path);
|
||||
@@ -1196,6 +1251,12 @@ impl Session {
|
||||
/// The working mesh as a file for `path`, in `format` (obj, glb, usda, usdc, usdz; default:
|
||||
/// from the extension, else OBJ). The extension is appended when it doesn't match.
|
||||
pub fn mesh_export(&mut self, path: &str, format: Option<&str>) -> Result<MeshExport> {
|
||||
self.mesh_export_with_normals(path, format, false)
|
||||
}
|
||||
|
||||
/// [`Session::mesh_export`], optionally computing smooth area-weighted normals on the
|
||||
/// exported copy. The project's source and render meshes are never changed.
|
||||
pub fn mesh_export_with_normals(&mut self, path: &str, format: Option<&str>, recompute_normals: bool) -> Result<MeshExport> {
|
||||
let ext = match format {
|
||||
Some(f) if MESH_EXPORT_FORMATS.contains(&f) => f.to_string(),
|
||||
Some(other) => return Err(bad("file.exportMesh", format!("unknown mesh format `{other}` ({})", MESH_EXPORT_FORMATS.join(", ")))),
|
||||
@@ -1203,14 +1264,16 @@ impl Session {
|
||||
None => "obj".into(),
|
||||
};
|
||||
let path = if ext_of(path) == ext { path.to_string() } else { format!("{path}.{ext}") };
|
||||
|
||||
let (bytes, textures) = match (ext.as_str(), texturecraft_formats::UsdFormat::from_ext(&ext)) {
|
||||
("glb", _) => (self.mesh_glb_bytes()?, Vec::new()),
|
||||
("glb", _) => (self.mesh_glb_bytes_with_normals(recompute_normals)?, Vec::new()),
|
||||
(_, Some(format)) => {
|
||||
let usd = self.mesh_usd(format)?;
|
||||
let usd = self.mesh_usd_with_normals(format, recompute_normals)?;
|
||||
(usd.bytes, usd.textures)
|
||||
}
|
||||
_ => self.mesh_obj_with_mtl(std::path::Path::new(&path).file_stem().and_then(|s| s.to_str()).unwrap_or("mesh"))?,
|
||||
_ => self.mesh_obj_with_mtl_and_normals(std::path::Path::new(&path).file_stem().and_then(|s| s.to_str()).unwrap_or("mesh"), recompute_normals)?,
|
||||
};
|
||||
|
||||
Ok(MeshExport { path, bytes, textures })
|
||||
}
|
||||
}
|
||||
@@ -1402,6 +1465,72 @@ f 1/1 2/2 3/3
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mesh_export_can_recompute_normals_without_changing_the_project() {
|
||||
let mut s = Session::new_project("t", primitives::cube(1.0), "builtin:cube", None, 128).unwrap();
|
||||
std::sync::Arc::make_mut(&mut s.source).normals.fill(texturecraft_geom::glam::Vec3::Y);
|
||||
std::sync::Arc::make_mut(&mut s.mesh).normals.fill(texturecraft_geom::glam::Vec3::Y);
|
||||
let mut expected = s.source_mesh();
|
||||
expected.compute_smooth_normals();
|
||||
let dir = std::env::temp_dir().join(format!("tc_export_recompute_{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
|
||||
for (format, suffix) in [("obj", "obj"), ("glb", "glb"), ("usda", "usda")] {
|
||||
let path = dir.join(format!("cube-{format}.{suffix}"));
|
||||
let reply = crate::execute(&mut s, "file.exportMesh", &json!({"path": path, "recomputeNormals": true})).unwrap();
|
||||
let bytes = std::fs::read(reply["path"].as_str().unwrap()).unwrap();
|
||||
let back = texturecraft_formats::import_mesh_bytes(&format!("cube.{suffix}"), &bytes).unwrap().mesh;
|
||||
|
||||
assert_eq!(back.normals.len(), expected.normals.len(), "{format}: one normal per exported vertex");
|
||||
for (position, actual) in back.positions.iter().zip(&back.normals) {
|
||||
let wanted = expected
|
||||
.positions
|
||||
.iter()
|
||||
.zip(&expected.normals)
|
||||
.find_map(|(expected_position, normal)| ((*expected_position - *position).length() < 1e-4).then_some(*normal))
|
||||
.unwrap_or_else(|| panic!("{format}: exported position {position:?} is missing from the source"));
|
||||
assert!((*actual - wanted).length() < 1e-4, "{format}: actual {actual:?}, wanted {wanted:?}");
|
||||
}
|
||||
}
|
||||
|
||||
assert!(s.source.normals.iter().all(|n| *n == texturecraft_geom::glam::Vec3::Y), "the source project is unchanged");
|
||||
assert!(s.mesh.normals.iter().all(|n| *n == texturecraft_geom::glam::Vec3::Y), "the render project is unchanged");
|
||||
|
||||
let stored_path = dir.join("stored.obj");
|
||||
let stored = crate::execute(&mut s, "file.exportMesh", &json!({"path": stored_path})).unwrap();
|
||||
let stored = std::fs::read(stored["path"].as_str().unwrap()).unwrap();
|
||||
let stored = texturecraft_formats::import_mesh_bytes("stored.obj", &stored).unwrap().mesh;
|
||||
assert!(stored.normals.iter().all(|n| *n == texturecraft_geom::glam::Vec3::Y), "the default keeps stored normals for compatibility");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recomputed_normals_weld_uv_seams_in_exported_mesh() {
|
||||
use texturecraft_geom::glam::Vec3;
|
||||
|
||||
// The UV seam duplicates edge 0–2 at vertices 3 and 4
|
||||
let positions = vec![Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::ZERO, Vec3::Y, Vec3::new(-1.0, 0.0, 1.0)];
|
||||
let mesh = Mesh::from_parts(
|
||||
positions,
|
||||
Some(vec![Vec3::Y; 6]),
|
||||
vec![Vec2::new(0.0, 0.0), Vec2::new(0.5, 0.5), Vec2::new(0.0, 1.0), Vec2::new(1.0, 0.0), Vec2::new(1.0, 1.0), Vec2::new(0.5, 1.0)],
|
||||
vec![0, 1, 2, 3, 4, 5],
|
||||
"Default",
|
||||
)
|
||||
.unwrap();
|
||||
let mut s = Session::new_project("seam", mesh, "builtin:seam", None, 128).unwrap();
|
||||
|
||||
let bytes = s.mesh_glb_bytes_with_normals(true).unwrap();
|
||||
let back = texturecraft_formats::import_mesh_bytes("seam.glb", &bytes).unwrap().mesh;
|
||||
|
||||
for point in [Vec3::ZERO, Vec3::Y] {
|
||||
let normals: Vec<_> = back.positions.iter().zip(&back.normals).filter_map(|(position, normal)| (*position == point).then_some(*normal)).collect();
|
||||
assert!(normals.len() >= 2, "{point:?}: the UV seam must still have two exported vertices");
|
||||
assert!(normals.windows(2).all(|pair| (pair[0] - pair[1]).length() < 1e-5), "{point:?}: UV split normals disagree: {normals:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejected_glb_export_preserves_existing_files_and_publishes_nothing() {
|
||||
let mut s = Session::new_project("t", primitives::cube(1.0), "builtin:cube", None, 128).unwrap();
|
||||
@@ -1540,11 +1669,18 @@ f 1/1 2/2 3/3
|
||||
let a = dir.join("a.obj");
|
||||
std::fs::write(&a, "v 0 0 0\nv 1 0 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n").unwrap();
|
||||
|
||||
// Same triangle count, other vertices
|
||||
// Keep the triangle count fixed while changing the geometry
|
||||
let b = dir.join("b.obj");
|
||||
std::fs::write(&b, "v 0 0 0\nv 2 0 0\nv 0 2 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n").unwrap();
|
||||
let mut s = Session::from_mesh_bytes("a.obj", &std::fs::read(&a).unwrap(), 128, "a").unwrap();
|
||||
let cage = crate::bake::BakeMesh { name: "cage".into(), folder: None, bytes: Default::default(), mesh: s.mesh.clone(), base_color: Vec::new() };
|
||||
let cage = crate::bake::BakeMesh {
|
||||
name: "cage".into(),
|
||||
folder: None,
|
||||
bytes: Default::default(),
|
||||
mesh: s.mesh.clone(),
|
||||
base_color: Vec::new(),
|
||||
fingerprint: 0,
|
||||
};
|
||||
s.doc.bake_meshes.cage = Some(cage);
|
||||
let _ = s.doc.bake_meshes.low_base_color.set(Err("old".into()));
|
||||
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
use crate::session::Session;
|
||||
|
||||
/// An archive that was written successfully. Only the same project can adopt its path.
|
||||
pub struct SaveOutput {
|
||||
pub path: String,
|
||||
pub(super) project_id: u64,
|
||||
pub(super) saved_revision: Option<u64>,
|
||||
pub(super) adopt: bool,
|
||||
}
|
||||
|
||||
impl SaveOutput {
|
||||
/// Apply the saved path without clearing edits made since the snapshot.
|
||||
pub fn apply(&self, session: &mut Session) {
|
||||
if session.project_id != self.project_id {
|
||||
return;
|
||||
}
|
||||
|
||||
if self.adopt {
|
||||
session.path = Some(self.path.clone());
|
||||
|
||||
// A stroke started after capture changes the revision only when committed
|
||||
if self.saved_revision == Some(session.save_revision) {
|
||||
session.modified = false;
|
||||
}
|
||||
}
|
||||
|
||||
session.log.info("Project", format!("Saved {}", self.path));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
pub(super) struct SaveTarget {
|
||||
pub(super) project_id: u64,
|
||||
pub(super) saved_revision: Option<u64>,
|
||||
pub(super) adopt: bool,
|
||||
pub(super) path: String,
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
|
||||
use texturecraft_core::PROJECT_EXT;
|
||||
use texturecraft_formats::{ProjectFile, project_file::SaveProgress};
|
||||
use texturecraft_geom::Mesh;
|
||||
|
||||
use super::{BakePaintMaps, SaveOutput, ext_of, fe, prepare_archive, save_target::SaveTarget};
|
||||
use crate::Result;
|
||||
use crate::session::Session;
|
||||
|
||||
/// A manual save of the document at the moment it was requested. Large payloads are shared
|
||||
/// until the worker assembles the archive.
|
||||
pub struct SaveTask {
|
||||
target: SaveTarget,
|
||||
archive: ProjectFile<Arc<Vec<u8>>, Arc<Vec<u8>>>,
|
||||
bake_paint: BakePaintMaps,
|
||||
uv_source: Option<Arc<Mesh>>,
|
||||
}
|
||||
|
||||
impl Session {
|
||||
pub fn save_task(&self, path: &str, adopt: bool) -> SaveTask {
|
||||
let path = if ext_of(path) == PROJECT_EXT { path.to_string() } else { format!("{path}.{PROJECT_EXT}") };
|
||||
let saved_revision = (!self.stroke_active()).then_some(self.save_revision);
|
||||
|
||||
SaveTask {
|
||||
target: SaveTarget { project_id: self.project_id, saved_revision, adopt, path },
|
||||
archive: self.capture_archive(self.doc.resources.clone(), Arc::clone),
|
||||
bake_paint: self.doc.bake_paint.clone(),
|
||||
uv_source: self.saved_uv_source().cloned(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl SaveTask {
|
||||
/// Complete the atomic write on the worker. Waiting for a previous save to release the
|
||||
/// RAM allowance also happens here.
|
||||
pub fn run(mut self, progress: Option<&SaveProgress>) -> Result<SaveOutput> {
|
||||
let mut reservation = texturecraft_formats::RamReservation::for_save().map_err(fe)?;
|
||||
prepare_archive(&mut self.archive, self.uv_source.as_deref(), &self.bake_paint);
|
||||
drop(self.uv_source);
|
||||
drop(self.bake_paint);
|
||||
|
||||
let path = Path::new(&self.target.path);
|
||||
match progress {
|
||||
Some(progress) => reservation.save_with_progress(path, &self.archive, progress),
|
||||
None => reservation.save(path, &self.archive),
|
||||
}
|
||||
.map_err(fe)?;
|
||||
|
||||
Ok(SaveOutput { path: self.target.path, project_id: self.target.project_id, saved_revision: self.target.saved_revision, adopt: self.target.adopt })
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
//! without a screenshot.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_core::{Effect, EffectKind, Fill, Filter, Generator, Layer, LayerKind, NormalFormat, Projection, Sampling, Source};
|
||||
use texturecraft_core::{Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, Layer, LayerKind, NormalFormat, Projection, Sampling, Source};
|
||||
|
||||
use crate::Session;
|
||||
use crate::session::StackTarget;
|
||||
@@ -162,6 +162,9 @@ fn generator_json(generator: &Generator) -> Value {
|
||||
if let Some(light) = &generator.light {
|
||||
out["light"] = json!(light);
|
||||
}
|
||||
if generator.on_earlier_model() && matches!(generator.kind, GeneratorKind::Position | GeneratorKind::Direction) {
|
||||
out["direction"] = json!(generator.direction);
|
||||
}
|
||||
if let Some(texture) = &generator.texture {
|
||||
out["texture"] = json!(texture);
|
||||
}
|
||||
@@ -261,6 +264,10 @@ pub fn texture_set(session: &Session, index: usize) -> Value {
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
let out_of_date: std::collections::BTreeMap<_, Vec<_>> =
|
||||
session.out_of_date_maps(index).into_iter().map(|(map, changes)| (map.id(), changes.iter().map(|change| change.id()).collect())).collect();
|
||||
|
||||
json!({
|
||||
"index": index,
|
||||
"name": texture_set.name,
|
||||
@@ -273,6 +280,8 @@ pub fn texture_set(session: &Session, index: usize) -> Value {
|
||||
"layers": session.doc.project.walk(index).len(),
|
||||
"parts": crate::set_cmds::parts(session, index),
|
||||
"baked": crate::project_cmds::baked_json(session.doc.baked.get(&index)),
|
||||
"outOfDate": out_of_date,
|
||||
"autoRebake": texture_set.auto_rebake.map(texturecraft_core::BakedMap::id),
|
||||
"visible": texture_set.visible,
|
||||
"active": index == session.ts(),
|
||||
})
|
||||
|
||||
@@ -324,8 +324,8 @@ fn select(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
Some(Value::String(t)) if t == "content" => StackTarget::Content,
|
||||
Some(v) => match v.as_u64() {
|
||||
Some(e) if s.doc.project.effect(LayerId(e)).is_some_and(|(owner, _)| owner == id) => StackTarget::Effect(LayerId(e)),
|
||||
_ => return Err(bad("layer.select", "target must be content, mask or an effect id of this layer")),
|
||||
Some(effect) if selectable_effect(&s.doc.project, id, LayerId(effect)) => StackTarget::Effect(LayerId(effect)),
|
||||
_ => return Err(bad("layer.select", "target must be content, mask or an effect id of this layer or of the mask it draws with")),
|
||||
},
|
||||
None => StackTarget::Content,
|
||||
};
|
||||
@@ -334,6 +334,15 @@ fn select(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "layer": id.0, "textureSet": ts, "layers": [id.0] }))
|
||||
}
|
||||
|
||||
/// Whether the effect belongs to the layer or to the mask it draws with.
|
||||
fn selectable_effect(project: &Project, layer: LayerId, effect_id: LayerId) -> bool {
|
||||
let Some((owner, _)) = project.effect(effect_id) else { return false };
|
||||
|
||||
owner == layer
|
||||
|| (owner == project.mask_owner(layer)
|
||||
&& project.layers.get(&owner).and_then(|layer| layer.mask.as_ref()).is_some_and(|mask| mask.effects.iter().any(|effect| effect.id == effect_id)))
|
||||
}
|
||||
|
||||
fn rename(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = layer_param(s, "layer.rename", p)?;
|
||||
let name = strp(p, "name").map(str::trim).filter(|n| !n.is_empty()).ok_or_else(|| bad("layer.rename", "`name` is required"))?.to_string();
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
pub mod add_mask_cmds;
|
||||
mod anchored_micro_edit;
|
||||
pub mod bake;
|
||||
pub mod bake_log_cmds;
|
||||
pub mod bake_preview;
|
||||
pub mod brush_preset_cmds;
|
||||
pub mod camera_cmds;
|
||||
@@ -51,6 +52,7 @@ pub mod material_lib;
|
||||
mod material_preview_pixel;
|
||||
pub mod materials;
|
||||
pub mod materialx_cmds;
|
||||
mod mesh_map_sampler;
|
||||
pub mod meshmap_cmds;
|
||||
mod meshmap_file_name;
|
||||
pub mod meshmap_import_cmds;
|
||||
@@ -73,7 +75,16 @@ pub mod preview;
|
||||
mod procedural_params;
|
||||
pub mod project_cmds;
|
||||
pub mod quick_mask;
|
||||
// Reloading resource files reads paths on native targets only
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
mod reloaded_file;
|
||||
// Remembered file comparisons exist on native targets only
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
mod resource_check;
|
||||
pub mod resource_cmds;
|
||||
pub mod resource_state;
|
||||
pub mod resource_status;
|
||||
pub mod resource_update_cmds;
|
||||
pub mod session;
|
||||
mod session_log;
|
||||
pub mod set_cmds;
|
||||
@@ -102,6 +113,8 @@ pub use fill_mode::FillMode;
|
||||
pub use log::{LogEntry, LogLevel, SessionLog};
|
||||
pub use path_tool::PathState;
|
||||
pub use project_cmds::sample_session;
|
||||
pub use resource_state::ResourceState;
|
||||
pub use resource_status::ResourceStatus;
|
||||
pub use session::{
|
||||
CloneFrom, CloneSource, Document, HISTORY_TEMPLATES, NORMAL_HEIGHT_MESH_LABEL, Session, SetCache, StackTarget, StencilLook, StencilState, Tool, ToolState,
|
||||
ViewMode, history_label, stroke_template,
|
||||
@@ -127,6 +140,8 @@ pub enum EngineError {
|
||||
BadParams { cmd: String, msg: String },
|
||||
#[error(transparent)]
|
||||
Core(#[from] texturecraft_core::CoreError),
|
||||
#[error("bake failed: bake cancelled")]
|
||||
BakeCancelled,
|
||||
#[error("{0}")]
|
||||
Other(String),
|
||||
}
|
||||
|
||||
@@ -344,6 +344,68 @@ pub fn open_in_materialcraft(package: &std::path::Path) -> Result<()> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Prefix of the folders [`stage_handoff_package`] makes in the temp folder.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const HANDOFF_PREFIX: &str = "texturecraft-open-";
|
||||
|
||||
/// Folders from earlier hand-offs older than this are removed (MaterialCraft may still have a young one open).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const HANDOFF_MAX_AGE: std::time::Duration = std::time::Duration::from_secs(7 * 24 * 3600);
|
||||
|
||||
/// Write `package` as `file_name` inside a new folder only this call can have made under the temp folder, and return the
|
||||
/// file's path (for [`open_in_materialcraft`]). A fixed `<temp>/<name>` is guessable: on a shared `/tmp` another user
|
||||
/// could plant a file or link there first and the write would go through it. The folder name is random, is created
|
||||
/// exclusively (mode `0700` on Unix) and the file is created with `create_new` (mode `0600`), so nothing planted is ever written through.
|
||||
/// The folder stays after the call because MaterialCraft needs the file while it is open; folders over a week old go.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn stage_handoff_package(file_name: &str, package: &[u8]) -> Result<std::path::PathBuf> {
|
||||
stage_handoff_package_in(&std::env::temp_dir(), file_name, package)
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn stage_handoff_package_in(base: &std::path::Path, file_name: &str, package: &[u8]) -> Result<std::path::PathBuf> {
|
||||
use std::io::Write;
|
||||
let io = |e: std::io::Error| EngineError::Other(format!("cannot stage the package for MaterialCraft: {e}"));
|
||||
if file_name.is_empty() || std::path::Path::new(file_name).file_name() != Some(std::ffi::OsStr::new(file_name)) {
|
||||
return Err(EngineError::Other(format!("`{file_name}` is not a plain file name")));
|
||||
}
|
||||
sweep_old_handoffs(base, HANDOFF_MAX_AGE);
|
||||
// Dropped (and removed) on any early return, so a failed write leaves no empty folder behind.
|
||||
let mut builder = tempfile::Builder::new();
|
||||
builder.prefix(HANDOFF_PREFIX);
|
||||
// tempfile makes folders with the default mode (0755 under the usual umask), so ask for 0700 and 0600 explicitly.
|
||||
#[cfg(unix)]
|
||||
builder.permissions(std::os::unix::fs::PermissionsExt::from_mode(0o700));
|
||||
let dir = builder.tempdir_in(base).map_err(io)?;
|
||||
let path = dir.path().join(file_name);
|
||||
let mut options = std::fs::OpenOptions::new();
|
||||
options.write(true).create_new(true);
|
||||
#[cfg(unix)]
|
||||
std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
|
||||
let mut file = options.open(&path).map_err(io)?;
|
||||
file.write_all(package).map_err(io)?;
|
||||
file.sync_all().map_err(io)?;
|
||||
let _ = dir.keep();
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
/// Remove hand-off folders in `base` last changed more than `max_age` ago. Only real folders with our prefix are
|
||||
/// touched (never a link), and every failure is ignored: a leftover folder costs disk space, not work.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn sweep_old_handoffs(base: &std::path::Path, max_age: std::time::Duration) {
|
||||
let Ok(entries) = std::fs::read_dir(base) else { return };
|
||||
for entry in entries.flatten() {
|
||||
if !entry.file_name().to_string_lossy().starts_with(HANDOFF_PREFIX) {
|
||||
continue;
|
||||
}
|
||||
let Ok(meta) = std::fs::symlink_metadata(entry.path()) else { continue };
|
||||
let old = meta.modified().ok().and_then(|t| t.elapsed().ok()).is_some_and(|age| age > max_age);
|
||||
if meta.is_dir() && old {
|
||||
let _ = std::fs::remove_dir_all(entry.path());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Source file extensions are chosen from the linked resource name, never an untrusted path.
|
||||
pub fn source_extension(name: &str) -> &'static str {
|
||||
if name.to_ascii_lowercase().ends_with(".mcmat") {
|
||||
@@ -623,6 +685,7 @@ impl Session {
|
||||
|
||||
for name in old_names.iter().filter(|name| !used_names.contains(name)) {
|
||||
session.doc.resources.remove(name);
|
||||
session.doc.project.resource_sources.remove(name);
|
||||
}
|
||||
|
||||
Ok(names)
|
||||
@@ -711,4 +774,82 @@ mod tests {
|
||||
assert_eq!(typed(&p, &json!("#+f+f+f")), None);
|
||||
assert!(typed(&p, &json!("#ff8000")).is_some());
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn scratch(name: &str) -> std::path::PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("tc_handoff_{name}_{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
/// A file another user planted at the old, guessable `<temp>/<name>` is never written through.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn handoff_package_is_not_written_through_a_planted_link() {
|
||||
let base = scratch("planted");
|
||||
let victim = base.join("victim.txt");
|
||||
std::fs::write(&victim, b"precious").unwrap();
|
||||
// The old code wrote `<temp>/<name>` with `fs::write`; a hard link there reaches the victim on every platform.
|
||||
std::fs::hard_link(&victim, base.join("wood.mcraft")).unwrap();
|
||||
|
||||
let path = super::stage_handoff_package_in(&base, "wood.mcraft", b"package").unwrap();
|
||||
|
||||
assert_eq!(std::fs::read(&victim).unwrap(), b"precious");
|
||||
assert_eq!(std::fs::read(&path).unwrap(), b"package");
|
||||
assert_ne!(path.parent().unwrap(), base, "the file is inside a folder of its own");
|
||||
std::fs::remove_dir_all(&base).unwrap();
|
||||
}
|
||||
|
||||
/// Every hand-off gets its own empty-until-written folder, even when the name repeats.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn handoff_packages_get_distinct_folders() {
|
||||
let base = scratch("distinct");
|
||||
let a = super::stage_handoff_package_in(&base, "m.mcraft", b"a").unwrap();
|
||||
let b = super::stage_handoff_package_in(&base, "m.mcraft", b"b").unwrap();
|
||||
assert_ne!(a.parent(), b.parent());
|
||||
assert_eq!((std::fs::read(&a).unwrap(), std::fs::read(&b).unwrap()), (b"a".to_vec(), b"b".to_vec()));
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
assert_eq!(std::fs::metadata(a.parent().unwrap()).unwrap().permissions().mode() & 0o777, 0o700);
|
||||
assert_eq!(std::fs::metadata(&a).unwrap().permissions().mode() & 0o777, 0o600);
|
||||
}
|
||||
std::fs::remove_dir_all(&base).unwrap();
|
||||
}
|
||||
|
||||
/// A name with a path in it cannot leave the new folder.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn handoff_package_rejects_names_that_are_paths() {
|
||||
let base = scratch("names");
|
||||
for bad in ["", "..", "a/b.mcraft", "../x.mcraft"] {
|
||||
assert!(super::stage_handoff_package_in(&base, bad, b"x").is_err(), "{bad}");
|
||||
}
|
||||
assert_eq!(std::fs::read_dir(&base).unwrap().count(), 0, "a rejected name leaves nothing behind");
|
||||
std::fs::remove_dir_all(&base).unwrap();
|
||||
}
|
||||
|
||||
/// Old hand-off folders are swept; young ones, other folders and files stay.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn handoff_sweep_removes_only_old_handoff_folders() {
|
||||
let base = scratch("sweep");
|
||||
let old = base.join("texturecraft-open-old");
|
||||
let other = base.join("somebody-elses-folder");
|
||||
let file = base.join("texturecraft-open-file");
|
||||
for dir in [&old, &other] {
|
||||
std::fs::create_dir(dir).unwrap();
|
||||
}
|
||||
std::fs::write(&file, b"x").unwrap();
|
||||
// Zero age limit: everything with the prefix that is a folder counts as old.
|
||||
super::sweep_old_handoffs(&base, std::time::Duration::ZERO);
|
||||
assert!(!old.exists() && other.exists() && file.exists());
|
||||
let young = base.join("texturecraft-open-young");
|
||||
std::fs::create_dir(&young).unwrap();
|
||||
super::sweep_old_handoffs(&base, std::time::Duration::from_secs(3600));
|
||||
assert!(young.exists());
|
||||
std::fs::remove_dir_all(&base).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -70,6 +70,7 @@ pub(crate) fn one_set_document(src_set: &TextureSet, name: &str) -> Document {
|
||||
set.tile_resolutions = src_set.tile_resolutions.clone();
|
||||
set.channels = src_set.channels.clone();
|
||||
project.texture_sets.push(set);
|
||||
|
||||
Document {
|
||||
bake_meshes: Default::default(),
|
||||
bake_paint: BTreeMap::new(),
|
||||
@@ -77,6 +78,7 @@ pub(crate) fn one_set_document(src_set: &TextureSet, name: &str) -> Document {
|
||||
pixels: PixelStore::default(),
|
||||
baked: BTreeMap::new(),
|
||||
resources: BTreeMap::new(),
|
||||
painted_regions: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -99,7 +101,7 @@ impl Session {
|
||||
images_used(&mini.project, root, &mut used, 0);
|
||||
let resources = used.into_iter().filter_map(|name| self.doc.resources.get(&name).map(|bytes| (name, Arc::clone(bytes)))).collect();
|
||||
|
||||
let snapshot = texturecraft_formats::ProjectFile {
|
||||
let snapshot = texturecraft_formats::ProjectFile::<Arc<Vec<u8>>> {
|
||||
project: mini.project,
|
||||
pixels: mini.pixels,
|
||||
baked: BTreeMap::new(),
|
||||
@@ -145,6 +147,7 @@ impl Session {
|
||||
project: project_file.project,
|
||||
pixels: project_file.pixels,
|
||||
baked: BTreeMap::new(),
|
||||
painted_regions: Default::default(),
|
||||
resources,
|
||||
};
|
||||
|
||||
|
||||
@@ -34,17 +34,25 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
/// Loads an image file named in the document (relative to it): its bytes, or why not.
|
||||
pub type Loader<'a> = &'a dyn Fn(&str) -> std::result::Result<Vec<u8>, String>;
|
||||
|
||||
type LocatedImage = (Vec<u8>, Option<texturecraft_core::ResourceSource>);
|
||||
type LocatedLoader<'a> = &'a dyn Fn(&str) -> std::result::Result<LocatedImage, String>;
|
||||
|
||||
impl Session {
|
||||
/// Add `material` as a fill layer on the active texture set, loading its images with `load`.
|
||||
/// Returns the reply of `file.importMaterialX`.
|
||||
pub fn import_material(&mut self, material: Material, name: Option<&str>, load: Loader) -> Result<Value> {
|
||||
self.import_material_with_sources(material, name, &|file| load(file).map(|bytes| (bytes, None)))
|
||||
}
|
||||
|
||||
fn import_material_with_sources(&mut self, material: Material, name: Option<&str>, load: LocatedLoader) -> Result<Value> {
|
||||
let mut warnings = material.warnings.clone();
|
||||
let ts = self.ts();
|
||||
let available = self.doc.project.texture_set(ts).map(|t| t.channel_list()).unwrap_or_default();
|
||||
let mut fill = Fill { projection: Projection::Uv { scale: material.uv_tiling, rotation: 0.0, offset: [0.0, 0.0] }, ..Fill::default() };
|
||||
// Resources to add (name and encoded bytes), and their decoded images for the session.
|
||||
|
||||
let mut added: Vec<(String, Arc<Vec<u8>>)> = Vec::new();
|
||||
let mut decoded = Vec::new();
|
||||
let mut sources = Vec::new();
|
||||
let mut names: BTreeMap<String, String> = BTreeMap::new();
|
||||
let mut channels: Vec<Channel> = Vec::new();
|
||||
for (channel, value) in &material.channels {
|
||||
@@ -52,15 +60,17 @@ impl Session {
|
||||
warnings.push(format!("{} was skipped: this texture set has no such channel", channel.id()));
|
||||
continue;
|
||||
}
|
||||
|
||||
let source = match value {
|
||||
Mtlx::Constant(c) => Source::Uniform(*c),
|
||||
Mtlx::Image(file) => {
|
||||
let resource = match names.get(file) {
|
||||
Some(n) => n.clone(),
|
||||
None => {
|
||||
let loaded =
|
||||
load(file).and_then(|bytes| texturecraft_formats::decode_image(&bytes).map(|image| (bytes, image)).map_err(|e| e.to_string()));
|
||||
let (bytes, image) = match loaded {
|
||||
let loaded = load(file).and_then(|(bytes, source)| {
|
||||
texturecraft_formats::decode_image(&bytes).map(|image| (bytes, image, source)).map_err(|e| e.to_string())
|
||||
});
|
||||
let (bytes, image, source) = match loaded {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
warnings.push(format!("{} was skipped: {file}: {e}", channel.id()));
|
||||
@@ -69,11 +79,11 @@ impl Session {
|
||||
};
|
||||
let leaf = file.rsplit(['/', '\\']).next().unwrap_or(file);
|
||||
let base = texturecraft_formats::sanitize_resource_name(leaf);
|
||||
let (mut unique, mut n) = (base.clone(), 2);
|
||||
while self.doc.resources.contains_key(&unique) || added.iter().any(|(a, _)| *a == unique) {
|
||||
unique = format!("{n}_{base}");
|
||||
n += 1;
|
||||
}
|
||||
let unique = crate::resource_cmds::unique_resource_name(base, |name| {
|
||||
self.doc.resources.contains_key(name) || added.iter().any(|(added_name, _)| added_name == name)
|
||||
});
|
||||
|
||||
sources.extend(source.map(|source| (unique.clone(), source)));
|
||||
added.push((unique.clone(), Arc::new(bytes)));
|
||||
decoded.push((unique.clone(), crate::resource_cmds::decoded(image)));
|
||||
names.insert(file.clone(), unique.clone());
|
||||
@@ -90,12 +100,14 @@ impl Session {
|
||||
let why = if warnings.is_empty() { String::new() } else { format!(" ({})", warnings.join("; ")) };
|
||||
return Err(EngineError::Other(format!("file.importMaterialX: nothing to import from {:?}{why}", material.name)));
|
||||
}
|
||||
|
||||
let layer_name = name.map(str::to_string).unwrap_or_else(|| self.doc.project.next_layer_name(ts, &material.name));
|
||||
let resource_names: Vec<String> = added.iter().map(|(n, _)| n.clone()).collect();
|
||||
let id = self.edit("Import MaterialX material", |s| {
|
||||
for (n, bytes) in &added {
|
||||
s.doc.resources.insert(n.clone(), bytes.clone());
|
||||
}
|
||||
s.doc.project.resource_sources.extend(sources);
|
||||
let id = s.doc.project.alloc_id();
|
||||
crate::layer_cmds::insert_selected(s, Layer::new(id, layer_name, LayerKind::Fill(fill), &channels))
|
||||
})?;
|
||||
@@ -119,34 +131,42 @@ fn import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if !meta.is_file() || meta.len() > texturecraft_formats::materialx_read::MAX_BYTES as u64 {
|
||||
return Err(bad(cmd, format!("{path} is not a MaterialX file of a readable size")));
|
||||
}
|
||||
|
||||
let bytes = std::fs::read(path).map_err(|e| bad(cmd, format!("cannot read {path}: {e}")))?;
|
||||
let material = texturecraft_formats::materialx_read::read_materialx(&bytes, strp(p, "material")).map_err(|e| bad(cmd, format!("{path}: {e}")))?;
|
||||
let folder = Path::new(path).parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or(Path::new("."));
|
||||
let dir = folder.canonicalize().map_err(|e| bad(cmd, format!("cannot read the folder of {path}: {e}")))?;
|
||||
let load = |file: &str| -> std::result::Result<Vec<u8>, String> {
|
||||
// `<UDIM>` stands for a tile number; the first tile is read.
|
||||
let load = |file: &str| -> std::result::Result<LocatedImage, String> {
|
||||
// Import the first tile of a UDIM image
|
||||
let file = file.replace("<UDIM>", "1001");
|
||||
let rel = Path::new(&file);
|
||||
let outside = "the file is outside the material's folder";
|
||||
if rel.is_absolute() || rel.components().any(|c| matches!(c, Component::ParentDir | Component::Prefix(_) | Component::RootDir)) {
|
||||
return Err(outside.into());
|
||||
}
|
||||
|
||||
let full = dir.join(rel).canonicalize().map_err(|e| e.to_string())?;
|
||||
if !full.starts_with(&dir) {
|
||||
return Err(outside.into());
|
||||
}
|
||||
|
||||
let meta = std::fs::metadata(&full).map_err(|e| e.to_string())?;
|
||||
// A pipe or device in the folder would block the read (a pipe reports no length).
|
||||
|
||||
// Avoid blocking on pipes and devices
|
||||
if !meta.is_file() {
|
||||
return Err("it is not a regular file".into());
|
||||
}
|
||||
|
||||
let len = meta.len();
|
||||
if len > crate::resource_cmds::MAX_BYTES as u64 {
|
||||
return Err(format!("the file is over {} MB", crate::resource_cmds::MAX_BYTES >> 20));
|
||||
}
|
||||
std::fs::read(&full).map_err(|e| e.to_string())
|
||||
|
||||
let source = full.to_str().map(crate::resource_update_cmds::file_source);
|
||||
let bytes = std::fs::read(&full).map_err(|e| e.to_string())?;
|
||||
Ok((bytes, source))
|
||||
};
|
||||
s.import_material(material, strp(p, "name"), &load)
|
||||
s.import_material_with_sources(material, strp(p, "name"), &load)
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
//! Sample image resources into a mesh-map atlas or compare them with an existing atlas.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use rayon::prelude::*;
|
||||
use texturecraft_compose::ImageRes;
|
||||
use texturecraft_core::{BakedMap, NormalFormat, TileGrid, udim_at};
|
||||
|
||||
use crate::commands::bad;
|
||||
use crate::{Result, Session};
|
||||
|
||||
pub(crate) struct MeshMapSampler<'a> {
|
||||
width: u32,
|
||||
height: u32,
|
||||
components: usize,
|
||||
flip_green: bool,
|
||||
grid: Option<TileGrid>,
|
||||
first: &'a ImageRes,
|
||||
images: &'a BTreeMap<u32, Arc<ImageRes>>,
|
||||
}
|
||||
|
||||
impl<'a> MeshMapSampler<'a> {
|
||||
pub(crate) fn new(session: &Session, cmd: &str, texture_set: usize, map: BakedMap, images: &'a BTreeMap<u32, Arc<ImageRes>>) -> Result<Self> {
|
||||
let set = session.doc.project.texture_set(texture_set)?;
|
||||
let grid = set.tile_grid();
|
||||
if let Some(tile) = set.uv_tiles.iter().find(|tile| grid.is_some() && !images.contains_key(tile)) {
|
||||
return Err(bad(cmd, format!("no image for UV tile {tile}")));
|
||||
}
|
||||
|
||||
let (width, height) = crate::meshmap_cmds::image_map_size(session, cmd, texture_set)?;
|
||||
let first = images.values().next().ok_or_else(|| bad(cmd, "no image to use"))?;
|
||||
|
||||
// Both tangent-space normal maps follow the project's green-channel convention
|
||||
let flip_green = matches!(map, BakedMap::Normal | BakedMap::BentNormal) && session.doc.project.normal_format == NormalFormat::DirectX;
|
||||
Ok(Self { width, height, components: map.components(), flip_green, grid, first, images })
|
||||
}
|
||||
|
||||
fn row(&self, y: usize) -> impl Iterator<Item = [f32; 4]> + '_ {
|
||||
let v = (y as f32 + 0.5) / self.height as f32;
|
||||
(0..self.width).map(move |x| {
|
||||
let u = (x as f32 + 0.5) / self.width as f32;
|
||||
let mut pixel = match self.grid {
|
||||
None => self.first.sample(u, v),
|
||||
Some(grid) => {
|
||||
let uv = grid.from_atlas([u, v]);
|
||||
udim_at(uv).and_then(|tile| self.images.get(&tile)).map_or([0.0; 4], |image| image.sample(uv[0] - uv[0].floor(), uv[1] - uv[1].floor()))
|
||||
}
|
||||
};
|
||||
if self.flip_green {
|
||||
pixel[1] = 1.0 - pixel[1];
|
||||
}
|
||||
|
||||
pixel
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn matches(&self, current: &[f32]) -> bool {
|
||||
let row_len = self.width as usize * self.components;
|
||||
current.len() == row_len * self.height as usize
|
||||
&& current
|
||||
.par_chunks_exact(row_len)
|
||||
.enumerate()
|
||||
.all(|(y, row)| row.chunks_exact(self.components).zip(self.row(y)).all(|(stored, sampled)| stored == &sampled[..self.components]))
|
||||
}
|
||||
|
||||
pub(crate) fn render(&self) -> (u32, Vec<f32>) {
|
||||
let row_len = self.width as usize * self.components;
|
||||
let mut pixels = vec![0.0; row_len * self.height as usize];
|
||||
pixels.par_chunks_exact_mut(row_len).enumerate().for_each(|(y, row)| {
|
||||
for (output, sampled) in row.chunks_exact_mut(self.components).zip(self.row(y)) {
|
||||
output.copy_from_slice(&sampled[..self.components]);
|
||||
}
|
||||
});
|
||||
|
||||
(self.width, pixels)
|
||||
}
|
||||
}
|
||||
@@ -4,10 +4,9 @@
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use rayon::prelude::*;
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_compose::{ImageRes, ImageStore};
|
||||
use texturecraft_core::{BakedMap, MAX_RESOLUTION, NormalFormat, UDIM_RANGE, udim_at};
|
||||
use texturecraft_core::{BakedMap, MAX_RESOLUTION, Project, UDIM_RANGE};
|
||||
|
||||
use crate::commands::{CommandSpec, always, bad, strp};
|
||||
use crate::set_cmds::ts_param;
|
||||
@@ -45,39 +44,41 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
None => BTreeMap::from([(FIRST_TILE, image)]),
|
||||
};
|
||||
|
||||
let resolution = s.edit("Use image as mesh map", |s| use_images(s, CMD, ts, map, &images))?;
|
||||
let resolution = s.edit("Use image as mesh map", |s| {
|
||||
let resolution = use_images(s, CMD, ts, map, &images)?;
|
||||
detach_imported_sources(&mut s.doc.project, ts, |previous| previous == map);
|
||||
Ok(resolution)
|
||||
})?;
|
||||
|
||||
Ok(json!({ "map": map.id(), "resolution": resolution }))
|
||||
}
|
||||
|
||||
/// A bake, a manual assignment or a clear ends the import link but keeps the image resource
|
||||
pub(crate) fn detach_imported_sources(project: &mut Project, texture_set: usize, replaced: impl Fn(BakedMap) -> bool) {
|
||||
for source in project.resource_sources.values_mut() {
|
||||
if source.mesh_map.is_some_and(|slot| slot.texture_set == texture_set && replaced(slot.map)) {
|
||||
source.mesh_map = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The tile number a set without UV tiles keys its one image by
|
||||
pub(crate) const FIRST_TILE: u32 = *UDIM_RANGE.start();
|
||||
|
||||
/// Use `images` (by UV tile; one at [`FIRST_TILE`] without UV tiles) as mesh map `map` of set `ts` in the caller's edit; returns its width
|
||||
pub(crate) fn use_images(s: &mut Session, cmd: &str, ts: usize, map: BakedMap, images: &BTreeMap<u32, Arc<ImageRes>>) -> Result<u32> {
|
||||
let texture_set = s.doc.project.texture_set(ts)?;
|
||||
let grid = texture_set.tile_grid();
|
||||
if let Some(tile) = texture_set.uv_tiles.iter().find(|tile| grid.is_some() && !images.contains_key(tile)) {
|
||||
return Err(bad(cmd, format!("no image for UV tile {tile}")));
|
||||
}
|
||||
/// Use `images` (by UV tile; one at [`FIRST_TILE`] without UV tiles) as mesh map `map` of set `texture_set` in the caller's edit; returns its width
|
||||
pub(crate) fn use_images(session: &mut Session, command: &str, texture_set: usize, map: BakedMap, images: &BTreeMap<u32, Arc<ImageRes>>) -> Result<u32> {
|
||||
let (width, data) = crate::mesh_map_sampler::MeshMapSampler::new(session, command, texture_set, map, images)?.render();
|
||||
|
||||
let (width, height) = image_map_size(s, cmd, ts)?;
|
||||
|
||||
// Bent normals are tangent-space maps like the normal map, so both follow the project's normal format
|
||||
let flip_green = matches!(map, BakedMap::Normal | BakedMap::BentNormal) && s.doc.project.normal_format == NormalFormat::DirectX;
|
||||
let data = match (grid, images.values().next()) {
|
||||
(_, None) => return Err(bad(cmd, "no image to use")),
|
||||
(None, Some(image)) => resample(map.components(), (width, height), flip_green, |u, v| image.sample(u, v)),
|
||||
// An atlas texel reads the image of the tile its mesh UV falls in
|
||||
(Some(grid), Some(_)) => resample(map.components(), (width, height), flip_green, |u, v| {
|
||||
let uv = grid.from_atlas([u, v]);
|
||||
udim_at(uv).and_then(|tile| images.get(&tile)).map_or([0.0; 4], |image| image.sample(uv[0] - uv[0].floor(), uv[1] - uv[1].floor()))
|
||||
}),
|
||||
};
|
||||
|
||||
let entry = s.doc.baked.entry(ts).or_default();
|
||||
let entry = session.doc.baked.entry(texture_set).or_default();
|
||||
entry.resolution = width;
|
||||
entry.maps.insert(map, Arc::new(data));
|
||||
s.doc.project.texture_set_mut(ts)?.baked.insert(map);
|
||||
|
||||
let set = session.doc.project.texture_set_mut(texture_set)?;
|
||||
set.baked.insert(map);
|
||||
|
||||
// Imported pixels have no bake provenance
|
||||
set.bake_sources.remove(&map);
|
||||
|
||||
Ok(width)
|
||||
}
|
||||
|
||||
@@ -133,39 +134,26 @@ fn udim_in(name: &str) -> Option<usize> {
|
||||
})
|
||||
}
|
||||
|
||||
/// `w` × `h` texels of `comps` values each from `sample` (atlas UV → RGBA), as stored in the
|
||||
/// file (mesh maps hold data, not colors, so nothing is linearized); `flip_green` reads a
|
||||
/// DirectX normal or bent normal map.
|
||||
fn resample(comps: usize, (w, h): (u32, u32), flip_green: bool, sample: impl Fn(f32, f32) -> [f32; 4] + Sync) -> Vec<f32> {
|
||||
let mut out = vec![0.0; w as usize * h as usize * comps];
|
||||
out.par_chunks_mut(w as usize * comps).enumerate().for_each(|(y, row)| {
|
||||
let v = (y as f32 + 0.5) / h as f32;
|
||||
for (x, texel) in row.chunks_exact_mut(comps).enumerate() {
|
||||
let mut c = sample((x as f32 + 0.5) / w as f32, v);
|
||||
if flip_green {
|
||||
c[1] = 1.0 - c[1];
|
||||
}
|
||||
for (o, c) in texel.iter_mut().zip(c) {
|
||||
*o = c;
|
||||
}
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
fn clear(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const CMD: &str = "textureSet.meshMap.clear";
|
||||
let ts = ts_param(s, p, CMD)?;
|
||||
let map = map_param(p, CMD)?;
|
||||
if !s.doc.baked.get(&ts).is_some_and(|b| b.maps.contains_key(&map)) {
|
||||
return Err(bad(CMD, format!("texture set {ts} has no {} map", map.id())));
|
||||
fn clear(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
const COMMAND: &str = "textureSet.meshMap.clear";
|
||||
let texture_set = ts_param(session, params, COMMAND)?;
|
||||
let map = map_param(params, COMMAND)?;
|
||||
if !session.doc.baked.get(&texture_set).is_some_and(|baked| baked.maps.contains_key(&map)) {
|
||||
return Err(bad(COMMAND, format!("texture set {texture_set} has no {} map", map.id())));
|
||||
}
|
||||
s.edit("Clear mesh map", |s| {
|
||||
if let Some(b) = s.doc.baked.get_mut(&ts) {
|
||||
b.maps.remove(&map);
|
||||
|
||||
session.edit("Clear mesh map", |session| {
|
||||
if let Some(baked) = session.doc.baked.get_mut(&texture_set) {
|
||||
baked.maps.remove(&map);
|
||||
}
|
||||
s.doc.project.texture_set_mut(ts)?.baked.remove(&map);
|
||||
|
||||
let set = session.doc.project.texture_set_mut(texture_set)?;
|
||||
set.baked.remove(&map);
|
||||
set.bake_sources.remove(&map);
|
||||
detach_imported_sources(&mut session.doc.project, texture_set, |previous| previous == map);
|
||||
|
||||
Ok(())
|
||||
})?;
|
||||
|
||||
Ok(Value::Null)
|
||||
}
|
||||
@@ -4,12 +4,13 @@ use std::collections::BTreeMap;
|
||||
use std::path::Path;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_core::BakedMap;
|
||||
use texturecraft_core::{BakedMap, MeshMapSlot, ResourceSource};
|
||||
|
||||
use crate::commands::{CommandSpec, always, bad, strp};
|
||||
use crate::meshmap_cmds::{FIRST_TILE, image_map_size, tile_number, use_images};
|
||||
use crate::meshmap_file_name::{baked_map_from_file_name, texture_set_from_file_name};
|
||||
use crate::resource_cmds::read_image_file;
|
||||
use crate::resource_update_cmds::file_source;
|
||||
use crate::{Result, Session, cmd};
|
||||
|
||||
const CMD: &str = "textureSet.meshMap.import";
|
||||
@@ -84,11 +85,20 @@ fn import_with_budget(s: &mut Session, p: &Value, max_bytes: u64) -> Result<Valu
|
||||
|
||||
let mut images = BTreeMap::new();
|
||||
for (tile, path) in tiles {
|
||||
let slot = MeshMapSlot { texture_set: *ts, map: *map, tile: *tile };
|
||||
let source = ResourceSource { mesh_map: Some(slot), ..file_source(path) };
|
||||
let bytes = read_image_file(CMD, path, remaining_bytes)?;
|
||||
reserve_bytes(&mut remaining_bytes, bytes.len() as u64)?;
|
||||
|
||||
let bytes_per_texel = size_of::<[f32; 4]>() as u64;
|
||||
let name = s.add_image_resource(path, bytes, remaining_bytes / bytes_per_texel)?;
|
||||
|
||||
// The slot follows only its latest file
|
||||
for earlier in s.doc.project.resource_sources.values_mut().filter(|earlier| earlier.mesh_map == Some(slot)) {
|
||||
earlier.mesh_map = None;
|
||||
}
|
||||
s.doc.project.resource_sources.insert(name.clone(), source);
|
||||
|
||||
let image = s.images.get(&name).ok_or_else(|| bad(CMD, format!("no decoded image `{name}`")))?;
|
||||
reserve_bytes(&mut remaining_bytes, u64::from(image.width) * u64::from(image.height) * bytes_per_texel)?;
|
||||
images.insert(*tile, image.clone());
|
||||
@@ -98,7 +108,8 @@ fn import_with_budget(s: &mut Session, p: &Value, max_bytes: u64) -> Result<Valu
|
||||
}
|
||||
Ok(assigned)
|
||||
});
|
||||
// A failed edit leaves the document as it was; forget the images it decoded
|
||||
|
||||
// Forget images decoded during an edit that rolled back
|
||||
if result.is_err() {
|
||||
s.sync_images();
|
||||
}
|
||||
|
||||
@@ -591,8 +591,7 @@ impl Session {
|
||||
self.undo.remove(0);
|
||||
}
|
||||
self.redo.clear();
|
||||
self.modified = true;
|
||||
self.revision = self.revision.wrapping_add(1);
|
||||
self.mark_modified();
|
||||
|
||||
// Recompute committed tiles at low priority because the live preview already shows them
|
||||
self.mark_settle(stroke.ts, stroke.target, stroke.canvas.dirty.iter().copied());
|
||||
|
||||
@@ -940,28 +940,28 @@ impl Session {
|
||||
}
|
||||
|
||||
/// [`Session::put_path`] recompositing only the tiles it changed, with no undo step: returns the paint report and the document before
|
||||
fn repaint_path(&mut self, eid: LayerId, index: usize, shape: PathShape) -> Result<(Value, Document)> {
|
||||
fn repaint_path(&mut self, effect_id: LayerId, index: usize, shape: PathShape) -> Result<(Value, Document)> {
|
||||
let before = self.doc.clone();
|
||||
let painted = match self.put_path(eid, index, shape) {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
let painted = match self.put_path(effect_id, index, shape) {
|
||||
Ok(report) => report,
|
||||
Err(error) => {
|
||||
self.doc = before;
|
||||
return Err(e);
|
||||
return Err(error);
|
||||
}
|
||||
};
|
||||
|
||||
// Paths paint into the active set; a sublayer in another set recomposites in full
|
||||
let project = &self.doc.project;
|
||||
let set = project.effect(eid).and_then(|(owner, _)| project.locate(owner)).map(|(ts, _, _)| ts);
|
||||
let set = project.effect(effect_id).and_then(|(owner, _)| project.locate(owner)).map(|(ts, _, _)| ts);
|
||||
if set == Some(self.ts()) {
|
||||
// Content or mask, the sublayer's owner decides which sets redraw
|
||||
let tiles = changed_tiles(&before.pixels, &self.doc.pixels, eid);
|
||||
self.mark_painted(self.ts(), Some(PaintTarget::Layer(eid)), tiles);
|
||||
let tiles = changed_tiles(&before.pixels, &self.doc.pixels, effect_id);
|
||||
self.mark_painted(self.ts(), Some(PaintTarget::Layer(effect_id)), tiles);
|
||||
} else {
|
||||
self.invalidate_changed(&before);
|
||||
}
|
||||
self.revision = self.revision.wrapping_add(1);
|
||||
self.modified = true;
|
||||
|
||||
self.mark_modified();
|
||||
Ok((painted, before))
|
||||
}
|
||||
|
||||
|
||||
@@ -80,6 +80,9 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
pub type FileList = Vec<(String, u64)>;
|
||||
/// Reads a file of the list by name.
|
||||
pub type Loader<'a> = &'a dyn Fn(&str) -> std::result::Result<Vec<u8>, String>;
|
||||
/// The file on disk a file of the list is read from (None: an archive entry or bytes in memory),
|
||||
/// asked right before reading it.
|
||||
type Locator<'a> = &'a dyn Fn(&str) -> Option<texturecraft_core::ResourceSource>;
|
||||
|
||||
mod pbr_options;
|
||||
mod take;
|
||||
@@ -137,10 +140,16 @@ impl Session {
|
||||
/// Import the maps found among `files` as one fill layer on the active texture set; `load`
|
||||
/// reads a file by name. Returns the reply of `file.importPbrFolder`.
|
||||
pub fn import_pbr(&mut self, files: &FileList, load: Loader, options: &PbrOptions) -> Result<Value> {
|
||||
self.import_pbr_with_budget(files, load, options, import_memory_budget())
|
||||
self.import_pbr_with_budget(files, load, &|_| None, options, import_memory_budget())
|
||||
}
|
||||
|
||||
fn import_pbr_with_budget(&mut self, files: &FileList, load: Loader, options: &PbrOptions, memory_budget: u64) -> Result<Value> {
|
||||
/// [`Session::import_pbr`] that records the disk files `locate` names, so the Resources Updater can read them again
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn import_pbr_located(&mut self, files: &FileList, load: Loader, locate: Locator, options: &PbrOptions) -> Result<Value> {
|
||||
self.import_pbr_with_budget(files, load, locate, options, import_memory_budget())
|
||||
}
|
||||
|
||||
fn import_pbr_with_budget(&mut self, files: &FileList, load: Loader, locate: Locator, options: &PbrOptions, memory_budget: u64) -> Result<Value> {
|
||||
let set = detect_with(files, &options.choose)?;
|
||||
if set.is_empty() {
|
||||
return Err(EngineError::Other(format!(
|
||||
@@ -193,6 +202,10 @@ impl Session {
|
||||
let mut fill = Fill { projection: options.projection.clone(), ..Fill::default() };
|
||||
let mut added: Vec<(String, Arc<Vec<u8>>)> = Vec::new();
|
||||
let mut decoded = Vec::new();
|
||||
|
||||
// Disk files read by name, and the resources that hold one of them unchanged
|
||||
let mut file_sources: BTreeMap<String, texturecraft_core::ResourceSource> = BTreeMap::new();
|
||||
let mut resource_sources: Vec<(String, texturecraft_core::ResourceSource)> = Vec::new();
|
||||
let mut channels: Vec<Channel> = Vec::new();
|
||||
let mut total_texels = 0u64;
|
||||
let mut retained_bytes = 0u64;
|
||||
@@ -231,6 +244,9 @@ impl Session {
|
||||
let loaded = if allowed_texels == 0 {
|
||||
Err("not enough memory is available to import more textures".to_string())
|
||||
} else {
|
||||
if let Some(source) = locate(&file) {
|
||||
file_sources.insert(file.clone(), source);
|
||||
}
|
||||
load(&file).and_then(|bytes| {
|
||||
if bytes.len() as u64 > MAX_FILE_BYTES {
|
||||
return Err(format!("the file is over {} MB", MAX_FILE_BYTES >> 20));
|
||||
@@ -288,10 +304,15 @@ impl Session {
|
||||
}
|
||||
};
|
||||
let base = texturecraft_formats::sanitize_resource_name(&resource_name);
|
||||
let (mut unique, mut suffix_index) = (base.clone(), 2);
|
||||
while self.doc.resources.contains_key(&unique) || added.iter().any(|(a, _)| *a == unique) {
|
||||
unique = format!("{suffix_index}_{base}");
|
||||
suffix_index += 1;
|
||||
let unique = crate::resource_cmds::unique_resource_name(base, |name| {
|
||||
self.doc.resources.contains_key(name) || added.iter().any(|(added_name, _)| added_name == name)
|
||||
});
|
||||
|
||||
// Only a resource holding the file's own bytes can be compared with it later
|
||||
if take == Take::Whole
|
||||
&& let Some(source) = file_sources.get(&file)
|
||||
{
|
||||
resource_sources.push((unique.clone(), source.clone()));
|
||||
}
|
||||
|
||||
added.push((unique.clone(), resource_bytes));
|
||||
@@ -316,6 +337,7 @@ impl Session {
|
||||
for (n, bytes) in &added {
|
||||
s.doc.resources.insert(n.clone(), bytes.clone());
|
||||
}
|
||||
s.doc.project.resource_sources.extend(resource_sources);
|
||||
let id = s.doc.project.alloc_id();
|
||||
crate::layer_cmds::insert_selected(s, Layer::new(id, layer_name.clone(), LayerKind::Fill(fill), &channels))
|
||||
})?;
|
||||
@@ -420,7 +442,12 @@ fn import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if options.name.is_none() {
|
||||
options.name = found.name.clone();
|
||||
}
|
||||
s.import_pbr(&found.files, &|name| found.load(name), &options)
|
||||
s.import_pbr_located(
|
||||
&found.files,
|
||||
&|name| found.load(name),
|
||||
&|name| found.disk_path(name).map(|path| crate::resource_update_cmds::file_source(&path)),
|
||||
&options,
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -462,7 +489,7 @@ mod tests {
|
||||
let mut session = Session::new_project("test", crate::geom::primitives::builtin("plane").unwrap(), "builtin:plane", None, 128).unwrap();
|
||||
let load = |_: &str| Ok(bytes.clone());
|
||||
|
||||
let result = session.import_pbr_with_budget(&files, &load, &PbrOptions::default(), 64);
|
||||
let result = session.import_pbr_with_budget(&files, &load, &|_| None, &PbrOptions::default(), 64);
|
||||
|
||||
assert!(result.unwrap_err().to_string().contains("more than 1 texels"));
|
||||
assert!(session.doc.resources.is_empty());
|
||||
@@ -471,7 +498,7 @@ mod tests {
|
||||
assert_eq!(allowed_source_texels(256, 64, 3), 2);
|
||||
|
||||
let never_load = |_: &str| -> std::result::Result<Vec<u8>, String> { panic!("no source should load after the budget is spent") };
|
||||
let result = session.import_pbr_with_budget(&files, &never_load, &PbrOptions::default(), 0);
|
||||
let result = session.import_pbr_with_budget(&files, &never_load, &|_| None, &PbrOptions::default(), 0);
|
||||
|
||||
assert!(result.unwrap_err().to_string().contains("not enough memory"));
|
||||
}
|
||||
|
||||
@@ -11,6 +11,16 @@ pub(in crate::pbr_cmds) struct Found {
|
||||
}
|
||||
|
||||
impl Found {
|
||||
/// The file on disk `name` is read from (None for an archive entry or a name not in the list)
|
||||
pub(in crate::pbr_cmds) fn disk_path(&self, name: &str) -> Option<String> {
|
||||
let path = match &self.source {
|
||||
Origin::Folder { root } => root.join(name),
|
||||
Origin::Files(paths) => paths.iter().find(|p| p.file_name().is_some_and(|n| n.to_string_lossy() == name))?.clone(),
|
||||
Origin::Zip(_) => return None,
|
||||
};
|
||||
path.to_str().map(str::to_string)
|
||||
}
|
||||
|
||||
/// Reads one file of the list. Archive entries are read through a limit, since their
|
||||
/// declared size can lie.
|
||||
pub(in crate::pbr_cmds) fn load(&self, name: &str) -> std::result::Result<Vec<u8>, String> {
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
//! An image file read again for a resource, checked before the project changes
|
||||
|
||||
use texturecraft_core::ResourceSource;
|
||||
use texturecraft_formats::DecodedImage;
|
||||
|
||||
use crate::Result;
|
||||
use crate::resource_cmds::{MAX_BYTES, read_image_file};
|
||||
use crate::resource_update_cmds::file_source;
|
||||
|
||||
/// A resource's new bytes, their decoded pixels and the file they came from
|
||||
pub(crate) struct ReloadedFile {
|
||||
pub name: String,
|
||||
pub bytes: Vec<u8>,
|
||||
pub image: DecodedImage,
|
||||
pub source: ResourceSource,
|
||||
}
|
||||
|
||||
impl ReloadedFile {
|
||||
pub(crate) fn read(cmd: &str, name: String, path: &str) -> Result<Self> {
|
||||
let source = file_source(path);
|
||||
let bytes = read_image_file(cmd, path, MAX_BYTES as u64)?;
|
||||
|
||||
Self::decode(cmd, name, source, bytes)
|
||||
}
|
||||
|
||||
pub(crate) fn read_changed(cmd: &str, name: &str, previous: &ResourceSource, stored: &[u8], decoded: bool) -> Result<Option<Self>> {
|
||||
let mut source = file_source(&previous.path);
|
||||
let bytes = read_image_file(cmd, &previous.path, MAX_BYTES as u64)?;
|
||||
let unchanged = bytes == stored;
|
||||
if unchanged && decoded {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
source.mesh_map = previous.mesh_map;
|
||||
let file = Self::decode(cmd, name.to_owned(), source, bytes)?;
|
||||
Ok((!unchanged).then_some(file))
|
||||
}
|
||||
|
||||
fn decode(cmd: &str, name: String, source: ResourceSource, bytes: Vec<u8>) -> Result<Self> {
|
||||
let image = texturecraft_formats::decode_image(&bytes).map_err(|error| crate::commands::bad(cmd, format!("{}: {error}", source.path)))?;
|
||||
|
||||
Ok(Self { name, bytes, image, source })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
//! A remembered comparison of a resource with its file, so an unchanged file is not read again
|
||||
|
||||
use std::sync::{Arc, Weak};
|
||||
|
||||
use crate::resource_status::ResourceStatus;
|
||||
|
||||
/// What reading a resource's file found, kept while the file's size and time stay the same
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct ResourceCheck {
|
||||
pub path: String,
|
||||
pub size: u64,
|
||||
pub modified_ms: u64,
|
||||
/// The resource bytes the file was compared with (an update or undo replaces them)
|
||||
pub bytes: Weak<Vec<u8>>,
|
||||
pub status: ResourceStatus,
|
||||
}
|
||||
|
||||
impl ResourceCheck {
|
||||
/// Whether this verdict still holds for the file and the resource's bytes
|
||||
pub(crate) fn holds_for(&self, path: &str, size: u64, modified_ms: u64, bytes: &Arc<Vec<u8>>) -> bool {
|
||||
self.path == path && self.size == size && self.modified_ms == modified_ms && std::ptr::eq(self.bytes.as_ptr(), Arc::as_ptr(bytes))
|
||||
}
|
||||
}
|
||||
@@ -34,24 +34,6 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
always,
|
||||
rename
|
||||
),
|
||||
cmd!(
|
||||
"resource.reload",
|
||||
"Reload resource",
|
||||
[],
|
||||
None,
|
||||
"{name} — read the image again from the file it was imported from in this session",
|
||||
always,
|
||||
reload
|
||||
),
|
||||
cmd!(
|
||||
"resource.update",
|
||||
"Update resources used in project",
|
||||
[],
|
||||
None,
|
||||
"{} — read again every image imported from a file in this session whose file changed (one undo step); returns {updated: [names], failed: [{name, error}]}",
|
||||
always,
|
||||
update
|
||||
),
|
||||
cmd!("file.removeUnused", "Remove unused resources...", ["File"], None, "{}", always, remove_unused),
|
||||
cmd!(
|
||||
"layer.add.image",
|
||||
@@ -73,6 +55,30 @@ pub(crate) fn decoded(d: texturecraft_formats::DecodedImage) -> Arc<ImageRes> {
|
||||
Arc::new(ImageRes::new(d.width, d.height, d.rgba, d.srgb))
|
||||
}
|
||||
|
||||
/// Disambiguate a sanitized resource name without losing its archive key on save.
|
||||
pub(crate) fn unique_resource_name(base: String, taken: impl Fn(&str) -> bool) -> String {
|
||||
if !taken(&base) {
|
||||
return base;
|
||||
}
|
||||
|
||||
let (stem, extension) = base.rfind('.').map_or((base.as_str(), ""), |start| base.split_at(start));
|
||||
let mut index = 2;
|
||||
loop {
|
||||
let discriminator = format!("{index}_");
|
||||
let available = MAX_RESOURCE_NAME_LEN - discriminator.len();
|
||||
|
||||
// An unusually long extension must leave room for the name itself
|
||||
let (stem, extension) = if extension.len() < available { (stem, extension) } else { (base.as_str(), "") };
|
||||
let stem = &stem[..stem.len().min(available - extension.len())];
|
||||
let name = format!("{discriminator}{stem}{extension}");
|
||||
if !taken(&name) {
|
||||
return name;
|
||||
}
|
||||
|
||||
index += 1;
|
||||
}
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Add an image resource from bytes (one undo step); returns its unique, sanitized name
|
||||
pub fn import_resource_bytes(&mut self, file_name: &str, bytes: Vec<u8>) -> Result<String> {
|
||||
@@ -107,40 +113,14 @@ impl Session {
|
||||
base.insert_str(0, &prefix);
|
||||
}
|
||||
|
||||
let (stem, extension) = base.rfind('.').map_or((base.as_str(), ""), |extension_start| base.split_at(extension_start));
|
||||
let mut name = base.clone();
|
||||
let mut duplicate_index = 2;
|
||||
while self.doc.resources.contains_key(&name) || crate::fill_alpha::library_alpha_of(&name).is_some() {
|
||||
let discriminator = format!("{duplicate_index}_");
|
||||
let available = MAX_RESOURCE_NAME_LEN - discriminator.len();
|
||||
|
||||
// Leave room for a stem even for names that end in an unusually long extension
|
||||
let (stem, extension) = if extension.len() < available { (stem, extension) } else { (base.as_str(), "") };
|
||||
let stem = stem.get(..stem.len().min(available - extension.len())).unwrap_or(stem);
|
||||
name = format!("{discriminator}{stem}{extension}");
|
||||
duplicate_index += 1;
|
||||
}
|
||||
let name = unique_resource_name(base, |name| self.doc.resources.contains_key(name) || crate::fill_alpha::library_alpha_of(name).is_some());
|
||||
|
||||
self.doc.resources.insert(name.clone(), Arc::new(bytes));
|
||||
self.images.insert(name.clone(), decoded(image));
|
||||
|
||||
Ok(name)
|
||||
}
|
||||
|
||||
/// The file image resource `name` was imported from in this session (what `resource.reload` reads again)
|
||||
pub fn resource_source(&self, name: &str) -> Option<&std::path::Path> {
|
||||
let bytes = self.doc.resources.get(name)?;
|
||||
self.resource_sources.iter().rev().find(|(source, _)| std::ptr::eq(source.as_ptr(), Arc::as_ptr(bytes))).map(|(_, path)| path.as_path())
|
||||
}
|
||||
|
||||
/// Remembers that image resource `name`, with the bytes it holds now, came from the file at `path`
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn remember_resource_source(&mut self, name: &str, path: &std::path::Path) {
|
||||
self.resource_sources.retain(|(source, _)| source.strong_count() > 0);
|
||||
if let Some(bytes) = self.doc.resources.get(name) {
|
||||
self.resource_sources.push((Arc::downgrade(bytes), path.to_path_buf()));
|
||||
}
|
||||
}
|
||||
|
||||
/// Decode resources that are not decoded yet and forget removed ones (after undo, redo, load).
|
||||
pub fn sync_images(&mut self) {
|
||||
self.images.retain(|name, _| self.doc.resources.contains_key(name));
|
||||
@@ -188,6 +168,16 @@ impl Session {
|
||||
self.drop_missing_image_view();
|
||||
}
|
||||
|
||||
/// Undo and redo restore resource bytes under the same name (the Resources Updater replaces
|
||||
/// them in place): the pixels decoded from the bytes `other` held are stale
|
||||
pub(crate) fn forget_replaced_images(&mut self, other: &crate::Document) {
|
||||
for (name, bytes) in &self.doc.resources {
|
||||
if other.resources.get(name).is_some_and(|previous| !Arc::ptr_eq(previous, bytes)) {
|
||||
self.images.remove(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The "Other..." view cannot show an image that is gone (removed or renamed): the material comes back
|
||||
pub(crate) fn drop_missing_image_view(&mut self) {
|
||||
if self.view == crate::ViewMode::Image && !self.view_image.as_ref().is_some_and(|name| self.images.contains_key(name)) {
|
||||
@@ -214,9 +204,16 @@ fn list(s: &Session) -> Value {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = strp(p, "path").ok_or_else(|| bad("resource.import", "`path` is required"))?;
|
||||
let prefix = strp(p, "prefix").unwrap_or("");
|
||||
|
||||
let source = crate::resource_update_cmds::file_source(path);
|
||||
let bytes = read_image_file("resource.import", path, MAX_BYTES as u64)?;
|
||||
let name = s.import_resource_bytes_prefixed(strp(p, "prefix").unwrap_or(""), path, bytes)?;
|
||||
s.remember_resource_source(&name, std::path::Path::new(path));
|
||||
|
||||
let name = s.edit("Import resource", |session| {
|
||||
let name = session.add_image_resource_prefixed(prefix, path, bytes, texturecraft_formats::MAX_RESOURCE_TEXELS)?;
|
||||
session.doc.project.resource_sources.insert(name.clone(), source);
|
||||
Ok(name)
|
||||
})?;
|
||||
Ok(json!({ "name": name }))
|
||||
}
|
||||
|
||||
@@ -298,6 +295,7 @@ fn remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
s.edit("Remove resource", |s| {
|
||||
s.doc.resources.remove(&name);
|
||||
s.doc.project.resource_sources.remove(&name);
|
||||
Ok(())
|
||||
})?;
|
||||
s.sync_images();
|
||||
@@ -350,6 +348,10 @@ fn rename(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
s.edit("Rename resource", |s| {
|
||||
let bytes = s.doc.resources.remove(&name).ok_or_else(|| bad(command, format!("no resource `{name}`")))?;
|
||||
s.doc.resources.insert(to.clone(), bytes);
|
||||
// The Resources Updater keeps following the file the image came from
|
||||
if let Some(source) = s.doc.project.resource_sources.remove(&name) {
|
||||
s.doc.project.resource_sources.insert(to.clone(), source);
|
||||
}
|
||||
rename_references(&mut s.doc.project, &name, &to);
|
||||
|
||||
// Refuse rather than leave a reference this rename does not know about pointing at nothing
|
||||
@@ -400,102 +402,6 @@ fn rename_references(project: &mut texturecraft_core::Project, from: &str, to: &
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads image resource `name` again from the file this session imported it from (one undo step)
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn reload(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let command = "resource.reload";
|
||||
let name = strp(p, "name").ok_or_else(|| bad(command, "`name` is required"))?.to_string();
|
||||
if !s.doc.resources.contains_key(&name) {
|
||||
return Err(bad(command, format!("no resource `{name}`")));
|
||||
}
|
||||
|
||||
let path = s
|
||||
.resource_source(&name)
|
||||
.map(std::path::Path::to_path_buf)
|
||||
.ok_or_else(|| bad(command, format!("`{name}` was imported before this session: no file to reload from")))?;
|
||||
let (bytes, image) = read_source(command, &path)?;
|
||||
s.edit("Reload resource", |s| {
|
||||
s.doc.resources.insert(name.clone(), Arc::new(bytes));
|
||||
Ok(())
|
||||
})?;
|
||||
|
||||
s.remember_resource_source(&name, &path);
|
||||
s.show_reloaded(name.clone(), image);
|
||||
Ok(json!({ "name": name }))
|
||||
}
|
||||
|
||||
/// Reads again, in one undo step, every image whose source file no longer holds the bytes the project has; nothing changed adds no step
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn update(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let command = "resource.update";
|
||||
let mut changed = Vec::new();
|
||||
let mut failed = Vec::new();
|
||||
for (name, held) in &s.doc.resources {
|
||||
let Some(path) = s.resource_source(name) else { continue };
|
||||
// Only a file whose bytes changed is decoded
|
||||
let read = read_resource_file(command, path, MAX_BYTES as u64)
|
||||
.and_then(|bytes| if bytes == **held { Ok(None) } else { decode_source(command, path, &bytes).map(|image| Some((bytes, image))) });
|
||||
match read {
|
||||
Ok(None) => {}
|
||||
Ok(Some((bytes, image))) => changed.push((name.clone(), path.to_path_buf(), bytes, image)),
|
||||
Err(error) => failed.push(json!({ "name": name, "error": error.to_string() })),
|
||||
}
|
||||
}
|
||||
|
||||
if !changed.is_empty() {
|
||||
s.edit("Update resources", |s| {
|
||||
for (name, _, bytes, _) in &mut changed {
|
||||
s.doc.resources.insert(name.clone(), Arc::new(std::mem::take(bytes)));
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
|
||||
let updated: Vec<String> = changed.iter().map(|(name, _, _, _)| name.clone()).collect();
|
||||
for (name, path, _, image) in changed {
|
||||
s.remember_resource_source(&name, &path);
|
||||
s.show_reloaded(name, image);
|
||||
}
|
||||
Ok(json!({ "updated": updated, "failed": failed }))
|
||||
}
|
||||
|
||||
/// The bytes of the image file at `path` and its decoded pixels
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn read_source(command: &str, path: &std::path::Path) -> Result<(Vec<u8>, texturecraft_formats::DecodedImage)> {
|
||||
let bytes = read_resource_file(command, path, MAX_BYTES as u64)?;
|
||||
let image = decode_source(command, path, &bytes)?;
|
||||
Ok((bytes, image))
|
||||
}
|
||||
|
||||
/// The pixels of `bytes` read from the image file at `path`
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn decode_source(command: &str, path: &std::path::Path, bytes: &[u8]) -> Result<texturecraft_formats::DecodedImage> {
|
||||
texturecraft_formats::decode_image_within(bytes, texturecraft_formats::MAX_RESOURCE_TEXELS)
|
||||
.map_err(|error| bad(command, format!("{}: {error}", path.display())))
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
impl Session {
|
||||
/// Shows the pixels of image `name` read again from its file, still a saved brush picture when it matches one
|
||||
fn show_reloaded(&mut self, name: String, image: texturecraft_formats::DecodedImage) {
|
||||
self.library_alphas.remove(&name);
|
||||
if crate::fill_alpha::matches_saved_picture(&name, &image) {
|
||||
self.library_alphas.insert(name.clone());
|
||||
}
|
||||
self.images.insert(name, decoded(image));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn reload(_: &mut Session, _: &Value) -> Result<Value> {
|
||||
Err(bad("resource.reload", "file paths are not available in the browser"))
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn update(_: &mut Session, _: &Value) -> Result<Value> {
|
||||
Err(bad("resource.update", "file paths are not available in the browser"))
|
||||
}
|
||||
|
||||
/// Every image resource a layer, mask effect, stored path or the environment of `project` uses
|
||||
fn project_images(project: &texturecraft_core::Project) -> Vec<String> {
|
||||
let mut used = Vec::new();
|
||||
@@ -514,16 +420,21 @@ fn images_in_use(s: &Session) -> Vec<String> {
|
||||
used.extend(s.tool.stencil.as_ref().map(|st| st.image.clone()));
|
||||
used.extend(s.tool.brush.alpha_image.clone());
|
||||
used.extend(s.tool.mask_image.clone());
|
||||
used.extend(s.doc.project.resource_sources.iter().filter_map(|(name, source)| {
|
||||
let slot = source.mesh_map?;
|
||||
s.doc.baked.get(&slot.texture_set).is_some_and(|baked| baked.maps.contains_key(&slot.map)).then(|| name.clone())
|
||||
}));
|
||||
used
|
||||
}
|
||||
|
||||
/// Drop resources no layer, mask effect, the brush alpha, the projection stencil, the mask brush or the environment uses (one undo step)
|
||||
/// Drop resources unused by layers, mesh maps, paint tools or the environment (one undo step)
|
||||
fn remove_unused(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let used = images_in_use(s);
|
||||
let unused: Vec<String> = s.doc.resources.keys().filter(|k| !used.contains(k)).cloned().collect();
|
||||
if !unused.is_empty() {
|
||||
s.edit("Remove unused resources", |s| {
|
||||
s.doc.resources.retain(|k, _| !unused.contains(k));
|
||||
s.doc.project.resource_sources.retain(|k, _| !unused.contains(k));
|
||||
Ok(())
|
||||
})?;
|
||||
s.sync_images();
|
||||
@@ -618,6 +529,21 @@ mod tests {
|
||||
assert_eq!(session.tool.brush.alpha_image.as_ref(), Some(&renamed), "the brush alpha follows the redo");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_renamed_image_keeps_following_its_file() {
|
||||
let path = std::env::temp_dir().join(format!("texturecraft-rename-source-{}.png", std::process::id()));
|
||||
std::fs::write(&path, texturecraft_formats::gray16_png(1, 1, [0.25].into_iter()).unwrap()).unwrap();
|
||||
let mut session = crate::sample_session(128, 32).unwrap();
|
||||
let name = crate::execute(&mut session, "resource.import", &json!({"path": path.to_str().unwrap()})).unwrap()["name"].as_str().unwrap().to_string();
|
||||
|
||||
let renamed = crate::execute(&mut session, "resource.rename", &json!({"name": name, "to": "stone"})).unwrap()["name"].as_str().unwrap().to_string();
|
||||
std::fs::write(&path, texturecraft_formats::gray16_png(1, 1, [0.75].into_iter()).unwrap()).unwrap();
|
||||
let updated = crate::execute(&mut session, "resource.update", &json!({"names": [renamed]})).unwrap();
|
||||
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
assert_eq!(updated["updated"], json!([renamed]), "the renamed image reads its changed file again: {updated}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renaming_a_linked_materials_package_moves_a_material_effects_link_with_it() {
|
||||
use std::collections::BTreeMap;
|
||||
@@ -674,97 +600,6 @@ mod tests {
|
||||
assert_eq!(generator.grunge, Some(Source::image(renamed)), "the generator's grunge follows the rename");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reloading_reads_the_file_again_and_undo_restores_the_pixels() {
|
||||
let mut session = crate::sample_session(128, 32).unwrap();
|
||||
let path = std::env::temp_dir().join(format!("texturecraft-reload-resource-{}.png", std::process::id()));
|
||||
std::fs::write(&path, texturecraft_formats::gray16_png(1, 1, [0.2].into_iter()).unwrap()).unwrap();
|
||||
let name = crate::execute(&mut session, "resource.import", &json!({"path": path.to_str().unwrap()})).unwrap()["name"].as_str().unwrap().to_string();
|
||||
let before = session.images[&name].rgba.clone();
|
||||
std::fs::write(&path, texturecraft_formats::gray16_png(1, 1, [0.8].into_iter()).unwrap()).unwrap();
|
||||
|
||||
crate::execute(&mut session, "resource.reload", &json!({"name": name})).unwrap();
|
||||
let reloaded = session.images[&name].rgba.clone();
|
||||
session.undo().unwrap();
|
||||
|
||||
assert_ne!(reloaded, before, "reload decodes the file's new pixels");
|
||||
assert_eq!(session.images[&name].rgba, before, "undo shows the old pixels again");
|
||||
std::fs::remove_file(path).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_image_under_a_removed_ones_name_does_not_reload_its_file() {
|
||||
let mut session = crate::sample_session(128, 32).unwrap();
|
||||
let path = std::env::temp_dir().join(format!("texturecraft-reused-name-{}.png", std::process::id()));
|
||||
std::fs::write(&path, texturecraft_formats::gray16_png(1, 1, [0.2].into_iter()).unwrap()).unwrap();
|
||||
let name = crate::execute(&mut session, "resource.import", &json!({"path": path.to_str().unwrap()})).unwrap()["name"].as_str().unwrap().to_string();
|
||||
crate::execute(&mut session, "resource.remove", &json!({"name": name})).unwrap();
|
||||
|
||||
let reused = session.import_resource_bytes(&name, texturecraft_formats::gray16_png(1, 1, [0.6].into_iter()).unwrap()).unwrap();
|
||||
std::fs::remove_file(path).unwrap();
|
||||
|
||||
assert_eq!(reused, name, "the name is free again");
|
||||
assert!(session.resource_source(&reused).is_none(), "the new image has no file to reload from");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undo_gives_an_image_back_its_own_file_after_another_file_took_its_name() {
|
||||
let mut session = crate::sample_session(128, 32).unwrap();
|
||||
let folder = |side: &str| std::env::temp_dir().join(format!("texturecraft-own-file-{side}-{}", std::process::id()));
|
||||
let import = |session: &mut Session, side: &str, value: f32| {
|
||||
std::fs::create_dir_all(folder(side)).unwrap();
|
||||
let path = folder(side).join("photo.png");
|
||||
std::fs::write(&path, texturecraft_formats::gray16_png(1, 1, [value].into_iter()).unwrap()).unwrap();
|
||||
let name = crate::execute(session, "resource.import", &json!({"path": path.to_str().unwrap()})).unwrap()["name"].as_str().unwrap().to_string();
|
||||
(path, name)
|
||||
};
|
||||
let (first_path, first) = import(&mut session, "first", 0.2);
|
||||
crate::execute(&mut session, "resource.remove", &json!({"name": first})).unwrap();
|
||||
let (second_path, second) = import(&mut session, "second", 0.6);
|
||||
|
||||
// One undo takes back the second import, the next the removal
|
||||
session.undo().unwrap();
|
||||
session.undo().unwrap();
|
||||
let source = session.resource_source(&first).map(std::path::Path::to_path_buf);
|
||||
for side in ["first", "second"] {
|
||||
std::fs::remove_dir_all(folder(side)).unwrap();
|
||||
}
|
||||
|
||||
assert_eq!(second, first, "the second file takes the removed image's name");
|
||||
assert_ne!(first_path, second_path);
|
||||
assert_eq!(source, Some(first_path), "the image the undo brings back reloads from its own file");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn updating_reads_only_changed_files_in_one_undo_step() {
|
||||
let mut session = crate::sample_session(128, 32).unwrap();
|
||||
let import = |session: &mut Session, label: &str, value: f32| {
|
||||
let path = std::env::temp_dir().join(format!("texturecraft-update-{label}-{}.png", std::process::id()));
|
||||
std::fs::write(&path, texturecraft_formats::gray16_png(1, 1, [value].into_iter()).unwrap()).unwrap();
|
||||
let name = crate::execute(session, "resource.import", &json!({"path": path.to_str().unwrap()})).unwrap()["name"].as_str().unwrap().to_string();
|
||||
(path, name)
|
||||
};
|
||||
let (edited_path, edited) = import(&mut session, "edited", 0.2);
|
||||
let (kept_path, kept) = import(&mut session, "kept", 0.4);
|
||||
let unchanged = crate::execute(&mut session, "resource.update", &json!({})).unwrap();
|
||||
let steps = session.history_labels().len();
|
||||
let before = session.images[&edited].rgba.clone();
|
||||
std::fs::write(&edited_path, texturecraft_formats::gray16_png(1, 1, [0.8].into_iter()).unwrap()).unwrap();
|
||||
|
||||
let result = crate::execute(&mut session, "resource.update", &json!({})).unwrap();
|
||||
let updated = session.images[&edited].rgba.clone();
|
||||
let steps_after = session.history_labels().len();
|
||||
session.undo().unwrap();
|
||||
|
||||
assert_eq!(unchanged["updated"], json!([]), "files that didn't change aren't read in again");
|
||||
assert_eq!(result["updated"], json!([edited]), "only the changed file is read again, not `{kept}`");
|
||||
assert_ne!(updated, before, "the changed file's new pixels show");
|
||||
assert_eq!(steps_after, steps + 1, "one undo step for the update");
|
||||
assert_eq!(session.images[&edited].rgba, before, "undo shows the old pixels again");
|
||||
std::fs::remove_file(edited_path).unwrap();
|
||||
std::fs::remove_file(kept_path).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_reads_obey_the_remaining_byte_budget() {
|
||||
let path = std::env::temp_dir().join(format!("texturecraft-read-image-{}.png", std::process::id()));
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
//! One row of the Resources Updater: an image resource, its file and how they compare
|
||||
|
||||
use crate::resource_status::ResourceStatus;
|
||||
|
||||
/// An image resource, the file it came from and whether that file changed on disk
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ResourceState {
|
||||
/// The resource's name in the project.
|
||||
pub name: String,
|
||||
/// How the resource compares with its file now.
|
||||
pub status: ResourceStatus,
|
||||
/// The file it was imported from or relinked to (None: made in the app or imported without a path).
|
||||
pub path: Option<String>,
|
||||
/// Why the file could not be checked (with [`ResourceStatus::Missing`]).
|
||||
pub error: Option<String>,
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
//! Whether a resource still matches the file it was imported from
|
||||
|
||||
/// How a resource compares with its file on disk (materials have none). The order is the Resources Updater's
|
||||
/// list order: what needs attention first.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub enum ResourceStatus {
|
||||
/// The file changed since it was read: Update reads it again.
|
||||
Outdated,
|
||||
/// The file is gone, or cannot be read.
|
||||
Missing,
|
||||
/// The file still holds the resource's bytes.
|
||||
UpToDate,
|
||||
/// Made in the app or imported without a file path: there is nothing to compare with.
|
||||
NoSource,
|
||||
/// A linked MaterialCraft package stored in the project, without a source file to compare.
|
||||
Material,
|
||||
}
|
||||
|
||||
impl ResourceStatus {
|
||||
pub const ALL: [ResourceStatus; 5] =
|
||||
[ResourceStatus::Outdated, ResourceStatus::Missing, ResourceStatus::UpToDate, ResourceStatus::NoSource, ResourceStatus::Material];
|
||||
|
||||
/// The id used by the control protocol
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
ResourceStatus::Outdated => "outdated",
|
||||
ResourceStatus::Missing => "missing",
|
||||
ResourceStatus::UpToDate => "upToDate",
|
||||
ResourceStatus::NoSource => "noSource",
|
||||
ResourceStatus::Material => "material",
|
||||
}
|
||||
}
|
||||
|
||||
/// The name shown in the Resources Updater (English; the shell translates it)
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
ResourceStatus::Outdated => "Outdated",
|
||||
ResourceStatus::Missing => "Missing",
|
||||
ResourceStatus::UpToDate => "Up to date",
|
||||
ResourceStatus::NoSource => "No source file",
|
||||
ResourceStatus::Material => "Material",
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,395 @@
|
||||
//! The Resources Updater: compare image resources with the files they came from, read changed
|
||||
//! files again and point a resource at another file. Each change is one undo step, and every
|
||||
//! layer, mask and view using a changed resource recomposites; a mesh map imported from a changed
|
||||
//! file is resampled while it still holds what the file gave it.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_core::ResourceSource;
|
||||
|
||||
use crate::commands::{CommandSpec, always, bad};
|
||||
use crate::resource_state::ResourceState;
|
||||
use crate::resource_status::ResourceStatus;
|
||||
use crate::{Result, Session, cmd};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
"resource.status",
|
||||
"Check resources on disk",
|
||||
[],
|
||||
None,
|
||||
"{} → {resources: [{name, status: outdated|missing|upToDate|noSource|material, path?, error?}] (outdated first; material: a stored MaterialCraft package), total, outdated}",
|
||||
always,
|
||||
|s, _| Ok(status(s))
|
||||
),
|
||||
cmd!(
|
||||
"resource.update",
|
||||
"Update resources",
|
||||
[],
|
||||
None,
|
||||
"{names?: [resource name] (default: every outdated resource)} → {updated, failed: [{name, error}]} — reads their files again, one undo step",
|
||||
always,
|
||||
update
|
||||
),
|
||||
cmd!(
|
||||
"resource.relink",
|
||||
"Relink resource",
|
||||
[],
|
||||
None,
|
||||
"{name: image resource, path — an image file (png, jpg, tga, tif, bmp, webp, exr, hdr)} → {name, path} — the resource takes the file's pixels and follows it from now on",
|
||||
always,
|
||||
relink
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Project images and linked MaterialCraft packages, ordered by status and then by name.
|
||||
/// Equal-size files are compared when their modification time changed or is unknown.
|
||||
/// A known time lets later checks reuse the verdict.
|
||||
pub fn resource_states(&mut self) -> Vec<ResourceState> {
|
||||
let mut states = self.compare_resources();
|
||||
let materials = self.material_packages().into_iter();
|
||||
states.extend(materials.map(|name| ResourceState { name, status: ResourceStatus::Material, path: None, error: None }));
|
||||
states.sort_by(|a, b| a.status.cmp(&b.status).then_with(|| a.name.cmp(&b.name)));
|
||||
states
|
||||
}
|
||||
|
||||
/// The packages of linked MaterialCraft materials (fill layers and material effects) the project holds
|
||||
fn material_packages(&self) -> std::collections::BTreeSet<String> {
|
||||
use texturecraft_core::{EffectKind, Fill, LayerKind};
|
||||
|
||||
let package_of = |fill: &Fill| fill.link.as_ref().map(|link| link.package.clone());
|
||||
let mut packages = std::collections::BTreeSet::new();
|
||||
for layer in self.doc.project.layers.values() {
|
||||
if let LayerKind::Fill(fill) = &layer.kind {
|
||||
packages.extend(package_of(fill));
|
||||
}
|
||||
for effect in layer.mask.iter().flat_map(|mask| &mask.effects).chain(&layer.content_effects) {
|
||||
if let EffectKind::Material(fill) = &effect.kind {
|
||||
packages.extend(package_of(fill));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
packages.retain(|name| self.doc.resources.contains_key(name));
|
||||
packages
|
||||
}
|
||||
|
||||
/// Whether `name` is an image resource the Resources Updater lists
|
||||
fn is_image_resource(&self, name: &str) -> bool {
|
||||
self.doc.resources.contains_key(name) && (self.images.contains_key(name) || self.doc.project.resource_sources.contains_key(name))
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn compare_resources(&mut self) -> Vec<ResourceState> {
|
||||
let mut checks = std::mem::take(&mut self.resource_checks);
|
||||
let names: Vec<String> = self.doc.resources.keys().filter(|name| self.is_image_resource(name)).cloned().collect();
|
||||
let mut states = Vec::with_capacity(names.len());
|
||||
for name in names {
|
||||
let (Some(bytes), source) = (self.doc.resources.get(&name), self.doc.project.resource_sources.get(&name)) else { continue };
|
||||
let (status, error) = source.map_or((ResourceStatus::NoSource, None), |source| compare_with_file(&name, source, bytes, &mut checks));
|
||||
states.push(ResourceState { path: source.map(|source| source.path.clone()), name, status, error });
|
||||
}
|
||||
|
||||
checks.retain(|name, _| self.doc.resources.contains_key(name));
|
||||
self.resource_checks = checks;
|
||||
states
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn compare_resources(&mut self) -> Vec<ResourceState> {
|
||||
let sources = &self.doc.project.resource_sources;
|
||||
let browser = "file paths are not available in the browser";
|
||||
let names = self.doc.resources.keys().filter(|name| self.is_image_resource(name));
|
||||
names
|
||||
.map(|name| match sources.get(name) {
|
||||
Some(source) => {
|
||||
ResourceState { name: name.clone(), status: ResourceStatus::Missing, path: Some(source.path.clone()), error: Some(browser.into()) }
|
||||
}
|
||||
None => ResourceState { name: name.clone(), status: ResourceStatus::NoSource, path: None, error: None },
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Stream changed files into one undo step. A mesh map is compared before its first tile is replaced.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn install_reloaded(&mut self, label: &str, files: impl Iterator<Item = crate::reloaded_file::ReloadedFile>) -> Result<Vec<String>> {
|
||||
let mut files = files.peekable();
|
||||
if files.peek().is_none() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
||||
let mut updated = Vec::new();
|
||||
let result = self.edit(label, |session| {
|
||||
let mut slots = std::collections::BTreeMap::new();
|
||||
for file in files {
|
||||
if let Some(slot) = file.source.mesh_map {
|
||||
slots.entry((slot.texture_set, slot.map)).or_insert_with(|| session.mesh_map_matches(slot.texture_set, slot.map));
|
||||
}
|
||||
|
||||
let name = file.name;
|
||||
if crate::fill_alpha::matches_saved_picture(&name, &file.image) {
|
||||
session.library_alphas.insert(name.clone());
|
||||
} else {
|
||||
session.library_alphas.remove(&name);
|
||||
}
|
||||
|
||||
session.images.insert(name.clone(), crate::resource_cmds::decoded(file.image));
|
||||
session.doc.resources.insert(name.clone(), std::sync::Arc::new(file.bytes));
|
||||
session.doc.project.resource_sources.insert(name.clone(), file.source);
|
||||
updated.push(name);
|
||||
}
|
||||
|
||||
for ((texture_set, map), matches) in slots {
|
||||
if matches {
|
||||
let images = session.mesh_map_images(texture_set, map).ok_or_else(|| bad("resource.update", "a mesh map source image is missing"))?;
|
||||
crate::meshmap_cmds::use_images(session, "resource.update", texture_set, map, &images)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
|
||||
if let Err(error) = result {
|
||||
// The edit restored the encoded bytes, so rebuild any cache entries replaced before rollback
|
||||
for name in &updated {
|
||||
self.images.remove(name);
|
||||
}
|
||||
self.sync_images();
|
||||
return Err(error);
|
||||
}
|
||||
|
||||
Ok(updated)
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn mesh_map_images(
|
||||
&self,
|
||||
texture_set: usize,
|
||||
map: texturecraft_core::BakedMap,
|
||||
) -> Option<std::collections::BTreeMap<u32, std::sync::Arc<texturecraft_compose::ImageRes>>> {
|
||||
let mut images = std::collections::BTreeMap::new();
|
||||
for (name, source) in &self.doc.project.resource_sources {
|
||||
if let Some(slot) = source.mesh_map.filter(|slot| slot.texture_set == texture_set && slot.map == map) {
|
||||
images.insert(slot.tile, self.images.get(name)?.clone());
|
||||
}
|
||||
}
|
||||
|
||||
Some(images)
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn mesh_map_matches(&self, texture_set: usize, map: texturecraft_core::BakedMap) -> bool {
|
||||
let Some(current) = self.doc.baked.get(&texture_set).and_then(|baked| baked.maps.get(&map)) else { return false };
|
||||
let Some(images) = self.mesh_map_images(texture_set, map) else { return false };
|
||||
|
||||
crate::mesh_map_sampler::MeshMapSampler::new(self, "resource.update", texture_set, map, &images).is_ok_and(|sampler| sampler.matches(current))
|
||||
}
|
||||
}
|
||||
|
||||
/// How `stored` (a resource's bytes) compares with the file `source` names now, reusing the
|
||||
/// remembered verdict in `checks` while the file's size and time stay the same
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn compare_with_file(
|
||||
name: &str,
|
||||
source: &ResourceSource,
|
||||
stored: &std::sync::Arc<Vec<u8>>,
|
||||
checks: &mut std::collections::HashMap<String, crate::resource_check::ResourceCheck>,
|
||||
) -> (ResourceStatus, Option<String>) {
|
||||
let path = std::path::Path::new(&source.path);
|
||||
let metadata = match std::fs::metadata(path) {
|
||||
Ok(metadata) if metadata.is_file() => metadata,
|
||||
Ok(_) => return (ResourceStatus::Missing, Some(format!("{} is not a regular file", source.path))),
|
||||
Err(error) => return (ResourceStatus::Missing, Some(format!("{}: {error}", source.path))),
|
||||
};
|
||||
|
||||
let size = metadata.len();
|
||||
if size != stored.len() as u64 {
|
||||
return (ResourceStatus::Outdated, None);
|
||||
}
|
||||
|
||||
let modified_ms = modified_ms(&metadata);
|
||||
if modified_ms != 0 && modified_ms == source.modified_ms {
|
||||
return (ResourceStatus::UpToDate, None);
|
||||
}
|
||||
|
||||
if let Some(check) = checks.get(name)
|
||||
&& check.holds_for(&source.path, size, modified_ms, stored)
|
||||
{
|
||||
return (check.status, None);
|
||||
}
|
||||
|
||||
// A newer time alone is not a change: the file may have been saved again unchanged
|
||||
let status = match file_matches(path, stored) {
|
||||
Ok(true) => ResourceStatus::UpToDate,
|
||||
Ok(false) => ResourceStatus::Outdated,
|
||||
Err(error) => return (ResourceStatus::Missing, Some(error.to_string())),
|
||||
};
|
||||
if modified_ms == 0 {
|
||||
// An unknown time cannot establish that the next check sees the same file contents
|
||||
checks.remove(name);
|
||||
} else {
|
||||
let bytes = std::sync::Arc::downgrade(stored);
|
||||
checks.insert(name.to_string(), crate::resource_check::ResourceCheck { path: source.path.clone(), size, modified_ms, bytes, status });
|
||||
}
|
||||
|
||||
(status, None)
|
||||
}
|
||||
|
||||
/// Compare without allocating a second copy of the resource. Read to the checked end to detect I/O errors and growth.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn file_matches(path: &std::path::Path, stored: &[u8]) -> Result<bool> {
|
||||
use std::io::{ErrorKind, Read};
|
||||
|
||||
const CMD: &str = "resource.status";
|
||||
const CHUNK_BYTES: usize = 32 * 1024;
|
||||
let read_error = |error| bad(CMD, format!("cannot read {}: {error}", path.display()));
|
||||
let too_large = || bad(CMD, format!("{} is too large (limit {} bytes)", path.display(), crate::resource_cmds::MAX_BYTES));
|
||||
let mut file = crate::resource_cmds::open_resource_file(CMD, path)?;
|
||||
let len = file.metadata().map_err(read_error)?.len();
|
||||
if len > crate::resource_cmds::MAX_BYTES as u64 {
|
||||
return Err(too_large());
|
||||
}
|
||||
|
||||
let mut chunk = [0; CHUNK_BYTES];
|
||||
let mut equal = len == stored.len() as u64;
|
||||
for start in (0..len as usize).step_by(CHUNK_BYTES) {
|
||||
let end = (start + CHUNK_BYTES).min(len as usize);
|
||||
let part = &mut chunk[..end - start];
|
||||
match file.read_exact(part) {
|
||||
Ok(()) => equal = equal && stored.get(start..end) == Some(part),
|
||||
Err(error) if error.kind() == ErrorKind::UnexpectedEof => return Ok(false),
|
||||
Err(error) => return Err(read_error(error)),
|
||||
}
|
||||
}
|
||||
|
||||
if file.read(&mut [0]).map_err(read_error)? > 0 {
|
||||
return Err(too_large());
|
||||
}
|
||||
|
||||
Ok(equal)
|
||||
}
|
||||
|
||||
/// A file's modification time in milliseconds since the Unix epoch (0 when the system has none)
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn modified_ms(metadata: &std::fs::Metadata) -> u64 {
|
||||
let since_epoch = metadata.modified().ok().and_then(|modified| modified.duration_since(std::time::UNIX_EPOCH).ok());
|
||||
since_epoch.map_or(0, |elapsed| u64::try_from(elapsed.as_millis()).unwrap_or(u64::MAX))
|
||||
}
|
||||
|
||||
/// The record for an image about to be read from `path`: its absolute path and its current
|
||||
/// modification time, taken before reading so a write during the read still shows as a change
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn file_source(path: &str) -> ResourceSource {
|
||||
let absolute = std::path::absolute(path).ok().and_then(|absolute| absolute.to_str().map(str::to_string)).unwrap_or_else(|| path.to_string());
|
||||
let modified_ms = std::fs::metadata(path).map_or(0, |metadata| modified_ms(&metadata));
|
||||
ResourceSource { path: absolute, modified_ms, mesh_map: None }
|
||||
}
|
||||
|
||||
/// The browser reads no paths; the record keeps the name it was given
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub(crate) fn file_source(path: &str) -> ResourceSource {
|
||||
ResourceSource { path: path.to_string(), modified_ms: 0, mesh_map: None }
|
||||
}
|
||||
|
||||
fn status(s: &mut Session) -> Value {
|
||||
let states = s.resource_states();
|
||||
let outdated = states.iter().filter(|state| state.status == ResourceStatus::Outdated).count();
|
||||
let resources: Vec<Value> = states
|
||||
.iter()
|
||||
.map(|state| {
|
||||
let mut row = json!({"name": state.name, "status": state.status.id()});
|
||||
if let Some(path) = &state.path {
|
||||
row["path"] = json!(path);
|
||||
}
|
||||
if let Some(error) = &state.error {
|
||||
row["error"] = json!(error);
|
||||
}
|
||||
|
||||
row
|
||||
})
|
||||
.collect();
|
||||
|
||||
json!({"resources": resources, "total": states.len(), "outdated": outdated})
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn update(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const CMD: &str = "resource.update";
|
||||
|
||||
let names: Vec<String> = match p.get("names") {
|
||||
None | Some(Value::Null) => s.resource_states().into_iter().filter(|state| state.status == ResourceStatus::Outdated).map(|state| state.name).collect(),
|
||||
Some(Value::Array(names)) => {
|
||||
names.iter().map(|name| name.as_str().map(str::to_string).ok_or_else(|| bad(CMD, "`names` must be resource names"))).collect::<Result<_>>()?
|
||||
}
|
||||
Some(_) => return Err(bad(CMD, "`names` must be an array of resource names")),
|
||||
};
|
||||
|
||||
// Validate the complete selection before opening files
|
||||
let mut selected = Vec::new();
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
for name in names {
|
||||
let bytes = s.doc.resources.get(&name).ok_or_else(|| bad(CMD, format!("no resource `{name}`")))?;
|
||||
let Some(source) = s.doc.project.resource_sources.get(&name) else {
|
||||
let reason = if s.images.contains_key(&name) {
|
||||
format!("`{name}` has no source file: relink it to a file first")
|
||||
} else {
|
||||
format!("`{name}` has no source file: only image resources can be relinked")
|
||||
};
|
||||
return Err(bad(CMD, reason));
|
||||
};
|
||||
|
||||
if seen.insert(name.clone()) {
|
||||
let decoded = s.images.contains_key(&name);
|
||||
selected.push((name, source.clone(), bytes.clone(), decoded));
|
||||
}
|
||||
}
|
||||
|
||||
let mut failed = Vec::new();
|
||||
let files = selected.into_iter().filter_map(|(name, source, stored, decoded)| {
|
||||
match crate::reloaded_file::ReloadedFile::read_changed(CMD, &name, &source, &stored, decoded) {
|
||||
Ok(file) => file,
|
||||
Err(error) => {
|
||||
failed.push(json!({"name": name, "error": error.to_string()}));
|
||||
None
|
||||
}
|
||||
}
|
||||
});
|
||||
let updated = s.install_reloaded("Update resources", files)?;
|
||||
|
||||
if updated.is_empty() && !failed.is_empty() {
|
||||
let reasons: Vec<&str> = failed.iter().filter_map(|failure| failure["error"].as_str()).collect();
|
||||
return Err(bad(CMD, format!("nothing was updated: {}", reasons.join("; "))));
|
||||
}
|
||||
|
||||
Ok(json!({"updated": updated, "failed": failed}))
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn relink(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const CMD: &str = "resource.relink";
|
||||
|
||||
let name = crate::commands::strp(p, "name").ok_or_else(|| bad(CMD, "`name` is required"))?.to_string();
|
||||
let path = crate::commands::strp(p, "path").ok_or_else(|| bad(CMD, "`path` is required"))?;
|
||||
if !s.is_image_resource(&name) {
|
||||
return Err(bad(CMD, format!("no image resource `{name}`")));
|
||||
}
|
||||
|
||||
// A relinked mesh map file still feeds its mesh map
|
||||
let mut file = crate::reloaded_file::ReloadedFile::read(CMD, name.clone(), path)?;
|
||||
file.source.mesh_map = s.doc.project.resource_sources.get(&name).and_then(|source| source.mesh_map);
|
||||
let path = file.source.path.clone();
|
||||
s.install_reloaded("Relink resource", std::iter::once(file))?;
|
||||
|
||||
Ok(json!({"name": name, "path": path}))
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn update(_: &mut Session, _: &Value) -> Result<Value> {
|
||||
Err(bad("resource.update", "file paths are not available in the browser"))
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn relink(_: &mut Session, _: &Value) -> Result<Value> {
|
||||
Err(bad("resource.relink", "file paths are not available in the browser"))
|
||||
}
|
||||
@@ -33,6 +33,9 @@ pub struct Document {
|
||||
pub resources: BTreeMap<String, Arc<Vec<u8>>>,
|
||||
/// High-definition meshes and cage for baking (saved inside the project)
|
||||
pub bake_meshes: crate::BakeMeshes,
|
||||
/// Skew and cage paint bounds since each set's last Auto-rebake. Undo restores the bounds
|
||||
/// with their maps. The project file omits these bounds.
|
||||
pub(crate) painted_regions: BTreeMap<usize, crate::bake::PaintedRegion>,
|
||||
}
|
||||
|
||||
/// Derived per-texture-set data (rebuilt when the mesh or resolution changes).
|
||||
@@ -425,9 +428,15 @@ pub struct Session {
|
||||
pub project_id: u64,
|
||||
/// The mesh with its own UVs (`mesh` maps UV-tiled sets into their atlas).
|
||||
pub(crate) source: Arc<Mesh>,
|
||||
/// Fingerprint of the bake inputs in `source`, computed on first use
|
||||
pub(crate) low_poly_fingerprint: std::sync::OnceLock<u64>,
|
||||
/// Fingerprint of the packed mesh file, computed only for bakes that read its material colors.
|
||||
pub(crate) low_material_file_fingerprint: std::sync::OnceLock<u64>,
|
||||
/// Skew and cage strokes so far
|
||||
pub(crate) painted_strokes: u64,
|
||||
pub bvh: Arc<Bvh>,
|
||||
/// Original mesh file (saved inside the project); None for built-in meshes.
|
||||
pub mesh_source: Option<(String, Vec<u8>)>,
|
||||
pub mesh_source: Option<(String, Arc<Vec<u8>>)>,
|
||||
pub caches: Vec<SetCache>,
|
||||
pub(crate) undo: Vec<(String, Document)>,
|
||||
pub(crate) redo: Vec<(String, Document)>,
|
||||
@@ -451,6 +460,8 @@ pub struct Session {
|
||||
pub solo: Option<crate::Solo>,
|
||||
/// The live bake preview while the app bakes (see [`crate::bake_preview`]).
|
||||
pub bake_preview: Option<crate::bake_preview::BakePreview>,
|
||||
/// The latest bake, map by map (the Baking Log)
|
||||
pub bake_log: crate::bake::BakeLog,
|
||||
/// Viewport size (pixels) used by scripted strokes.
|
||||
pub viewport: Vec2,
|
||||
pub(crate) stroke: Option<ActiveStroke>,
|
||||
@@ -462,8 +473,9 @@ pub struct Session {
|
||||
pub images: texturecraft_compose::ImageStore,
|
||||
/// Resource names whose decoded pixels match a library alpha.
|
||||
pub(crate) library_alphas: BTreeSet<String>,
|
||||
/// The file each image resource imported in this session came from, for Reload (not saved). Kept by the resource's bytes, so undo, redo and renames keep each file with its own image
|
||||
pub(crate) resource_sources: Vec<(std::sync::Weak<Vec<u8>>, std::path::PathBuf)>,
|
||||
/// Resources whose file was read for the Resources Updater, by name: the verdict stays while the file's size and time do
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) resource_checks: std::collections::HashMap<String, crate::resource_check::ResourceCheck>,
|
||||
/// Temporary texel mask limiting paint strokes (not saved, not in the history).
|
||||
pub quick_mask: crate::quick_mask::QuickMask,
|
||||
/// A path sublayer is being repainted from its paths (the only way to paint into one).
|
||||
@@ -480,6 +492,9 @@ pub struct Session {
|
||||
/// (see [`crate::commands::check_enabled`]).
|
||||
pub project_open: bool,
|
||||
pub modified: bool,
|
||||
/// Edits to saved data, independent of viewport and tool changes.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) save_revision: u64,
|
||||
/// Bumps on every document change.
|
||||
pub revision: u64,
|
||||
/// Messages for the UI (status bar / toasts).
|
||||
@@ -524,9 +539,12 @@ impl Session {
|
||||
mesh_id: next_mesh_id(),
|
||||
project_id: next_mesh_id(),
|
||||
source,
|
||||
low_poly_fingerprint: Default::default(),
|
||||
low_material_file_fingerprint: Default::default(),
|
||||
painted_strokes: 0,
|
||||
mesh,
|
||||
bvh: Arc::new(bvh),
|
||||
mesh_source,
|
||||
mesh_source: mesh_source.map(|(extension, bytes)| (extension, Arc::new(bytes))),
|
||||
caches,
|
||||
undo: Vec::new(),
|
||||
redo: Vec::new(),
|
||||
@@ -542,13 +560,15 @@ impl Session {
|
||||
view_image: None,
|
||||
solo: None,
|
||||
bake_preview: None,
|
||||
bake_log: Default::default(),
|
||||
viewport: Vec2::new(1280.0, 800.0),
|
||||
stroke: None,
|
||||
clipboard: None,
|
||||
blending_clipboard: None,
|
||||
images: Default::default(),
|
||||
library_alphas: BTreeSet::new(),
|
||||
resource_sources: Vec::new(),
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
resource_checks: std::collections::HashMap::new(),
|
||||
quick_mask: Default::default(),
|
||||
painting_paths: false,
|
||||
path_cache: None,
|
||||
@@ -557,6 +577,8 @@ impl Session {
|
||||
path: None,
|
||||
project_open: true,
|
||||
modified: false,
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
save_revision: 0,
|
||||
revision: 1,
|
||||
log: crate::log::SessionLog::new(),
|
||||
log_id: next_mesh_id(),
|
||||
@@ -586,6 +608,10 @@ impl Session {
|
||||
pub fn switch_to(&mut self, mut next: Session) {
|
||||
// Invalidate caches even when both projects were loaded with the same revision
|
||||
next.revision = self.revision.wrapping_add(1);
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
next.save_revision = self.save_revision.wrapping_add(1);
|
||||
}
|
||||
|
||||
next.viewport = self.viewport;
|
||||
next.export_presets = std::mem::take(&mut self.export_presets);
|
||||
@@ -638,6 +664,7 @@ impl Session {
|
||||
pixels: PixelStore::default(),
|
||||
baked: BTreeMap::new(),
|
||||
resources: BTreeMap::new(),
|
||||
painted_regions: Default::default(),
|
||||
},
|
||||
mesh,
|
||||
mesh_source,
|
||||
@@ -738,8 +765,7 @@ impl Session {
|
||||
self.path_steps = Default::default();
|
||||
}
|
||||
|
||||
self.modified = true;
|
||||
self.revision = self.revision.wrapping_add(1);
|
||||
self.mark_modified();
|
||||
if !(merge && self.undo.last().is_some_and(|(l, _)| l == label)) {
|
||||
self.undo.push((label.to_string(), before));
|
||||
}
|
||||
@@ -750,8 +776,7 @@ impl Session {
|
||||
|
||||
/// A change from `other` to the current document that is not an undo step (a path preview)
|
||||
pub(crate) fn changed_without_history(&mut self, other: &Document) {
|
||||
self.modified = true;
|
||||
self.revision = self.revision.wrapping_add(1);
|
||||
self.mark_modified();
|
||||
self.invalidate_changed(other);
|
||||
}
|
||||
|
||||
@@ -877,14 +902,23 @@ impl Session {
|
||||
|
||||
/// Mark the document changed and every texture set dirty.
|
||||
pub fn touched(&mut self) {
|
||||
self.modified = true;
|
||||
self.revision = self.revision.wrapping_add(1);
|
||||
self.mark_modified();
|
||||
self.sync_caches();
|
||||
for c in &mut self.caches {
|
||||
c.invalidate_all();
|
||||
}
|
||||
}
|
||||
|
||||
/// Mark saved data changed without invalidating the texture sets.
|
||||
pub fn mark_modified(&mut self) {
|
||||
self.modified = true;
|
||||
self.revision = self.revision.wrapping_add(1);
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
self.save_revision = self.save_revision.wrapping_add(1);
|
||||
}
|
||||
}
|
||||
|
||||
/// Make caches agree with the project's texture sets (resolution or channel changes).
|
||||
pub fn sync_caches(&mut self) {
|
||||
let sets = self.doc.project.texture_sets.clone();
|
||||
@@ -967,6 +1001,7 @@ impl Session {
|
||||
let (label, restored) = self.undo.pop().ok_or_else(|| EngineError::Other("nothing to undo".into()))?;
|
||||
let current = std::mem::replace(&mut self.doc, restored);
|
||||
self.after_history(¤t);
|
||||
self.forget_replaced_images(¤t);
|
||||
self.redo.push((label.clone(), current));
|
||||
self.sync_images();
|
||||
Ok(label)
|
||||
@@ -987,26 +1022,21 @@ impl Session {
|
||||
let (label, restored) = self.redo.pop().ok_or_else(|| EngineError::Other("nothing to redo".into()))?;
|
||||
let current = std::mem::replace(&mut self.doc, restored);
|
||||
self.after_history(¤t);
|
||||
self.forget_replaced_images(¤t);
|
||||
self.undo.push((label.clone(), current));
|
||||
self.sync_images();
|
||||
Ok(label)
|
||||
}
|
||||
|
||||
fn after_history(&mut self, other: &Document) {
|
||||
// A resource whose bytes the step changed (a reload) decodes again
|
||||
self.images.retain(|name, _| match (other.resources.get(name), self.doc.resources.get(name)) {
|
||||
(Some(left), Some(right)) => Arc::ptr_eq(left, right),
|
||||
_ => true,
|
||||
});
|
||||
self.follow_renamed_resources(other);
|
||||
|
||||
// Pending operations may still hold layer IDs from the discarded snapshot
|
||||
self.doc.project.next_id = self.doc.project.next_id.max(other.project.next_id);
|
||||
self.modified = true;
|
||||
self.mark_modified();
|
||||
|
||||
// Layers picked together belong to the stack they were picked in
|
||||
self.multi.clear();
|
||||
self.revision = self.revision.wrapping_add(1);
|
||||
self.invalidate_changed(other);
|
||||
|
||||
// An undone add or duplicate takes the selected effect away
|
||||
|
||||
@@ -243,6 +243,7 @@ impl Session {
|
||||
pixels: pf.pixels,
|
||||
baked: BTreeMap::new(),
|
||||
resources: BTreeMap::new(),
|
||||
painted_regions: Default::default(),
|
||||
};
|
||||
|
||||
let label = src.project.texture_sets.first().map(|t| t.name.clone()).unwrap_or_default();
|
||||
|
||||
@@ -36,6 +36,7 @@ pub struct ProjectTemplate {
|
||||
pub spec_gloss: bool,
|
||||
pub parallax: bool,
|
||||
pub ior: f32,
|
||||
pub ior_specular: bool,
|
||||
pub scatter_color: [f32; 3],
|
||||
pub scatter_radius: f32,
|
||||
}
|
||||
@@ -51,6 +52,7 @@ impl Default for ProjectTemplate {
|
||||
spec_gloss: d.spec_gloss,
|
||||
parallax: d.parallax,
|
||||
ior: d.ior,
|
||||
ior_specular: d.ior_specular,
|
||||
scatter_color: d.scatter_color,
|
||||
scatter_radius: d.scatter_radius,
|
||||
}
|
||||
@@ -116,7 +118,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Project templates",
|
||||
[],
|
||||
None,
|
||||
"{} → [{name, label, builtin, resolution, normalFormat, channels: [ids], specGloss}]",
|
||||
"{} → [{name, label, builtin, resolution, normalFormat, channels: [ids], specGloss, iorSpecular}]",
|
||||
always,
|
||||
list
|
||||
),
|
||||
@@ -189,28 +191,36 @@ impl Session {
|
||||
matches.next().is_none().then(|| template.clone())
|
||||
}
|
||||
|
||||
/// Start this (new, unpainted) project from template `t`: its channels on every texture set
|
||||
/// and layer, normal format and shader settings. The resolution is the caller's choice.
|
||||
pub fn apply_template(&mut self, t: &ProjectTemplate) {
|
||||
let p = &mut self.doc.project;
|
||||
p.normal_format = t.normal_format;
|
||||
let d = &mut p.display;
|
||||
(d.spec_gloss, d.parallax, d.ior, d.scatter_color, d.scatter_radius) = (t.spec_gloss, t.parallax, t.ior, t.scatter_color, t.scatter_radius);
|
||||
for ts in 0..p.texture_sets.len() {
|
||||
if let Some(set) = p.texture_sets.get_mut(ts) {
|
||||
set.channels = t.channels.clone();
|
||||
/// Apply the template's channels and shader settings to a new, unpainted project.
|
||||
/// The caller chooses the texture set resolution.
|
||||
pub fn apply_template(&mut self, template: &ProjectTemplate) {
|
||||
let project = &mut self.doc.project;
|
||||
project.normal_format = template.normal_format;
|
||||
|
||||
let display = &mut project.display;
|
||||
display.spec_gloss = template.spec_gloss;
|
||||
display.parallax = template.parallax;
|
||||
display.ior = template.ior;
|
||||
display.ior_specular = template.ior_specular;
|
||||
display.scatter_color = template.scatter_color;
|
||||
display.scatter_radius = template.scatter_radius;
|
||||
|
||||
for set_index in 0..project.texture_sets.len() {
|
||||
if let Some(set) = project.texture_sets.get_mut(set_index) {
|
||||
set.channels = template.channels.clone();
|
||||
}
|
||||
let wanted: Vec<Channel> = t.channels.iter().map(|(c, _)| *c).collect();
|
||||
for (id, _) in p.walk(ts) {
|
||||
if let Ok(l) = p.layer_mut(id) {
|
||||
let mode = if l.is_group() { texturecraft_core::BlendMode::Passthrough } else { texturecraft_core::BlendMode::Normal };
|
||||
l.channels.retain(|c, _| wanted.contains(c));
|
||||
for c in &wanted {
|
||||
l.channels.entry(*c).or_insert(ChannelBlend { mode, opacity: 1.0 });
|
||||
|
||||
for (id, _) in project.walk(set_index) {
|
||||
if let Ok(layer) = project.layer_mut(id) {
|
||||
let mode = if layer.is_group() { texturecraft_core::BlendMode::Passthrough } else { texturecraft_core::BlendMode::Normal };
|
||||
layer.channels.retain(|channel, _| template.channels.iter().any(|(wanted, _)| channel == wanted));
|
||||
for &(channel, _) in &template.channels {
|
||||
layer.channels.entry(channel).or_insert(ChannelBlend { mode, opacity: 1.0 });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
self.touched();
|
||||
self.modified = false;
|
||||
}
|
||||
@@ -277,6 +287,7 @@ fn list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
"normalFormat": if t.normal_format == NormalFormat::DirectX { "directX" } else { "openGl" },
|
||||
"channels": t.channels.iter().map(|(c, _)| c.id()).collect::<Vec<_>>(),
|
||||
"specGloss": t.spec_gloss,
|
||||
"iorSpecular": t.ior_specular,
|
||||
})
|
||||
};
|
||||
Ok(json!(builtin_templates().iter().map(|t| entry(t, true)).chain(s.templates.list.iter().map(|t| entry(t, false))).collect::<Vec<_>>()))
|
||||
@@ -296,6 +307,7 @@ fn save(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
spec_gloss: display.spec_gloss,
|
||||
parallax: display.parallax,
|
||||
ior: display.ior,
|
||||
ior_specular: display.ior_specular,
|
||||
scatter_color: display.scatter_color,
|
||||
scatter_radius: display.scatter_radius,
|
||||
};
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Edit, viewport and display commands.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_core::project::ENVIRONMENTS;
|
||||
use texturecraft_core::project::{ENVIRONMENTS, MAX_INDEX_OF_REFRACTION, MIN_INDEX_OF_REFRACTION};
|
||||
use texturecraft_core::{BakedMap, Channel, EffectKind, EnvAlignment, Filter, Project, ShadowMode, ToneMapping};
|
||||
|
||||
use crate::commands::{CommandSpec, always, bad, boolp, can_redo, can_undo, color_param, f32p, strp, u64p, vec3};
|
||||
@@ -70,7 +70,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Display settings",
|
||||
[],
|
||||
None,
|
||||
"{environment?: <built-in>|resource:<image resource>, exposure?, blur?, rotation?, opacity?, toneMapping?: linear|aces, fov?, shadows?, shadowMode? (intensive|average|lightweight: the shadow map resolution), shadowOpacity? (0..1: how dark the shadows are), alignment? (world|camera: what the environment turns with), soloUnlit? (single-channel views flat; off: lit), aoIntensity?, bloom?, vignette?, sharpen?, grain?, postEffects?, taa?, specGloss?, parallax?, displacement? (the viewport moves the surface by the height channel), scatterColor?: [r,g,b] linear or \"#rrggbb\" sRGB, scatterRadius? (0..1 of the mesh radius), ior? (1..3, transmission), dof?: {enabled?, focusDistance? (view depth, world units; 0 = the orbit target), aperture? (lens radius, 0..1 of the mesh radius)}, projectionGizmos? (the selected fill's projection gizmos show in the 3D view)}",
|
||||
"{environment?: <built-in>|resource:<image resource>, exposure?, blur?, rotation?, opacity?, toneMapping?: linear|aces, fov?, shadows?, shadowMode? (intensive|average|lightweight: the shadow map resolution), shadowOpacity? (0..1: how dark the shadows are), alignment? (world|camera: what the environment turns with), soloUnlit? (single-channel views flat; off: lit), aoIntensity?, bloom?, vignette?, sharpen?, grain?, postEffects?, taa?, specGloss?, parallax?, displacement? (the viewport moves the surface by the height channel), scatterColor?: [r,g,b] linear or \"#rrggbb\" sRGB, scatterRadius? (0..1 of the mesh radius), ior? (1..3, transmission), iorSpecular? (use IOR for dielectric reflectance at normal incidence in Metallic Roughness), dof?: {enabled?, focusDistance? (view depth, world units; 0 = the orbit target), aperture? (lens radius, 0..1 of the mesh radius)}, projectionGizmos? (the selected fill's projection gizmos show in the 3D view)}",
|
||||
always,
|
||||
display
|
||||
),
|
||||
@@ -314,6 +314,8 @@ fn display(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let scatter_color = color_param("display.set", p, "scatterColor")?;
|
||||
let (environment_before, rotation_before) = (s.doc.project.display.environment.clone(), s.doc.project.display.env_rotation);
|
||||
let settings = &mut s.doc.project.display;
|
||||
let (ior_before, ior_specular_before, spec_gloss_before) = (settings.ior, settings.ior_specular, settings.spec_gloss);
|
||||
|
||||
if let Some(picked) = environment {
|
||||
settings.environment = picked;
|
||||
}
|
||||
@@ -329,7 +331,7 @@ fn display(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
("sharpen", &mut settings.sharpen, 0.0, 1.0),
|
||||
("grain", &mut settings.grain, 0.0, 1.0),
|
||||
("scatterRadius", &mut settings.scatter_radius, 0.0, 1.0),
|
||||
("ior", &mut settings.ior, 1.0, 3.0),
|
||||
("ior", &mut settings.ior, MIN_INDEX_OF_REFRACTION, MAX_INDEX_OF_REFRACTION),
|
||||
("shadowOpacity", &mut settings.shadow_opacity, 0.0, 1.0),
|
||||
] {
|
||||
if let Some(value) = f32p(p, key) {
|
||||
@@ -366,6 +368,7 @@ fn display(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
("postEffects", &mut settings.post_effects),
|
||||
("taa", &mut settings.taa),
|
||||
("specGloss", &mut settings.spec_gloss),
|
||||
("iorSpecular", &mut settings.ior_specular),
|
||||
("parallax", &mut settings.parallax),
|
||||
("displacement", &mut settings.displacement),
|
||||
("soloUnlit", &mut settings.solo_unlit),
|
||||
@@ -376,6 +379,9 @@ fn display(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
|
||||
let saved_settings_changed =
|
||||
settings.ior_specular != ior_specular_before || (settings.ior_specular && (settings.ior != ior_before || settings.spec_gloss != spec_gloss_before));
|
||||
|
||||
// The field of view applies to the view only when set (a saved camera keeps its own)
|
||||
if f32p(p, "fov").is_some() {
|
||||
s.camera.fov = s.doc.project.display.fov;
|
||||
@@ -388,7 +394,12 @@ fn display(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
cache.invalidate_all();
|
||||
}
|
||||
}
|
||||
s.revision = s.revision.wrapping_add(1);
|
||||
if saved_settings_changed {
|
||||
s.mark_modified();
|
||||
} else {
|
||||
s.revision = s.revision.wrapping_add(1);
|
||||
}
|
||||
|
||||
Ok(serde_json::to_value(&s.doc.project.display).unwrap_or(Value::Null))
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Live bake preview: maps stream into the view while a bake runs, the view mode comes back,
|
||||
//! painting is paused, a cancelled bake leaves the set it was baking alone (sets finished before it
|
||||
//! painting is paused, ending the preview leaves the set it was baking alone (sets finished before it
|
||||
//! stay applied), the streamed pixels are the ones a single bake makes, and the preview and the
|
||||
//! document share each map's buffer instead of holding two copies.
|
||||
|
||||
@@ -208,14 +208,14 @@ fn cancelling_mid_bake_leaves_the_document_and_the_shown_maps_whole() {
|
||||
|
||||
assert!(result.is_err(), "a cancelled bake fails");
|
||||
|
||||
// The two maps that landed are whole and equal to a full bake's; the others are still neutral
|
||||
// Compare the streamed pixels with a full bake to verify each preview is complete
|
||||
let shown = session.bake_preview_baked(0).unwrap();
|
||||
assert_eq!(shown.maps.len(), 2);
|
||||
for (map, data) in &shown.maps {
|
||||
assert!(**data == full.maps[map], "{map:?}");
|
||||
}
|
||||
|
||||
// What the app does on cancel: end the preview; the document keeps what it had
|
||||
// The UI applies eligible maps separately through keep_canceled_bake
|
||||
session.bake_preview_end();
|
||||
|
||||
assert_eq!(session.doc.baked.get(&0).cloned(), before);
|
||||
|
||||
@@ -0,0 +1,231 @@
|
||||
//! Auto-rebake: one map per texture set, due when it goes out of date, rebaked alone
|
||||
|
||||
use serde_json::json;
|
||||
use texturecraft_engine::bake::Progress;
|
||||
use texturecraft_engine::core::BakedMap;
|
||||
use texturecraft_engine::geom::primitives;
|
||||
use texturecraft_engine::{Session, execute, sample_session};
|
||||
|
||||
/// A plane with its position and ID maps baked
|
||||
fn baked_plane() -> Session {
|
||||
let mesh = primitives::builtin("plane").unwrap();
|
||||
let mut session = Session::new_project("t", mesh, "builtin:plane", None, 128).unwrap();
|
||||
execute(&mut session, "bake.run", &json!({ "resolution": 64, "maps": ["position", "id"], "dilation": 0 })).unwrap();
|
||||
session
|
||||
}
|
||||
|
||||
fn due_maps(session: &Session) -> Vec<(usize, BakedMap)> {
|
||||
session.auto_rebake_due().into_iter().map(|(set, map, _)| (set, map)).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_map_per_set_is_auto_rebaked_and_it_is_due_only_once_out_of_date() {
|
||||
let mut session = baked_plane();
|
||||
execute(&mut session, "bake.autoRebake", &json!({ "map": "id" })).unwrap();
|
||||
let turned_on = execute(&mut session, "bake.autoRebake", &json!({ "map": "position" })).unwrap();
|
||||
assert_eq!(turned_on, json!({ "ts": 0, "autoRebake": "position" }), "the second map replaces the first");
|
||||
assert!(due_maps(&session).is_empty(), "up to date: {:?}", due_maps(&session));
|
||||
|
||||
execute(&mut session, "bake.settings", &json!({ "positionMode": "boundingBox" })).unwrap();
|
||||
assert_eq!(due_maps(&session), [(0, BakedMap::Position)]);
|
||||
|
||||
execute(&mut session, "bake.autoRebake", &json!({ "map": null })).unwrap();
|
||||
assert!(due_maps(&session).is_empty(), "turned off: {:?}", due_maps(&session));
|
||||
assert!(execute(&mut session, "bake.autoRebake", &json!({ "map": "glow" })).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_auto_rebake_map_is_saved_with_the_project_and_undone_like_an_edit() {
|
||||
let mut session = baked_plane();
|
||||
let before = session.to_project_bytes().unwrap();
|
||||
execute(&mut session, "bake.autoRebake", &json!({ "map": "position" })).unwrap();
|
||||
|
||||
let reopened = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap();
|
||||
assert_eq!(reopened.doc.project.texture_sets[0].auto_rebake, Some(BakedMap::Position));
|
||||
let inspect = execute(&mut session, "project.inspect", &json!({})).unwrap();
|
||||
assert_eq!(inspect["textureSets"][0]["autoRebake"], json!("position"));
|
||||
|
||||
execute(&mut session, "edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(session.doc.project.texture_sets[0].auto_rebake, None);
|
||||
assert_eq!(Session::from_project_bytes(&before).unwrap().doc.project.texture_sets[0].auto_rebake, None, "older projects have none");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_one_map_bake_brings_that_map_up_to_date_and_leaves_the_others_alone() {
|
||||
let mut session = baked_plane();
|
||||
execute(&mut session, "bake.settings", &json!({ "maps": ["id"], "positionMode": "boundingBox" })).unwrap();
|
||||
let id_before = session.baked(0).unwrap().maps[&BakedMap::Id].clone();
|
||||
|
||||
let task = session.bake_task_for(0, &[BakedMap::Position]).unwrap();
|
||||
assert_eq!(task.maps(), [BakedMap::Position], "an unchecked map bakes when asked for");
|
||||
let output = task.run_streaming(&Progress::new(), &mut |_| {}).unwrap();
|
||||
session.apply_streamed_bake(0, output).unwrap();
|
||||
|
||||
assert!(session.bake_changes(0, BakedMap::Position).is_empty(), "{:?}", session.bake_changes(0, BakedMap::Position));
|
||||
let baked = session.baked(0).unwrap();
|
||||
assert!(std::sync::Arc::ptr_eq(&baked.maps[&BakedMap::Id], &id_before), "the ID map was not baked again");
|
||||
assert_eq!(session.doc.project.texture_sets[0].bake.maps.enabled().collect::<Vec<_>>(), [BakedMap::Id], "the checks stay");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_output_size_rebakes_every_checked_map_so_none_is_lost() {
|
||||
let mut session = baked_plane();
|
||||
execute(&mut session, "bake.autoRebake", &json!({ "map": "position" })).unwrap();
|
||||
execute(&mut session, "bake.settings", &json!({ "resolution": 128 })).unwrap();
|
||||
|
||||
let maps = session.auto_rebake_maps(0, BakedMap::Position);
|
||||
let output = session.bake_task_for(0, &maps).unwrap().run_streaming(&Progress::new(), &mut |_| {}).unwrap();
|
||||
session.apply_streamed_bake(0, output).unwrap();
|
||||
|
||||
let baked = session.baked(0).unwrap();
|
||||
assert!(baked.maps.contains_key(&BakedMap::Id), "the ID map survives the new size: {:?}", baked.maps.keys().collect::<Vec<_>>());
|
||||
assert!(session.out_of_date_maps(0).is_empty(), "{:?}", session.out_of_date_maps(0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unchanged_uv_atlas_size_rebakes_only_the_auto_rebake_map() {
|
||||
let mut session = Session::new_project("t", primitives::udim_plane(), "builtin:udim_plane", None, 128).unwrap();
|
||||
execute(&mut session, "bake.run", &json!({ "resolution": 64, "maps": ["position", "id"], "dilation": 0 })).unwrap();
|
||||
let id_before = session.baked(0).unwrap().maps[&BakedMap::Id].clone();
|
||||
execute(&mut session, "bake.autoRebake", &json!({ "map": "position" })).unwrap();
|
||||
execute(&mut session, "bake.settings", &json!({ "positionMode": "boundingBox" })).unwrap();
|
||||
|
||||
let maps = session.auto_rebake_maps(0, BakedMap::Position);
|
||||
let output = session.bake_task_for(0, &maps).unwrap().run_streaming(&Progress::new(), &mut |_| {}).unwrap();
|
||||
session.apply_streamed_bake(0, output).unwrap();
|
||||
|
||||
let id_after = &session.baked(0).unwrap().maps[&BakedMap::Id];
|
||||
assert!(std::sync::Arc::ptr_eq(&id_before, id_after), "an unchanged atlas size leaves the other map alone");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_skew_stroke_rebakes_only_its_box_and_the_box_matches_a_whole_bake() {
|
||||
let mut session = super::bake::leaning_session(true);
|
||||
execute(&mut session, "bake.run", &json!({ "maps": ["position"], "dilation": 2 })).unwrap();
|
||||
execute(&mut session, "bake.autoRebake", &json!({ "map": "position" })).unwrap();
|
||||
assert!(session.auto_rebake_painted().is_empty(), "nothing painted since the bake");
|
||||
let before = session.baked(0).unwrap().maps[&BakedMap::Position].clone();
|
||||
|
||||
execute(&mut session, "bake.skew.paint", &json!({ "points": [[0.3, 0.3], [0.4, 0.35]], "radius": 0.05, "size": 64 })).unwrap();
|
||||
let painted: Vec<_> = session.auto_rebake_painted().into_iter().map(|(set, map, _, _)| (set, map)).collect();
|
||||
assert_eq!(painted, [(0, BakedMap::Position)]);
|
||||
assert!(session.auto_rebake_due().is_empty(), "painting is not a settings change: {:?}", due_maps(&session));
|
||||
|
||||
let mut task = session.bake_painted_task(0, BakedMap::Position).unwrap();
|
||||
task.tracer = None;
|
||||
let region = task.region.expect("a stroke rebakes only its box");
|
||||
let mut whole = session.bake_task_for(0, &[BakedMap::Position]).unwrap();
|
||||
whole.tracer = None;
|
||||
let whole = whole.run(&Progress::new()).unwrap().maps.remove(&BakedMap::Position).unwrap();
|
||||
let output = task.run_streaming(&Progress::new(), &mut |_| {}).unwrap();
|
||||
|
||||
let width = output.resolution as usize;
|
||||
assert!(((region.max.0 - region.min.0) as usize) < width / 2, "the box is far smaller than the map: {region:?}");
|
||||
let components = BakedMap::Position.components();
|
||||
let pixels = output.maps[&BakedMap::Position].chunks(components).zip(before.chunks(components)).zip(whole.chunks(components));
|
||||
let mut changed = 0;
|
||||
for (index, ((rebaked, kept), baked_whole)) in pixels.enumerate() {
|
||||
assert_eq!(rebaked, baked_whole, "texel {index} matches a whole bake");
|
||||
if region.contains(index % width, index / width) {
|
||||
changed += usize::from(rebaked != kept);
|
||||
} else {
|
||||
assert_eq!(rebaked, kept, "texel {index} outside the box");
|
||||
}
|
||||
}
|
||||
assert!(changed > 0, "the stroke changed the map inside its box");
|
||||
|
||||
session.apply_streamed_bake(0, output).unwrap();
|
||||
assert!(session.auto_rebake_painted().is_empty(), "the rebake took the stroke");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stroke_painted_while_the_rebake_runs_waits_for_the_next_one() {
|
||||
let mut session = super::bake::leaning_session(true);
|
||||
execute(&mut session, "bake.run", &json!({ "maps": ["position"], "dilation": 2 })).unwrap();
|
||||
execute(&mut session, "bake.autoRebake", &json!({ "map": "position" })).unwrap();
|
||||
let stroke = |at: f32| json!({ "points": [[at, at]], "radius": 0.05, "size": 64 });
|
||||
execute(&mut session, "bake.skew.paint", &stroke(0.3)).unwrap();
|
||||
|
||||
let mut task = session.bake_painted_task(0, BakedMap::Position).unwrap();
|
||||
task.tracer = None;
|
||||
execute(&mut session, "bake.skew.paint", &stroke(0.7)).unwrap();
|
||||
let output = task.run_streaming(&Progress::new(), &mut |_| {}).unwrap();
|
||||
session.apply_streamed_bake(0, output).unwrap();
|
||||
|
||||
let painted: Vec<_> = session.auto_rebake_painted().into_iter().map(|(set, map, _, _)| (set, map)).collect();
|
||||
assert_eq!(painted, [(0, BakedMap::Position)], "the second stroke is not in the stored map yet");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undoing_the_rebake_of_a_stroke_makes_its_box_due_again() {
|
||||
let mut session = super::bake::leaning_session(true);
|
||||
execute(&mut session, "bake.run", &json!({ "maps": ["position"], "dilation": 2 })).unwrap();
|
||||
execute(&mut session, "bake.autoRebake", &json!({ "map": "position" })).unwrap();
|
||||
execute(&mut session, "bake.skew.paint", &json!({ "points": [[0.3, 0.3]], "radius": 0.05, "size": 64 })).unwrap();
|
||||
let mut task = session.bake_painted_task(0, BakedMap::Position).unwrap();
|
||||
task.tracer = None;
|
||||
let output = task.run_streaming(&Progress::new(), &mut |_| {}).unwrap();
|
||||
session.apply_streamed_bake(0, output).unwrap();
|
||||
assert!(session.auto_rebake_painted().is_empty(), "the rebake took the stroke");
|
||||
|
||||
session.undo().unwrap();
|
||||
|
||||
let painted: Vec<_> = session.auto_rebake_painted().into_iter().map(|(set, map, _, _)| (set, map)).collect();
|
||||
assert_eq!(painted, [(0, BakedMap::Position)], "the map is back to its pixels from before the stroke, which is still painted");
|
||||
session.redo().unwrap();
|
||||
assert!(session.auto_rebake_painted().is_empty(), "redo brings the rebake back");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bake_after_a_mesh_reimport_takes_the_strokes_painted_before_it() {
|
||||
let quad = "v 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 1 1\nvt 0 1\nf 1/1 2/2 3/3\nf 1/1 3/3 4/4\n";
|
||||
let mut session = Session::from_mesh_bytes_with_uvs("quad.obj", quad.as_bytes(), 128, "quad", None, false).unwrap();
|
||||
session.add_high_poly_bytes("quad_high.obj", quad.replace("v 1 1 0", "v 1 1 0.1").into_bytes()).unwrap();
|
||||
execute(&mut session, "bake.run", &json!({ "resolution": 32, "maps": ["position"], "dilation": 0 })).unwrap();
|
||||
execute(&mut session, "bake.autoRebake", &json!({ "map": "position" })).unwrap();
|
||||
execute(&mut session, "bake.skew.paint", &json!({ "points": [[0.5, 0.5]], "radius": 0.05, "size": 64 })).unwrap();
|
||||
|
||||
session.reimport_mesh(None, false).unwrap();
|
||||
execute(&mut session, "bake.run", &json!({})).unwrap();
|
||||
|
||||
let painted: Vec<_> = session.auto_rebake_painted().into_iter().map(|(set, map, _, _)| (set, map)).collect();
|
||||
assert!(painted.is_empty(), "the bake after the reimport took the stroke: {painted:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_bake_keeps_the_painted_box_of_the_sets_it_rolled_back() {
|
||||
let mut session = sample_session(256, 64).unwrap();
|
||||
session.add_high_poly_bytes("detail_high.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap();
|
||||
execute(&mut session, "bake.run", &json!({ "ts": "all", "resolution": 32, "maps": ["position"], "dilation": 0 })).unwrap();
|
||||
execute(&mut session, "bake.autoRebake", &json!({ "ts": 0, "map": "position" })).unwrap();
|
||||
execute(&mut session, "bake.skew.paint", &json!({ "ts": 0, "points": [[0.5, 0.5]], "radius": 0.05, "size": 64 })).unwrap();
|
||||
let second = &mut session.doc.project.texture_sets[1].bake.maps.ao;
|
||||
second.is_enabled = true;
|
||||
second.parameters.rays.rays = 0;
|
||||
|
||||
assert!(execute(&mut session, "bake.run", &json!({ "ts": "all" })).is_err(), "set 1's AO has no rays to cast");
|
||||
|
||||
let painted: Vec<_> = session.auto_rebake_painted().into_iter().map(|(set, map, _, _)| (set, map)).collect();
|
||||
assert_eq!(painted, [(0, BakedMap::Position)], "set 0's stroke is still waiting for its rebake");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_first_skew_stroke_turns_auto_rebake_on_for_the_normal_map_once() {
|
||||
let mut session = super::bake::leaning_session(true);
|
||||
let stroke = json!({ "points": [[0.5, 0.5]], "radius": 0.05, "size": 64 });
|
||||
execute(&mut session, "bake.cage.paint", &stroke).unwrap();
|
||||
assert_eq!(session.doc.project.texture_sets[0].auto_rebake, None, "cage painting leaves it alone");
|
||||
|
||||
execute(&mut session, "bake.skew.paint", &stroke).unwrap();
|
||||
assert_eq!(session.doc.project.texture_sets[0].auto_rebake, Some(BakedMap::Normal));
|
||||
execute(&mut session, "edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(session.doc.project.texture_sets[0].auto_rebake, None, "undone with the stroke");
|
||||
|
||||
execute(&mut session, "bake.autoRebake", &json!({ "map": "position" })).unwrap();
|
||||
execute(&mut session, "bake.skew.paint", &stroke).unwrap();
|
||||
assert_eq!(session.doc.project.texture_sets[0].auto_rebake, Some(BakedMap::Position), "a map picked before stays");
|
||||
|
||||
execute(&mut session, "bake.autoRebake", &json!({ "map": null })).unwrap();
|
||||
execute(&mut session, "bake.skew.paint", &stroke).unwrap();
|
||||
assert_eq!(session.doc.project.texture_sets[0].auto_rebake, None, "turned off after skew painting started, it stays off");
|
||||
}
|
||||
@@ -435,6 +435,35 @@ fn textured_glb(mesh: &Mesh, dy: f32, png: &[u8]) -> Vec<u8> {
|
||||
glb
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reimporting_a_low_poly_texture_changes_opacity_provenance() {
|
||||
use texturecraft_engine::core::BakeChange;
|
||||
use texturecraft_engine::formats::MeshFile;
|
||||
|
||||
let mesh = primitives::builtin("plane").unwrap();
|
||||
let name = "painted.glb";
|
||||
let mut session = Session::from_mesh_bytes(name, &textured_glb(&mesh, 0.0, &quadrants_png()), 128, "painted").unwrap();
|
||||
execute(&mut session, "bake.run", &json!({ "resolution": 32, "maps": ["opacity", "position"], "dilation": 0 })).unwrap();
|
||||
execute(&mut session, "bake.autoRebake", &json!({ "map": "opacity" })).unwrap();
|
||||
let prior_opacity = session.baked(0).unwrap().maps[&BakedMap::Opacity].clone();
|
||||
let mut opaque = Vec::new();
|
||||
image::RgbaImage::from_pixel(4, 4, image::Rgba([255; 4])).write_to(&mut std::io::Cursor::new(&mut opaque), image::ImageFormat::Png).unwrap();
|
||||
|
||||
let replacement = MeshFile { name: name.into(), bytes: textured_glb(&mesh, 0.0, &opaque), warnings: Vec::new() };
|
||||
session.reimport_mesh(Some(replacement), false).unwrap();
|
||||
|
||||
assert_eq!(session.bake_changes(0, BakedMap::Opacity), [BakeChange::LowPoly]);
|
||||
assert!(session.bake_changes(0, BakedMap::Position).is_empty());
|
||||
assert_eq!(session.out_of_date_maps(0).len(), 1);
|
||||
assert_eq!(session.auto_rebake_due().first().map(|entry| entry.1), Some(BakedMap::Opacity));
|
||||
|
||||
execute(&mut session, "bake.run", &json!({})).unwrap();
|
||||
let reopened = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap();
|
||||
|
||||
assert_ne!(reopened.baked(0).unwrap().maps[&BakedMap::Opacity], prior_opacity);
|
||||
assert!(reopened.auto_rebake_due().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opacity_samples_a_textured_gltf_high_poly() {
|
||||
let mut session = plane_session();
|
||||
@@ -526,13 +555,14 @@ fn opacity_samples_textures_next_to_a_high_poly() {
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
/// A plane session whose vertex normals lean, with a high poly plane `dy` above it.
|
||||
fn leaning_session(lean: bool) -> Session {
|
||||
/// Two parallel planes, with tilted low-poly vertex normals when `lean` is true.
|
||||
pub(super) fn leaning_session(lean: bool) -> Session {
|
||||
let mut mesh = primitives::builtin("plane").unwrap();
|
||||
if lean {
|
||||
mesh.normals = vec![texturecraft_engine::geom::glam::Vec3::new(0.6, 0.8, 0.0); mesh.positions.len()];
|
||||
mesh.compute_tangents();
|
||||
}
|
||||
|
||||
let high_text = obj(&mesh, 0.1, f32::MAX, [1.0; 3]);
|
||||
let mut s = Session::new_project("t", mesh, "builtin:plane", None, 256).unwrap();
|
||||
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
//! The Baking Log's record of the latest bake, map by map
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use serde_json::json;
|
||||
use texturecraft_engine::bake::{BakeHighState, BakeLog, BakeMapState, NamePair};
|
||||
use texturecraft_engine::compose::BakedMaps;
|
||||
use texturecraft_engine::core::{BakedMap, MeshMatchMode};
|
||||
use texturecraft_engine::geom::primitives;
|
||||
use texturecraft_engine::{Session, execute, sample_session};
|
||||
|
||||
#[test]
|
||||
fn bake_run_lists_every_checked_map_of_the_set_as_baked() {
|
||||
let mesh = primitives::builtin("plane").unwrap();
|
||||
let mut session = Session::new_project("t", mesh, "builtin:plane", None, 256).unwrap();
|
||||
|
||||
execute(&mut session, "bake.run", &json!({ "resolution": 64, "maps": ["opacity", "position"], "dilation": 0 })).unwrap();
|
||||
|
||||
let set_name = &session.doc.project.texture_sets[0].name;
|
||||
let rows = &session.bake_log.maps;
|
||||
let maps: BTreeSet<BakedMap> = rows.iter().map(|row| row.map).collect();
|
||||
|
||||
assert_eq!(maps, BTreeSet::from([BakedMap::Position, BakedMap::Opacity]));
|
||||
assert!(rows.iter().all(|row| row.state == BakeMapState::Baked && &row.set_name == set_name), "{rows:?}");
|
||||
assert!(!session.bake_log.is_running());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_canceled_bake_keeps_the_finished_sets_and_cancels_the_rest() {
|
||||
let mut session = sample_session(256, 64).unwrap();
|
||||
for set in &mut session.doc.project.texture_sets {
|
||||
set.bake.maps.select([BakedMap::Normal, BakedMap::Curvature]);
|
||||
}
|
||||
let log = &mut session.bake_log;
|
||||
log.begin(&session.doc.project, &session.doc.bake_meshes.high, &[0, 1]);
|
||||
|
||||
log.set_started(0);
|
||||
log.map_baked(0, BakedMap::Normal);
|
||||
log.map_baked(0, BakedMap::Curvature);
|
||||
log.set_finished(0);
|
||||
log.set_started(1);
|
||||
log.map_baked(1, BakedMap::Normal);
|
||||
|
||||
let baking: Vec<_> = log.maps.iter().filter(|row| row.state == BakeMapState::Baking).map(|row| (row.texture_set, row.map)).collect();
|
||||
assert_eq!(baking, [(1, BakedMap::Curvature)], "the next map of the running set is the one in progress");
|
||||
|
||||
log.cancel(Some(1));
|
||||
|
||||
let state_of = |set: usize| log.maps.iter().filter(move |row| row.texture_set == set).map(|row| row.state.clone()).collect::<Vec<_>>();
|
||||
assert!(state_of(0).iter().all(|state| *state == BakeMapState::Baked), "{:?}", log.maps);
|
||||
assert!(state_of(1).iter().all(|state| *state == BakeMapState::Canceled), "maps of the set not kept are canceled: {:?}", log.maps);
|
||||
assert!(!log.is_running());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bake_log_reports_each_map_with_its_state_and_a_failures_reason() {
|
||||
let mesh = primitives::builtin("plane").unwrap();
|
||||
let mut session = Session::new_project("t", mesh, "builtin:plane", None, 256).unwrap();
|
||||
execute(&mut session, "bake.run", &json!({ "resolution": 64, "maps": ["opacity", "position"], "dilation": 0 })).unwrap();
|
||||
|
||||
let log = execute(&mut session, "bake.log", &json!({})).unwrap();
|
||||
|
||||
assert_eq!(log["running"], false);
|
||||
let maps: BTreeSet<&str> = log["maps"].as_array().unwrap().iter().map(|row| row["map"].as_str().unwrap()).collect();
|
||||
assert_eq!(maps, BTreeSet::from(["opacity", "position"]));
|
||||
assert!(log["maps"].as_array().unwrap().iter().all(|row| row["state"] == "baked" && row["textureSet"] == 0 && row.get("reason").is_none()), "{log}");
|
||||
|
||||
session.bake_log.set_failed(0, "The high poly file could not be read.");
|
||||
let log = execute(&mut session, "bake.log", &json!({})).unwrap();
|
||||
|
||||
assert!(log["maps"].as_array().unwrap().iter().all(|row| row["state"] == "failed" && row["reason"] == "The high poly file could not be read."), "{log}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bake_lists_the_high_polys_each_set_loads_and_skips_a_set_baking_from_its_low_poly() {
|
||||
let mut session = sample_session(256, 64).unwrap();
|
||||
session.add_high_poly_bytes("ball_high.obj", b"o Ball_high\nv 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap();
|
||||
session.doc.project.texture_sets[1].bake.high_poly.use_low_as_high = true;
|
||||
|
||||
execute(&mut session, "bake.run", &json!({ "ts": [0, 1], "resolution": 64, "maps": ["opacity"], "dilation": 0 })).unwrap();
|
||||
|
||||
let highs: Vec<_> = session.bake_log.highs.iter().map(|row| (row.texture_set, row.file.as_str(), row.state.clone())).collect();
|
||||
assert_eq!(highs, [(0, "ball_high.obj", BakeHighState::Loaded)]);
|
||||
let log = execute(&mut session, "bake.log", &json!({})).unwrap();
|
||||
assert_eq!(log["highPolys"][0]["state"], "loaded", "{log}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_set_that_fails_before_its_high_polys_are_ready_marks_them_failed_and_a_cancel_the_rest_canceled() {
|
||||
let mut session = sample_session(256, 64).unwrap();
|
||||
session.add_high_poly_bytes("ball_high.obj", b"o Ball_high\nv 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap();
|
||||
let log = &mut session.bake_log;
|
||||
log.begin(&session.doc.project, &session.doc.bake_meshes.high, &[0, 1]);
|
||||
let state = |log: &BakeLog, set: usize| log.highs.iter().find(|high| high.texture_set == set).map(|high| high.state.clone());
|
||||
|
||||
log.set_started(0);
|
||||
|
||||
assert_eq!(state(log, 0), Some(BakeHighState::Loading));
|
||||
assert!(log.is_loading_high_polys());
|
||||
|
||||
log.set_failed(0, "The cage file could not be read.");
|
||||
log.set_started(1);
|
||||
log.cancel(Some(1));
|
||||
|
||||
assert_eq!(state(log, 0), Some(BakeHighState::Failed("The cage file could not be read.".into())));
|
||||
assert_eq!(state(log, 1), Some(BakeHighState::Canceled));
|
||||
assert!(!log.is_loading_high_polys());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bake_matching_by_name_lists_its_pairs_and_only_the_high_parts_no_set_pairs_with() {
|
||||
let obj = "o Box_low\nusemtl Body\nv 0 0 0\nv 1 0 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n\
|
||||
o Lid_low\nusemtl Lid\nv 2 0 0\nv 3 0 0\nv 2 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 4/4 5/5 6/6\n";
|
||||
let mut session = Session::from_mesh_bytes("sets.obj", obj.as_bytes(), 128, "sets").unwrap();
|
||||
session
|
||||
.add_high_poly_bytes("high.obj", b"o Box_high\nv 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\no Extra_high\nv 2 0 0\nv 3 0 0\nv 2 1 0\nf 4 5 6\n".to_vec())
|
||||
.unwrap();
|
||||
session.begin_bake_log(&[0, 1]);
|
||||
|
||||
assert_eq!(session.bake_log.matching, None, "matching \"Always\" lists no pairs");
|
||||
|
||||
for set in &mut session.doc.project.texture_sets {
|
||||
set.bake.high_poly.match_mode = MeshMatchMode::ByMeshName;
|
||||
}
|
||||
session.begin_bake_log(&[0, 1]);
|
||||
|
||||
let pair = |low: Option<&str>, high: Option<&str>| NamePair { low: low.map(Into::into), high: high.map(Into::into) };
|
||||
let matching = session.bake_log.matching.clone().unwrap();
|
||||
assert_eq!(
|
||||
matching.pairs,
|
||||
[pair(Some("Box_low"), Some("Box_high")), pair(Some("Lid_low"), None), pair(None, Some("Extra_high"))],
|
||||
"Box_high is paired by the other set"
|
||||
);
|
||||
assert_eq!(matching.issue_count(), 2);
|
||||
let log = execute(&mut session, "bake.log", &json!({})).unwrap();
|
||||
assert_eq!(log["matching"]["pairs"][1], json!({ "low": "Lid_low", "high": null }), "{log}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_high_part_counts_as_unused_only_when_no_set_of_the_bake_matches_always() {
|
||||
let obj = "o Box_low\nusemtl Body\nv 0 0 0\nv 1 0 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n\
|
||||
o Lid_low\nusemtl Lid\nv 2 0 0\nv 3 0 0\nv 2 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 4/4 5/5 6/6\n";
|
||||
let mut session = Session::from_mesh_bytes("sets.obj", obj.as_bytes(), 128, "sets").unwrap();
|
||||
session
|
||||
.add_high_poly_bytes("high.obj", b"o Box_high\nv 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\no Extra_high\nv 2 0 0\nv 3 0 0\nv 2 1 0\nf 4 5 6\n".to_vec())
|
||||
.unwrap();
|
||||
session.doc.project.texture_sets[0].bake.high_poly.match_mode = MeshMatchMode::ByMeshName;
|
||||
|
||||
session.begin_bake_log(&[0, 1]);
|
||||
|
||||
let matching = session.bake_log.matching.clone().unwrap();
|
||||
assert!(matching.pairs.iter().all(|pair| pair.low.is_some()), "the set matching \"Always\" bakes from Extra_high: {:?}", matching.pairs);
|
||||
assert_eq!(matching.issue_count(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_canceled_bake_at_a_new_output_size_keeps_none_of_its_maps_so_the_sets_others_stay() {
|
||||
let mut session = sample_session(256, 64).unwrap();
|
||||
let before = session.baked(0).cloned().unwrap();
|
||||
let resolution = before.resolution * 2;
|
||||
let data = std::sync::Arc::new(vec![0.5; (resolution * resolution) as usize * BakedMap::Normal.components()]);
|
||||
let finished = BakedMaps { resolution, maps: [(BakedMap::Normal, data)].into() };
|
||||
|
||||
let kept = session.keep_canceled_bake(0, finished, &Default::default(), 0).unwrap();
|
||||
|
||||
assert!(kept.is_empty(), "{kept:?}");
|
||||
assert_eq!(session.baked(0).map(|baked| baked.maps.keys().copied().collect::<Vec<_>>()), Some(before.maps.keys().copied().collect()));
|
||||
assert_eq!(session.baked(0).map(|baked| baked.resolution), Some(before.resolution));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_canceled_bake_keeps_the_out_of_date_mark_of_a_map_it_did_not_finish() {
|
||||
let mut session = sample_session(256, 64).unwrap();
|
||||
execute(&mut session, "bake.run", &json!({ "resolution": 64, "maps": ["id", "position"], "dilation": 0 })).unwrap();
|
||||
execute(&mut session, "bake.settings", &json!({ "positionMode": "boundingBox" })).unwrap();
|
||||
let task = session.bake_task_for(0, &[BakedMap::Id, BakedMap::Position]).unwrap();
|
||||
let stored = session.baked(0).cloned().unwrap();
|
||||
let finished = BakedMaps { resolution: stored.resolution, maps: [(BakedMap::Id, stored.maps[&BakedMap::Id].clone())].into() };
|
||||
|
||||
let kept = session.keep_canceled_bake(0, finished, &task.sources, task.painted_stroke).unwrap();
|
||||
|
||||
assert_eq!(kept, [BakedMap::Id]);
|
||||
assert!(!session.bake_changes(0, BakedMap::Position).is_empty(), "Position still has its old pixels, so it stays out of date");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_canceled_bakes_log_line_names_the_set_as_the_texture_set_list_does() {
|
||||
let mut session = sample_session(256, 64).unwrap();
|
||||
let stored = session.baked(0).cloned().unwrap();
|
||||
let (map, data) = stored.maps.iter().next().map(|(map, data)| (*map, data.clone())).unwrap();
|
||||
let finished = BakedMaps { resolution: stored.resolution, maps: [(map, data)].into() };
|
||||
|
||||
session.keep_canceled_bake(0, finished, &Default::default(), 0).unwrap();
|
||||
|
||||
let name = session.doc.project.texture_sets[0].name.clone();
|
||||
let line = session.log.iter().find(|line| line.contains("canceled bake")).map(|line| line.message.clone()).unwrap();
|
||||
assert!(line.contains(&format!("texture set {name} ")), "the first set is not numbered 0: {line}");
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
//! Out-of-date mesh maps: what each map was baked from, compared with what a bake would read now
|
||||
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
use serde_json::json;
|
||||
use texturecraft_engine::bake::Progress;
|
||||
use texturecraft_engine::core::{BakeChange, BakedMap, CageType, IdColorSource, MeshMatchMode};
|
||||
use texturecraft_engine::formats::MeshFile;
|
||||
use texturecraft_engine::geom::primitives;
|
||||
use texturecraft_engine::{Session, execute};
|
||||
|
||||
/// A plane with its position map baked by `bake.run`
|
||||
fn baked_plane() -> Session {
|
||||
let mesh = primitives::builtin("plane").unwrap();
|
||||
let mut session = Session::new_project("t", mesh, "builtin:plane", None, 128).unwrap();
|
||||
execute(&mut session, "bake.run", &json!({ "resolution": 64, "maps": ["position"], "dilation": 0 })).unwrap();
|
||||
session
|
||||
}
|
||||
|
||||
fn changes(session: &Session) -> Vec<BakeChange> {
|
||||
session.bake_changes(0, BakedMap::Position)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_map_goes_out_of_date_when_its_settings_or_the_shared_ones_change_and_a_bake_brings_it_back() {
|
||||
let mut session = baked_plane();
|
||||
assert!(changes(&session).is_empty(), "fresh bake: {:?}", changes(&session));
|
||||
|
||||
execute(&mut session, "bake.settings", &json!({ "positionMode": "boundingBox" })).unwrap();
|
||||
assert_eq!(changes(&session), [BakeChange::MapSettings]);
|
||||
execute(&mut session, "bake.settings", &json!({ "dilation": 4 })).unwrap();
|
||||
assert_eq!(changes(&session), [BakeChange::Settings, BakeChange::MapSettings]);
|
||||
let inspect = execute(&mut session, "project.inspect", &json!({})).unwrap();
|
||||
assert_eq!(inspect["textureSets"][0]["outOfDate"], json!({ "position": ["settings", "mapSettings"] }));
|
||||
|
||||
execute(&mut session, "bake.run", &json!({})).unwrap();
|
||||
assert!(changes(&session).is_empty(), "rebaked: {:?}", changes(&session));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_record_is_saved_with_the_project() {
|
||||
let mut session = baked_plane();
|
||||
execute(&mut session, "bake.settings", &json!({ "positionMode": "boundingBox" })).unwrap();
|
||||
|
||||
let reopened = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap();
|
||||
|
||||
assert_eq!(changes(&reopened), [BakeChange::MapSettings]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maps_saved_before_records_existed_and_imported_maps_never_go_out_of_date() {
|
||||
let mut old = baked_plane();
|
||||
old.doc.project.texture_sets[0].bake_sources.clear();
|
||||
let mut old = Session::from_project_bytes(&old.to_project_bytes().unwrap()).unwrap();
|
||||
execute(&mut old, "bake.settings", &json!({ "positionMode": "boundingBox" })).unwrap();
|
||||
assert!(changes(&old).is_empty(), "{:?}", changes(&old));
|
||||
|
||||
let mut imported = baked_plane();
|
||||
let mut png = Vec::new();
|
||||
image::RgbImage::from_pixel(4, 4, image::Rgb([128, 64, 32])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
|
||||
imported.import_resource_bytes("position.png", png).unwrap();
|
||||
execute(&mut imported, "textureSet.meshMap.set", &json!({ "map": "position", "image": "position.png" })).unwrap();
|
||||
execute(&mut imported, "bake.settings", &json!({ "positionMode": "boundingBox" })).unwrap();
|
||||
assert!(changes(&imported).is_empty(), "{:?}", changes(&imported));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adding_a_high_poly_puts_the_maps_out_of_date() {
|
||||
let mut session = baked_plane();
|
||||
|
||||
session.add_high_poly_bytes("detail_high.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap();
|
||||
|
||||
assert_eq!(changes(&session), [BakeChange::HighPoly]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replacing_low_poly_vertex_colors_marks_the_id_map_out_of_date() {
|
||||
let triangle = |color: &str| format!("o Painted\nv 0 0 0 {color}\nv 1 0 0 {color}\nv 0 1 0 {color}\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n");
|
||||
let name = "painted.obj";
|
||||
let mut session = Session::from_mesh_bytes_with_uvs(name, triangle("1 0 0").as_bytes(), 128, "painted", None, false).unwrap();
|
||||
session.doc.project.texture_sets[0].bake.maps.id.parameters.source = IdColorSource::VertexColor;
|
||||
execute(&mut session, "bake.run", &json!({ "resolution": 32, "maps": ["id"], "dilation": 0 })).unwrap();
|
||||
let previous = session.baked(0).unwrap().maps[&BakedMap::Id].clone();
|
||||
|
||||
let replacement = MeshFile { name: name.into(), bytes: triangle("0 1 0").into_bytes(), warnings: Vec::new() };
|
||||
session.reimport_mesh(Some(replacement), false).unwrap();
|
||||
|
||||
assert_eq!(session.bake_changes(0, BakedMap::Id), [BakeChange::LowPoly]);
|
||||
execute(&mut session, "bake.run", &json!({})).unwrap();
|
||||
assert_ne!(session.baked(0).unwrap().maps[&BakedMap::Id], previous);
|
||||
assert!(session.bake_changes(0, BakedMap::Id).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reimporting_a_quad_as_triangles_invalidates_its_tangent_frame() {
|
||||
let corners = "v 0 0 0\nv 1 0 0\nv 1 1 0.6\nv 0 1 0\nvt 0 0.1\nvt 1 0\nvt 0.9 1\nvt 0.3 0.8\nvn 0 0 1\n";
|
||||
let quad = format!("{corners}f 1/1/1 2/2/1 3/3/1 4/4/1\n");
|
||||
let triangles = format!("{corners}f 1/1/1 2/2/1 3/3/1\nf 1/1/1 3/3/1 4/4/1\n");
|
||||
let mut session = Session::from_mesh_bytes("surface.obj", quad.as_bytes(), 128, "surface").unwrap();
|
||||
execute(&mut session, "bake.run", &json!({ "resolution": 32, "maps": ["normal"], "dilation": 0 })).unwrap();
|
||||
let previous = session.mesh.clone();
|
||||
|
||||
let replacement = MeshFile { name: "surface.obj".into(), bytes: triangles.into_bytes(), warnings: Vec::new() };
|
||||
session.reimport_mesh(Some(replacement), false).unwrap();
|
||||
|
||||
assert_eq!(session.mesh.indices, previous.indices);
|
||||
assert_ne!(session.mesh.tangents, previous.tangents);
|
||||
assert_eq!(session.bake_changes(0, BakedMap::Normal), [BakeChange::LowPoly]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renaming_a_low_poly_part_invalidates_its_by_name_bake() {
|
||||
let triangle = |part: &str, height: f32| format!("o {part}\nv 0 0 {height}\nv 1 0 {height}\nv 0 1 {height}\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n");
|
||||
let name = "parts.obj";
|
||||
let mut session = Session::from_mesh_bytes_with_uvs(name, triangle("Body_low", 0.0).as_bytes(), 128, "parts", None, false).unwrap();
|
||||
session.add_high_poly_bytes("detail.obj", triangle("Body_high", 0.05).into_bytes()).unwrap();
|
||||
session.doc.project.texture_sets[0].bake.high_poly.match_mode = MeshMatchMode::ByMeshName;
|
||||
execute(&mut session, "bake.run", &json!({ "resolution": 32, "maps": ["position"], "dilation": 0 })).unwrap();
|
||||
assert!(session.bake_name_pairs(0).unwrap().unwrap().iter().any(|pair| !pair.unpaired()));
|
||||
|
||||
let replacement = MeshFile { name: name.into(), bytes: triangle("Trim_low", 0.0).into_bytes(), warnings: Vec::new() };
|
||||
session.reimport_mesh(Some(replacement), false).unwrap();
|
||||
|
||||
assert!(session.bake_name_pairs(0).unwrap().unwrap().iter().all(|pair| pair.unpaired()));
|
||||
assert_eq!(changes(&session), [BakeChange::LowPoly]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cage_file_counts_only_for_sets_that_bake_with_it() {
|
||||
let mut session = baked_plane();
|
||||
session.add_high_poly_bytes("detail_high.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap();
|
||||
execute(&mut session, "bake.run", &json!({})).unwrap();
|
||||
|
||||
let cage: String = (0..session.mesh.triangle_count()).map(|_| "v 0 0 0\nv 1 0 0\nv 0 1 0\nf -3 -2 -1\n").collect();
|
||||
session.set_cage_bytes("cage.obj", cage.into_bytes()).unwrap();
|
||||
assert!(changes(&session).is_empty(), "the cage type is not Custom File: {:?}", changes(&session));
|
||||
|
||||
session.doc.project.texture_sets[0].bake.cage.kind = CageType::CustomFile;
|
||||
assert!(changes(&session).contains(&BakeChange::Cage), "{:?}", changes(&session));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_setting_changed_while_the_bake_runs_leaves_the_new_map_out_of_date() {
|
||||
let mut session = baked_plane();
|
||||
let task = session.bake_task(0).unwrap();
|
||||
execute(&mut session, "bake.settings", &json!({ "positionMode": "boundingBox" })).unwrap();
|
||||
|
||||
let streamed_once = AtomicBool::new(false);
|
||||
let output = task.run_streaming(&Progress::new(), &mut |_| streamed_once.store(true, Ordering::Relaxed)).unwrap();
|
||||
session.apply_streamed_bake(0, output).unwrap();
|
||||
|
||||
assert!(streamed_once.load(Ordering::Relaxed));
|
||||
assert_eq!(changes(&session), [BakeChange::MapSettings]);
|
||||
}
|
||||
|
||||
/// Two quads side by side, one texture set each, lifted by `lift` where a high poly or cage stands off the low poly
|
||||
fn two_parts(lift: f32) -> String {
|
||||
let mut obj = String::new();
|
||||
for left in [0.0, 2.0] {
|
||||
let right = left + 1.0;
|
||||
obj += &format!("v {left} 0 {lift}\nv {right} 0 {lift}\nv {right} 1 {lift}\nv {left} 1 {lift}\n");
|
||||
}
|
||||
obj += "vt 0 0\nvt 1 0\nvt 1 1\nvt 0 1\n";
|
||||
obj += "usemtl Left\nf 1/1 2/2 3/3\nf 1/1 3/3 4/4\nusemtl Right\nf 5/1 6/2 7/3\nf 5/1 7/3 8/4\n";
|
||||
obj
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reopened_project_keeps_every_sets_maps_up_to_date() {
|
||||
let mut session = Session::from_mesh_bytes_with_uvs("parts.obj", two_parts(0.0).as_bytes(), 128, "parts", None, false).unwrap();
|
||||
session.add_high_poly_bytes("parts_high.obj", two_parts(0.05).into_bytes()).unwrap();
|
||||
session.set_cage_bytes("parts_cage.obj", two_parts(0.2).into_bytes()).unwrap();
|
||||
for texture_set in &mut session.doc.project.texture_sets {
|
||||
texture_set.bake.cage.kind = CageType::CustomFile;
|
||||
}
|
||||
execute(&mut session, "bake.run", &json!({ "ts": "all", "resolution": 32, "maps": ["position", "normal"], "dilation": 0 })).unwrap();
|
||||
execute(&mut session, "bake.autoRebake", &json!({ "ts": 1, "map": "normal" })).unwrap();
|
||||
let records = |session: &Session| session.doc.project.texture_sets.iter().map(|set| set.bake_sources.clone()).collect::<Vec<_>>();
|
||||
assert_eq!(session.set_count(), 2);
|
||||
assert!(records(&session).iter().all(|sources| sources.len() == 2), "both maps of both sets are recorded");
|
||||
|
||||
let reopened = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap();
|
||||
|
||||
assert_eq!(records(&reopened), records(&session), "the records are saved as they were");
|
||||
for texture_set in 0..reopened.set_count() {
|
||||
assert!(reopened.out_of_date_maps(texture_set).is_empty(), "set {texture_set}: {:?}", reopened.out_of_date_maps(texture_set));
|
||||
}
|
||||
assert!(reopened.auto_rebake_due().is_empty(), "opening the project starts no rebake");
|
||||
}
|
||||
@@ -246,6 +246,42 @@ fn anchor_effects_added_through_instance_validate_against_source() {
|
||||
assert!(session.doc.project.layer(LayerId(source)).unwrap().mask.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_instance_selects_the_effects_of_the_mask_it_draws_with() {
|
||||
let mut s = session();
|
||||
let source = id(execute(&mut s, "layer.add.fill", &json!({"height": 0.5})).unwrap(), "layer");
|
||||
execute(&mut s, "mask.add.black", &Value::Null).unwrap();
|
||||
let source_mask = id(execute(&mut s, "effect.add.generator", &json!({"generator": "position", "level": 0.5})).unwrap(), "effect");
|
||||
let source_content = id(execute(&mut s, "effect.add.filter", &json!({"target": "content", "filter": "invert"})).unwrap(), "effect");
|
||||
let other = id(execute(&mut s, "layer.add.fill", &Value::Null).unwrap(), "layer");
|
||||
execute(&mut s, "mask.add.black", &Value::Null).unwrap();
|
||||
let other_mask = id(execute(&mut s, "effect.add.generator", &json!({"generator": "position", "level": 0.5})).unwrap(), "effect");
|
||||
let instance = id(execute(&mut s, "layer.instance", &json!({"layer": source})).unwrap(), "layer");
|
||||
let select = |s: &mut Session, effect: u64| execute(s, "layer.select", &json!({"layer": instance, "target": effect}));
|
||||
|
||||
// The instance inherits its source mask
|
||||
select(&mut s, source_mask).unwrap();
|
||||
|
||||
assert_eq!(s.selected_layer(), Some(LayerId(instance)));
|
||||
assert_eq!(s.target, StackTarget::Effect(LayerId(source_mask)));
|
||||
|
||||
// The source's content and unrelated layers remain outside the selection
|
||||
for effect in [source_content, other_mask] {
|
||||
let error = select(&mut s, effect).unwrap_err().to_string();
|
||||
assert!(error.contains("an effect id of this layer or of the mask it draws with"), "{error}");
|
||||
}
|
||||
assert_ne!(other, instance);
|
||||
|
||||
// A local mask overrides the source mask
|
||||
execute(&mut s, "layer.select", &json!({"layer": instance})).unwrap();
|
||||
execute(&mut s, "mask.add.black", &Value::Null).unwrap();
|
||||
let own = id(execute(&mut s, "effect.add.generator", &json!({"generator": "position", "level": 0.5})).unwrap(), "effect");
|
||||
|
||||
assert!(select(&mut s, source_mask).is_err());
|
||||
select(&mut s, own).unwrap();
|
||||
assert_eq!(s.target, StackTarget::Effect(LayerId(own)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mask_anchor_points_feed_layers_above_and_folders_take_them() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -167,3 +167,26 @@ fn inspect_reports_the_reference_controls_set() {
|
||||
assert!(inspected.contains(&format!("\"{key}\"")) && inspected.contains(value), "{key} with {value} in {inspected}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inspect_reports_direction_only_on_the_earlier_model() {
|
||||
let mut session = session();
|
||||
let earlier_dir = add(&mut session, json!({"generator": "direction", "direction": [1.0, 0.0, 0.0]}));
|
||||
let light_dir = add(&mut session, json!({"generator": "direction", "lightHorizontal": 90.0}));
|
||||
let earlier_pos = add(&mut session, json!({"generator": "position", "direction": [0.0, 0.0, 1.0]}));
|
||||
let section_pos = add(&mut session, json!({"generator": "position", "sectionContrast": 0.25}));
|
||||
|
||||
let inspected = execute(&mut session, "project.inspect", &Value::Null).unwrap();
|
||||
let effects = inspected["layers"][0]["mask"]["effects"].as_array().unwrap();
|
||||
let gen_of = |effect_id: u64| &effects.iter().find(|entry| entry["id"] == effect_id).unwrap()["generator"];
|
||||
|
||||
assert_eq!(gen_of(earlier_dir)["direction"], json!([1.0, 0.0, 0.0]));
|
||||
assert!(gen_of(earlier_dir).get("light").is_none());
|
||||
assert!(gen_of(light_dir).get("direction").is_none());
|
||||
assert!(gen_of(light_dir).get("light").is_some());
|
||||
|
||||
assert_eq!(gen_of(earlier_pos)["direction"], json!([0.0, 0.0, 1.0]));
|
||||
assert!(gen_of(earlier_pos).get("section").is_none());
|
||||
assert!(gen_of(section_pos).get("direction").is_none());
|
||||
assert!(gen_of(section_pos).get("section").is_some());
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
//! The "Use IOR for specular reflection" shader setting persists with projects and templates
|
||||
//! and stays off for projects and templates without it (texturecraft #749).
|
||||
|
||||
use std::io::{Cursor, Write};
|
||||
|
||||
use serde_json::json;
|
||||
use texturecraft_engine::{Session, execute, geom::primitives};
|
||||
use zip::{ZipWriter, write::SimpleFileOptions};
|
||||
|
||||
const IOR: f32 = 1.8;
|
||||
|
||||
fn session() -> Session {
|
||||
Session::new_project("Ior", primitives::sphere(1.0, 16, 8), "builtin:sphere", None, 128).unwrap()
|
||||
}
|
||||
|
||||
fn opt_in(session: &mut Session) {
|
||||
execute(session, "display.set", &json!({"iorSpecular": true, "ior": IOR})).unwrap();
|
||||
}
|
||||
|
||||
fn new_project_uses_ior_specular(session: &mut Session, template: &str) -> bool {
|
||||
execute(session, "project.new", &json!({"template": template})).unwrap();
|
||||
session.doc.project.display.ior_specular
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_opt_in_survives_save_and_reopen() {
|
||||
let mut session = session();
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let path = directory.path().join("ior.tcraft");
|
||||
opt_in(&mut session);
|
||||
|
||||
execute(&mut session, "file.saveAs", &json!({"path": path})).unwrap();
|
||||
execute(&mut session, "project.new", &json!({})).unwrap();
|
||||
let new_project_uses_it = session.doc.project.display.ior_specular;
|
||||
execute(&mut session, "file.open", &json!({"path": path})).unwrap();
|
||||
|
||||
assert!(!new_project_uses_it, "a new project starts with the setting off");
|
||||
let display = &session.doc.project.display;
|
||||
assert!(display.ior_specular);
|
||||
assert_eq!(display.ior, IOR);
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn an_older_save_cannot_clear_ior_specular_changes() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let path = directory.path().join("ior.tcraft");
|
||||
|
||||
for params in [json!({"iorSpecular": false}), json!({"ior": 2.0}), json!({"specGloss": true})] {
|
||||
let mut session = session();
|
||||
opt_in(&mut session);
|
||||
let save = session.save_task(path.to_str().unwrap(), true);
|
||||
|
||||
execute(&mut session, "display.set", ¶ms).unwrap();
|
||||
save.run(None).unwrap().apply(&mut session);
|
||||
|
||||
assert!(session.modified, "the archive predates the edit {params}");
|
||||
let archived = texturecraft_engine::file_cmds::open_path(path.to_str().unwrap()).unwrap();
|
||||
assert_ne!(archived.doc.project.display, session.doc.project.display);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_project_saved_before_the_setting_opens_with_it_off() {
|
||||
let mut session = session();
|
||||
opt_in(&mut session);
|
||||
let mut project = serde_json::to_value(&session.doc.project).unwrap();
|
||||
let removed = project["display"].as_object_mut().unwrap().remove("ior_specular");
|
||||
let mut archive = ZipWriter::new(Cursor::new(Vec::new()));
|
||||
archive.start_file("project.json", SimpleFileOptions::default()).unwrap();
|
||||
archive.write_all(&serde_json::to_vec(&project).unwrap()).unwrap();
|
||||
let bytes = archive.finish().unwrap().into_inner();
|
||||
|
||||
let older = Session::from_project_bytes(&bytes).unwrap();
|
||||
|
||||
assert_eq!(removed, Some(json!(true)), "the stripped field is the saved setting");
|
||||
let display = &older.doc.project.display;
|
||||
assert!(!display.ior_specular);
|
||||
assert_eq!(display.ior, IOR, "the other shader settings still load");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_opt_in_survives_a_template_and_other_templates_leave_it_off() {
|
||||
let library = tempfile::tempdir().unwrap();
|
||||
let mut author = session();
|
||||
author.load_templates(library.path().to_path_buf());
|
||||
opt_in(&mut author);
|
||||
execute(&mut author, "project.template.save", &json!({"name": "Glass"})).unwrap();
|
||||
|
||||
// A template written before the setting existed
|
||||
let older = json!({"name": "Older", "resolution": 128, "ior": IOR});
|
||||
std::fs::write(library.path().join("Older.json"), serde_json::to_vec(&older).unwrap()).unwrap();
|
||||
|
||||
let mut user = session();
|
||||
let warnings = user.load_templates(library.path().to_path_buf());
|
||||
let listed = execute(&mut user, "project.templates", &json!({})).unwrap();
|
||||
|
||||
assert!(warnings.is_empty(), "{warnings:?}");
|
||||
assert!(new_project_uses_ior_specular(&mut user, "Glass"));
|
||||
assert_eq!(user.doc.project.display.ior, IOR);
|
||||
assert!(!new_project_uses_ior_specular(&mut user, "Older"));
|
||||
for template in listed.as_array().unwrap() {
|
||||
let name = template["name"].as_str().unwrap();
|
||||
assert_eq!(template["iorSpecular"], json!(name == "Glass"), "{name}");
|
||||
assert_eq!(new_project_uses_ior_specular(&mut user, name), name == "Glass", "{name}");
|
||||
}
|
||||
}
|
||||
@@ -2,8 +2,11 @@
|
||||
//! Keep feature tests in their own modules; the standalone session.rs target remains available.
|
||||
|
||||
mod add_mask_items;
|
||||
mod auto_rebake;
|
||||
mod bake;
|
||||
mod bake_checks;
|
||||
mod bake_log;
|
||||
mod bake_out_of_date;
|
||||
mod bake_resolution;
|
||||
mod bake_settings;
|
||||
mod bake_tiles;
|
||||
@@ -46,6 +49,7 @@ mod generator_wear;
|
||||
mod gradient_map;
|
||||
mod high_poly_missed;
|
||||
mod instances;
|
||||
mod ior_specular;
|
||||
mod layer_multi_select;
|
||||
mod mask_clone_smudge;
|
||||
mod mask_export;
|
||||
@@ -63,6 +67,7 @@ mod perf;
|
||||
mod polygon_fill;
|
||||
mod project_recovery;
|
||||
mod rebuilt_uv_layout;
|
||||
mod resource_updater;
|
||||
mod resources_used;
|
||||
mod sample;
|
||||
mod solo;
|
||||
|
||||
@@ -56,6 +56,31 @@ fn a_rebuilt_project_reopens_with_its_saved_uv_layout_not_a_new_unwrap() {
|
||||
assert_eq!(corner_uvs(&resaved.source_mesh()), locked, "saving again keeps the layout");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pending_save_keeps_the_rebuilt_layout_and_releases_unused_bake_geometry() {
|
||||
let mut session = Session::from_project_bytes(&locked_archive()).unwrap();
|
||||
session.add_high_poly_bytes("high.obj", QUAD_OBJ.as_bytes().to_vec()).unwrap();
|
||||
let expected_layout = corner_uvs(&session.source_mesh());
|
||||
let high = &session.doc.bake_meshes.high[0];
|
||||
let encoded = std::sync::Arc::downgrade(&high.bytes);
|
||||
let parsed = std::sync::Arc::downgrade(&high.mesh);
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let path = directory.path().join("saved.tcraft");
|
||||
|
||||
let save = session.save_task(path.to_str().unwrap(), true);
|
||||
drop(session);
|
||||
assert!(parsed.upgrade().is_none(), "only the source UV layout needs parsed geometry");
|
||||
assert!(encoded.upgrade().is_some(), "the pending archive shares the original file bytes");
|
||||
|
||||
save.run(None).unwrap();
|
||||
let reopened = texturecraft_engine::file_cmds::open_path(path.to_str().unwrap()).unwrap();
|
||||
|
||||
assert!(encoded.upgrade().is_none(), "the worker released the original bytes");
|
||||
assert_eq!(reopened.doc.bake_meshes.high[0].bytes.as_slice(), QUAD_OBJ.as_bytes());
|
||||
assert!(reopened.doc.project.mesh_rebuild_uvs);
|
||||
assert_eq!(corner_uvs(&reopened.source_mesh()), expected_layout);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opening_a_builtin_project_refuses_rebuilt_mesh_uvs() {
|
||||
let mut file = texturecraft_engine::formats::load_project_bytes(&locked_archive()).unwrap();
|
||||
|
||||
@@ -0,0 +1,547 @@
|
||||
//! The Resources Updater: image resources remember their files, a changed file shows as outdated,
|
||||
//! Update reads it again (one undo step, recompositing its layers) and Relink follows another file
|
||||
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, SystemTime};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_engine::core::{BakedMap, Channel};
|
||||
use texturecraft_engine::geom::primitives;
|
||||
use texturecraft_engine::{ResourceStatus, Session, execute};
|
||||
|
||||
const RESOLUTION: u32 = 128;
|
||||
const SAMPLE_STRIDE: usize = 8;
|
||||
const RED: [u8; 4] = [255, 0, 0, 255];
|
||||
const GREEN: [u8; 4] = [0, 255, 0, 255];
|
||||
|
||||
fn session() -> Session {
|
||||
Session::new_project("t", primitives::sphere(1.0, 16, 8), "builtin:sphere", None, RESOLUTION).unwrap()
|
||||
}
|
||||
|
||||
/// Write a `size` × `size` PNG of one colour (sizes differ between versions, so the file size changes too)
|
||||
fn write_png(path: &Path, size: u32, color: [u8; 4]) {
|
||||
image::RgbaImage::from_pixel(size, size, image::Rgba(color)).save(path).unwrap();
|
||||
}
|
||||
|
||||
fn text(path: &Path) -> &str {
|
||||
path.to_str().unwrap()
|
||||
}
|
||||
|
||||
/// Give the file at `path` the modification time `time` without changing its contents
|
||||
fn set_modified(path: &Path, time: SystemTime) {
|
||||
std::fs::File::options().write(true).open(path).unwrap().set_modified(time).unwrap();
|
||||
}
|
||||
|
||||
fn modified(path: &Path) -> SystemTime {
|
||||
std::fs::metadata(path).unwrap().modified().unwrap()
|
||||
}
|
||||
|
||||
fn import(s: &mut Session, path: &Path) -> String {
|
||||
execute(s, "resource.import", &json!({"path": text(path)})).unwrap()["name"].as_str().unwrap().to_string()
|
||||
}
|
||||
|
||||
/// Import `path` and show it as a base colour fill; returns the resource name
|
||||
fn import_as_fill(s: &mut Session, path: &Path) -> String {
|
||||
let name = import(s, path);
|
||||
execute(s, "layer.add.image", &json!({"name": name})).unwrap();
|
||||
s.update();
|
||||
name
|
||||
}
|
||||
|
||||
fn base_colors(s: &Session) -> Vec<[f32; 3]> {
|
||||
let composite = &s.caches[s.ts()].composite;
|
||||
let samples = || (0..RESOLUTION).step_by(SAMPLE_STRIDE);
|
||||
samples().flat_map(|y| samples().map(move |x| (x, y))).map(|(x, y)| composite.value(Channel::BaseColor, x, y)).collect()
|
||||
}
|
||||
|
||||
fn status_of(s: &mut Session, name: &str) -> ResourceStatus {
|
||||
s.resource_states().into_iter().find(|state| state.name == name).expect("the resource is listed").status
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_changed_file_is_outdated_and_update_replaces_its_pixels_as_one_undo_step() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let file = dir.path().join("bricks.png");
|
||||
write_png(&file, 4, RED);
|
||||
let mut s = session();
|
||||
let name = import_as_fill(&mut s, &file);
|
||||
let before = base_colors(&s);
|
||||
assert_eq!(status_of(&mut s, &name), ResourceStatus::UpToDate);
|
||||
|
||||
write_png(&file, 8, GREEN);
|
||||
let status = execute(&mut s, "resource.status", &Value::Null).unwrap();
|
||||
|
||||
assert_eq!(status["outdated"], json!(1));
|
||||
assert_eq!(status["resources"][0]["name"], json!(name));
|
||||
assert_eq!(status["resources"][0]["status"], json!("outdated"));
|
||||
|
||||
let steps = s.history_labels().len();
|
||||
let updated = execute(&mut s, "resource.update", &json!({})).unwrap();
|
||||
s.update();
|
||||
let after = base_colors(&s);
|
||||
|
||||
assert_eq!(updated["updated"], json!([name]));
|
||||
assert_eq!(s.history_labels().len(), steps + 1, "one undo step");
|
||||
assert_eq!(status_of(&mut s, &name), ResourceStatus::UpToDate);
|
||||
assert_eq!(s.images[&name].width, 8, "the new pixels are decoded");
|
||||
assert_ne!(after, before, "the fill using the resource recomposited");
|
||||
|
||||
execute(&mut s, "edit.undo", &Value::Null).unwrap();
|
||||
s.update();
|
||||
|
||||
assert_eq!(s.images[&name].width, 4, "undo brings back the old pixels under the same name");
|
||||
assert_eq!(base_colors(&s), before);
|
||||
assert_eq!(status_of(&mut s, &name), ResourceStatus::Outdated, "the file on disk is still the new one");
|
||||
|
||||
execute(&mut s, "edit.redo", &Value::Null).unwrap();
|
||||
s.update();
|
||||
|
||||
assert_eq!(s.images[&name].width, 8);
|
||||
assert_eq!(base_colors(&s), after);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outdated_resources_come_first_then_missing_up_to_date_unlinked_and_materials() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let [fine, gone, changed] = ["b_fine.png", "c_gone.png", "d_changed.png"].map(|name| dir.path().join(name));
|
||||
for file in [&fine, &gone, &changed] {
|
||||
write_png(file, 4, RED);
|
||||
}
|
||||
let mut s = session();
|
||||
let png = std::fs::read(&fine).unwrap();
|
||||
s.import_resource_bytes("a_unlinked.png", png).unwrap();
|
||||
for file in [&fine, &gone, &changed] {
|
||||
import(&mut s, file);
|
||||
}
|
||||
|
||||
// The environment map and the brush alpha are image resources like any other
|
||||
let environment = format!("{}b_fine.png", texturecraft_engine::core::project::ENV_RESOURCE_PREFIX);
|
||||
execute(&mut s, "display.set", &json!({"environment": environment})).unwrap();
|
||||
execute(&mut s, "tool.brush", &json!({"alpha": {"image": "d_changed.png"}})).unwrap();
|
||||
|
||||
// A linked MaterialCraft material keeps its package as a resource without a file
|
||||
s.doc.resources.insert("a_brick.mcmat".to_string(), Arc::new(b"package".to_vec()));
|
||||
let layer = execute(&mut s, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap();
|
||||
let link = serde_json::from_value(json!({"name": "Brick", "package": "a_brick.mcmat", "graph": "Brick", "params": [], "size": 4})).unwrap();
|
||||
if let texturecraft_engine::core::LayerKind::Fill(fill) = &mut s.doc.project.layers.get_mut(&texturecraft_engine::core::LayerId(layer)).unwrap().kind {
|
||||
fill.link = Some(link);
|
||||
}
|
||||
|
||||
std::fs::remove_file(&gone).unwrap();
|
||||
write_png(&changed, 8, GREEN);
|
||||
|
||||
let states = s.resource_states();
|
||||
let order: Vec<&str> = states.iter().map(|state| state.name.as_str()).collect();
|
||||
let statuses: Vec<&str> = states.iter().map(|state| state.status.id()).collect();
|
||||
|
||||
assert_eq!(order, ["d_changed.png", "c_gone.png", "b_fine.png", "a_unlinked.png", "a_brick.mcmat"], "by status first, against the name order");
|
||||
assert_eq!(statuses, ["outdated", "missing", "upToDate", "noSource", "material"], "the alpha's and the environment's files are checked too");
|
||||
let error = execute(&mut s, "resource.update", &json!({"names": ["a_brick.mcmat"]})).unwrap_err();
|
||||
assert!(error.to_string().contains("only image resources can be relinked"), "{error}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_same_size_file_is_compared_by_contents_once_per_time() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let file = dir.path().join("same.png");
|
||||
write_png(&file, 4, RED);
|
||||
let mut s = session();
|
||||
let name = import(&mut s, &file);
|
||||
let original = std::fs::read(&file).unwrap();
|
||||
let later = modified(&file) + Duration::from_secs(10);
|
||||
|
||||
// Saved again unchanged: a new time alone is no change, and updating adds no step
|
||||
set_modified(&file, later);
|
||||
let steps = s.history_labels().len();
|
||||
assert_eq!(status_of(&mut s, &name), ResourceStatus::UpToDate);
|
||||
assert_eq!(execute(&mut s, "resource.update", &json!({})).unwrap()["updated"], json!([]));
|
||||
assert_eq!(s.history_labels().len(), steps);
|
||||
|
||||
// Different bytes of the same size and time are not read again: the verdict for that size and time stands
|
||||
let mut edited = original.clone();
|
||||
let last = edited.len() - 1;
|
||||
edited[last] ^= 0xff;
|
||||
std::fs::write(&file, &edited).unwrap();
|
||||
set_modified(&file, later);
|
||||
assert_eq!(status_of(&mut s, &name), ResourceStatus::UpToDate, "the remembered verdict is used");
|
||||
|
||||
// Another time reads the file, and its bytes differ
|
||||
set_modified(&file, later + Duration::from_secs(10));
|
||||
assert_eq!(status_of(&mut s, &name), ResourceStatus::Outdated);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_file_without_a_usable_timestamp_is_compared_on_each_check() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("archived.png");
|
||||
write_png(&path, 4, RED);
|
||||
set_modified(&path, SystemTime::UNIX_EPOCH - Duration::from_secs(20));
|
||||
let mut session = session();
|
||||
let name = import(&mut session, &path);
|
||||
assert_eq!(status_of(&mut session, &name), ResourceStatus::UpToDate);
|
||||
|
||||
let mut changed = std::fs::read(&path).unwrap();
|
||||
changed[0] ^= 1;
|
||||
std::fs::write(&path, changed).unwrap();
|
||||
set_modified(&path, SystemTime::UNIX_EPOCH - Duration::from_secs(10));
|
||||
|
||||
assert_eq!(status_of(&mut session, &name), ResourceStatus::Outdated);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_file_is_reported_and_updating_it_changes_nothing() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let file = dir.path().join("gone.png");
|
||||
write_png(&file, 4, RED);
|
||||
let mut s = session();
|
||||
let name = import_as_fill(&mut s, &file);
|
||||
std::fs::remove_file(&file).unwrap();
|
||||
let steps = s.history_labels().len();
|
||||
|
||||
let state = s.resource_states().into_iter().find(|state| state.name == name).unwrap();
|
||||
let error = execute(&mut s, "resource.update", &json!({"names": [name]})).unwrap_err();
|
||||
|
||||
assert_eq!(state.status, ResourceStatus::Missing);
|
||||
assert!(state.error.is_some(), "the reason is shown");
|
||||
assert!(error.to_string().contains("nothing was updated"), "{error}");
|
||||
assert_eq!(s.history_labels().len(), steps);
|
||||
assert_eq!(s.images[&name].width, 4, "the resource keeps its pixels");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unreadable_file_fails_alone_while_the_others_update() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let (kept, gone) = (dir.path().join("kept.png"), dir.path().join("gone.png"));
|
||||
write_png(&kept, 4, RED);
|
||||
write_png(&gone, 4, RED);
|
||||
let mut s = session();
|
||||
let kept_name = import_as_fill(&mut s, &kept);
|
||||
let gone_name = import_as_fill(&mut s, &gone);
|
||||
write_png(&kept, 8, GREEN);
|
||||
std::fs::remove_file(&gone).unwrap();
|
||||
|
||||
let result = execute(&mut s, "resource.update", &json!({"names": [kept_name, gone_name]})).unwrap();
|
||||
|
||||
assert_eq!(result["updated"], json!([kept_name]));
|
||||
assert_eq!(result["failed"][0]["name"], json!(gone_name));
|
||||
assert_eq!(s.images[&kept_name].width, 8);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relink_reads_another_file_and_follows_it_from_then_on() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let (first, second) = (dir.path().join("first.png"), dir.path().join("second.png"));
|
||||
write_png(&first, 4, RED);
|
||||
write_png(&second, 8, GREEN);
|
||||
let mut s = session();
|
||||
let name = import_as_fill(&mut s, &first);
|
||||
let before = base_colors(&s);
|
||||
let steps = s.history_labels().len();
|
||||
|
||||
execute(&mut s, "resource.relink", &json!({"name": name, "path": text(&second)})).unwrap();
|
||||
s.update();
|
||||
|
||||
assert_eq!(s.history_labels().len(), steps + 1, "one undo step");
|
||||
assert_eq!(s.images[&name].width, 8, "the resource keeps its name and takes the new file's pixels");
|
||||
assert_ne!(base_colors(&s), before);
|
||||
assert!(s.doc.project.resource_sources[&name].path.ends_with("second.png"));
|
||||
|
||||
// The old file no longer matters, the new one does
|
||||
write_png(&first, 16, GREEN);
|
||||
assert_eq!(status_of(&mut s, &name), ResourceStatus::UpToDate);
|
||||
write_png(&second, 16, RED);
|
||||
assert_eq!(status_of(&mut s, &name), ResourceStatus::Outdated);
|
||||
|
||||
execute(&mut s, "edit.undo", &Value::Null).unwrap();
|
||||
assert!(s.doc.project.resource_sources[&name].path.ends_with("first.png"), "undo restores the link");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relink_refuses_resources_that_are_not_images() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let file = dir.path().join("picture.png");
|
||||
write_png(&file, 4, RED);
|
||||
let mut s = session();
|
||||
s.doc.resources.insert("material.mcmat".to_string(), Arc::new(vec![1, 2, 3]));
|
||||
let steps = s.history_labels().len();
|
||||
|
||||
let error = execute(&mut s, "resource.relink", &json!({"name": "material.mcmat", "path": text(&file)})).unwrap_err();
|
||||
|
||||
assert!(error.to_string().contains("no image resource"), "{error}");
|
||||
assert_eq!(*s.doc.resources["material.mcmat"], vec![1, 2, 3]);
|
||||
assert_eq!(s.history_labels().len(), steps);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resources_without_a_file_cannot_update_and_a_reopened_project_keeps_its_links() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let file = dir.path().join("kept.png");
|
||||
write_png(&file, 4, RED);
|
||||
let mut s = session();
|
||||
let linked = import_as_fill(&mut s, &file);
|
||||
let png = std::fs::read(&file).unwrap();
|
||||
let unlinked = s.import_resource_bytes("made.png", png).unwrap();
|
||||
|
||||
assert_eq!(status_of(&mut s, &unlinked), ResourceStatus::NoSource);
|
||||
assert!(execute(&mut s, "resource.update", &json!({"names": [unlinked]})).is_err());
|
||||
|
||||
let mut reopened = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap();
|
||||
write_png(&file, 8, GREEN);
|
||||
|
||||
assert_eq!(status_of(&mut reopened, &linked), ResourceStatus::Outdated);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_removed_resource_forgets_its_file() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let file = dir.path().join("old.png");
|
||||
write_png(&file, 4, RED);
|
||||
let mut s = session();
|
||||
let name = import(&mut s, &file);
|
||||
|
||||
execute(&mut s, "resource.remove", &json!({"name": name})).unwrap();
|
||||
let png = std::fs::read(&file).unwrap();
|
||||
let reused = s.import_resource_bytes("old.png", png).unwrap();
|
||||
|
||||
assert_eq!(reused, name, "the name is free again");
|
||||
assert_eq!(status_of(&mut s, &reused), ResourceStatus::NoSource, "a new resource under the old name does not inherit the file");
|
||||
}
|
||||
|
||||
/// The material ball: texture sets "Ball" and "Base"
|
||||
fn ball() -> Session {
|
||||
Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap()
|
||||
}
|
||||
|
||||
fn ambient_occlusion(s: &Session) -> Vec<f32> {
|
||||
s.doc.baked[&0].maps[&BakedMap::AmbientOcclusion].as_ref().clone()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_imported_mesh_map_follows_its_changed_file_until_something_else_replaces_it() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let file = dir.path().join("Ball_ao.png");
|
||||
write_png(&file, 4, [60, 60, 60, 255]);
|
||||
let mut s = ball();
|
||||
execute(&mut s, "textureSet.meshMap.import", &json!({"files": [{"path": text(&file)}]})).unwrap();
|
||||
let name = s.doc.project.resource_sources.keys().next().expect("the file is remembered").clone();
|
||||
let imported = ambient_occlusion(&s);
|
||||
|
||||
write_png(&file, 8, [200, 200, 200, 255]);
|
||||
execute(&mut s, "resource.update", &json!({})).unwrap();
|
||||
let updated = ambient_occlusion(&s);
|
||||
|
||||
assert_ne!(updated, imported, "the mesh map is resampled from the new file");
|
||||
|
||||
// Another image in the slot is not overwritten by a later change of the file
|
||||
let other = dir.path().join("other.png");
|
||||
write_png(&other, 4, [10, 10, 10, 255]);
|
||||
let other_name = import(&mut s, &other);
|
||||
execute(&mut s, "textureSet.meshMap.set", &json!({"ts": 0, "map": "ambientOcclusion", "image": other_name})).unwrap();
|
||||
let replaced = ambient_occlusion(&s);
|
||||
write_png(&file, 16, [120, 120, 120, 255]);
|
||||
let result = execute(&mut s, "resource.update", &json!({"names": [name]})).unwrap();
|
||||
|
||||
assert_eq!(result["updated"], json!([name]), "the resource itself still updates");
|
||||
assert_eq!(ambient_occlusion(&s), replaced, "the mesh map keeps the image set over it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_explicit_mesh_map_replacement_breaks_the_import_link_even_when_pixels_match() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let original = dir.path().join("Ball_ao.png");
|
||||
let replacement = dir.path().join("replacement.png");
|
||||
let equal_color = [60, 60, 60, 255];
|
||||
write_png(&original, 4, equal_color);
|
||||
write_png(&replacement, 4, equal_color);
|
||||
let mut session = ball();
|
||||
let replacement_name = import(&mut session, &replacement);
|
||||
execute(&mut session, "textureSet.meshMap.import", &json!({"files": [{"path": text(&original)}]})).unwrap();
|
||||
let imported = ambient_occlusion(&session);
|
||||
|
||||
execute(&mut session, "textureSet.meshMap.set", &json!({"ts": 0, "map": "ambientOcclusion", "image": replacement_name})).unwrap();
|
||||
write_png(&original, 8, [200, 200, 200, 255]);
|
||||
let result = execute(&mut session, "resource.update", &Value::Null).unwrap();
|
||||
|
||||
assert_eq!(result["updated"], json!(["Ball_ao.png"]));
|
||||
assert!(ambient_occlusion(&session) == imported, "replacing a map explicitly takes ownership even when the pixels were equal");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_import_replaces_bake_provenance_and_clear_detaches_the_link() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let file = dir.path().join("Ball_position.png");
|
||||
write_png(&file, 4, RED);
|
||||
let mut session = ball();
|
||||
execute(&mut session, "bake.run", &json!({"ts": 0, "resolution": 32, "maps": ["position"], "dilation": 0})).unwrap();
|
||||
execute(&mut session, "bake.settings", &json!({"ts": 0, "positionMode": "boundingBox"})).unwrap();
|
||||
assert!(!session.bake_changes(0, BakedMap::Position).is_empty(), "the previous bake is stale");
|
||||
|
||||
execute(&mut session, "textureSet.meshMap.import", &json!({"files": [{"path": text(&file)}]})).unwrap();
|
||||
write_png(&file, 8, [0, 0, 255, 255]);
|
||||
let imported = session.baked(0).unwrap().maps[&BakedMap::Position].clone();
|
||||
execute(&mut session, "resource.update", &Value::Null).unwrap();
|
||||
|
||||
assert_ne!(*imported, *session.baked(0).unwrap().maps[&BakedMap::Position], "the replacement follows its file");
|
||||
assert!(session.bake_changes(0, BakedMap::Position).is_empty(), "the imported map has no bake provenance");
|
||||
|
||||
execute(&mut session, "textureSet.meshMap.clear", &json!({"ts": 0, "map": "position"})).unwrap();
|
||||
assert!(session.doc.project.resource_sources["Ball_position.png"].mesh_map.is_none(), "clearing releases the file link");
|
||||
write_png(&file, 16, RED);
|
||||
execute(&mut session, "resource.update", &Value::Null).unwrap();
|
||||
assert!(!session.baked(0).unwrap().maps.contains_key(&BakedMap::Position), "updating the old source leaves the slot empty");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removing_unused_resources_keeps_the_file_that_feeds_an_imported_mesh_map() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let map_file = dir.path().join("Ball_ao.png");
|
||||
let unused_file = dir.path().join("unused.png");
|
||||
write_png(&map_file, 4, [60, 60, 60, 255]);
|
||||
write_png(&unused_file, 4, RED);
|
||||
let mut session = ball();
|
||||
let unused_name = import(&mut session, &unused_file);
|
||||
execute(&mut session, "textureSet.meshMap.import", &json!({"files": [{"path": text(&map_file)}]})).unwrap();
|
||||
let imported = ambient_occlusion(&session);
|
||||
|
||||
let cleanup = execute(&mut session, "file.removeUnused", &Value::Null).unwrap();
|
||||
|
||||
assert_eq!(cleanup["removed"], json!([unused_name]));
|
||||
write_png(&map_file, 8, [200, 200, 200, 255]);
|
||||
let update = execute(&mut session, "resource.update", &Value::Null).unwrap();
|
||||
|
||||
assert_eq!(update["updated"], json!(["Ball_ao.png"]));
|
||||
assert_ne!(ambient_occlusion(&session), imported);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn updating_duplicate_names_replaces_each_image_once_and_releases_old_pixels() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let files = ["first.png", "second.png"].map(|name| dir.path().join(name));
|
||||
let mut session = session();
|
||||
let names = files.each_ref().map(|path| {
|
||||
write_png(path, 4, RED);
|
||||
import(&mut session, path)
|
||||
});
|
||||
let old_pixels = names.each_ref().map(|name| Arc::downgrade(&session.images[name]));
|
||||
for file in &files {
|
||||
write_png(file, 8, GREEN);
|
||||
}
|
||||
|
||||
let result = execute(&mut session, "resource.update", &json!({"names": [&names[0], &names[1], &names[0]]})).unwrap();
|
||||
|
||||
assert_eq!(result["updated"], json!(names));
|
||||
assert!(old_pixels.iter().all(|pixels| pixels.upgrade().is_none()), "history keeps the encoded bytes, so replaced decoded images can drop");
|
||||
for name in names {
|
||||
assert_eq!(session.images[&name].width, 8);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pbr_folder_and_materialx_imports_remember_their_image_files() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let long_name = |suffix: &str| format!("{}{suffix}", "m".repeat(texturecraft_formats::MAX_RESOURCE_NAME_LEN - suffix.len()));
|
||||
let color = dir.path().join(long_name("_col.png"));
|
||||
write_png(&color, 4, RED);
|
||||
std::fs::create_dir(dir.path().join("tex")).unwrap();
|
||||
let base_name = long_name("_base.png");
|
||||
let base = dir.path().join("tex").join(&base_name);
|
||||
write_png(&base, 4, GREEN);
|
||||
let mtlx = dir.path().join("m.mtlx");
|
||||
let document = r#"<?xml version="1.0"?>
|
||||
<materialx version="1.39" fileprefix="tex/">
|
||||
<open_pbr_surface name="S" type="surfaceshader"><input name="base_color" type="color3" nodename="a" /></open_pbr_surface>
|
||||
<tiledimage name="a" type="color3"><input name="file" type="filename" value="base.png" /></tiledimage>
|
||||
<surfacematerial name="M" type="material"><input name="surfaceshader" type="surfaceshader" nodename="S" /></surfacematerial>
|
||||
</materialx>"#;
|
||||
std::fs::write(&mtlx, document.replace("base.png", &base_name)).unwrap();
|
||||
let mut s = session();
|
||||
import(&mut s, &color);
|
||||
import(&mut s, &base);
|
||||
|
||||
let pbr = execute(&mut s, "file.importPbrFolder", &json!({"files": [text(&color)]})).unwrap();
|
||||
let materialx = execute(&mut s, "file.importMaterialX", &json!({"path": text(&mtlx)})).unwrap();
|
||||
let pbr_name = pbr["resources"][0].as_str().unwrap().to_string();
|
||||
let materialx_name = materialx["resources"][0].as_str().unwrap().to_string();
|
||||
|
||||
let mut reopened = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap();
|
||||
assert_eq!(Path::new(&reopened.doc.project.resource_sources[&pbr_name].path).canonicalize().unwrap(), color.canonicalize().unwrap());
|
||||
assert_eq!(Path::new(&reopened.doc.project.resource_sources[&materialx_name].path).canonicalize().unwrap(), base.canonicalize().unwrap());
|
||||
|
||||
write_png(&color, 8, GREEN);
|
||||
write_png(&base, 8, RED);
|
||||
|
||||
let rows = reopened.resource_states();
|
||||
let missing: Vec<_> = [&pbr_name, &materialx_name]
|
||||
.into_iter()
|
||||
.filter(|name| !rows.iter().any(|row| row.name == name.as_str() && row.status == ResourceStatus::Outdated))
|
||||
.collect();
|
||||
assert!(missing.is_empty(), "both material imports must keep their source images after reopening: {missing:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mesh_map_imported_twice_follows_the_latest_file() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let file = dir.path().join("Ball_ao.png");
|
||||
let import_file = |s: &mut Session| execute(s, "textureSet.meshMap.import", &json!({"files": [{"path": text(&file)}]})).unwrap();
|
||||
let mut s = ball();
|
||||
write_png(&file, 4, [60, 60, 60, 255]);
|
||||
import_file(&mut s);
|
||||
let first = s.doc.project.resource_sources.keys().next().unwrap().clone();
|
||||
write_png(&file, 8, [200, 200, 200, 255]);
|
||||
import_file(&mut s);
|
||||
let latest = s.doc.project.resource_sources.keys().find(|name| **name != first).expect("a second resource").clone();
|
||||
let imported = ambient_occlusion(&s);
|
||||
|
||||
write_png(&file, 16, [10, 10, 10, 255]);
|
||||
execute(&mut s, "resource.update", &json!({"names": [latest]})).unwrap();
|
||||
|
||||
assert_ne!(ambient_occlusion(&s), imported, "the mesh map follows the file imported last");
|
||||
assert!(s.doc.project.resource_sources[&first].mesh_map.is_none(), "the earlier import no longer feeds the slot");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_undecodable_saved_resource_is_reported_even_when_its_file_is_unchanged() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let file = dir.path().join("broken.png");
|
||||
write_png(&file, 4, RED);
|
||||
let mut session = session();
|
||||
let name = import(&mut session, &file);
|
||||
let invalid = b"incomplete image".to_vec();
|
||||
std::fs::write(&file, &invalid).unwrap();
|
||||
session.doc.resources.insert(name.clone(), Arc::new(invalid));
|
||||
session.images.remove(&name);
|
||||
|
||||
let result = execute(&mut session, "resource.update", &json!({"names": [name]}));
|
||||
|
||||
assert!(result.unwrap_err().to_string().contains("nothing was updated"));
|
||||
assert!(!session.images.contains_key(&name));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rejected_update_restores_all_previously_decoded_images() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut session = session();
|
||||
let names = ["left.png", "right.png"].map(|name| {
|
||||
let path = dir.path().join(name);
|
||||
write_png(&path, 4, RED);
|
||||
let imported = import_as_fill(&mut session, &path);
|
||||
write_png(&path, 8, GREEN);
|
||||
imported
|
||||
});
|
||||
|
||||
// Make final document validation fail after both replacements have been processed
|
||||
let layer = session.doc.project.layers.values_mut().next().unwrap();
|
||||
layer.kind = texturecraft_engine::core::LayerKind::Instance { source: layer.id };
|
||||
let steps = session.history_labels().len();
|
||||
|
||||
let result = execute(&mut session, "resource.update", &json!({"names": names}));
|
||||
|
||||
assert!(result.unwrap_err().to_string().contains("would draw itself"));
|
||||
assert_eq!(session.history_labels().len(), steps);
|
||||
for name in names {
|
||||
assert_eq!(session.images[&name].width, 4);
|
||||
assert_eq!(status_of(&mut session, &name), ResourceStatus::Outdated);
|
||||
}
|
||||
}
|
||||
@@ -200,7 +200,7 @@ pub enum VirtualMap {
|
||||
Glossiness,
|
||||
/// Baked AO × AO channel (per the texture set's AO mixing).
|
||||
AoMixed,
|
||||
/// Dielectric reflectance at normal incidence: 0.08 × specular level.
|
||||
/// Dielectric reflectance at normal incidence: Specular Level scaled by the project's shader settings.
|
||||
F0,
|
||||
/// 1 − glossiness (specular/glossiness projects).
|
||||
Roughness,
|
||||
@@ -770,6 +770,7 @@ struct Sampler<'a> {
|
||||
/// Normal convention overriding every normal output.
|
||||
normal_override: Option<NormalFormat>,
|
||||
project_normal: NormalFormat,
|
||||
dielectric_f0_scale: f32,
|
||||
}
|
||||
|
||||
fn unpack(v: [f32; 3]) -> Vec3 {
|
||||
@@ -856,7 +857,7 @@ impl Sampler<'_> {
|
||||
VirtualMap::NormalOpenGl => self.normal(at, NormalFormat::OpenGl, cache),
|
||||
VirtualMap::NormalDirectX => self.normal(at, NormalFormat::DirectX, cache),
|
||||
VirtualMap::Glossiness => [1.0 - self.channel(Channel::Roughness, at)[0]; 3],
|
||||
VirtualMap::F0 => [0.08 * self.channel(Channel::SpecularLevel, at)[0]; 3],
|
||||
VirtualMap::F0 => [self.dielectric_f0_scale * self.channel(Channel::SpecularLevel, at)[0]; 3],
|
||||
VirtualMap::Roughness => [1.0 - self.channel(Channel::Glossiness, at)[0]; 3],
|
||||
VirtualMap::SheenTint => self.channel(Channel::SheenColor, at).map(|c| c * self.channel(Channel::SheenWeight, at)[0]),
|
||||
VirtualMap::HeightNormal => {
|
||||
@@ -933,6 +934,7 @@ pub fn render_planned_maps(input: &ExportInput, options: &ExportOptions, planned
|
||||
scales: set.block_scales(),
|
||||
normal_override: options.normal_format,
|
||||
project_normal: input.project.normal_format,
|
||||
dielectric_f0_scale: input.project.display.dielectric_f0_scale(),
|
||||
};
|
||||
|
||||
planned
|
||||
|
||||
@@ -1575,3 +1575,42 @@ fn write_files_accepts_a_long_nested_folder_and_stem() {
|
||||
assert!(paths[0].is_file());
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn specular_glossiness_exports_ignore_the_ior_specular_setting() {
|
||||
let mut fx = Fx::new(&[Channel::BaseColor, Channel::Specular, Channel::Glossiness, Channel::SpecularLevel]);
|
||||
fx.set_all(Channel::Specular, |_, _| [0.3, 0.2, 0.1]);
|
||||
fx.set_all(Channel::Glossiness, |_, _| [0.7; 3]);
|
||||
fx.set_all(Channel::SpecularLevel, |_, _| [0.5; 3]);
|
||||
(fx.project.display.spec_gloss, fx.project.display.ior) = (true, 1.8);
|
||||
let channel = |channel| SourceRef::Channel { channel, component: 0 };
|
||||
let virt = |map| SourceRef::Virtual { map, component: 0 };
|
||||
let specular = MapSpec {
|
||||
file: "specular".into(),
|
||||
format: FileFormat::Png,
|
||||
bit_depth: 16,
|
||||
channels: [Dest::R, Dest::G, Dest::B]
|
||||
.into_iter()
|
||||
.zip(0u8..)
|
||||
.map(|(dest, component)| (dest, SourceRef::Channel { channel: Channel::Specular, component }))
|
||||
.collect(),
|
||||
inverted: Vec::new(),
|
||||
};
|
||||
let preset = ExportPreset {
|
||||
name: "spec gloss".into(),
|
||||
maps: vec![
|
||||
specular,
|
||||
gray_map("gloss", channel(Channel::Glossiness)),
|
||||
gray_map("rough", virt(VirtualMap::Roughness)),
|
||||
gray_map("f0", virt(VirtualMap::F0)),
|
||||
],
|
||||
};
|
||||
let options = ExportOptions::new(preset);
|
||||
|
||||
let off = fx.render(&options);
|
||||
fx.project.display.ior_specular = true;
|
||||
let on = fx.render(&options);
|
||||
|
||||
assert!(off.iter().any(|file| file.name.starts_with("f0")), "the F0 map is part of the comparison");
|
||||
assert_eq!(on, off, "Specular/Glossiness takes reflectance from the Specular color, not the IOR");
|
||||
}
|
||||
@@ -25,7 +25,7 @@ use std::collections::hash_map::Entry;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use texturecraft_geom::glam::{Mat4, Vec2, Vec3, Vec4};
|
||||
use texturecraft_geom::unwrap::{all_triangles_degenerate, auto_unwrap, weld_ids};
|
||||
use texturecraft_geom::unwrap::{all_triangles_degenerate, auto_unwrap};
|
||||
use texturecraft_geom::{BaseColor, MAX_TRIANGLES, Mesh, SubMesh, UvGBuffer};
|
||||
|
||||
use crate::{FormatError, Result};
|
||||
@@ -508,7 +508,7 @@ fn geometry(raw: RawMesh) -> Result<(Mesh, Vec<String>, Option<Vec<Vec2>>)> {
|
||||
|
||||
mesh.normals = match normals {
|
||||
Some(n) if n.len() == mesh.positions.len() => n.into_iter().map(|v| v.try_normalize().unwrap_or(Vec3::Y)).collect(),
|
||||
_ => smooth_normals(&mesh),
|
||||
_ => mesh.smooth_normals(),
|
||||
};
|
||||
if let Some(c) = colors.filter(|c| c.len() == mesh.positions.len()) {
|
||||
mesh.colors = c.into_iter().map(|v| if v.is_finite() { v.clamp(Vec4::ZERO, Vec4::ONE) } else { Vec4::ONE }).collect();
|
||||
@@ -641,23 +641,6 @@ fn orbit_cameras(raw: &[RawCamera], mesh: &Mesh) -> Vec<texturecraft_core::Camer
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Area-weighted smooth normals over welded positions (UV seams do not split shading).
|
||||
fn smooth_normals(mesh: &Mesh) -> Vec<Vec3> {
|
||||
let welded_vertices = weld_ids(&mesh.positions);
|
||||
let mut normals = vec![Vec3::ZERO; mesh.positions.len()];
|
||||
for triangle in mesh.indices.as_chunks::<3>().0 {
|
||||
let p = |i: u32| mesh.positions.get(i as usize).copied().unwrap_or_default();
|
||||
let face = (p(triangle[1]) - p(triangle[0])).cross(p(triangle[2]) - p(triangle[0]));
|
||||
for v in triangle {
|
||||
if let Some(a) = welded_vertices.get(*v as usize).and_then(|w| normals.get_mut(*w as usize)) {
|
||||
*a += face;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
welded_vertices.iter().map(|w| normals.get(*w as usize).and_then(|n| n.try_normalize()).unwrap_or(Vec3::Y)).collect()
|
||||
}
|
||||
|
||||
/// Inspects `mesh` and generates its UV report (overlaps, out-of-range UVs, warnings).
|
||||
pub fn mesh_report(mesh: &Mesh) -> MeshReport {
|
||||
report(mesh, false, Vec::new())
|
||||
|
||||
@@ -42,11 +42,13 @@ mod load_budget;
|
||||
mod project_open_limit;
|
||||
mod ram_operation;
|
||||
mod ram_reservation;
|
||||
mod save_progress;
|
||||
mod uv_layout;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub use entries::{DEFAULT_RAM_PERCENT, DEFAULT_RESERVED_CORES, available_save_resources, configured_ram_budget, save_ram_budget, set_save_resources};
|
||||
pub use project_open_limit::{DEFAULT_PROJECT_OPEN_LIMIT_GIB, project_open_limit_gib, set_project_open_limit_gib};
|
||||
pub use ram_reservation::RamReservation;
|
||||
pub use save_progress::SaveProgress;
|
||||
|
||||
const KIND: &str = "project file";
|
||||
#[cfg(test)]
|
||||
@@ -70,21 +72,21 @@ pub use bake_paint_data::BakePaintData;
|
||||
|
||||
/// Everything a project file holds.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ProjectFile<Resource = Vec<u8>> {
|
||||
pub struct ProjectFile<Resource = Vec<u8>, MeshBytes = Vec<u8>> {
|
||||
pub project: Project,
|
||||
pub pixels: PixelStore,
|
||||
/// Baked mesh maps per texture set index.
|
||||
pub baked: BTreeMap<usize, BakedMaps>,
|
||||
/// Original mesh file: (extension, bytes).
|
||||
pub mesh: Option<(String, Vec<u8>)>,
|
||||
pub mesh: Option<(String, MeshBytes)>,
|
||||
/// Saved UV layout of `mesh` when its UVs were rebuilt: the UV of every triangle corner, in
|
||||
/// index order, as the mesh was first imported.
|
||||
pub mesh_uvs: Option<Vec<Vec2>>,
|
||||
/// High-definition mesh files for baking: (file name, bytes). Names are
|
||||
/// [`sanitize_resource_name`]d on save.
|
||||
pub high_poly: Vec<(String, Vec<u8>)>,
|
||||
pub high_poly: Vec<(String, MeshBytes)>,
|
||||
/// Baking cage mesh file: (file name, bytes).
|
||||
pub cage: Option<(String, Vec<u8>)>,
|
||||
pub cage: Option<(String, MeshBytes)>,
|
||||
pub bake_paint: BTreeMap<(usize, BakePaintTarget), BakePaintData>,
|
||||
pub thumbnail: Option<Vec<u8>>,
|
||||
/// Imported resources (images used by fills, alphas, stencils), by name: original bytes.
|
||||
@@ -93,7 +95,7 @@ pub struct ProjectFile<Resource = Vec<u8>> {
|
||||
pub warnings: Vec<String>,
|
||||
}
|
||||
|
||||
impl<Resource> ProjectFile<Resource> {
|
||||
impl<Resource, MeshBytes> ProjectFile<Resource, MeshBytes> {
|
||||
/// Check that the mesh source and the rebuild setting agree with the saved layout.
|
||||
pub fn validate_mesh_uvs(&self) -> Result<()> {
|
||||
if self.project.mesh_rebuild_uvs != self.mesh_uvs.is_some() {
|
||||
@@ -132,11 +134,15 @@ pub fn save_project(path: &std::path::Path, project_file: &ProjectFile) -> Resul
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn write_project_atomic(path: &std::path::Path, project_file: &ProjectFile<impl Borrow<Vec<u8>>>) -> Result<()> {
|
||||
fn write_project_atomic(
|
||||
path: &std::path::Path,
|
||||
project_file: &ProjectFile<impl Borrow<Vec<u8>>, impl Borrow<Vec<u8>>>,
|
||||
progress: Option<&SaveProgress>,
|
||||
) -> Result<()> {
|
||||
let (temporary_path, file) = crate::create_temp(path)?;
|
||||
let result = (|| -> Result<()> {
|
||||
let mut file = std::io::BufWriter::new(file);
|
||||
write_project(&mut file, project_file)?;
|
||||
write_project(&mut file, project_file, progress)?;
|
||||
file.into_inner().map_err(|error| error.into_error())?.sync_all()?;
|
||||
std::fs::rename(&temporary_path, path)?;
|
||||
Ok(())
|
||||
@@ -210,7 +216,7 @@ fn write_baked(w: &mut dyn Write, res: u32, h: u32, comps: usize, data: &[f32])
|
||||
}
|
||||
|
||||
/// The zip entries of a project file, in file order. Bodies run later, possibly on other threads.
|
||||
fn entries(project_file: &ProjectFile<impl Borrow<Vec<u8>>>) -> Result<Vec<Entry<'_>>> {
|
||||
fn entries(project_file: &ProjectFile<impl Borrow<Vec<u8>>, impl Borrow<Vec<u8>>>) -> Result<Vec<Entry<'_>>> {
|
||||
project_file.validate_mesh_uvs()?;
|
||||
|
||||
let deflate = SimpleFileOptions::default().compression_method(CompressionMethod::Deflated).large_file(true);
|
||||
@@ -227,6 +233,7 @@ fn entries(project_file: &ProjectFile<impl Borrow<Vec<u8>>>) -> Result<Vec<Entry
|
||||
let mut out = vec![Entry { name: "project.json".into(), options: deflate, weight: json.len() as u64, body: Box::new(move |w| w.write_all(&json)) }];
|
||||
|
||||
if let Some((ext, bytes)) = &project_file.mesh {
|
||||
let bytes = bytes.borrow();
|
||||
out.push(Entry {
|
||||
name: format!("mesh.{}", sanitize_ext(ext)),
|
||||
options: deflate,
|
||||
@@ -246,6 +253,7 @@ fn entries(project_file: &ProjectFile<impl Borrow<Vec<u8>>>) -> Result<Vec<Entry
|
||||
|
||||
let mut used = HashSet::new();
|
||||
for (dir, (name, bytes)) in project_file.high_poly.iter().map(|m| ("highpoly", m)).chain(project_file.cage.iter().map(|m| ("cage", m))) {
|
||||
let bytes = bytes.borrow();
|
||||
out.push(Entry {
|
||||
name: unique_entry_name(dir, name, &mut used),
|
||||
options: deflate,
|
||||
@@ -327,9 +335,13 @@ fn entries(project_file: &ProjectFile<impl Borrow<Vec<u8>>>) -> Result<Vec<Entry
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn write_project<W: Write + Seek>(out: W, pf: &ProjectFile<impl Borrow<Vec<u8>>>) -> Result<()> {
|
||||
fn write_project<W: Write + Seek>(out: W, pf: &ProjectFile<impl Borrow<Vec<u8>>, impl Borrow<Vec<u8>>>, progress: Option<&SaveProgress>) -> Result<()> {
|
||||
let mut zip = ZipWriter::new(out);
|
||||
entries::write_entries(&mut zip, entries(pf)?)?;
|
||||
let mut entries = entries(pf)?;
|
||||
if let Some(progress) = progress {
|
||||
progress.track(&mut entries);
|
||||
}
|
||||
entries::write_entries(&mut zip, entries)?;
|
||||
zip.finish().map_err(zip_err)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -2,6 +2,8 @@ use std::borrow::Borrow;
|
||||
use std::io::Cursor;
|
||||
use std::sync::{Condvar, Mutex};
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use super::SaveProgress;
|
||||
use super::{ProjectFile, ram_operation::RamOperation, write_project};
|
||||
use crate::{FormatError, Result};
|
||||
|
||||
@@ -54,17 +56,28 @@ impl RamReservation {
|
||||
Some(Self(RamOperation::Save))
|
||||
}
|
||||
|
||||
pub fn save_bytes(&mut self, project_file: &ProjectFile<impl Borrow<Vec<u8>>>) -> Result<Vec<u8>> {
|
||||
pub fn save_bytes(&mut self, project_file: &ProjectFile<impl Borrow<Vec<u8>>, impl Borrow<Vec<u8>>>) -> Result<Vec<u8>> {
|
||||
self.check_save()?;
|
||||
let mut out = Cursor::new(Vec::new());
|
||||
write_project(&mut out, project_file)?;
|
||||
write_project(&mut out, project_file, None)?;
|
||||
Ok(out.into_inner())
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn save(&mut self, path: &std::path::Path, project_file: &ProjectFile<impl Borrow<Vec<u8>>>) -> Result<()> {
|
||||
pub fn save(&mut self, path: &std::path::Path, project_file: &ProjectFile<impl Borrow<Vec<u8>>, impl Borrow<Vec<u8>>>) -> Result<()> {
|
||||
self.check_save()?;
|
||||
super::write_project_atomic(path, project_file)
|
||||
super::write_project_atomic(path, project_file, None)
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn save_with_progress(
|
||||
&mut self,
|
||||
path: &std::path::Path,
|
||||
project_file: &ProjectFile<impl Borrow<Vec<u8>>, impl Borrow<Vec<u8>>>,
|
||||
progress: &SaveProgress,
|
||||
) -> Result<()> {
|
||||
self.check_save()?;
|
||||
super::write_project_atomic(path, project_file, Some(progress))
|
||||
}
|
||||
|
||||
fn check_save(&self) -> Result<()> {
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use super::entries::Entry;
|
||||
|
||||
mod progress_writer;
|
||||
|
||||
use progress_writer::ProgressWriter;
|
||||
|
||||
// Leave room on the indicator for syncing and replacing the archive
|
||||
const MAX_PAYLOAD_PROGRESS: f32 = 0.95;
|
||||
|
||||
/// Estimated archive progress, based on the payload processed by the entry writers.
|
||||
/// Completing the archive, syncing it to disk, and replacing the destination can take longer.
|
||||
#[derive(Default)]
|
||||
pub struct SaveProgress {
|
||||
total: AtomicU64,
|
||||
processed: AtomicU64,
|
||||
}
|
||||
|
||||
impl SaveProgress {
|
||||
pub fn fraction(&self) -> f32 {
|
||||
let total = self.total.load(Ordering::Relaxed);
|
||||
if total == 0 {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
let processed = self.processed.load(Ordering::Relaxed).min(total);
|
||||
MAX_PAYLOAD_PROGRESS * (processed as f64 / total as f64) as f32
|
||||
}
|
||||
|
||||
pub(super) fn track<'a>(&'a self, entries: &mut [Entry<'a>]) {
|
||||
self.processed.store(0, Ordering::Relaxed);
|
||||
self.total.store(entries.iter().fold(0u64, |sum, entry| sum.saturating_add(entry.weight)), Ordering::Relaxed);
|
||||
for entry in entries {
|
||||
let body = std::mem::replace(&mut entry.body, Box::new(|_| Ok(())));
|
||||
let remaining = entry.weight;
|
||||
entry.body = Box::new(move |target| {
|
||||
let mut writer = ProgressWriter { target, progress: self, remaining, pending: 0 };
|
||||
body(&mut writer)?;
|
||||
writer.report();
|
||||
Ok(())
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
use std::io::{self, Write};
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
use super::SaveProgress;
|
||||
|
||||
// Batch updates to reduce contention between compression workers
|
||||
const PROGRESS_UPDATE_BYTES: u64 = 64 * 1024;
|
||||
|
||||
pub(super) struct ProgressWriter<'a> {
|
||||
pub(super) target: &'a mut dyn Write,
|
||||
pub(super) progress: &'a SaveProgress,
|
||||
pub(super) remaining: u64,
|
||||
pub(super) pending: u64,
|
||||
}
|
||||
|
||||
impl ProgressWriter<'_> {
|
||||
pub(super) fn report(&mut self) {
|
||||
self.progress.processed.fetch_add(std::mem::take(&mut self.pending), Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
impl Write for ProgressWriter<'_> {
|
||||
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
|
||||
let written = self.target.write(bytes)?;
|
||||
let counted = (written as u64).min(self.remaining);
|
||||
self.remaining -= counted;
|
||||
self.pending += counted;
|
||||
if self.pending >= PROGRESS_UPDATE_BYTES {
|
||||
self.report();
|
||||
}
|
||||
Ok(written)
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> io::Result<()> {
|
||||
self.target.flush()
|
||||
}
|
||||
}
|
||||
+55
-2
@@ -245,6 +245,27 @@ impl Mesh {
|
||||
self.normals = normals.into_iter().map(|v| v.try_normalize().unwrap_or(Vec3::Y)).collect();
|
||||
}
|
||||
|
||||
/// Area-weighted smooth normals over welded positions, so UV and material seams do not split shading.
|
||||
pub fn smooth_normals(&self) -> Vec<Vec3> {
|
||||
let welded_vertices = crate::unwrap::weld_ids(&self.positions);
|
||||
let mut normals = vec![Vec3::ZERO; self.positions.len()];
|
||||
for triangle in self.indices.as_chunks::<3>().0 {
|
||||
let p = |i: u32| self.positions.get(i as usize).copied().unwrap_or_default();
|
||||
let face = (p(triangle[1]) - p(triangle[0])).cross(p(triangle[2]) - p(triangle[0]));
|
||||
for v in triangle {
|
||||
if let Some(accumulated) = welded_vertices.get(*v as usize).and_then(|welded| normals.get_mut(*welded as usize)) {
|
||||
*accumulated += face;
|
||||
}
|
||||
}
|
||||
}
|
||||
welded_vertices.iter().map(|welded| normals.get(*welded as usize).and_then(|normal| normal.try_normalize()).unwrap_or(Vec3::Y)).collect()
|
||||
}
|
||||
|
||||
/// Replace normals with [`Mesh::smooth_normals`] on this mesh.
|
||||
pub fn compute_smooth_normals(&mut self) {
|
||||
self.normals = self.smooth_normals();
|
||||
}
|
||||
|
||||
/// The faces MikkTSpace sees: each importer quad (a fan pair marked in [`Mesh::diagonals`])
|
||||
/// as one four-corner face, like Blender hands it over, and every other triangle as a
|
||||
/// triangle. Polygons with more than four corners stay fan triangles. The vertex and index
|
||||
@@ -315,8 +336,11 @@ impl Mesh {
|
||||
if self.uvs.len() != self.positions.len() {
|
||||
self.uvs = vec![Vec2::ZERO; self.positions.len()];
|
||||
}
|
||||
// mikktspace crashes (out-of-bounds) when every triangle is degenerate; skip it then.
|
||||
if crate::unwrap::all_triangles_degenerate(self) {
|
||||
// mikktspace crashes (out-of-bounds) when every triangle is degenerate; skip it then. Its
|
||||
// callbacks read a missing vertex as the origin, which the degenerate check cannot see, so
|
||||
// an index past the last vertex skips it too.
|
||||
let n = self.positions.len();
|
||||
if !self.indices.iter().all(|&i| (i as usize) < n) || crate::unwrap::all_triangles_degenerate(self) {
|
||||
self.simple_tangents();
|
||||
} else {
|
||||
let faces = self.tangent_faces();
|
||||
@@ -497,6 +521,9 @@ impl Mesh {
|
||||
|
||||
/// A single-material mesh from raw attributes; computes missing normals and tangents.
|
||||
pub fn from_parts(positions: Vec<Vec3>, normals: Option<Vec<Vec3>>, uvs: Vec<Vec2>, indices: Vec<u32>, material: &str) -> Result<Mesh> {
|
||||
if let Some(bad) = indices.iter().find(|&&i| i as usize >= positions.len()) {
|
||||
return Err(GeomError::Invalid(format!("index {bad} out of range ({} vertices)", positions.len())));
|
||||
}
|
||||
let count = indices.len() as u32;
|
||||
let mut m = Mesh {
|
||||
normals: normals.unwrap_or_default(),
|
||||
@@ -910,4 +937,30 @@ mod tests {
|
||||
assert_eq!(m.uv_tiles(1).into_iter().collect::<Vec<_>>(), vec![(1, 0)]);
|
||||
assert_eq!(m.uv_tiles(0).into_iter().collect::<Vec<_>>(), vec![(0, 0)]);
|
||||
}
|
||||
|
||||
/// An index past the last vertex reads as the origin in MikkTSpace's callbacks. With two
|
||||
/// positions at the origin and one missing, the degenerate-mesh guard (which sees the missing
|
||||
/// vertex as different) let it through while MikkTSpace saw every triangle as degenerate and
|
||||
/// underflowed: a panic in debug builds, an out-of-bounds walk in release.
|
||||
#[test]
|
||||
fn from_parts_refuses_an_out_of_range_index_without_crashing() {
|
||||
let positions = vec![Vec3::ZERO, Vec3::X];
|
||||
let uvs = vec![Vec2::ZERO, Vec2::X];
|
||||
let e = Mesh::from_parts(positions, None, uvs, vec![0, 1, 2], "M").unwrap_err();
|
||||
assert!(e.to_string().contains("out of range"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tangents_of_a_mesh_with_an_out_of_range_index_fall_back_without_crashing() {
|
||||
for indices in [vec![0, 1, 2], vec![0, 0, 2], vec![0, 1, 5, 0, 1, 1]] {
|
||||
let mut m = Mesh::from_parts(vec![Vec3::ZERO, Vec3::X, Vec3::Y], None, vec![Vec2::ZERO, Vec2::X, Vec2::Y], vec![0, 1, 2], "M").unwrap();
|
||||
m.positions.truncate(2);
|
||||
m.normals.truncate(2);
|
||||
m.uvs.truncate(2);
|
||||
m.indices = indices;
|
||||
m.compute_tangents();
|
||||
assert_eq!(m.tangents.len(), 2);
|
||||
assert!(m.tangents.iter().all(|t| t.is_finite()), "{:?}", m.tangents);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -30,3 +30,4 @@ wasm-bindgen-futures = "0.4"
|
||||
|
||||
[dev-dependencies]
|
||||
image = { workspace = true }
|
||||
texturecraft-formats = { workspace = true }
|
||||
@@ -18,6 +18,10 @@ use texturecraft_geom::glam::Vec3;
|
||||
use crate::gpu_trace::{STACK, buffer, bvh_depth, bvh_rows, entry, scoped, storage};
|
||||
|
||||
const WORKGROUP: u32 = 64;
|
||||
// The shader binds BVH nodes, triangles, input queries and results
|
||||
const RAY_STORAGE_BUFFERS: u32 = 4;
|
||||
// The hemisphere reduction stores one vec4 and one count per lane
|
||||
const WORKGROUP_STORAGE_BYTES: u32 = WORKGROUP * (size_of::<[f32; 4]>() + size_of::<u32>()) as u32;
|
||||
/// Rays per dispatch: short dispatches keep slow GPUs clear of driver watchdogs.
|
||||
const RAYS_PER_DISPATCH: usize = 1 << 24;
|
||||
const NONE: u32 = u32::MAX;
|
||||
@@ -66,23 +70,11 @@ fn err(e: impl std::fmt::Display) -> BakeError {
|
||||
|
||||
impl Gpu {
|
||||
fn new() -> Result<Gpu, String> {
|
||||
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle_from_env());
|
||||
let options = wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::HighPerformance, ..Default::default() };
|
||||
let adapter = pollster::block_on(instance.request_adapter(&options)).map_err(|e| format!("no GPU adapter: {e}"))?;
|
||||
let info = adapter.get_info();
|
||||
if info.device_type == wgpu::DeviceType::Cpu {
|
||||
return Err(format!("{} is a software renderer", info.name));
|
||||
}
|
||||
let limits = adapter.limits();
|
||||
if limits.max_storage_buffers_per_shader_stage < 3
|
||||
|| limits.max_compute_invocations_per_workgroup < WORKGROUP
|
||||
|| limits.max_compute_workgroup_size_x < WORKGROUP
|
||||
{
|
||||
return Err(format!("{} has no usable compute shaders", info.name));
|
||||
}
|
||||
let (adapter, name, limits) = bake_adapter()?;
|
||||
let desc = wgpu::DeviceDescriptor { label: Some("tc_bake"), required_limits: limits, ..Default::default() };
|
||||
let (device, queue) = pollster::block_on(adapter.request_device(&desc)).map_err(|e| format!("no GPU device: {e}"))?;
|
||||
// Errors are caught by the scopes around every call; never let wgpu's default handler panic.
|
||||
|
||||
// Each GPU call has an error scope so the default handler should leave failures to those scopes
|
||||
device.on_uncaptured_error(Arc::new(|_| {}));
|
||||
let (layout, transfer, hemisphere) = scoped(&device, "GPU baking: pipelines", || {
|
||||
let params = wgpu::BindingType::Buffer {
|
||||
@@ -112,7 +104,7 @@ impl Gpu {
|
||||
(layout, pipe("transfer_main"), pipe("hemisphere_main"))
|
||||
})?;
|
||||
let stride = size_of::<Params>().next_multiple_of(device.limits().min_uniform_buffer_offset_alignment.max(1) as usize);
|
||||
Ok(Gpu { device, queue, name: info.name, layout, transfer, hemisphere, stride })
|
||||
Ok(Gpu { device, queue, name, layout, transfer, hemisphere, stride })
|
||||
}
|
||||
|
||||
/// The largest storage buffer this device binds.
|
||||
@@ -122,6 +114,43 @@ impl Gpu {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the adapter selected for mesh-map baking supports its compute shaders.
|
||||
pub fn raytracing_available() -> bool {
|
||||
static SUPPORTED: OnceLock<bool> = OnceLock::new();
|
||||
*SUPPORTED.get_or_init(|| bake_adapter().is_ok())
|
||||
}
|
||||
|
||||
fn bake_adapter() -> Result<(wgpu::Adapter, String, wgpu::Limits), String> {
|
||||
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle_from_env());
|
||||
let options = wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::HighPerformance, ..Default::default() };
|
||||
let adapter = pollster::block_on(instance.request_adapter(&options)).map_err(|e| format!("no GPU adapter: {e}"))?;
|
||||
let info = adapter.get_info();
|
||||
let limits = adapter.limits();
|
||||
let flags = adapter.get_downlevel_capabilities().flags;
|
||||
if let Some(reason) = unsupported_adapter(info.device_type, flags, &limits) {
|
||||
return Err(format!("{} {reason}", info.name));
|
||||
}
|
||||
|
||||
Ok((adapter, info.name, limits))
|
||||
}
|
||||
|
||||
fn unsupported_adapter(device_type: wgpu::DeviceType, flags: wgpu::DownlevelFlags, limits: &wgpu::Limits) -> Option<&'static str> {
|
||||
if device_type == wgpu::DeviceType::Cpu {
|
||||
return Some("is a software renderer");
|
||||
}
|
||||
|
||||
if !flags.contains(wgpu::DownlevelFlags::COMPUTE_SHADERS)
|
||||
|| limits.max_storage_buffers_per_shader_stage < RAY_STORAGE_BUFFERS
|
||||
|| limits.max_compute_invocations_per_workgroup < WORKGROUP
|
||||
|| limits.max_compute_workgroup_size_x < WORKGROUP
|
||||
|| limits.max_compute_workgroup_storage_size < WORKGROUP_STORAGE_BYTES
|
||||
{
|
||||
return Some("has no usable compute shaders");
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
/// The GPU [`Tracer`]. Its device is created on the first bake; without a hardware adapter
|
||||
/// every bake reports [`BakeError::Tracer`] (and runs on the CPU).
|
||||
#[derive(Default)]
|
||||
@@ -383,6 +412,22 @@ mod tests {
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn raytracing_requires_hardware_and_compute_support() {
|
||||
let limits = wgpu::Limits::default();
|
||||
let compute = wgpu::DownlevelFlags::COMPUTE_SHADERS;
|
||||
let no_compute = wgpu::Limits { max_compute_workgroup_size_x: 0, ..limits.clone() };
|
||||
let three_buffers = wgpu::Limits { max_storage_buffers_per_shader_stage: 3, ..limits.clone() };
|
||||
let no_shared_memory = wgpu::Limits { max_compute_workgroup_storage_size: 0, ..limits.clone() };
|
||||
|
||||
assert!(unsupported_adapter(wgpu::DeviceType::DiscreteGpu, compute, &limits).is_none());
|
||||
assert!(unsupported_adapter(wgpu::DeviceType::Cpu, compute, &limits).is_some());
|
||||
assert!(unsupported_adapter(wgpu::DeviceType::IntegratedGpu, wgpu::DownlevelFlags::empty(), &limits).is_some());
|
||||
assert!(unsupported_adapter(wgpu::DeviceType::IntegratedGpu, compute, &no_compute).is_some());
|
||||
assert!(unsupported_adapter(wgpu::DeviceType::IntegratedGpu, compute, &three_buffers).is_some(), "the bind group requires four storage buffers");
|
||||
assert!(unsupported_adapter(wgpu::DeviceType::IntegratedGpu, compute, &no_shared_memory).is_some());
|
||||
}
|
||||
|
||||
/// The GPU baker, or None (test skipped) without a hardware adapter.
|
||||
fn gpu() -> Option<GpuBaker> {
|
||||
let g = GpuBaker::new();
|
||||
|
||||
Loaded 100 of 188 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user