mirror of
https://github.com/storytold/texturecraft.git
synced 2026-11-28 00:59:29 +01:00
Auto: Validate Xwayland setup before selecting X11 and integrate main
Keep native Wayland when the local X server rejects setup or lacks the requested screen. Cover rejected and accepted replies, document pointer support and Flatpak access, and retain the PhotoCraft copyright and license notices. Focused Linux desktop, titlebar and framework tests passed, along with Clippy, formatting, layers and wasm checks.
This commit is contained in:
commit
59270b4a52
76 files changed
+3779
-358
No files matched your search
@@ -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 }}
|
||||
@@ -53,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
+3
@@ -5830,6 +5830,7 @@ dependencies = [
|
||||
"log",
|
||||
"rfd",
|
||||
"ron",
|
||||
"rustix 1.1.6",
|
||||
"serde_json",
|
||||
"texturecraft-automation",
|
||||
"texturecraft-engine",
|
||||
@@ -5837,6 +5838,7 @@ dependencies = [
|
||||
"winit",
|
||||
"winresource",
|
||||
"winsafe",
|
||||
"x11rb-protocol",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6006,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).
|
||||
|
||||
@@ -23,7 +23,7 @@ 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 }
|
||||
# The window's backend (Xwayland for a pen, src/xwayland_pen.rs) for the title bar and the UI runtime.
|
||||
# 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"
|
||||
@@ -37,10 +37,11 @@ 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 }
|
||||
|
||||
# Opening the window through Xwayland for a pen on Wayland (src/xwayland_pen.rs): winit's
|
||||
# `EventLoopBuilderExtX11`. Already in Cargo.lock through eframe.
|
||||
# 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]
|
||||
|
||||
@@ -336,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<_>>())
|
||||
@@ -345,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,
|
||||
@@ -363,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);
|
||||
@@ -379,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")));
|
||||
@@ -395,14 +394,16 @@ fn main() {
|
||||
prefs.apply_work_threads();
|
||||
prefs.apply_resource_limits();
|
||||
let session = initial_session(&args);
|
||||
// winit picks Wayland whenever `WAYLAND_DISPLAY` is set; a pen works only through Xwayland there
|
||||
|
||||
// Xwayland can forward pen input as pointer events on Wayland desktops
|
||||
#[cfg(target_os = "linux")]
|
||||
let pen_needs_x11 = xwayland_pen::opens_through_xwayland();
|
||||
let use_xwayland_for_pen = xwayland_pen::opens_through_xwayland();
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
let pen_needs_x11 = false;
|
||||
let backend = if pen_needs_x11 { craft_host::target::Backend::X11 } else { craft_host::target::Backend::from_env() };
|
||||
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())
|
||||
@@ -411,22 +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 pen_needs_x11 {
|
||||
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,
|
||||
@@ -439,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();
|
||||
@@ -465,6 +477,7 @@ 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, backend)?;
|
||||
let frame_guard = window_frame::service(cc, matches!(title_bar, TitleBar::App(_)));
|
||||
let mut app = TextureCraftApp::new(cc, session);
|
||||
@@ -485,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);
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
//! 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
|
||||
@@ -9,13 +12,18 @@
|
||||
//! 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. Replace it with a shared craft-libs crate once one exists
|
||||
//! (AGENTS.md rule 9).
|
||||
//! 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
|
||||
const NATIVE_WAYLAND_VARIABLE: &str = "TEXTURECRAFT_NATIVE_WAYLAND";
|
||||
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
|
||||
@@ -30,46 +38,94 @@ const ABS_Y: u32 = 0x01;
|
||||
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
|
||||
/// can run the window (the X11 libraries are installed and the X server answers). Says so on
|
||||
/// stderr when it does.
|
||||
/// 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));
|
||||
let xwayland_ready = || x11_libraries_available() && var("DISPLAY").is_some_and(|display| x_server_answers(&display));
|
||||
if !pen_needs_xwayland(var, pen, xwayland_ready) {
|
||||
return false;
|
||||
}
|
||||
|
||||
eprintln!("texturecraft: opening the window through Xwayland for the pen ({NATIVE_WAYLAND_VARIABLE}=1 keeps Wayland)");
|
||||
true
|
||||
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() -> bool) -> bool {
|
||||
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 && set("DISPLAY") && pen() && xwayland_ready()
|
||||
wayland && !keeps_wayland && var("DISPLAY").filter(|display| !display.is_empty()).is_some_and(|display| pen() && xwayland_ready(&display))
|
||||
}
|
||||
|
||||
/// Does the X server `display` names accept a connection? winit can't fall back to Wayland once
|
||||
/// X11 is chosen, so a `DISPLAY` left over from another session must keep the window on Wayland.
|
||||
/// Only a local display is tried, by its socket path or the abstract socket of the same name.
|
||||
fn x_server_answers(display: &str) -> bool {
|
||||
use std::os::linux::net::SocketAddrExt as _;
|
||||
use std::os::unix::net::{SocketAddr, UnixStream};
|
||||
/// 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) = local_x_socket(display) else { return false };
|
||||
UnixStream::connect(&socket).is_ok() || SocketAddr::from_abstract_name(socket.as_bytes()).and_then(|address| UnixStream::connect_addr(&address)).is_ok()
|
||||
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)
|
||||
}
|
||||
|
||||
/// The socket of a local X display (`:0`, `:0.0`, `unix:0`); `None` for a remote one
|
||||
fn local_x_socket(display: &str) -> Option<String> {
|
||||
let number = display.strip_prefix(':').or_else(|| display.strip_prefix("unix:"))?;
|
||||
let number: u32 = number.split('.').next()?.parse().ok()?;
|
||||
Some(format!("/tmp/.X11-unix/X{number}"))
|
||||
/// 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
|
||||
@@ -118,7 +174,10 @@ fn ldconfig_has(cache: &str, soname: &str) -> bool {
|
||||
};
|
||||
|
||||
cache.lines().any(|line| {
|
||||
let Some((name, rest)) = line.trim_start().split_once(' ') else { return false };
|
||||
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))
|
||||
})
|
||||
@@ -137,11 +196,11 @@ fn library_dirs(ld_library_path: Option<&str>) -> Vec<PathBuf> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A touchpad (`BTN_TOOL_FINGER`, no pen) and a Wacom pen, from `/proc/bus/input/devices`
|
||||
// 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";
|
||||
|
||||
/// A uinput keyboard (RustDesk's) claims every key, `BTN_TOOL_PEN` included, with no axes
|
||||
// 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]
|
||||
@@ -159,13 +218,47 @@ mod tests {
|
||||
}
|
||||
const WAYLAND: &[(&str, &str)] = &[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0")];
|
||||
|
||||
assert!(pen_needs_xwayland(env(WAYLAND), || true, || true));
|
||||
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.0", "unix:0", "remote:0"].map(local_x_socket), [Some("/tmp/.X11-unix/X1".into()), Some("/tmp/.X11-unix/X0".into()), None]);
|
||||
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());
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
@@ -121,6 +123,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 +138,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,
|
||||
}
|
||||
@@ -316,8 +316,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 +383,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 +442,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 +479,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 +501,7 @@ impl Project {
|
||||
display: DisplaySettings::default(),
|
||||
cameras: Vec::new(),
|
||||
swatches: Vec::new(),
|
||||
resource_sources: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -817,6 +849,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>,
|
||||
}
|
||||
@@ -281,7 +281,9 @@ impl Session {
|
||||
|
||||
fn store_bake_maps(&mut self, texture_set: usize, resolution: u32, height: u32, maps: std::collections::BTreeMap<BakedMap, Arc<Vec<f32>>>) -> Result<()> {
|
||||
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();
|
||||
}
|
||||
|
||||
|
||||
@@ -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; 14] = [
|
||||
"project.inspect",
|
||||
"project.templates",
|
||||
"project.new",
|
||||
@@ -45,6 +45,7 @@ impl CommandSpec {
|
||||
"bake.preview",
|
||||
"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)
|
||||
@@ -144,6 +145,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
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());
|
||||
|
||||
+124
-11
@@ -91,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
|
||||
),
|
||||
@@ -137,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)
|
||||
}
|
||||
@@ -158,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
|
||||
@@ -1169,7 +1208,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);
|
||||
@@ -1206,6 +1245,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(", ")))),
|
||||
@@ -1213,14 +1258,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 })
|
||||
}
|
||||
}
|
||||
@@ -1412,6 +1459,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();
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -51,6 +51,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 +74,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 +112,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,
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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,34 +44,30 @@ 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}")));
|
||||
}
|
||||
|
||||
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 (width, data) = crate::mesh_map_sampler::MeshMapSampler::new(s, cmd, ts, map, images)?.render();
|
||||
|
||||
let entry = s.doc.baked.entry(ts).or_default();
|
||||
entry.resolution = width;
|
||||
@@ -133,26 +128,6 @@ 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)?;
|
||||
@@ -160,11 +135,14 @@ fn clear(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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())));
|
||||
}
|
||||
|
||||
s.edit("Clear mesh map", |s| {
|
||||
if let Some(b) = s.doc.baked.get_mut(&ts) {
|
||||
b.maps.remove(&map);
|
||||
}
|
||||
s.doc.project.texture_set_mut(ts)?.baked.remove(&map);
|
||||
detach_imported_sources(&mut s.doc.project, ts, |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();
|
||||
}
|
||||
|
||||
@@ -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))
|
||||
}
|
||||
}
|
||||
@@ -45,6 +45,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> {
|
||||
@@ -79,19 +103,7 @@ 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));
|
||||
@@ -146,6 +158,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)) {
|
||||
@@ -172,8 +194,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)?;
|
||||
|
||||
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 }))
|
||||
}
|
||||
|
||||
@@ -255,13 +285,14 @@ 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();
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
/// 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 mut used = Vec::new();
|
||||
for set in &s.doc.project.texture_sets {
|
||||
@@ -273,10 +304,16 @@ fn remove_unused(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
used.extend(s.tool.brush.alpha_image.clone());
|
||||
used.extend(s.tool.mask_image.clone());
|
||||
used.extend(s.doc.project.display.environment_resource().map(str::to_string));
|
||||
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())
|
||||
}));
|
||||
|
||||
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();
|
||||
|
||||
@@ -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"))
|
||||
}
|
||||
@@ -462,6 +462,9 @@ pub struct Session {
|
||||
pub images: texturecraft_compose::ImageStore,
|
||||
/// Resource names whose decoded pixels match a library alpha.
|
||||
pub(crate) library_alphas: BTreeSet<String>,
|
||||
/// 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).
|
||||
@@ -549,6 +552,8 @@ impl Session {
|
||||
blending_clipboard: None,
|
||||
images: Default::default(),
|
||||
library_alphas: BTreeSet::new(),
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
resource_checks: std::collections::HashMap::new(),
|
||||
quick_mask: Default::default(),
|
||||
painting_paths: false,
|
||||
path_cache: None,
|
||||
@@ -980,6 +985,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)
|
||||
@@ -1000,6 +1006,7 @@ 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)
|
||||
|
||||
@@ -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))
|
||||
}
|
||||
|
||||
|
||||
@@ -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}");
|
||||
}
|
||||
}
|
||||
@@ -46,6 +46,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 +64,7 @@ mod perf;
|
||||
mod polygon_fill;
|
||||
mod project_recovery;
|
||||
mod rebuilt_uv_layout;
|
||||
mod resource_updater;
|
||||
mod resources_used;
|
||||
mod sample;
|
||||
mod solo;
|
||||
|
||||
@@ -0,0 +1,522 @@
|
||||
//! 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 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())
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -30,3 +30,4 @@ wasm-bindgen-futures = "0.4"
|
||||
|
||||
[dev-dependencies]
|
||||
image = { workspace = true }
|
||||
texturecraft-formats = { workspace = true }
|
||||
@@ -97,6 +97,7 @@ struct SceneConst {
|
||||
env_camera: bool,
|
||||
heights: Vec<f32>,
|
||||
ior: f32,
|
||||
dielectric_f0_scale: f32,
|
||||
/// Focus depth (0: the orbit target) and lens radius in world units (0: pinhole).
|
||||
lens: [f32; 2],
|
||||
}
|
||||
@@ -348,8 +349,8 @@ impl GpuTracer {
|
||||
};
|
||||
let same_geometry = self.geometry.as_ref().is_some_and(|g| Arc::ptr_eq(&g.mesh, &scene.mesh) && g.tri_set == scene.tri_set);
|
||||
if !same_geometry {
|
||||
let nodes: Vec<(Vec3, Vec3, u32, u32)> = scene.bvh.nodes().collect();
|
||||
if bvh_depth(&nodes).is_none_or(|d| d >= STACK) {
|
||||
let depth = bvh_depth(&scene.bvh.nodes().collect::<Vec<_>>());
|
||||
if depth.is_none_or(|depth| depth >= STACK) {
|
||||
return Err("the mesh's BVH is too deep for GPU traversal".into());
|
||||
}
|
||||
|
||||
@@ -367,24 +368,23 @@ impl GpuTracer {
|
||||
})?);
|
||||
self.bind = None;
|
||||
}
|
||||
|
||||
if !self.env.as_ref().is_some_and(|e| Arc::ptr_eq(&e.image, &scene.env)) {
|
||||
let img = &scene.env;
|
||||
let (w, h) = (img.width as usize, img.height as usize);
|
||||
let valid = w > 0 && h > 0 && img.data.len() >= w * h && img.width.max(img.height) <= limits.max_texture_dimension_2d;
|
||||
let (tw, th, rgba): (u32, u32, Vec<[f32; 4]>) =
|
||||
if valid { (img.width, img.height, img.data.iter().take(w * h).map(|c| [c[0], c[1], c[2], 1.0]).collect()) } else { (1, 1, vec![[0.0; 4]]) };
|
||||
let mut cdf = Vec::new();
|
||||
if let Some(l) = scene.light.as_ref().filter(|l| valid && l.width == w && l.height == h) {
|
||||
cdf.extend_from_slice(&l.rows);
|
||||
cdf.extend_from_slice(&l.cols);
|
||||
cdf.extend_from_slice(&l.prob);
|
||||
}
|
||||
fits("environment table", cdf.len() * 4)?;
|
||||
let light = !cdf.is_empty();
|
||||
if !light {
|
||||
cdf.push(0.0);
|
||||
}
|
||||
let valid = w > 0 && h > 0 && img.width.max(img.height) <= limits.max_texture_dimension_2d && img.data.len() >= w * h;
|
||||
let sampler = scene.light.as_ref().filter(|table| valid && table.width == w && table.height == h);
|
||||
|
||||
// The shader binds one zero when importance sampling is disabled
|
||||
let parts = sampler.map_or([&[0.0][..], &[], &[]], |table| [table.rows.as_slice(), table.cols.as_slice(), table.prob.as_slice()]);
|
||||
fits("environment table", parts.iter().map(|part| std::mem::size_of_val(*part)).sum())?;
|
||||
|
||||
let env = scoped(device, "GPU path tracing: environment upload", || {
|
||||
let (tw, th, rgba): (u32, u32, Vec<[f32; 4]>) = if valid {
|
||||
(img.width, img.height, img.data.iter().take(w * h).map(|c| [c[0], c[1], c[2], 1.0]).collect())
|
||||
} else {
|
||||
(1, 1, vec![[0.0; 4]])
|
||||
};
|
||||
let tex = device.create_texture_with_data(
|
||||
queue,
|
||||
&wgpu::TextureDescriptor {
|
||||
@@ -400,16 +400,19 @@ impl GpuTracer {
|
||||
wgpu::util::TextureDataOrder::LayerMajor,
|
||||
bytemuck::cast_slice(&rgba),
|
||||
);
|
||||
drop(rgba);
|
||||
|
||||
EnvGpu {
|
||||
image: scene.env.clone(),
|
||||
view: tex.create_view(&Default::default()),
|
||||
cdf: buffer(device, "tc_trace_cdf", bytemuck::cast_slice(&cdf)),
|
||||
light,
|
||||
cdf: buffer(device, "tc_trace_cdf", bytemuck::cast_slice(&parts.concat())),
|
||||
light: sampler.is_some(),
|
||||
}
|
||||
})?;
|
||||
self.env = Some(env);
|
||||
self.bind = None;
|
||||
}
|
||||
|
||||
self.scene = Some(SceneConst {
|
||||
spec_gloss: scene.spec_gloss,
|
||||
eps: scene.eps,
|
||||
@@ -418,6 +421,7 @@ impl GpuTracer {
|
||||
env_camera: scene.env_camera,
|
||||
heights: scene.sets.iter().map(|s| s.height_strength).collect(),
|
||||
ior: scene.ior,
|
||||
dielectric_f0_scale: scene.dielectric_f0_scale,
|
||||
lens: scene.lens.map_or([0.0; 2], |[focus, aperture]| [focus, aperture.max(0.0) * scene.radius]),
|
||||
});
|
||||
Ok(())
|
||||
@@ -609,7 +613,7 @@ impl GpuTracer {
|
||||
env: [sin, cos, 0.0, 0.0],
|
||||
sigma: sc.sigma.extend(0.0).to_array(),
|
||||
eye: cam.eye().extend(1.0).to_array(),
|
||||
lens: [if sc.lens[0] > 0.0 { sc.lens[0] } else { cam.distance }, sc.lens[1], sc.ior, 0.0],
|
||||
lens: [if sc.lens[0] > 0.0 { sc.lens[0] } else { cam.distance }, sc.lens[1], sc.ior, sc.dielectric_f0_scale],
|
||||
};
|
||||
let mut sets = [[0.0f32; 4]; 256];
|
||||
for (i, (slot, m)) in sets.iter_mut().zip(&mat.info).enumerate() {
|
||||
@@ -1017,6 +1021,33 @@ mod tests {
|
||||
assert_region_means_match("varying roughness, default base color", &gpu, &cpu.rgba8(&d), 48, 36, 3.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gpu_matches_cpu_with_ior_specular_reflectance() {
|
||||
use Channel::*;
|
||||
let Some((mut h, mut t)) = gpu() else { return };
|
||||
|
||||
// A dark, glossy dielectric shows mostly its F0
|
||||
let values = [(BaseColor, [0.02; 3]), (Metallic, [0.0; 3]), (Roughness, [0.15; 3]), (SpecularLevel, [1.0; 3])];
|
||||
let d = TraceDisplay { exposure: 1.0, aces: true, env_opacity: 0.5, denoise: false, background: crate::DEFAULT_BACKGROUND };
|
||||
let settings = TraceSettings { bounces: 4 };
|
||||
let mut sphere_brightness = Vec::new();
|
||||
|
||||
for ior_specular in [false, true] {
|
||||
let display = texturecraft_core::DisplaySettings { ior: 1.8, ior_specular, ..Default::default() };
|
||||
let mut scene = sphere_scene(&mut h, crate::ibl::environment("Studio Contrast", 256), &values);
|
||||
(scene.ior, scene.dielectric_f0_scale) = (display.ior, display.dielectric_f0_scale());
|
||||
let (_, _, gpu) = t.render(&h.device, &h.queue, &h.renderer, &scene, &camera(), &settings, &d, [48, 36], 1024).unwrap();
|
||||
let mut cpu = Tracer::new(48, 36);
|
||||
for _ in 0..1024 {
|
||||
cpu.pass(&scene, &camera(), &settings);
|
||||
}
|
||||
assert_region_means_match(&format!("IOR specular {ior_specular}"), &gpu, &cpu.rgba8(&d), 48, 36, 3.0);
|
||||
sphere_brightness.push(gpu.as_chunks::<4>().0.iter().map(|pixel| pixel[..3].iter().map(|v| u32::from(*v)).sum::<u32>()).sum::<u32>());
|
||||
}
|
||||
|
||||
assert!(sphere_brightness[1] > sphere_brightness[0], "IOR 1.8 reflects more than the legacy F0: {sphere_brightness:?}");
|
||||
}
|
||||
|
||||
/// Mean luminance of each 6×6 block of two RGBA8 renders agrees within `tol` 8-bit levels.
|
||||
fn assert_region_means_match(name: &str, a: &[u8], b: &[u8], w: usize, h: usize, tol: f32) {
|
||||
let lum = |img: &[u8], x: usize, y: usize| {
|
||||
|
||||
@@ -25,6 +25,7 @@ use std::collections::HashMap;
|
||||
|
||||
use bytemuck::{Pod, Zeroable};
|
||||
use texturecraft_compose::{DisplayKind, ImageRes};
|
||||
use texturecraft_core::project::LEGACY_DIELECTRIC_F0_SCALE;
|
||||
use texturecraft_core::{Channel, DisplaySettings, EnvAlignment, Project, ToneMapping};
|
||||
use texturecraft_geom::glam::{Mat4, Vec3};
|
||||
use texturecraft_geom::{Mesh, OrbitCamera};
|
||||
@@ -212,6 +213,8 @@ pub struct Shade {
|
||||
pub scatter: [f32; 3],
|
||||
/// Index of refraction of the Transmission channel.
|
||||
pub ior: f32,
|
||||
/// Multiplier for Specular Level when shading a dielectric in Metallic/Roughness.
|
||||
pub dielectric_f0_scale: f32,
|
||||
/// Depth of field (3D material view): focus depth along the view axis (0: the orbit
|
||||
/// target) and lens radius as a fraction of the mesh's bounding radius.
|
||||
pub dof: Option<[f32; 2]>,
|
||||
@@ -264,6 +267,7 @@ impl Shade {
|
||||
taa: d.taa,
|
||||
scatter: scatter_wrap(d),
|
||||
ior: d.ior,
|
||||
dielectric_f0_scale: d.dielectric_f0_scale(),
|
||||
dof: d.dof.enabled.then_some([d.dof.focus_distance, d.dof.aperture]),
|
||||
displacement: d.displacement,
|
||||
solo_lit: !d.solo_unlit,
|
||||
@@ -320,6 +324,7 @@ impl Default for Shade {
|
||||
taa: false,
|
||||
scatter: scatter_wrap(&DisplaySettings::default()),
|
||||
ior: 1.5,
|
||||
dielectric_f0_scale: LEGACY_DIELECTRIC_F0_SCALE,
|
||||
dof: None,
|
||||
sss_blur: None,
|
||||
refraction: false,
|
||||
@@ -2131,7 +2136,7 @@ impl Renderer {
|
||||
scatter: [s.scatter[0], s.scatter[1], s.scatter[2], if sss.is_some() { 1.0 } else { 0.0 }],
|
||||
fwd: [fwd.x, fwd.y, fwd.z, 0.0],
|
||||
disp,
|
||||
refr: [if refraction { 1.0 } else { 0.0 }, (BEHIND_LEVELS - 1) as f32, REFRACTION_DEPTH * radius, 0.0],
|
||||
refr: [if refraction { 1.0 } else { 0.0 }, (BEHIND_LEVELS - 1) as f32, REFRACTION_DEPTH * radius, s.dielectric_f0_scale],
|
||||
highlight: highlight_globals(s.highlight, HIGHLIGHT_OPACITY, s, data),
|
||||
highlight_shift: highlight_shift(frame.size),
|
||||
set_hover: highlight_globals(s.set_hover, SET_HOVER_OPACITY, s, data),
|
||||
|
||||
@@ -23,7 +23,7 @@ struct Globals {
|
||||
scatter: vec4<f32>, // xyz per-channel diffuse wrap at scattering weight 1 (0 = Lambert), w G-buffer holds the scattering light (1)
|
||||
fwd: vec4<f32>, // xyz camera view direction (unit), w -
|
||||
disp: vec4<f32>, // x displacement on (1), y world units per unit of height at strength 1, z vertex spacing in UV units, w -
|
||||
refr: vec4<f32>, // x screen-space refraction on (1), y lods of the scene behind, z refraction depth (world units), w -
|
||||
refr: vec4<f32>, // x screen-space refraction on (1), y lods of the scene behind, z refraction depth (world units), w dielectric F0 scale
|
||||
highlight: vec4<f32>, // rgb highlighted set's edge color in the scene (before exposure and tone mapping), a opacity
|
||||
highlight_shift: vec4<f32>, // xy sideways shift of each highlight line copy (clip units), zw -
|
||||
set_hover: vec4<f32>, // rgb hovered set's scene color, a opacity
|
||||
@@ -430,6 +430,9 @@ const UV_CHECKER_FINE_CELLS: f32 = 256.0;
|
||||
// Offset alpha dithering between accumulated frames
|
||||
const DITHER_FRAME_STEP: vec2<f32> = vec2<f32>(17.0, 59.0);
|
||||
|
||||
// Lit single-channel views keep the legacy specular level multiplier
|
||||
const LEGACY_DIELECTRIC_F0_SCALE: f32 = 0.08;
|
||||
|
||||
fn shade_mesh(i: VOut, front: bool) -> Shaded {
|
||||
var n_geo = normalize(i.nrm);
|
||||
if (!front) {
|
||||
@@ -548,7 +551,8 @@ fn shade_mesh(i: VOut, front: bool) -> Shaded {
|
||||
let rough = clamp(orm.g, SPECULAR_ROUGHNESS_FLOOR, 1.0);
|
||||
let metal = orm.b;
|
||||
let nov = clamp(abs(dot(n, v)), GRAZING_COSINE_FLOOR, 1.0);
|
||||
var f0 = mix(vec3<f32>(0.08 * orm.a), albedo, metal);
|
||||
let dielectric_f0_scale = select(g.refr.w, LEGACY_DIELECTRIC_F0_SCALE, solo_lit);
|
||||
var f0 = mix(vec3<f32>(dielectric_f0_scale * orm.a), albedo, metal);
|
||||
var diffuse_col = albedo * (1.0 - metal);
|
||||
if (g.material.x > 0.5 && !solo_lit) {
|
||||
// Specular color gives F0 (a solo-lit channel view keeps its neutral material); remove its energy from diffuse
|
||||
|
||||
@@ -17,7 +17,7 @@ struct Params {
|
||||
env: vec4<f32>, // sin and cos of the environment rotation
|
||||
sigma: vec4<f32>, // subsurface extinction per color channel
|
||||
eye: vec4<f32>, // camera position
|
||||
lens: vec4<f32>, // focus depth along the view axis, lens radius (0: pinhole), transmission IOR
|
||||
lens: vec4<f32>, // focus depth along the view axis, lens radius (0: pinhole), transmission IOR, dielectric F0 scale
|
||||
// Per texture set (array layer): width, height, bit mask of 1×1 placeholder kinds, height strength.
|
||||
sets: array<vec4<f32>, MAX_SETS>,
|
||||
};
|
||||
@@ -332,7 +332,7 @@ fn surface(hit: Hit, o: vec3<f32>, d: vec3<f32>) -> Surface {
|
||||
metallic = clamp(orm.b, 0.0, 1.0);
|
||||
let level = clamp(orm.a, 0.0, 1.0);
|
||||
diffuse = base * (1.0 - metallic);
|
||||
f0 = mix(vec3<f32>(0.08 * level), base, metallic);
|
||||
f0 = mix(vec3<f32>(P.lens.w * level), base, metallic);
|
||||
}
|
||||
|
||||
// The coat normal packs x and y around 128 so flat stays exact
|
||||
|
||||
+231
-75
@@ -23,7 +23,7 @@ use std::sync::Arc;
|
||||
use rayon::prelude::*;
|
||||
use texturecraft_compose::{Composite, ImageRes};
|
||||
use texturecraft_core::Channel;
|
||||
use texturecraft_core::project::{DisplaySettings, EnvAlignment, ToneMapping};
|
||||
use texturecraft_core::project::{DisplaySettings, EnvAlignment, LEGACY_DIELECTRIC_F0_SCALE, ToneMapping};
|
||||
use texturecraft_geom::glam::{Vec2, Vec3};
|
||||
use texturecraft_geom::{Bvh, Mesh, OrbitCamera};
|
||||
|
||||
@@ -63,6 +63,8 @@ pub struct TraceScene {
|
||||
pub(crate) radius: f32,
|
||||
/// Index of refraction of the Transmission channel.
|
||||
pub ior: f32,
|
||||
/// Multiplier for Specular Level in the Metallic/Roughness model.
|
||||
pub(crate) dielectric_f0_scale: f32,
|
||||
/// Thin lens: focus depth along the view axis (0: the camera's orbit target) and lens radius
|
||||
/// as a fraction of the mesh's bounding radius (the viewport's depth of field).
|
||||
pub lens: Option<[f32; 2]>,
|
||||
@@ -103,6 +105,7 @@ impl TraceScene {
|
||||
scatter_sigma: Vec3::ONE,
|
||||
radius,
|
||||
ior: 1.5,
|
||||
dielectric_f0_scale: LEGACY_DIELECTRIC_F0_SCALE,
|
||||
lens: None,
|
||||
};
|
||||
let d = DisplaySettings::default();
|
||||
@@ -137,6 +140,7 @@ impl TraceScene {
|
||||
scene.spec_gloss = display.spec_gloss;
|
||||
scene.set_scatter(display.scatter_color, display.scatter_radius);
|
||||
scene.ior = display.ior;
|
||||
scene.dielectric_f0_scale = display.dielectric_f0_scale();
|
||||
scene.lens = display.dof.enabled.then_some([display.dof.focus_distance, display.dof.aperture]);
|
||||
|
||||
scene
|
||||
@@ -201,16 +205,22 @@ impl EnvSampler {
|
||||
if w == 0 || h == 0 || env.data.len() < w * h {
|
||||
return None;
|
||||
}
|
||||
let mut weight: Vec<f32> = env.data.iter().take(w * h).map(|c| luminance(Vec3::from(*c)).max(0.0)).collect();
|
||||
for (y, row) in weight.chunks_mut(w).enumerate() {
|
||||
|
||||
let mut prob: Vec<f32> = env.data.iter().take(w * h).map(|c| luminance(Vec3::from(*c)).max(0.0)).collect();
|
||||
for (y, row) in prob.chunks_mut(w).enumerate() {
|
||||
let sin = (PI * (y as f32 + 0.5) / h as f32).sin();
|
||||
row.iter_mut().for_each(|v| *v = (*v + 1e-4) * sin);
|
||||
}
|
||||
let total: f32 = weight.iter().sum();
|
||||
|
||||
let total: f32 = prob.iter().sum();
|
||||
if !total.is_finite() || total <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
let prob: Vec<f32> = weight.iter().map(|v| v / total).collect();
|
||||
|
||||
for probability in &mut prob {
|
||||
*probability /= total;
|
||||
}
|
||||
|
||||
let mut rows = Vec::with_capacity(h);
|
||||
let mut cols = Vec::with_capacity(w * h);
|
||||
let mut acc_rows = 0.0;
|
||||
@@ -224,6 +234,7 @@ impl EnvSampler {
|
||||
cols.push(acc);
|
||||
}
|
||||
}
|
||||
|
||||
Some(EnvSampler { width: w, height: h, rows, cols, prob })
|
||||
}
|
||||
|
||||
@@ -539,100 +550,115 @@ fn rnm(base: Vec3, detail: Vec3) -> Vec3 {
|
||||
(t * t.dot(u) - u * t.z).normalize_or(Vec3::Z)
|
||||
}
|
||||
|
||||
fn surface(scene: &TraceScene, tri: u32, u: f32, v: f32, o: Vec3, d: Vec3, t: f32) -> Option<Surface> {
|
||||
let m = &scene.mesh;
|
||||
let i = tri as usize * 3;
|
||||
let idx = [*m.indices.get(i)? as usize, *m.indices.get(i + 1)? as usize, *m.indices.get(i + 2)? as usize];
|
||||
let p = idx.map(|k| m.positions.get(k).copied().unwrap_or(Vec3::ZERO));
|
||||
let mut geo = (p[1] - p[0]).cross(p[2] - p[0]).normalize_or(Vec3::Y);
|
||||
let nrm = idx.map(|k| m.normals.get(k).copied().unwrap_or(geo));
|
||||
let mut n_geo = lerp3(nrm[0], nrm[1], nrm[2], u, v).normalize_or(geo);
|
||||
let front = geo.dot(d) <= 0.0;
|
||||
fn surface(scene: &TraceScene, triangle: u32, u: f32, v: f32, origin: Vec3, direction: Vec3, distance: f32) -> Option<Surface> {
|
||||
// Match the minimum roughness in the GPU tracer
|
||||
const SPECULAR_ROUGHNESS_FLOOR: f32 = 0.045;
|
||||
const SHEEN_ROUGHNESS_FLOOR: f32 = 0.07;
|
||||
const HEIGHT_SLOPE_UV_DIVISOR: f32 = 16.0;
|
||||
|
||||
let mesh = &scene.mesh;
|
||||
let first_index = triangle as usize * 3;
|
||||
let indices = [*mesh.indices.get(first_index)? as usize, *mesh.indices.get(first_index + 1)? as usize, *mesh.indices.get(first_index + 2)? as usize];
|
||||
let points = indices.map(|index| mesh.positions.get(index).copied().unwrap_or(Vec3::ZERO));
|
||||
let mut geo = (points[1] - points[0]).cross(points[2] - points[0]).normalize_or(Vec3::Y);
|
||||
let normals = indices.map(|index| mesh.normals.get(index).copied().unwrap_or(geo));
|
||||
let mut interpolated_normal = lerp3(normals[0], normals[1], normals[2], u, v).normalize_or(geo);
|
||||
|
||||
let front = geo.dot(direction) <= 0.0;
|
||||
if !front {
|
||||
geo = -geo;
|
||||
}
|
||||
if n_geo.dot(geo) < 0.0 {
|
||||
n_geo = -n_geo;
|
||||
if interpolated_normal.dot(geo) < 0.0 {
|
||||
interpolated_normal = -interpolated_normal;
|
||||
}
|
||||
let uvs = idx.map(|k| m.uvs.get(k).copied().unwrap_or(Vec2::ZERO));
|
||||
let uv = uvs[0] * (1.0 - u - v) + uvs[1] * u + uvs[2] * v;
|
||||
let tan = idx.map(|k| m.tangents.get(k).copied().unwrap_or(texturecraft_geom::glam::Vec4::X));
|
||||
let tw = lerp3(tan[0].truncate(), tan[1].truncate(), tan[2].truncate(), u, v);
|
||||
let sign = if tan[0].w < 0.0 { -1.0 } else { 1.0 };
|
||||
|
||||
let set = scene.tri_set.get(tri as usize).and_then(|s| scene.sets.get(*s));
|
||||
// The composite texel at offset (dx, dy) from the hit.
|
||||
let texel = |s: &TraceSet, dx: i32, dy: i32| {
|
||||
let (w, h) = (s.composite.resolution.max(1) as i32, s.composite.height.max(1) as i32);
|
||||
(((uv.x * w as f32).floor() as i32 + dx).rem_euclid(w) as u32, ((uv.y * h as f32).floor() as i32 + dy).rem_euclid(h) as u32)
|
||||
};
|
||||
let ch = |c: Channel, dx: i32, dy: i32| -> [f32; 3] {
|
||||
let Some(s) = set else { return c.default_value() };
|
||||
let (x, y) = texel(s, dx, dy);
|
||||
s.composite.value(c, x, y)
|
||||
};
|
||||
let base = Vec3::from(ch(Channel::BaseColor, 0, 0));
|
||||
// A UV tile smaller than its atlas block has fewer texels per UV unit: slopes per texel shrink.
|
||||
let k = set.map_or(0.0, |s| {
|
||||
let (x, y) = texel(s, 0, 0);
|
||||
s.height_strength * s.composite.resolution as f32 / 16.0 * s.composite.block_scales.at(x, y)
|
||||
let uvs = indices.map(|index| mesh.uvs.get(index).copied().unwrap_or(Vec2::ZERO));
|
||||
let uv = uvs[0] * (1.0 - u - v) + uvs[1] * u + uvs[2] * v;
|
||||
let tangents = indices.map(|index| mesh.tangents.get(index).copied().unwrap_or(texturecraft_geom::glam::Vec4::X));
|
||||
let mesh_tangent = lerp3(tangents[0].truncate(), tangents[1].truncate(), tangents[2].truncate(), u, v);
|
||||
let sign = if tangents[0].w < 0.0 { -1.0 } else { 1.0 };
|
||||
|
||||
let surface_texel = scene.tri_set.get(triangle as usize).and_then(|index| scene.sets.get(*index)).map(|set| {
|
||||
let width = set.composite.resolution.max(1);
|
||||
let height = set.composite.height.max(1);
|
||||
let x = ((uv.x * width as f32).floor() as i32).rem_euclid(width as i32) as u32;
|
||||
let y = ((uv.y * height as f32).floor() as i32).rem_euclid(height as i32) as u32;
|
||||
(set, [width, height], [x, y])
|
||||
});
|
||||
let n_height = if k != 0.0 {
|
||||
let h = |dx, dy| ch(Channel::Height, dx, dy)[0];
|
||||
Vec3::new(-(h(1, 0) - h(-1, 0)) * 0.5 * k, (h(0, 1) - h(0, -1)) * 0.5 * k, 1.0).normalize_or(Vec3::Z)
|
||||
} else {
|
||||
Vec3::Z
|
||||
};
|
||||
let detail = (Vec3::from(ch(Channel::Normal, 0, 0)) * 2.0 - Vec3::ONE).normalize_or(Vec3::Z);
|
||||
let n_ts = rnm(n_height, detail);
|
||||
let tt = (tw - n_geo * n_geo.dot(tw)).normalize_or(n_geo.any_orthonormal_vector());
|
||||
let b = n_geo.cross(tt) * sign;
|
||||
let mut n = (tt * n_ts.x + b * n_ts.y + n_geo * n_ts.z).normalize_or(n_geo);
|
||||
if n.dot(-d) <= 0.0 {
|
||||
n = n_geo;
|
||||
let sample_channel = |channel: Channel| surface_texel.map_or_else(|| channel.default_value(), |(set, _, [x, y])| set.composite.value(channel, x, y));
|
||||
let base = Vec3::from(sample_channel(Channel::BaseColor));
|
||||
|
||||
// A unit height across one sixteenth of the UV width tilts 45°
|
||||
// A smaller tile reduces the number of texels across that span
|
||||
let height_normal = surface_texel.map_or(Vec3::Z, |(set, [width, height], [x, y])| {
|
||||
let strength = set.height_strength * set.composite.resolution as f32 / HEIGHT_SLOPE_UV_DIVISOR * set.composite.block_scales.at(x, y);
|
||||
if strength == 0.0 {
|
||||
return Vec3::Z;
|
||||
}
|
||||
|
||||
// Neighbors wrap independently across each axis
|
||||
let previous = |position, size| if position == 0 { size - 1 } else { position - 1 };
|
||||
let next = |position, size| if position + 1 == size { 0 } else { position + 1 };
|
||||
let height_at = |x, y| set.composite.value(Channel::Height, x, y)[0];
|
||||
let slope_x = height_at(next(x, width), y) - height_at(previous(x, width), y);
|
||||
let slope_y = height_at(x, next(y, height)) - height_at(x, previous(y, height));
|
||||
Vec3::new(-slope_x * 0.5 * strength, slope_y * 0.5 * strength, 1.0).normalize_or(Vec3::Z)
|
||||
});
|
||||
|
||||
let detail = (Vec3::from(sample_channel(Channel::Normal)) * 2.0 - Vec3::ONE).normalize_or(Vec3::Z);
|
||||
let tangent_normal = rnm(height_normal, detail);
|
||||
let base_tangent = (mesh_tangent - interpolated_normal * interpolated_normal.dot(mesh_tangent)).normalize_or(interpolated_normal.any_orthonormal_vector());
|
||||
let bitangent = interpolated_normal.cross(base_tangent) * sign;
|
||||
let mut normal =
|
||||
(base_tangent * tangent_normal.x + bitangent * tangent_normal.y + interpolated_normal * tangent_normal.z).normalize_or(interpolated_normal);
|
||||
if normal.dot(-direction) <= 0.0 {
|
||||
normal = interpolated_normal;
|
||||
}
|
||||
let scalar = |c: Channel| ch(c, 0, 0)[0].clamp(0.0, 1.0);
|
||||
|
||||
let scalar = |channel| sample_channel(channel)[0].clamp(0.0, 1.0);
|
||||
let (sin, cos) = (scalar(Channel::AnisotropyAngle) * PI).sin_cos();
|
||||
let turned = tt * cos + b * sin;
|
||||
let tangent = (turned - n * n.dot(turned)).normalize_or(n.any_orthonormal_vector());
|
||||
// Glossiness replaces roughness wherever a set has it (as in the viewport).
|
||||
let roughness = match set {
|
||||
Some(s) if s.composite.channels.contains_key(&Channel::Glossiness) => 1.0 - ch(Channel::Glossiness, 0, 0)[0],
|
||||
_ => ch(Channel::Roughness, 0, 0)[0],
|
||||
let turned_tangent = base_tangent * cos + bitangent * sin;
|
||||
let tangent = (turned_tangent - normal * normal.dot(turned_tangent)).normalize_or(normal.any_orthonormal_vector());
|
||||
|
||||
// Match the viewport's preference for Glossiness when both channels exist
|
||||
let roughness = match surface_texel {
|
||||
Some((set, _, _)) if set.composite.channels.contains_key(&Channel::Glossiness) => 1.0 - sample_channel(Channel::Glossiness)[0],
|
||||
_ => sample_channel(Channel::Roughness)[0],
|
||||
};
|
||||
let (diffuse, f0, metallic) = if scene.spec_gloss {
|
||||
let f0 = Vec3::from(ch(Channel::Specular, 0, 0)).clamp(Vec3::ZERO, Vec3::ONE);
|
||||
let f0 = Vec3::from(sample_channel(Channel::Specular)).clamp(Vec3::ZERO, Vec3::ONE);
|
||||
(base * (1.0 - f0.max_element()), f0, 0.0)
|
||||
} else {
|
||||
let metallic = ch(Channel::Metallic, 0, 0)[0].clamp(0.0, 1.0);
|
||||
let level = ch(Channel::SpecularLevel, 0, 0)[0].clamp(0.0, 1.0);
|
||||
(base * (1.0 - metallic), Vec3::splat(0.08 * level).lerp(base, metallic), metallic)
|
||||
let metallic = sample_channel(Channel::Metallic)[0].clamp(0.0, 1.0);
|
||||
let level = sample_channel(Channel::SpecularLevel)[0].clamp(0.0, 1.0);
|
||||
(base * (1.0 - metallic), Vec3::splat(scene.dielectric_f0_scale * level).lerp(base, metallic), metallic)
|
||||
};
|
||||
let coat_base = if n_geo.dot(-d) > 0.0 { n_geo } else { geo };
|
||||
let coat_n = match set {
|
||||
Some(s) if s.composite.channels.contains_key(&Channel::CoatNormal) => {
|
||||
let c = (Vec3::from(ch(Channel::CoatNormal, 0, 0)) * 2.0 - Vec3::ONE).normalize_or(Vec3::Z);
|
||||
let turned = (tt * c.x + b * c.y + coat_base * c.z).normalize_or(coat_base);
|
||||
if turned.dot(-d) > 0.0 { turned } else { coat_base }
|
||||
let coat_base = if interpolated_normal.dot(-direction) > 0.0 { interpolated_normal } else { geo };
|
||||
let coat_n = match surface_texel {
|
||||
Some((set, _, _)) if set.composite.channels.contains_key(&Channel::CoatNormal) => {
|
||||
let detail = (Vec3::from(sample_channel(Channel::CoatNormal)) * 2.0 - Vec3::ONE).normalize_or(Vec3::Z);
|
||||
let tilted = (base_tangent * detail.x + bitangent * detail.y + coat_base * detail.z).normalize_or(coat_base);
|
||||
if tilted.dot(-direction) > 0.0 { tilted } else { coat_base }
|
||||
}
|
||||
_ => coat_base,
|
||||
};
|
||||
|
||||
Some(Surface {
|
||||
pos: o + d * t,
|
||||
pos: origin + direction * distance,
|
||||
geo,
|
||||
n,
|
||||
n: normal,
|
||||
tangent,
|
||||
diffuse,
|
||||
f0,
|
||||
roughness: roughness.clamp(0.045, 1.0),
|
||||
emissive: Vec3::from(ch(Channel::Emissive, 0, 0)),
|
||||
opacity: ch(Channel::Opacity, 0, 0)[0].clamp(0.0, 1.0),
|
||||
roughness: roughness.clamp(SPECULAR_ROUGHNESS_FLOOR, 1.0),
|
||||
emissive: Vec3::from(sample_channel(Channel::Emissive)),
|
||||
opacity: sample_channel(Channel::Opacity)[0].clamp(0.0, 1.0),
|
||||
anisotropy: scalar(Channel::AnisotropyLevel),
|
||||
coat: scalar(Channel::CoatWeight),
|
||||
coat_roughness: scalar(Channel::CoatRoughness).max(0.045),
|
||||
coat_roughness: scalar(Channel::CoatRoughness).max(SPECULAR_ROUGHNESS_FLOOR),
|
||||
coat_n,
|
||||
sheen: Vec3::from(ch(Channel::SheenColor, 0, 0)).clamp(Vec3::ZERO, Vec3::ONE) * scalar(Channel::SheenWeight),
|
||||
sheen_roughness: scalar(Channel::SheenRoughness).max(0.07),
|
||||
sheen: Vec3::from(sample_channel(Channel::SheenColor)).clamp(Vec3::ZERO, Vec3::ONE) * scalar(Channel::SheenWeight),
|
||||
sheen_roughness: scalar(Channel::SheenRoughness).max(SHEEN_ROUGHNESS_FLOOR),
|
||||
scatter: scalar(Channel::ScatterWeight),
|
||||
transmission: scalar(Channel::Transmission) * (1.0 - metallic),
|
||||
base: base.clamp(Vec3::ZERO, Vec3::ONE),
|
||||
@@ -1412,4 +1438,134 @@ mod tests {
|
||||
assert!(blurred > 3 * pinhole.max(10), "out of focus: {pinhole} -> {blurred} edge pixels");
|
||||
assert!(focused < pinhole + pinhole / 2 + 10, "the silhouette (about the focus depth) stays sharp: {pinhole} -> {focused}");
|
||||
}
|
||||
|
||||
/// Specular Level 0.5 stands for OpenPBR's default specular weight of 1
|
||||
const OPENPBR_DEFAULT_SPECULAR_LEVEL: f32 = 0.5;
|
||||
/// A non-default IOR for the opt-in comparisons
|
||||
const DENSE_IOR: f32 = 1.8;
|
||||
/// The 32-bit export and the shading read the same 16-bit texel: only float rounding separates them
|
||||
const F0_TOLERANCE: f32 = 1e-5;
|
||||
|
||||
/// One texture set holding a uniform dielectric with both shader models' channels.
|
||||
fn dielectric_composite() -> Composite {
|
||||
use Channel::*;
|
||||
let values = [
|
||||
(BaseColor, [0.1; 3]),
|
||||
(Metallic, [0.0; 3]),
|
||||
(Roughness, [0.3; 3]),
|
||||
(SpecularLevel, [OPENPBR_DEFAULT_SPECULAR_LEVEL; 3]),
|
||||
(Specular, [0.3, 0.2, 0.1]),
|
||||
(Glossiness, [0.7; 3]),
|
||||
];
|
||||
let channels: Vec<Channel> = values.iter().map(|(channel, _)| *channel).collect();
|
||||
let mut composite = Composite::new(&channels, 8);
|
||||
for (channel, value) in values {
|
||||
let raw: Vec<u16> = value[..channel.components()].iter().map(|v| texturecraft_texel::to_u16(*v)).collect();
|
||||
let image = composite.channels.get_mut(&channel).unwrap();
|
||||
for y in 0..8 {
|
||||
for x in 0..8 {
|
||||
image.set(x, y, &raw);
|
||||
}
|
||||
}
|
||||
}
|
||||
composite
|
||||
}
|
||||
|
||||
/// A sphere covered by [`dielectric_composite`] under `display`.
|
||||
fn dielectric_scene(display: &DisplaySettings) -> TraceScene {
|
||||
let mesh = Arc::new(primitives::sphere(1.0, 32, 16));
|
||||
let bvh = Arc::new(Bvh::new(&mesh));
|
||||
let sets = vec![TraceSet { material: 0, composite: dielectric_composite(), height_strength: 0.0 }];
|
||||
TraceScene::for_display_env(mesh, bvh, sets, display, Arc::new(crate::ibl::environment("Studio Soft", 32)))
|
||||
}
|
||||
|
||||
/// The F0 the CPU tracer shades the sphere's front with.
|
||||
fn shaded_f0(display: &DisplaySettings) -> Vec3 {
|
||||
let scene = dielectric_scene(display);
|
||||
let (origin, direction) = (Vec3::new(0.0, 0.0, 4.0), Vec3::NEG_Z);
|
||||
let hit = scene.bvh.closest(origin, direction, f32::MAX).unwrap();
|
||||
surface(&scene, hit.tri, hit.u, hit.v, origin, direction, hit.t).unwrap().f0
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn height_normals_sample_across_both_texture_edges() {
|
||||
let mut mesh = primitives::plane(1.0, 1);
|
||||
mesh.uvs.fill(Vec2::ZERO);
|
||||
let mesh = Arc::new(mesh);
|
||||
let bvh = Arc::new(Bvh::new(&mesh));
|
||||
let mut composite = Composite::with_size(&[Channel::Height], 4, 5);
|
||||
let height = composite.channels.get_mut(&Channel::Height).unwrap();
|
||||
height.set(3, 0, &[u16::MAX]);
|
||||
height.set(0, 4, &[u16::MAX]);
|
||||
let sets = vec![TraceSet { material: 0, composite, height_strength: 1.0 }];
|
||||
let scene = TraceScene::new(mesh, bvh, sets, Arc::new(crate::ibl::environment("Studio Soft", 8)), 0.0);
|
||||
|
||||
let normal = surface(&scene, 0, 0.25, 0.25, Vec3::Y, Vec3::NEG_Y, 1.0).unwrap().n;
|
||||
|
||||
assert!(normal.x.abs() > f32::EPSILON && normal.z.abs() > f32::EPSILON, "the opposite edges tilt both axes: {normal}");
|
||||
}
|
||||
|
||||
/// The F0 map a 32-bit float export writes for [`dielectric_composite`] under `display`.
|
||||
fn exported_f0(display: &DisplaySettings) -> f32 {
|
||||
use texturecraft_formats::{Dest, ExportInput, ExportOptions, ExportPreset, FileFormat, MapSpec, SourceRef, VirtualMap};
|
||||
|
||||
let composite = dielectric_composite();
|
||||
let mut project = texturecraft_core::Project::new("F0", "builtin:sphere");
|
||||
let mut set = texturecraft_core::TextureSet::new("Set", 0, composite.resolution);
|
||||
set.channels = composite.channels.keys().map(|channel| (*channel, texturecraft_core::ChannelFormat::default_for(*channel))).collect();
|
||||
project.texture_sets.push(set);
|
||||
project.display = display.clone();
|
||||
let coverage = vec![true; (composite.resolution * composite.resolution) as usize];
|
||||
let input = ExportInput { project: &project, ts: 0, composite: &composite, baked: &Default::default(), coverage: &coverage, mesh_name: "sphere" };
|
||||
let f0 = |component| SourceRef::Virtual { map: VirtualMap::F0, component };
|
||||
let channels = vec![(Dest::R, f0(0)), (Dest::G, f0(1)), (Dest::B, f0(2))];
|
||||
let map = MapSpec { file: "f0".into(), format: FileFormat::Exr, bit_depth: 32, channels, inverted: Vec::new() };
|
||||
let options = ExportOptions::new(ExportPreset { name: "F0".into(), maps: vec![map] });
|
||||
|
||||
let files = texturecraft_formats::render_maps(&input, &options).unwrap();
|
||||
|
||||
let image = image::load_from_memory_with_format(&files[0].bytes, image::ImageFormat::OpenExr).unwrap().to_rgb32f();
|
||||
image.get_pixel(4, 4)[0]
|
||||
}
|
||||
|
||||
fn ior_display(ior: f32, ior_specular: bool, spec_gloss: bool) -> DisplaySettings {
|
||||
DisplaySettings { ior, ior_specular, spec_gloss, ..DisplaySettings::default() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exported_f0_matches_the_metallic_roughness_shading_in_both_modes() {
|
||||
let (legacy, opt_in) = (ior_display(DENSE_IOR, false, false), ior_display(DENSE_IOR, true, false));
|
||||
|
||||
// OpenPBR: at specular weight 1 the dielectric F0 is the Fresnel reflectance of the IOR
|
||||
let fresnel = ((DENSE_IOR - 1.0) / (DENSE_IOR + 1.0)).powi(2);
|
||||
|
||||
let (legacy_shaded, legacy_exported) = (shaded_f0(&legacy), exported_f0(&legacy));
|
||||
let (opt_in_shaded, opt_in_exported) = (shaded_f0(&opt_in), exported_f0(&opt_in));
|
||||
let default_ior_shaded = shaded_f0(&ior_display(1.5, true, false));
|
||||
|
||||
for (mode, shaded, exported) in [("legacy", legacy_shaded, legacy_exported), ("IOR", opt_in_shaded, opt_in_exported)] {
|
||||
assert!(shaded.abs_diff_eq(Vec3::splat(exported), F0_TOLERANCE), "{mode}: shaded {shaded}, exported {exported}");
|
||||
}
|
||||
assert!((legacy_exported - LEGACY_DIELECTRIC_F0_SCALE * OPENPBR_DEFAULT_SPECULAR_LEVEL).abs() < F0_TOLERANCE, "legacy {legacy_exported}");
|
||||
assert!((opt_in_exported - fresnel).abs() < F0_TOLERANCE, "IOR {DENSE_IOR}: {opt_in_exported}, Fresnel {fresnel}");
|
||||
assert!(opt_in_exported > legacy_exported, "IOR {DENSE_IOR} reflects more than the legacy 1.5 equivalent");
|
||||
assert!(default_ior_shaded.abs_diff_eq(legacy_shaded, F0_TOLERANCE), "IOR 1.5 keeps the legacy reflectance: {default_ior_shaded}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn specular_glossiness_shading_ignores_the_ior_specular_setting() {
|
||||
let (off, on) = (ior_display(DENSE_IOR, false, true), ior_display(DENSE_IOR, true, true));
|
||||
let render = |display: &DisplaySettings| {
|
||||
let (scene, mut tracer) = (dielectric_scene(display), Tracer::new(24, 16));
|
||||
for _ in 0..2 {
|
||||
tracer.pass(&scene, &camera(), &TraceSettings::default());
|
||||
}
|
||||
tracer.rgba8(&TraceDisplay::from_display(display))
|
||||
};
|
||||
|
||||
let (off_f0, on_f0) = (shaded_f0(&off), shaded_f0(&on));
|
||||
|
||||
assert_eq!(on_f0, off_f0, "the Specular color gives F0");
|
||||
assert_eq!(render(&on), render(&off));
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
use texturecraft_compose::{DisplayKind, ImageRes};
|
||||
use texturecraft_core::DisplaySettings;
|
||||
use texturecraft_geom::glam::Vec3;
|
||||
use texturecraft_geom::{OrbitCamera, primitives};
|
||||
use texturecraft_render::headless::Headless;
|
||||
@@ -789,6 +790,31 @@ fn specular_glossiness_takes_f0_from_the_specular_color() {
|
||||
assert!(sg.mean(200, 100, 280, 180) > 20.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ior_specular_changes_dielectric_reflections_in_the_viewport_only_for_metallic_roughness() {
|
||||
let Some((mut h, frame)) = setup() else { return };
|
||||
|
||||
// A dark, glossy dielectric at full Specular Level shows mostly its F0
|
||||
fill(&mut h, &[0, 1], DisplayKind::BaseColor, &[5, 5, 5, 255]);
|
||||
fill(&mut h, &[0, 1], DisplayKind::Orm, &[255, 38, 0, 255]);
|
||||
let mut view = |ior: f32, ior_specular: bool, spec_gloss: bool, name: &str| {
|
||||
// Without temporal anti-aliasing each frame is the same still image
|
||||
let display = DisplaySettings { ior, ior_specular, spec_gloss, taa: false, ..DisplaySettings::default() };
|
||||
render(&mut h, &Frame { shade: Shade::from_display(&display), ..frame.clone() }, name)
|
||||
};
|
||||
|
||||
let legacy = view(1.8, false, false, "ior_specular_off");
|
||||
let opt_in = view(1.8, true, false, "ior_specular_on");
|
||||
let default_ior = view(1.5, true, false, "ior_specular_default_ior");
|
||||
let spec_gloss_off = view(1.8, false, true, "ior_specular_spec_gloss_off");
|
||||
let spec_gloss_on = view(1.8, true, true, "ior_specular_spec_gloss_on");
|
||||
|
||||
let (brighter, darker) = (opt_in.mean(200, 100, 280, 180), legacy.mean(200, 100, 280, 180));
|
||||
assert!(brighter > darker + 2.0, "IOR 1.8 reflects more than the legacy F0 ({brighter} vs {darker})");
|
||||
assert_same(&default_ior, &legacy, "IOR 1.5 keeps the legacy reflectance");
|
||||
assert_eq!(spec_gloss_on.px, spec_gloss_off.px, "Specular/Glossiness takes F0 from the Specular color");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lit_metallic_view_ignores_the_specular_channel() {
|
||||
let Some((mut h, frame)) = setup() else { return };
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
//! Where a project's autosave copy goes. Each project has a file of its own, `<stem>-copy-<suffix>.tcraft`: a project's
|
||||
//! name comes from its mesh file, so the name alone would let projects made from one mesh overwrite each other's copy
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use texturecraft_engine::core::PROJECT_EXT;
|
||||
use texturecraft_engine::formats::export::sanitize_file_stem;
|
||||
|
||||
use crate::TextureCraftApp;
|
||||
|
||||
/// Hex digits of a copy's suffix
|
||||
const SUFFIX_DIGITS: usize = 16;
|
||||
|
||||
/// Between a copy's stem and its suffix, so a user's own file named like `report-20240115` is not taken for a copy
|
||||
const COPY_MARK: &str = "-copy-";
|
||||
|
||||
/// The longest stem kept, so the suffix and the temporary files of a save still fit a file name
|
||||
const MAX_STEM_CHARS: usize = 170;
|
||||
|
||||
impl TextureCraftApp {
|
||||
/// The open project's autosave file in `folder`. A saved project's copy is named after its file and stays the
|
||||
/// same across restarts; an unsaved project gets one that no other open project or running instance shares
|
||||
pub(crate) fn autosave_path(&mut self, folder: &Path) -> PathBuf {
|
||||
let Some(saved) = self.session.path.as_deref() else {
|
||||
let project = self.session.project_id;
|
||||
let suffix = match self.unsaved_autosave_suffix {
|
||||
Some((owner, suffix)) if owner == project => suffix,
|
||||
_ => {
|
||||
let suffix = new_suffix(project);
|
||||
self.unsaved_autosave_suffix = Some((project, suffix));
|
||||
suffix
|
||||
}
|
||||
};
|
||||
return folder.join(file_name(&self.session.doc.project.name, suffix));
|
||||
};
|
||||
|
||||
let saved = absolute(Path::new(saved));
|
||||
|
||||
// A project opened from its autosave copy keeps writing there, rather than chaining suffixes
|
||||
if is_copy_in(&saved, &absolute(folder)) {
|
||||
return saved;
|
||||
}
|
||||
|
||||
let stem = saved.file_stem().map_or_else(|| self.session.doc.project.name.clone(), |stem| stem.to_string_lossy().into_owned());
|
||||
folder.join(file_name(&stem, hash(saved.as_os_str().as_encoded_bytes())))
|
||||
}
|
||||
}
|
||||
|
||||
fn file_name(stem: &str, suffix: u64) -> String {
|
||||
let stem: String = sanitize_file_stem(stem).chars().take(MAX_STEM_CHARS).collect();
|
||||
format!("{stem}{COPY_MARK}{suffix:0SUFFIX_DIGITS$x}.{PROJECT_EXT}")
|
||||
}
|
||||
|
||||
/// `path` made absolute, as given when that fails
|
||||
fn absolute(path: &Path) -> PathBuf {
|
||||
std::path::absolute(path).unwrap_or_else(|_| path.to_path_buf())
|
||||
}
|
||||
|
||||
/// `path` with links and, on Windows, the verbatim prefix resolved so two spellings of one folder compare equal; made absolute when that fails
|
||||
fn resolved(path: &Path) -> PathBuf {
|
||||
std::fs::canonicalize(path).unwrap_or_else(|_| absolute(path))
|
||||
}
|
||||
|
||||
/// Whether `path` is an autosave copy of `folder`: a project file there whose name ends in the copy mark and a suffix
|
||||
fn is_copy_in(path: &Path, folder: &Path) -> bool {
|
||||
let suffix = path.file_stem().and_then(|stem| stem.to_str()).and_then(|stem| stem.rsplit_once(COPY_MARK)).map(|(_, suffix)| suffix);
|
||||
path.parent().is_some_and(|parent| resolved(parent) == resolved(folder))
|
||||
&& path.extension().is_some_and(|extension| extension == PROJECT_EXT)
|
||||
&& suffix.is_some_and(|suffix| suffix.len() == SUFFIX_DIGITS && suffix.bytes().all(|digit| digit.is_ascii_hexdigit()))
|
||||
}
|
||||
|
||||
/// A suffix for the unsaved project `project`: from this process and the moment, so another instance or a later run
|
||||
/// takes a different one
|
||||
fn new_suffix(project: u64) -> u64 {
|
||||
let now = chrono::Utc::now().timestamp_nanos_opt().unwrap_or_default();
|
||||
let mut seed = Vec::new();
|
||||
seed.extend_from_slice(&std::process::id().to_le_bytes());
|
||||
seed.extend_from_slice(&now.to_le_bytes());
|
||||
seed.extend_from_slice(&project.to_le_bytes());
|
||||
hash(&seed)
|
||||
}
|
||||
|
||||
/// 64-bit FNV-1a: the same bytes give the same suffix in every release, which the standard hasher does not promise.
|
||||
/// Wide enough that two paths are very unlikely to share one
|
||||
fn hash(bytes: &[u8]) -> u64 {
|
||||
bytes.iter().fold(0xcbf2_9ce4_8422_2325, |hash, byte| (hash ^ u64::from(*byte)).wrapping_mul(0x0000_0100_0000_01b3))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use texturecraft_engine::Session;
|
||||
use texturecraft_engine::geom::primitives;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn project(name: &str) -> Session {
|
||||
Session::new_project(name, primitives::cube(1.0), "builtin:cube", None, 128).unwrap()
|
||||
}
|
||||
|
||||
fn app(session: Session) -> TextureCraftApp {
|
||||
TextureCraftApp::new(&eframe::CreationContext::_new_kittest(egui::Context::default()), session)
|
||||
}
|
||||
|
||||
fn name_of(path: &Path) -> &str {
|
||||
path.file_name().and_then(|name| name.to_str()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsaved_projects_with_one_name_get_different_copies_that_stay_put() {
|
||||
let folder = Path::new("autosave");
|
||||
let mut first = app(project("hero"));
|
||||
let mut second = app(project("hero"));
|
||||
|
||||
let (one, other) = (first.autosave_path(folder), second.autosave_path(folder));
|
||||
|
||||
assert_ne!(one, other, "another instance never writes the same file");
|
||||
assert!(name_of(&one).starts_with("hero-") && name_of(&one).ends_with(".tcraft"), "{one:?}");
|
||||
assert_eq!(one.parent(), Some(folder));
|
||||
assert_eq!(first.autosave_path(folder), one, "the next autosave replaces this project's copy");
|
||||
|
||||
first.session.switch_to(project("hero"));
|
||||
assert_ne!(first.autosave_path(folder), one, "a new project of the same name starts its own copy");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_saved_project_names_its_copy_after_its_file_and_keeps_it_across_restarts() {
|
||||
let folder = Path::new("autosave");
|
||||
let copy_of = |saved: &str| {
|
||||
let mut app = app(project("hero"));
|
||||
app.session.path = Some(saved.to_string());
|
||||
app.autosave_path(folder)
|
||||
};
|
||||
|
||||
let first = copy_of("work/Hero_v1.tcraft");
|
||||
let second = copy_of("work/Hero_v2.tcraft");
|
||||
let same_name_elsewhere = copy_of("backup/Hero_v1.tcraft");
|
||||
|
||||
assert!(name_of(&first).starts_with("Hero_v1-"), "{first:?}");
|
||||
assert_ne!(first, second);
|
||||
assert_ne!(first, same_name_elsewhere, "files of one name in two folders keep two copies");
|
||||
assert_eq!(copy_of("work/Hero_v1.tcraft"), first, "a later run finds the same copy");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_project_opened_from_its_copy_keeps_writing_to_it() {
|
||||
let folder = std::env::temp_dir().join("tc-autosave");
|
||||
let mut app = app(project("hero"));
|
||||
let copy = app.autosave_path(&folder);
|
||||
|
||||
app.session.path = Some(copy.display().to_string());
|
||||
assert_eq!(app.autosave_path(&folder), copy);
|
||||
|
||||
// A file there that is not a copy is the user's own: autosave leaves it alone
|
||||
let own = folder.join("hero.tcraft");
|
||||
app.session.path = Some(own.display().to_string());
|
||||
assert_ne!(app.autosave_path(&folder), own);
|
||||
|
||||
let dated = folder.join("hero-20240115.tcraft");
|
||||
app.session.path = Some(dated.display().to_string());
|
||||
assert_ne!(app.autosave_path(&folder), dated);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn suffixes_have_a_fixed_width_and_long_names_are_cut() {
|
||||
let narrow = file_name("hero", 1);
|
||||
let wide = file_name("hero", u64::MAX);
|
||||
assert_eq!(narrow.len(), wide.len(), "every suffix has the same width");
|
||||
assert!(file_name(&"a".repeat(500), 1).len() < 200);
|
||||
}
|
||||
}
|
||||
@@ -2787,12 +2787,12 @@ fn fill_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn open_link_in_materialcraft(app: &mut TextureCraftApp, layer: LayerId, link: &texturecraft_engine::core::MaterialLink) {
|
||||
let ext = texturecraft_engine::link_cmds::source_extension(&link.package);
|
||||
let path = std::env::temp_dir().join(format!("{}.{ext}", texturecraft_engine::formats::export::sanitize_file_stem(&link.name)));
|
||||
let file_name = format!("{}.{ext}", texturecraft_engine::formats::export::sanitize_file_stem(&link.name));
|
||||
let opened = app
|
||||
.session
|
||||
.link_package(layer)
|
||||
.and_then(|package| std::fs::write(&path, package.as_slice()).map_err(|err| texturecraft_engine::EngineError::Other(err.to_string())))
|
||||
.and_then(|()| texturecraft_engine::link_cmds::open_in_materialcraft(&path));
|
||||
.and_then(|package| texturecraft_engine::link_cmds::stage_handoff_package(&file_name, package.as_slice()))
|
||||
.and_then(|path| texturecraft_engine::link_cmds::open_in_materialcraft(&path));
|
||||
match opened {
|
||||
Ok(()) => app.toast(tr("Opened in MaterialCraft: use File > Send to TextureCraft there to bring your changes back"), false),
|
||||
Err(e) => app.toast(e.to_string(), true),
|
||||
|
||||
@@ -48,6 +48,7 @@ fn install_with(ctx: &egui::Context, shell: ShellInfo, windows: Arc<dyn WindowSy
|
||||
if let Some(frame) = frame {
|
||||
spec = spec.frame(frame);
|
||||
}
|
||||
|
||||
embed::install(ctx, spec, &ui_fonts()).map(drop).map_err(|error| format!("the UI runtime could not be installed: {error}"))
|
||||
}
|
||||
|
||||
|
||||
@@ -261,6 +261,9 @@ mod tests {
|
||||
keys.extend(BlendMode::all().map(|mode| mode.label()));
|
||||
keys.extend(texturecraft_engine::formats::export::VirtualMap::ALL.iter().map(|map| map.label()));
|
||||
keys.extend(texturecraft_engine::Tool::ALL.iter().map(|tool| tool.label()));
|
||||
keys.extend(texturecraft_engine::ResourceStatus::ALL.iter().map(|status| status.label()));
|
||||
let notice = crate::toast_action::ToastAction::UpdateResources { project: 0 };
|
||||
keys.extend([notice.label(), notice.accessible_name()]);
|
||||
keys.extend(texturecraft_engine::HISTORY_TEMPLATES);
|
||||
keys.extend(ProceduralKind::ALL.iter().map(|kind| kind.label()));
|
||||
keys.extend(GeneratorKind::ALL.iter().map(|kind| kind.label()));
|
||||
|
||||
+61
-10
@@ -10,6 +10,8 @@
|
||||
mod anchor_properties;
|
||||
mod angle_dial;
|
||||
mod ask;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
mod autosave_name;
|
||||
mod bake_job;
|
||||
pub mod bake_mode;
|
||||
mod bake_preset;
|
||||
@@ -141,6 +143,8 @@ mod resolution_band;
|
||||
mod resource_panel;
|
||||
mod resource_picker;
|
||||
mod resource_picker_item;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
mod resources_updater;
|
||||
mod round_gizmo;
|
||||
mod running_bake;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -176,6 +180,7 @@ pub mod thumbs;
|
||||
mod tile_edits;
|
||||
mod tile_picture;
|
||||
pub mod titlebar;
|
||||
pub mod toast_action;
|
||||
pub mod toolbar;
|
||||
pub mod ui_state_store;
|
||||
pub mod unavailable;
|
||||
@@ -257,6 +262,8 @@ pub struct Toast {
|
||||
pub error: bool,
|
||||
pub until: f64,
|
||||
pub show_log: bool,
|
||||
/// A button after the text that acts on the notice
|
||||
pub action: Option<toast_action::ToastAction>,
|
||||
announce: bool,
|
||||
}
|
||||
|
||||
@@ -362,10 +369,19 @@ pub struct TextureCraftApp {
|
||||
/// When the next autosave is due (seconds of app time; desktop only).
|
||||
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
|
||||
next_autosave: f64,
|
||||
/// The unsaved project (its id) and the suffix of its autosave copy.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
unsaved_autosave_suffix: Option<(u64, u64)>,
|
||||
/// The brightness and accent the style was last built for.
|
||||
styled: Option<(theme::Brightness, theme::Accent)>,
|
||||
/// Whether the window had focus last frame.
|
||||
focused: bool,
|
||||
/// The outdated resources the last "changed on disk" notice named, so an unchanged set is not announced again
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) resources_notified: std::collections::BTreeSet<String>,
|
||||
/// The project the Resources Updater last checked on opening (see `resources_updater::follow_project`)
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) resources_project: Option<u64>,
|
||||
/// The update check and prompt (desktop only).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) updates_rt: updates_ui::Runtime,
|
||||
@@ -505,9 +521,15 @@ impl TextureCraftApp {
|
||||
fired_clipboard: Vec::new(),
|
||||
last_time: 0.0,
|
||||
next_autosave,
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
unsaved_autosave_suffix: None,
|
||||
styled: None,
|
||||
focused: true,
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
resources_notified: std::collections::BTreeSet::new(),
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
resources_project: None,
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
updates_rt: updates_ui::Runtime::default(),
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
file_dialogs: file_dialogs::FileDialogs::new(cc.egui_ctx.clone()),
|
||||
@@ -665,13 +687,24 @@ impl TextureCraftApp {
|
||||
}
|
||||
|
||||
pub fn toast(&mut self, text: impl Into<String>, error: bool) {
|
||||
self.toasts.push(Toast { text: text.into(), error, until: self.last_time + if error { 6.0 } else { 3.0 }, show_log: false, announce: false });
|
||||
const ERROR_SECONDS: f64 = 6.0;
|
||||
const NOTICE_SECONDS: f64 = 3.0;
|
||||
let until = self.last_time + if error { ERROR_SECONDS } else { NOTICE_SECONDS };
|
||||
|
||||
self.toasts.push(Toast { text: text.into(), error, until, show_log: false, action: None, announce: false });
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn announce_latest_toast(&mut self) {
|
||||
if let Some(toast) = self.toasts.last_mut() {
|
||||
toast.announce = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// An error toast that stays until the user dismisses it (for a problem that persists and
|
||||
/// is reported once, like a texture set the GPU could not hold).
|
||||
pub fn toast_sticky(&mut self, text: impl Into<String>) {
|
||||
self.toasts.push(Toast { text: text.into(), error: true, until: f64::INFINITY, show_log: false, announce: false });
|
||||
self.toasts.push(Toast { text: text.into(), error: true, until: f64::INFINITY, show_log: false, action: None, announce: false });
|
||||
}
|
||||
|
||||
/// Bake texture sets in the background, one after another; invalid set indices show an error without starting anything
|
||||
@@ -1073,11 +1106,7 @@ impl TextureCraftApp {
|
||||
|
||||
self.next_autosave = now + period;
|
||||
let dir = user_dir("autosave");
|
||||
let path = dir.join(format!(
|
||||
"{}.{}",
|
||||
texturecraft_engine::formats::export::sanitize_file_stem(&self.session.doc.project.name),
|
||||
texturecraft_engine::core::PROJECT_EXT
|
||||
));
|
||||
let path = self.autosave_path(&dir);
|
||||
let snapshot = self.session.project_snapshot();
|
||||
let spawned = std::thread::Builder::new().name("texturecraft-autosave".into()).spawn(move || {
|
||||
let result =
|
||||
@@ -1226,8 +1255,14 @@ impl eframe::App for TextureCraftApp {
|
||||
let focused = ctx.input(|input| input.viewport().focused).unwrap_or(true);
|
||||
if focused && !self.focused {
|
||||
self.library = None;
|
||||
|
||||
// Files may have been edited in another app meanwhile
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
resources_updater::check_files(self);
|
||||
}
|
||||
self.focused = focused;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
resources_updater::follow_project(self);
|
||||
|
||||
let scale = self.ui.prefs.ui_scale.clamp(*UI_SCALE_APPLIED.start(), *UI_SCALE_APPLIED.end());
|
||||
if (ctx.zoom_factor() - scale).abs() > SAME_ZOOM_TOLERANCE {
|
||||
@@ -1468,14 +1503,17 @@ fn toasts(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
if app.toasts.iter().any(|t| t.until.is_finite()) {
|
||||
ctx.request_repaint_after(std::time::Duration::from_millis(250));
|
||||
}
|
||||
|
||||
let tk = theme::Tokens::get(ctx);
|
||||
let mut dismissed = None;
|
||||
let mut show_log = false;
|
||||
let mut clicked_action = None;
|
||||
|
||||
// Limit toast dimensions so the dismiss button stays visible
|
||||
let screen = ctx.content_rect().size();
|
||||
let max_width = (screen.x - 52.0).clamp(120.0, 360.0);
|
||||
let max_text_height = (screen.y * 0.35).clamp(48.0, 220.0);
|
||||
|
||||
egui::Area::new(egui::Id::unique("toasts")).anchor(egui::Align2::RIGHT_BOTTOM, egui::vec2(-16.0, -36.0)).show(ctx, |ui| {
|
||||
for (i, t) in app.toasts.iter().enumerate() {
|
||||
egui::Frame::NONE
|
||||
@@ -1493,15 +1531,23 @@ fn toasts(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
ui.allocate_ui_with_layout(egui::vec2(width, 0.0), egui::Layout::top_down(egui::Align::Min), |ui| {
|
||||
egui::ScrollArea::vertical().id_salt(("toast", i)).max_height(max_text_height).show(ui, |ui| {
|
||||
ui.set_max_width(width);
|
||||
let label = ui.add(egui::Label::new(egui::RichText::new(&t.text).color(tk.text_strong)).wrap());
|
||||
if t.announce {
|
||||
ui.ctx().accesskit_node_builder(label.id, |node| node.set_live(egui::accesskit::Live::Polite));
|
||||
let message = ui.add(egui::Label::new(egui::RichText::new(&t.text).color(tk.text_strong)).wrap());
|
||||
if t.announce || t.action.is_some() {
|
||||
ui.ctx().accesskit_node_builder(message.id, |node| node.set_live(egui::accesskit::Live::Polite));
|
||||
}
|
||||
});
|
||||
if t.show_log && ui.link(i18n::tr("Open Log")).clicked() {
|
||||
show_log = true;
|
||||
dismissed = Some(i);
|
||||
}
|
||||
if let Some(action) = t.action {
|
||||
let button = ui.button(i18n::tr(action.label()));
|
||||
button.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, i18n::tr(action.accessible_name())));
|
||||
if button.clicked() {
|
||||
clicked_action = Some(action);
|
||||
dismissed = Some(i);
|
||||
}
|
||||
}
|
||||
});
|
||||
if sticky && widgets::icon_button(ui, egui_phosphor::regular::X, i18n::tr("Dismiss"), false, 18.0).clicked() {
|
||||
dismissed = Some(i);
|
||||
@@ -1511,6 +1557,7 @@ fn toasts(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
ui.add_space(4.0);
|
||||
}
|
||||
});
|
||||
|
||||
if let Some(i) = dismissed.filter(|i| *i < app.toasts.len()) {
|
||||
app.toasts.remove(i);
|
||||
}
|
||||
@@ -1519,4 +1566,8 @@ fn toasts(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
app.ui.log_channel = log_panel::LogChannel::General;
|
||||
crate::rail_popup::open(app, crate::docking::Panel::Log);
|
||||
}
|
||||
|
||||
if let Some(action) = clicked_action {
|
||||
action.run(app);
|
||||
}
|
||||
}
|
||||
@@ -126,9 +126,7 @@ impl TextureCraftApp {
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(toast) = self.toasts.last_mut() {
|
||||
toast.announce = true;
|
||||
}
|
||||
self.announce_latest_toast();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -232,6 +230,10 @@ mod tests {
|
||||
assert!(h.state().session.modified);
|
||||
assert_eq!(h.state().ui.windows.unsaved, Some(Unsaved::Quit));
|
||||
assert!(prompt_is_usable(&h), "the prompt answers again after the failed write");
|
||||
|
||||
let message = &h.state().toasts.iter().find(|toast| toast.error).expect("the failed write shows an error").text;
|
||||
let announced = h.get_all_by_label(message).any(|node| node.accesskit_node().live() == egui::accesskit::Live::Polite);
|
||||
assert!(announced, "the save error is announced away from focus");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -31,6 +31,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
|
||||
let mut open = true;
|
||||
let (mut export, mut cancel) = (false, false);
|
||||
let mut triangulated = true;
|
||||
crate::windows::dialog(ctx, "mesh_export_options", tr("Mesh Export Options"), &mut open).show(ctx, |ui| {
|
||||
ui.set_width(DIALOG_WIDTH);
|
||||
|
||||
@@ -38,24 +39,26 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
ui.add(egui::RadioButton::new(true, tr("Without displacement/tessellation")));
|
||||
option(
|
||||
ui,
|
||||
true,
|
||||
&mut triangulated,
|
||||
false,
|
||||
tr("Apply triangulation"),
|
||||
&[
|
||||
tr("Splits every face with more than three corners into triangles; triangles stay as they are."),
|
||||
tr("TextureCraft keeps meshes as triangles, so the exported mesh is always triangulated."),
|
||||
],
|
||||
);
|
||||
ui.add_space(GROUP_GAP);
|
||||
unavailable::greyed(ui, |ui| ui.add(egui::RadioButton::new(false, tr("With displacement/tessellation"))));
|
||||
option(
|
||||
ui,
|
||||
&mut app.ui.mesh_recompute_normals,
|
||||
true,
|
||||
tr("Recompute vertex normals"),
|
||||
&[
|
||||
tr("Replaces the mesh's vertex normals with newly computed ones in the exported file."),
|
||||
tr("TextureCraft cannot do this yet: it writes the vertex normals the mesh has in the project."),
|
||||
tr("On: smooth area-weighted normals from the exported geometry. Off: the project's stored normals. The project itself is not changed."),
|
||||
],
|
||||
);
|
||||
ui.add_space(GROUP_GAP);
|
||||
unavailable::greyed(ui, |ui| ui.add(egui::RadioButton::new(false, tr("With displacement/tessellation"))));
|
||||
ui.add_space(8.0);
|
||||
|
||||
// One row keeps the window to its contents; a bare right-to-left layout fills the screen height
|
||||
@@ -76,12 +79,16 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
}
|
||||
}
|
||||
|
||||
/// A greyed option under a choice, ticked as the reference shows it, with an info icon at the
|
||||
/// row's right end whose tooltip has the paragraphs `info`
|
||||
fn option(ui: &mut Ui, checked: bool, label: &str, info: &[&str]) {
|
||||
/// An option under a choice, greyed when `enabled` is false, with an info icon at the row's right
|
||||
/// end whose tooltip has the paragraphs `info`.
|
||||
fn option(ui: &mut Ui, checked: &mut bool, enabled: bool, label: &str, info: &[&str]) {
|
||||
ui.horizontal(|ui| {
|
||||
ui.add_space(OPTION_INDENT);
|
||||
unavailable::checkbox(ui, checked, label);
|
||||
if enabled {
|
||||
ui.checkbox(checked, label);
|
||||
} else {
|
||||
unavailable::checkbox(ui, *checked, label);
|
||||
}
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
let icon = ui.label(egui::RichText::new(egui_phosphor::regular::INFO).color(Tokens::get(ui.ctx()).text_dim));
|
||||
icon.on_hover_ui(|ui| {
|
||||
|
||||
@@ -0,0 +1,442 @@
|
||||
//! The Resources Updater: the project's image resources and whether the files they were imported
|
||||
//! from changed on disk. Update reads a changed file again, Select new resource points a resource
|
||||
//! at another file, and a notice offers to update when the app gets the focus back after files
|
||||
//! changed. Everything runs through `resource.status`, `resource.update` and `resource.relink`.
|
||||
|
||||
mod row_request;
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use serde_json::json;
|
||||
use texturecraft_engine::{ResourceState, ResourceStatus};
|
||||
|
||||
use crate::TextureCraftApp;
|
||||
use crate::file_dialogs::{Bound, FileDialog};
|
||||
use crate::i18n::{tr, trf};
|
||||
use crate::state::ResourcesUpdater;
|
||||
use crate::theme::Tokens;
|
||||
use crate::toast_action::ToastAction;
|
||||
use crate::web_files::IMAGE_EXTS;
|
||||
use row_request::RowRequest;
|
||||
|
||||
/// Width of the window
|
||||
const WINDOW_WIDTH_POINTS: f32 = 640.0;
|
||||
/// Height of the resource list
|
||||
const LIST_HEIGHT_POINTS: f32 = 360.0;
|
||||
/// Initial space for the header, tabs, filters and footer
|
||||
const WINDOW_CHROME_HEIGHT_POINTS: f32 = 160.0;
|
||||
/// Side of a row's thumbnail
|
||||
const THUMBNAIL_POINTS: f32 = 40.0;
|
||||
/// Width of the name filter field
|
||||
const NAME_FILTER_WIDTH_POINTS: f32 = 160.0;
|
||||
/// Width of the status dropdown
|
||||
const STATUS_WIDTH_POINTS: f32 = 120.0;
|
||||
/// Space inside a row's frame
|
||||
const ROW_MARGIN: egui::Margin = egui::Margin::same(4);
|
||||
/// Strength of the danger tint behind an outdated row (the status text says it too)
|
||||
const OUTDATED_TINT: f32 = 0.18;
|
||||
/// How long the "changed on disk" notice stays, in seconds: long enough to reach its button
|
||||
const NOTICE_SECONDS: f64 = 12.0;
|
||||
/// Time between two checks while the window is open, in seconds (each check looks at every file; an unchanged one is not read)
|
||||
const RECHECK_SECONDS: f64 = 0.5;
|
||||
|
||||
/// Opens the window, or closes it when it is open (the shelf button)
|
||||
pub(crate) fn toggle(app: &mut TextureCraftApp) {
|
||||
if app.ui.windows.resources_updater.take().is_none() {
|
||||
open(app);
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens the window with the resources checked now (an open window is checked again)
|
||||
pub(crate) fn open(app: &mut TextureCraftApp) {
|
||||
let window = app.ui.windows.resources_updater.take().unwrap_or_default();
|
||||
app.ui.windows.resources_updater =
|
||||
Some(ResourcesUpdater { rows: app.session.resource_states(), project: app.session.project_id, checked_at: app.last_time, ..window });
|
||||
}
|
||||
|
||||
/// Check once when another project is open (files may have changed while it was closed), and
|
||||
/// forget what was announced for the last one
|
||||
pub(crate) fn follow_project(app: &mut TextureCraftApp) {
|
||||
if !app.session.project_open || app.resources_project == Some(app.session.project_id) {
|
||||
return;
|
||||
}
|
||||
|
||||
app.resources_project = Some(app.session.project_id);
|
||||
app.resources_notified.clear();
|
||||
check_files(app);
|
||||
}
|
||||
|
||||
/// Check the files again (the app has the focus back, or a project opened) and, when other
|
||||
/// resources than last time are outdated, show a notice whose button updates them
|
||||
pub(crate) fn check_files(app: &mut TextureCraftApp) {
|
||||
if !app.session.project_open {
|
||||
return;
|
||||
}
|
||||
|
||||
let rows = app.session.resource_states();
|
||||
let outdated: BTreeSet<String> = rows.iter().filter(|row| row.status == ResourceStatus::Outdated).map(|row| row.name.clone()).collect();
|
||||
if let Some(window) = app.ui.windows.resources_updater.as_mut() {
|
||||
window.rows = rows;
|
||||
window.checked_at = app.last_time;
|
||||
}
|
||||
|
||||
if !outdated.is_empty() && outdated != app.resources_notified {
|
||||
let text = if outdated.len() == 1 {
|
||||
tr("1 resource changed on disk").to_string()
|
||||
} else {
|
||||
trf("{count} resources changed on disk", &[("count", &outdated.len())])
|
||||
};
|
||||
app.toast(text, false);
|
||||
if let Some(toast) = app.toasts.last_mut() {
|
||||
toast.until = app.last_time + NOTICE_SECONDS;
|
||||
toast.action = Some(ToastAction::UpdateResources { project: app.session.project_id });
|
||||
}
|
||||
}
|
||||
app.resources_notified = outdated;
|
||||
}
|
||||
|
||||
/// Read the files of `names` again (every outdated resource when None), one undo step, and say
|
||||
/// what happened
|
||||
pub(crate) fn update(app: &mut TextureCraftApp, names: Option<Vec<String>>) {
|
||||
let params = match names {
|
||||
Some(names) => json!({ "names": names }),
|
||||
None => json!({}),
|
||||
};
|
||||
let Some(result) = app.run("resource.update", params) else {
|
||||
app.announce_latest_toast();
|
||||
return;
|
||||
};
|
||||
|
||||
let updated = result["updated"].as_array().map_or(0, Vec::len);
|
||||
let failed: Vec<String> = result["failed"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(|failure| format!("{}: {}", failure["name"].as_str().unwrap_or_default(), failure["error"].as_str().unwrap_or_default()))
|
||||
.collect();
|
||||
if failed.is_empty() {
|
||||
app.toast(trf("Updated {count} resources", &[("count", &updated)]), false);
|
||||
} else {
|
||||
app.toast(trf("Updated {count} resources; could not update {failed}", &[("count", &updated), ("failed", &failed.join("; "))]), true);
|
||||
}
|
||||
app.announce_latest_toast();
|
||||
|
||||
// What was announced is handled; a later change is announced again
|
||||
app.resources_notified.clear();
|
||||
}
|
||||
|
||||
/// Ask for another file for resource `name`; the resource takes its pixels and follows it
|
||||
fn select_new_resource(app: &mut TextureCraftApp, name: String) {
|
||||
let dialog = FileDialog::open().filter(tr("Images"), IMAGE_EXTS);
|
||||
app.ask_file(dialog, Bound::Project, move |app, paths| {
|
||||
let Some(path) = paths.first() else { return };
|
||||
let Some(path) = path.to_str() else {
|
||||
app.toast(trf("Could not use a path that is not UTF-8: {path}", &[("path", &path.display())]), true);
|
||||
app.announce_latest_toast();
|
||||
return;
|
||||
};
|
||||
|
||||
if app.run("resource.relink", json!({ "name": name, "path": path })).is_some() {
|
||||
app.toast(trf("{name} now reads {path}", &[("name", &name), ("path", &path)]), false);
|
||||
}
|
||||
app.announce_latest_toast();
|
||||
});
|
||||
}
|
||||
|
||||
/// Show the folder holding `path` in the system's file manager
|
||||
fn show_in_folder(app: &mut TextureCraftApp, path: &str) {
|
||||
let folder = std::path::Path::new(path).parent().map(std::path::Path::to_path_buf).unwrap_or_default();
|
||||
if let Err(error) = app.file_dialogs.show_folder(&folder) {
|
||||
app.toast(trf("Could not show {folder}: {error}", &[("folder", &folder.display()), ("error", &error)]), true);
|
||||
app.announce_latest_toast();
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `row` passes the window's status and name filters
|
||||
fn shown(window: &ResourcesUpdater, row: &ResourceState) -> bool {
|
||||
let name_filter = window.name_filter.trim().to_lowercase();
|
||||
window.status_filter.is_none_or(|status| row.status == status) && (name_filter.is_empty() || row.name.to_lowercase().contains(&name_filter))
|
||||
}
|
||||
|
||||
/// "(N resources, M outdated)"
|
||||
fn summary(rows: &[ResourceState]) -> String {
|
||||
let outdated = rows.iter().filter(|row| row.status == ResourceStatus::Outdated).count();
|
||||
trf("({count} resources, {outdated} outdated)", &[("count", &rows.len()), ("outdated", &outdated)])
|
||||
}
|
||||
|
||||
pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
let Some(mut window) = app.ui.windows.resources_updater.take() else { return };
|
||||
|
||||
// Drop the window state when its project closes or changes
|
||||
if window.project != app.session.project_id || !app.session.project_open {
|
||||
return;
|
||||
}
|
||||
|
||||
// Files changed on disk and document changes (undo, a removed resource) show while the window stays open
|
||||
let wait = window.checked_at + RECHECK_SECONDS - app.last_time;
|
||||
if wait <= 0.0 {
|
||||
window.rows = app.session.resource_states();
|
||||
window.checked_at = app.last_time;
|
||||
ctx.request_repaint_after(std::time::Duration::from_secs_f64(RECHECK_SECONDS));
|
||||
} else {
|
||||
ctx.request_repaint_after(std::time::Duration::from_secs_f64(wait));
|
||||
}
|
||||
|
||||
// Only close on Escape when the window owned keyboard focus
|
||||
// Read raw input because egui consumes Escape when it clears focus
|
||||
let escape = ctx.input(|input| input.raw.events.iter().any(|event| matches!(event, egui::Event::Key { key: egui::Key::Escape, pressed: true, .. })));
|
||||
if window.had_keyboard && escape && !egui::Popup::is_any_open(ctx) {
|
||||
return;
|
||||
}
|
||||
|
||||
let tokens = Tokens::get(ctx);
|
||||
let mut window_open = true;
|
||||
let (mut refresh, mut update_all) = (false, false);
|
||||
let mut request = None;
|
||||
|
||||
let shown = crate::windows::dialog(ctx, "resources_updater", tr("Resources Updater"), &mut window_open)
|
||||
.default_size(egui::vec2(WINDOW_WIDTH_POINTS, LIST_HEIGHT_POINTS + WINDOW_CHROME_HEIGHT_POINTS))
|
||||
.show(ctx, |ui| {
|
||||
ui.label(format!("{} {}", tr("Project :"), app.session.doc.project.name));
|
||||
|
||||
let tab = ui.add(egui::Button::selectable(true, tr("Resources")));
|
||||
tab.widget_info(|| egui::WidgetInfo::selected(egui::Role::Tab, true, true, tr("Resources")));
|
||||
ui.separator();
|
||||
|
||||
ui.horizontal(|ui| {
|
||||
let status_label = ui.label(tr("Status:"));
|
||||
let selected = window.status_filter.map_or(tr("All"), |status| tr(status.label()));
|
||||
egui::ComboBox::from_id_salt("resources_updater_status")
|
||||
.width(STATUS_WIDTH_POINTS)
|
||||
.selected_text(selected)
|
||||
.show_ui(ui, |ui| {
|
||||
ui.selectable_value(&mut window.status_filter, None, tr("All"));
|
||||
for status in ResourceStatus::ALL {
|
||||
ui.selectable_value(&mut window.status_filter, Some(status), tr(status.label()));
|
||||
}
|
||||
})
|
||||
.response
|
||||
.labelled_by(status_label.id);
|
||||
|
||||
let name_label = ui.label(tr("Name filter:"));
|
||||
ui.add(egui::TextEdit::singleline(&mut window.name_filter).desired_width(NAME_FILTER_WIDTH_POINTS)).labelled_by(name_label.id);
|
||||
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if ui.button(tr("Bottom")).clicked() {
|
||||
window.jump = Some(egui::Align::Max);
|
||||
}
|
||||
if ui.button(tr("Top")).clicked() {
|
||||
window.jump = Some(egui::Align::Min);
|
||||
}
|
||||
});
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
|
||||
ui.with_layout(egui::Layout::bottom_up(egui::Align::Min), |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
let refresh_button = ui.button(tr("Refresh"));
|
||||
refresh_button.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tr("Refresh resources")));
|
||||
refresh = refresh_button.clicked();
|
||||
let count = ui.label(summary(&window.rows));
|
||||
ui.ctx().accesskit_node_builder(count.id, |node| node.set_live(egui::accesskit::Live::Polite));
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
let outdated = window.rows.iter().any(|row| row.status == ResourceStatus::Outdated);
|
||||
let label = egui::RichText::new(tr("Update All")).color(tokens.text_strong);
|
||||
let action = egui::Button::new(label).fill(tokens.accent_dim).stroke(egui::Stroke::new(1.0, tokens.text_dim));
|
||||
let button = ui.add_enabled(outdated, action);
|
||||
update_all = button.on_disabled_hover_text(tr("No resource is outdated")).clicked();
|
||||
});
|
||||
});
|
||||
ui.separator();
|
||||
|
||||
let list_height = ui.available_height().max(0.0);
|
||||
ui.with_layout(egui::Layout::top_down(egui::Align::Min), |ui| {
|
||||
egui::ScrollArea::vertical().max_height(list_height).auto_shrink([false, false]).show(ui, |ui| {
|
||||
let jump = window.jump.take();
|
||||
if jump == Some(egui::Align::Min) {
|
||||
ui.scroll_to_cursor(Some(egui::Align::Min));
|
||||
}
|
||||
|
||||
let visible: Vec<&ResourceState> = window.rows.iter().filter(|row| shown(&window, row)).collect();
|
||||
if visible.is_empty() {
|
||||
ui.label(tr("No resources match the filters"));
|
||||
}
|
||||
for (index, row) in visible.into_iter().enumerate() {
|
||||
// Keep keyboard focus with the resource when rows move
|
||||
let row_scope = egui::UiBuilder::new().scope_id(ui.scope_id().with(("resources_updater_row", &row.name)));
|
||||
let asked = ui.scope_builder(row_scope, |ui| row_ui(app, ui, &tokens, index + 1, row)).inner;
|
||||
if let Some(asked) = asked {
|
||||
request = Some(asked);
|
||||
}
|
||||
}
|
||||
|
||||
if jump == Some(egui::Align::Max) {
|
||||
ui.scroll_to_cursor(Some(egui::Align::Max));
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
let focused = ctx.memory(|memory| memory.focused()).and_then(|id| ctx.read_response(id));
|
||||
window.had_keyboard = shown.as_ref().zip(focused.as_ref()).is_some_and(|(shown, focused)| focused.layer_id == shown.response.layer_id);
|
||||
if !window_open {
|
||||
return;
|
||||
}
|
||||
|
||||
app.ui.windows.resources_updater = Some(window);
|
||||
|
||||
// Its own changes and Refresh show at once
|
||||
let check_now = refresh || update_all || matches!(request, Some(RowRequest::Update(_)));
|
||||
if update_all {
|
||||
update(app, None);
|
||||
}
|
||||
match request {
|
||||
Some(RowRequest::Update(name)) => update(app, Some(vec![name])),
|
||||
Some(RowRequest::SelectNew(name)) => select_new_resource(app, name),
|
||||
Some(RowRequest::ShowFolder(path)) => show_in_folder(app, &path),
|
||||
None => {}
|
||||
}
|
||||
|
||||
if check_now {
|
||||
open(app);
|
||||
}
|
||||
}
|
||||
|
||||
/// One resource: its thumbnail, number, name, file and status, and its buttons. Outdated rows are
|
||||
/// tinted, and their status says so in words too.
|
||||
fn row_ui(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens, number: usize, row: &ResourceState) -> Option<RowRequest> {
|
||||
let outdated = row.status == ResourceStatus::Outdated;
|
||||
let (fill, stroke) = if outdated {
|
||||
(tokens.danger.gamma_multiply(OUTDATED_TINT), egui::Stroke::new(1.0, tokens.danger))
|
||||
} else {
|
||||
(egui::Color32::TRANSPARENT, egui::Stroke::NONE)
|
||||
};
|
||||
let mut request = None;
|
||||
|
||||
egui::Frame::NONE.fill(fill).stroke(stroke).inner_margin(ROW_MARGIN).corner_radius(crate::theme::CARD_RADIUS).show(ui, |ui| {
|
||||
ui.set_width(ui.available_width());
|
||||
ui.horizontal(|ui| {
|
||||
match app.session.images.get(&row.name) {
|
||||
Some(image) => {
|
||||
let (rect, preview) = ui.allocate_exact_size(egui::Vec2::splat(THUMBNAIL_POINTS), egui::Sense::hover());
|
||||
preview.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Image, true, &row.name));
|
||||
if ui.is_rect_visible(rect) {
|
||||
let texture = app.thumbs.image(ui.ctx(), &row.name, image);
|
||||
egui::Image::new(&texture).paint_at(ui, rect);
|
||||
}
|
||||
}
|
||||
|
||||
// Reserve thumbnail space for images that failed to decode
|
||||
None => ui.add_space(THUMBNAIL_POINTS),
|
||||
}
|
||||
ui.label(number.to_string());
|
||||
|
||||
// Reserve space for the buttons before truncating the labels
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
let update = ui.add_enabled(outdated, egui::Button::new(tr("Update")));
|
||||
let update_name = format!("{} {}", tr("Update"), row.name);
|
||||
update.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, outdated, &update_name));
|
||||
if update.clicked() {
|
||||
request = Some(RowRequest::Update(row.name.clone()));
|
||||
}
|
||||
|
||||
// Only images can be relinked to disk
|
||||
let material = row.status == ResourceStatus::Material;
|
||||
if !material {
|
||||
let select = ui.button(tr("Select new resource"));
|
||||
let select_name = format!("{} {}", tr("Select new resource"), row.name);
|
||||
select.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &select_name));
|
||||
if select.clicked() {
|
||||
request = Some(RowRequest::SelectNew(row.name.clone()));
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(path) = &row.path {
|
||||
let folder = ui.button(tr("Show in folder"));
|
||||
let folder_name = format!("{} {}", tr("Show in folder"), row.name);
|
||||
folder.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &folder_name));
|
||||
if folder.clicked() {
|
||||
request = Some(RowRequest::ShowFolder(path.clone()));
|
||||
}
|
||||
}
|
||||
|
||||
ui.vertical(|ui| {
|
||||
ui.add(egui::Label::new(format!("{} {}", tr("Name :"), row.name)).truncate());
|
||||
ui.label(format!("{} {}", tr("Shelf :"), tr("project")));
|
||||
let file = row.path.as_deref().unwrap_or(tr("No source file"));
|
||||
ui.add(egui::Label::new(format!("{} {}", tr("File :"), file)).truncate()).on_hover_text(file);
|
||||
let status = ui.label(tr(row.status.label()));
|
||||
let detail = row
|
||||
.error
|
||||
.as_deref()
|
||||
.or_else(|| material.then(|| tr("This MaterialCraft package is stored in the project. Its cooked maps are separate image resources.")));
|
||||
if let Some(detail) = detail {
|
||||
ui.ctx().accesskit_node_builder(status.id, |node| node.set_description(detail));
|
||||
status.on_hover_text(detail);
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
request
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::PoisonError;
|
||||
|
||||
use egui_kittest::Harness;
|
||||
use egui_kittest::kittest::{NodeT as _, Queryable as _};
|
||||
use texturecraft_engine::Session;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn write_png(path: &std::path::Path, size: u32) {
|
||||
image::RgbaImage::from_pixel(size, size, image::Rgba([10, 200, 30, 255])).save(path).unwrap();
|
||||
}
|
||||
|
||||
fn notices(app: &TextureCraftApp) -> Vec<ToastAction> {
|
||||
app.toasts.iter().filter_map(|toast| toast.action).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_changed_file_is_announced_once_and_the_notice_updates_it() {
|
||||
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("notice.png");
|
||||
write_png(&path, 4);
|
||||
let session = Session::new_project("Test", texturecraft_engine::geom::primitives::cube(1.0), "builtin:cube", None, 128).unwrap();
|
||||
let mut harness = Harness::builder().with_context_setup(crate::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
|
||||
harness.state_mut().ui.prefs.language = "en".into();
|
||||
harness.run_steps(2);
|
||||
let app = harness.state_mut();
|
||||
let name = app.run("resource.import", json!({ "path": path.to_str().unwrap() })).unwrap()["name"].as_str().unwrap().to_string();
|
||||
|
||||
check_files(app);
|
||||
assert!(notices(app).is_empty(), "nothing changed yet");
|
||||
|
||||
write_png(&path, 8);
|
||||
check_files(app);
|
||||
check_files(app);
|
||||
let announced = notices(app);
|
||||
assert_eq!(announced, [ToastAction::UpdateResources { project: app.session.project_id }], "the same change is announced once");
|
||||
|
||||
// A notice about another project does nothing
|
||||
ToastAction::UpdateResources { project: app.session.project_id + 1 }.run(app);
|
||||
assert_eq!(app.session.images[&name].width, 4);
|
||||
|
||||
harness.run_steps(2);
|
||||
let message = harness.get_by_label("1 resource changed on disk");
|
||||
assert_eq!(message.accesskit_node().live(), egui::accesskit::Live::Polite, "the notice is announced away from focus");
|
||||
harness.get_by_role_and_label(egui::Role::Button, "Update resources").focus();
|
||||
harness.run_steps(2);
|
||||
harness.key_press(egui::Key::Enter);
|
||||
harness.run_steps(2);
|
||||
|
||||
let app = harness.state();
|
||||
assert_eq!(app.session.images[&name].width, 8, "the notice's button updated the resource");
|
||||
assert_eq!(app.session.history_labels().last().map(String::as_str), Some("Update resources"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
/// What a Resources Updater row's buttons asked for, run after the window is drawn
|
||||
pub(super) enum RowRequest {
|
||||
/// Update: read the resource's file again
|
||||
Update(String),
|
||||
/// Select new resource: ask for another file for the resource
|
||||
SelectNew(String),
|
||||
/// Show in folder: the folder holding this file
|
||||
ShowFolder(String),
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
use egui::{RichText, Ui, vec2};
|
||||
use egui_phosphor::regular as ic;
|
||||
use texturecraft_engine::core::project::DisplaySettings;
|
||||
use texturecraft_engine::core::project::{DisplaySettings, MAX_INDEX_OF_REFRACTION, MIN_INDEX_OF_REFRACTION};
|
||||
|
||||
use crate::TextureCraftApp;
|
||||
use crate::i18n::tr;
|
||||
@@ -52,7 +52,7 @@ const SHADER_MODEL_COMBO_WIDTH: f32 = 260.0;
|
||||
const SCATTER_SWATCH_WIDTH: f32 = 44.0;
|
||||
|
||||
/// Index of refraction slider range: air to well past diamond (2.42)
|
||||
const INDEX_OF_REFRACTION_RANGE: std::ops::RangeInclusive<f32> = 1.0..=3.0;
|
||||
const INDEX_OF_REFRACTION_RANGE: std::ops::RangeInclusive<f32> = MIN_INDEX_OF_REFRACTION..=MAX_INDEX_OF_REFRACTION;
|
||||
|
||||
/// Values the reference's panel shows for controls TextureCraft lacks
|
||||
const SCATTER_ANISOTROPY_SHOWN: f32 = 0.1;
|
||||
@@ -70,8 +70,9 @@ pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
header(ui);
|
||||
|
||||
let mut display = app.session.doc.project.display.clone();
|
||||
let mut ior_specular = display.ior_specular;
|
||||
section_page::show(ui, "shader_settings", &SECTIONS, |ui, index| match index {
|
||||
0 => shader_parameters(ui, &mut display),
|
||||
0 => shader_parameters(ui, &mut display, &mut ior_specular),
|
||||
_ => displacement(ui, &mut display),
|
||||
});
|
||||
|
||||
@@ -79,6 +80,10 @@ pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
app.session.doc.project.display = display;
|
||||
app.session.mark_modified();
|
||||
}
|
||||
|
||||
if ior_specular != app.session.doc.project.display.ior_specular {
|
||||
app.run("display.set", serde_json::json!({"iorSpecular": ior_specular}));
|
||||
}
|
||||
}
|
||||
|
||||
/// Undo and Redo of the shader's settings, the shader button and the instance name
|
||||
@@ -138,7 +143,7 @@ pub fn matches_query(name: &str, query: &str) -> bool {
|
||||
}
|
||||
|
||||
/// Base Surface, Specular, Transmission and Subsurface
|
||||
fn shader_parameters(ui: &mut Ui, display: &mut DisplaySettings) {
|
||||
fn shader_parameters(ui: &mut Ui, display: &mut DisplaySettings, ior_specular: &mut bool) {
|
||||
let tokens = Tokens::get(ui.ctx());
|
||||
section(ui, "shader_base_surface", tr("Base Surface"), true, |ui| {
|
||||
shader_model(ui, display);
|
||||
@@ -147,8 +152,22 @@ fn shader_parameters(ui: &mut Ui, display: &mut DisplaySettings) {
|
||||
section(ui, "shader_specular", tr("Specular"), true, |ui| {
|
||||
unavailable::checkbox(ui, false, tr("Enable anisotropy"));
|
||||
slider(ui, tr("Index of refraction"), &mut display.ior, INDEX_OF_REFRACTION_RANGE, 2).on_hover_text(tr(
|
||||
"How strongly transmissive surfaces bend light (where the Transmission channel is painted): water 1.33, glass 1.5, diamond 2.42",
|
||||
"Controls how strongly transmissive surfaces bend light. When the checkbox below is on, it also controls dielectric reflectance.",
|
||||
));
|
||||
|
||||
ui.add_enabled_ui(!display.spec_gloss, |ui| {
|
||||
let widgets = &mut ui.visuals_mut().widgets;
|
||||
widgets.inactive.bg_stroke.color = tokens.text_dim;
|
||||
widgets.hovered.bg_stroke.color = tokens.text;
|
||||
widgets.active.bg_stroke.color = tokens.text_strong;
|
||||
|
||||
ui.checkbox(ior_specular, tr("Use IOR for specular reflection"))
|
||||
.on_hover_text(tr(
|
||||
"Uses the index of refraction for dielectric reflectance at normal incidence. Specular level adjusts the surface reflection.",
|
||||
))
|
||||
.on_disabled_hover_text(tr("Specular Glossiness uses the Specular color channel for reflectance."));
|
||||
});
|
||||
|
||||
unavailable::checkbox(ui, false, tr("Enable specular color"));
|
||||
});
|
||||
section(ui, "shader_transmission", tr("Transmission"), true, |ui| {
|
||||
|
||||
@@ -14,11 +14,13 @@ mod import_row;
|
||||
mod library_location;
|
||||
mod project_config;
|
||||
mod resource_usage;
|
||||
mod resources_updater;
|
||||
pub use import_resources::ImportResources;
|
||||
pub use import_row::ImportRow;
|
||||
pub use library_location::LibraryLocation;
|
||||
pub use project_config::ProjectConfig;
|
||||
pub use resource_usage::ResourceUsage;
|
||||
pub use resources_updater::ResourcesUpdater;
|
||||
|
||||
mod console_line;
|
||||
mod export_job;
|
||||
@@ -115,6 +117,9 @@ pub struct Windows {
|
||||
/// File > Import resources: the files added so far, imported by Import.
|
||||
#[serde(skip)]
|
||||
pub import_resources: Option<ImportResources>,
|
||||
/// The Resources Updater: the project's image resources and whether their files changed on disk.
|
||||
#[serde(skip)]
|
||||
pub resources_updater: Option<ResourcesUpdater>,
|
||||
/// What waits on the unsaved-changes dialog: save, don't save or cancel.
|
||||
#[serde(skip)]
|
||||
pub unsaved: Option<Unsaved>,
|
||||
@@ -588,6 +593,10 @@ pub struct UiState {
|
||||
/// Window ▸ Hide UI (Tab): only the viewport.
|
||||
pub hide_ui: bool,
|
||||
pub windows: Windows,
|
||||
/// Mesh Export Options: compute smooth normals on the exported copy, not the project.
|
||||
/// Off by default so an export keeps the project's authored normals unless the user opts in.
|
||||
#[serde(default)]
|
||||
pub mesh_recompute_normals: bool,
|
||||
pub uv_zoom: f32,
|
||||
pub uv_pan: [f32; 2],
|
||||
/// The 2D view's turn, counter-clockwise on screen in radians (Alt+left drag)
|
||||
@@ -763,6 +772,7 @@ impl UiState {
|
||||
}
|
||||
|
||||
self.export = keep.export;
|
||||
self.mesh_recompute_normals = keep.mesh_recompute_normals;
|
||||
self.recent = keep.recent;
|
||||
self.last_template = keep.last_template;
|
||||
self.prefs = keep.prefs;
|
||||
@@ -802,6 +812,7 @@ impl Default for UiState {
|
||||
selected_baked_map: None,
|
||||
hide_ui: false,
|
||||
windows: Windows::default(),
|
||||
mesh_recompute_normals: false,
|
||||
uv_zoom: 1.0,
|
||||
uv_pan: [0.0, 0.0],
|
||||
uv_rotation: 0.0,
|
||||
@@ -884,6 +895,15 @@ mod tests {
|
||||
assert_eq!(crate::start_ui(None, &mut session).prefs.language, crate::i18n::SYSTEM_LANGUAGE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mesh_export_normal_choice_defaults_off_for_older_saved_states() {
|
||||
assert!(!UiState::default().mesh_recompute_normals);
|
||||
let mut saved = serde_json::to_value(UiState::default()).unwrap();
|
||||
saved.as_object_mut().unwrap().remove("mesh_recompute_normals");
|
||||
let loaded: UiState = serde_json::from_value(saved).unwrap();
|
||||
assert!(!loaded.mesh_recompute_normals, "older states keep the project's stored normals unless the user opts in");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adopting_a_layout_keeps_recent_files_and_user_settings() {
|
||||
use crate::frame_gizmo::warp_toolbar::{GizmoMode, GizmoSpace, WarpToolbarSettings};
|
||||
@@ -893,7 +913,9 @@ mod tests {
|
||||
ui.warp_toolbar = warp_toolbar;
|
||||
ui.export.preset = "Mine".into();
|
||||
ui.keymap.insert("file.save".into(), "F5".into());
|
||||
ui.mesh_recompute_normals = false;
|
||||
let mut layout = UiState::default();
|
||||
layout.mesh_recompute_normals = true;
|
||||
layout.dock.close(crate::docking::Panel::Assets);
|
||||
|
||||
ui.adopt_layout(layout);
|
||||
@@ -902,6 +924,7 @@ mod tests {
|
||||
assert_eq!(ui.recent, vec!["a.tcraft".to_string()]);
|
||||
assert_eq!(ui.export.preset, "Mine");
|
||||
assert_eq!(ui.keymap.get("file.save").map(String::as_str), Some("F5"));
|
||||
assert!(!ui.mesh_recompute_normals, "a layout does not change the user's export setting");
|
||||
assert_eq!(ui.warp_toolbar, warp_toolbar, "loading a layout keeps the user's warp settings");
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
use texturecraft_engine::{ResourceState, ResourceStatus};
|
||||
|
||||
/// The Resources Updater window: the project's image resources as last checked, and the filters
|
||||
#[derive(Clone, Debug, PartialEq, Default)]
|
||||
pub struct ResourcesUpdater {
|
||||
/// The resources and how they compare with their files, outdated first (checked on opening,
|
||||
/// Refresh, twice a second while open and when the app gets the focus back)
|
||||
pub rows: Vec<ResourceState>,
|
||||
/// The status the list is narrowed to (None: all)
|
||||
pub status_filter: Option<ResourceStatus>,
|
||||
/// Shows only resources whose name contains this, ignoring case
|
||||
pub name_filter: String,
|
||||
/// Top or Bottom asked the list to scroll to that end in the next frame
|
||||
pub jump: Option<egui::Align>,
|
||||
/// The project that was open when this window opened
|
||||
pub project: u64,
|
||||
/// When the rows were checked, in app seconds
|
||||
pub(crate) checked_at: f64,
|
||||
/// Whether a control of the window had the keyboard focus when it was last drawn (Escape then closes it)
|
||||
pub(crate) had_keyboard: bool,
|
||||
}
|
||||
@@ -93,6 +93,7 @@ impl TitleBar {
|
||||
if overridden.is_none() && system {
|
||||
return TitleBar::System;
|
||||
}
|
||||
|
||||
match frame {
|
||||
Frame::App(layout) => TitleBar::App(layout.clone()),
|
||||
Frame::Desktop if overridden.is_some() => TitleBar::System,
|
||||
@@ -238,15 +239,18 @@ mod tests {
|
||||
#[test]
|
||||
fn the_override_wins_then_the_setting_then_the_platform() {
|
||||
let gnome = Frame::App(Layout::parse("appmenu:close"));
|
||||
// TEXTURECRAFT_TITLEBAR=app / =system, whatever the setting.
|
||||
|
||||
// The environment override wins regardless of the saved setting
|
||||
for system in [false, true] {
|
||||
assert_eq!(TitleBar::from_choice(&gnome, Some(true), system), TitleBar::App(Layout::parse("appmenu:close")));
|
||||
assert_eq!(TitleBar::from_choice(&Frame::Desktop, Some(false), system), TitleBar::System);
|
||||
}
|
||||
// The setting brings the system's frame back.
|
||||
|
||||
// The saved setting selects the system frame without an override
|
||||
assert_eq!(TitleBar::from_choice(&gnome, None, true), TitleBar::System);
|
||||
assert_eq!(TitleBar::from_choice(&Frame::Desktop, None, true), TitleBar::System);
|
||||
// The platform: a compositor that leaves the frame to the app gets the app's.
|
||||
|
||||
// Otherwise the desktop determines who draws the frame
|
||||
assert_eq!(TitleBar::from_choice(&gnome, None, false), TitleBar::App(Layout::parse("appmenu:close")));
|
||||
let desktop = TitleBar::from_choice(&Frame::Desktop, None, false);
|
||||
let expected = if cfg!(windows) {
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
//! A button on a toast that acts on what the toast says
|
||||
|
||||
use crate::TextureCraftApp;
|
||||
|
||||
/// What a toast's button does
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ToastAction {
|
||||
/// "Update": read every outdated resource file of `project` again (the desktop's "changed on disk" notice)
|
||||
UpdateResources {
|
||||
/// The project the notice is about; the button does nothing once another one is open
|
||||
project: u64,
|
||||
},
|
||||
}
|
||||
|
||||
impl ToastAction {
|
||||
/// The button's text (English; translated where it is drawn)
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
ToastAction::UpdateResources { .. } => "Update",
|
||||
}
|
||||
}
|
||||
|
||||
/// The button's accessible name, which says what it acts on (English; translated where it is drawn)
|
||||
pub fn accessible_name(self) -> &'static str {
|
||||
match self {
|
||||
ToastAction::UpdateResources { .. } => "Update resources",
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn run(self, app: &mut TextureCraftApp) {
|
||||
match self {
|
||||
// Another project's notice is stale
|
||||
ToastAction::UpdateResources { project } if project != app.session.project_id => {}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
ToastAction::UpdateResources { .. } => crate::resources_updater::update(app, None),
|
||||
// The browser has no files to read again
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
ToastAction::UpdateResources { .. } => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -510,15 +510,33 @@ pub fn tool_shelf(app: &mut TextureCraftApp, ui: &mut egui::Ui) {
|
||||
ui.add_space(SHELF_GROUP_GAP);
|
||||
}
|
||||
|
||||
for (icon, label) in [(ic::HOURGLASS, "Snooze Autosave"), (ic::ARROWS_CLOCKWISE, "Resources Updater")] {
|
||||
ui.add_enabled_ui(false, |ui| icon_button(ui, icon, tr(label), false, SHELF_BUTTON_SIZE))
|
||||
.inner
|
||||
.on_disabled_hover_text(tr(crate::unavailable::NOT_AVAILABLE));
|
||||
}
|
||||
ui.add_enabled_ui(false, |ui| icon_button(ui, ic::HOURGLASS, tr("Snooze Autosave"), false, SHELF_BUTTON_SIZE))
|
||||
.inner
|
||||
.on_disabled_hover_text(tr(crate::unavailable::NOT_AVAILABLE));
|
||||
resources_updater_button(app, ui);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/// The shelf's Resources Updater button: opens or closes its window while a project is open
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn resources_updater_button(app: &mut TextureCraftApp, ui: &mut egui::Ui) {
|
||||
let open = app.ui.windows.resources_updater.is_some();
|
||||
let label = tr("Resources Updater");
|
||||
let button = ui.add_enabled_ui(app.session.project_open, |ui| icon_button(ui, ic::ARROWS_CLOCKWISE, label, open, SHELF_BUTTON_SIZE)).inner;
|
||||
if button.on_disabled_hover_text(tr("Open a project to check its resources")).clicked() {
|
||||
crate::resources_updater::toggle(app);
|
||||
}
|
||||
}
|
||||
|
||||
/// The browser reads no files from disk, so there is nothing to update
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn resources_updater_button(_: &mut TextureCraftApp, ui: &mut egui::Ui) {
|
||||
ui.add_enabled_ui(false, |ui| icon_button(ui, ic::ARROWS_CLOCKWISE, tr("Resources Updater"), false, SHELF_BUTTON_SIZE))
|
||||
.inner
|
||||
.on_disabled_hover_text(tr(crate::unavailable::NOT_AVAILABLE));
|
||||
}
|
||||
|
||||
/// Width of the icon rail beside the dock
|
||||
const RAIL_WIDTH: f32 = 38.0;
|
||||
|
||||
|
||||
@@ -337,9 +337,9 @@ mod web {
|
||||
pub fn export_mesh(app: &mut TextureCraftApp, ext: &str) {
|
||||
let name = format!("{}.{ext}", sanitize_file_stem(&app.session.doc.project.name));
|
||||
let bytes = match ext {
|
||||
"glb" => app.session.mesh_glb_bytes(),
|
||||
"usdz" => app.session.mesh_usd(texturecraft_engine::formats::UsdFormat::Usdz).map(|u| u.bytes),
|
||||
_ => app.session.mesh_obj_bytes(),
|
||||
"glb" => app.session.mesh_glb_bytes_with_normals(app.ui.mesh_recompute_normals),
|
||||
"usdz" => app.session.mesh_usd_with_normals(texturecraft_engine::formats::UsdFormat::Usdz, app.ui.mesh_recompute_normals).map(|u| u.bytes),
|
||||
_ => app.session.mesh_obj_bytes_with_normals(app.ui.mesh_recompute_normals),
|
||||
};
|
||||
match bytes.map_err(|e| e.to_string()).and_then(|b| download(&name, &b)) {
|
||||
Ok(()) => app.toast(trf("Downloaded {name}", &[("name", &name)]), false),
|
||||
|
||||
@@ -23,6 +23,7 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
{
|
||||
crate::project_config::show(app, ctx);
|
||||
crate::import_resources::show(app, ctx);
|
||||
crate::resources_updater::show(app, ctx);
|
||||
}
|
||||
crate::keymap::window(app, ctx);
|
||||
crate::export_window::show(app, ctx);
|
||||
@@ -631,7 +632,8 @@ pub fn file_action(app: &mut TextureCraftApp, _ctx: &egui::Context, id: &str) ->
|
||||
.file_name(name);
|
||||
app.ask_file(dialog, Bound::Project, |app, paths| {
|
||||
if let Some(path) = paths.first()
|
||||
&& let Some(result) = app.run("file.exportMesh", json!({"path": path.display().to_string()}))
|
||||
&& let Some(result) =
|
||||
app.run("file.exportMesh", json!({"path": path.display().to_string(), "recomputeNormals": app.ui.mesh_recompute_normals}))
|
||||
{
|
||||
let saved_path = result["path"].as_str().unwrap_or_default();
|
||||
app.toast(trf("Exported mesh to {path}", &[("path", &saved_path)]), false);
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
//! The desktop autosave writes each project's copy to a file of its own. This is a test binary of its own because it
|
||||
//! points the process's data folder at a temporary one
|
||||
|
||||
#![cfg(not(target_arch = "wasm32"))]
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use egui_kittest::Harness;
|
||||
use serde_json::json;
|
||||
use texturecraft_engine::geom::primitives;
|
||||
use texturecraft_engine::{Session, execute};
|
||||
use texturecraft_ui_egui::TextureCraftApp;
|
||||
|
||||
/// App time each frame advances by, so a few frames pass any autosave interval
|
||||
const FRAME_SECONDS: f32 = 600.0;
|
||||
|
||||
/// How long the worker thread gets to write a copy
|
||||
const WRITE_TIMEOUT: Duration = Duration::from_secs(60);
|
||||
|
||||
/// A project named as one made from `hero.fbx` would be, with `layers` paint layers added since it was saved
|
||||
fn unsaved_hero(layers: usize) -> Session {
|
||||
let mut session = Session::new_project("hero", primitives::cube(1.0), "builtin:cube", None, 128).unwrap();
|
||||
for _ in 0..layers {
|
||||
execute(&mut session, "layer.add.paint", &json!({})).unwrap();
|
||||
}
|
||||
session
|
||||
}
|
||||
|
||||
fn copies(folder: &Path) -> Vec<PathBuf> {
|
||||
let files = std::fs::read_dir(folder).map(|entries| entries.flatten().map(|entry| entry.path()).collect::<Vec<_>>()).unwrap_or_default();
|
||||
files.into_iter().filter(|path| path.extension().is_some_and(|extension| extension == "tcraft")).collect()
|
||||
}
|
||||
|
||||
/// Runs an app on `session` until the autosave folder holds `count` copies
|
||||
fn autosave(session: Session, folder: &Path, count: usize) -> Harness<'static, TextureCraftApp> {
|
||||
let mut harness = Harness::builder()
|
||||
.with_step_dt(FRAME_SECONDS)
|
||||
.with_context_setup(texturecraft_ui_egui::framework::install_headless)
|
||||
.build_eframe(|cc| TextureCraftApp::new(cc, session));
|
||||
let started = Instant::now();
|
||||
while copies(folder).len() < count {
|
||||
harness.step();
|
||||
assert!(started.elapsed() < WRITE_TIMEOUT, "autosave wrote {:?}", copies(folder));
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
harness
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_projects_of_one_name_keep_two_autosave_copies() {
|
||||
let data = std::env::temp_dir().join(format!("tc-autosave-files-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&data);
|
||||
texturecraft_ui_egui::set_data_root(data.clone());
|
||||
let folder = data.join("autosave");
|
||||
|
||||
let first = autosave(unsaved_hero(1), &folder, 1);
|
||||
let second = autosave(unsaved_hero(2), &folder, 2);
|
||||
drop((first, second));
|
||||
|
||||
// Each copy opens as the project that wrote it
|
||||
let mut layers: Vec<usize> =
|
||||
copies(&folder).iter().map(|path| texturecraft_engine::file_cmds::open_path(path.to_str().unwrap()).unwrap().doc.project.layers.len()).collect();
|
||||
layers.sort_unstable();
|
||||
assert_eq!(layers[1], layers[0] + 1, "{layers:?}");
|
||||
|
||||
std::fs::remove_dir_all(&data).unwrap();
|
||||
}
|
||||
@@ -83,6 +83,7 @@ mod rail;
|
||||
mod reference_order;
|
||||
mod rename_anchor;
|
||||
mod reset_ui;
|
||||
mod resources_updater;
|
||||
mod sample_project;
|
||||
mod settings_window;
|
||||
mod shelf_click;
|
||||
|
||||
@@ -0,0 +1,240 @@
|
||||
//! The Resources Updater window, driven from the keyboard: the shelf button opens it, outdated
|
||||
//! resources come first, Update reads a changed file again as one undo step and Select new resource
|
||||
//! follows another file. File pickers are answered by the override, never shown.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use egui::{Key, Role, vec2};
|
||||
use egui_kittest::Harness;
|
||||
use egui_kittest::kittest::{NodeT, Queryable};
|
||||
use serde_json::json;
|
||||
use texturecraft_engine::Session;
|
||||
use texturecraft_ui_egui::TextureCraftApp;
|
||||
use texturecraft_ui_egui::file_dialogs::{Answer, Request};
|
||||
use texturecraft_ui_egui::state::ViewLayout;
|
||||
|
||||
use super::temp_dir::TempDir;
|
||||
|
||||
fn app() -> Harness<'static, TextureCraftApp> {
|
||||
let session = Session::new_project("Test", texturecraft_engine::geom::primitives::cube(1.0), "builtin:cube", None, 128).unwrap();
|
||||
let mut h = Harness::builder()
|
||||
.with_size(egui::vec2(1600.0, 960.0))
|
||||
.with_context_setup(texturecraft_ui_egui::framework::install_headless)
|
||||
.build_eframe(|cc| TextureCraftApp::new(cc, session));
|
||||
h.state_mut().ui.prefs.language = "en".into();
|
||||
h.run_steps(4);
|
||||
|
||||
h
|
||||
}
|
||||
|
||||
/// Write a `size` × `size` PNG (each size is a different file size, so a change is seen at once)
|
||||
fn png(dir: &Path, name: &str, size: u32) -> PathBuf {
|
||||
let file = dir.join(name);
|
||||
image::RgbaImage::from_pixel(size, size, image::Rgba([10, 200, 30, 255])).save(&file).unwrap();
|
||||
|
||||
file
|
||||
}
|
||||
|
||||
fn import(h: &mut Harness<'_, TextureCraftApp>, file: &Path) {
|
||||
h.state_mut().run("resource.import", json!({ "path": file.to_str().unwrap() })).unwrap();
|
||||
h.run_steps(2);
|
||||
}
|
||||
|
||||
fn press(h: &mut Harness<'_, TextureCraftApp>, key: Key) {
|
||||
h.key_press(key);
|
||||
h.run_steps(3);
|
||||
}
|
||||
|
||||
/// Move the keyboard focus to button `label` and press Enter
|
||||
fn activate(h: &mut Harness<'_, TextureCraftApp>, label: &str) {
|
||||
h.get_by_role_and_label(Role::Button, label).focus();
|
||||
h.run_steps(2);
|
||||
press(h, Key::Enter);
|
||||
}
|
||||
|
||||
fn shows(h: &Harness<'_, TextureCraftApp>, text: &str) -> bool {
|
||||
h.query_by_label(text).is_some()
|
||||
}
|
||||
|
||||
fn width_of(h: &Harness<'_, TextureCraftApp>, name: &str) -> u32 {
|
||||
h.state().session.images[name].width
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_window_opens_from_the_keyboard_and_updates_an_outdated_resource_as_one_undo_step() {
|
||||
let dir = TempDir::new("resources-updater-update");
|
||||
let (kept, changed) = (png(&dir, "aa_kept.png", 4), png(&dir, "zz_changed.png", 4));
|
||||
let mut h = app();
|
||||
import(&mut h, &kept);
|
||||
import(&mut h, &changed);
|
||||
png(&dir, "zz_changed.png", 8);
|
||||
|
||||
activate(&mut h, "Resources Updater");
|
||||
|
||||
let rows = &h.state().ui.windows.resources_updater.as_ref().expect("the window is open").rows;
|
||||
assert_eq!(rows[0].name, "zz_changed.png", "outdated resources come first, before names that sort earlier");
|
||||
assert!(shows(&h, "Project : Test"));
|
||||
assert_eq!(h.get_all_by_label("Shelf : project").count(), 2, "the reference's shelf line, one per row");
|
||||
assert!(shows(&h, "(2 resources, 1 outdated)"));
|
||||
assert!(shows(&h, "Outdated"), "the status is written out, not only coloured");
|
||||
assert!(h.get_by_role_and_label(Role::Button, "Update aa_kept.png").accesskit_node().is_disabled(), "only outdated resources update");
|
||||
|
||||
let steps = h.state().session.history_labels().len();
|
||||
activate(&mut h, "Update zz_changed.png");
|
||||
|
||||
assert_eq!(width_of(&h, "zz_changed.png"), 8, "the new file's pixels are in the project");
|
||||
assert_eq!(h.state().session.history_labels().len(), steps + 1, "one undo step");
|
||||
assert!(shows(&h, "(2 resources, 0 outdated)"));
|
||||
let result = h.get_by_label("Updated 1 resources");
|
||||
assert_eq!(result.accesskit_node().live(), egui::accesskit::Live::Polite, "the update result is announced away from focus");
|
||||
|
||||
// Undo brings the old pixels back, so Refresh shows the file as changed again
|
||||
h.state_mut().run("edit.undo", json!({})).unwrap();
|
||||
activate(&mut h, "Refresh resources");
|
||||
|
||||
assert_eq!(width_of(&h, "zz_changed.png"), 4);
|
||||
assert!(shows(&h, "(2 resources, 1 outdated)"));
|
||||
|
||||
activate(&mut h, "Update All");
|
||||
assert_eq!(width_of(&h, "zz_changed.png"), 8);
|
||||
|
||||
// Update All went grey with nothing left to update; the keyboard moves on to another button of the window
|
||||
h.get_by_role_and_label(Role::Button, "Select new resource aa_kept.png").focus();
|
||||
h.run_steps(2);
|
||||
press(&mut h, Key::Escape);
|
||||
assert!(h.state().ui.windows.resources_updater.is_none(), "Escape closes the window while it has the keyboard");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn select_new_resource_follows_the_chosen_file_and_the_name_filter_narrows_the_list() {
|
||||
let dir = TempDir::new("resources-updater-relink");
|
||||
let (first, second) = (png(&dir, "first.png", 4), png(&dir, "second.png", 4));
|
||||
let other = png(&dir, "other.png", 16);
|
||||
let mut h = app();
|
||||
import(&mut h, &first);
|
||||
import(&mut h, &second);
|
||||
activate(&mut h, "Resources Updater");
|
||||
|
||||
h.state_mut().file_dialogs.set_override(Some(Box::new(move |_: &Request| Answer::Paths(vec![other.clone()]))));
|
||||
activate(&mut h, "Select new resource first.png");
|
||||
h.run_steps(3);
|
||||
|
||||
assert_eq!(width_of(&h, "first.png"), 16, "the resource keeps its name and takes the chosen file's pixels");
|
||||
let source = &h.state().session.doc.project.resource_sources["first.png"].path;
|
||||
assert!(source.ends_with("other.png"));
|
||||
let announcement = format!("first.png now reads {source}");
|
||||
let result = h.get_by_label(&announcement);
|
||||
assert_eq!(result.accesskit_node().live(), egui::accesskit::Live::Polite, "the relink result is announced away from focus");
|
||||
|
||||
h.get_by_role_and_label(Role::TextInput, "Name filter:").focus();
|
||||
h.run_steps(2);
|
||||
h.get_by_role_and_label(Role::TextInput, "Name filter:").type_text("SEC");
|
||||
h.run_steps(3);
|
||||
|
||||
assert!(h.query_by_label("Update first.png").is_none(), "the filter hides other names");
|
||||
assert!(h.query_by_label("Update second.png").is_some(), "names match ignoring case");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn show_in_folder_shows_the_folder_of_the_resource_file_and_materials_have_no_file() {
|
||||
let dir = TempDir::new("resources-updater-folder");
|
||||
let file = png(&dir, "bricks.png", 4);
|
||||
let mut h = app();
|
||||
import(&mut h, &file);
|
||||
|
||||
// A linked MaterialCraft material keeps its package as a resource without a file
|
||||
let layer = h.state_mut().run("layer.add.fill", json!({})).unwrap()["layer"].as_u64().unwrap();
|
||||
let session = &mut h.state_mut().session;
|
||||
session.doc.resources.insert("brick.mcmat".to_string(), std::sync::Arc::new(b"package".to_vec()));
|
||||
let link = serde_json::from_value(json!({"name": "Brick", "package": "brick.mcmat", "graph": "Brick", "params": [], "size": 4})).unwrap();
|
||||
if let texturecraft_engine::core::LayerKind::Fill(fill) = &mut session.doc.project.layers.get_mut(&texturecraft_engine::core::LayerId(layer)).unwrap().kind
|
||||
{
|
||||
fill.link = Some(link);
|
||||
}
|
||||
activate(&mut h, "Resources Updater");
|
||||
|
||||
activate(&mut h, "Show in folder bricks.png");
|
||||
|
||||
let shown = h.state().file_dialogs.shown_folders().to_vec();
|
||||
assert_eq!(shown.len(), 1);
|
||||
assert_eq!(shown[0].file_name(), dir.file_name(), "the file's own folder");
|
||||
assert!(shows(&h, "Name : brick.mcmat"), "the material is listed");
|
||||
assert!(h.query_by_label("Select new resource brick.mcmat").is_none(), "a material cannot point at an image file");
|
||||
assert!(h.query_by_label("Show in folder brick.mcmat").is_none(), "it has no file");
|
||||
assert!(h.get_by_label("Update brick.mcmat").accesskit_node().is_disabled());
|
||||
assert!(
|
||||
h.get_all_by_label("Material").any(|node| node.accesskit_node().description().is_some_and(|text| text.contains("stored in the project"))),
|
||||
"the material status explains the stored package in the accessibility tree"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn escape_cancels_a_stroke_while_the_window_is_open_without_the_keyboard() {
|
||||
const FRAMES_PER_DRAG_EVENT: usize = 2;
|
||||
|
||||
let mut h = app();
|
||||
h.state_mut().run("layer.add.paint", json!({})).unwrap();
|
||||
h.state_mut().ui.layout = ViewLayout::Only3D;
|
||||
h.run_steps(3);
|
||||
let center = h.state().viewport_rect.center();
|
||||
h.drag_at(center);
|
||||
h.run_steps(FRAMES_PER_DRAG_EVENT);
|
||||
h.hover_at(center + vec2(20.0, 0.0));
|
||||
h.run_steps(FRAMES_PER_DRAG_EVENT);
|
||||
assert!(h.state().session.stroke_active());
|
||||
|
||||
// Opened from the shelf mid-stroke, the keyboard stays on the shelf button
|
||||
activate(&mut h, "Resources Updater");
|
||||
assert!(h.state().ui.windows.resources_updater.is_some());
|
||||
assert!(h.state().session.stroke_active());
|
||||
|
||||
press(&mut h, Key::Escape);
|
||||
|
||||
assert!(!h.state().session.stroke_active(), "Escape cancels the stroke");
|
||||
assert!(h.state().ui.windows.resources_updater.is_some(), "the window keeps open: its controls do not have the keyboard");
|
||||
h.drop_at(center + vec2(30.0, 0.0));
|
||||
h.run_steps(3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_changed_while_the_window_stays_open_shows_without_refresh() {
|
||||
/// Steps of the harness's quarter second: over the window's half-second check
|
||||
const FRAMES: usize = 4;
|
||||
|
||||
let dir = TempDir::new("resources-updater-idle");
|
||||
let file = png(&dir, "bricks.png", 4);
|
||||
let mut h = app();
|
||||
import(&mut h, &file);
|
||||
activate(&mut h, "Resources Updater");
|
||||
assert!(shows(&h, "(1 resources, 0 outdated)"));
|
||||
|
||||
png(&dir, "bricks.png", 8);
|
||||
h.run_steps(FRAMES);
|
||||
|
||||
let summary = h.get_by_label("(1 resources, 1 outdated)");
|
||||
assert_eq!(summary.accesskit_node().live(), egui::accesskit::Live::Polite, "an idle change is announced away from keyboard focus");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_keyboard_focus_stays_with_its_resource_when_the_rows_reorder() {
|
||||
/// Steps of the harness's quarter second: over the window's half-second check
|
||||
const FRAMES: usize = 4;
|
||||
const SELECT_LATER: &str = "Select new resource zz_later.png";
|
||||
|
||||
let dir = TempDir::new("resources-updater-focus");
|
||||
let (earlier, later) = (png(&dir, "aa_earlier.png", 4), png(&dir, "zz_later.png", 4));
|
||||
let mut h = app();
|
||||
import(&mut h, &earlier);
|
||||
import(&mut h, &later);
|
||||
activate(&mut h, "Resources Updater");
|
||||
h.get_by_role_and_label(Role::Button, SELECT_LATER).focus();
|
||||
h.run_steps(2);
|
||||
|
||||
// The changed file moves to the top of the list
|
||||
png(&dir, "zz_later.png", 8);
|
||||
h.run_steps(FRAMES);
|
||||
|
||||
let rows = &h.state().ui.windows.resources_updater.as_ref().unwrap().rows;
|
||||
assert_eq!(rows[0].name, "zz_later.png", "the outdated resource moved up");
|
||||
assert!(h.get_by_role_and_label(Role::Button, SELECT_LATER).accesskit_node().is_focused(), "the focus moved with it");
|
||||
}
|
||||
@@ -177,6 +177,31 @@ fn export_mesh_asks_the_options_then_the_file() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recompute_normals_is_an_enabled_keyboard_operable_checkbox() {
|
||||
let mut harness = app();
|
||||
let context = harness.ctx.clone();
|
||||
texturecraft_ui_egui::menus::invoke(harness.state_mut(), &context, "file.exportMesh");
|
||||
harness.run_steps(SETTLE_FRAMES);
|
||||
let checkbox = harness.get_by_role_and_label(Role::CheckBox, "Recompute vertex normals");
|
||||
assert!(!checkbox.accesskit_node().is_disabled(), "the option is really available");
|
||||
assert!(!is_on(&checkbox), "stored normals are kept until the user opts in");
|
||||
assert!(!harness.state().ui.mesh_recompute_normals);
|
||||
|
||||
checkbox.focus();
|
||||
harness.key_press(egui::Key::Space);
|
||||
harness.run_steps(SETTLE_FRAMES);
|
||||
assert!(harness.state().ui.mesh_recompute_normals, "Space changes the setting used by export");
|
||||
let checkbox = harness.get_by_role_and_label(Role::CheckBox, "Recompute vertex normals");
|
||||
assert!(is_on(&checkbox), "the accessibility tree reports the checked state");
|
||||
assert_eq!(checkbox.accesskit_node().label().as_deref(), Some("Recompute vertex normals"));
|
||||
|
||||
checkbox.click();
|
||||
harness.run_steps(SETTLE_FRAMES);
|
||||
assert!(!harness.state().ui.mesh_recompute_normals, "a pointer click turns it back off");
|
||||
assert!(!is_on(&harness.get_by_role_and_label(Role::CheckBox, "Recompute vertex normals")));
|
||||
}
|
||||
|
||||
/// Whether the Log lists `line` (the status bar under it repeats the last message)
|
||||
fn log_lists(harness: &Harness<'_, TextureCraftApp>, line: &str) -> bool {
|
||||
harness.query_all_by_label(line).any(|node| node.rect().bottom() < STATUS_BAR_TOP)
|
||||
@@ -289,6 +314,70 @@ fn shader_settings_show_the_reference_rows_and_the_shader_choice() {
|
||||
assert!(harness.get_by_label(&tiles[1]).accesskit_node().is_disabled(), "the others are not available yet");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_unchecked_ior_control_is_visible_at_each_brightness() {
|
||||
use craft_theme::{Contrast, Rgba, contrast_ratio, non_text_contrast_min};
|
||||
use texturecraft_ui_egui::theme::{Brightness, Tokens};
|
||||
|
||||
let mut harness = app();
|
||||
click_rail(&mut harness, "Shader Settings");
|
||||
let minimum_contrast = non_text_contrast_min(Contrast::Standard);
|
||||
|
||||
for brightness in Brightness::ALL {
|
||||
harness.state_mut().ui.prefs.brightness = brightness;
|
||||
harness.run_steps(SETTLE_FRAMES);
|
||||
|
||||
let checkbox = harness.get_by_role_and_label(Role::CheckBox, "Use IOR for specular reflection");
|
||||
let bounds = checkbox.rect();
|
||||
let panel = Tokens::get(&harness.ctx).panel;
|
||||
let indicator = harness
|
||||
.output()
|
||||
.shapes
|
||||
.iter()
|
||||
.filter_map(|painted| match &painted.shape {
|
||||
egui::Shape::Rect(frame) if painted.clip_rect.contains_rect(frame.rect) && bounds.contains_rect(frame.rect) => Some(frame),
|
||||
_ => None,
|
||||
})
|
||||
.find(|frame| frame.fill.a() > 0 || !frame.stroke.is_empty())
|
||||
.expect("the unchecked indicator is painted inside its accessibility bounds");
|
||||
let fill = panel.blend(indicator.fill);
|
||||
let outline = if indicator.stroke.width > 0.0 { fill.blend(indicator.stroke.color) } else { fill };
|
||||
let contrast = |color: egui::Color32| contrast_ratio(Rgba(color.to_array()), Rgba(panel.to_array()));
|
||||
let ratio = contrast(fill).max(contrast(outline));
|
||||
|
||||
assert!(ratio >= minimum_contrast, "{brightness:?}: the unchecked box has {ratio:.2}:1 contrast against the panel");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keyboard_toggles_ior_reflectance_only_in_metallic_roughness() {
|
||||
let mut harness = app();
|
||||
let label = "Use IOR for specular reflection";
|
||||
harness.state_mut().ui.dock.focus(Panel::Shader);
|
||||
harness.state_mut().session.modified = false;
|
||||
harness.run_steps(SETTLE_FRAMES);
|
||||
let checkbox = harness.get_by_role_and_label(Role::CheckBox, label);
|
||||
assert_eq!(checkbox.accesskit_node().toggled(), Some(egui::accesskit::Toggled::False));
|
||||
checkbox.focus();
|
||||
harness.run_steps(SETTLE_FRAMES);
|
||||
|
||||
harness.key_press(egui::Key::Space);
|
||||
harness.run_steps(SETTLE_FRAMES);
|
||||
|
||||
let checkbox = harness.get_by_role_and_label(Role::CheckBox, label);
|
||||
assert!(checkbox.is_focused());
|
||||
assert!(is_on(&checkbox));
|
||||
assert!(harness.state().session.doc.project.display.ior_specular);
|
||||
assert!(harness.state().session.modified);
|
||||
|
||||
harness.state_mut().run("display.set", serde_json::json!({"specGloss": true})).unwrap();
|
||||
harness.run_steps(SETTLE_FRAMES);
|
||||
|
||||
let checkbox = harness.get_by_role_and_label(Role::CheckBox, label);
|
||||
assert!(checkbox.accesskit_node().is_disabled());
|
||||
assert!(is_on(&checkbox), "the current preference is retained");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shader_edit_marks_the_project_modified() {
|
||||
let mut harness = app();
|
||||
|
||||
@@ -235,7 +235,7 @@ keeps its state in a throwaway file.
|
||||
| `session.inspect` | | project, mesh, texture sets, layer stack, tool, camera, display, history |
|
||||
| `ui.inspect` | | UI state, viewport rect, fps, bake progress (`baking`, 0..1), the running bake's stage (`bakeStatus`, e.g. "Baking Ambient Occlusion (2/4)") and live preview (`bakePreview`, see *Live bake preview*), toasts, `titleBar` (who draws the title bar this run: `app`, `integrated` on macOS, or `system`) |
|
||||
| `ui.menu.list` | | the menu catalog: `{menu, submenu, label, id, shortcut, implemented, enabled, checked}` |
|
||||
| `ui.menu.invoke` | `{id}` | behaves like a menu click (may open a window; `ui.resetUi` opens its question; `file.exportMesh` opens the Mesh Export Options prompt, whose Export asks for the file; `ui.view.export` opens the right bar's Export panel). `{"id": "ui.layout.apply", "name": "<layout>"}` switches to a legacy named panel layout (still accessible through assigned shortcuts) (panels only; mode, zoom and wireframes stay) and errors when no layout has that name. `ui.layout.save` still saves the active mode; `ui.layout.save.painting`, `ui.layout.save.rendering` and `ui.layout.save.baking` ask where to save only that mode's panels and view arrangement as a JSON file (without preferences or recent projects); loading preserves the other modes, `ui.layout.load` asks for one to load ("Load UI Layout"); `ui.toolbar.docks` and `ui.toolbar.tools` show or hide the right bar and the painting tools; the disabled Snooze Autosave and Resources Updater buttons stay visible when Tools is off; `ui.view.renderer` toggles the Renderer Settings panel (Rendering Mode only). `{"id": "ui.layout.swap"}` swaps the 3D and 2D views of the split layout (F4) |
|
||||
| `ui.menu.invoke` | `{id}` | behaves like a menu click (may open a window; `ui.resetUi` opens its question; `file.exportMesh` opens the Mesh Export Options prompt, whose Export asks for the file; `ui.view.export` opens the right bar's Export panel). `{"id": "ui.layout.apply", "name": "<layout>"}` switches to a legacy named panel layout (still accessible through assigned shortcuts) (panels only; mode, zoom and wireframes stay) and errors when no layout has that name. `ui.layout.save` still saves the active mode; `ui.layout.save.painting`, `ui.layout.save.rendering` and `ui.layout.save.baking` ask where to save only that mode's panels and view arrangement as a JSON file (without preferences or recent projects); loading preserves the other modes, `ui.layout.load` asks for one to load ("Load UI Layout"); `ui.toolbar.docks` and `ui.toolbar.tools` show or hide the right bar and the painting tools; the disabled Snooze Autosave button and the Resources Updater button (enabled while a project is open) stay visible when Tools is off; `ui.view.renderer` toggles the Renderer Settings panel (Rendering Mode only). `{"id": "ui.layout.swap"}` swaps the 3D and 2D views of the split layout (F4) |
|
||||
| `ui.menu.invoke` id `project.sample` | `{id}` | File > Open Sample Project opens a picker for a `.tcraft` file. On desktop, it copies any missing bundled samples (currently `Material Ball.tcraft`) into `Samples` under the data folder and opens the picker there. If preparation fails, it shows an error and opens the picker without a start folder. In the browser, the picker uses local files. The direct `project.sample` engine command generates a sample for automation. |
|
||||
| `ui.menu.invoke` id `ui.saveAsTemplate` | `{id}` | File > More Save Options > Save As Template opens a save dialog in the user templates folder. The choice supplies the file path and template name to `project.template.save`. `ui.saveReduced` (Save and Reduce File Size) is listed as not implemented and not enabled |
|
||||
| `ui.menu.invoke` ids `ui.help.releaseNotes`, `ui.help.showLog`, `ui.help.exportLog` | `{id}` | Help > Release Notes opens the releases page in the browser; Help > Show Log opens the current desktop run's rolling `log.txt` in the system text-file handler; Help > Export Log exports the session log with each entry’s recorded UTC time, severity and source (a save dialog on desktop with a `Log_TextureCraft_<version>_<date>_<os>_<gpuMode>.txt` name, a download on the web) |
|
||||
@@ -368,7 +368,8 @@ A `prefs` object without `language` sets the system language (`""`), the default
|
||||
File › Save.
|
||||
|
||||
Through `command_run`, every `file.*` command but `file.close` and `file.removeUnused` (and
|
||||
`file.reimportMesh` without a `path`) is refused, and so is any command given a `path` or `dir`, at the top level or in
|
||||
`file.reimportMesh` without a `path`) is refused, and so are `resource.status`, `resource.update` and `resource.relink` (they read
|
||||
the files a project names) and any command given a `path` or `dir`, at the top level or in
|
||||
a `files` entry (`resource.import`, `material.save`, `material.load`, `textureSet.meshMap.import`, …), in both modes: use the workspace tools below. `resource.text`
|
||||
takes a font family, not a path: it reads only the system's font folders.
|
||||
|
||||
@@ -390,7 +391,7 @@ With `rebuildUvs: true`, the project file saves the generated layout. Reopening
|
||||
| `project_save` | `{path?}` | `.tcraft` (appended if missing), relative to the write root |
|
||||
| `mesh_import` | `{path, resolution?}` | New project from .glb/.gltf/.fbx/.dae/.usd/.usda/.usdc/.usdz/.abc/.obj/.ply/.stl; a .gltf's buffers and images and a loose USD layer's textures are read from its folder |
|
||||
| `mesh_reimport` | `{path?, preserveStrokes?}` | Reimport the mesh from a file, or (no path) from the project's own copy; bridge mode supports only the latter |
|
||||
| `mesh_export` | `{path, format?}` | The mesh as obj, glb, usda, usdc or usdz below the write root (obj: its .mtl and textures, usda / usdc: textures next to it) → `{path, textures?}` |
|
||||
| `mesh_export` | `{path, format?, recomputeNormals?}` | The mesh as obj, glb, usda, usdc or usdz below the write root; `recomputeNormals: true` writes smooth area-weighted normals on the exported copy (default false) (obj: its .mtl and textures, usda / usdc: textures next to it) → `{path, textures?}` |
|
||||
| `bake_mesh_add` | `{path, cage?}` | Add a high-definition mesh for baking, or set the cage → `{name, meshes}` |
|
||||
| `resource_import` | `{path}` | Image resource (png, jpg, tga, tif, bmp, webp, exr, hdr) → its name, for `layer.add.image` / `tool.stencil`, or as a mesh map instead of baking it: `textureSet.meshMap.set {ts?, map, image}` (`textureSet.meshMap.clear {ts?, map}` empties the slot); call it once per baked map file (the desktop app's `textureSet.meshMap.import`, which takes host paths, is refused through `command_run`) |
|
||||
| `material_save` | `{path, layer?, name?}` | A layer or folder as a `.tcmat` smart material below the write root |
|
||||
@@ -465,7 +466,7 @@ File access follows `--read-root` / `--write-root` as for MCP.
|
||||
| `project.save` | `{path?}` |
|
||||
| `mesh.import` | `{path, resolution?, name?}` |
|
||||
| `mesh.reimport` | `{path?, preserveStrokes?}` |
|
||||
| `mesh.export` | `{path, format?}` |
|
||||
| `mesh.export` | `{path, format?, recomputeNormals?}` |
|
||||
| `bake.mesh.add` | `{path, cage?}` |
|
||||
| `resource.import` | `{path}` |
|
||||
| `material.save` | `{path, layer?, name?}` |
|
||||
@@ -490,6 +491,31 @@ printf '%s\n' '{"id":1,"method":"command.run","params":{"id":"project.new","para
|
||||
'{"id":2,"method":"render","params":{"width":512,"height":512}}' | texturecraft-cli serve
|
||||
```
|
||||
|
||||
## Resources Updater
|
||||
|
||||
An image resource read from a file remembers that file (its absolute path and modification time,
|
||||
saved with the project): `resource.import {path}`, the images `file.importPbrFolder` stores unchanged
|
||||
(not ORM channels split out, not archive entries), the images of `file.importMaterialX` and the files of
|
||||
`textureSet.meshMap.import` (with their mesh map: an update resamples it while it still holds what the
|
||||
old file gave it, so a bake or another image set over it since is kept). The shelf's Resources Updater
|
||||
window lists the project's images and linked MaterialCraft packages. It checks image files when it opens, on
|
||||
Refresh, twice a second while it stays open, once after a project opens and when the app gets the
|
||||
focus back; a notice ("N resources changed on disk", with an Update button) appears when the set of
|
||||
outdated resources differs from the last notice. A file whose size matches but whose time changed is
|
||||
read once. Its verdict is kept until its size or time changes again. When the file has no usable
|
||||
modification time, each check compares its contents.
|
||||
|
||||
| Command | Params and result |
|
||||
|---|---|
|
||||
| `resource.status` | `{}` → `{resources: [{name, status, path?, error?}], total, outdated}`; `status` is `outdated` (the file's size or contents differ from the resource), `missing` (the file is gone or unreadable, `error` says why), `upToDate`, `noSource` (made in the app or imported without a path) or `material` (the package of a linked MaterialCraft material, stored in the project without a source file); outdated first, then by name. An equal-size file is compared when its modification time changed or is unknown |
|
||||
| `resource.update` | `{names?: [name]}` (default: every outdated resource) → `{updated, failed: [{name, error}]}`: reads the files again and replaces the resources' bytes and pixels under the same names, so every layer, mask and view using them recomposites; one undo step, none when nothing changed. A file that cannot be read fails alone; when none could be read the command is an error. Unknown names and resources without a file are refused |
|
||||
| `resource.relink` | `{name, path}` → `{name, path}`: an image resource takes the image file's pixels (within the image import limits) and follows that file from then on; one undo step |
|
||||
|
||||
For linked fill layers, `material.link.cook` refreshes the separate cooked image maps from the stored package.
|
||||
|
||||
These commands read host paths stored in the project, so MCP and `serve` refuse them through
|
||||
`command_run`; the desktop app's control channel and the trusted local CLI run them.
|
||||
|
||||
## PBR texture folders
|
||||
|
||||
`file.importPbrFolder` turns a folder, a `.zip` or a list of image files of PBR maps into one fill layer
|
||||
@@ -634,6 +660,10 @@ None is an undo step.
|
||||
`display.set` also takes `alignment` (`world` or `camera`: the environment, and the key light with it,
|
||||
turns with the camera about the vertical axis), `shadowMode` (`intensive`, `average` or `lightweight`, the
|
||||
default: the shadow map's resolution) and `shadowOpacity` (0 to 1, default 1: how dark the shadows are).
|
||||
Set `iorSpecular` to true to derive the Metallic Roughness surface reflectance at normal incidence
|
||||
from `ior` (clamped to 1–3). Specular Level scales this reflectance in the viewport, both path
|
||||
tracers and F0 map export. Path-traced transmission uses its own Fresnel calculation for glass
|
||||
interfaces. The setting defaults to false and is saved with the project and its templates.
|
||||
|
||||
`viewport.view {mode: "image", image: <image resource>}` shows a project image as it is, stretched over
|
||||
the UV square, on the mesh and in the 2D view (the view picker's "Other..."). `display.set {soloUnlit}`
|
||||
|
||||
+19
-3
@@ -98,6 +98,15 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA
|
||||
and alpha images become the brush alpha. Filter by role or remove selected rows before importing.
|
||||
Failed rows stay in the dialog for retry. Color LUT, post effects and asset-library import are
|
||||
unavailable. The browser imports images straight from its file picker.
|
||||
- **Resources Updater:** the desktop tool shelf lists the project's image resources, with outdated
|
||||
resources first. Filter by status or name, and use *Show in folder* to find a linked file. Images
|
||||
imported from disk through Import resources, PBR folders, MaterialX and mesh map import remember
|
||||
their source file. *Update* and *Update All* reread changed files in one undo step. Layers see the
|
||||
updated image, and an imported mesh map refreshes while it still matches the previous source.
|
||||
*Select new resource* links an image to another file. The list refreshes while the window is open,
|
||||
and a notice offers *Update* when changed files are found on opening a project or regaining focus.
|
||||
Linked MaterialCraft packages appear without a source file. Re-cooking a linked fill layer refreshes
|
||||
its cooked maps.
|
||||
- **Your own library:** right-click a layer or folder, choose *Create smart material*, and it
|
||||
appears under *My smart materials*, pixels and images included. *Create smart mask* in the same
|
||||
menu saves just the layer's mask (all its effects, painted pixels and images); it appears under
|
||||
@@ -258,9 +267,13 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA
|
||||
- **Its own title bar** with the app icon, menus and window buttons on Windows (and on Linux
|
||||
desktops that leave the frame to the app, such as GNOME), the macOS traffic lights over the same
|
||||
strip, and the system's frame instead with `prefs.system_title_bar` through `ui.set` (for now).
|
||||
- **A pen on a Linux Wayland desktop** opens the window through Xwayland, where the pen moves the
|
||||
cursor and paints (some compositors send a pen nothing in a native Wayland window);
|
||||
`TEXTURECRAFT_NATIVE_WAYLAND=1` keeps native Wayland.
|
||||
- **A pen on a Linux Wayland desktop** can move the cursor and paint as a pointer through Xwayland.
|
||||
At launch, TextureCraft uses Xwayland when it detects a pen, finds the X11 libraries and the
|
||||
local X server accepts setup. Otherwise it uses native Wayland. Set
|
||||
`TEXTURECRAFT_NATIVE_WAYLAND=1` to keep native Wayland. The Flatpak grants X11 access only as a
|
||||
fallback when Wayland is unavailable. Linux pen pressure is tracked separately in
|
||||
[#818](https://github.com/storytold/texturecraft/pull/818) and
|
||||
[#816](https://github.com/storytold/texturecraft/issues/816).
|
||||
- **Dockable, tabbed and floating panels**, saved layouts, and panels that reopen where you closed
|
||||
them. The right bar's panels (Export, Log, Display Settings, Shader Settings, History) pop out
|
||||
beside it; *Undock* makes one a floating window, and its *Dock* button puts it back on the bar.
|
||||
@@ -282,6 +295,9 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA
|
||||
- A **data folder** of your choice for autosaves, smart materials, presets, templates and UI
|
||||
layouts, on any drive (Settings › General › Files › Data folder, with `Documents/TextureCraft` as
|
||||
the default). Nightly shows its fixed profile path in the same row.
|
||||
- **Autosave**: each project keeps its own copy in the data folder's `autosave`, named
|
||||
`<name>-copy-<suffix>.tcraft` after its saved file (or, until it is saved, the project), so projects made from
|
||||
one mesh never overwrite each other's copy.
|
||||
- A **Settings window** (Edit › Settings) with General, Shortcuts and Libraries pages; changes
|
||||
apply on OK and Cancel drops them. General holds the language (or the system's), the 3D view's
|
||||
rotation, zoom and wheel speeds with inverse directions, GPU or CPU bake rays, resource limits
|
||||
|
||||
+4
-2
@@ -71,8 +71,10 @@ that closes it back onto the bar; the float is saved with the UI state.
|
||||
with materials that refer to the exported textures; greyed in the browser), *Export shaders
|
||||
parameters* greyed, *Include all*, *Save settings* and "N textures selected for export").
|
||||
*Export MaterialX* beside them is a TextureCraft addition: it adds `materialX: true` to the
|
||||
export. The prompt's *With displacement/tessellation* choice and both option checkboxes are
|
||||
greyed; TextureCraft exports the mesh as it is.
|
||||
export. The prompt's *With displacement/tessellation* choice and *Apply triangulation* are greyed
|
||||
(TextureCraft exports the mesh as it is, triangulated). *Recompute vertex normals* works and sits under
|
||||
*Without displacement/tessellation*, off by default: it writes smooth area-weighted normals to the
|
||||
exported copy only.
|
||||
- **Window menu:** Views lists *Renderer Settings* (a panel of its own: the tracer in use, the
|
||||
samples so far and a note; it floats when first opened and is not opened by itself in Rendering
|
||||
mode), *Properties - Paint* while a project is open (other tools read "Properties - <tool>",
|
||||
|
||||
Reference in new issue
Block a user