Auto: Restore main CI and fix GPU update bounds and resource lifetimes

Integrate main’s seam padding, rectangular atlases, AO handling, and adapter selection. Restore its workflows and launcher, and use the existing Rayon scheduler for background rendering.

Validate brush readback and UV-grid bounds, preserve filter coverage when downscaling, and expose CPU fallback reasons to accessibility clients. Coalesce pending tile uploads, release retired GPU inputs, reuse upload buffers and filter plans, and avoid copying static shader fragments.

Organize introduced Rust types by name. Cover regional texture replacement, wrapped paint invalidation, and GPU sample rendering with island padding while retaining the default seam fallback test.
This commit is contained in:
chasse20
2026-11-30 03:44:22 +00:00
412 changed files with 24134 additions and 10963 deletions
+12 -2
View File
@@ -88,7 +88,9 @@
}
},
"max_artifact_bytes": 2147483648,
"automatic_signer_actors": [],
"automatic_signer_actors": [
"github-actions[bot]"
],
"platforms": {
"windows-x86_64": {
"unsigned_artifact_name": "nightly-unsigned-windows-x86_64",
@@ -100,7 +102,15 @@
"unsigned_artifact_name": "nightly-unsigned-linux-x86_64",
"trust": {
"fingerprint": "2B76741B414AAD6CD33E631213A005C0B9D7C3ED"
}
},
"package_formats": [
"appimage",
"arch",
"deb",
"flatpak",
"oci",
"rpm"
]
},
"macos-aarch64": {
"unsigned_artifact_name": "nightly-unsigned-macos-aarch64",
+1 -2
View File
@@ -26,7 +26,6 @@ jobs:
os: '["ubuntu-24.04","windows-latest"]'
# xtask ci runs cargo test (including doctests), not cargo nextest.
tools: ""
windows-command: pwsh -NoProfile -File .github/workflows/windows-vulkan-gate.ps1
packages: >-
libxkbcommon-dev libwayland-dev libx11-dev libxrandr-dev libxi-dev libgl1-mesa-dev
libgtk-3-dev mesa-vulkan-drivers
libgtk-3-dev
+2 -2
View File
@@ -11,9 +11,9 @@ permissions: {}
jobs:
dispatch:
# SOURCE PREPARATION: literal off until immutable shared tooling and policy qualification.
# Exact context guard only; admission belongs to the protected signer branch.
if: >-
false && github.repository == 'storytold/texturecraft' &&
github.repository == 'storytold/texturecraft' &&
github.event_name == 'workflow_run'
runs-on: ubuntu-latest
timeout-minutes: 5
+3 -2
View File
@@ -1,8 +1,9 @@
name: TextureCraft unsigned nightly
# Enabled for supervised manual runs by the reviewed manual actor only; no schedule yet.
# A later explicit opt-in may add a cadence (and turn on nightly-dispatch.yml with it).
# Automated daily schedule at 06:00 UTC plus supervised manual runs by reviewed manual actors.
on:
schedule:
- cron: '0 6 * * *'
workflow_dispatch:
permissions:
-62
View File
@@ -1,62 +0,0 @@
$ErrorActionPreference = 'Stop'
# Hosted Windows runners have no physical GPU. Use an isolated Vulkan ICD so
# the renderer tests run without relying on the D3D12 software driver.
$runtime = Join-Path ([System.IO.Path]::GetTempPath()) 'texturecraft-ci-vulkan'
New-Item -ItemType Directory -Path $runtime -Force | Out-Null
function Get-VerifiedArchive($uri, $name, $sha256) {
$archive = Join-Path $runtime $name
Invoke-WebRequest -Uri $uri -OutFile $archive -TimeoutSec 120
if ((Get-FileHash -LiteralPath $archive -Algorithm SHA256).Hash -ne $sha256) {
throw "Unexpected SHA-256 for $name"
}
return $archive
}
$mesa = Get-VerifiedArchive `
'https://github.com/pal1000/mesa-dist-win/releases/download/26.3.0/mesa3d-26.3.0-release-msvc.7z' `
'mesa.7z' 'C505FCC77E8F63A09D7DDAC086591D2F542C0698D37FC9E3094685A34D0D9991'
$loader = Get-VerifiedArchive `
'https://sdk.lunarg.com/sdk/download/1.4.363.0/windows/VulkanRT-X64-1.4.363.0-Components.zip' `
'vulkan.zip' 'A25A927AA8B9F0371048F1861CF88AC3B9BC9B1FB332C42D897C8AB32695769A'
# The shared action starts this script from Git Bash, whose tar treats C: as a remote host.
$system = [System.Environment]::SystemDirectory
$tar = Join-Path $system 'tar.exe'
& $tar -xf $mesa -C $runtime x64/lvp_icd.x86_64.json x64/vulkan_lvp.dll
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
$loaderRoot = 'VulkanRT-X64-1.4.363.0-Components/x64'
& $tar -xf $loader -C $runtime "$loaderRoot/vulkan-1.dll" "$loaderRoot/vulkaninfo.exe"
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
$loaderBin = Join-Path $runtime $loaderRoot
$env:PATH = "$loaderBin;$env:PATH"
$env:VK_DRIVER_FILES = Join-Path $runtime 'x64/lvp_icd.x86_64.json'
if ($env:RUNNER_ENVIRONMENT -eq 'github-hosted') {
# The loader can ignore environment-based driver discovery for elevated processes.
$drivers = 'HKLM:\SOFTWARE\Khronos\Vulkan\Drivers'
New-Item -Path $drivers -Force | Out-Null
New-ItemProperty -LiteralPath $drivers -Name $env:VK_DRIVER_FILES -PropertyType DWord -Value 0 -Force | Out-Null
$systemLoader = Join-Path $system 'vulkan-1.dll'
if (!(Test-Path -LiteralPath $systemLoader)) {
Copy-Item -LiteralPath (Join-Path $loaderBin 'vulkan-1.dll') -Destination $systemLoader
}
}
$env:WGPU_BACKEND = 'vulkan'
$env:TC_CI_LAVAPIPE = '1'
# Keep software devices from contending for all runner cores at once.
$env:RUST_TEST_THREADS = '2'
$env:LP_NUM_THREADS = '2'
# LLVM's optimisation passes cost more than the tests' shaders then run
$env:GALLIVM_PERF = 'nopt'
Write-Host 'Windows CI using Mesa Lavapipe 26.3.0 with Vulkan loader 1.4.363.0'
$summary = & (Join-Path $loaderBin 'vulkaninfo.exe') --summary
if ($LASTEXITCODE -ne 0 -or !($summary -match 'deviceName\s*=\s*llvmpipe')) {
$summary | Write-Host
throw 'Vulkan preflight did not find the Lavapipe adapter'
}
$summary | Select-String 'deviceType|deviceName|driverInfo' | ForEach-Object { Write-Host $_.Line }
cargo xtask ci
exit $LASTEXITCODE
Generated
+10
View File
@@ -1324,6 +1324,14 @@ dependencies = [
"serde",
]
[[package]]
name = "craft-nightly"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24#1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24"
dependencies = [
"winsafe",
]
[[package]]
name = "craft-pdf"
version = "0.1.0"
@@ -5949,6 +5957,7 @@ dependencies = [
"craft-host",
"craft-image-codecs",
"craft-menu",
"craft-nightly",
"craft-update",
"eframe",
"egui",
@@ -6119,6 +6128,7 @@ dependencies = [
"harfrust 0.12.0",
"rayon",
"serde",
"serde_json",
"skrifa 0.44.0",
"texturecraft-compose",
"texturecraft-core",
+2
View File
@@ -89,6 +89,8 @@ craft-menu = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a
craft-host = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
# The theme mode the app hands the runtime (crates/ui-egui/src/framework.rs).
craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
# Nightly profile isolation, launch protocol, and security fence (apps/texturecraft).
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24" }
# egui 0.37 and winit: the suite's forks (storytold/egui, storytold/winit), as craft-libs pins them.
[patch.crates-io]
+1 -1
View File
@@ -48,7 +48,7 @@ pub(crate) enum Command {
///
/// --camera looks through a camera saved in the project (camera.add); --samples path traces it
/// instead (Rendering mode), on the GPU when it has compute shaders, else (or with --cpu) on
/// the CPU.
/// the CPU (no GPU needed).
#[command(after_help = INPUTS)]
Render(RenderArgs),
/// A new project from a mesh or a built-in mesh
+28
View File
@@ -184,6 +184,34 @@ fn render_writes_a_png() {
let _ = std::fs::remove_dir_all(&d);
}
/// Without a GPU, the viewport render's error says what still works, and that does work. A backend
/// this platform lacks stands in for a machine without a GPU: the CLI's wgpu instance reads
/// `WGPU_BACKEND`.
#[test]
fn render_without_a_gpu_points_to_path_tracing() {
let d = tmp("no-gpu");
let out = d.join("cube.png");
let absent = if cfg!(target_os = "macos") { "dx12" } else { "metal" };
let render = |extra: &[&str]| {
Command::new(cli_binary())
.env("WGPU_BACKEND", absent)
.env_remove("WGPU_ADAPTER_NAME")
.env_remove("WGPU_POWER_PREF")
.args(["render", "builtin:cube", p(&out), "--size", "64x64"])
.args(extra)
.output()
.unwrap()
};
let o = render(&[]);
let err = String::from_utf8_lossy(&o.stderr);
assert_eq!(o.status.code(), Some(1), "{err}");
assert!(err.contains("cannot render") && err.contains("path tracing (`samples`) needs no GPU"), "{err}");
let o = render(&["--samples", "2"]);
assert!(o.status.success(), "{}", String::from_utf8_lossy(&o.stderr));
assert_eq!(image::open(&out).unwrap().width(), 64);
let _ = std::fs::remove_dir_all(&d);
}
#[test]
fn path_traced_render_needs_no_gpu() {
let d = tmp("trace");
+2
View File
@@ -25,6 +25,8 @@ log = { workspace = true }
rfd = { workspace = true }
# Pass the selected window backend to the title bar and UI runtime
craft-host = { workspace = true }
# Nightly profile isolation, launch protocol, and security fence.
craft-nightly = { workspace = true }
# Reads the saved System title bar setting before the window opens (eframe's settings format).
ron = "0.12"
+1 -31
View File
@@ -1,14 +1,9 @@
//! The build-time channel, which is distinct from a launch selector: no runtime environment can
//! promote a stable build into the Nightly one.
use crate::launch_profile::Profile;
use std::ffi::OsString;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BuildFlavor {
Stable,
NightlyV1,
}
pub use craft_nightly::BuildFlavor;
/// `TEXTURECRAFT_BUILD_CHANNEL=nightly-v1` at compile time (`build.rs`).
pub const COMPILED: BuildFlavor = if cfg!(texturecraft_nightly_v1) { BuildFlavor::NightlyV1 } else { BuildFlavor::Stable };
@@ -17,15 +12,6 @@ pub const COMPILED: BuildFlavor = if cfg!(texturecraft_nightly_v1) { BuildFlavor
/// workspace version (`build.rs` bakes it so both flavors read it the same way).
pub const BUILT_VERSION: &str = env!("TEXTURECRAFT_VERSION");
/// A nightly build starts only with its profile, and a stable build only without one.
pub fn require_profile(flavor: BuildFlavor, profile: &Profile) -> Result<(), String> {
match (flavor, profile.is_nightly()) {
(BuildFlavor::NightlyV1, false) => Err("Open TextureCraft Nightly from ArtCraft Launcher".into()),
(BuildFlavor::Stable, true) => Err("This is a stable TextureCraft build; nightly-v1 requires the nightly build".into()),
_ => Ok(()),
}
}
/// A refused nightly start explains itself in a native dialog: a release Windows build has no
/// console, and a Dock launch on macOS has none either.
pub fn needs_native_error(flavor: BuildFlavor, desktop_session: bool) -> bool {
@@ -58,22 +44,6 @@ mod tests {
assert!(!needs_native_error(BuildFlavor::Stable, false));
}
#[test]
fn nightly_build_without_a_profile_is_refused_before_startup() {
let started = std::cell::Cell::new(false);
let result = require_profile(BuildFlavor::NightlyV1, &Profile::Stable).map(|()| started.set(true));
assert!(result.unwrap_err().contains("ArtCraft Launcher"));
assert!(!started.get());
}
#[test]
fn stable_and_nightly_flavors_accept_only_their_own_profile() {
let nightly = Profile::NightlyV1(std::path::PathBuf::from("already validated root"));
assert!(require_profile(BuildFlavor::Stable, &Profile::Stable).is_ok());
assert!(require_profile(BuildFlavor::Stable, &nightly).is_err());
assert!(require_profile(BuildFlavor::NightlyV1, &nightly).is_ok());
}
#[test]
fn the_nightly_version_line_is_exact_and_says_its_channel() {
let nightly = version(BuildFlavor::NightlyV1);
+4 -8
View File
@@ -84,19 +84,17 @@ pub fn pick_adapter_index(candidates: &[Candidate], named_filter: Option<&str>,
.iter()
.enumerate()
.min_by_key(|(orig_idx, c)| {
// Surface support is required; unsupported adapters rank last.
// The selected adapter must be able to present to the window
let surface_penalty = !c.surface_supported;
// Explicit named filter (e.g. --gpu nvidia, WGPU_ADAPTER_NAME=3080).
let name_penalty = match named_filter {
Some(filter) => !c.matches_filter(filter),
None => false,
};
// Hardware GPUs before software/CPU rasterizers.
let software_penalty = c.is_software();
// Native backends before OpenGL (except when preserving system order).
// Preserve system backend order when no power preference is set
let backend_rank = match (power, c.backend) {
(PowerPreference::None, _) => 0,
(_, Backend::Dx12) if cfg!(windows) => 1,
@@ -105,7 +103,6 @@ pub fn pick_adapter_index(candidates: &[Candidate], named_filter: Option<&str>,
_ => 3,
};
// Power preference ranking.
let power_rank = match power {
PowerPreference::HighPerformance => match c.device_type {
DeviceType::DiscreteGpu => 0,
@@ -148,9 +145,8 @@ pub fn configure(options: &mut NativeOptions, cli_gpu: Option<String>, cli_power
let device_descriptor = create.device_descriptor.clone();
create.device_descriptor = Arc::new(move |adapter| {
let mut descriptor = device_descriptor(adapter);
// The compositor sizes its bands and working buffers against the device's limits, so
// request everything the adapter reports, as `texturecraft_render::device_limits`
// does for headless devices. Negotiating a limit allocates nothing.
// Request adapter limits so compositor bands fit the same budget as headless renders
descriptor.required_limits = adapter.limits();
descriptor
});
+89 -172
View File
@@ -1,126 +1,30 @@
//! The Launcher's nightly-v1 bootstrap, selected before logging, updates, fonts or saved state.
//! Stable launches keep their arguments and directory policy unchanged, and no environment is
//! mutated: the profile is a value this process reads, not a variable it exports.
//! The Launcher's nightly-v1 bootstrap and direct-launch self-isolation, backed by `craft-nightly`.
//!
//! Selected before logging, updates, fonts or saved state. Stable launches keep their arguments and
//! directory policy unchanged, and no environment is mutated: the profile is a value this process
//! reads, not a variable it exports.
use std::ffi::OsString;
use std::path::{Component, Path, PathBuf};
use std::sync::OnceLock;
pub const VERSION: &str = "nightly-v1";
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Profile {
Stable,
NightlyV1(PathBuf),
}
impl Profile {
pub fn is_nightly(&self) -> bool {
matches!(self, Self::NightlyV1(_))
}
pub fn root(&self) -> Option<&Path> {
match self {
Self::Stable => None,
Self::NightlyV1(root) => Some(root),
}
}
}
#[derive(Debug, PartialEq, Eq)]
pub struct Launch {
pub profile: Profile,
pub args: Vec<OsString>,
}
static PROFILE: OnceLock<Profile> = OnceLock::new();
pub use craft_nightly::{BuildFlavor, Launch, Profile, ProfileError, StartupOptions};
pub fn current() -> &'static Profile {
PROFILE.get().unwrap_or(&Profile::Stable)
craft_nightly::current().unwrap_or(&Profile::Stable)
}
pub fn install(profile: Profile) -> Result<(), String> {
PROFILE.set(profile).map_err(|_| "the launch profile was already selected".into())
}
/// Recognize only the agreed literal selector/root pair before `--`. Everything after it is a
/// file, even when it looks like a profile flag. No filesystem or startup hook runs here.
pub fn parse(args: Vec<OsString>) -> Result<Launch, String> {
let mut selector = None;
let mut root = None;
let mut other = Vec::new();
let mut files = Vec::new();
let mut iter = args.iter();
let mut delimiter = false;
while let Some(arg) = iter.next() {
if arg == "--" {
delimiter = true;
files.extend(iter.cloned());
break;
}
if arg == "--launch-profile" || arg == "--profile-root" {
let slot = if arg == "--launch-profile" { &mut selector } else { &mut root };
if slot.is_some() {
return Err("the profile selector and root must each occur exactly once".into());
}
let value = iter.next().filter(|v| !v.is_empty()).ok_or("the profile selector/root needs a value")?;
if value.to_string_lossy().starts_with("--") {
return Err("the profile selector/root needs a value".into());
}
*slot = Some(value.clone());
} else if arg.to_string_lossy().starts_with("--launch-profile=") || arg.to_string_lossy().starts_with("--profile-root=") {
return Err("the nightly protocol requires separate literal selector/root argument tokens".into());
} else {
other.push(arg.clone());
}
}
match (selector, root) {
(None, None) => Ok(Launch { profile: Profile::Stable, args }),
(Some(version), Some(root)) if version == VERSION => {
if !delimiter || !other.is_empty() {
return Err("nightly-v1 accepts only its selector/root followed by -- and file names".into());
}
let root = PathBuf::from(root);
if !root.is_absolute() || root.components().any(|c| matches!(c, Component::ParentDir)) {
return Err("the nightly profile root must be absolute and contain no parent traversal".into());
}
Ok(Launch { profile: Profile::NightlyV1(root), args: std::iter::once(OsString::from("--")).chain(files).collect() })
}
(Some(_), Some(_)) => Err("unsupported launch profile (expected nightly-v1)".into()),
_ => Err("--launch-profile and --profile-root must be supplied together".into()),
}
}
/// The Launcher's version check: the selector/root pair followed by exactly `--version` (or `-V`),
/// answered like a plain version query. Only [`parse`]'s lexical checks apply; the root is never
/// validated or touched, and `-- --version` stays a file name.
pub fn version_query(args: &[OsString]) -> bool {
let Some((last, pair)) = args.split_last() else { return false };
if last != "--version" && last != "-V" {
return false;
}
let lexical = pair.iter().cloned().chain(std::iter::once(OsString::from("--"))).collect();
matches!(parse(lexical), Ok(Launch { profile: Profile::NightlyV1(_), args }) if args.len() == 1)
}
/// Validation finishes before the caller's first startup effect. Stable never calls the nightly
/// root validator, so its old directory resolution stays unchanged.
pub fn prepare(mut launch: Launch, validate: impl FnOnce(&Path) -> Result<PathBuf, String>) -> Result<Launch, String> {
if let Profile::NightlyV1(root) = &launch.profile {
launch.profile = Profile::NightlyV1(validate(root)?);
}
Ok(launch)
}
/// Resolve the selected private root before the caller's first startup effect.
pub fn validate_root(root: &Path, env: impl Fn(&str) -> Option<OsString>, exe: Option<&Path>) -> Result<PathBuf, String> {
crate::profile_root::validate(root, env, exe, crate::profile_root::ensure_writable)
/// Parse startup arguments for `flavor`, validate and prepare the isolated nightly profile root
/// (self-isolating into `craft_nightly::canonical_profile_root("texturecraft")` on direct nightly
/// launches, or using the explicit `--launch-profile nightly-v1 --profile-root <dir>` pair), and
/// install the resolved [`Profile`] into the process-wide `OnceLock`.
pub fn prepare(flavor: BuildFlavor, args: Vec<OsString>) -> Result<Launch, ProfileError> {
let spec = crate::profile_root::spec();
craft_nightly::prepare_launch(flavor, &spec, args, &StartupOptions::new())
}
#[cfg(test)]
mod tests {
use super::*;
use std::cell::Cell;
use std::path::PathBuf;
fn args(values: &[&str]) -> Vec<OsString> {
values.iter().map(OsString::from).collect()
@@ -130,88 +34,101 @@ mod tests {
if cfg!(windows) { r"C:\NightlyData\profiles\texturecraft" } else { "/nightly-data/profiles/texturecraft" }
}
fn nightly() -> Vec<OsString> {
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"])
}
#[test]
fn stable_arguments_and_directory_policy_are_unchanged() {
fn stable_arguments_are_unchanged_and_nightly_flags_are_refused() {
let spec = crate::profile_root::spec();
for argv in [args(&[]), args(&["model.glb"]), args(&["--gpu", "nvidia"]), args(&["--", "--launch-profile", "model.glb"])] {
let launch = prepare(parse(argv.clone()).unwrap(), |_| panic!("stable must never validate a nightly root")).unwrap();
assert_eq!(launch, Launch { profile: Profile::Stable, args: argv });
let launch = craft_nightly::parse_startup(BuildFlavor::Stable, &spec, argv.clone(), &StartupOptions::new()).unwrap();
assert_eq!(launch.profile, Profile::Stable);
assert_eq!(launch.passthrough_args, argv);
}
let nightly_flags = args(&["--launch-profile", craft_nightly::NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--"]);
let err = craft_nightly::parse_startup(BuildFlavor::Stable, &spec, nightly_flags, &StartupOptions::new()).unwrap_err();
assert!(matches!(err, ProfileError::NightlyFlagsInStableBuild));
}
#[test]
fn exact_version_and_root_are_parsed_without_reinterpreting_file_names() {
let mut argv = nightly();
argv.extend(args(&["--profile-root", "model with spaces.glb"]));
let launch = parse(argv).unwrap();
fn direct_nightly_launch_self_isolates_to_canonical_root_and_preserves_args() {
let spec = crate::profile_root::spec();
let expected_root = craft_nightly::canonical_profile_root(crate::profile_root::APP_ID).expect("canonical profile root");
let argv = args(&["model.glb", "--gpu", "nvidia"]);
let launch = craft_nightly::parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &StartupOptions::new()).unwrap();
assert_eq!(launch.profile, Profile::NightlyV1(expected_root));
assert!(launch.profile.is_nightly());
assert_eq!(launch.passthrough_args, argv);
assert!(!launch.is_version_query());
}
#[test]
fn explicit_launcher_flags_override_canonical_root_and_preserve_files() {
let spec = crate::profile_root::spec();
let argv = args(&[
craft_nightly::LAUNCH_PROFILE_FLAG,
craft_nightly::NIGHTLY_V1_CONTRACT,
craft_nightly::PROFILE_ROOT_FLAG,
absolute(),
"--",
"--profile-root",
"model with spaces.glb",
]);
let launch = craft_nightly::parse_startup(BuildFlavor::NightlyV1, &spec, argv, &StartupOptions::new()).unwrap();
assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute())));
assert_eq!(launch.args, args(&["--", "--profile-root", "model with spaces.glb"]));
assert_eq!(launch.passthrough_args, args(&["--profile-root", "model with spaces.glb"]));
}
#[test]
fn missing_duplicate_unknown_and_conflicting_profile_arguments_are_refused() {
fn invalid_profile_arguments_are_refused() {
let spec = crate::profile_root::spec();
for argv in [
args(&["--launch-profile", VERSION]),
args(&["--launch-profile", craft_nightly::NIGHTLY_V1_CONTRACT]),
args(&["--profile-root", absolute()]),
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--launch-profile", VERSION, "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", "", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--gpu", "nvidia", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute()]),
args(&["--launch-profile=nightly-v1", "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--profile-root=/nightly-data/profiles/texturecraft", "--"]),
args(&[
"--launch-profile",
craft_nightly::NIGHTLY_V1_CONTRACT,
"--launch-profile",
craft_nightly::NIGHTLY_V1_CONTRACT,
"--profile-root",
absolute(),
"--",
]),
args(&["--launch-profile", craft_nightly::NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--profile-root", absolute(), "--"]),
args(&["--launch-profile", craft_nightly::NIGHTLY_V1_CONTRACT, "--profile-root", "", "--"]),
args(&["--gpu", "nvidia", "--launch-profile", craft_nightly::NIGHTLY_V1_CONTRACT, "--profile-root", absolute()]),
] {
assert!(parse(argv.clone()).is_err(), "{argv:?}");
assert!(craft_nightly::parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &StartupOptions::new()).is_err(), "{argv:?}");
}
}
#[test]
fn the_launcher_version_check_is_a_version_query_only_in_its_exact_form() {
let pair = &["--launch-profile", VERSION, "--profile-root", absolute()];
let reversed = &["--profile-root", absolute(), "--launch-profile", VERSION];
fn version_queries_are_recognized_plain_and_via_launcher() {
let spec = crate::profile_root::spec();
for flag in ["--version", "-V"] {
for form in [pair, reversed] {
let mut argv = args(form);
argv.push(flag.into());
assert!(version_query(&argv), "{argv:?}");
let plain = craft_nightly::parse_startup(BuildFlavor::NightlyV1, &spec, args(&[flag]), &StartupOptions::new()).unwrap();
assert!(plain.is_version_query(), "plain {flag}");
for header in [
["--launch-profile", craft_nightly::NIGHTLY_V1_CONTRACT, "--profile-root", absolute()],
["--profile-root", absolute(), "--launch-profile", craft_nightly::NIGHTLY_V1_CONTRACT],
] {
let mut query = args(&header);
query.push(flag.into());
assert!(
craft_nightly::parse_startup(BuildFlavor::NightlyV1, &spec, query, &StartupOptions::new()).unwrap().is_version_query(),
"launcher {flag}"
);
let mut gpu = args(&header);
gpu.extend(args(&["--gpu", "nvidia", flag]));
let launch = craft_nightly::parse_startup(BuildFlavor::NightlyV1, &spec, gpu, &StartupOptions::new()).unwrap();
assert!(!launch.is_version_query());
assert_eq!(launch.passthrough_args, args(&["--gpu", "nvidia", flag]));
}
}
for argv in [
args(&["--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--", "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--gpu", "nvidia", "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--version"]),
args(&["--version", "--launch-profile", VERSION, "--profile-root", absolute()]),
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--version"]),
args(&["--launch-profile", VERSION, "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--help"]),
] {
assert!(!version_query(&argv), "{argv:?}");
}
// Outside the query the strict protocol still refuses the version flag.
assert!(parse(args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version"])).is_err());
}
#[test]
fn failed_root_validation_never_reaches_startup_or_falls_back_to_stable() {
let reached = Cell::new(false);
let result = prepare(parse(nightly()).unwrap(), |_| Err("read-only or unsafe profile".into())).map(|_| reached.set(true));
assert!(result.is_err());
assert!(!reached.get());
}
#[test]
fn successful_root_validation_keeps_the_persistent_root_not_the_binary_tag() {
let checked = PathBuf::from(absolute()).join("checked");
let launch = prepare(parse(nightly()).unwrap(), |_| Ok(checked.clone())).unwrap();
assert_eq!(launch.profile.root(), Some(checked.as_path()));
assert!(launch.profile.is_nightly());
let file_named_version = craft_nightly::parse_startup(BuildFlavor::NightlyV1, &spec, args(&["--", "--version"]), &StartupOptions::new()).unwrap();
assert!(!file_named_version.is_version_query());
}
}
+19 -21
View File
@@ -291,33 +291,31 @@ fn report_launch_profile_error(error: &str) {
}
}
/// Select the immutable launch profile before any startup service or side effect, and answer the
/// Launcher's version queries before root validation, logging, IPC or a window. `None` means the
/// launch is already answered and the process returns.
/// Select the immutable launch profile before any startup service or side effect, and answer
/// version queries before root validation, logging, IPC or a window. `None` means the launch is
/// already answered and the process returns.
fn prepare_launch() -> Option<Vec<OsString>> {
let argv: Vec<OsString> = std::env::args_os().skip(1).collect();
// Plain `--version`, or the Launcher's `--launch-profile nightly-v1 --profile-root <dir>
// --version`: both are answered here, with nothing but standard output written.
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && (build_flavor::version_query(&argv) || launch_profile::version_query(&argv)) {
// Plain `--version` / `-V` is answered immediately with nothing but standard output written,
// even in a minimal environment without home/data variables.
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && build_flavor::version_query(&argv) {
use std::io::Write as _;
let _ = writeln!(std::io::stdout(), "{}", build_flavor::version(build_flavor::COMPILED));
return None;
}
let early = launch_profile::prepare(build_flavor::COMPILED, argv).unwrap_or_else(|error| {
report_launch_profile_error(&error.to_string());
std::process::exit(2)
});
// Launcher's `--launch-profile nightly-v1 --profile-root <dir> --version`: `craft-nightly`
// skips root validation and profile installation for version queries.
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && early.is_version_query() {
use std::io::Write as _;
let _ = writeln!(std::io::stdout(), "{}", build_flavor::version(build_flavor::COMPILED));
return None;
}
let early = launch_profile::parse(argv)
.and_then(|launch| {
build_flavor::require_profile(build_flavor::COMPILED, &launch.profile)?;
initialize_nightly_process_identity().map_err(|error| error.to_string())?;
Ok(launch)
})
.and_then(|launch| {
launch_profile::prepare(launch, |root| launch_profile::validate_root(root, |key| std::env::var_os(key), std::env::current_exe().ok().as_deref()))
})
.unwrap_or_else(|error| {
report_launch_profile_error(&error);
std::process::exit(2)
});
let identity = if early.profile.is_nightly() { LaunchIdentity::NightlyV1 } else { LaunchIdentity::Stable };
if let Err(error) = launch_profile::install(early.profile).and_then(|()| os_window::select_identity(identity)) {
if let Err(error) = initialize_nightly_process_identity().map_err(|error| error.to_string()).and_then(|()| os_window::select_identity(identity)) {
report_launch_profile_error(&error);
std::process::exit(2);
}
@@ -326,7 +324,7 @@ fn prepare_launch() -> Option<Vec<OsString>> {
texturecraft_ui_egui::set_data_root(root.clone());
texturecraft_ui_egui::os_window::set_display_version(build_flavor::BUILT_VERSION.to_owned());
}
Some(early.args)
Some(early.passthrough_args)
}
/// The launch arguments as text. A Nightly protocol argument is a path the app opens, so a value
+164 -506
View File
@@ -1,567 +1,225 @@
//! App-owned nightly profile fences; no stable fallback, migration or process environment changes.
//! App-owned nightly profile specification backed by `craft-nightly`.
//!
//! A Nightly profile has to hold *all* of its user state: eframe's `app.ron`/`ui.json`, the error
//! log, session logs, autosave copies, smart materials, layouts, templates, brush and export
//! presets. Anything that resolves to a stable folder would read and prune Stable's files, so the
//! root is refused when it overlaps one of them, when an entry inside it is an alias that leaves it,
//! or when it is not writable.
//! A Nightly profile holds *all* of its user state: eframe's `app.ron`/`ui.json`, the error log,
//! session logs, autosave copies, smart materials, layouts, templates, brush and export presets.
//! `craft-nightly` enforces the security fence, symlink/hardlink checks, `0o700` hardening, and
//! writability probe using the TextureCraft-specific boundaries declared here.
use std::ffi::OsString;
use std::path::{Component, Path, PathBuf};
use std::path::PathBuf;
/// The folder names the launch checks use for this app in each platform's location.
use craft_nightly::AppProfileSpec;
/// Canonical lowercase app identifier used for the default nightly profile path.
pub const APP_ID: &str = "texturecraft";
/// Human-readable application name and stable folder name.
const BRAND: &str = "TextureCraft";
/// The bundle identifier of the stable package (macOS library folders, the Linux Flatpak).
const STABLE_ID: &str = "ai.storyteller.texturecraft";
/// The package id of the Nightly Flatpak bundle (`packaging/linux/flatpak-bundle.sh`). Inside that
/// sandbox `FLATPAK_ID` is always set, so this exact id is the one a Nightly native launch accepts.
const NIGHTLY_ID: &str = "ai.storyteller.texturecraft.nightly";
/// eframe lowercases its folder name on Linux (`file_storage.rs`), so Stable's real settings folder
/// is `$XDG_DATA_HOME/texturecraft`, not the capitalised `TextureCraft` the app is called.
const LINUX_STORAGE_BRAND: &str = "texturecraft";
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Platform {
Windows,
Linux,
Mac,
}
impl Platform {
fn current() -> Result<Self, String> {
match std::env::consts::OS {
"windows" => Ok(Self::Windows),
"linux" => Ok(Self::Linux),
"macos" => Ok(Self::Mac),
_ => Err("nightly-v1 is not defined for this operating system".into()),
}
}
fn ignores_case(self) -> bool {
self != Self::Linux
}
}
fn absolute(path: PathBuf, label: &str) -> Result<PathBuf, String> {
if !path.is_absolute() || path.components().any(|c| matches!(c, Component::ParentDir)) {
return Err(format!("{label} must be absolute and contain no parent traversal"));
}
Ok(path)
}
fn required_base(env: &impl Fn(&str) -> Option<OsString>, key: &str) -> Result<PathBuf, String> {
let value = env(key).filter(|v| !v.is_empty()).ok_or_else(|| format!("cannot establish the stable {key} boundary"))?;
absolute(PathBuf::from(value), key)
}
fn xdg_base(env: &impl Fn(&str) -> Option<OsString>, key: &str, fallback: &str) -> Result<PathBuf, String> {
match env(key).filter(|v| !v.is_empty()) {
Some(value) => absolute(PathBuf::from(value), key),
None => Ok(required_base(env, "HOME")?.join(fallback)),
}
}
/// Resolve existing ancestors before creating anything. A dangling link or an inaccessible ancestor
/// is not a missing directory that may be replaced or followed later.
fn canonical_future(path: &Path) -> Result<PathBuf, String> {
let mut parent = path;
let mut missing = Vec::new();
loop {
match std::fs::symlink_metadata(parent) {
Ok(_) => break,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
missing.push(parent.file_name().ok_or("the profile root has no existing ancestor")?.to_os_string());
parent = parent.parent().ok_or("the profile root has no existing ancestor")?;
}
Err(error) => return Err(format!("cannot inspect the profile boundary: {error}")),
}
}
let mut resolved = std::fs::canonicalize(parent).map_err(|e| format!("cannot resolve the profile boundary: {e}"))?;
for part in missing.into_iter().rev() {
resolved.push(part);
}
Ok(resolved)
}
/// Whether one path is the other or contains it (in either direction), compared component by
/// component and folded the way the platform's filesystem folds names. `TextureCraft2` is not
/// inside `TextureCraft`.
fn overlaps(a: &Path, b: &Path, platform: Platform) -> bool {
let parts = |p: &Path| {
p.components()
.map(|c| {
let value = c.as_os_str().to_string_lossy().into_owned();
if platform.ignores_case() { value.to_lowercase() } else { value }
})
.collect::<Vec<_>>()
};
let (a, b) = (parts(a), parts(b));
a.starts_with(&b) || b.starts_with(&a)
}
/// The running install: never let the profile live inside it (it would be replaced or removed by
/// the next update).
fn installation_boundary(platform: Platform, exe: &Path) -> Result<PathBuf, String> {
let parent = exe.parent().ok_or("cannot establish the installation boundary")?;
if platform == Platform::Mac {
// A profile in Resources is still inside the versioned bundle, not beside MacOS.
if let Some(bundle) = exe.ancestors().find(|p| p.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("app"))) {
return Ok(bundle.to_path_buf());
}
}
Ok(parent.to_path_buf())
}
/// The default data folder, `Documents/TextureCraft`, as the app's own resolver builds it
/// (`crate::data_folder("")`): `USERPROFILE` on Windows and `HOME` elsewhere, then `Documents`.
fn default_data_folder(platform: Platform, env: &impl Fn(&str) -> Option<OsString>) -> Result<PathBuf, String> {
let home = match platform {
Platform::Windows => required_base(env, "USERPROFILE")?,
_ => required_base(env, "HOME")?,
};
Ok(home.join("Documents").join(BRAND))
}
fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option<OsString>, exe: &Path) -> Result<Vec<PathBuf>, String> {
let mut roots = match platform {
Platform::Windows => {
// eframe's settings folder (`%APPDATA%\TextureCraft`), its local counterpart, and the MSI's
// per-machine and any per-user install folders. A custom install folder is covered by the
// executable's own folder below.
let mut roots = ["APPDATA", "LOCALAPPDATA"].into_iter().map(|key| required_base(env, key).map(|p| p.join(BRAND))).collect::<Result<Vec<_>, _>>()?;
roots.push(required_base(env, "LOCALAPPDATA")?.join("Programs").join("ArtCraft").join(BRAND));
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
if let Some(base) = env(key).filter(|v| !v.is_empty()) {
roots.push(absolute(PathBuf::from(base), key)?.join(BRAND));
}
}
roots
}
Platform::Linux => {
// The four XDG roots carry eframe's settings, caches and state under the app's name.
let mut roots =
[("XDG_CONFIG_HOME", ".config"), ("XDG_DATA_HOME", ".local/share"), ("XDG_CACHE_HOME", ".cache"), ("XDG_STATE_HOME", ".local/state")]
.into_iter()
.map(|(key, fallback)| xdg_base(env, key, fallback).map(|p| p.join(BRAND)))
.collect::<Result<Vec<_>, _>>()?;
// eframe's own folder for this app on Linux, which is what holds Stable's `app.ron`,
// `ui.json` and `errors.log`: it folds the name, so it is the lowercase one.
roots.push(xdg_base(env, "XDG_DATA_HOME", ".local/share")?.join(LINUX_STORAGE_BRAND));
roots.extend(["/usr/bin/texturecraft", "/usr/local/bin/texturecraft", "/opt/texturecraft"].map(PathBuf::from));
// The stable Flatpak keeps its own per-app data folder.
roots.push(required_base(env, "HOME")?.join(format!(".var/app/{STABLE_ID}")));
roots
}
Platform::Mac => {
let home = required_base(env, "HOME")?;
let library = home.join("Library");
vec![
library.join("Application Support").join(BRAND),
library.join("Caches").join(BRAND),
library.join("Caches").join(STABLE_ID),
library.join("Preferences").join(BRAND),
library.join("Preferences").join(format!("{STABLE_ID}.plist")),
library.join("Saved Application State").join(format!("{STABLE_ID}.savedState")),
home.join("Applications").join(format!("{BRAND}.app")),
PathBuf::from("/Applications").join(format!("{BRAND}.app")),
]
}
};
// The user's own documents folder is Stable's default data folder on every platform; a profile
// there would share autosaves, smart materials and presets with it.
roots.push(default_data_folder(platform, env)?);
roots.push(installation_boundary(platform, exe)?);
roots.into_iter().map(|p| canonical_future(&p)).collect()
}
/// An entry inside the profile must resolve inside it, so a link planted there cannot point
/// Nightly's writes at another app's files.
fn private_subdirectory(root: &Path, name: impl AsRef<Path>, label: &str) -> Result<PathBuf, String> {
let chosen = canonical_future(&absolute(root.to_path_buf(), "the nightly profile root")?)?;
let entry = chosen.join(name);
let metadata = std::fs::symlink_metadata(&entry).map_err(|e| format!("cannot inspect the nightly {label}: {e}"))?;
if !metadata.is_dir() {
return Err(format!("the nightly {label} must be a directory inside its selected profile"));
}
let child = canonical_future(&entry)?;
if child == chosen || !child.starts_with(&chosen) {
return Err(format!("the nightly {label} must stay inside its selected profile"));
}
Ok(child)
}
/// The bundle identifier of the stable package (macOS library folders, the Linux Flatpak).
const STABLE_ID: &str = "ai.storyteller.texturecraft";
/// The package id of the Nightly Flatpak bundle (`packaging/linux/flatpak-bundle.sh`).
const NIGHTLY_ID: &str = "ai.storyteller.texturecraft.nightly";
/// Known folder-only entries directly inside a Nightly profile.
const PROFILE_FOLDERS: [&str; 10] = ["autosave", "logs", "cache", "library", "layouts", "templates", "brushes", "export", "export-presets", "Samples"];
const PROFILE_FOLDERS: &[&str] = &["autosave", "logs", "cache", "library", "layouts", "templates", "brushes", "export", "export-presets", "Samples"];
/// Every existing entry directly in the profile (autosave, logs, library and so on) must resolve
/// inside it.
fn entries_stay_inside(root: &Path) -> Result<(), String> {
let entries = match std::fs::read_dir(root) {
Ok(entries) => entries,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(error) => return Err(format!("cannot inspect the nightly profile: {error}")),
};
for entry in entries {
let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
let path = entry.path();
let metadata = std::fs::symlink_metadata(&path).map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
// Settings and session state are ordinary files, not directories. Keep the existing
// directory-boundary check for folders (including the known folder-only entries).
let folder_only = PROFILE_FOLDERS.iter().any(|name| entry.file_name().eq_ignore_ascii_case(name));
if metadata.is_file() && !folder_only {
private_regular_file(&path, &metadata)?;
} else {
private_subdirectory(root, entry.file_name(), "profile entry")?;
}
}
Ok(())
/// Build TextureCraft's `craft_nightly::AppProfileSpec` from the current process environment.
pub fn spec() -> AppProfileSpec {
spec_with_env(|key| std::env::var_os(key))
}
/// Persisted files must have their own ordinary file identity, not an alias to other data.
fn private_regular_file(path: &Path, metadata: &std::fs::Metadata) -> Result<(), String> {
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt as _;
if metadata.nlink() != 1 {
return Err("the nightly profile file must not be shared".into());
}
/// Build TextureCraft's `craft_nightly::AppProfileSpec` using a custom environment lookup.
pub fn spec_with_env(env: impl Fn(&str) -> Option<OsString>) -> AppProfileSpec {
AppProfileSpec {
app_id: APP_ID,
display_name: BRAND,
stable_dir_names: &[BRAND, LINUX_STORAGE_BRAND],
stable_package_id: STABLE_ID,
nightly_package_id: NIGHTLY_ID,
profile_root_env: None,
forbidden_env_vars: &[],
portable_markers: &[],
folder_only_entries: PROFILE_FOLDERS,
extra_forbidden_roots: extra_forbidden_roots(&env),
}
#[cfg(windows)]
{
use winsafe::{HFILE, co};
let (file, _) = HFILE::CreateFile(
path.to_str().ok_or("the nightly profile file path is not textual")?,
co::GENERIC::default(),
Some(co::FILE_SHARE::READ | co::FILE_SHARE::WRITE | co::FILE_SHARE::DELETE),
None,
co::DISPOSITION::OPEN_EXISTING,
co::FILE_ATTRIBUTE::NORMAL,
Some(co::FILE_FLAG::OPEN_REPARSE_POINT),
None,
None,
)
.map_err(|e| e.to_string())?;
let info = file.GetFileInformationByHandle().map_err(|e| e.to_string())?;
if info.dwFileAttributes.has(co::FILE_ATTRIBUTE::REPARSE_POINT | co::FILE_ATTRIBUTE::DIRECTORY) {
return Err("the nightly profile file must not be an alias or directory".into());
}
if info.nNumberOfLinks != 1 {
return Err("the nightly profile file must not be shared".into());
}
}
let _ = (path, metadata);
Ok(())
}
/// The app's writable probe: create a file exclusively in the profile and remove it again.
pub fn ensure_writable(dir: &Path) -> std::io::Result<()> {
let probe = dir.join("exclusive-write-probe");
let file = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe)?;
drop(file);
std::fs::remove_file(probe)
fn non_empty_abs_env(env: &impl Fn(&str) -> Option<OsString>, key: &str) -> Option<PathBuf> {
let value = env(key).filter(|v| !v.is_empty())?;
let path = PathBuf::from(value);
path.is_absolute().then_some(path)
}
/// Refuse a stable folder, the running install or an alias, create a missing root with owner-only
/// access where the platform has it, and return the resolved root to use.
pub fn validate(
root: &Path,
env: impl Fn(&str) -> Option<OsString>,
exe: Option<&Path>,
writable: impl FnOnce(&Path) -> std::io::Result<()>,
) -> Result<PathBuf, String> {
validate_for(Platform::current()?, root, env, exe, writable)
}
/// Platform-specific stable data and install roots beyond the OS config/data/cache dirs that
/// `craft-nightly` already fences from `stable_dir_names` and `stable_package_id`.
fn extra_forbidden_roots(env: &impl Fn(&str) -> Option<OsString>) -> Vec<PathBuf> {
let mut roots = Vec::new();
fn validate_for(
platform: Platform,
root: &Path,
env: impl Fn(&str) -> Option<OsString>,
exe: Option<&Path>,
writable: impl FnOnce(&Path) -> std::io::Result<()>,
) -> Result<PathBuf, String> {
absolute(root.to_path_buf(), "the nightly profile root")?;
// A native package must not carry another app's Flatpak namespace, and the Nightly bundle must
// be able to start inside its own sandbox, where the runtime always sets `FLATPAK_ID`. Its
// `~/.var/app/<nightly id>` sandbox is separate from stable's, so only other ids are refused.
if platform != Platform::Windows
&& let Some(id) = env("FLATPAK_ID").filter(|v| !v.is_empty())
&& id != NIGHTLY_ID
// The user's own Documents folder is Stable's default data folder on every platform; a profile
// there would share autosaves, smart materials and presets with it.
#[cfg(target_os = "windows")]
if let Some(home) = non_empty_abs_env(env, "USERPROFILE") {
roots.push(home.join("Documents").join(BRAND));
}
#[cfg(not(target_os = "windows"))]
if let Some(home) = non_empty_abs_env(env, "HOME") {
roots.push(home.join("Documents").join(BRAND));
}
#[cfg(target_os = "windows")]
{
return Err("nightly-v1 only runs inside its own Flatpak; launch through the native Launcher or the Nightly bundle".into());
if let Some(local) = non_empty_abs_env(env, "LOCALAPPDATA") {
roots.push(local.join("Programs").join("ArtCraft").join(BRAND));
}
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
if let Some(base) = non_empty_abs_env(env, key) {
roots.push(base.join(BRAND));
}
}
}
let chosen = canonical_future(root)?;
let exe = absolute(exe.ok_or("cannot establish the installation boundary")?.to_path_buf(), "the executable")?;
let forbidden = forbidden_roots(platform, &env, &exe)?;
if forbidden.iter().any(|stable| overlaps(&chosen, stable, platform)) {
return Err("the nightly root must not overlap stable data or an installation".into());
}
// Existing aliases under the profile must not redirect any of its folders elsewhere.
entries_stay_inside(&chosen)?;
let mut create = std::fs::DirBuilder::new();
create.recursive(true);
#[cfg(unix)]
#[cfg(target_os = "linux")]
{
use std::os::unix::fs::DirBuilderExt as _;
create.mode(0o700);
roots.extend(["/usr/bin/texturecraft", "/usr/local/bin/texturecraft", "/opt/texturecraft"].map(PathBuf::from));
if let Some(home) = non_empty_abs_env(env, "HOME") {
roots.push(home.join(format!(".var/app/{STABLE_ID}")));
}
}
create.create(&chosen).map_err(|e| format!("cannot create the nightly profile: {e}"))?;
let confirmed = std::fs::canonicalize(&chosen).map_err(|e| format!("cannot resolve the created nightly profile: {e}"))?;
if confirmed != chosen || forbidden.iter().any(|stable| overlaps(&confirmed, stable, platform)) {
return Err("the nightly profile changed while it was being validated".into());
#[cfg(target_os = "macos")]
{
if let Some(home) = non_empty_abs_env(env, "HOME") {
let library = home.join("Library");
roots.push(library.join("Preferences").join(format!("{STABLE_ID}.plist")));
roots.push(library.join("Saved Application State").join(format!("{STABLE_ID}.savedState")));
roots.push(home.join("Applications").join(format!("{BRAND}.app")));
}
roots.push(PathBuf::from("/Applications").join(format!("{BRAND}.app")));
}
entries_stay_inside(&confirmed)?;
writable(&confirmed).map_err(|e| format!("the nightly profile is not writable: {e}"))?;
Ok(confirmed)
roots
}
#[cfg(test)]
mod tests {
use super::*;
use craft_nightly::{ProfileError, validate_and_prepare_root};
use std::collections::BTreeMap;
use std::path::Path;
use std::sync::atomic::{AtomicU64, Ordering};
struct Fixture {
root: PathBuf,
env: BTreeMap<String, OsString>,
exe: PathBuf,
struct TempDir {
path: PathBuf,
}
impl Fixture {
fn new() -> Self {
impl TempDir {
fn new(label: &str) -> Self {
static NEXT: AtomicU64 = AtomicU64::new(0);
let root = loop {
let candidate =
std::env::temp_dir().join(format!("texturecraft-profile-policy-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
let base = std::fs::canonicalize(std::env::temp_dir()).unwrap_or_else(|_| std::env::temp_dir());
let path = loop {
let candidate = base.join(format!("texturecraft-profile-spec-{label}-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
match std::fs::create_dir(&candidate) {
Ok(()) => break std::fs::canonicalize(candidate).unwrap(),
Ok(()) => break candidate,
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
Err(error) => panic!("cannot create owned fixture: {error}"),
}
};
let home = root.join("home");
let exe = root.join("install/texturecraft");
std::fs::create_dir_all(&home).unwrap();
std::fs::create_dir_all(exe.parent().unwrap()).unwrap();
std::fs::write(&exe, b"fixture executable, never run").unwrap();
let env = [("HOME", home.clone()), ("USERPROFILE", home), ("APPDATA", root.join("roaming")), ("LOCALAPPDATA", root.join("local"))]
.into_iter()
.map(|(key, value)| (key.into(), value.into_os_string()))
.collect();
Self { root, env, exe }
Self { path }
}
fn get(&self, key: &str) -> Option<OsString> {
self.env.get(key).cloned()
}
fn check(&self, platform: Platform, root: &Path) -> Result<PathBuf, String> {
validate_for(platform, root, |key| self.get(key), Some(&self.exe), ensure_writable)
}
fn home(&self) -> PathBuf {
PathBuf::from(self.get("HOME").unwrap())
}
fn profile(&self, name: &str) -> PathBuf {
self.root.join("profiles").join(name)
fn path(&self) -> &Path {
&self.path
}
}
impl Drop for Fixture {
impl Drop for TempDir {
fn drop(&mut self) {
// Only the directory this fixture created is owned for removal.
std::fs::remove_dir_all(&self.root).unwrap();
let _ = std::fs::remove_dir_all(&self.path);
}
}
#[test]
fn a_fresh_private_profile_is_created_and_returned_resolved() {
let fixture = Fixture::new();
let profile = fixture.profile("nightly");
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
assert_eq!(fixture.check(platform, &profile).unwrap(), profile);
assert!(profile.is_dir());
std::fs::remove_dir_all(&profile).ok();
fn spec_declares_texturecraft_ids_folders_and_extra_forbidden_roots() {
let tmp = TempDir::new("spec");
let home = tmp.path().join("home");
let mut env = BTreeMap::new();
env.insert("HOME", home.clone().into_os_string());
env.insert("USERPROFILE", home.clone().into_os_string());
env.insert("LOCALAPPDATA", tmp.path().join("local").into_os_string());
env.insert("ProgramFiles", tmp.path().join("Program Files").into_os_string());
let spec = spec_with_env(|key| env.get(key).cloned());
assert_eq!(spec.app_id, "texturecraft");
assert_eq!(spec.display_name, "TextureCraft");
assert_eq!(spec.stable_dir_names, &["TextureCraft", "texturecraft"]);
assert_eq!(spec.stable_package_id, "ai.storyteller.texturecraft");
assert_eq!(spec.nightly_package_id, "ai.storyteller.texturecraft.nightly");
assert_eq!(spec.profile_root_env, None);
assert!(spec.forbidden_env_vars.is_empty());
assert!(spec.portable_markers.is_empty());
assert_eq!(spec.folder_only_entries, PROFILE_FOLDERS);
assert!(spec.extra_forbidden_roots.contains(&home.join("Documents").join(BRAND)));
#[cfg(target_os = "linux")]
{
assert!(spec.extra_forbidden_roots.contains(&PathBuf::from("/usr/bin/texturecraft")));
assert!(spec.extra_forbidden_roots.contains(&PathBuf::from("/opt/texturecraft")));
assert!(spec.extra_forbidden_roots.contains(&home.join(format!(".var/app/{STABLE_ID}"))));
}
#[cfg(target_os = "macos")]
{
assert!(spec.extra_forbidden_roots.contains(&home.join(format!("Library/Preferences/{STABLE_ID}.plist"))));
assert!(spec.extra_forbidden_roots.contains(&home.join(format!("Library/Saved Application State/{STABLE_ID}.savedState"))));
assert!(spec.extra_forbidden_roots.contains(&home.join(format!("Applications/{BRAND}.app"))));
assert!(spec.extra_forbidden_roots.contains(&PathBuf::from(format!("/Applications/{BRAND}.app"))));
}
#[cfg(target_os = "windows")]
{
assert!(spec.extra_forbidden_roots.contains(&tmp.path().join("local/Programs/ArtCraft").join(BRAND)));
assert!(spec.extra_forbidden_roots.contains(&tmp.path().join("Program Files").join(BRAND)));
}
}
#[test]
fn every_stable_data_folder_of_each_platform_is_refused_before_any_probe() {
let fixture = Fixture::new();
let home = fixture.home();
let candidates: Vec<(Platform, PathBuf)> = vec![
(Platform::Windows, PathBuf::from(fixture.get("APPDATA").unwrap()).join(BRAND)),
(Platform::Windows, PathBuf::from(fixture.get("LOCALAPPDATA").unwrap()).join(BRAND)),
(Platform::Windows, PathBuf::from(fixture.get("LOCALAPPDATA").unwrap()).join("Programs/ArtCraft").join(BRAND)),
(Platform::Windows, home.join("Documents").join(BRAND)),
(Platform::Linux, home.join(".config").join(BRAND)),
(Platform::Linux, home.join(".local/share").join(BRAND)),
(Platform::Linux, home.join(".local/share").join(LINUX_STORAGE_BRAND)),
(Platform::Linux, home.join(".cache").join(BRAND)),
(Platform::Linux, home.join(".local/state").join(BRAND)),
(Platform::Linux, home.join("Documents").join(BRAND)),
(Platform::Linux, PathBuf::from("/usr/bin/texturecraft")),
(Platform::Linux, PathBuf::from("/opt/texturecraft")),
(Platform::Linux, home.join(format!(".var/app/{STABLE_ID}"))),
(Platform::Mac, home.join("Library/Application Support").join(BRAND)),
(Platform::Mac, home.join("Library/Caches").join(BRAND)),
(Platform::Mac, home.join("Library/Preferences").join(format!("{STABLE_ID}.plist"))),
(Platform::Mac, home.join("Library/Saved Application State").join(format!("{STABLE_ID}.savedState"))),
(Platform::Mac, home.join("Documents").join(BRAND)),
(Platform::Mac, PathBuf::from(format!("/Applications/{BRAND}.app"))),
];
for (platform, stable) in candidates {
for candidate in [stable.clone(), stable.join("nested nightly")] {
let probed = std::cell::Cell::new(false);
let result = validate_for(
platform,
&candidate,
|key| fixture.get(key),
Some(&fixture.exe),
|_| {
probed.set(true);
Ok(())
},
);
assert!(result.is_err(), "{platform:?} accepted {}", candidate.display());
assert!(!probed.get(), "a refused root must not be probed: {}", candidate.display());
}
fn nightly_profile_reopens_and_enforces_folder_only_entries() {
let tmp = TempDir::new("reopen");
let private = tmp.path().join("nightly-profile");
let spec = spec_with_env(|_| None);
let canonical = validate_and_prepare_root(&private, &spec).expect("fresh private profile");
assert_eq!(canonical, private);
for name in ["app.ron", "ui.json", "errors.log", "nightly-session.lock", "nightly-session.json"] {
std::fs::write(private.join(name), b"saved profile data").unwrap();
}
for name in PROFILE_FOLDERS {
std::fs::create_dir(private.join(name)).unwrap();
}
assert_eq!(validate_and_prepare_root(&private, &spec).expect("reopen populated profile"), private);
for name in ["app.ron", "ui.json", "errors.log", "nightly-session.lock", "nightly-session.json"] {
assert_eq!(std::fs::read(private.join(name)).unwrap(), b"saved profile data", "{name} remains intact after reopen");
}
for name in PROFILE_FOLDERS {
let path = private.join(name);
std::fs::remove_dir(&path).unwrap();
std::fs::write(&path, b"not a directory").unwrap();
assert!(matches!(validate_and_prepare_root(&private, &spec), Err(ProfileError::ExpectedDirectoryEntry(_))), "{name} must stay a directory");
std::fs::remove_file(&path).unwrap();
std::fs::create_dir(&path).unwrap();
}
}
#[test]
fn the_running_install_is_fenced_on_every_platform() {
let fixture = Fixture::new();
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
let inside = fixture.exe.parent().unwrap().join("profile");
assert!(fixture.check(platform, &inside).is_err(), "{platform:?} let the profile inside the install");
}
}
fn documents_data_folder_is_refused() {
let tmp = TempDir::new("documents");
let home = tmp.path().join("home");
let documents_stable = home.join("Documents").join(BRAND);
let spec = spec_with_env(|key| matches!(key, "HOME" | "USERPROFILE").then(|| home.clone().into_os_string()));
#[test]
fn lookalike_names_are_not_overlaps_but_case_folding_is() {
let fixture = Fixture::new();
let documents = fixture.home().join("Documents");
assert!(fixture.check(Platform::Linux, &documents.join("TextureCraft2")).is_ok(), "a neighbor with a suffix is a different folder");
assert!(fixture.check(Platform::Linux, &documents.join("texturecraft")).is_ok(), "Linux folds names exactly");
for platform in [Platform::Windows, Platform::Mac] {
assert!(fixture.check(platform, &documents.join("texturecraft")).is_err(), "{platform:?} must fold case");
}
}
#[test]
fn relative_parent_traversal_and_empty_roots_are_refused() {
let fixture = Fixture::new();
for root in [PathBuf::from("relative/profile"), PathBuf::from("/nightly/../stable"), PathBuf::from("")] {
assert!(fixture.check(Platform::Linux, &root).is_err(), "{}", root.display());
}
}
#[test]
fn only_the_nightly_flatpak_may_start_with_its_own_id() {
let fixture = Fixture::new();
let profile = fixture.profile("flatpak");
assert!(fixture.check(Platform::Linux, &profile).is_ok());
std::fs::remove_dir_all(&profile).ok();
let check_with = |id: &str, candidate: &Path| {
let id = OsString::from(id);
validate_for(
Platform::Linux,
candidate,
|key| if key == "FLATPAK_ID" { Some(id.clone()) } else { fixture.get(key) },
Some(&fixture.exe),
ensure_writable,
)
};
// Stable's id, its window id and an unrelated app's id are all refusals.
for id in [STABLE_ID, "ai.storyteller.texturecraft.nightly-v1", "org.example.other"] {
assert!(check_with(id, &profile).is_err(), "{id} was accepted");
}
// The Nightly bundle's own id is the sandbox the Nightly package runs in: accepted, with the
// profile its wrapper names inside it (`${XDG_DATA_HOME}/TextureCraft-Nightly`).
let sandbox = fixture.home().join(format!(".var/app/{NIGHTLY_ID}"));
let sandboxed = sandbox.join(".local/share/TextureCraft-Nightly");
assert_eq!(check_with(NIGHTLY_ID, &sandboxed).expect("the Nightly Flatpak may start"), sandboxed);
std::fs::remove_dir_all(&sandbox).ok();
}
#[test]
#[cfg(unix)]
fn an_entry_that_leaves_the_profile_is_refused() {
let fixture = Fixture::new();
let profile = fixture.profile("aliased");
let outside = fixture.root.join("somewhere else");
std::fs::create_dir_all(&profile).unwrap();
std::fs::create_dir_all(&outside).unwrap();
std::os::unix::fs::symlink(&outside, profile.join("autosave")).unwrap();
assert!(fixture.check(Platform::Linux, &profile).is_err(), "a link out of the profile must be refused");
// A dangling link is not a missing folder that may be created.
std::fs::remove_file(profile.join("autosave")).unwrap();
std::os::unix::fs::symlink(profile.join("missing"), profile.join("logs")).unwrap();
assert!(fixture.check(Platform::Linux, &profile).is_err());
std::fs::remove_file(profile.join("logs")).unwrap();
// A plain folder inside it is fine.
std::fs::create_dir(profile.join("autosave")).unwrap();
assert!(fixture.check(Platform::Linux, &profile).is_ok());
}
#[test]
fn a_failed_write_probe_never_falls_back_to_stable() {
let fixture = Fixture::new();
let profile = fixture.profile("read only");
let reached = std::cell::Cell::new(false);
let result = validate_for(
Platform::Linux,
&profile,
|key| fixture.get(key),
Some(&fixture.exe),
|_| {
reached.set(true);
Err(std::io::Error::other("read-only filesystem"))
},
);
assert!(result.is_err());
assert!(reached.get());
assert!(result.unwrap_err().contains("not writable"));
// The app must not then use the stable folder: it simply refuses to start.
assert!(fixture.check(Platform::Linux, &fixture.home().join("Documents").join(BRAND)).is_err());
}
#[test]
fn nightly_profile_reopens_after_saving_settings_and_session_state() {
let fixture = Fixture::new();
for platform in [Platform::Mac, Platform::Linux, Platform::Windows] {
let private = fixture.root.join(format!("nightly-reopen-{platform:?}"));
assert_eq!(fixture.check(platform, &private).unwrap(), private);
for name in ["app.ron", "ui.json", "errors.log", "nightly-session.lock", "nightly-session.json"] {
std::fs::write(private.join(name), b"saved profile data").unwrap();
}
for name in PROFILE_FOLDERS {
std::fs::create_dir(private.join(name)).unwrap();
}
assert_eq!(fixture.check(platform, &private).unwrap(), private);
assert_eq!(std::fs::read(private.join("app.ron")).unwrap(), b"saved profile data");
for name in PROFILE_FOLDERS {
let path = private.join(name);
std::fs::remove_dir(&path).unwrap();
std::fs::write(&path, b"not a directory").unwrap();
assert!(fixture.check(platform, &private).is_err(), "{name} must stay a directory");
std::fs::remove_file(&path).unwrap();
std::fs::create_dir(&path).unwrap();
}
}
}
#[test]
#[cfg(unix)]
fn a_profile_whose_existing_ancestor_is_a_link_resolves_before_the_fence() {
let fixture = Fixture::new();
let real = fixture.root.join("real profiles");
std::fs::create_dir_all(&real).unwrap();
let link = fixture.root.join("linked");
std::os::unix::fs::symlink(&real, &link).unwrap();
// A link to a private folder is fine, and the resolved root is what the app uses.
let resolved = fixture.check(Platform::Linux, &link.join("nightly")).unwrap();
assert_eq!(resolved, real.join("nightly"));
assert!(matches!(validate_and_prepare_root(&documents_stable, &spec), Err(ProfileError::ForbiddenRootOverlap { .. })));
assert!(matches!(validate_and_prepare_root(&documents_stable.join("nested"), &spec), Err(ProfileError::ForbiddenRootOverlap { .. })));
}
}
-17
View File
@@ -1,17 +0,0 @@
//! Test executables of this crate on Windows (MSVC) reserve 8 MiB for each thread that does not
//! ask for a stack size of its own, as texturecraft-render's do: the tests render through
//! texturecraft-render on Mesa's lavapipe on the Windows CI gate, whose shader threads get the
//! executable's default of 1 MiB there and overflow it on the larger programs (Linux gives them
//! 8 MiB). This library crate links no other executable.
/// Bytes each thread reserves for its stack when it asks for none.
const THREAD_STACK_RESERVE: u32 = 8 * 1024 * 1024;
fn main() {
println!("cargo:rerun-if-changed=build.rs");
let target_os = std::env::var("CARGO_CFG_TARGET_OS").unwrap_or_default();
let target_env = std::env::var("CARGO_CFG_TARGET_ENV").unwrap_or_default();
if target_os == "windows" && target_env == "msvc" {
println!("cargo:rustc-link-arg=/STACK:{THREAD_STACK_RESERVE}");
}
}
+1 -1
View File
@@ -401,7 +401,7 @@ impl Headless {
let gpu = match self.gpu.get_or_insert_with(Gpu::new) {
Ok(g) => g,
Err(e) => return Err(AutomationError::Other(format!("cannot render: {e}"))),
Err(e) => return Err(AutomationError::Other(format!("cannot render: {e}; path tracing (`samples`) needs no GPU"))),
};
// Last-resort guard: wgpu panics on device errors; drop the device and report instead
+27 -16
View File
@@ -6,6 +6,7 @@ use std::sync::{Arc, Weak};
use rayon::prelude::*;
use texturecraft_engine::compose::{DisplayKind, ImageRes, all_tiles, tile_bytes};
use texturecraft_engine::core::AoMixing;
use texturecraft_engine::{Session, ViewMode};
use texturecraft_render::displace::trace_geometry;
use texturecraft_render::gpu_trace::GpuTracer;
@@ -67,6 +68,7 @@ impl Gpu {
let empty = Default::default();
let baked = session.doc.baked.get(&set_index).unwrap_or(&empty);
let composite = &cache.composite;
let ao_mixing = session.doc.project.texture_sets.get(set_index).map_or(AoMixing::Multiply, |set| set.ao_mixing);
// Limit live converted pixels while retaining parallel conversion within each batch
const UPLOAD_TILES_PER_BATCH: usize = 64;
@@ -74,7 +76,7 @@ impl Gpu {
let bytes: Vec<_> = batch
.par_iter()
.flat_map_iter(|&(tile_x, tile_y)| DisplayKind::ALL.into_iter().map(move |kind| (kind, tile_x, tile_y)))
.map(|(kind, tile_x, tile_y)| (kind, tile_x, tile_y, tile_bytes(composite, baked, kind, tile_x, tile_y)))
.map(|(kind, tile_x, tile_y)| (kind, tile_x, tile_y, tile_bytes(composite, baked, ao_mixing, kind, tile_x, tile_y)))
.collect();
for (kind, tile_x, tile_y, pixels) in bytes {
headless.renderer.upload_tile(&headless.device, &headless.queue, set_index, kind, tile_x, tile_y, &pixels);
@@ -166,7 +168,14 @@ fn trace_inputs(s: &mut Session) -> (TraceScene, TraceDisplay) {
.texture_sets
.iter()
.zip(&s.caches)
.map(|(ts, c)| TraceSet { material: ts.material, composite: c.composite.clone(), height_strength: ts.atlas_height_strength() })
.map(|(ts, c)| TraceSet {
material: ts.material,
composite: c.composite.clone(),
height_strength: ts.atlas_height_strength(),
height_y_factor: ts.atlas_height_y_factor(),
height_in_normal: ts.height_in_normal(),
height_to_normal: ts.height_to_normal,
})
.collect();
let d = &s.doc.project.display;
let env_image = d.environment_resource().and_then(|n| s.images.get(n));
@@ -201,10 +210,15 @@ pub fn shade(s: &Session) -> Shade {
ViewMode::UvChecker => (3, 0),
ViewMode::NormalHeightMesh => (4, 0),
};
let active_set = s.doc.project.texture_sets.get(s.ts());
Shade {
height_strength: s.doc.project.texture_sets.get(s.ts()).map(|t| t.atlas_height_strength()).unwrap_or(1.0),
height_strength: active_set.map_or(1.0, |t| t.atlas_height_strength()),
height_y_factor: active_set.map_or(1.0, |t| t.atlas_height_y_factor()),
height_in_normal: active_set.is_none_or(|t| t.height_in_normal()),
height_to_normal: active_set.map_or_else(Default::default, |t| t.height_to_normal),
view_mode,
channel,
// Only the 2D view uses this default
wireframe: true,
..Shade::from_project(&s.doc.project)
@@ -216,13 +230,7 @@ mod tests {
use super::*;
use serde_json::json;
use texturecraft_engine::execute;
/// One GPU test at a time: the NVIDIA driver (620.70) can deadlock when one test's device is
/// destroyed while another test records commands on its own device.
fn gpu_lock() -> std::sync::MutexGuard<'static, ()> {
static GPU: std::sync::Mutex<()> = std::sync::Mutex::new(());
GPU.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
}
use texturecraft_render::headless::TestGpuTurn;
/// A 64×32 Radiance `.hdr` (flat RGBE scanlines): a hot orange sky over a dim blue ground.
fn sky_hdr() -> Vec<u8> {
@@ -245,11 +253,12 @@ mod tests {
let mut s = Session::new_project("t", mesh, "builtin:material_ball", None, 256).unwrap();
let name = s.import_resource_bytes("sky.hdr", sky_hdr()).unwrap();
assert!(s.images[&name].rgba[0][0] > 10.0, "the decoder keeps HDR values");
let _gpu = gpu_lock();
let _turn = TestGpuTurn::take();
let Ok(mut gpu) = Gpu::new() else {
eprintln!("skipping: no GPU adapter");
return;
};
let cam = s.camera;
let (_, _, base) = gpu.render(&mut s, ViewKind::Scene, [160, 120], cam).unwrap();
execute(&mut s, "display.set", &json!({"environment": format!("resource:{name}"), "specGloss": true, "parallax": true})).unwrap();
@@ -264,7 +273,7 @@ mod tests {
let mut session = Session::new_project("Test", texturecraft_engine::geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
session.doc.project.display.taa = false;
let name = session.import_resource_bytes("sky.hdr", sky_hdr()).unwrap();
let _gpu = gpu_lock();
let _turn = TestGpuTurn::take();
let Ok(mut gpu) = Gpu::new() else {
eprintln!("skipping: no GPU adapter");
return;
@@ -296,7 +305,7 @@ mod tests {
execute(&mut session, "viewport.view", &json!({"mode": "image", "image": "red"})).unwrap();
let camera = session.camera;
let uv = |ts| ViewKind::Uv { ts, zoom: 1.0, pan: [0.0, 0.0], rotation: 0.0 };
let _gpu = gpu_lock();
let _turn = TestGpuTurn::take();
let Ok(mut gpu) = Gpu::new() else {
eprintln!("skipping: no GPU adapter");
return;
@@ -320,11 +329,12 @@ mod tests {
let mesh = texturecraft_engine::geom::primitives::material_ball();
let mut s = Session::new_project("t", mesh, "builtin:material_ball", None, 256).unwrap();
execute(&mut s, "layer.add.fill", &json!({"color": [0.75, 0.42, 0.23], "roughness": 0.3, "metallic": 0.4})).unwrap();
let _gpu = gpu_lock();
let _turn = TestGpuTurn::take();
let Ok(mut gpu) = Gpu::new() else {
eprintln!("skipping: no GPU adapter");
return;
};
let (cam, settings, size) = (s.camera, TraceSettings { bounces: 4 }, [64, 48]);
let g = match gpu.path_trace(&mut s, size, cam, 384, &settings) {
Ok((_, _, px)) => px,
@@ -334,7 +344,8 @@ mod tests {
}
};
let (_, _, c) = path_trace(&mut s, size, cam, 384, &settings);
// Mean luminance per 8×8 block (8-bit levels) agrees.
// Block averages absorb the expected variation between individual traced samples
let lum = |img: &[u8], x: usize, y: usize| {
let p = &img[(y * 64 + x) * 4..(y * 64 + x) * 4 + 3];
0.2126 * p[0] as f32 + 0.7152 * p[1] as f32 + 0.0722 * p[2] as f32
@@ -354,7 +365,7 @@ mod tests {
// Atlas UV 0.75 is the middle of tile 1002
execute(&mut s, "tool.strokeUv", &json!({"points": [[0.75, 0.5]]})).unwrap();
let _gpu = gpu_lock();
let _turn = TestGpuTurn::take();
let Ok(mut gpu) = Gpu::new() else {
eprintln!("skipping: no GPU adapter");
return;
+3 -2
View File
@@ -124,8 +124,9 @@ impl Headless {
}
}
/// Answer one request line. A panic inside a command becomes an error reply (edits run on a
/// snapshot, so the session stays consistent).
/// Answer one request line. A panic inside a command becomes an error reply. `Session::edit`
/// rolls the document back on unwind, but work outside it (scripted strokes) and other session
/// state, such as the selection or tool, is not rolled back.
pub fn respond(h: &Mutex<Headless>, line: &str) -> Value {
let req: Value = match serde_json::from_str(line) {
Ok(v) => v,
+3 -2
View File
@@ -338,8 +338,9 @@ impl TexturecraftMcp {
match &*self.backend {
Backend::Headless(h) => {
let (h, m) = (h.clone(), method.to_string());
// A panicking command poisons the lock, but edits run on a document snapshot
// (`Session::edit`), so the session stays consistent: keep serving.
// A panicking command poisons the lock: keep serving. `Session::edit` rolls the
// document back on unwind, but work outside it (scripted strokes) and other
// session state, such as the selection or tool, is not rolled back.
tokio::task::spawn_blocking(move || h.lock().unwrap_or_else(PoisonError::into_inner).handle(&m, &p))
.await
.unwrap_or_else(|_| Err(AutomationError::Other(format!("internal error in `{method}`"))))
+2 -1
View File
@@ -57,9 +57,10 @@ fn display_all(session: &mut Session) -> usize {
let tiles = session.take_uploads(texture_set);
let baked = session.baked(texture_set).cloned().unwrap_or_default();
let composite = &session.caches[texture_set].composite;
let ao_mixing = session.doc.project.texture_sets[texture_set].ao_mixing;
bytes += tiles
.par_iter()
.flat_map_iter(|&(tile_x, tile_y)| DisplayKind::ALL.map(|kind| tile_bytes(composite, &baked, kind, tile_x, tile_y).len()))
.flat_map_iter(|&(tile_x, tile_y)| DisplayKind::ALL.map(|kind| tile_bytes(composite, &baked, ao_mixing, kind, tile_x, tile_y).len()))
.sum::<usize>();
}
+26 -4
View File
@@ -123,6 +123,8 @@ impl<'a> Source<'a> {
}
}
/// The material's base colour at `uv` (bilinear, wrapping), sRGB RGBA times its factor; white
/// where there is no texture or the UV is not finite.
fn base_color(material: &BaseColor, uv: Vec2) -> Vec4 {
let sampled_color = if material.texels.is_empty() || !uv.is_finite() {
Vec4::ONE
@@ -134,11 +136,31 @@ fn base_color(material: &BaseColor, uv: Vec2) -> Vec4 {
Vec4::new(srgb_to_linear(color(0)), srgb_to_linear(color(1)), srgb_to_linear(color(2)), color(3))
};
let (fx, fy) = (uv.x * width as f32 - 0.5, uv.y * height as f32 - 0.5);
let (x0, y0) = (fx.floor(), fy.floor());
let (tx, ty) = (fx - x0, fy - y0);
let (x, y) = (x0 as i64, y0 as i64);
texel(x, y).lerp(texel(x + 1, y), tx).lerp(texel(x, y + 1).lerp(texel(x + 1, y + 1), tx), ty)
if fx.is_finite() && fy.is_finite() {
let (x0, y0) = (fx.floor(), fy.floor());
let (tx, ty) = (fx - x0, fy - y0);
let (x, y) = (x0 as i64, y0 as i64);
let (x1, y1) = (x.saturating_add(1), y.saturating_add(1));
texel(x, y).lerp(texel(x1, y), tx).lerp(texel(x, y1).lerp(texel(x1, y1), tx), ty)
} else {
Vec4::ONE
}
};
let color = sampled_color * material.factor;
Vec4::new(linear_to_srgb(color.x), linear_to_srgb(color.y), linear_to_srgb(color.z), color.w)
}
#[cfg(test)]
mod tests {
use super::*;
/// Sampling at huge but finite UVs returns a finite colour instead of overflowing.
#[test]
fn base_color_sampling_survives_huge_finite_uvs() {
let material = BaseColor { factor: Vec4::ONE, width: 2, height: 2, texels: vec![[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255], [255; 4]] };
for uv in [Vec2::new(1.0e30, 0.5), Vec2::new(0.5, -1.0e30), Vec2::splat(f32::MAX), Vec2::splat(1.0e6)] {
let c = base_color(&material, uv);
assert!(c.is_finite(), "{uv}: {c}");
}
}
}
+2 -1
View File
@@ -240,10 +240,11 @@ impl StackKey {
continue;
}
// Unchanged resampled instances do not constrain the grid of another target.
// Unchanged resampled instances do not constrain the grid of another target
if (left_image.width(), left_image.height()) != size {
return None;
}
let target = if left_channel.is_some() { PaintTarget::Layer(*left_id) } else { PaintTarget::Mask(*left_id) };
for tile_y in 0..left_image.tiles_y() {
for tile_x in 0..left_image.tiles_x() {
+76
View File
@@ -0,0 +1,76 @@
//! What a channel's storage format keeps of a composited value
use std::sync::OnceLock;
use texturecraft_core::{ChannelFormat, lum};
use texturecraft_texel::{linear_to_srgb, srgb_to_linear};
/// What `value` keeps in `format`: 8-bit = 256 steps (sRGB8 gamma-spaced), L = grey, others = the tiles' 16 bits; `signed` = stored offset into 0..1
pub(crate) fn stored(format: ChannelFormat, signed: bool, mut value: [f32; 3], components: usize) -> [f32; 3] {
if format.is_grey() && components == 3 {
value = [lum(value); 3];
}
value.map(|component| stored_value(format, signed, component))
}
fn stored_value(format: ChannelFormat, signed: bool, component: f32) -> f32 {
let value = if signed { component * 0.5 + 0.5 } else { component };
let unit = |unit_value: f32| if signed { unit_value * 2.0 - 1.0 } else { unit_value };
let step = |unit_value: f32| (unit_value.clamp(0.0, 1.0) * 255.0).round();
match format {
ChannelFormat::Rgb8 | ChannelFormat::L8 => unit(step(value) / 255.0),
ChannelFormat::Srgb8 => unit(srgb8_linear().get(step(linear_to_srgb(value.clamp(0.0, 1.0))) as usize).copied().unwrap_or(0.0)),
ChannelFormat::L16 | ChannelFormat::Rgb16 | ChannelFormat::L16F | ChannelFormat::Rgb16F | ChannelFormat::L32F | ChannelFormat::Rgb32F => component,
}
}
/// The linear value of each 8-bit sRGB step, so storing a colour decodes no sRGB per texel
fn srgb8_linear() -> &'static [f32; 256] {
static LINEAR: OnceLock<[f32; 256]> = OnceLock::new();
LINEAR.get_or_init(|| std::array::from_fn(|step| srgb_to_linear(step as f32 / 255.0)))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn eight_bit_formats_keep_256_steps_and_sixteen_bit_ones_everything() {
let x = 0.3_f32 + 1.0 / 1024.0;
let eight = stored(ChannelFormat::L8, false, [x; 3], 1)[0];
assert!((eight * 255.0 - (eight * 255.0).round()).abs() < 1e-4, "on a 1/255 step");
assert!((eight - x).abs() > 1e-4 && (eight - x).abs() <= 0.5 / 255.0 + 1e-6);
assert_eq!(stored(ChannelFormat::L16, false, [x; 3], 1)[0], x);
assert_eq!(stored(ChannelFormat::Rgb32F, true, [-x; 3], 1)[0], -x);
}
#[test]
fn srgb8_keeps_more_of_the_darks_than_rgb8() {
let dark = 0.002_f32;
let srgb = stored(ChannelFormat::Srgb8, false, [dark; 3], 3)[0];
let linear = stored(ChannelFormat::Rgb8, false, [dark; 3], 3)[0];
assert!((srgb - dark).abs() < (linear - dark).abs());
}
#[test]
fn srgb8_keeps_the_same_steps_as_decoding_each_one() {
for value in (0..=1000).map(|step| step as f32 / 1000.0) {
let decoded = srgb_to_linear((linear_to_srgb(value) * 255.0).round() / 255.0);
assert_eq!(stored(ChannelFormat::Srgb8, false, [value; 3], 3)[0], decoded, "at {value}");
}
}
#[test]
fn grey_formats_turn_colours_grey_and_signed_values_keep_their_sign() {
let grey = stored(ChannelFormat::L16, false, [1.0, 0.0, 0.0], 3);
assert!(grey[0] == grey[1] && grey[1] == grey[2] && grey[0] > 0.0 && grey[0] < 1.0);
assert_eq!(stored(ChannelFormat::Rgb16, false, [1.0, 0.0, 0.0], 3), [1.0, 0.0, 0.0]);
let low = stored(ChannelFormat::L8, true, [-0.5; 3], 1)[0];
assert!(low < -0.49 && low > -0.51);
}
}
+41 -28
View File
@@ -25,7 +25,7 @@
//! the extra lobes off, so the renderer can keep Lobes and Sheen as 1×1 placeholders until a
//! tile with a non-default value arrives.
use texturecraft_core::{BakedMap, Channel};
use texturecraft_core::{AoMixing, BakedMap, Channel};
use texturecraft_texel::{TILE, TILE_AREA, srgb_lut};
use crate::eval::Composite;
@@ -93,7 +93,7 @@ impl DisplayKind {
/// The texel of a set that has none of this texture's channels (the GPU clear value).
pub fn default_texel(self) -> Vec<u8> {
let mut px = tile_bytes(&Composite::new(&[], TILE), &BakedMaps::default(), self, 0, 0);
let mut px = tile_bytes(&Composite::new(&[], TILE), &BakedMaps::default(), AoMixing::Multiply, self, 0, 0);
px.truncate(self.bytes_per_texel());
px
}
@@ -110,26 +110,28 @@ fn u8_of(v: u16) -> u8 {
(v >> 8) as u8
}
/// Tile bytes (`TILE × TILE`, row-major) for `kind`, using channel defaults for absent source tiles.
pub fn tile_bytes(composite: &Composite, baked: &BakedMaps, kind: DisplayKind, tx: u32, ty: u32) -> Vec<u8> {
encode_tile(composite, baked, kind, tx, ty, 0)
/// Tile bytes (`TILE × TILE`, row-major) for `kind`, mixing baked occlusion by `ao_mixing` and using channel defaults for absent source tiles.
pub fn tile_bytes(composite: &Composite, baked: &BakedMaps, ao_mixing: AoMixing, kind: DisplayKind, tx: u32, ty: u32) -> Vec<u8> {
encode_tile(composite, baked, ao_mixing, kind, tx, ty, 0)
}
/// Pack only the samples the viewport uses at a reduced display resolution.
pub fn display_tile_bytes(composite: &Composite, baked: &BakedMaps, kind: DisplayKind, tx: u32, ty: u32, shift: u32) -> Vec<u8> {
pub fn display_tile_bytes(composite: &Composite, baked: &BakedMaps, ao_mixing: AoMixing, kind: DisplayKind, tx: u32, ty: u32, shift: u32) -> Vec<u8> {
if shift == 0 {
return tile_bytes(composite, baked, kind, tx, ty);
return tile_bytes(composite, baked, ao_mixing, kind, tx, ty);
}
encode_tile(composite, baked, kind, tx, ty, shift.min(TILE.ilog2()))
encode_tile(composite, baked, ao_mixing, kind, tx, ty, shift.min(TILE.ilog2()))
}
// Specialize the full-resolution entry point so its hot loops retain contiguous indexing.
// Specialize the full-resolution entry point so its hot loops retain contiguous indexing
#[inline(always)]
fn encode_tile(composite: &Composite, baked: &BakedMaps, kind: DisplayKind, tx: u32, ty: u32, shift: u32) -> Vec<u8> {
fn encode_tile(composite: &Composite, baked: &BakedMaps, ao_mixing: AoMixing, kind: DisplayKind, tx: u32, ty: u32, shift: u32) -> Vec<u8> {
let bytes_per_texel = kind.bytes_per_texel();
let area = TILE_AREA >> (2 * shift);
let mut out = vec![0u8; area * bytes_per_texel];
// Downscaling uses the top-left sample at each stride, matching the viewport upload.
// Downscaling uses the top-left sample at each stride, matching the viewport upload
let source = |offset: usize| {
let side = TILE as usize >> shift;
let row = offset >> (TILE.ilog2() - shift);
@@ -208,9 +210,12 @@ fn encode_tile(composite: &Composite, baked: &BakedMaps, kind: DisplayKind, tx:
for offset in 0..area {
let i = source(offset);
let (x, y) = (tx * TILE + (i as u32 % TILE), ty * TILE + (i as u32 / TILE));
let baked_ao = baked
.sample_working(BakedMap::AmbientOcclusion, x, y, (resolution, composite.height), &composite.block_scales)
.map_or(1.0, |value| value[0]);
let baked_ao = match ao_mixing {
AoMixing::Multiply => baked
.sample_working(BakedMap::AmbientOcclusion, x, y, (resolution, composite.height), &composite.block_scales)
.map_or(1.0, |value| value[0]),
AoMixing::None => 1.0,
};
let ch_ao = ao.and_then(|a| a.get(i)).map(|v| *v as f32 / 65535.0).unwrap_or(1.0);
let pixel = &mut out[offset * 4..offset * 4 + 4];
@@ -290,7 +295,7 @@ mod tests {
}
for kind in DisplayKind::ALL.into_iter().filter(|k| !kinds_for(channels).any(|n| n == *k)) {
let want = kind.default_texel().repeat(TILE_AREA);
assert!(tile_bytes(&comp, &BakedMaps::default(), kind, 0, 0) == want, "{kind:?} for {channels:?}");
assert!(tile_bytes(&comp, &BakedMaps::default(), AoMixing::Multiply, kind, 0, 0) == want, "{kind:?} for {channels:?}");
}
}
}
@@ -301,7 +306,7 @@ mod tests {
comp.channels.get_mut(&Channel::BaseColor).unwrap().set(0, 0, &[to_u16(1.0), to_u16(0.5), 0]);
comp.channels.get_mut(&Channel::Opacity).unwrap().set(0, 0, &[to_u16(0.5)]);
let b = tile_bytes(&comp, &BakedMaps::default(), DisplayKind::BaseColor, 0, 0);
let b = tile_bytes(&comp, &BakedMaps::default(), AoMixing::Multiply, DisplayKind::BaseColor, 0, 0);
assert_eq!(b[0], 255);
assert!((b[1] as i32 - 188).abs() <= 1, "{}", b[1]);
@@ -315,7 +320,7 @@ mod tests {
set.uv_tiles = vec![1001, 1002];
set.tile_resolutions.insert(1002, 64);
let comp = Composite { block_scales: set.block_scales(), ..Composite::new(&[], 512) };
let alpha = |tx: u32| tile_bytes(&comp, &BakedMaps::default(), DisplayKind::Extra, tx, 0)[3];
let alpha = |tx: u32| tile_bytes(&comp, &BakedMaps::default(), AoMixing::Multiply, DisplayKind::Extra, tx, 0)[3];
// Tile 1001 fills its block; 1002 fills a quarter, encoded as 32 × log2(4)
assert_eq!((alpha(0), alpha(3), alpha(4), alpha(7)), (0, 0, 64, 64));
@@ -324,20 +329,28 @@ mod tests {
#[test]
fn missing_channels_fall_back_to_defaults() {
let comp = Composite::new(&[], 64);
let orm = tile_bytes(&comp, &BakedMaps::default(), DisplayKind::Orm, 0, 0);
let orm = tile_bytes(&comp, &BakedMaps::default(), AoMixing::Multiply, DisplayKind::Orm, 0, 0);
assert_eq!(&orm[..4], &[255, 128, 0, 128]);
assert_eq!(normal_texel(&comp, &BakedMaps::default(), 0), [0.0, 0.0, 1.0, 0.5], "flat, sheen roughness 0.5 rides in alpha");
assert_eq!(&tile_bytes(&comp, &BakedMaps::default(), DisplayKind::Emissive, 0, 0)[..4], &[0, 0, 0, 0]);
assert_eq!(&tile_bytes(&comp, &BakedMaps::default(), DisplayKind::Lobes, 0, 0)[..4], &[0, 25, 0, 0], "lobes off, coat roughness 0.1");
assert_eq!(&tile_bytes(&comp, &BakedMaps::default(), DisplayKind::Sheen, 0, 0)[..4], &[255, 255, 255, 0]);
assert_eq!(&tile_bytes(&comp, &BakedMaps::default(), DisplayKind::Extra, 0, 0)[..4], &[128, 128, 0, 0], "flat coat normal, no transmission");
assert_eq!(&tile_bytes(&comp, &BakedMaps::default(), AoMixing::Multiply, DisplayKind::Emissive, 0, 0)[..4], &[0, 0, 0, 0]);
assert_eq!(
&tile_bytes(&comp, &BakedMaps::default(), AoMixing::Multiply, DisplayKind::Lobes, 0, 0)[..4],
&[0, 25, 0, 0],
"lobes off, coat roughness 0.1"
);
assert_eq!(&tile_bytes(&comp, &BakedMaps::default(), AoMixing::Multiply, DisplayKind::Sheen, 0, 0)[..4], &[255, 255, 255, 0]);
assert_eq!(
&tile_bytes(&comp, &BakedMaps::default(), AoMixing::Multiply, DisplayKind::Extra, 0, 0)[..4],
&[128, 128, 0, 0],
"flat coat normal, no transmission"
);
for k in DisplayKind::ALL {
assert_eq!(k.default_texel(), tile_bytes(&comp, &BakedMaps::default(), k, 3, 5)[..k.bytes_per_texel()]);
assert_eq!(k.default_texel(), tile_bytes(&comp, &BakedMaps::default(), AoMixing::Multiply, k, 3, 5)[..k.bytes_per_texel()]);
}
let h = tile_bytes(&comp, &BakedMaps::default(), DisplayKind::Height, 0, 0);
let h = tile_bytes(&comp, &BakedMaps::default(), AoMixing::Multiply, DisplayKind::Height, 0, 0);
assert_eq!(h.len(), TILE_AREA * 8);
assert_eq!(half::f16::from_le_bytes([h[2], h[3]]).to_f32(), half::f16::from_f32(0.04).to_f32(), "default F0");
}
@@ -366,7 +379,7 @@ mod tests {
/// Decode texel `i` of the Normal display tile (0, 0).
fn normal_texel(comp: &Composite, baked: &BakedMaps, i: usize) -> [f32; 4] {
let bytes = tile_bytes(comp, baked, DisplayKind::Normal, 0, 0);
let bytes = tile_bytes(comp, baked, AoMixing::Multiply, DisplayKind::Normal, 0, 0);
[0, 1, 2, 3].map(|k| half::f16::from_le_bytes([bytes[i * 8 + k * 2], bytes[i * 8 + k * 2 + 1]]).to_f32())
}
@@ -401,11 +414,11 @@ mod tests {
comp.channels.get_mut(&Channel::Glossiness).unwrap().set(0, 0, &[to_u16(0.8)]);
comp.channels.get_mut(&Channel::Specular).unwrap().set(0, 0, &[to_u16(1.0), to_u16(0.5), 0]);
let orm = tile_bytes(&comp, &BakedMaps::default(), DisplayKind::Orm, 0, 0);
let orm = tile_bytes(&comp, &BakedMaps::default(), AoMixing::Multiply, DisplayKind::Orm, 0, 0);
assert!((orm[1] as i32 - 51).abs() <= 1, "roughness = 1 - 0.8, got {}", orm[1]);
let h = tile_bytes(&comp, &BakedMaps::default(), DisplayKind::Height, 0, 0);
let h = tile_bytes(&comp, &BakedMaps::default(), AoMixing::Multiply, DisplayKind::Height, 0, 0);
let at = |k: usize| half::f16::from_le_bytes([h[k * 2], h[k * 2 + 1]]).to_f32();
assert_eq!(at(0), 0.0);
@@ -429,7 +442,7 @@ mod tests {
set(Channel::Transmission, &[to_u16(0.6)]);
set(Channel::CoatNormal, &[to_u16(1.0), to_u16(0.5), to_u16(1.0)]);
let px = |k: DisplayKind| tile_bytes(&comp, &BakedMaps::default(), k, 0, 0)[4..8].to_vec();
let px = |k: DisplayKind| tile_bytes(&comp, &BakedMaps::default(), AoMixing::Multiply, k, 0, 0)[4..8].to_vec();
let near = |a: &[u8], b: &[u8]| a.iter().zip(b).all(|(x, y)| x.abs_diff(*y) <= 1);
assert!(near(&px(DisplayKind::Lobes), &[255, 51, 153, 64]), "{:?}", px(DisplayKind::Lobes));
+651 -191
View File
File diff suppressed because it is too large Load Diff
+111
View File
@@ -0,0 +1,111 @@
//! Which layers lay something down at one texel, for R + click on the model
use super::{
Acc, BlendMode, Channel, Content, EvaluationInputs, Inputs, LayerId, NCH, NO_TRI, Node, ProjectorDepthCache, TILE, Texel, evaluation_channels,
evaluation_fields, mix_group, plan, prepare_generators,
};
/// Below this weight a layer leaves the texel unchanged (one 16-bit step)
const SMALLEST_WEIGHT: f32 = 1.0 / 65535.0;
/// The paint and fill layers (and instances) that lay something down at texel (x, y) of texture set `inputs.ts` in any of `shown` channels, top first, each with the shown channels it changes there. Hidden layers, layers masked out there (by their own mask or a folder's) and channels at zero opacity count as laying nothing down. Projection depth maps come from `projectors` when it serves `inputs.mesh`
pub fn layers_at(inputs: &Inputs, projectors: &ProjectorDepthCache, (x, y): (u32, u32), shown: &[Channel]) -> Vec<(LayerId, Vec<Channel>)> {
let Ok(set) = inputs.project.texture_set(inputs.ts) else { return Vec::new() };
let gbuf = inputs.gbuf;
let covered = x < gbuf.width && y < gbuf.height && gbuf.tri.get((y * gbuf.width + x) as usize).is_some_and(|tri| *tri != NO_TRI);
if !covered {
return Vec::new();
}
// A cache built for another mesh would hand out its depth maps
let unbound = ProjectorDepthCache::default();
let served = projectors.serves(inputs.mesh);
let mut inputs = EvaluationInputs::new(inputs, if served { projectors } else { &unbound });
// The viewport's anchor heights are kept for the next query
if served {
inputs = inputs.of_the_session_stack();
}
prepare_generators(&mut inputs, None);
let inputs = &inputs;
let channels = evaluation_channels(inputs, set.channel_list());
// Plan the neighborhood that filters and anchors can read
let (tile_x, tile_y) = (x / TILE, y / TILE);
let fields = evaluation_fields(inputs, &channels, &[(tile_x, tile_y)]);
let nodes = plan(inputs, &set.stack, &channels, tile_x, tile_y, 0, Some(&fields));
let offset = ((y % TILE) * TILE + x % TILE) as usize;
let mut texel = Texel::new(inputs, x, y, offset, 0.0);
let mut stack = Channel::ALL.map(Channel::default_value);
let mut found = Vec::new();
texel.layers_laying_down(&nodes, &mut stack, [1.0; NCH], shown, &mut found);
// The stack runs bottom first
found.reverse();
found
}
impl Texel<'_, '_> {
/// Composite `nodes` (bottom first) over `stack`, pushing the leaf layers that lay something down in a `shown` channel, with those channels, each channel weighted by `weights` (the opacity and mask of the folders holding them)
fn layers_laying_down(&mut self, nodes: &[Node], stack: &mut Acc, weights: [f32; NCH], shown: &[Channel], found: &mut Vec<(LayerId, Vec<Channel>)>) {
for node in nodes {
// A mask comparing with the layers below reads the stack under its own layer
self.below = Some(*stack);
let mask = self.node_mask(node);
if mask <= 0.0 {
// A masked-out layer still records its anchor points
self.eval(std::slice::from_ref(node), stack);
continue;
}
let mut node_weights = [0.0; NCH];
for chan in node.chans.iter().filter(|chan| shown.iter().any(|channel| channel.index() == chan.ch)) {
if let (Some(weight), Some(slot)) = (weights.get(chan.ch), node_weights.get_mut(chan.ch)) {
*slot = weight * chan.opacity * mask;
}
}
match &node.content {
Content::Group(children) => {
let mut inner = *stack;
let first_child = found.len();
self.layers_laying_down(children, &mut inner, node_weights, shown, found);
mix_group(stack, &inner, &node.chans, mask);
// The folder instance is the selectable row for its source's children
if found.len() > first_child && self.inp.project.layers.get(&node.draw.0).and_then(|layer| layer.instance_source()).is_some() {
let contributed: Vec<Channel> =
shown.iter().copied().filter(|channel| found[first_child..].iter().any(|(_, channels)| channels.contains(channel))).collect();
found.truncate(first_child);
found.push((node.draw.0, contributed));
}
}
content => {
let changed: Vec<Channel> = shown
.iter()
.copied()
.filter(|channel| {
node.chans.iter().filter(|chan| chan.ch == channel.index()).any(|chan| {
let weight = node_weights.get(chan.ch).copied().unwrap_or(0.0);
// Replace lays its value down at full weight wherever the layer has content
weight > SMALLEST_WEIGHT
&& self
.content(content, chan)
.is_some_and(|(_, coverage)| chan.blend == BlendMode::Replace || weight * coverage > SMALLEST_WEIGHT)
})
})
.collect();
if !changed.is_empty() {
found.push((node.draw.0, changed));
}
self.eval(std::slice::from_ref(node), stack);
}
}
}
}
}
+1
View File
@@ -57,6 +57,7 @@ pub(crate) fn field_identity(inputs: &Inputs) -> u64 {
mesh.submeshes.iter().for_each(|part| (part.material, part.start, part.count).hash(&mut hash));
set.uv_tiles.hash(&mut hash);
set.resolution.hash(&mut hash);
set.resolution_height.hash(&mut hash);
set.tile_resolutions.hash(&mut hash);
}
@@ -0,0 +1,8 @@
/// Why a folder can't be flattened
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FlattenFolderError {
NotAFolder,
/// Its layers add up past what an image holds, which baking would clip
ValueOutOfRange,
}
+11 -2
View File
@@ -10,6 +10,7 @@
pub mod axis_frame;
mod baked_maps;
pub mod below;
mod channel_store;
mod curvature_size_level;
pub mod curvature_sizes;
pub mod display;
@@ -26,6 +27,7 @@ pub mod fill_copies;
pub mod fill_copy;
mod fill_depth;
mod fill_place;
mod flatten_folder_error;
pub mod frame_placement;
mod fur_lock;
mod generator_maps;
@@ -37,6 +39,7 @@ mod mask_gray;
mod micro_detail;
pub mod mip_level;
mod organic;
mod padding_maps;
pub mod pattern;
mod pattern_context;
pub mod projector_cover;
@@ -44,6 +47,8 @@ pub mod projector_depth;
mod projector_depth_cache;
pub mod projector_view;
mod sampled_map;
pub mod seam_padding;
mod seam_padding_input;
mod sections;
mod shape_distance;
mod slope_texel;
@@ -51,6 +56,7 @@ mod slot_placement;
mod soft_box;
pub mod solo;
pub mod store;
mod texel_edge;
mod texture_layer;
mod three_d_distance;
pub mod thumb;
@@ -73,12 +79,15 @@ pub use display::{DisplayKind, display_tile_bytes, kinds_for, tile_bytes};
pub use effect_histogram::EffectHistogram;
pub use eval::{
BLOCK, Composite, Inputs, MASK_CHANNEL, PaintTarget, Stencil, StrokePreview, all_tiles, compare_histograms, composite_tiles, composite_tiles_cached,
composite_tiles_with_projectors, covered_tiles, effect_histogram, flatten_layer, mask_at, mask_image, mask_image_sized, mask_texels, mask_values,
pad_tiles, stack_reads_neighbours,
composite_tiles_with_projectors, covered_tiles, effect_histogram, flatten_folder, flatten_layer, layers_at, mask_at, mask_image, mask_image_sized,
mask_texels, mask_values, pad_tiles, stack_reads_neighbours,
};
pub use flatten_folder_error::FlattenFolderError;
pub use mask_gray::MaskGray;
pub use padding_maps::PaddingMaps;
pub use pattern_context::PatternContext;
pub use projector_depth_cache::ProjectorDepthCache;
pub use seam_padding_input::SeamPaddingInput;
pub use solo::solo_project;
pub use store::{BakedMaps, ImageRes, ImageStore, PixelStore};
+196
View File
@@ -0,0 +1,196 @@
//! A texture set's UV padding: from island edges, and across seams for the texels past one
use std::collections::{BTreeMap, BTreeSet};
use texturecraft_core::{Channel, ChannelKind, UvPaddingMode};
use texturecraft_texel::TILE;
use texturecraft_texel::dilate::DilationMap;
use crate::SeamPaddingInput;
use crate::seam_padding::{SEAM_REACH, cross_seams};
/// A texture set's padding: `flat` for every texel, with the few texels past a seam listed apart in `crossed` by row
#[derive(Clone, Debug, PartialEq)]
pub struct PaddingMaps {
/// Padding from island edges (2D), which tangent-space normals always take: a normal turns with its island, so it can't continue across a seam
pub flat: DilationMap,
/// Across seams (3D): (texel, source texel) indices of the padding texels that continue from a seam's other side, sorted by texel
pub crossed: Vec<(u32, u32)>,
/// Where each row's texels start in `crossed`, one more than the rows (empty without any), so a lookup searches one row
pub(crate) row_starts: Vec<u32>,
/// For each tile holding a seam's far side, the tiles whose padding continues from it, so a change there repads them however far they are
pub(crate) crossed_into: BTreeMap<(u32, u32), BTreeSet<(u32, u32)>>,
}
impl PaddingMaps {
/// A padding map without seam continuation.
pub fn from_flat(flat: DilationMap) -> Self {
Self { flat, crossed: Vec::new(), row_starts: Vec::new(), crossed_into: BTreeMap::new() }
}
/// Bytes in the dense map, sparse seam arrays, and tile-index entries.
pub fn bytes(&self) -> usize {
self.flat.src.capacity() * size_of::<u32>()
+ self.crossed.capacity() * size_of::<(u32, u32)>()
+ self.row_starts.capacity() * size_of::<u32>()
+ (self.crossed_into.len() + self.crossed_into.values().map(BTreeSet::len).sum::<usize>()) * size_of::<(u32, u32)>()
}
/// The padding for `mode`: `covered` texels of a `width × height` set padded up to `max_dist` texels inside each `block`
pub fn new(
mode: UvPaddingMode,
covered: &[bool],
(width, height): (u32, u32),
max_dist: Option<u32>,
block: (u32, u32),
seams: Option<&SeamPaddingInput<'_>>,
) -> PaddingMaps {
let flat = DilationMap::in_rectangular_blocks(covered, width, height, max_dist, block);
let crossed = seams
.filter(|_| mode == UvPaddingMode::Space3d)
.map_or_else(Vec::new, |seams| cross_seams(&flat, max_dist.map_or(SEAM_REACH, |d| d.min(SEAM_REACH)), block, seams));
let row_starts =
if crossed.is_empty() { Vec::new() } else { (0..=height).map(|y| crossed.partition_point(|(texel, _)| *texel < y * width) as u32).collect() };
let tile_of = |texel: u32| ((texel % width) / TILE, (texel / width) / TILE);
let mut crossed_into: BTreeMap<(u32, u32), BTreeSet<(u32, u32)>> = BTreeMap::new();
for &(texel, source) in &crossed {
crossed_into.entry(tile_of(source)).or_default().insert(tile_of(texel));
}
PaddingMaps { flat, crossed, row_starts, crossed_into }
}
/// The tiles whose padding continues across a seam from texels in `tile`
pub fn tiles_crossed_from(&self, tile: (u32, u32)) -> impl Iterator<Item = (u32, u32)> + '_ {
self.crossed_into.get(&tile).into_iter().flatten().copied()
}
/// Texels across and down
pub fn size(&self) -> (u32, u32) {
(self.flat.width, self.flat.height)
}
/// Whether `channel` pads across seams; tangent-space normals pad from island edges
pub fn crosses_seams(channel: Channel) -> bool {
channel.kind() != ChannelKind::NormalMap
}
/// The covered texel padding (x, y), itself when covered; `across_seams` takes the seams' other sides
pub fn source(&self, across_seams: bool, x: u32, y: u32) -> Option<(u32, u32)> {
let source = self.flat.source(x, y)?;
if !across_seams || source == (x, y) {
return Some(source);
}
let (texel, width) = (y * self.flat.width + x, self.flat.width);
let row = match (self.row_starts.get(y as usize), self.row_starts.get(y as usize + 1)) {
(Some(&start), Some(&end)) => self.crossed.get(start as usize..end as usize).unwrap_or_default(),
_ => &[],
};
match row.binary_search_by_key(&texel, |(crossed_texel, _)| *crossed_texel) {
Ok(found) => row.get(found).map(|(_, crossed_source)| (crossed_source % width, crossed_source / width)),
Err(_) => Some(source),
}
}
}
#[cfg(test)]
mod tests {
use texturecraft_geom::glam::Vec2;
use texturecraft_geom::{NO_TRI, TrianglePartition, UvSeam, UvSeamSide, primitives};
use super::*;
/// Two islands of one 3D edge: the left one's right side is the right one's left side
fn two_islands() -> (Vec<bool>, Vec<UvSeam>) {
let (width, height) = (32u32, 8u32);
let covered = (0..width * height).map(|i| matches!(i % width, 4..=11 | 20..=27)).collect();
let at = |x: f32, y: f32| Vec2::new(x / width as f32, y / height as f32);
let left = UvSeamSide { triangle: 0, start: at(12.0, 0.0), end: at(12.0, 8.0), interior: at(4.0, 0.0) };
let right = UvSeamSide { triangle: 1, start: at(20.0, 0.0), end: at(20.0, 8.0), interior: at(28.0, 0.0) };
(covered, vec![UvSeam { sides: [left, right] }])
}
fn islands(seams: Vec<UvSeam>, triangles: &[u32]) -> SeamPaddingInput<'_> {
// A synthetic raster supplies its island ids directly
let mesh = primitives::plane(1.0, 2);
let partition = TrianglePartition::new(&mesh, 0, |_, _| Vec::<u32>::new());
SeamPaddingInput::new(seams, triangles, partition)
}
#[test]
fn a_flat_seam_keeps_the_last_row_within_its_reach() {
let (width, height) = (128, 128);
let at = |x: f32, y: f32| Vec2::new(x / width as f32, y / height as f32);
// The length rounds the normalized edge slightly below one
let near = UvSeamSide { triangle: 0, start: at(1.0, 32.5), end: at(16.25, 32.5), interior: at(1.0, 40.0) };
let far = UvSeamSide { triangle: 1, start: at(65.0, 32.5), end: at(80.25, 32.5), interior: at(65.0, 100.0) };
let triangles: Vec<_> = (0..width * height)
.map(|index| match (index % width, index / width) {
(1..=15, 32..=39) => 0,
(65..=79, 32..=99) => 1,
_ => NO_TRI,
})
.collect();
let covered: Vec<_> = triangles.iter().map(|&triangle| triangle != NO_TRI).collect();
let seams = islands(vec![UvSeam { sides: [near, far] }], &triangles);
let padding = PaddingMaps::new(UvPaddingMode::Space3d, &covered, (width, height), Some(SEAM_REACH), (64, height), Some(&seams));
assert!(padding.source(true, 15, 0).is_some_and(|(x, _)| x >= 64), "the boundary row borrows from the far island");
assert!(padding.source(false, 15, 0).is_some_and(|(x, _)| x < 64), "flat padding still uses the near island");
}
#[test]
fn padding_stops_at_the_far_islands_edge() {
let (_, seams) = two_islands();
let (width, height) = (32, 8);
for (gap, far_strip) in [(false, 2), (true, 2), (true, 1)] {
let triangles: Vec<_> = (0..width * height)
.map(|pixel| match pixel % width {
4..=11 => 0,
20..=21 => 1,
22 if gap => NO_TRI,
22..=27 => far_strip,
_ => NO_TRI,
})
.collect();
let covered: Vec<_> = triangles.iter().map(|id| *id != NO_TRI).collect();
let input = islands(seams.clone(), &triangles);
let padding = PaddingMaps::new(UvPaddingMode::Space3d, &covered, (width, height), Some(4), (0, 0), Some(&input));
assert_eq!(padding.source(true, 13, 3), Some((21, 3)), "a texel inside the far island continues the seam");
assert_eq!(padding.source(true, 15, 3), padding.source(false, 15, 3), "another island is out of reach even with no texel gap");
}
}
#[test]
fn padding_past_a_seam_continues_from_its_other_side_and_normals_stay_flat() {
let (covered, seams) = two_islands();
let triangles: Vec<_> = (0..32 * 8)
.map(|pixel| match pixel % 32 {
4..=11 => 0,
20..=27 => 1,
_ => NO_TRI,
})
.collect();
let input = islands(seams, &triangles);
let space_3d = PaddingMaps::new(UvPaddingMode::Space3d, &covered, (32, 8), Some(4), (0, 0), Some(&input));
let space_2d = PaddingMaps::new(UvPaddingMode::Space2d, &covered, (32, 8), Some(4), (0, 0), Some(&input));
let island = |padding: &PaddingMaps, across_seams: bool, x: u32| {
padding.source(across_seams, x, 3).map(|(source_x, _)| if source_x < 16 { "left" } else { "right" })
};
// Just right of the left island, then just left of the right island
assert_eq!((island(&space_3d, true, 13), island(&space_3d, true, 18)), (Some("right"), Some("left")));
assert_eq!((island(&space_2d, true, 13), island(&space_2d, true, 18)), (Some("left"), Some("right")));
assert_eq!((island(&space_3d, false, 13), island(&space_3d, false, 18)), (Some("left"), Some("right")));
assert!(PaddingMaps::crosses_seams(Channel::BaseColor) && !PaddingMaps::crosses_seams(Channel::Normal));
// Away from the seam, both modes pad from the near island, and only texels between the islands are kept apart
assert_eq!(island(&space_3d, true, 2), Some("left"));
assert!(!space_3d.crossed.is_empty() && space_2d.crossed.is_empty());
assert!(space_3d.crossed.iter().all(|(texel, _)| (12..20).contains(&(texel % 32))));
}
}
+3 -20
View File
@@ -33,26 +33,9 @@ const MIN_CELL_SIZE: f32 = 1e-6;
/// A cell centre this close outside a triangle's edge (as a share of its area) still counts as inside, so shared edges leave no gaps
const EDGE_TOLERANCE: f32 = 1e-6;
/// A depth map's grid as the CPU reads it in [`ProjectorDepth::cover`], for the GPU compositor
#[derive(Clone, Copy, Debug)]
pub struct DepthGrid<'a> {
/// The view the grid lies across
pub view: ProjectorView,
/// The view point at the grid's lower corner
pub origin: Vec2,
/// One cell's size across and up in the view
pub cell: Vec2,
/// Cells across and up
pub grid_side: usize,
/// The mesh radius measured along the view's depth axis
pub nearness_unit: f32,
/// Per cell, row by row from the lower corner: the nearest surface's nearness at the cell centre and its slope across and up (nearness -inf where no surface is)
pub front: &'a [[f32; 3]],
/// `cover`'s bias, slope bias limit and fade width, in mesh radii
pub bias: f32,
pub max_slope_bias: f32,
pub fade: f32,
}
mod depth_grid;
pub use depth_grid::DepthGrid;
impl ProjectorDepth {
/// The grid as `cover` reads it.
@@ -0,0 +1,22 @@
use super::{ProjectorView, Vec2};
/// A depth map's grid as the CPU reads it in [`super::ProjectorDepth::cover`], for the GPU compositor
#[derive(Clone, Copy, Debug)]
pub struct DepthGrid<'a> {
/// The view the grid lies across
pub view: ProjectorView,
/// The view point at the grid's lower corner
pub origin: Vec2,
/// One cell's size across and up in the view
pub cell: Vec2,
/// Cells across and up
pub grid_side: usize,
/// The mesh radius measured along the view's depth axis
pub nearness_unit: f32,
/// Per cell, row by row from the lower corner: the nearest surface's nearness at the cell centre and its slope across and up (nearness -inf where no surface is)
pub front: &'a [[f32; 3]],
/// `cover`'s bias, slope bias limit and fade width, in mesh radii
pub bias: f32,
pub max_slope_bias: f32,
pub fade: f32,
}
@@ -27,6 +27,11 @@ impl ProjectorDepthCache {
}
}
/// Whether its depth maps were built for `mesh`
pub(crate) fn serves(&self, mesh: &Mesh) -> bool {
std::ptr::eq(self.mesh.as_ptr(), mesh)
}
pub(crate) fn get(&self, mesh: &Mesh, key: FillDepthKey) -> Option<Arc<FillDepth>> {
// Rasterization is serial so tile workers can wait for a single build
let mut maps = self.maps.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
+153
View File
@@ -0,0 +1,153 @@
//! UV padding across seams (3D): texels past a UV seam continue the surface from the seam's other side
use std::collections::HashMap;
use texturecraft_geom::glam::{IVec2, Vec2};
use texturecraft_texel::dilate::{DilationMap, NONE};
use crate::SeamPaddingInput;
use crate::texel_edge::TexelEdge;
/// Farthest a padding texel reaches across a seam, in texels; farther ones keep their nearest covered texel
pub const SEAM_REACH: u32 = 32;
/// The padding texels of `flat` just outside a seam, each with the texel as far inside the seam's other side: (texel, source) indices sorted by texel
pub(crate) fn cross_seams(flat: &DilationMap, reach: u32, block: (u32, u32), input: &SeamPaddingInput<'_>) -> Vec<(u32, u32)> {
let (width, height) = (flat.width, flat.height);
let size = Vec2::new(width as f32, height as f32);
let block_of = |x: u32, y: u32| (x.checked_div(block.0).unwrap_or(0), y.checked_div(block.1).unwrap_or(0));
// Each crossed texel's source and how far outside its seam it is; a nearer seam replaces it
let mut crossed: HashMap<u32, (u32, f32)> = HashMap::new();
for seam in input.seams.iter() {
for (near, far) in [(seam.sides[0], seam.sides[1]), (seam.sides[1], seam.sides[0])] {
let (Some(near_edge), Some(far_edge)) = (TexelEdge::new(near, size), TexelEdge::new(far, size)) else {
continue;
};
let reach = reach as f32;
let low = near_edge.start.min(near_edge.end) - Vec2::splat(reach);
let high = near_edge.start.max(near_edge.end) + Vec2::splat(reach);
let (x0, y0) = (low.x.floor().max(0.0) as u32, low.y.floor().max(0.0) as u32);
let (x1, y1) = (high.x.ceil().min(size.x) as u32, high.y.ceil().min(size.y) as u32);
let mut side_islands = None;
for y in y0..y1 {
for x in near_edge.outside_columns(y, x0..x1, reach) {
let index = y * width + x;
let Some(&flat_source) = flat.src.get(index as usize) else { continue };
if flat_source == NONE || flat_source == index {
continue;
}
let point = Vec2::new(x as f32 + 0.5, y as f32 + 0.5);
let Some((along, outside)) = near_edge.outside(point) else { continue };
if outside > reach || crossed.get(&index).is_some_and(|(_, distance)| outside >= *distance) {
continue;
}
// Another island's edge nearer than the seam keeps its texel
let (source_x, source_y) = (flat_source % width, flat_source / width);
if (source_x.abs_diff(x).max(source_y.abs_diff(y)) as f32) + 1.0 < outside {
continue;
}
// Padding stays inside its UV tile, like the 2D padding
let inside = near_edge.start.lerp(near_edge.end, along) + near_edge.inward * 0.5;
if block_of(inside.x.max(0.0) as u32, inside.y.max(0.0) as u32) != block_of(x, y) {
continue;
}
// Start at the first texel centres on the seam's far side
let far_boundary = far_edge.start.lerp(far_edge.end, along);
let start = far_boundary + far_edge.inward * 0.5;
let target = far_boundary + far_edge.inward * outside.max(0.5);
if target.x < 0.0 || target.y < 0.0 || target.x >= size.x || target.y >= size.y {
continue;
}
let target_index = target.y as u32 * width + target.x as u32;
if flat.src.get(target_index as usize) != Some(&target_index) {
continue;
}
let (Some(near_island), Some(far_island)) =
*side_islands.get_or_insert_with(|| (input.triangle_island(near.triangle), input.triangle_island(far.triangle)))
else {
continue;
};
if input.island_at(flat_source) != Some(near_island) {
continue;
}
if input.island_at(target_index) == Some(far_island) && follows_island(input, start, target, far_island, (width, height), block) {
crossed.insert(index, (target_index, outside));
}
}
}
}
}
let mut sources: Vec<(u32, u32)> = crossed.into_iter().map(|(texel, (source, _))| (texel, source)).collect();
sources.sort_unstable();
sources
}
fn follows_island(input: &SeamPaddingInput<'_>, start: Vec2, target: Vec2, island: usize, (width, height): (u32, u32), block: (u32, u32)) -> bool {
let mut cell = start.floor().as_ivec2();
let end = target.floor().as_ivec2();
let limit = IVec2::new(width as i32, height as i32);
if cell.cmplt(IVec2::ZERO).any() || cell.cmpge(limit).any() {
return false;
}
if block.0 != 0 && block.1 != 0 {
let block = IVec2::new(block.0 as i32, block.1 as i32);
if cell / block != end / block {
return false;
}
}
let step = (end - cell).signum();
let delta = (target - start).abs();
let step_time = Vec2::new(1.0 / delta.x, 1.0 / delta.y);
let boundary_time = |axis: usize| {
if step[axis] == 0 {
return f32::INFINITY;
}
let boundary = cell[axis] + i32::from(step[axis] > 0);
(boundary as f32 - start[axis]).abs() * step_time[axis]
};
let mut next = Vec2::new(boundary_time(0), boundary_time(1));
// Visit every texel with a nonzero stretch of the path
let mut last_triangle = None;
loop {
let Some(triangle) = input.triangle_at(cell.y as u32 * width + cell.x as u32) else { return false };
if Some(triangle) != last_triangle {
if input.triangle_island(triangle) != Some(island) {
return false;
}
last_triangle = Some(triangle);
}
if cell == end {
return true;
}
let time = next.x.min(next.y);
if next.x == time {
cell.x += step.x;
next.x = if cell.x == end.x { f32::INFINITY } else { next.x + step_time.x };
}
if next.y == time {
cell.y += step.y;
next.y = if cell.y == end.y { f32::INFINITY } else { next.y + step_time.y };
}
}
}
+47
View File
@@ -0,0 +1,47 @@
use std::borrow::Cow;
use std::sync::OnceLock;
use texturecraft_geom::{Mesh, TrianglePartition, UvSeam};
/// Seams and the UV island of each rasterized triangle, borrowing the existing texel-to-triangle grid
pub struct SeamPaddingInput<'a> {
pub(crate) seams: Cow<'a, [UvSeam]>,
triangles: &'a [u32],
material: Option<(&'a Mesh, usize)>,
islands: OnceLock<TrianglePartition>,
}
impl<'a> SeamPaddingInput<'a> {
/// Use seams and a partition from the same mesh and material as the rasterized triangles
pub fn new(seams: Vec<UvSeam>, triangles: &'a [u32], islands: TrianglePartition) -> Self {
Self { seams: Cow::Owned(seams), triangles, material: None, islands: OnceLock::from(islands) }
}
/// Find seams now and build island ownership only if a padding texel can cross
pub fn of_material(mesh: &'a Mesh, material: usize, triangles: &'a [u32]) -> Option<Self> {
let seams = UvSeam::of_material(mesh, material);
if seams.is_empty() {
return None;
}
Some(Self { seams: Cow::Owned(seams), triangles, material: Some((mesh, material)), islands: OnceLock::new() })
}
/// Reuse already identified seams for a material's current UV layout.
pub fn with_material_seams(mesh: &'a Mesh, material: usize, triangles: &'a [u32], seams: &'a [UvSeam]) -> Self {
Self { seams: Cow::Borrowed(seams), triangles, material: Some((mesh, material)), islands: OnceLock::new() }
}
pub(crate) fn triangle_island(&self, triangle: u32) -> Option<usize> {
let islands = self.islands.get().or_else(|| self.material.map(|(mesh, material)| self.islands.get_or_init(|| UvSeam::islands_of(mesh, material))))?;
islands.index_of(triangle)
}
pub(crate) fn triangle_at(&self, texel: u32) -> Option<u32> {
self.triangles.get(texel as usize).copied()
}
pub(crate) fn island_at(&self, texel: u32) -> Option<usize> {
self.triangle_island(self.triangle_at(texel)?)
}
}
+1
View File
@@ -362,6 +362,7 @@ mod tests {
fn the_public_mip_chains_are_the_levels_bilinear_hq_reads() {
let image = ImageRes::new(8, 8, (0..64).map(|i| [i as f32 / 63.0, 0.25, 0.75, 1.0]).collect(), false);
let sampling = Sampling { filtering: Filtering::BilinearHq, ..Sampling::SAVED_BEFORE };
// Footprint 2: exactly the first halved level
let level = &image.mip_chain()[0];
assert_eq!(image.sample_filtered(0.3, 0.6, sampling, 2.0), bilinear(&level.rgba, level.width, level.height, 0.3, 0.6, (true, true)));
+103
View File
@@ -0,0 +1,103 @@
//! A UV seam side in texel space
use std::ops::Range;
use texturecraft_geom::UvSeamSide;
use texturecraft_geom::glam::Vec2;
/// A seam side in texel space, with its unit normal into the island
pub(crate) struct TexelEdge {
pub(crate) start: Vec2,
pub(crate) end: Vec2,
pub(crate) inward: Vec2,
}
impl TexelEdge {
pub(crate) fn new(side: UvSeamSide, size: Vec2) -> Option<TexelEdge> {
let (start, end, interior) = (side.start * size, side.end * size, side.interior * size);
let normal = (end - start).perp().try_normalize()?;
let inward = if normal.dot(interior - start) < 0.0 { -normal } else { normal };
Some(TexelEdge { start, end, inward })
}
/// How far along the edge (0..1) and how far outside the island `point` is, when it is beside the edge on the outside
pub(crate) fn outside(&self, point: Vec2) -> Option<(f32, f32)> {
let direction = self.end - self.start;
let along = (point - self.start).dot(direction) / direction.length_squared();
let outside = self.outside_distance(point);
((0.0..=1.0).contains(&along) && outside > 0.0).then_some((along, outside))
}
fn outside_distance(&self, point: Vec2) -> f32 {
-(point - self.start).dot(self.inward)
}
/// Clip columns to the exterior distance band using the same rounded distances as `outside`
pub(crate) fn outside_columns(&self, row: u32, columns: Range<u32>, reach: f32) -> Range<u32> {
if columns.is_empty() {
return columns;
}
let distance = |column| self.outside_distance(Vec2::new(column as f32 + 0.5, row as f32 + 0.5));
if self.inward.x == 0.0 {
let outside = distance(columns.start);
return if outside > 0.0 && outside <= reach { columns } else { 0..0 };
}
// Signed distance is monotone across a row even when adjacent values round to the same distance
let (start, end) = if self.inward.x < 0.0 {
let start = first_column_after(columns.clone(), |column| distance(column) <= 0.0);
(start, first_column_after(start..columns.end, |column| distance(column) <= reach))
} else {
let start = first_column_after(columns.clone(), |column| distance(column) > reach);
(start, first_column_after(start..columns.end, |column| distance(column) > 0.0))
};
start..end
}
}
fn first_column_after(mut columns: Range<u32>, before: impl Fn(u32) -> bool) -> u32 {
while columns.start < columns.end {
let middle = columns.start.midpoint(columns.end);
if before(middle) {
columns.start = middle + 1;
} else {
columns.end = middle;
}
}
columns.start
}
#[cfg(test)]
mod tests {
use texturecraft_geom::UvSeamSide;
use texturecraft_geom::glam::Vec2;
use super::TexelEdge;
#[test]
fn a_diagonal_edges_band_spans_every_texel_beside_it_without_scanning_the_rectangle() {
let size = Vec2::splat(512.0);
let side = UvSeamSide { triangle: 0, start: Vec2::new(0.05, 0.05), end: Vec2::new(0.95, 0.9), interior: Vec2::new(0.9, 0.1) };
let edge = TexelEdge::new(side, size).unwrap();
let reach = 32.0;
let (mut beside, mut spanned) = (0, 0);
for y in 0..512u32 {
let centre_y = y as f32 + 0.5;
let span = edge.outside_columns(y, 0..512, reach);
spanned += span.len();
for x in 0..512 {
let point = Vec2::new(x as f32 + 0.5, centre_y);
if edge.outside(point).is_some_and(|(_, outside)| outside <= reach) {
beside += 1;
assert!(span.contains(&x), "{point} is beside the edge but outside its row's span {span:?}");
}
}
}
// The diagonal's bounding box holds far more texels than its band
assert!(beside > 0 && spanned < 512 * 512 / 4, "{spanned} texels spanned for {beside} beside the edge");
}
}
+8 -24
View File
@@ -8,6 +8,12 @@ use texturecraft_geom::glam::Vec2;
use crate::store::{ImageRes, ImageStore};
use crate::tile_random_stream::TileRandomStream;
mod tile_layout;
mod tile_placement;
pub use tile_layout::TileLayout;
pub use tile_placement::TilePlacement;
/// The settings a Tile Generator pattern saved without its own reads
pub(crate) static DEFAULT: LazyLock<TileGenerator> = LazyLock::new(TileGenerator::default);
@@ -177,30 +183,6 @@ fn wrap(delta: f32, span: f32) -> f32 {
delta - (delta / span).round() * span
}
/// The part of a tile's evaluation that is constant across every image texel.
#[derive(Clone, Copy, Debug)]
pub struct TilePlacement {
pub center: Vec2,
pub size: Vec2,
pub radius: Vec2,
/// Sine and cosine of the clockwise screen-space rotation.
pub rotation: [f32; 2],
pub quarter_turns: u32,
pub mirrors: [bool; 2],
pub input: Option<usize>,
pub luminance: f32,
}
/// Positions and search bounds shared by the CPU and GPU Tile Generator.
#[derive(Debug)]
pub struct TileLayout {
pub amount: [u32; 2],
pub reach: Vec2,
pub line_shifts: Vec<f32>,
/// Columns first, then rows, matching the generator's pattern order.
pub placements: Vec<Option<TilePlacement>>,
}
pub fn prepare_tile_layout(tile: &TileGenerator, seed: u32) -> TileLayout {
let amount = tile.amount.map(|count| count.clamp(1, *TileGenerator::AMOUNT.end()));
let [columns, rows] = amount.map(|count| count as i32);
@@ -283,11 +265,13 @@ fn tile_value(tile: &TileGenerator, seed: u32, cell: (i32, i32), counts: (i32, i
if y.abs() > radius.y {
continue;
}
for copy_x in first.x as i32..=last.x as i32 {
let x = delta.x + copy_x as f32;
if x.abs() > radius.x {
continue;
}
let mut local = Vec2::new(cos * x + sin * y, -sin * x + cos * y) * 2.0 / size;
for _ in 0..quarter_turns {
local = Vec2::new(local.y, -local.x);
@@ -0,0 +1,13 @@
use texturecraft_geom::glam::Vec2;
use super::TilePlacement;
/// Positions and search bounds shared by the CPU and GPU Tile Generator.
#[derive(Debug)]
pub struct TileLayout {
pub amount: [u32; 2],
pub reach: Vec2,
pub line_shifts: Vec<f32>,
/// Columns first, then rows, matching the generator's pattern order.
pub placements: Vec<Option<TilePlacement>>,
}
@@ -0,0 +1,15 @@
use texturecraft_geom::glam::Vec2;
/// The part of a tile's evaluation that is constant across every image texel.
#[derive(Clone, Copy, Debug)]
pub struct TilePlacement {
pub center: Vec2,
pub size: Vec2,
pub radius: Vec2,
/// Sine and cosine of the clockwise screen-space rotation.
pub rotation: [f32; 2],
pub quarter_turns: u32,
pub mirrors: [bool; 2],
pub input: Option<usize>,
pub luminance: f32,
}
+416 -10
View File
@@ -39,6 +39,77 @@ pub enum Channel {
Transmission,
/// Tangent-space normal of the clear coat (relative to the mesh normal).
CoatNormal,
/// How much of the base layer shows (stored and exported: our shader does not read it)
BaseWeight,
/// Roughness of the diffuse base (stored and exported: our shader does not read it)
BaseDiffuseRoughness,
/// Strength of the specular lobe (stored and exported: our shader does not read it)
SpecularWeight,
/// Tint of the specular lobe (stored and exported: our shader does not read it)
SpecularColor,
/// Tint of transmitted light (stored and exported: our shader does not read it)
TransmissionColor,
/// Subsurface scattering color (stored and exported: our shader does not read it)
SubsurfaceColor,
/// Scattering distance per color (stored and exported: our shader does not read it)
SubsurfaceRadiusScale,
/// Clear coat tint (stored and exported: our shader does not read it)
CoatColor,
/// Clear coat anisotropy (stored and exported: our shader does not read it)
CoatAnisotropy,
/// Clear coat reflectance (stored and exported: our shader does not read it)
CoatSpecularLevel,
/// Tangent-space direction of the clear coat anisotropy, packed like a normal (stored and exported: our shader does not read it)
CoatTangent,
/// Thin-film iridescence weight (stored and exported: our shader does not read it)
ThinFilmWeight,
/// Tangent-space anisotropy direction, packed like a normal (stored and exported: our shader does not read it)
Tangent,
/// Mask for blending materials in an engine (stored and exported only)
BlendingMask,
/// Diffuse color of older shaders (stored and exported only)
Diffuse,
/// Signed displacement for render engines (stored and exported only)
Displacement,
/// Index of refraction, 0..1 as the target shader maps it (stored and exported only)
Ior,
/// Reflection amount of older shaders (stored and exported only)
Reflection,
/// Transmissive color of older shaders (stored and exported only)
Transmissive,
/// Free channels for anything a target shader needs (grey, stored and exported)
User0,
User1,
User2,
User3,
User4,
User5,
User6,
User7,
User8,
User9,
User10,
User11,
User12,
User13,
User14,
User15,
User16,
User17,
User18,
User19,
User20,
User21,
User22,
User23,
User24,
User25,
User26,
User27,
User28,
User29,
User30,
User31,
}
/// How a channel's values are stored and interpreted.
@@ -55,7 +126,7 @@ pub enum ChannelKind {
}
impl Channel {
pub const ALL: [Channel; 21] = [
pub const ALL: [Channel; 72] = [
Channel::BaseColor,
Channel::Metallic,
Channel::Roughness,
@@ -77,8 +148,62 @@ impl Channel {
Channel::ScatterWeight,
Channel::Transmission,
Channel::CoatNormal,
Channel::BaseWeight,
Channel::BaseDiffuseRoughness,
Channel::SpecularWeight,
Channel::SpecularColor,
Channel::TransmissionColor,
Channel::SubsurfaceColor,
Channel::SubsurfaceRadiusScale,
Channel::CoatColor,
Channel::CoatAnisotropy,
Channel::CoatSpecularLevel,
Channel::CoatTangent,
Channel::ThinFilmWeight,
Channel::Tangent,
Channel::BlendingMask,
Channel::Diffuse,
Channel::Displacement,
Channel::Ior,
Channel::Reflection,
Channel::Transmissive,
Channel::User0,
Channel::User1,
Channel::User2,
Channel::User3,
Channel::User4,
Channel::User5,
Channel::User6,
Channel::User7,
Channel::User8,
Channel::User9,
Channel::User10,
Channel::User11,
Channel::User12,
Channel::User13,
Channel::User14,
Channel::User15,
Channel::User16,
Channel::User17,
Channel::User18,
Channel::User19,
Channel::User20,
Channel::User21,
Channel::User22,
Channel::User23,
Channel::User24,
Channel::User25,
Channel::User26,
Channel::User27,
Channel::User28,
Channel::User29,
Channel::User30,
Channel::User31,
];
/// How many channels, from the start of [`Channel::ALL`], our shader reads
pub const SHADED_COUNT: usize = 21;
/// The extra shading lobes (clear coat, sheen, anisotropy, subsurface scattering,
/// transmission). Their defaults switch the lobes off, so a set without them shades exactly
/// as before.
@@ -101,8 +226,15 @@ impl Channel {
pub fn kind(self) -> ChannelKind {
match self {
Channel::BaseColor | Channel::Emissive | Channel::Specular | Channel::SheenColor => ChannelKind::Color,
Channel::Normal | Channel::CoatNormal => ChannelKind::NormalMap,
Channel::Height => ChannelKind::Signed,
Channel::SpecularColor
| Channel::TransmissionColor
| Channel::SubsurfaceColor
| Channel::SubsurfaceRadiusScale
| Channel::CoatColor
| Channel::Diffuse
| Channel::Transmissive => ChannelKind::Color,
Channel::Normal | Channel::CoatNormal | Channel::Tangent | Channel::CoatTangent => ChannelKind::NormalMap,
Channel::Height | Channel::Displacement => ChannelKind::Signed,
_ => ChannelKind::Scalar,
}
}
@@ -133,8 +265,53 @@ impl Channel {
Channel::Normal | Channel::CoatNormal => [0.5, 0.5, 1.0],
Channel::Opacity | Channel::AmbientOcclusion => [1.0; 3],
Channel::SpecularLevel | Channel::Glossiness => [0.5; 3],
// F0 of a common dielectric (4 %).
// F0 of a common dielectric (4 %)
Channel::Specular => [0.04; 3],
Channel::BaseWeight | Channel::SpecularWeight | Channel::SpecularColor | Channel::TransmissionColor | Channel::CoatColor => [1.0; 3],
Channel::BaseDiffuseRoughness
| Channel::CoatAnisotropy
| Channel::ThinFilmWeight
| Channel::BlendingMask
| Channel::Displacement
| Channel::Reflection
| Channel::Transmissive => [0.0; 3],
Channel::SubsurfaceColor => [0.8; 3],
Channel::SubsurfaceRadiusScale => [1.0, 0.5, 0.25],
Channel::CoatSpecularLevel | Channel::Diffuse | Channel::Ior => [0.5; 3],
Channel::CoatTangent | Channel::Tangent => [1.0, 0.5, 0.5],
Channel::User0
| Channel::User1
| Channel::User2
| Channel::User3
| Channel::User4
| Channel::User5
| Channel::User6
| Channel::User7
| Channel::User8
| Channel::User9
| Channel::User10
| Channel::User11
| Channel::User12
| Channel::User13
| Channel::User14
| Channel::User15
| Channel::User16
| Channel::User17
| Channel::User18
| Channel::User19
| Channel::User20
| Channel::User21
| Channel::User22
| Channel::User23
| Channel::User24
| Channel::User25
| Channel::User26
| Channel::User27
| Channel::User28
| Channel::User29
| Channel::User30
| Channel::User31 => [0.0; 3],
}
}
@@ -161,6 +338,57 @@ impl Channel {
Channel::ScatterWeight => "Scattering weight",
Channel::Transmission => "Transmission",
Channel::CoatNormal => "Coat normal",
Channel::BaseWeight => "Base weight",
Channel::BaseDiffuseRoughness => "Base diffuse roughness",
Channel::SpecularWeight => "Specular weight",
Channel::SpecularColor => "Specular color",
Channel::TransmissionColor => "Transmission color",
Channel::SubsurfaceColor => "Subsurface color",
Channel::SubsurfaceRadiusScale => "Subsurface radius scale",
Channel::CoatColor => "Coat color",
Channel::CoatAnisotropy => "Coat anisotropy",
Channel::CoatSpecularLevel => "Coat specular level",
Channel::CoatTangent => "Coat tangent",
Channel::ThinFilmWeight => "Thin-film weight",
Channel::Tangent => "Tangent",
Channel::BlendingMask => "Blending mask",
Channel::Diffuse => "Diffuse",
Channel::Displacement => "Displacement",
Channel::Ior => "Ior",
Channel::Reflection => "Reflection",
Channel::Transmissive => "Transmissive",
Channel::User0 => "User0",
Channel::User1 => "User1",
Channel::User2 => "User2",
Channel::User3 => "User3",
Channel::User4 => "User4",
Channel::User5 => "User5",
Channel::User6 => "User6",
Channel::User7 => "User7",
Channel::User8 => "User8",
Channel::User9 => "User9",
Channel::User10 => "User10",
Channel::User11 => "User11",
Channel::User12 => "User12",
Channel::User13 => "User13",
Channel::User14 => "User14",
Channel::User15 => "User15",
Channel::User16 => "User16",
Channel::User17 => "User17",
Channel::User18 => "User18",
Channel::User19 => "User19",
Channel::User20 => "User20",
Channel::User21 => "User21",
Channel::User22 => "User22",
Channel::User23 => "User23",
Channel::User24 => "User24",
Channel::User25 => "User25",
Channel::User26 => "User26",
Channel::User27 => "User27",
Channel::User28 => "User28",
Channel::User29 => "User29",
Channel::User30 => "User30",
Channel::User31 => "User31",
}
}
@@ -188,6 +416,57 @@ impl Channel {
Channel::ScatterWeight => "scatter",
Channel::Transmission => "transm",
Channel::CoatNormal => "coat nrm",
Channel::BaseWeight => "base weight",
Channel::BaseDiffuseRoughness => "diffuse rough",
Channel::SpecularWeight => "spec weight",
Channel::SpecularColor => "spec color",
Channel::TransmissionColor => "transm color",
Channel::SubsurfaceColor => "sss color",
Channel::SubsurfaceRadiusScale => "sss radius",
Channel::CoatColor => "coat color",
Channel::CoatAnisotropy => "coat aniso",
Channel::CoatSpecularLevel => "coat spec",
Channel::CoatTangent => "coat tangent",
Channel::ThinFilmWeight => "thin film",
Channel::Tangent => "tangent",
Channel::BlendingMask => "blend mask",
Channel::Diffuse => "diffuse",
Channel::Displacement => "displace",
Channel::Ior => "ior",
Channel::Reflection => "reflection",
Channel::Transmissive => "transmissive",
Channel::User0 => "user0",
Channel::User1 => "user1",
Channel::User2 => "user2",
Channel::User3 => "user3",
Channel::User4 => "user4",
Channel::User5 => "user5",
Channel::User6 => "user6",
Channel::User7 => "user7",
Channel::User8 => "user8",
Channel::User9 => "user9",
Channel::User10 => "user10",
Channel::User11 => "user11",
Channel::User12 => "user12",
Channel::User13 => "user13",
Channel::User14 => "user14",
Channel::User15 => "user15",
Channel::User16 => "user16",
Channel::User17 => "user17",
Channel::User18 => "user18",
Channel::User19 => "user19",
Channel::User20 => "user20",
Channel::User21 => "user21",
Channel::User22 => "user22",
Channel::User23 => "user23",
Channel::User24 => "user24",
Channel::User25 => "user25",
Channel::User26 => "user26",
Channel::User27 => "user27",
Channel::User28 => "user28",
Channel::User29 => "user29",
Channel::User30 => "user30",
Channel::User31 => "user31",
}
}
@@ -215,18 +494,84 @@ impl Channel {
Channel::ScatterWeight => "scatterWeight",
Channel::Transmission => "transmission",
Channel::CoatNormal => "coatNormal",
Channel::BaseWeight => "baseWeight",
Channel::BaseDiffuseRoughness => "baseDiffuseRoughness",
Channel::SpecularWeight => "specularWeight",
Channel::SpecularColor => "specularColor",
Channel::TransmissionColor => "transmissionColor",
Channel::SubsurfaceColor => "subsurfaceColor",
Channel::SubsurfaceRadiusScale => "subsurfaceRadiusScale",
Channel::CoatColor => "coatColor",
Channel::CoatAnisotropy => "coatAnisotropy",
Channel::CoatSpecularLevel => "coatSpecularLevel",
Channel::CoatTangent => "coatTangent",
Channel::ThinFilmWeight => "thinFilmWeight",
Channel::Tangent => "tangent",
Channel::BlendingMask => "blendingMask",
Channel::Diffuse => "diffuse",
Channel::Displacement => "displacement",
Channel::Ior => "ior",
Channel::Reflection => "reflection",
Channel::Transmissive => "transmissive",
Channel::User0 => "user0",
Channel::User1 => "user1",
Channel::User2 => "user2",
Channel::User3 => "user3",
Channel::User4 => "user4",
Channel::User5 => "user5",
Channel::User6 => "user6",
Channel::User7 => "user7",
Channel::User8 => "user8",
Channel::User9 => "user9",
Channel::User10 => "user10",
Channel::User11 => "user11",
Channel::User12 => "user12",
Channel::User13 => "user13",
Channel::User14 => "user14",
Channel::User15 => "user15",
Channel::User16 => "user16",
Channel::User17 => "user17",
Channel::User18 => "user18",
Channel::User19 => "user19",
Channel::User20 => "user20",
Channel::User21 => "user21",
Channel::User22 => "user22",
Channel::User23 => "user23",
Channel::User24 => "user24",
Channel::User25 => "user25",
Channel::User26 => "user26",
Channel::User27 => "user27",
Channel::User28 => "user28",
Channel::User29 => "user29",
Channel::User30 => "user30",
Channel::User31 => "user31",
}
}
/// Parse an id, label or short label (case-insensitive, spaces/underscores ignored).
/// Parse an id, label or short label, ignoring case, spaces, underscores and hyphens.
pub fn parse(s: &str) -> Option<Channel> {
let norm = |x: &str| x.to_ascii_lowercase().replace([' ', '_', '-'], "");
let want = norm(s);
Channel::ALL.into_iter().find(|c| norm(c.id()) == want || norm(c.label()) == want || norm(c.short()) == want || norm(&format!("{c:?}")) == want)
if let Some(channel) = Channel::ALL.into_iter().find(|channel| channel.id().eq_ignore_ascii_case(s)) {
return Some(channel);
}
let normalize = |name: &str| name.to_ascii_lowercase().replace([' ', '_', '-'], "");
let wanted = normalize(s);
Channel::ALL.into_iter().find(|channel| {
normalize(channel.id()) == wanted
|| normalize(channel.label()) == wanted
|| normalize(channel.short()) == wanted
|| normalize(&format!("{channel:?}")) == wanted
})
}
/// Position in [`Channel::ALL`] (the declaration order)
pub fn index(self) -> usize {
Channel::ALL.iter().position(|c| *c == self).unwrap_or(0)
self as usize
}
/// Whether our shader reads the channel; the others are stored and exported for other shaders
pub fn is_shaded(self) -> bool {
self.index() < Channel::SHADED_COUNT
}
}
@@ -253,6 +598,39 @@ impl ChannelFormat {
ChannelKind::Signed => ChannelFormat::L16F,
}
}
/// Every format, in the order the channel settings list them
pub const ALL: [ChannelFormat; 9] = [
ChannelFormat::Srgb8,
ChannelFormat::L8,
ChannelFormat::Rgb8,
ChannelFormat::L16,
ChannelFormat::Rgb16,
ChannelFormat::L16F,
ChannelFormat::Rgb16F,
ChannelFormat::L32F,
ChannelFormat::Rgb32F,
];
/// A format by its label, ignoring case ("srgb8", "L16F")
pub fn parse(label: &str) -> Option<ChannelFormat> {
ChannelFormat::ALL.into_iter().find(|format| format.label().eq_ignore_ascii_case(label.trim()))
}
/// Grey formats keep one value per texel: a colour channel stored in one turns grey
pub fn is_grey(self) -> bool {
matches!(self, ChannelFormat::L8 | ChannelFormat::L16 | ChannelFormat::L16F | ChannelFormat::L32F)
}
/// The 16-bit format holding everything an 8-bit one does (itself for the others)
pub fn at_least_16_bit(self) -> ChannelFormat {
match self {
ChannelFormat::Srgb8 | ChannelFormat::Rgb8 => ChannelFormat::Rgb16,
ChannelFormat::L8 => ChannelFormat::L16,
other => other,
}
}
pub fn label(self) -> &'static str {
match self {
ChannelFormat::Srgb8 => "sRGB8",
@@ -279,6 +657,7 @@ mod tests {
assert_eq!(Channel::parse(c.label()), Some(c));
assert_eq!(Channel::parse(c.short()), Some(c));
}
assert_eq!(Channel::parse("base color"), Some(Channel::BaseColor));
assert_eq!(Channel::parse("nope"), None);
}
@@ -293,17 +672,44 @@ mod tests {
assert!(prev.is_none_or(|p| p == c), "`{name}` names both {prev:?} and {c:?}");
}
}
for c in Channel::LOBES {
assert!(Channel::ALL.contains(&c));
// Tints, roughnesses and the flat coat normal only matter once their lobe has weight.
// Tints, roughnesses and the flat coat normal only matter once their lobe has weight
let off =
matches!(c, Channel::CoatRoughness | Channel::SheenColor | Channel::SheenRoughness | Channel::CoatNormal) || c.default_value() == [0.0; 3];
assert!(off, "{c:?} must default to an inactive lobe");
}
assert_eq!(Channel::parse("sheen color"), Some(Channel::SheenColor));
assert_eq!(Channel::parse("coatWeight"), Some(Channel::CoatWeight));
}
#[test]
fn formats_parse_by_label() {
for f in ChannelFormat::ALL {
assert_eq!(ChannelFormat::parse(&f.label().to_lowercase()), Some(f));
assert!(f.at_least_16_bit().is_grey() == f.is_grey());
}
assert_eq!(ChannelFormat::parse("RGB4"), None);
}
#[test]
fn unshaded_channels_round_trip_through_ids() {
// Project files and commands name channels by id: every added channel must come back as itself
for c in Channel::ALL.into_iter().filter(|c| !c.is_shaded()) {
assert_eq!(Channel::parse(c.id()), Some(c));
let json = serde_json::to_string(&c).unwrap_or_default();
assert_eq!(serde_json::from_str::<Channel>(&json).ok(), Some(c));
}
assert!(Channel::LOBES.iter().chain(&Channel::DEFAULT_SET).all(|c| c.is_shaded()));
assert_eq!(Channel::parse("User31"), Some(Channel::User31));
assert_eq!(Channel::parse("thin-film weight"), Some(Channel::ThinFilmWeight));
}
#[test]
fn index_matches_all_order() {
for (i, c) in Channel::ALL.iter().enumerate() {
+119
View File
@@ -0,0 +1,119 @@
//! The groups the channel manager lists material channels under
use crate::Channel;
/// A group of material channels, in the manager's reading order
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ChannelGroup {
Base,
Specular,
Transmission,
Subsurface,
Coat,
Sheen,
Emission,
ThinFilm,
Geometry,
Miscellaneous,
User,
}
impl ChannelGroup {
pub const ALL: [ChannelGroup; 11] = [
ChannelGroup::Base,
ChannelGroup::Specular,
ChannelGroup::Transmission,
ChannelGroup::Subsurface,
ChannelGroup::Coat,
ChannelGroup::Sheen,
ChannelGroup::Emission,
ChannelGroup::ThinFilm,
ChannelGroup::Geometry,
ChannelGroup::Miscellaneous,
ChannelGroup::User,
];
pub fn label(self) -> &'static str {
match self {
ChannelGroup::Base => "Base",
ChannelGroup::Specular => "Specular",
ChannelGroup::Transmission => "Transmission",
ChannelGroup::Subsurface => "Subsurface",
ChannelGroup::Coat => "Coat",
ChannelGroup::Sheen => "Fuzz / Sheen",
ChannelGroup::Emission => "Emission",
ChannelGroup::ThinFilm => "Thin-film",
ChannelGroup::Geometry => "Geometry",
ChannelGroup::Miscellaneous => "Miscellaneous",
ChannelGroup::User => "User",
}
}
/// The group's channels, in the order the manager lists them
pub fn channels(self) -> &'static [Channel] {
use Channel as C;
match self {
ChannelGroup::Base => &[C::BaseWeight, C::BaseColor, C::BaseDiffuseRoughness, C::Metallic],
ChannelGroup::Specular => &[C::SpecularWeight, C::SpecularColor, C::Roughness, C::SpecularLevel, C::AnisotropyLevel, C::AnisotropyAngle],
ChannelGroup::Transmission => &[C::Transmission, C::TransmissionColor],
ChannelGroup::Subsurface => &[C::ScatterWeight, C::SubsurfaceColor, C::SubsurfaceRadiusScale],
ChannelGroup::Coat => &[C::CoatWeight, C::CoatColor, C::CoatRoughness, C::CoatAnisotropy, C::CoatSpecularLevel, C::CoatNormal, C::CoatTangent],
ChannelGroup::Sheen => &[C::SheenWeight, C::SheenColor, C::SheenRoughness],
ChannelGroup::Emission => &[C::Emissive],
ChannelGroup::ThinFilm => &[C::ThinFilmWeight],
ChannelGroup::Geometry => &[C::Opacity, C::Normal, C::Height, C::AmbientOcclusion, C::Tangent],
ChannelGroup::Miscellaneous => &[C::BlendingMask, C::Diffuse, C::Displacement, C::Ior, C::Reflection, C::Specular, C::Glossiness, C::Transmissive],
ChannelGroup::User => &[
C::User0,
C::User1,
C::User2,
C::User3,
C::User4,
C::User5,
C::User6,
C::User7,
C::User8,
C::User9,
C::User10,
C::User11,
C::User12,
C::User13,
C::User14,
C::User15,
C::User16,
C::User17,
C::User18,
C::User19,
C::User20,
C::User21,
C::User22,
C::User23,
C::User24,
C::User25,
C::User26,
C::User27,
C::User28,
C::User29,
C::User30,
C::User31,
],
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_channel_is_listed_in_exactly_one_group() {
// A channel added to `Channel` but left out here could never be added from the manager
let mut listed: Vec<Channel> = ChannelGroup::ALL.iter().flat_map(|group| group.channels().iter().copied()).collect();
let count = listed.len();
listed.sort();
listed.dedup();
assert_eq!(listed.len(), count, "a channel is listed twice");
assert_eq!(listed, Channel::ALL.to_vec());
}
}
+8 -3
View File
@@ -53,9 +53,14 @@ impl HeightToNormal {
}
/// The unit tangent-space normal (OpenGL, +Y up the image) of a height changing by `gx` per texel to the right and `gy` per texel down
pub fn normal(&self, [gx, gy]: [f32; 2], res: u32) -> [f32; 3] {
let strength = self.strength(res);
let (x, y) = (-gx * strength, gy * strength);
pub fn normal(&self, slope: [f32; 2], res: u32) -> [f32; 3] {
self.normal_for_size(slope, [res; 2])
}
/// The same tangent-space normal for a UV tile with independent width and height
pub fn normal_for_size(&self, [gx, gy]: [f32; 2], [width, height]: [u32; 2]) -> [f32; 3] {
let strength_per_uv = self.strength(1);
let (x, y) = (-gx * (strength_per_uv * width as f32), gy * (strength_per_uv * height as f32));
let length = (x * x + y * y + 1.0).sqrt();
if length.is_finite() { [x / length, y / length, 1.0 / length] } else { [0.0, 0.0, 1.0] }
}
@@ -0,0 +1,48 @@
//! How a texture set turns its Height into normal slopes
use serde::{Deserialize, Serialize};
/// Height to normal method: the slope filter a texture set's height-to-normal uses
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum HeightToNormalMethod {
/// Sharp: the difference of the two neighbours across, so single-texel detail stays crisp
Sharp,
/// Smooth (Sobel): a 3×3 Sobel filter, so the slope also reads the diagonal neighbours
#[default]
Smooth,
}
impl HeightToNormalMethod {
pub const ALL: [HeightToNormalMethod; 2] = [HeightToNormalMethod::Sharp, HeightToNormalMethod::Smooth];
/// Stable id for commands and inspect
pub fn id(self) -> &'static str {
match self {
HeightToNormalMethod::Sharp => "sharp",
HeightToNormalMethod::Smooth => "smooth",
}
}
pub fn parse(id: &str) -> Option<HeightToNormalMethod> {
HeightToNormalMethod::ALL.into_iter().find(|value| value.id() == id)
}
/// The change of height per texel to the right and down, from the heights `h(dx, dy)` around a texel
pub fn slope(self, h: impl Fn(i32, i32) -> f32) -> [f32; 2] {
match self {
HeightToNormalMethod::Sharp => [(h(1, 0) - h(-1, 0)) * 0.5, (h(0, 1) - h(0, -1)) * 0.5],
HeightToNormalMethod::Smooth => {
// Both axes read the same four corner heights
let upper_left = h(-1, -1);
let upper_right = h(1, -1);
let lower_left = h(-1, 1);
let lower_right = h(1, 1);
[
(upper_right + 2.0 * h(1, 0) + lower_right - upper_left - 2.0 * h(-1, 0) - lower_left) / 8.0,
(lower_left + 2.0 * h(0, 1) + lower_right - upper_left - 2.0 * h(0, -1) - upper_right) / 8.0,
]
}
}
}
}
+7 -1
View File
@@ -2428,10 +2428,16 @@ pub struct Effect {
impl Effect {
pub fn new(id: LayerId, kind: EffectKind) -> Effect {
// Generators are named after their kind, as filters are
let name = match &kind {
EffectKind::Generator(generator) => generator.kind.label(),
_ => kind.name(),
};
// Generators and fills that build a mask usually add on top of the background
Effect {
id,
name: kind.name().to_string(),
name: name.to_string(),
visible: true,
kind,
blend: BlendMode::Normal,
+4 -1
View File
@@ -14,12 +14,15 @@ pub struct Sampling {
pub scale: ScaleMode,
#[serde(default, skip_serializing_if = "FillSymmetry::is_default")]
pub symmetry: FillSymmetry,
/// Each channel's image alpha is how much of that channel shows (the images a folder is flattened into)
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub alpha_coverage: bool,
}
impl Sampling {
/// What fills saved before the sampling choices existed did: plain bilinear
pub const SAVED_BEFORE: Sampling =
Sampling { filtering: Filtering::BilinearSharp, wrap: UvWrap::Repeat, scale: ScaleMode::Tiling, symmetry: FillSymmetry::OFF };
Sampling { filtering: Filtering::BilinearSharp, wrap: UvWrap::Repeat, scale: ScaleMode::Tiling, symmetry: FillSymmetry::OFF, alpha_coverage: false };
/// Serde default for fills saved before the field existed
pub fn saved_before() -> Sampling {
+6
View File
@@ -18,6 +18,7 @@ pub mod bevel_smooth;
pub mod blend;
mod block_scales;
pub mod channel;
pub mod channel_group;
pub mod color_match;
pub mod color_selection;
pub mod compare_source;
@@ -34,6 +35,7 @@ pub mod gradient_input;
pub mod grayscale_conversion;
pub mod grayscale_mode;
pub mod height_to_normal;
mod height_to_normal_method;
pub mod highpass_space;
pub mod image_input;
pub mod layer;
@@ -70,6 +72,7 @@ pub mod target_color_mode;
pub mod threshold_mode;
pub mod tile_transform;
pub mod unit_value;
mod uv_padding_mode;
pub mod validation_mode;
pub mod warp_blending;
pub mod warp_mode;
@@ -96,6 +99,7 @@ pub use bevel_direction::BevelDirection;
pub use bevel_smooth::BevelSmooth;
pub use blend::{BlendMode, blend1, blend3, lum, mix3};
pub use channel::{Channel, ChannelFormat, ChannelKind};
pub use channel_group::ChannelGroup;
pub use color_match::ColorMatch;
pub use color_selection::ColorSelection;
pub use compare_source::CompareSource;
@@ -111,6 +115,7 @@ pub use gradient_input::GradientInput;
pub use grayscale_conversion::GrayscaleConversion;
pub use grayscale_mode::GrayscaleMode;
pub use height_to_normal::HeightToNormal;
pub use height_to_normal_method::HeightToNormalMethod;
pub use highpass_space::HighpassSpace;
pub use image_input::ImageInput;
pub use layer::{
@@ -154,6 +159,7 @@ pub use target_color_mode::TargetColorMode;
pub use threshold_mode::ThresholdMode;
pub use tile_transform::{FlipMode, RepeatMode, TileTransform};
pub use unit_value::{at_or_above_threshold, finite_unit};
pub use uv_padding_mode::UvPaddingMode;
pub use validation_mode::ValidationMode;
pub use warp_blending::WarpBlending;
pub use warp_mode::WarpMode;
+235 -9
View File
@@ -4,7 +4,10 @@ use std::collections::{BTreeMap, BTreeSet};
use serde::{Deserialize, Serialize};
use crate::{BakeSettings, BakeSource, BakeSyncGroup, BakedMap, Channel, ChannelFormat, ContentsOffset, CoreError, Effect, Layer, LayerId, LayerKind, Result};
use crate::{
BakeSettings, BakeSource, BakeSyncGroup, BakedMap, Channel, ChannelFormat, ContentsOffset, CoreError, Effect, HeightToNormalMethod, Layer, LayerId,
LayerKind, Result, UvPaddingMode,
};
pub use crate::env_alignment::EnvAlignment;
pub use crate::shadow_mode::ShadowMode;
@@ -38,6 +41,22 @@ pub enum NormalMixing {
Replace,
}
impl NormalMixing {
pub const ALL: [NormalMixing; 2] = [NormalMixing::Combine, NormalMixing::Replace];
/// Stable id for commands and inspect
pub fn id(self) -> &'static str {
match self {
NormalMixing::Combine => "combine",
NormalMixing::Replace => "replace",
}
}
pub fn parse(id: &str) -> Option<NormalMixing> {
NormalMixing::ALL.into_iter().find(|mixing| mixing.id() == id)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum AoMixing {
#[default]
@@ -45,6 +64,22 @@ pub enum AoMixing {
None,
}
impl AoMixing {
pub const ALL: [AoMixing; 2] = [AoMixing::Multiply, AoMixing::None];
/// Stable id for commands and inspect
pub fn id(self) -> &'static str {
match self {
AoMixing::Multiply => "multiply",
AoMixing::None => "none",
}
}
pub fn parse(id: &str) -> Option<AoMixing> {
AoMixing::ALL.into_iter().find(|mixing| mixing.id() == id)
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TextureSet {
pub name: String,
@@ -52,15 +87,28 @@ pub struct TextureSet {
pub description: String,
/// Material index in the mesh this set paints.
pub material: usize,
/// Power of two, 128..=8192.
/// Texels across: a power of two, 128..=8192 (the side of a square set)
pub resolution: u32,
/// Texels down when they differ from `resolution` (a power of two, 128..=8192); sets with per-tile resolutions stay square
#[serde(default, skip_serializing_if = "Option::is_none")]
pub resolution_height: Option<u32>,
/// Channels and their storage formats; see [`TextureSet::formats`] for what they hold
pub channels: Vec<(Channel, ChannelFormat)>,
/// Whether channels hold their formats' precision; until a format is set every channel keeps 16 bits, what TextureCraft always stored
#[serde(default)]
pub format_precision: bool,
/// Top-level layers, bottom → top.
pub stack: Vec<LayerId>,
#[serde(default)]
pub normal_mixing: NormalMixing,
#[serde(default)]
pub ao_mixing: AoMixing,
/// Height to normal method; projects without it keep Smooth, the filter their exports already used
#[serde(default)]
pub height_to_normal: HeightToNormalMethod,
/// UV padding; projects without it keep padding from island edges (2D), the padding they were made with
#[serde(default)]
pub uv_padding: UvPaddingMode,
/// Height-to-normal strength.
#[serde(default = "one")]
pub height_strength: f32,
@@ -170,10 +218,14 @@ impl TextureSet {
description: String::new(),
material,
resolution,
resolution_height: None,
channels: Channel::DEFAULT_SET.iter().map(|c| (*c, ChannelFormat::default_for(*c))).collect(),
format_precision: false,
stack: Vec::new(),
normal_mixing: NormalMixing::Combine,
ao_mixing: AoMixing::Multiply,
height_to_normal: HeightToNormalMethod::Smooth,
uv_padding: UvPaddingMode::Space3d,
height_strength: 1.0,
bake: BakeSettings::default(),
baked: BTreeSet::new(),
@@ -214,11 +266,42 @@ impl TextureSet {
self.height_strength / self.tile_grid().map_or(1.0, |g| g.cols as f32)
}
/// Texels across and down: [`TextureSet::block_resolution`] per block of the atlas grid.
/// Columns over rows of the atlas grid (1 for a classic set): how much more slopes down the texture tilt than across it, as in export per block
pub fn atlas_height_y_factor(&self) -> f32 {
self.tile_grid().map_or(1.0, |g| g.cols as f32 / g.rows.max(1) as f32)
}
/// Whether the height slope joins the shaded normal ([`NormalMixing::Replace`] leaves it out)
pub fn height_in_normal(&self) -> bool {
self.normal_mixing == NormalMixing::Combine
}
/// Texels across and down: [`TextureSet::block_size`] per block of the atlas grid
pub fn size(&self) -> (u32, u32) {
let (cols, rows) = self.tile_grid().map_or((1, 1), |g| (g.cols, g.rows));
let (width, height) = self.block_size();
(width.saturating_mul(cols), height.saturating_mul(rows))
}
/// Texels down of the set's size (`resolution` for a square set)
pub fn height(&self) -> u32 {
self.resolution_height.unwrap_or(self.resolution)
}
/// Set the size to `width × height` (`height` stored only when it differs)
pub fn set_size(&mut self, width: u32, height: u32) {
self.resolution = width;
self.resolution_height = (height != width).then_some(height);
}
/// Texels across and down of an atlas block: the set's size, or the largest tile resolution square when tiles have their own
pub fn block_size(&self) -> (u32, u32) {
if self.tile_resolutions.is_empty() {
return (self.resolution, self.height());
}
let block = self.block_resolution();
(block.saturating_mul(cols), block.saturating_mul(rows))
(block, block)
}
/// Texels per side of UV tile `udim` (its override, else `resolution`).
@@ -226,12 +309,12 @@ impl TextureSet {
self.tile_resolutions.get(&udim).copied().unwrap_or(self.resolution)
}
/// Texels per side of an atlas block: the largest tile resolution (`resolution` for a
/// classic set or one without overrides).
/// Texels across an atlas block: the largest tile resolution (`resolution` without overrides); see [`TextureSet::block_size`]
pub fn block_resolution(&self) -> u32 {
if self.tile_resolutions.is_empty() {
return self.resolution;
}
self.uv_tiles.iter().map(|t| self.tile_resolution(*t)).max().unwrap_or(self.resolution)
}
@@ -246,9 +329,20 @@ impl TextureSet {
/// [`TextureSet::tile_scale`] of every atlas block, to look up by atlas texel.
pub fn block_scales(&self) -> BlockScales {
let Some(g) = self.tile_grid().filter(|_| !self.tile_resolutions.is_empty()) else { return BlockScales::default() };
let scales = (0..g.rows).flat_map(|by| (0..g.cols).map(move |bx| g.udim(bx, by))).map(|u| self.tile_scale(u)).collect();
BlockScales { block: self.block_resolution(), cols: g.cols, scales }
if self.tile_resolutions.is_empty() {
return BlockScales::default();
}
let Some(grid) = self.tile_grid() else { return BlockScales::default() };
let block = self.block_resolution();
let mut scales = vec![1.0; (grid.rows * grid.cols) as usize];
for &tile in &self.uv_tiles {
if let Some((column, row)) = grid.block(tile) {
scales[(row * grid.cols + column) as usize] = (self.tile_resolution(tile) as f32 / block.max(1) as f32).clamp(1e-3, 1.0);
}
}
BlockScales { block, cols: grid.cols, scales }
}
/// Scale of the tile holding mesh UV `uv` (v down) and that tile's origin corner.
@@ -283,6 +377,49 @@ impl TextureSet {
pub fn channel_list(&self) -> Vec<Channel> {
self.channels.iter().map(|(c, _)| *c).collect()
}
/// Channels the viewport can display individually, in texture-set order.
pub fn viewport_channels(&self) -> impl Iterator<Item = Channel> + '_ {
self.channels.iter().map(|(channel, _)| *channel).filter(|channel| channel.is_shaded())
}
/// The channels with the formats they are stored in (8-bit ones read as 16-bit without `format_precision`)
pub fn formats(&self) -> Vec<(Channel, ChannelFormat)> {
self.iter_formats().collect()
}
/// The effective storage formats in texture-set order
pub fn iter_formats(&self) -> impl Iterator<Item = (Channel, ChannelFormat)> + '_ {
self.channels.iter().map(|&(channel, format)| (channel, if self.format_precision { format } else { format.at_least_16_bit() }))
}
/// Add channel `c` in its default format (16-bit or more until a format is set, see [`TextureSet::formats`]); false when present
pub fn add_channel(&mut self, c: Channel) -> bool {
if self.has_channel(c) {
return false;
}
let format = ChannelFormat::default_for(c);
self.channels.push((c, if self.format_precision { format.at_least_16_bit() } else { format }));
self.channels.sort_by_key(|(c, _)| c.index());
true
}
/// Store channel `target` in `format` (false when the set lacks it); the other channels keep what they hold
pub fn set_channel_format(&mut self, target: Channel, format: ChannelFormat) -> bool {
if !self.has_channel(target) {
return false;
}
self.channels = self.formats();
self.format_precision = true;
for (channel, stored) in &mut self.channels {
if *channel == target {
*stored = format;
}
}
true
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
@@ -424,6 +561,7 @@ impl DisplaySettings {
}
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);
@@ -761,24 +899,37 @@ impl Project {
if self.format_version > FORMAT_VERSION {
return Err(CoreError::Invalid(format!("project format {} is newer than this TextureCraft supports ({FORMAT_VERSION})", self.format_version)));
}
if let Some(t) = self.texture_sets.iter().find(|t| !t.uv_tiles.is_empty() && (t.tile_grid().is_none() || !t.uv_tiles.is_sorted_by(|a, b| a < b))) {
return Err(CoreError::Invalid(format!("texture set \"{}\" has invalid UV tiles {:?}", t.name, t.uv_tiles)));
}
let bad_tile_res = |t: &TextureSet| {
t.tile_resolutions.iter().any(|(u, r)| !t.uv_tiles.contains(u) || !r.is_power_of_two() || !(MIN_RESOLUTION..=MAX_RESOLUTION).contains(r))
};
if let Some(t) = self.texture_sets.iter().find(|t| bad_tile_res(t)) {
return Err(CoreError::Invalid(format!("texture set \"{}\" has invalid UV tile resolutions {:?}", t.name, t.tile_resolutions)));
}
let bad_height = |set: &TextureSet| {
set.resolution_height
.is_some_and(|height| !height.is_power_of_two() || !(MIN_RESOLUTION..=MAX_RESOLUTION).contains(&height) || !set.tile_resolutions.is_empty())
};
if let Some(set) = self.texture_sets.iter().find(|set| bad_height(set)) {
return Err(CoreError::Invalid(format!("texture set \"{}\" has an invalid height {:?}", set.name, set.resolution_height)));
}
let mut seen = BTreeSet::new();
for ts in 0..self.texture_sets.len() {
for (id, depth) in self.walk(ts) {
if depth > MAX_DEPTH {
return Err(CoreError::Invalid("layer groups nested too deeply".into()));
}
if !self.layers.contains_key(&id) {
return Err(CoreError::Invalid(format!("stack references missing layer {}", id.0)));
}
if !seen.insert(id) {
return Err(CoreError::Invalid(format!("layer {} appears twice", id.0)));
}
@@ -870,6 +1021,37 @@ mod tests {
p
}
#[test]
fn older_sets_without_the_new_fields_open_square_with_2d_padding_and_smooth_normals() {
let mut v = serde_json::to_value(TextureSet::new("a", 0, 256)).unwrap();
for field in ["resolution_height", "format_precision", "height_to_normal", "uv_padding"] {
v.as_object_mut().unwrap().remove(field);
}
let old: TextureSet = serde_json::from_value(v).unwrap();
assert_eq!(old.size(), (256, 256));
assert_eq!((old.uv_padding, old.height_to_normal), (UvPaddingMode::Space2d, HeightToNormalMethod::Smooth));
}
#[test]
fn sets_keep_16_bits_until_a_format_is_set_also_in_older_files() {
let new = TextureSet::new("a", 0, 128);
let mut v = serde_json::to_value(&new).unwrap();
v.as_object_mut().unwrap().remove("format_precision");
let mut old: TextureSet = serde_json::from_value(v).unwrap();
let format = |t: &TextureSet, c: Channel| t.formats().into_iter().find(|(x, _)| *x == c).map(|(_, f)| f);
assert_eq!(format(&new, Channel::Roughness), Some(ChannelFormat::L16));
assert_eq!(format(&old, Channel::Roughness), Some(ChannelFormat::L16));
assert_eq!(format(&old, Channel::BaseColor), Some(ChannelFormat::Rgb16));
assert!(old.set_channel_format(Channel::Metallic, ChannelFormat::L8));
assert_eq!(format(&old, Channel::Metallic), Some(ChannelFormat::L8));
assert_eq!(format(&old, Channel::Roughness), Some(ChannelFormat::L16), "the other channels keep their precision");
assert!(!old.set_channel_format(Channel::Emissive, ChannelFormat::L8), "a channel the set lacks");
}
#[test]
fn enabling_ior_at_the_default_preserves_legacy_reflectance() {
let mut display = DisplaySettings::default();
@@ -1124,6 +1306,50 @@ mod tests {
}
}
#[test]
fn atlas_slopes_along_each_side_match_a_block_in_wide_tall_and_square_grids() {
let mut t = TextureSet::new("a", 0, 256);
t.height_strength = 3.0;
for tiles in [vec![1001, 1002], vec![1001, 1011], vec![1001, 1002, 1011, 1012], vec![1001, 1002, 1003]] {
t.uv_tiles = tiles;
let ((width, height), (block_width, block_height)) = (t.size(), t.block_size());
let across = t.atlas_height_strength() * width as f32;
let down = t.atlas_height_strength() * t.atlas_height_y_factor() * height as f32;
assert_eq!(across, t.height_strength * block_width as f32, "{:?}", t.uv_tiles);
assert_eq!(down, t.height_strength * block_height as f32, "{:?}", t.uv_tiles);
}
}
#[test]
fn non_square_sets_are_wider_than_tall_per_block_and_stay_square_with_tile_sizes() {
let mut p = project();
let t = &mut p.texture_sets[0];
t.set_size(1024, 256);
let (w, h) = t.size();
assert!(w > h, "{:?}", t.size());
t.uv_tiles = vec![1001, 1011];
// Tiles stack down, each block keeping the set's shape
assert_eq!(t.size(), (w, h * 2));
p.validate().unwrap();
// A height must be a valid size, and per-tile sizes need a square set
for bad in [Some(100), Some(16384)] {
let mut q = p.clone();
q.texture_sets[0].resolution_height = bad;
assert!(q.validate().is_err(), "{bad:?}");
}
let mut q = p.clone();
q.texture_sets[0].tile_resolutions.insert(1011, 128);
assert!(q.validate().is_err());
// The same size both ways is stored as square
p.texture_sets[0].set_size(512, 512);
assert_eq!(p.texture_sets[0].resolution_height, None);
}
#[test]
fn validate_rejects_newer_formats_and_dangling_ids() {
let mut p = project();
+29
View File
@@ -0,0 +1,29 @@
//! Where a texture set's UV padding takes its texels from
use serde::{Deserialize, Serialize};
/// UV padding mode: what fills the texels just outside a texture set's UV islands
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum UvPaddingMode {
/// Across seams (3D): past a UV seam, the texels continue the surface from the seam's other side
Space3d,
/// From island edges (2D): every texel repeats the nearest covered texel in the texture
#[default]
Space2d,
}
impl UvPaddingMode {
pub const ALL: [UvPaddingMode; 2] = [UvPaddingMode::Space3d, UvPaddingMode::Space2d];
/// Stable id for commands and inspect
pub fn id(self) -> &'static str {
match self {
UvPaddingMode::Space3d => "3d",
UvPaddingMode::Space2d => "2d",
}
}
pub fn parse(id: &str) -> Option<UvPaddingMode> {
UvPaddingMode::ALL.into_iter().find(|value| value.id() == id)
}
}
+14 -4
View File
@@ -1,10 +1,10 @@
//! The layer toolbar's Add mask items that add a mask with an effect in it (a bitmap, a height combination) and Add effect's colour selection
use serde_json::Value;
use texturecraft_core::{BlendMode, EffectKind, Sampling, Source};
use texturecraft_core::{BlendMode, Channel, EffectKind, Sampling, Source};
use texturecraft_paint::alphas;
use crate::commands::{CommandSpec, bad, has_layer, strp};
use crate::commands::{CommandSpec, bad, content_param, has_layer, strp};
use crate::mask_cmds::{color_selection, mask_target, new_compare, push_effect_as, push_own_mask_effect};
use crate::{Result, Session, cmd};
@@ -24,9 +24,9 @@ pub fn specs() -> Vec<CommandSpec> {
"Add mask with height combination",
["Layers", "Mask"],
None,
"{layer?} → {effect} — a compare mask (this layer's height greater than the layers below it, hardness 0.9) in the layer's mask (a new one if it has none); selected",
"{layer?} → {effect} — a compare mask (this layer's height greater than the layers below it, hardness 0.9) in the layer's mask (a new one if it has none); selected. The layer's height channel, if it has one, blends Normal",
has_layer,
|s, p| push_own_mask_effect(s, p, new_compare(), "Add mask with height combination", |_| Ok(()))
|s, p| push_own_mask_effect(s, p, new_compare(), "Add mask with height combination", |s| height_blends_normal(s, p))
),
cmd!(
"effect.add.colorSelection",
@@ -40,6 +40,16 @@ pub fn specs() -> Vec<CommandSpec> {
]
}
/// Where a height-combination mask shows the layer, the layer's height replaces the height below instead of mixing with it
fn height_blends_normal(s: &mut Session, p: &Value) -> Result<()> {
let id = content_param(s, "mask.add.heightCombination", p)?;
if let Some(blend) = s.doc.project.layers.get_mut(&id).and_then(|layer| layer.channels.get_mut(&Channel::Height)) {
blend.mode = BlendMode::Normal;
}
Ok(())
}
/// A mask fill reading an image resource or a library alpha, in one undo step with the alpha's resource
fn add_bitmap(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "mask.add.bitmap";
+6 -27
View File
@@ -16,34 +16,13 @@ pub type BrushTiles = BTreeSet<(u32, u32)>;
/// Stencil samples by document tile, in row-major linear RGBA.
pub type ProjectedTiles = BTreeMap<(u32, u32), Vec<[f32; 4]>>;
pub struct BrushBackend {
pub device: Arc<dyn BrushDevice>,
pub surface: Weak<UvGBuffer>,
}
mod brush_backend;
mod brush_surface;
mod device_stroke_preview;
pub struct BrushSurface {
pub mesh: Arc<Mesh>,
pub bvh: Arc<Bvh>,
pub uv: Arc<UvGBuffer>,
pub material: usize,
pub depth: Option<Arc<EyeDepth>>,
pub settings: BrushSettings,
pub stencil: Option<Stencil>,
pub limit: Option<(TileImage, bool)>,
}
pub struct DeviceStrokePreview<'a> {
pub ts: usize,
pub target: PaintTarget,
pub values: &'a BTreeMap<Channel, [f32; 3]>,
pub mask_value: f32,
/// The image resource whose gray a mask stroke paints per texel in place of `mask_value`.
pub mask_image: Option<&'a str>,
pub opacity: f32,
/// The Eraser: the stroke scales the target's paint and coverage down instead of painting.
pub erase: bool,
pub stroke: &'a dyn DeviceStroke,
}
pub use brush_backend::BrushBackend;
pub use brush_surface::BrushSurface;
pub use device_stroke_preview::DeviceStrokePreview;
pub trait BrushDevice: Send + Sync {
fn start(&self, surface: BrushSurface) -> std::result::Result<Box<dyn DeviceStroke>, String>;
@@ -0,0 +1,6 @@
use super::{Arc, BrushDevice, UvGBuffer, Weak};
pub struct BrushBackend {
pub device: Arc<dyn BrushDevice>,
pub surface: Weak<UvGBuffer>,
}
@@ -0,0 +1,12 @@
use super::{Arc, BrushSettings, Bvh, EyeDepth, Mesh, Stencil, TileImage, UvGBuffer};
pub struct BrushSurface {
pub mesh: Arc<Mesh>,
pub bvh: Arc<Bvh>,
pub uv: Arc<UvGBuffer>,
pub material: usize,
pub depth: Option<Arc<EyeDepth>>,
pub settings: BrushSettings,
pub stencil: Option<Stencil>,
pub limit: Option<(TileImage, bool)>,
}
@@ -0,0 +1,14 @@
use super::{BTreeMap, Channel, DeviceStroke, PaintTarget};
pub struct DeviceStrokePreview<'a> {
pub ts: usize,
pub target: PaintTarget,
pub values: &'a BTreeMap<Channel, [f32; 3]>,
pub mask_value: f32,
/// The image resource whose gray a mask stroke paints per texel in place of `mask_value`.
pub mask_image: Option<&'a str>,
pub opacity: f32,
/// The Eraser: the stroke scales the target's paint and coverage down instead of painting.
pub erase: bool,
pub stroke: &'a dyn DeviceStroke,
}
+41 -1
View File
@@ -193,6 +193,46 @@ pub fn check_enabled(spec: &CommandSpec, s: &Session) -> std::result::Result<(),
(spec.enabled)(s)
}
/// [`check_enabled`] for a run with `params`, checking a command that takes `layer`, or `effect` first, as if the named layer (one drawing the effect) were selected
fn check_enabled_for(spec: &CommandSpec, s: &mut Session, params: &Value) -> std::result::Result<(), String> {
let refused = match check_enabled(spec, s) {
Ok(()) => return Ok(()),
Err(why) => why,
};
let id_param = |key: &str| u64p(params, key).map(texturecraft_core::LayerId);
let ts = s.ts();
let project = &s.doc.project;
let in_active_set = |id| project.locate(id).is_some_and(|(found, _, _)| found == ts);
let named_layer = id_param("layer").filter(|_| spec.params.contains("layer?")).filter(|id| in_active_set(*id));
let named_effect = id_param("effect").filter(|_| spec.params.starts_with("{effect"));
// An effect's layer may sit in another texture set, drawn here by an instance
let layer_drawing_effect = || {
let owner = project.effect(named_effect?)?.0;
if in_active_set(owner) {
return Some(owner);
}
project.texture_set(ts).ok()?.stack.iter().copied().find(|id| project.render_tree(&[*id]).contains(&owner))
};
let Some(id) = named_layer.or_else(layer_drawing_effect) else { return Err(refused) };
let selected = s.selected.insert(ts, id);
let target = s.target;
if let Some(effect) = named_effect {
s.target = crate::StackTarget::Effect(effect);
}
let enabled = check_enabled(spec, s);
s.target = target;
match selected {
Some(old) => s.selected.insert(ts, old),
None => s.selected.remove(&ts),
};
enabled
}
pub fn find(id: &str) -> Option<&'static CommandSpec> {
command_specs().iter().find(|c| c.id == id)
}
@@ -201,7 +241,7 @@ pub fn find(id: &str) -> Option<&'static CommandSpec> {
/// `merge: true` its edits continue the previous undo step of the same label (drags).
pub fn execute(s: &mut Session, id: &str, params: &Value) -> Result<Value> {
let spec = find(id).ok_or_else(|| EngineError::UnknownCommand(id.to_string()))?;
check_enabled(spec, s).map_err(|why| EngineError::Disabled { cmd: id.to_string(), why })?;
check_enabled_for(spec, s, params).map_err(|why| EngineError::Disabled { cmd: id.to_string(), why })?;
let outer = std::mem::replace(&mut s.merge_edits, boolp(params, "merge").unwrap_or(false));
let result = (spec.run)(s, params);
s.merge_edits = outer;
+62 -40
View File
@@ -4,18 +4,21 @@ use std::collections::BTreeSet;
use std::ops::Deref;
use std::sync::{Arc, OnceLock};
use texturecraft_compose::{Composite, pad_tiles};
use texturecraft_geom::{NO_TRI, UvGBuffer};
use texturecraft_compose::{Composite, PaddingMaps, SeamPaddingInput, pad_tiles};
use texturecraft_core::{TextureSet, UvPaddingMode};
use texturecraft_geom::{Mesh, NO_TRI, UvGBuffer};
use texturecraft_texel::DilationMap;
use crate::display_seam_geometry::DisplaySeamGeometry;
use crate::session::DISPLAY_PADDING;
/// The viewport's padding map. Reading the dense map explicitly also works for uniform UVs.
pub struct DisplayPadding {
dense: Arc<OnceLock<Arc<DilationMap>>>,
dense: Arc<OnceLock<PaddingMaps>>,
size: (u32, u32),
mixed: Option<Arc<UvGBuffer>>,
block: u32,
block: (u32, u32),
seam_geometry: Option<Arc<DisplaySeamGeometry>>,
#[cfg(not(target_arch = "wasm32"))]
worker_started: bool,
/// All texels covered or all uncovered. Mixed coverage needs the ordinary dilation map.
@@ -23,7 +26,7 @@ pub struct DisplayPadding {
}
impl DisplayPadding {
pub(crate) fn new(gbuf: &Arc<UvGBuffer>, has_coverage: bool, block: u32) -> Self {
pub(crate) fn new(mesh: &Arc<Mesh>, set: &TextureSet, gbuf: &Arc<UvGBuffer>, has_coverage: bool, block: (u32, u32)) -> Self {
let size = (gbuf.width, gbuf.height);
let uniform = if !has_coverage {
Some(false)
@@ -33,11 +36,15 @@ impl DisplayPadding {
None
};
let mixed = uniform.is_none().then(|| Arc::clone(gbuf));
let seam_geometry =
if mixed.is_some() && set.uv_padding == UvPaddingMode::Space3d { DisplaySeamGeometry::new(mesh, set.material).map(Arc::new) } else { None };
Self {
dense: Arc::default(),
size,
mixed,
block,
seam_geometry,
#[cfg(not(target_arch = "wasm32"))]
worker_started: false,
uniform,
@@ -45,28 +52,38 @@ impl DisplayPadding {
}
pub(crate) fn apply_to_tiles(&self, output: &mut Composite, tiles: &[(u32, u32)]) -> BTreeSet<(u32, u32)> {
if self.uniform.is_some() { BTreeSet::new() } else { pad_tiles(output, self, tiles) }
if self.uniform.is_some() { BTreeSet::new() } else { pad_tiles(output, self.maps(), tiles) }
}
/// The same nearest covered source as the dense map, without constructing it for one pick.
pub(crate) fn source_for_sample(&self, x: u32, y: u32) -> Option<(u32, u32)> {
pub(crate) fn source_for_sample(&self, across_seams: bool, x: u32, y: u32) -> Option<(u32, u32)> {
if let Some(dense) = self.dense.get() {
return dense.source(x, y);
return dense.source(across_seams, x, y);
}
let gbuf = self.mixed.as_ref()?;
let block = if self.block == 0 { u32::MAX } else { self.block };
let bounds = |pos: u32, size: u32| {
if across_seams && self.seam_geometry.is_some() {
return self.maps().source(true, x, y);
}
let bounds = |pos: u32, size: u32, block: u32| {
let block = if block == 0 { u32::MAX } else { block };
let start = pos / block * block;
let last = start.saturating_add(block - 1).min(size - 1);
pos.saturating_sub(DISPLAY_PADDING).max(start)..=pos.saturating_add(DISPLAY_PADDING).min(last)
};
let columns = bounds(x, self.size.0);
bounds(y, self.size.1)
let columns = bounds(x, self.size.0, self.block.0);
bounds(y, self.size.1, self.block.1)
.flat_map(|sy| columns.clone().map(move |sx| (sx, sy)))
.filter(|&(sx, sy)| gbuf.tri[(sy * gbuf.width + sx) as usize] != NO_TRI)
.min_by_key(|&(sx, sy)| (sx.abs_diff(x).max(sy.abs_diff(y)), sy, sx))
}
/// Seam continuation needs the CPU when the atlas has uncovered texels.
pub fn needs_seam_padding(&self) -> bool {
self.seam_geometry.is_some()
}
/// Whether every texel has a surface sample and the display needs no padding.
pub fn fully_covered(&self) -> bool {
self.uniform == Some(true)
@@ -85,45 +102,50 @@ impl DisplayPadding {
/// Start the dense CPU fallback on a worker so the viewport can keep drawing.
#[cfg(not(target_arch = "wasm32"))]
pub fn prepare_on_worker(&mut self) -> bool {
if self.is_ready() {
return true;
pub fn prepare_on_worker(&mut self) {
if self.worker_started || self.is_ready() {
return;
}
let Some(gbuf) = self.mixed.as_ref() else { return true };
if !self.worker_started {
let (gbuf, dense, block) = (gbuf.clone(), self.dense.clone(), self.block);
self.worker_started = std::thread::Builder::new()
.name("texturecraft-padding".into())
.spawn(move || {
dense.get_or_init(|| mixed_sources(&gbuf, block));
})
.is_ok();
}
// If creating a thread failed, let the caller prepare the map synchronously.
!self.worker_started
let Some(gbuf) = self.mixed.as_ref() else { return };
let (gbuf, dense, block) = (Arc::downgrade(gbuf), Arc::downgrade(&self.dense), self.block);
let seam_geometry = self.seam_geometry.as_ref().map(Arc::downgrade);
self.worker_started = true;
rayon::spawn(move || {
let (Some(dense), Some(gbuf)) = (dense.upgrade(), gbuf.upgrade()) else { return };
let seam_geometry = seam_geometry.and_then(|geometry| geometry.upgrade());
dense.get_or_init(|| mixed_sources(&gbuf, block, seam_geometry.as_deref()));
});
}
pub(crate) fn bytes(&self) -> usize {
self.dense.get().map_or(0, |map| map.src.capacity() * size_of::<u32>())
self.dense.get().map_or(0, PaddingMaps::bytes)
}
}
impl Deref for DisplayPadding {
type Target = Arc<DilationMap>;
fn deref(&self) -> &Self::Target {
pub(crate) fn maps(&self) -> &PaddingMaps {
self.dense.get_or_init(|| {
let (width, height) = self.size;
if let Some(gbuf) = &self.mixed {
return mixed_sources(gbuf, self.block);
return mixed_sources(gbuf, self.block, self.seam_geometry.as_deref());
}
let n = width as usize * height as usize;
let src = if self.uniform == Some(true) { (0..n as u32).collect() } else { vec![texturecraft_texel::dilate::NONE; n] };
Arc::new(DilationMap { width, height, src })
let (width, height) = self.size;
let texel_count = width as usize * height as usize;
let src = if self.uniform == Some(true) { (0..texel_count as u32).collect() } else { vec![texturecraft_texel::dilate::NONE; texel_count] };
PaddingMaps::from_flat(DilationMap { width, height, src })
})
}
}
fn mixed_sources(gbuf: &UvGBuffer, block: u32) -> Arc<DilationMap> {
Arc::new(DilationMap::in_blocks(&gbuf.coverage_mask(), gbuf.width, gbuf.height, Some(DISPLAY_PADDING), block))
impl Deref for DisplayPadding {
type Target = DilationMap;
fn deref(&self) -> &Self::Target {
&self.maps().flat
}
}
fn mixed_sources(gbuf: &UvGBuffer, block: (u32, u32), seam_geometry: Option<&DisplaySeamGeometry>) -> PaddingMaps {
let seams = seam_geometry.map(|geometry| SeamPaddingInput::with_material_seams(&geometry.mesh, geometry.material, &gbuf.tri, &geometry.seams));
let mode = if seams.is_some() { UvPaddingMode::Space3d } else { UvPaddingMode::Space2d };
PaddingMaps::new(mode, &gbuf.coverage_mask(), (gbuf.width, gbuf.height), Some(DISPLAY_PADDING), block, seams.as_ref())
}
@@ -0,0 +1,17 @@
use std::sync::Arc;
use texturecraft_geom::{Mesh, UvSeam};
/// Seam topology shared with the worker that prepares display padding.
pub(crate) struct DisplaySeamGeometry {
pub(crate) mesh: Arc<Mesh>,
pub(crate) material: usize,
pub(crate) seams: Vec<UvSeam>,
}
impl DisplaySeamGeometry {
pub(crate) fn new(mesh: &Arc<Mesh>, material: usize) -> Option<Self> {
let seams = UvSeam::of_material(mesh, material);
(!seams.is_empty()).then(|| Self { mesh: mesh.clone(), material, seams })
}
}
+8
View File
@@ -0,0 +1,8 @@
//! Which way a step of `effect.moveUp` / `effect.moveDown` moves an effect
/// Which way an effect moves one place: up is later in its stack (rows list the top first)
#[derive(Clone, Copy)]
pub(crate) enum EffectStep {
Up,
Down,
}
+21 -7
View File
@@ -104,7 +104,7 @@ pub fn specs() -> Vec<CommandSpec> {
"List export outputs",
[],
None,
"{preset?: name or preset object, ts?, format?, bitDepth?, dithering?, size?, colorSpace?, maps?} → [{ts, map, file, tile: UV tile number or null, udimPattern: file pattern with <UDIM> or null, format, bitDepth, dithering, size, sourceSize, warnings, layers: [{map, name}] (a PSD's maps, top first)}] (keeps the first file per case-insensitive name, warns about later duplicates, and rejects file and folder conflicts)",
"{preset?: name or preset object, ts?, format?, bitDepth?, dithering?, size?, colorSpace?, maps?} → [{ts, map, file, tile: UV tile number or null, udimPattern: file pattern with <UDIM> or null, format, bitDepth, dithering, size (width), height, sourceSize, sourceHeight, warnings, layers: [{map, name}] (a PSD's maps, top first)}] (keeps the first file per case-insensitive name, warns about later duplicates, and rejects file and folder conflicts)",
always,
plan
),
@@ -442,6 +442,7 @@ impl Session {
let files = self.with_export_input(
set_index,
&mesh_name,
options.padding != Padding::None,
|grid| Cow::Owned(grid.coverage_mask()),
|input| texturecraft_formats::export::render_planned_maps(input, options, plans).map_err(fe),
)?;
@@ -456,6 +457,7 @@ impl Session {
&self,
set_index: usize,
mesh_name: &str,
needs_padding: bool,
coverage: impl FnOnce(&UvGBuffer) -> Cow<'_, [Coverage]>,
with: impl FnOnce(&ExportInput<Coverage>) -> Result<T>,
) -> Result<T> {
@@ -463,6 +465,11 @@ impl Session {
let cache = self.caches.get(set_index).ok_or_else(missing)?;
let composite = self.document_composite(set_index, &cache.covered_tiles).ok_or_else(missing)?;
let coverage = coverage(&cache.gbuf);
let seams = if needs_padding {
self.doc.project.texture_sets.get(set_index).and_then(|set| crate::session::padding_seams(&self.mesh, set, &cache.gbuf))
} else {
None
};
let empty = Default::default();
let input = ExportInput {
project: &self.doc.project,
@@ -470,6 +477,7 @@ impl Session {
composite: &composite,
baked: self.doc.baked.get(&set_index).unwrap_or(&empty),
coverage: &coverage,
seams: seams.as_ref(),
mesh_name,
};
with(&input)
@@ -488,6 +496,7 @@ impl Session {
self.with_export_input(
set_index,
&mesh_name,
false,
|grid| Cow::Borrowed(&grid.tri),
|input| MapPreview::sample_triangles(input, &options, map, side).map_err(fe),
)
@@ -627,7 +636,7 @@ fn preview(session: &mut Session, params: &Value) -> Result<Value> {
}
fn plan(session: &mut Session, params: &Value) -> Result<Value> {
use texturecraft_formats::export::{list_set_outputs, scale_export_side};
use texturecraft_formats::export::{list_set_outputs, output_dimensions};
let options = export_options(session, params, "export.plan")?;
let project = &session.doc.project;
@@ -640,12 +649,15 @@ fn plan(session: &mut Session, params: &Value) -> Result<Value> {
let Some((set_index, _)) = set_outputs.first() else { continue };
let set = project.texture_set(*set_index).map_err(|error| EngineError::Other(error.to_string()))?;
let block_size = set.block_resolution();
for (_, output) in set_outputs {
let source_size = output.tile.map_or(set.resolution, |tile| set.tile_resolution(tile));
let source = output_dimensions(set, output.tile, None);
// A map's own size wins over the export's; a PSD is the size of its largest layer
let size = output.maps().map(|map| scale_export_side(source_size, block_size, options.map_size(map))).max().unwrap_or(source_size);
// A PSD's canvas takes the largest width and height of its exported layers
let (size, height) = output
.maps()
.map(|map| output_dimensions(set, output.tile, options.map_size(map)))
.reduce(|(width, height), (next_width, next_height)| (width.max(next_width), height.max(next_height)))
.unwrap_or(source);
files.push(json!({
"ts": set_index,
@@ -657,7 +669,9 @@ fn plan(session: &mut Session, params: &Value) -> Result<Value> {
"bitDepth": output.bit_depth,
"dithering": output.dither,
"size": size,
"sourceSize": source_size,
"height": height,
"sourceSize": source.0,
"sourceHeight": source.1,
"warnings": output.warnings,
"layers": output.layers.iter().map(|layer| json!({ "map": layer.map, "name": layer.name })).collect::<Vec<_>>(),
}));
+2 -2
View File
@@ -19,9 +19,9 @@ pub fn specs() -> Vec<CommandSpec> {
)]
}
/// The sampling a reset Fill section has: a new fill's, with `current`'s symmetry (it belongs to the Symmetry section)
/// The sampling a reset Fill section has: a new fill's, with `current`'s symmetry (it belongs to the Symmetry section) and its alpha coverage (a flattened folder's shape)
pub fn reset_sampling(current: Sampling) -> Sampling {
Sampling { symmetry: current.symmetry, ..Sampling::default() }
Sampling { symmetry: current.symmetry, alpha_coverage: current.alpha_coverage, ..Sampling::default() }
}
/// The defaults of `current`'s projection kind: a new fill's projection of that kind, with the frame a placed planar or a warp projects from kept
+8 -1
View File
@@ -271,18 +271,25 @@ pub fn texture_set(session: &Session, index: usize) -> Value {
json!({
"index": index,
"name": texture_set.name,
"originalName": session.original_set_name(index),
"description": texture_set.description,
"resolution": texture_set.resolution,
"height": texture_set.height(),
"size": texture_set.size(),
"blockResolution": texture_set.block_resolution(),
"uvTiles": texture_set.uv_tiles,
"tiles": tiles,
"channels": texture_set.channels.iter().map(|(channel, format)| json!({ "channel": channel.id(), "format": format.label() })).collect::<Vec<_>>(),
"channels": texture_set.formats().iter().map(|(channel, format)| json!({ "channel": channel.id(), "format": format.label(), "shaded": channel.is_shaded() })).collect::<Vec<_>>(),
"layers": session.doc.project.walk(index).len(),
"parts": crate::set_cmds::parts(session, index),
"baked": crate::project_cmds::baked_json(session.doc.baked.get(&index)),
"outOfDate": out_of_date,
"autoRebake": texture_set.auto_rebake.map(texturecraft_core::BakedMap::id),
"visible": texture_set.visible,
"normalMixing": texture_set.normal_mixing.id(),
"aoMixing": texture_set.ao_mixing.id(),
"heightToNormal": texture_set.height_to_normal.id(),
"uvPadding": texture_set.uv_padding.id(),
"active": index == session.ts(),
})
}
+47
View File
@@ -87,6 +87,24 @@ pub fn specs() -> Vec<CommandSpec> {
always,
select
),
cmd!(
"layer.layersAt",
"Layers under the cursor",
[],
None,
"{x, y, viewport?: [w,h]} a point on the mesh — {layers: [{layer, name, channels}]}: the layers laying something down there in the shown channels, top first, each with the channels it changes there (R + click lists them)",
always,
layers_at
),
cmd!(
"layer.pickAt",
"Pick layer under the cursor",
[],
None,
"{x, y, viewport?: [w,h], layer?} a point on the mesh — selects the top layer laying something down there in the shown channels, or `layer`, refused when it lays nothing down there (R + click)",
always,
pick_at
),
cmd!("layer.rename", "Rename layer", [], None, "{layer?, name}", has_layer, rename),
cmd!(
"layer.visible",
@@ -282,6 +300,35 @@ fn new_folder(id: LayerId, name: String, channels: &[Channel]) -> Layer {
folder
}
fn pick_at(s: &mut Session, p: &Value) -> Result<Value> {
let (Some(x), Some(y)) = (f32p(p, "x"), f32p(p, "y")) else { return Err(bad("layer.pickAt", "`x` and `y` are required")) };
let viewport = crate::tool_cmds::viewport_of(s, p);
// An explicitly supplied layer must parse before falling back to the top layer
let wanted = match p.get("layer").filter(|layer| !layer.is_null()) {
Some(_) => Some(u64p(p, "layer").map(LayerId).ok_or_else(|| bad("layer.pickAt", "`layer` must be a layer id"))?),
None => None,
};
let id = s.pick_layer(texturecraft_geom::glam::Vec2::new(x, y), viewport, wanted)?;
Ok(json!({ "layer": id.0 }))
}
fn layers_at(s: &mut Session, p: &Value) -> Result<Value> {
let (Some(x), Some(y)) = (f32p(p, "x"), f32p(p, "y")) else { return Err(bad("layer.layersAt", "`x` and `y` are required")) };
let viewport = crate::tool_cmds::viewport_of(s, p);
let (_, layers) = s.layers_under(texturecraft_geom::glam::Vec2::new(x, y), viewport)?;
let layers: Vec<Value> = layers
.iter()
.map(|(id, channels)| {
let name = s.doc.project.layers.get(id).map(|layer| layer.name.as_str()).unwrap_or_default();
json!({ "layer": id.0, "name": name, "channels": channels.iter().map(|channel| channel.id()).collect::<Vec<_>>() })
})
.collect();
Ok(json!({ "layers": layers }))
}
fn select(s: &mut Session, p: &Value) -> Result<Value> {
if boolp(p, "all") == Some(true) {
return crate::layer_selection::select_all(s);
+212 -19
View File
@@ -1,9 +1,16 @@
//! Layer clipboard (copy, cut, paste across texture sets), flatten, and resampling of painted
//! pixels when a texture set changes size.
use std::collections::BTreeSet;
use serde_json::{Value, json};
use texturecraft_core::{Channel, ChannelKind, LayerId, LayerKind};
use texturecraft_texel::TileImage;
use texturecraft_compose::FlattenFolderError;
use texturecraft_compose::eval::FlatTile;
use texturecraft_core::{
Channel, ChannelKind, ContentsOffset, Effect, EffectKind, Fill, Filtering, Layer, LayerId, LayerKind, Mask, MaskBackground, Project, Sampling, Source,
};
use texturecraft_formats::DecodedImage;
use texturecraft_texel::{TILE, TileImage, from_u16, from_u16_signed, linear_to_srgb, to_u16};
use crate::commands::{CommandSpec, boolp, has_layer, layer_param};
use crate::session::{Document, StackTarget};
@@ -19,7 +26,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Flatten layer",
["Layers"],
Some("Ctrl+M"),
"{layer?} — a fill or masked paint layer becomes a plain paint layer",
"{layer?} — a fill or masked paint layer becomes a plain paint layer; a folder becomes a new fill layer above it holding one image per channel (its mask baked into a painted mask) and is hidden",
has_layer,
flatten
),
@@ -197,38 +204,224 @@ fn flatten(s: &mut Session, p: &Value) -> Result<Value> {
let id = layer_param(s, "layer.flatten", p)?;
let (ts, _, _) = s.doc.project.locate(id).ok_or_else(|| EngineError::Other("layer not in a stack".into()))?;
let layer = s.doc.project.layer(id)?.clone();
// An instance flattens what it draws into a plain layer of its own.
// An instance flattens what it draws into a plain layer of its own
let content = s.doc.project.content_layer(id).cloned().ok_or_else(|| EngineError::Other("the instance's source is missing".into()))?;
if content.is_group() {
return Err(EngineError::Other("flattening a folder is not supported yet; flatten its layers".into()));
return flatten_folder(s, ts, &layer, &content);
}
s.update();
let size = s.caches.get(ts).ok_or_else(|| EngineError::Other("texture set not ready".into()))?.size;
let flat = s.flatten(ts, id).ok_or_else(|| EngineError::Other("nothing to flatten".into()))?;
s.edit("Flatten layer", |s| {
for c in Channel::ALL {
s.doc.pixels.layers.remove(&(id, c));
for channel in Channel::ALL {
s.doc.pixels.layers.remove(&(id, channel));
}
let effects: Vec<LayerId> = layer.mask.iter().flat_map(|m| m.effects.iter()).chain(layer.content_effects.iter()).map(|e| e.id).collect();
s.doc.pixels.masks.retain(|e, _| !effects.contains(e));
s.doc.pixels.layers.retain(|(e, _), _| !effects.contains(e));
for (c, (tx, ty), data) in flat {
let img = s.doc.pixels.layer_mut(id, c, size);
img.set_tile(tx, ty, Some(std::sync::Arc::new(data)));
let effects: Vec<LayerId> =
layer.mask.iter().flat_map(|mask| mask.effects.iter()).chain(layer.content_effects.iter()).map(|effect| effect.id).collect();
s.doc.pixels.masks.retain(|effect, _| !effects.contains(effect));
s.doc.pixels.layers.retain(|(effect, _), _| !effects.contains(effect));
for (channel, (tx, ty), data) in flat {
let image = s.doc.pixels.layer_mut(id, channel, size);
image.set_tile(tx, ty, Some(std::sync::Arc::new(data)));
}
let channels = s.doc.project.texture_set(ts)?.channel_list();
let l = s.doc.project.layer_mut(id)?;
l.kind = LayerKind::Paint;
l.mask = None;
l.content_effects.clear();
l.height_mask = Default::default();
l.channels = content.channels.into_iter().filter(|(c, _)| channels.contains(c)).collect();
let flattened = s.doc.project.layer_mut(id)?;
flattened.kind = LayerKind::Paint;
flattened.mask = None;
flattened.content_effects.clear();
flattened.height_mask = Default::default();
flattened.channels = content.channels.into_iter().filter(|(channel, _)| channels.contains(channel)).collect();
s.target = StackTarget::Content;
Ok(())
})?;
Ok(json!({ "layer": id.0 }))
}
/// Flatten `folder` (drawing `drawn`: itself, or an instance's source) of texture set `ts` into a new fill layer above it, reading one image per channel it lays down, with its mask baked into a painted mask; the folder is hidden and kept, and the new layer shows only if the folder did
fn flatten_folder(s: &mut Session, ts: usize, folder: &Layer, drawn: &Layer) -> Result<Value> {
// A single fill image would repeat on each UV tile
if s.doc.project.texture_set(ts)?.uv_tiles.len() > 1 {
return Err(EngineError::Other("flattening a folder of a texture set with several UV tiles is not supported yet".into()));
}
// Protect visible readers that would lose an anchor
if folder.visible && anchor_read_outside(&s.doc.project, folder.id) {
return Err(EngineError::Other("a layer outside the folder reads one of its anchor points: flattening would change it".into()));
}
s.update();
let size = s.caches.get(ts).ok_or_else(|| EngineError::Other("texture set not ready".into()))?.size;
let tiles: Vec<(u32, u32)> = s.caches.get(ts).map(|cache| cache.covered_tiles.iter().copied().collect()).unwrap_or_default();
let flattened = s
.with_inputs(ts, |inputs| Some(texturecraft_compose::flatten_folder(inputs, folder.id, &tiles)))
.ok_or_else(|| EngineError::Other("texture set not ready".into()))?;
let (content, mask) = flattened.map_err(|error| {
EngineError::Other(match error {
FlattenFolderError::NotAFolder => "nothing to flatten".into(),
FlattenFolderError::ValueOutOfRange => "the folder's layers go past what an image holds: flattening would clip them".into(),
})
})?;
let images = channel_images(content, size)?;
if images.is_empty() {
return Err(EngineError::Other("the folder shows nothing to flatten".into()));
}
let (flat, decoded_images) = s.edit("Flatten folder", |s| {
let mut decoded_images = Vec::with_capacity(images.len());
let mut fill = Fill { sampling: Sampling { filtering: Filtering::Nearest, alpha_coverage: true, ..Sampling::default() }, ..Fill::default() };
for (channel, png, image) in images {
let file_name = format!("{} flattened {}.png", folder.name, channel.id());
let name = s.add_image_resource_bytes(&file_name, png)?;
fill.sources.insert(channel, Source::image(name.clone()));
decoded_images.push((name, crate::resource_cmds::decoded(image)));
}
// Cancel ancestor transforms so baked texels stay in place
let around = s.doc.project.contents_around(folder.id);
fill.projection = ContentsOffset::new(around.scale.recip(), -around.rotation).apply(&fill.projection);
// Enabling a channel without an image would cover the stack with its default
let channels: Vec<Channel> = fill.sources.keys().copied().collect();
let mut layer = Layer::new(s.doc.project.alloc_id(), format!("{} (flattened)", folder.name), LayerKind::Fill(fill), &channels);
layer.visible = folder.visible;
for (channel, blend) in &mut layer.channels {
blend.opacity = drawn.blend(*channel).map_or(1.0, |folder_blend| folder_blend.opacity);
}
if !mask.is_empty() {
let paint = s.doc.project.alloc_id();
let mut baked = Mask::new(MaskBackground::Black);
baked.effects.push(Effect::new(paint, EffectKind::Paint));
layer.mask = Some(baked);
let image = s.doc.pixels.mask_mut(paint, size);
for ((tx, ty), data) in mask {
image.set_tile(tx, ty, Some(std::sync::Arc::new(data)));
}
}
let flat = s.doc.project.insert_layer(ts, layer, Some(folder.id), false)?;
s.doc.project.layer_mut(folder.id)?.visible = false;
s.select_one(ts, flat);
s.target = StackTarget::Content;
Ok((flat, decoded_images))
})?;
// Cache decoded images only after the undoable document edit succeeds
s.images.extend(decoded_images);
Ok(json!({ "layer": flat.0 }))
}
/// Whether a layer staying on screen reads an anchor point that hiding folder `folder` (or folder instance) takes away
fn anchor_read_outside(project: &Project, folder: LayerId) -> bool {
// Hiding the folder does not hide an instance's source row elsewhere
let mut hidden = BTreeSet::new();
let mut unvisited = vec![folder];
while let Some(id) = unvisited.pop() {
if hidden.insert(id) {
unvisited.extend(project.layers.get(&id).into_iter().flat_map(|layer| layer.children().iter().copied()));
}
}
// Track masks and content still drawn through outside instances
let drawn_again: Vec<_> = project
.locate(folder)
.into_iter()
.flat_map(|(ts, _, _)| project.walk(ts))
.filter(|(id, _)| !hidden.contains(id) && project.layers.get(id).is_some_and(|layer| layer.instance_source().is_some()))
.map(|(id, _)| mask_and_content_owners(project, id))
.collect();
let anchors = project.render_tree(&[folder]).into_iter().filter_map(|id| project.layers.get(&id)).flat_map(|layer| {
let effects = layer.mask.iter().flat_map(|mask| mask.effects.iter()).chain(layer.content_effects.iter());
effects.filter(|effect| matches!(effect.kind, EffectKind::Anchor)).map(|effect| (layer.id, effect.id))
});
anchors.into_iter().any(|(owner, anchor)| {
project.anchor_readers(anchor).into_iter().any(|(reader, reading)| {
!hidden.contains(&reader) || drawn_again.iter().any(|drawn| draws(project, drawn, reader, reading) && !draws(project, drawn, owner, Some(anchor)))
})
})
}
/// The layers whose masks and the layers whose content drawing layer `root` reads: an instance's own mask stands in for its source's
fn mask_and_content_owners(project: &Project, root: LayerId) -> (BTreeSet<LayerId>, BTreeSet<LayerId>) {
let (mut masks, mut contents, mut visited) = (BTreeSet::new(), BTreeSet::new(), BTreeSet::new());
let mut unvisited = vec![root];
while let Some(id) = unvisited.pop() {
if !visited.insert(id) {
continue;
}
masks.insert(project.mask_owner(id));
if let Some(content) = project.content_layer(id) {
contents.insert(content.id);
unvisited.extend(content.children().iter().copied());
}
}
(masks, contents)
}
/// Whether a draw reading `owners` (see [`mask_and_content_owners`]) includes `effect` of layer `layer`, or the layer's own fill when None
fn draws(project: &Project, (masks, contents): &(BTreeSet<LayerId>, BTreeSet<LayerId>), layer: LayerId, effect: Option<LayerId>) -> bool {
let mask = project.layers.get(&layer).and_then(|layer| layer.mask.as_ref());
let in_mask = mask.is_some_and(|mask| mask.effects.iter().any(|other| Some(other.id) == effect));
if in_mask { masks.contains(&layer) } else { contents.contains(&layer) }
}
/// One flattened tile of a channel: (tile, value + coverage data)
type ChannelTile = ((u32, u32), Vec<u16>);
/// Flattened tiles as one 16-bit RGBA PNG per channel and its decoded pixels (straight values as a fill reads them, coverage in the alpha), in channel order
fn channel_images(tiles: Vec<FlatTile>, size: (u32, u32)) -> Result<Vec<(Channel, Vec<u8>, DecodedImage)>> {
let (width, height) = size;
let mut by_channel: std::collections::BTreeMap<Channel, Vec<ChannelTile>> = Default::default();
for (channel, tile, data) in tiles {
by_channel.entry(channel).or_default().push((tile, data));
}
by_channel
.into_iter()
.map(|(channel, tiles)| {
let comps = channel.components();
let mut rgba = vec![0u16; width as usize * height as usize * 4];
for ((tx, ty), data) in tiles {
for (offset, texel) in data.chunks_exact(comps + 1).enumerate() {
let (x, y) = (tx * TILE + offset as u32 % TILE, ty * TILE + offset as u32 / TILE);
let coverage = texel.get(comps).copied().map_or(0.0, from_u16);
if x >= width || y >= height || coverage <= 0.0 {
continue;
}
let straight = |i: usize| {
let premultiplied = texel.get(i).copied().unwrap_or(0);
let value = if channel.kind() == ChannelKind::Signed { from_u16_signed(premultiplied) } else { from_u16(premultiplied) };
value / coverage
};
let rgb = match channel.kind() {
ChannelKind::Color => [0, 1, 2].map(|i| linear_to_srgb(straight(i))),
ChannelKind::NormalMap => [0, 1, 2].map(straight),
ChannelKind::Scalar => [straight(0); 3],
// A fill reads a signed channel's image gray as -1..1
ChannelKind::Signed => [(straight(0) + 1.0) * 0.5; 3],
};
let start = (y as usize * width as usize + x as usize) * 4;
if let Some(pixel) = rgba.get_mut(start..start + 4) {
pixel.copy_from_slice(&[to_u16(rgb[0]), to_u16(rgb[1]), to_u16(rgb[2]), to_u16(coverage)]);
}
}
}
let (png, image) = texturecraft_formats::rgba16_resource(width, height, &rgba)
.map_err(|error| EngineError::Other(format!("flattened {}: {error}", channel.id())))?;
Ok((channel, png, image))
})
.collect()
}
impl Session {
/// Layer `id` of texture set `ts` alone (content times mask) as premultiplied tiles per
/// channel over the set's covered tiles. None for folders or a set not ready.
+91
View File
@@ -0,0 +1,91 @@
//! Picking a layer on the mesh (R + click in the viewport, `layer.layersAt` and `layer.pickAt`): the layers laying something down where the mesh is clicked, and selecting one of them
use texturecraft_core::{Channel, LayerId, LayerKind};
use texturecraft_geom::glam::Vec2;
use texturecraft_paint::{PickCtx, stroke::pick_filtered};
use crate::session::ViewMode;
use crate::{EngineError, Result, Session, StackTarget};
/// A texture set and the layers laying something down at one of its texels, top first, each with the channels it changes there
pub type LayersUnder = (usize, Vec<(LayerId, Vec<Channel>)>);
impl Session {
/// The texture set and texel of the mesh under `screen`, None off the mesh
pub fn texel_under(&self, screen: Vec2, viewport: Vec2) -> Option<(usize, (u32, u32))> {
let visible_set = |material| {
let ts = self.texture_set_of_material(material)?;
self.doc.project.texture_sets.get(ts).filter(|set| set.visible).map(|_| ts)
};
let nearest = self.pick(screen, viewport)?;
let (hit, ts) = match visible_set(nearest.material) {
Some(ts) => (nearest, ts),
None => {
// Only search past the first hit when its material is hidden
let ctx = PickCtx { mesh: &self.mesh, bvh: &self.bvh, camera: &self.camera, viewport };
let hit = pick_filtered(&ctx, screen, &|triangle| visible_set(self.mesh.material_of(triangle as usize).unwrap_or(0)).is_some())?;
(hit, visible_set(hit.material)?)
}
};
let cache = self.caches.get(ts)?;
let (width, height) = (cache.size.0 as f32, cache.size.1 as f32);
let texel = ((hit.uv.x * width).clamp(0.0, width - 1.0) as u32, (hit.uv.y * height).clamp(0.0, height - 1.0) as u32);
Some((ts, texel))
}
/// The layers laying something down at `texel` of texture set `ts` in the shown channels (every channel outside a single-channel view), top first, each with the channels it changes there
pub fn layers_at_texel(&self, ts: usize, texel: (u32, u32)) -> Vec<(LayerId, Vec<Channel>)> {
let shown = match self.view {
ViewMode::Channel(channel) => vec![channel],
_ => self.doc.project.texture_set(ts).map(|set| set.channel_list()).unwrap_or_default(),
};
// Match the visibility of the active solo view
let solo_view = self.solo_view();
self.with_inputs(ts, |inputs| {
let inputs =
texturecraft_compose::Inputs { project: solo_view.as_ref().unwrap_or(inputs.project), block_scales: inputs.block_scales.clone(), ..*inputs };
Some(texturecraft_compose::layers_at(&inputs, &self.projector_depth_cache, texel, &shown))
})
.unwrap_or_default()
}
/// The texture set under `screen` and the layers laying something down there (see [`Session::layers_at_texel`])
pub fn layers_under(&self, screen: Vec2, viewport: Vec2) -> Result<LayersUnder> {
let (ts, texel) = self.texel_under(screen, viewport).ok_or_else(|| EngineError::Other("nothing under the cursor".into()))?;
Ok((ts, self.layers_at_texel(ts, texel)))
}
/// Select `wanted` when it lays something down under `screen`, else the top layer there
pub fn pick_layer(&mut self, screen: Vec2, viewport: Vec2, wanted: Option<LayerId>) -> Result<LayerId> {
let (ts, layers) = self.layers_under(screen, viewport)?;
let picked = match wanted {
Some(wanted) => layers.iter().find(|(id, _)| *id == wanted).ok_or_else(|| EngineError::Other("that layer lays nothing down here".into()))?,
None => layers.first().ok_or_else(|| EngineError::Other("no visible layer lays anything down here".into()))?,
};
let id = picked.0;
// Finish the current set's path and discard its clone source before switching
if ts != self.ts() {
self.finish_path()?;
self.tool.clone_source = None;
}
self.active_set = ts;
self.select_one(ts, id);
self.open_folders_holding(id);
self.target = StackTarget::Content;
self.revision = self.revision.wrapping_add(1);
Ok(id)
}
/// Expand every collapsed folder holding `id`, so the Layers panel shows its row
fn open_folders_holding(&mut self, id: LayerId) {
let mut child = id;
while let Some((_, Some(folder), _)) = self.doc.project.locate(child) {
if let Some(LayerKind::Group { collapsed, .. }) = self.doc.project.layers.get_mut(&folder).map(|layer| &mut layer.kind) {
*collapsed = false;
}
child = folder;
}
}
}
+3
View File
@@ -22,6 +22,7 @@ pub mod decal_cmds;
pub mod distance_params;
pub mod effect_blending_cmds;
pub mod effect_clipboard;
mod effect_step;
pub mod file_cmds;
pub mod fill_alpha;
pub mod fill_hit_test;
@@ -39,6 +40,7 @@ pub mod inspect;
pub mod instance_cmds;
pub mod layer_cmds;
pub mod layer_ops;
mod layer_pick;
pub mod layer_selection;
pub mod link_cmds;
pub mod log;
@@ -72,6 +74,7 @@ mod polygon_fill_mirror;
mod stencil_look;
// Mesh reimport reads files on native targets only
mod display_padding;
mod display_seam_geometry;
#[cfg(not(target_arch = "wasm32"))]
mod preserve;
pub mod preset_cmds;
+83 -4
View File
@@ -313,7 +313,8 @@ fn save_source(_: &mut Session, _: &Value) -> Result<Value> {
Err(EngineError::Other("file paths are not available in the browser".into()))
}
/// A MaterialCraft executable: `$<env>`, else next to this program, else `name` on `PATH`.
/// A MaterialCraft executable: `$<env>`, else next to this program, else in the sibling
/// `MaterialCraft` folder (the launcher's layout), else `name` on `PATH`.
#[cfg(not(target_arch = "wasm32"))]
pub fn materialcraft_tool(name: &str, env: &str) -> std::path::PathBuf {
if let Some(p) = std::env::var_os(env).filter(|p| !p.is_empty()) {
@@ -321,7 +322,18 @@ pub fn materialcraft_tool(name: &str, env: &str) -> std::path::PathBuf {
}
let exe = format!("{name}{}", std::env::consts::EXE_SUFFIX);
std::env::current_exe().ok().and_then(|e| Some(e.parent()?.join(&exe))).filter(|p| p.is_file()).unwrap_or_else(|| exe.into())
let app_dir = std::env::current_exe().ok().and_then(|e| e.parent().map(std::path::Path::to_path_buf));
app_dir.and_then(|d| find_installed_tool(&d, &exe)).unwrap_or_else(|| exe.into())
}
/// `exe` in `app_dir` (next to this program), else in the sibling `MaterialCraft` folder beside `app_dir`
/// (`<root>/TextureCraft` and `<root>/MaterialCraft`, as the ArtCraft Launcher installs them). `None` if neither has it.
/// Versioned `<app>/<version>/` layouts and macOS `.app` bundles are not searched.
#[cfg(not(target_arch = "wasm32"))]
fn find_installed_tool(app_dir: &std::path::Path, exe: &str) -> Option<std::path::PathBuf> {
let beside = app_dir.join(exe);
let sibling = app_dir.parent().map(|root| root.join("MaterialCraft").join(exe));
std::iter::once(beside).chain(sibling).find(|p| p.is_file())
}
/// A command for a MaterialCraft executable that opens no console window.
@@ -335,12 +347,15 @@ fn quiet(program: &std::path::Path) -> std::process::Command {
}
/// Open `package` (a published material or authoring package) in the MaterialCraft app (`$MATERIALCRAFT`, next to this
/// program, or on `PATH`).
/// program, in the sibling `MaterialCraft` folder, or on `PATH`).
#[cfg(not(target_arch = "wasm32"))]
pub fn open_in_materialcraft(package: &std::path::Path) -> Result<()> {
let app = materialcraft_tool("materialcraft", "MATERIALCRAFT");
quiet(&app).arg(package).spawn().map(drop).map_err(|e| {
EngineError::Other(format!("MaterialCraft ({}) did not start: {e}. Install MaterialCraft next to TextureCraft or set MATERIALCRAFT", app.display()))
EngineError::Other(format!(
"MaterialCraft ({}) did not start: {e}. Install MaterialCraft next to TextureCraft or in a sibling MaterialCraft folder, or set MATERIALCRAFT",
app.display()
))
})
}
@@ -775,6 +790,70 @@ mod tests {
assert!(typed(&p, &json!("#ff8000")).is_some());
}
#[cfg(not(target_arch = "wasm32"))]
fn touch(dir: &std::path::Path, exe: &str) -> std::path::PathBuf {
std::fs::create_dir_all(dir).unwrap();
let p = dir.join(exe);
std::fs::write(&p, b"").unwrap();
p
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn launcher_layout_finds_the_sibling_materialcraft_folder() {
let root = tempfile::tempdir().unwrap();
let app = root.path().join("TextureCraft");
std::fs::create_dir_all(&app).unwrap();
let tool = touch(&root.path().join("MaterialCraft"), "materialcraft-cli");
assert_eq!(super::find_installed_tool(&app, "materialcraft-cli"), Some(tool));
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_tool_beside_the_program_wins_over_the_sibling_folder() {
let root = tempfile::tempdir().unwrap();
let app = root.path().join("TextureCraft");
let beside = touch(&app, "materialcraft-cli");
touch(&root.path().join("MaterialCraft"), "materialcraft-cli");
assert_eq!(super::find_installed_tool(&app, "materialcraft-cli"), Some(beside));
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_missing_tool_is_none_so_the_caller_falls_back_to_path() {
let root = tempfile::tempdir().unwrap();
let app = root.path().join("TextureCraft");
std::fs::create_dir_all(root.path().join("MaterialCraft")).unwrap();
assert_eq!(super::find_installed_tool(&app, "materialcraft-cli"), None);
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_folder_named_like_the_tool_is_not_the_tool() {
let root = tempfile::tempdir().unwrap();
let app = root.path().join("TextureCraft");
std::fs::create_dir_all(app.join("materialcraft-cli")).unwrap();
std::fs::create_dir_all(root.path().join("MaterialCraft").join("materialcraft-cli")).unwrap();
assert_eq!(super::find_installed_tool(&app, "materialcraft-cli"), None);
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn an_app_folder_with_no_parent_does_not_panic() {
// The root (or an empty path) has no parent: only the beside-the-program step can apply.
assert_eq!(super::find_installed_tool(std::path::Path::new(""), "no-such-materialcraft-tool"), None);
let root = std::env::temp_dir().ancestors().last().map(std::path::Path::to_path_buf).unwrap_or_default();
assert_eq!(super::find_installed_tool(&root, "no-such-materialcraft-tool"), None);
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_missing_app_folder_is_none() {
let root = tempfile::tempdir().unwrap();
let gone = root.path().join("nowhere").join("TextureCraft");
assert_eq!(super::find_installed_tool(&gone, "materialcraft-cli"), None);
}
#[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()));
+1 -1
View File
@@ -120,7 +120,7 @@ fn run_bounded(command: &std::process::Command, stdout: &Path, stderr: &Path, re
.stdout(std::fs::File::create(stdout).map_err(io)?)
.stderr(std::fs::File::create(stderr).map_err(io)?)
.spawn()
.map_err(|error| io(format!("could not start the MaterialCraft cook: {error}. Install MaterialCraft or set MATERIALCRAFT_CLI")))?;
.map_err(|error| io(format!("could not start the MaterialCraft cook: {error}. Install MaterialCraft next to TextureCraft or in a sibling MaterialCraft folder, or set MATERIALCRAFT_CLI")))?;
loop {
if canceled.load(Ordering::Relaxed) {
+51
View File
@@ -10,6 +10,7 @@ use texturecraft_core::{
use crate::anchored_micro_edit::AnchoredMicroEdit;
use crate::commands::{CommandSpec, always, bad, blend_param, boolp, channel_param, color_param, f32p, has_layer, layer_param, strp, u64p};
use crate::distance_params::distance_from;
use crate::effect_step::EffectStep;
use crate::generator_input::GeneratorInput;
use crate::layer_cmds::{projection_from, projection_from_fields};
use crate::mask_owner::MaskOwner;
@@ -118,6 +119,24 @@ pub fn specs() -> Vec<CommandSpec> {
duplicate_effect
),
cmd!("effect.move", "Move effect", [], None, "{effect, index: position in its stack, 0 = bottom (applied first)}", has_layer, move_effect),
cmd!(
"effect.moveUp",
"Move effect up",
["Layers"],
Some("Alt+Up"),
"{effect?: the selected effect} — one place up its stack (applied later)",
has_layer,
|s, p| step_effect(s, p, EffectStep::Up)
),
cmd!(
"effect.moveDown",
"Move effect down",
["Layers"],
Some("Alt+Down"),
"{effect?: the selected effect} — one place down its stack (applied earlier)",
has_layer,
|s, p| step_effect(s, p, EffectStep::Down)
),
cmd!(
"effect.histogram",
"Effect input histogram",
@@ -1019,6 +1038,9 @@ fn histogram(s: &mut Session, p: &Value) -> Result<Value> {
Ok(out)
}
/// The name every generator effect got before they were named after their kind
const FORMER_GENERATOR_NAME: &str = "Generator";
/// Edit visibility, blending, name, effect parameters, or a filter's type
pub(crate) fn set(session: &mut Session, params: &Value) -> Result<Value> {
const CMD: &str = "effect.set";
@@ -1100,6 +1122,13 @@ pub(crate) fn set(session: &mut Session, params: &Value) -> Result<Value> {
session.edit("Edit effect", |session| {
let edited = session.doc.project.effect_mut(effect).ok_or_else(|| bad(CMD, format!("no effect {}", effect.0)))?;
if let Some(generator) = swapped_generator {
// Preserve custom names when swapping generator kinds
if let EffectKind::Generator(old) = &edited.kind
&& (edited.name == old.kind.label() || edited.name == FORMER_GENERATOR_NAME)
{
edited.name = generator.kind.label().to_string();
}
edited.kind = EffectKind::Generator(generator);
}
if let Some((kind, label)) = swapped {
@@ -1389,6 +1418,28 @@ fn move_effect(s: &mut Session, p: &Value) -> Result<Value> {
Ok(Value::Null)
}
/// Move an effect one place in its stack (one undo step; nothing at its end)
fn step_effect(s: &mut Session, p: &Value, step: EffectStep) -> Result<Value> {
let cmd = match step {
EffectStep::Up => "effect.moveUp",
EffectStep::Down => "effect.moveDown",
};
if p.get("effect").is_some_and(|effect| !effect.is_null()) && u64p(p, "effect").is_none() {
return Err(bad(cmd, "`effect` must be an effect id"));
}
let effect = effect_id(s, p, cmd)?;
let (list, index) = stack_of(&mut s.doc.project, effect).ok_or_else(|| bad(cmd, format!("no effect {}", effect.0)))?;
let to = match step {
EffectStep::Up if index + 1 < list.len() => index + 1,
EffectStep::Down if index > 0 => index - 1,
_ => return Ok(json!({ "moved": false })),
};
move_effect(s, &json!({ "effect": effect.0, "index": to }))?;
Ok(json!({ "moved": true }))
}
fn remove_effect(s: &mut Session, p: &Value) -> Result<Value> {
let eid = effect_id(s, p, "effect.remove")?;
s.edit("Remove effect", |s| {
+9 -7
View File
@@ -42,20 +42,22 @@ impl Session {
let (width, height, values) = atlas;
let set = self.doc.project.texture_set(ts).map_err(|e| EngineError::Other(e.to_string()))?;
let Some(grid) = set.tile_grid().filter(|_| per_tile) else { return Ok(vec![MaskBitmap { tile: None, width, height, values }]) };
let block = set.block_resolution();
let (block_width, block_height) = set.block_size();
set.uv_tiles
.iter()
.map(|&tile| {
let (block_x, block_y) = grid.block(tile).ok_or_else(|| EngineError::Other(format!("UV tile {tile} is not in the set's grid")))?;
// A tile smaller than its block fills the block's top-left corner
let side = ((block as f32 * set.tile_scale(tile)).round() as u32).clamp(1, block);
let mut tile_values = Vec::with_capacity(side as usize * side as usize);
for row in 0..side {
let start = ((block_y * block + row) as usize) * width as usize + (block_x * block) as usize;
tile_values.extend_from_slice(values.get(start..start + side as usize).unwrap_or(&[]));
let scale = set.tile_scale(tile);
let tile_width = ((block_width as f32 * scale).round() as u32).clamp(1, block_width);
let tile_height = ((block_height as f32 * scale).round() as u32).clamp(1, block_height);
let mut tile_values = Vec::with_capacity(tile_width as usize * tile_height as usize);
for row in 0..tile_height {
let start = ((block_y * block_height + row) as usize) * width as usize + (block_x * block_width) as usize;
tile_values.extend_from_slice(values.get(start..start + tile_width as usize).unwrap_or(&[]));
}
Ok(MaskBitmap { tile: Some(tile), width: side, height: side, values: tile_values })
Ok(MaskBitmap { tile: Some(tile), width: tile_width, height: tile_height, values: tile_values })
})
.collect()
}
+2
View File
@@ -74,9 +74,11 @@ pub(crate) fn images_used(project: &Project, id: LayerId, out: &mut Vec<String>,
pub(crate) fn one_set_document(src_set: &TextureSet, name: &str) -> Document {
let mut project = Project::new(name, "builtin:none");
let mut set = TextureSet::new(name, 0, src_set.resolution);
set.resolution_height = src_set.resolution_height;
set.uv_tiles = src_set.uv_tiles.clone();
set.tile_resolutions = src_set.tile_resolutions.clone();
set.channels = src_set.channels.clone();
set.format_precision = src_set.format_precision;
project.texture_sets.push(set);
Document {
+12 -9
View File
@@ -2,7 +2,7 @@
use std::sync::Arc;
use texturecraft_compose::{BakedMaps, Composite, DisplayKind, Inputs, all_tiles, composite_tiles, kinds_for, tile_bytes};
use texturecraft_core::Channel;
use texturecraft_core::{AoMixing, Channel};
use texturecraft_geom::UvGBuffer;
use texturecraft_texel::TILE;
@@ -28,8 +28,8 @@ impl Session {
let (width, height) = ((w / step).max(1), (h / step).max(1));
let cache = self.caches.get(ts)?;
let source = &cache.gbuf;
// Sample the existing UV raster. Rasterizing a many-triangle mesh again can take
// longer than evaluating the overview itself.
// Reuse the full UV raster to avoid traversing the mesh again for an overview
let positions = (0..height).flat_map(|y| {
(0..width).map(move |x| {
let sx = ((x as u64 * 2 + 1) * w as u64 / (2 * width as u64)) as usize;
@@ -60,28 +60,31 @@ impl Session {
let mut composite = Composite { block_scales: scales, ..Composite::with_size(&channels, width, height) };
let tiles = all_tiles(width, height);
composite_tiles(&inputs, &mut composite, &tiles);
let padding =
crate::session::DisplayPadding::new(&gbuf, gbuf.tri.iter().any(|&t| t != texturecraft_geom::NO_TRI), (set.block_resolution() / step).max(1));
let (block_width, block_height) = set.block_size();
let block = ((block_width / step).max(1), (block_height / step).max(1));
let has_coverage = gbuf.tri.iter().any(|&triangle| triangle != texturecraft_geom::NO_TRI);
let padding = crate::session::DisplayPadding::new(&self.mesh, set, &gbuf, has_coverage, block);
padding.apply_to_tiles(&mut composite, &tiles);
let maps = pack_overview(&composite, baked, &channels, &tiles);
let maps = pack_overview(&composite, baked, set.ao_mixing, &channels, &tiles);
Some(MaterialOverview { size: (width, height), maps })
}
}
fn pack_overview(composite: &Composite, baked: &BakedMaps, channels: &[Channel], tiles: &[(u32, u32)]) -> Vec<(DisplayKind, Vec<u8>)> {
fn pack_overview(composite: &Composite, baked: &BakedMaps, ao_mixing: AoMixing, channels: &[Channel], tiles: &[(u32, u32)]) -> Vec<(DisplayKind, Vec<u8>)> {
let (width, height) = (composite.resolution, composite.height);
kinds_for(channels)
.map(|kind| {
let stride = kind.bytes_per_texel();
let mut image = vec![0; width as usize * height as usize * stride];
for &(tx, ty) in tiles {
let data = tile_bytes(composite, baked, kind, tx, ty);
let data = tile_bytes(composite, baked, ao_mixing, kind, tx, ty);
let (left, top) = (tx * TILE, ty * TILE);
let row_bytes = (width - left).min(TILE) as usize * stride;
for (row, src) in data.chunks_exact(TILE as usize * stride).take((height - top) as usize).enumerate() {
let offset = ((top as usize + row) * width as usize + left as usize) * stride;
image[offset..offset + row_bytes].copy_from_slice(&src[..row_bytes]);
// A preview tile can span several mixed-resolution UDIM blocks.
// A preview tile can span several mixed-resolution UDIM blocks
if kind == DisplayKind::Extra {
for (x, px) in image[offset..offset + row_bytes].chunks_exact_mut(stride).enumerate() {
px[3] = (-32.0 * composite.block_scales.at(left + x as u32, top + row as u32).log2()).round().clamp(0.0, 255.0) as u8;
+4 -2
View File
@@ -990,7 +990,8 @@ mod tests {
#[test]
fn every_material_and_smart_mask_applies_on_the_sample() {
let mut s = crate::sample_session(256, 256).unwrap();
// A baseline no material matches, so every material must visibly change the composite.
// The magenta baseline differs visibly from every material preset
crate::execute(&mut s, "layer.add.fill", &serde_json::json!({"color": [1.0, 0.0, 1.0], "roughness": 0.123})).unwrap();
s.update();
let before = snapshot(&s, 0);
@@ -1004,7 +1005,8 @@ mod tests {
s.undo().unwrap();
}
assert!(apply(&mut s, "nope").is_err());
// Smart masks on the pedestal: it has edges and cavities (the ball is a plain sphere).
// The pedestal exposes edges and cavities for the smart mask generators
s.active_set = 1;
apply(&mut s, "gold_polished").unwrap();
let layer = s.selected_layer().unwrap();
+121 -38
View File
@@ -224,15 +224,17 @@ impl Session {
.collect()
}
/// Common setup of 3D and 2D strokes. `first_uv` is where the stroke starts on the mesh
/// (the Clone tool's destination anchor).
/// Common setup of 3D and 2D strokes, `first_uv` being where the stroke starts on the mesh (the Clone tool's destination anchor)
fn start_stroke(&mut self, viewport: Vec2, uv_mode: bool, first_uv: Option<Vec2>) -> Result<()> {
// Texture size a stroke paints at before the texture set has a cache
const FALLBACK_TEXTURE_SIZE: (u32, u32) = (1024, 1024);
self.refuse_while_baking()?;
let tool = self.tool.tool;
let erase = tool == Tool::Eraser;
let quick_mask = self.quick_mask.editing;
let ts = self.ts();
let size = self.caches.get(ts).map(|c| c.size).unwrap_or((1024, 1024));
let size = self.caches.get(ts).map_or(FALLBACK_TEXTURE_SIZE, |cache| cache.size);
let pickup = if quick_mask { None } else { self.pickup_mode(first_uv)? };
let composite_pickup = tool == Tool::Smudge || (tool == Tool::Clone && self.tool.clone_from == CloneFrom::Composite);
if pickup.is_some() && composite_pickup && !self.paints_mask() && self.solo.is_none() {
@@ -247,26 +249,30 @@ impl Session {
}
_ => None,
};
let before = self.doc.clone();
let target = if quick_mask {
None
} else {
match self.paint_target() {
Ok(t) => Some(t),
Err(e) => {
Ok(target) => Some(target),
Err(error) => {
self.doc = before;
return Err(e);
return Err(error);
}
}
};
let values = target.map(|t| self.stroke_values(t)).unwrap_or_default();
let values = target.map(|target| self.stroke_values(target)).unwrap_or_default();
// Clone and smudge on a mask read the mask as it was before the stroke
let mask_owner = match target {
Some(PaintTarget::Mask(effect)) if pickup.is_some() => self.doc.project.effect(effect).map(|(owner, _)| owner),
_ => None,
};
let stencil = if tool == Tool::Projection && !quick_mask { self.capture_stencil(viewport) } else { None };
// The 2D view doesn't show the stencil, so there it shapes only the Projection tool
let stencil = if !quick_mask && tool.uses_stencil() && (tool == Tool::Projection || !uv_mode) { self.capture_stencil(viewport) } else { None };
let problem = if !erase && values.is_empty() && matches!(target, Some(PaintTarget::Layer(_))) {
Some("no channel enabled to paint: enable channels in the tool's material")
} else if tool == Tool::Projection && !quick_mask && stencil.is_none() && !uv_mode {
@@ -274,9 +280,10 @@ impl Session {
} else {
None
};
if let Some(msg) = problem {
if let Some(message) = problem {
self.doc = before;
return Err(EngineError::Other(msg.into()));
return Err(EngineError::Other(message.into()));
}
let depth = (!uv_mode).then(|| self.eye_depth(viewport));
@@ -285,6 +292,7 @@ impl Session {
if !quick_mask {
canvas.limit = self.stroke_limit(ts, size);
}
if let Some((mode, offset)) = pickup
&& let Some(cache) = self.caches.get(ts)
{
@@ -292,7 +300,7 @@ impl Session {
PickupMode::Clone { .. } => {
PickupMode::Clone { offset: [(offset[0] * size.0 as f32).round() as i64, (offset[1] * size.1 as f32).round() as i64] }
}
m => m,
other_mode => other_mode,
};
let mut pickup = match (&layer_source, mask_owner) {
// On a mask the stroke reads the mask's own values
@@ -324,31 +332,38 @@ impl Session {
canvas.pickup = Some(pickup);
if tool == Tool::Clone
&& self.tool.clone_aligned
&& let Some(src) = self.tool.clone_source.as_mut()
&& let Some(clone_source) = self.tool.clone_source.as_mut()
{
src.offset.get_or_insert(offset);
clone_source.offset.get_or_insert(offset);
}
}
if canvas.pickup.is_none() && tool == Tool::Paint && matches!(target, Some(PaintTarget::Layer(_))) {
canvas.pickup = self.brush_pattern(&values);
}
let label = if quick_mask {
QUICK_MASK_STROKE_LABEL.to_string()
} else {
let on_mask = matches!(target, Some(PaintTarget::Mask(_)));
history_label(stroke_template(tool, on_mask), &self.stroke_layer_name())
};
let settings = &stroke.settings;
// A 3D view projection without a stencil was refused above; the 2D view paints without one. A path repaints its curve as a stroke
let gpu_tool = matches!(tool, Tool::Paint | Tool::Projection | Tool::Path) || erase;
// Resolved once: staging, both previews and the commit paint this gray
let mask_gray = self.mask_gray();
// Symmetry copies reach the device with the stamps (a 3D copy carries its source for visibility); an Eraser with particles stays on the CPU
let device = if gpu_tool
&& canvas.pickup.is_none()
&& !(erase && settings.particles.enabled)
&& settings.alpha_image.is_none()
&& settings.alpha_library.is_none()
&& stencil.as_ref().is_none_or(|stencil| stencil.colors)
&& let Some(backend) = &self.brush_device
&& let Some(cache) = self.caches.get(ts)
&& backend.surface.ptr_eq(&std::sync::Arc::downgrade(&cache.gbuf))
@@ -393,6 +408,7 @@ impl Session {
erase,
stencil,
before,
start_revision: self.revision,
label,
staging: Staging::default(),
device,
@@ -444,13 +460,14 @@ impl Session {
}
}
/// The stencil placed for the current camera and viewport.
/// The stencil placed for the current camera and viewport
fn capture_stencil(&self, viewport: Vec2) -> Option<texturecraft_compose::Stencil> {
let st = self.tool.stencil.as_ref()?;
let image = self.images.get(&st.image)?.clone();
let stencil_state = self.tool.stencil.as_ref()?;
let image = self.images.get(&stencil_state.image)?.clone();
let aspect = viewport.x.max(1.0) / viewport.y.max(1.0);
let (center, half, rotation) = st.placement(image.width as f32 / image.height.max(1) as f32, aspect);
Some(texturecraft_compose::Stencil { image, view_proj: self.camera.view_proj(aspect), center, half, rotation, tile: st.tile })
let (center, half, rotation) = stencil_state.placement(image.width as f32 / image.height.max(1) as f32, aspect);
let colors = self.tool.tool == Tool::Projection;
Some(texturecraft_compose::Stencil { image, view_proj: self.camera.view_proj(aspect), center, half, rotation, tile: stencil_state.tile, colors })
}
/// Painting is paused while a bake preview shows the baked maps instead of the material.
@@ -581,6 +598,7 @@ impl Session {
if stamps.is_empty() {
return hit;
}
let rctx = RasterCtx {
mesh: &self.mesh,
bvh: &self.bvh,
@@ -602,6 +620,7 @@ impl Session {
}
return hit;
}
Err(error) => {
st.device = None;
st.display_tiles.append(&mut st.canvas.dirty);
@@ -763,6 +782,7 @@ impl Session {
if stroke.device.is_some() {
return None;
}
let tiles_in_bounds;
let touched = if let Some((min, max)) = texel_bounds {
tiles_in_bounds = stroke
@@ -815,6 +835,7 @@ impl Session {
let device = self.take_device_stroke(None);
let brush_tile = self.tile_demand(None).brush;
let Some(mut stroke) = self.stroke.take() else { return Ok(()) };
let size = (stroke.canvas.alpha.width(), stroke.canvas.alpha.height());
if stroke.canvas.dirty.is_empty() {
// Nothing painted: drop any mask effect the stroke created
@@ -822,13 +843,24 @@ impl Session {
return Ok(());
}
if self.painting_paths {
self.path_tiles.extend(stroke.canvas.dirty.iter().copied());
}
let gbuf = self.caches.get(stroke.ts).map(|c| c.gbuf.clone());
if stroke.stencil.is_some() && !with_commit_source(&stroke, gbuf.as_deref(), &self.mesh, &stroke.canvas.dirty, None, stencil_allows_stroke) {
self.mark_painted(stroke.ts, stroke.target, stroke.canvas.dirty.iter().copied(), false);
self.discard_unused_stroke_mask(&stroke);
return Ok(());
}
let mesh = self.mesh.clone();
let mut staging = std::mem::take(&mut stroke.staging);
let Some(target) = stroke.target else {
with_commit_source(&stroke, gbuf.as_deref(), &mesh, &stroke.canvas.dirty, None, |src| self.commit_quick_mask(stroke.ts, size, src));
return Ok(());
};
let pixels = &mut self.doc.pixels;
let mut commit = |tiles: &BrushTiles, projection: Option<&ProjectedTiles>| {
with_commit_source(&stroke, gbuf.as_deref(), &mesh, tiles, projection, |src| match target {
@@ -860,10 +892,8 @@ impl Session {
commit(&stroke.canvas.dirty, None);
}
let fed_before = self.fed_revisions(&stroke);
self.undo.push((stroke.label.clone(), stroke.before));
if self.undo.len() > crate::session::MAX_HISTORY {
self.undo.remove(0);
}
self.add_step(stroke.label, stroke.before);
self.redo.clear();
self.mark_modified();
@@ -888,6 +918,32 @@ impl Session {
Ok(())
}
fn discard_unused_stroke_mask(&mut self, stroke: &ActiveStroke) {
// An intervening edit may already have recorded the mask effect
if self.revision != stroke.start_revision {
return;
}
self.doc.project.next_id = stroke.before.project.next_id;
if let Some(PaintTarget::Mask(effect)) = stroke.target
&& let Some((owner, _)) = self.doc.project.effect(effect)
&& let Some(previous_layer) = stroke.before.project.layers.get(&owner)
&& !previous_layer.mask.iter().flat_map(|mask| &mask.effects).any(|previous| previous.id == effect)
&& let Some(layer) = self.doc.project.layers.get_mut(&owner)
{
layer.mask = previous_layer.mask.clone();
// Removing a new mask background can change texels outside the dabs
if previous_layer.mask.is_none() {
for texture_set in self.doc.project.sets_drawing(owner) {
if let Some(cache) = self.caches.get_mut(texture_set) {
cache.invalidate_all();
}
}
}
}
}
/// Abandon the active stroke (Esc).
pub fn cancel_stroke(&mut self) {
if let Some(st) = self.stroke.take() {
@@ -897,7 +953,8 @@ impl Session {
self.quick_mask.revision = self.quick_mask.revision.wrapping_add(1);
}
self.doc = st.before;
// A paint effect created by the stroke can get the same ID on a different owner.
// A paint effect created by the stroke can get the same ID on a different owner
for cache in &mut self.caches {
cache.invalidate_paint_margin();
}
@@ -951,6 +1008,9 @@ impl Session {
/// Commit a one-shot fill with the tool's material (one undo step), or into the quick mask.
pub(crate) fn commit_fill(&mut self, label: &str, ts: usize, canvas: &StrokeCanvas, gray: &MaskGray) -> Result<()> {
if self.painting_paths {
self.path_tiles.extend(canvas.dirty.iter().copied());
}
if self.quick_mask.editing {
return self.paint_fill(ts, canvas, gray);
}
@@ -1037,29 +1097,52 @@ impl Session {
}
}
/// Run `f` with stroke `st` as a commit source over `tiles` (the Projection tool's stencil
/// colors and alpha come from the surface under each texel).
/// Check that some rasterized paint survives the stencil before writing tiles or history.
fn stencil_allows_stroke(source: CommitSource) -> bool {
use texturecraft_texel::{TILE, from_u16};
let Some(sample_stencil) = source.per_texel else { return true };
let opacity = source.opacity.clamp(0.0, 1.0);
source.tiles.iter().any(|&(tile_x, tile_y)| {
source.alpha.tile(tile_x, tile_y).is_some_and(|alpha| {
alpha.iter().enumerate().any(|(index, &coverage)| {
let weight = from_u16(coverage) * opacity;
if weight <= 0.0 {
return false;
}
let x = tile_x * TILE + index as u32 % TILE;
let y = tile_y * TILE + index as u32 / TILE;
sample_stencil(x, y).is_some_and(|(_, factor)| weight * factor > 0.0)
})
})
})
}
/// Run `f` with `stroke` as a commit source over `tiles` (the stencil's alpha and, on the Projection tool, its colors come from the surface under each texel)
fn with_commit_source<R>(
st: &ActiveStroke,
gbuf: Option<&texturecraft_geom::UvGBuffer>,
stroke: &ActiveStroke,
gbuffer: Option<&texturecraft_geom::UvGBuffer>,
mesh: &texturecraft_geom::Mesh,
tiles: &BTreeSet<(u32, u32)>,
projection: Option<&ProjectedTiles>,
f: impl FnOnce(CommitSource) -> R,
) -> R {
let stencil_fn = |x: u32, y: u32| -> Option<([f32; 3], f32)> {
let stencil_fn = |x: u32, y: u32| -> Option<(Option<[f32; 3]>, f32)> {
if let Some(projection) = projection {
let tile = projection.get(&(x / TILE, y / TILE))?;
let i = ((y % TILE) * TILE + x % TILE) as usize;
let &[r, g, b, a] = tile.get(i)?;
return Some(([r, g, b], a));
let offset = ((y % TILE) * TILE + x % TILE) as usize;
let &[red, green, blue, alpha] = tile.get(offset)?;
return Some((Some([red, green, blue]), alpha));
}
let g = gbuf?;
let p = g.surface(mesh, (y * g.width + x) as usize)?.pos;
st.stencil.as_ref()?.sample_world(p)
let gbuffer = gbuffer?;
let position = gbuffer.surface(mesh, (y * gbuffer.width + x) as usize)?.pos;
stroke.stencil.as_ref()?.paint_world(position)
};
let per_texel: Option<texturecraft_paint::TexelFn> = if st.stencil.is_some() { Some(&stencil_fn) } else { None };
let carried = st.canvas.pickup.as_ref().map(|p| &p.values);
let carried_mask = st.canvas.pickup.as_ref().and_then(|p| p.mask_values());
f(CommitSource { alpha: &st.canvas.alpha, tiles, opacity: st.stroke.settings.opacity, erase: st.erase, per_texel, carried, carried_mask })
let per_texel: Option<texturecraft_paint::TexelFn> = if stroke.stencil.is_some() { Some(&stencil_fn) } else { None };
let carried = stroke.canvas.pickup.as_ref().map(|pickup| &pickup.values);
let carried_mask = stroke.canvas.pickup.as_ref().and_then(|pickup| pickup.mask_values());
f(CommitSource { alpha: &stroke.canvas.alpha, tiles, opacity: stroke.stroke.settings.opacity, erase: stroke.erase, per_texel, carried, carried_mask })
}
+468 -80
View File
@@ -11,7 +11,7 @@ use std::sync::Arc;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use texturecraft_compose::{PaintTarget, PixelStore};
use texturecraft_compose::{ImageRes, PaintTarget, PixelStore};
use texturecraft_core::{Channel, Effect, EffectKind, LayerId, LayerKind, Mask, MaskBackground, PathShape};
use texturecraft_geom::glam::{Mat3, Vec2, Vec3};
use texturecraft_geom::{OrbitCamera, surface_at};
@@ -26,6 +26,9 @@ use crate::{Document, EngineError, Result, Session, cmd};
/// Control points kept at most.
pub const MAX_PATH_POINTS: usize = 4096;
/// Bytes of tiles the path cache's snapshots may hold (plus the edited path's); the oldest go
/// first.
const CACHE_BYTES: usize = 256 << 20;
/// The undo step that adds a new path
pub(crate) const NEW_PATH_LABEL: &str = "Path";
/// Curve sampling step in viewport pixels (3D view) and texture units (2D view).
@@ -151,23 +154,120 @@ impl PathState {
}
}
/// A path sublayer's pixels after painting its first paths (`below`), with the mesh and
/// texture size they were painted for.
/// Mesh id, texture size, owner layer channels, texture set channels.
type CacheKey = (u64, Option<(u32, u32)>, Vec<Channel>, Vec<Channel>);
/// A path sublayer's images: its mask (`None`) and each channel.
type Snap = BTreeMap<Option<Channel>, TileImage>;
/// A stored path and the brush alpha image it was painted with.
type Painted = (PathShape, Option<Arc<ImageRes>>);
/// A path sublayer as last painted for `key`: its paths, its images after each path
/// (`snaps[k]` after the first k; tiles are shared, so a snapshot costs only the tiles that
/// path changed; None once [`evict`]ed) and the tiles each path painted.
#[derive(Clone)]
pub(crate) struct PathCache {
pub(crate) eid: LayerId,
// Session::invalidate_changed discards the prefix when an image it reads changes
key: (u64, Option<(u32, u32)>),
below: Vec<PathShape>,
mask: Option<texturecraft_texel::TileImage>,
layers: Vec<((LayerId, Channel), texturecraft_texel::TileImage)>,
key: CacheKey,
shapes: Vec<Painted>,
snaps: Vec<Option<Snap>>,
tiles: Vec<BTreeSet<(u32, u32)>>,
}
/// The identities of the tile buffers and tile tables `snap` holds, added to `seen`; returns the
/// bytes of those not already there. A table (one pointer per tile slot) is shared by clones until
/// one writes, so a snapshot that diverged from the live image holds its own.
fn charge(snap: &Snap, seen: &mut BTreeSet<usize>) -> usize {
let mut bytes = 0;
for img in snap.values() {
if seen.insert(img.table_id()) {
bytes += img.table_bytes();
}
for ty in 0..img.tiles_y() {
for tx in 0..img.tiles_x() {
if let Some(t) = img.tile_handle(tx, ty)
&& seen.insert(Arc::as_ptr(t) as usize)
{
bytes += t.len() * 2;
}
}
}
}
bytes
}
/// Drop the snapshots past `budget` bytes, oldest first, so adding a path and editing recent
/// ones stay cheap, but keep snapshot `edited` (below the path being edited, so its next live
/// repaint starts there). Tiles are shared between snapshots and with the live pixels (the last
/// snapshot) and snapshot k holds every tile as it was after k paths, so each snapshot, newest
/// first, is charged for the tile buffers no live pixels, kept newer snapshot or `edited` already
/// hold: what freeing it would release at most. The first (empty) and the last cost nothing.
/// Returns the bytes the kept snapshots are charged.
fn evict(snaps: &mut [Option<Snap>], budget: usize, edited: usize) -> usize {
let mut seen = BTreeSet::new();
for k in [snaps.len().saturating_sub(1), edited] {
if let Some(Some(snap)) = snaps.get(k) {
charge(snap, &mut seen);
}
}
let mut bytes = 0;
for k in (1..snaps.len().saturating_sub(1)).rev().filter(|&k| k != edited) {
let Some(Some(snap)) = snaps.get(k) else { continue };
// Count into a copy: an evicted snapshot's tiles are not retained by it any more.
let mut with = seen.clone();
let cost = charge(snap, &mut with);
if bytes + cost > budget {
snaps[k] = None;
} else {
bytes += cost;
seen = with;
}
}
bytes
}
mod evict_pacer;
use evict_pacer::EvictPacer;
fn same_handle<T>(a: Option<&Arc<T>>, b: Option<&Arc<T>>) -> bool {
match (a, b) {
(Some(x), Some(y)) => Arc::ptr_eq(x, y),
(x, y) => x.is_none() && y.is_none(),
}
}
fn same_path(a: &Painted, b: &Painted) -> bool {
a.0 == b.0 && same_handle(a.1.as_ref(), b.1.as_ref())
}
/// Whether `a` and `b` hold the same tiles at `tiles`, by shared handle (painting a tile always
/// gives it a new one); a missing image reads as empty.
fn same_tiles(a: &Snap, b: &Snap, tiles: &BTreeSet<(u32, u32)>) -> bool {
a.keys().chain(b.keys()).all(|k| {
let (x, y) = (a.get(k), b.get(k));
let dims = |i: &TileImage| (i.width(), i.height(), i.comps());
x.zip(y).is_none_or(|(x, y)| dims(x) == dims(y))
&& tiles.iter().all(|&(tx, ty)| same_handle(x.and_then(|i| i.tile_handle(tx, ty)), y.and_then(|i| i.tile_handle(tx, ty))))
})
}
/// Copy `from`'s tiles at `tiles` into `to`.
fn copy_tiles(to: &mut Snap, from: &Snap, tiles: &BTreeSet<(u32, u32)>) {
for (k, src) in from {
to.entry(*k).or_insert_with(|| TileImage::new(src.width(), src.height(), src.comps()));
}
for (k, dst) in to.iter_mut() {
let src = from.get(k);
for &(x, y) in tiles {
dst.set_tile(x, y, src.and_then(|i| i.tile_handle(x, y)).cloned());
}
}
}
impl PathCache {
/// The image resources the cached paths painted their mask with
pub(crate) fn images(&self) -> impl Iterator<Item = &str> + '_ {
// Only successfully painted paths enter the prefix
self.below.iter().filter_map(|shape| shape.paint.get("mask_image")?.as_str())
self.shapes.iter().filter_map(|(shape, _)| shape.paint.get("mask_image")?.as_str())
}
}
@@ -363,7 +463,7 @@ fn remove_path(s: &mut Session, p: &Value) -> Result<Value> {
{
shapes.remove(index);
}
s.render_paths(eid, index)
s.render_paths(eid)
})?;
if s.tool.path.editing.is_some_and(|(e, _)| e == eid) {
s.stop_path_edit();
@@ -612,7 +712,7 @@ impl Session {
if let Some(Effect { kind: EffectKind::Path(paths), .. }) = session.doc.project.effect_mut(effect) {
paths.remove(index);
}
session.render_paths(effect, index)
session.render_paths(effect)
},
)?;
self.cancel_path();
@@ -982,62 +1082,124 @@ impl Session {
},
_ => return Err(EngineError::Other(format!("{} is not a path sublayer", eid.0))),
};
let mut out = self.render_paths(eid, index)?.get(index).cloned().unwrap_or_else(|| json!({}));
let mut out = self.render_paths(eid)?.get(index).cloned().unwrap_or_else(|| json!({}));
out["effect"] = json!(eid.0);
out["index"] = json!(index);
Ok(out)
}
/// Repaint path sublayer `eid` from its stored paths, bottom to top, where paths before
/// `from` are unchanged: their pixels come from [`PathCache`] when it holds them, and are
/// cached for the next repaint otherwise, so editing a path repaints it and the paths above
/// only. Runs inside the caller's undo step. Returns each painted path's report (null for
/// the cached ones).
fn render_paths(&mut self, eid: LayerId, from: usize) -> Result<Vec<Value>> {
/// Repaint path sublayer `eid` from its stored paths, bottom to top. From [`PathCache`]: the
/// paths before the first changed one keep their pixels, and an unchanged path above it
/// whose tiles the change didn't reach keeps its painted tiles; the rest repaint. Runs
/// inside the caller's undo step. Returns each painted path's report (null for the cached
/// ones).
fn render_paths(&mut self, eid: LayerId) -> Result<Vec<Value>> {
let shapes = self.paths(eid).ok_or_else(|| EngineError::Other(format!("{} is not a path sublayer", eid.0)))?.to_vec();
let key = (self.mesh_id, self.caches.get(self.ts()).map(|c| c.size));
self.doc.pixels.masks.remove(&eid);
self.doc.pixels.layers.retain(|(id, _), _| *id != eid);
let start = match &self.path_cache {
Some(c) if c.eid == eid && c.key == key && c.below.len() <= from && shapes.get(..c.below.len()) == Some(&c.below[..]) => {
if let Some(m) = &c.mask {
self.doc.pixels.masks.insert(eid, m.clone());
let images = &self.images;
let alpha = |sh: &PathShape| read_paint(sh).ok().and_then(|p| p.brush.alpha_image).and_then(|n| images.get(&n).cloned());
let new: Vec<Painted> = shapes
.into_iter()
.map(|sh| {
let a = alpha(&sh);
(sh, a)
})
.collect();
let project = &self.doc.project;
let owner = project.effect(eid).and_then(|(o, _)| project.layer(o).ok()).map(|l| l.channels.keys().copied().collect()).unwrap_or_default();
let set = project.texture_set(self.ts()).map(|t| t.channel_list()).unwrap_or_default();
let key: CacheKey = (self.mesh_id, self.caches.get(self.ts()).map(|c| c.size), owner, set);
let old = self.path_cache.take().filter(|c| c.eid == eid && c.key == key);
let (prefix, suffix) = old.as_ref().map_or((0, 0), |c| {
let p = c.shapes.iter().zip(&new).take_while(|(a, b)| same_path(a, b)).count();
(p, c.shapes[p..].iter().rev().zip(new[p..].iter().rev()).take_while(|(a, b)| same_path(a, b)).count())
});
// Start from the last snapshot kept at or below the first changed path (the first one,
// empty, is always kept).
let start = old.as_ref().map_or(0, |c| (0..=prefix).rev().find(|&k| c.snaps[k].is_some()).unwrap_or(0));
let mut snaps = old.as_ref().map_or_else(|| vec![Some(Snap::new())], |c| c.snaps[..=start].to_vec());
let mut tiles = old.as_ref().map_or_else(Vec::new, |c| c.tiles[..start].to_vec());
let mut state = snaps[start].clone().unwrap_or_default();
let mut pacer = EvictPacer::start(&mut snaps, prefix);
// Each path goes through the regular stroke and fill code with its own settings; their
// own history entries are dropped (the caller records one step).
let mut out = vec![Value::Null; start];
let result = self.while_painting_paths(eid, |s| {
let mut result = Ok(());
for (j, (sh, _)) in new.iter().enumerate().skip(start) {
// Painting is per tile: over the same tiles, an unchanged path paints the same.
let o = if j < prefix { Some(j) } else { (j >= new.len() - suffix).then(|| j + old.as_ref().map_or(0, |c| c.shapes.len()) - new.len()) };
if let (Some(c), Some(o)) = (&old, o)
&& let (Some(below), Some(after)) = (&c.snaps[o], &c.snaps[o + 1])
&& same_tiles(&state, below, &c.tiles[o])
{
copy_tiles(&mut state, after, &c.tiles[o]);
tiles.push(c.tiles[o].clone());
snaps.push(Some(state.clone()));
pacer.appended(&mut snaps, prefix, &state, c.tiles[o].len());
out.push(Value::Null);
continue;
}
self.doc.pixels.layers.extend(c.layers.iter().cloned());
c.below.len()
s.put_snap(eid, &state);
s.path_tiles.clear();
match s.paint_shape(sh) {
Ok(v) => out.push(v),
Err(e) => {
result = Err(e);
break;
}
}
state = s.take_snap(eid);
tiles.push(std::mem::take(&mut s.path_tiles));
snaps.push(Some(state.clone()));
pacer.appended(&mut snaps, prefix, &state, tiles.last().map_or(0, BTreeSet::len));
}
_ => 0,
};
s.put_snap(eid, &state);
result
});
if result.is_ok() {
self.path_cache = Some(PathCache { eid, key, shapes: new, snaps, tiles });
}
result.map(|_| out)
}
// Regular stroke and fill code paints each path with its own settings
// Discard its history entries because the caller records one undo step
/// Run `f` with the session switched into path-painting state (path tool on sublayer `eid`,
/// empty history), then put the tool, camera, target, quick-mask flag and the undo/redo
/// stacks back. A panic in `f` restores them too before it continues unwinding: the
/// automation servers catch panics and keep serving this session, and must not find its
/// history gone.
fn while_painting_paths<T>(&mut self, eid: LayerId, f: impl FnOnce(&mut Session) -> T) -> T {
let saved = (self.tool.clone(), self.camera, self.target, self.quick_mask.editing);
let history = (std::mem::take(&mut self.undo), std::mem::take(&mut self.redo));
self.target = StackTarget::Effect(eid);
self.quick_mask.editing = false;
self.tool.tool = Tool::Path;
self.painting_paths = true;
let mut out = vec![Value::Null; start];
let mut result = Ok(());
for i in start..=shapes.len() {
if i == from.min(shapes.len()) && i > start {
let pixels = &self.doc.pixels;
let layers = pixels.layers.iter().filter(|((id, _), _)| *id == eid).map(|(k, v)| (*k, v.clone())).collect();
self.path_cache = Some(PathCache { eid, key, below: shapes[..i].to_vec(), mask: pixels.masks.get(&eid).cloned(), layers });
}
let Some(sh) = shapes.get(i) else { break };
match self.paint_shape(sh) {
Ok(v) => out.push(v),
Err(e) => {
result = Err(e);
break;
}
}
}
let ran = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| f(self)));
self.painting_paths = false;
(self.tool, self.camera, self.target, self.quick_mask.editing) = saved;
(self.undo, self.redo) = history;
result.map(|_| out)
match ran {
Ok(v) => v,
Err(panic) => std::panic::resume_unwind(panic),
}
}
fn take_snap(&self, eid: LayerId) -> Snap {
let p = &self.doc.pixels;
let mask = p.masks.get(&eid).map(|m| (None, m.clone()));
mask.into_iter().chain(p.layers.iter().filter(|((id, _), _)| *id == eid).map(|((_, c), img)| (Some(*c), img.clone()))).collect()
}
fn put_snap(&mut self, eid: LayerId, snap: &Snap) {
let p = &mut self.doc.pixels;
p.masks.remove(&eid);
p.layers.retain(|(id, _), _| *id != eid);
for (k, img) in snap {
match k {
None => p.masks.insert(eid, img.clone()),
Some(c) => p.layers.insert((eid, *c), img.clone()),
};
}
}
fn paint_shape(&mut self, shape: &PathShape) -> Result<Value> {
@@ -1216,45 +1378,246 @@ mod tests {
v
}
#[test]
fn cached_repaint_matches_a_full_repaint() {
let mut s = Session::new_project("t", texturecraft_geom::primitives::sphere(1.0, 24, 12), "builtin:test", None, 128).unwrap();
/// A session with horizontal UV paths at `rows` (one path sublayer) on a 512 texture.
fn with_paths(rows: &[f32]) -> (Session, texturecraft_core::LayerId) {
let mut s = Session::new_project("t", texturecraft_geom::primitives::sphere(1.0, 24, 12), "builtin:test", None, 512).unwrap();
s.update();
execute(&mut s, "tool.brush", &json!({"size": 6})).unwrap();
let mut eid = 0;
for v in [0.2, 0.5, 0.8] {
let r = execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, v], [0.9, v + 0.05]], "commit": true})).unwrap();
for v in rows {
let r = execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, v], [0.9, v]], "commit": true})).unwrap();
eid = r["committed"]["effect"].as_u64().unwrap();
}
let eid = texturecraft_core::LayerId(eid);
(s, texturecraft_core::LayerId(eid))
}
// Live edits of the middle path reuse the bottom path's pixels
execute(&mut s, "path.edit", &json!({"effect": eid.0, "index": 1})).unwrap();
for v in [0.4, 0.45] {
execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, v], [0.5, v], [0.9, v]]})).unwrap();
}
assert_eq!(s.path_cache.as_ref().map(|c| c.below.len()), Some(1));
let r = s.render_paths(eid, 1).unwrap();
assert!(r[0].is_null() && !r[1].is_null(), "the bottom path came from the cache: {r:?}");
let cached = pixels(&s, eid);
/// Move path `index` to row `v` (a live edit) and check the result against painting every
/// path. Returns which paths were repainted.
fn edit_row(s: &mut Session, eid: texturecraft_core::LayerId, index: usize, v: f32) -> Vec<bool> {
execute(s, "path.edit", &json!({"effect": eid.0, "index": index})).unwrap();
let before = s.path_cache.clone();
execute(s, "tool.path", &json!({"uvPoints": [[0.1, v], [0.5, v], [0.9, v]]})).unwrap();
let cached = pixels(s, eid);
s.path_cache = before;
let painted = s.render_paths(eid).unwrap().iter().map(|r| !r.is_null()).collect();
assert_eq!(cached, pixels(s, eid));
s.path_cache = None;
s.render_paths(eid, 0).unwrap();
assert_eq!(cached, pixels(&s, eid), "same pixels as painting every path");
s.render_paths(eid).unwrap();
assert_eq!(cached, pixels(s, eid), "same pixels as painting every path");
assert!(!cached.is_empty());
s.stop_path_edit();
painted
}
#[test]
fn cached_repaint_matches_a_full_repaint() {
// Rows 0.2, 0.45 and 0.8 of 512 texels are in different 64-texel tile rows.
let (mut s, eid) = with_paths(&[0.2, 0.45, 0.8]);
assert_eq!(edit_row(&mut s, eid, 1, 0.47), [false, true, false], "only the edited path repaints");
assert_eq!(edit_row(&mut s, eid, 0, 0.22), [true, false, false], "paths above keep their tiles");
assert_eq!(edit_row(&mut s, eid, 0, 0.79), [true, false, true], "a path over the change repaints");
}
#[test]
fn a_filled_path_above_an_edit_keeps_its_tiles() {
// The stroke at row 0.2 is edited; the closed, filled path above it lies in other tiles.
let (mut s, eid) = with_paths(&[0.2]);
execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, 0.7], [0.5, 0.7], [0.5, 0.9], [0.1, 0.9]], "closed": true, "fill": true, "commit": true}))
.unwrap();
assert_eq!(edit_row(&mut s, eid, 0, 0.22), [true, false], "the fill above comes from the cache, with its pixels");
}
#[test]
fn removing_a_path_keeps_the_paths_above() {
let (mut s, eid) = with_paths(&[0.2, 0.45, 0.8]);
let before = s.path_cache.clone();
execute(&mut s, "path.remove", &json!({"effect": eid.0, "index": 0})).unwrap();
let cached = pixels(&s, eid);
s.path_cache = before;
assert!(s.render_paths(eid).unwrap().iter().all(Value::is_null), "both paths above came from the cache");
s.path_cache = None;
s.render_paths(eid).unwrap();
assert_eq!(cached, pixels(&s, eid), "same pixels as painting every path");
}
#[test]
fn replacing_the_brush_alpha_image_repaints() {
let (mut s, eid) = with_paths(&[0.2]);
let img = |v: f32| std::sync::Arc::new(texturecraft_compose::ImageRes::new(2, 2, vec![[v; 4]; 4], false));
s.images.insert("a".into(), img(1.0));
execute(&mut s, "tool.brush", &json!({"alpha": {"image": "a"}})).unwrap();
execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, 0.8], [0.9, 0.8]], "commit": true})).unwrap();
s.render_paths(eid).unwrap();
s.images.insert("a".into(), img(0.5));
let r = s.render_paths(eid).unwrap();
assert!(r[0].is_null() && !r[1].is_null(), "only the path using the image repaints: {r:?}");
}
#[test]
fn snapshots_stay_within_the_budget() {
let (mut s, eid) = with_paths(&[0.2, 0.45, 0.8]);
let c = s.path_cache.as_mut().unwrap();
super::evict(&mut c.snaps, usize::MAX, 0);
assert_eq!(c.snaps.iter().flatten().count(), 4);
// The paths are on different tiles, so a snapshot costs nothing beyond its own tile table
// (the tiles are all shared with the live pixels): a budget of two tables keeps them.
let table: usize = c.snaps[1].as_ref().unwrap().values().map(texturecraft_texel::TileImage::table_bytes).sum();
super::evict(&mut c.snaps, 2 * table, 0);
assert_eq!(c.snaps.iter().flatten().count(), 4, "snapshots that share every tile with the live pixels cost only their tables");
// Drop them by hand to test the repaint from the bottom.
c.snaps[1] = None;
c.snaps[2] = None;
// Appending still paints the new path alone.
let shape = s.paths(eid).unwrap()[0].clone();
if let Some(texturecraft_core::Effect { kind: texturecraft_core::EffectKind::Path(v), .. }) = s.doc.project.effect_mut(eid) {
v.push(shape);
}
let r = s.render_paths(eid).unwrap();
assert_eq!(r.iter().map(|x| !x.is_null()).collect::<Vec<_>>(), [false, false, false, true]);
// Editing above evicted snapshots repaints from the bottom and matches a full repaint.
let c = s.path_cache.as_mut().unwrap();
assert!(c.snaps[1].is_none() && c.snaps[2].is_none());
assert_eq!(edit_row(&mut s, eid, 2, 0.81), [true; 4], "the copy of path 1 sits on repainted tiles");
// That edit kept the snapshot below path 3 within a one-table budget: its next frame starts
// there, and the snapshots above it that cost only a table keep their paths unrepainted.
let c = s.path_cache.as_mut().unwrap();
let table: usize = c.snaps[2].as_ref().unwrap().values().map(texturecraft_texel::TileImage::table_bytes).sum();
super::evict(&mut c.snaps, table, 2);
assert!(c.snaps[2].is_some());
assert_eq!(edit_row(&mut s, eid, 2, 0.83), [false, false, true, false], "only the edited path repaints");
}
/// `prev` with the tiles in `at` replaced by new handles (what painting a path does).
fn painted(prev: &super::Snap, at: &[(u32, u32)]) -> super::Snap {
let mut next = prev.clone();
for img in next.values_mut() {
for &(x, y) in at {
img.set_tile(x, y, Some(std::sync::Arc::new(vec![1u16; texturecraft_texel::TILE_AREA * 4])));
}
}
next
}
#[test]
fn the_budget_counts_the_tiles_an_old_snapshot_keeps_alive() {
let all: Vec<(u32, u32)> = (0..4).flat_map(|y| (0..4).map(move |x| (x, y))).collect();
let empty: super::Snap = [(Some(texturecraft_core::Channel::BaseColor), texturecraft_texel::TileImage::new(256, 256, 4))].into();
// A full-texture fill, a one-tile stroke, another full fill, another one-tile stroke.
let s1 = painted(&empty, &all);
let s2 = painted(&s1, &[(0, 0)]);
let s3 = painted(&s2, &all);
let s4 = painted(&s3, &[(0, 0)]);
let mut snaps = vec![Some(empty), Some(s1), Some(s2), Some(s3), Some(s4)];
// Snapshot 3 is the edited one. Snapshot 2 alone holds 15 tiles of the first fill that
// neither the live image nor snapshot 3 has: that is over a budget of 8 tiles.
let tile_bytes = texturecraft_texel::TILE_AREA * 4 * 2;
super::evict(&mut snaps, 8 * tile_bytes, 3);
assert!(snaps[3].is_some(), "the edited snapshot stays");
assert!(snaps[2].is_none(), "snapshot 2 keeps the first fill alive, over the budget");
}
#[test]
fn appending_paths_scans_the_snapshots_only_when_the_budget_may_be_passed() {
let empty: super::Snap = [(Some(texturecraft_core::Channel::BaseColor), texturecraft_texel::TileImage::new(256, 256, 4))].into();
let table = empty.values().map(texturecraft_texel::TileImage::table_bytes).sum::<usize>();
let tile_bytes = texturecraft_texel::TILE_AREA * 4 * 2;
let mut snaps = vec![Some(empty.clone()), Some(painted(&empty, &[(0, 0)]))];
let mut pacer = super::EvictPacer::start(&mut snaps, 0);
assert_eq!(pacer.held, 0, "the first and last snapshots are free");
// A few small paths add up to an estimate without a scan (a scan would reset it to the exact 0).
for n in 1..=3 {
pacer.appended(&mut snaps, 0, &empty, 1);
assert_eq!(pacer.held, n * (tile_bytes + table), "after {n} paths");
}
// Past the budget the estimate gives way to an exact scan.
pacer.appended(&mut snaps, 0, &empty, super::CACHE_BYTES / tile_bytes + 1);
assert!(pacer.held < super::CACHE_BYTES, "scanned: {}", pacer.held);
}
#[test]
fn a_snapshot_is_charged_only_for_what_no_kept_snapshot_shares() {
let all: Vec<(u32, u32)> = (0..4).flat_map(|y| (0..4).map(move |x| (x, y))).collect();
let empty: super::Snap = [(Some(texturecraft_core::Channel::BaseColor), texturecraft_texel::TileImage::new(256, 256, 4))].into();
let tile_bytes = texturecraft_texel::TILE_AREA * 4 * 2;
let table = empty.values().map(texturecraft_texel::TileImage::table_bytes).sum::<usize>();
// Two full fills then a one-tile stroke (the live pixels). Snapshot 2 shares 15 tiles with
// the live pixels and owns one; snapshot 1 owns the whole first fill: 16 tiles.
let s1 = painted(&empty, &all);
let s2 = painted(&s1, &all);
let s3 = painted(&s2, &[(0, 0)]);
let fresh = || vec![Some(empty.clone()), Some(s1.clone()), Some(s2.clone()), Some(s3.clone())];
let kept = |snaps: &[Option<super::Snap>]| snaps.iter().map(Option::is_some).collect::<Vec<_>>();
let mut snaps = fresh();
super::evict(&mut snaps, usize::MAX, 0);
assert_eq!(kept(&snaps), [true; 4]);
let mut snaps = fresh();
super::evict(&mut snaps, tile_bytes + table, 0);
assert_eq!(kept(&snaps), [true, false, true, true], "snapshot 2 costs one tile and a table, snapshot 1 sixteen");
let mut snaps = fresh();
super::evict(&mut snaps, 0, 0);
assert_eq!(kept(&snaps), [true, false, false, true], "snapshot 2 owns one tile, over a zero budget");
// Keeping snapshot 1 (edited) makes snapshot 2 free of the tiles they share, not of its own.
let mut snaps = fresh();
super::evict(&mut snaps, 0, 1);
assert_eq!(kept(&snaps), [true, true, false, true]);
}
#[test]
fn the_tile_table_of_a_diverged_snapshot_counts_once_against_the_budget() {
// Big image: the table (one slot per tile position) outweighs a one-tile stroke.
let empty: super::Snap = [(Some(texturecraft_core::Channel::Roughness), texturecraft_texel::TileImage::new(8192, 8192, 4))].into();
let table = empty.values().map(texturecraft_texel::TileImage::table_bytes).sum::<usize>();
assert!(table >= 128 * 128 * 8, "table {table}");
let s1 = painted(&empty, &[(0, 0)]);
let s2 = painted(&s1, &[(1, 0)]);
let s3 = painted(&s2, &[(2, 0)]);
let live = painted(&s3, &[(3, 0)]);
let mut seen = std::collections::BTreeSet::new();
// Alone, a diverged snapshot holds its own table; charged again with the same table, it is free.
let first = super::charge(&s2, &mut seen);
assert!(first >= table, "charged {first}");
assert_eq!(super::charge(&s2, &mut seen), 0);
// Tiles alone (8 KiB each) would fit this budget; with tables only one snapshot does.
let tile_only = texturecraft_texel::TILE_AREA * 4 * 2;
let mut snaps = vec![Some(empty.clone()), Some(s1), Some(s2), Some(s3), Some(live)];
super::evict(&mut snaps, 3 * tile_only, 0);
assert!(snaps.iter().filter(|s| s.is_some()).count() < 5, "tables must evict snapshots");
}
#[test]
fn the_quick_mask_does_not_clip_paths() {
let (mut s, eid) = with_paths(&[0.2, 0.8]);
let plain = pixels(&s, eid);
s.quick_mask.enabled = true;
s.path_cache = None;
s.render_paths(eid).unwrap();
assert_eq!(plain, pixels(&s, eid));
}
#[test]
fn owner_channel_change_skips_the_cache() {
let (mut s, eid) = with_paths(&[0.3, 0.7]);
s.render_paths(eid).unwrap();
let owner = s.doc.project.effect(eid).unwrap().0;
let layer = s.doc.project.layer_mut(owner).unwrap();
let ch = *layer.channels.keys().next().unwrap();
layer.channels.remove(&ch);
let r = s.render_paths(eid).unwrap();
assert!(!r[0].is_null(), "the bottom path was repainted: {r:?}");
assert!(!s.doc.pixels.layers.contains_key(&(eid, ch)), "no pixels left in the removed channel");
}
#[test]
fn deleting_the_path_effect_releases_its_cached_tiles() {
let (mut s, eid) = with_paths(&[0.2, 0.5, 0.8]);
execute(&mut s, "path.edit", &json!({"effect": eid.0, "index": 1})).unwrap();
execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, 0.35], [0.9, 0.4]]})).unwrap();
let cached_tiles = s.path_cache.as_ref().map_or(0, |cache| cache.layers.iter().map(|(_, image)| image.allocated_count()).sum::<usize>());
assert!(cached_tiles > 0);
let held = |s: &Session| {
s.path_cache.as_ref().map_or(0, |c| c.snaps.iter().flatten().flat_map(|snap| snap.values()).map(|i| i.allocated_count()).sum::<usize>())
};
assert!(held(&s) > 0);
execute(&mut s, "effect.remove", &json!({"effect": eid.0})).unwrap();
let remaining_tiles = s.path_cache.as_ref().map_or(0, |cache| cache.layers.iter().map(|(_, image)| image.allocated_count()).sum::<usize>());
assert_eq!(remaining_tiles, 0);
assert_eq!(held(&s), 0);
assert!(s.path_cache.is_none(), "deleting the path effect releases its cached tiles");
}
@@ -1278,14 +1641,14 @@ mod tests {
execute(&mut s, "path.edit", &json!({"effect": eid.0, "index": 1})).unwrap();
execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, 0.6], [0.9, 0.6]]})).unwrap();
assert_eq!(s.path_cache.as_ref().map(|c| c.below.len()), Some(1), "the bottom path is cached");
assert_eq!(s.path_cache.as_ref().map(|c| c.shapes.len()), Some(2), "the paths are cached");
execute(&mut s, "resource.remove", &json!({"name": image})).unwrap();
execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, 0.65], [0.9, 0.65]]})).unwrap();
let mask = |s: &Session| format!("{:?}", s.doc.pixels.masks.get(&eid));
let edited = mask(&s);
s.path_cache = None;
s.render_paths(eid, 0).unwrap();
s.render_paths(eid).unwrap();
assert_eq!(edited, mask(&s), "the bottom path paints the mask value as a full repaint does");
}
@@ -1297,7 +1660,9 @@ mod tests {
let tile = Arc::new(vec![1u16; texturecraft_texel::TILE_AREA]);
let retained = Arc::downgrade(&tile);
image.set_tile(0, 0, Some(tile));
session.path_cache = Some(PathCache { eid: LayerId(0), key: (0, None), below: Vec::new(), mask: Some(image), layers: Vec::new() });
let snap: Snap = [(None, image)].into();
session.path_cache =
Some(PathCache { eid: LayerId(0), key: (0, None, Vec::new(), Vec::new()), shapes: Vec::new(), snaps: vec![Some(snap)], tiles: Vec::new() });
let result: Result<()> = session.edit("Rejected edit", |_| Err(EngineError::Other("rejected".into())));
@@ -1418,4 +1783,27 @@ mod tests {
assert!(!off_mesh.is_empty());
assert!(off_mesh.iter().flatten().all(Option::is_none));
}
#[test]
fn a_panic_while_painting_paths_restores_history_and_tool_state() {
let mut s = Session::new_project("t", texturecraft_geom::primitives::sphere(1.0, 24, 12), "builtin:test", None, 128).unwrap();
s.update();
execute(&mut s, "tool.brush", &json!({"size": 6})).unwrap();
let r = execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, 0.2], [0.9, 0.25]], "commit": true})).unwrap();
let eid = texturecraft_core::LayerId(r["committed"]["effect"].as_u64().unwrap());
assert!(!s.history_labels().is_empty());
let labels = s.history_labels();
let (target, tool) = (s.target, s.tool.tool);
let panicked = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
s.while_painting_paths(eid, |s| {
s.edit("nested", |_| Ok(())).unwrap();
panic!("paint failed");
})
}));
assert!(panicked.is_err());
assert_eq!(s.history_labels(), labels);
assert_eq!((s.target, s.tool.tool), (target, tool));
assert!(!s.painting_paths);
}
}
@@ -0,0 +1,29 @@
use super::{CACHE_BYTES, Snap, TileImage, evict};
/// Runs [`evict`] only when the snapshots may have outgrown the budget. `evict` charges every
/// kept snapshot, so calling it after each appended path made a repaint of n paths cost n
/// scans of up to n snapshots. A snapshot differs from the one before it only in the tiles its
/// path painted, so those tiles bound what it adds: `held` is an upper bound on the bytes
/// charged, and the scan runs once it passes the budget (then `held` is exact again).
pub(super) struct EvictPacer {
pub(super) held: usize,
}
impl EvictPacer {
/// Scan the snapshots kept from the previous repaint once, trimming them to the budget.
pub(super) fn start(snaps: &mut [Option<Snap>], edited: usize) -> Self {
Self { held: evict(snaps, CACHE_BYTES, edited) }
}
/// A snapshot was appended after a path that painted `tiles` tile positions of `state`'s images.
pub(super) fn appended(&mut self, snaps: &mut [Option<Snap>], edited: usize, state: &Snap, tiles: usize) {
let tile_bytes: usize = state.values().map(|image| texturecraft_texel::TILE_AREA * image.comps() * 2).sum();
// The new snapshot may also own a table per image (a write after the clone copies it)
let table_bytes: usize = state.values().map(TileImage::table_bytes).sum();
self.held = self.held.saturating_add(tiles.saturating_mul(tile_bytes)).saturating_add(table_bytes);
if self.held > CACHE_BYTES {
self.held = evict(snaps, CACHE_BYTES, edited);
}
}
}
+3
View File
@@ -472,6 +472,7 @@ mod tests {
assert!(warnings.is_empty(), "{warnings:?}");
assert_eq!(run(&mut s, "export.preset.get", json!({"name": name.to_ascii_lowercase()})).unwrap(), custom);
let plan = run(&mut s, "export.plan", json!({"preset": name, "ts": 0})).unwrap();
assert_eq!(plan.as_array().unwrap().len(), 1);
assert!(plan[0]["file"].as_str().unwrap().ends_with("_R.png"));
@@ -481,9 +482,11 @@ mod tests {
let builtin = format!("builtin:{name}");
assert!(names.iter().any(|entry| entry["name"] == builtin && entry["builtin"] == true));
let builtin_plan = run(&mut s, "export.plan", json!({"preset": builtin, "ts": 0})).unwrap();
assert!(builtin_plan.as_array().unwrap().len() > 1);
run(&mut s, "export.preset.save", json!({"preset": custom})).unwrap();
run(&mut s, "export.preset.remove", json!({"name": name})).unwrap();
assert_eq!(run(&mut s, "export.preset.get", json!({"name": name})).unwrap()["maps"].as_array().unwrap().len(), 4);
}
+5 -9
View File
@@ -27,13 +27,9 @@ pub struct QuickMask {
pub revision: u64,
}
/// Live brush coverage for the temporary mask (never written into document layers).
pub struct QuickMaskStroke<'a> {
pub alpha: &'a TileImage,
pub device: Option<&'a dyn crate::brush_device::DeviceStroke>,
pub opacity: f32,
pub erase: bool,
}
mod quick_mask_stroke;
pub use quick_mask_stroke::QuickMaskStroke;
pub fn specs() -> Vec<CommandSpec> {
vec![
@@ -103,10 +99,10 @@ impl Session {
}
/// What limits a paint stroke on `ts`: the mask and whether it is inverted (None when the
/// quick mask is off or being edited).
/// quick mask is off or being edited, and for paths, which repaint from what they store).
pub(crate) fn stroke_limit(&self, ts: usize, size: (u32, u32)) -> Option<(TileImage, bool)> {
let q = &self.quick_mask;
(q.enabled && !q.editing).then(|| (self.quick_mask_image(ts, size), q.inverted))
(q.enabled && !q.editing && !self.painting_paths).then(|| (self.quick_mask_image(ts, size), q.inverted))
}
/// Commit a stroke into the quick mask of `ts`.
@@ -0,0 +1,9 @@
use super::TileImage;
/// Live brush coverage for the temporary mask (never written into document layers).
pub struct QuickMaskStroke<'a> {
pub alpha: &'a TileImage,
pub device: Option<&'a dyn crate::brush_device::DeviceStroke>,
pub opacity: f32,
pub erase: bool,
}
+40 -13
View File
@@ -55,6 +55,15 @@ pub(crate) fn decoded(d: texturecraft_formats::DecodedImage) -> Arc<ImageRes> {
Arc::new(ImageRes::new(d.width, d.height, d.rgba, d.srgb))
}
/// Refuse resource files over [`MAX_BYTES`]
fn within_byte_limit(file_name: &str, bytes: &[u8]) -> Result<()> {
if bytes.len() > MAX_BYTES {
return Err(EngineError::Other(format!("{file_name} is larger than {} MB", MAX_BYTES >> 20)));
}
Ok(())
}
/// 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) {
@@ -95,12 +104,23 @@ impl Session {
self.add_image_resource_prefixed("", file_name, bytes, max_texels)
}
/// Store encoded pixels in the document during an edit; the caller can cache the decoded pixels after commit
pub(crate) fn add_image_resource_bytes(&mut self, file_name: &str, bytes: Vec<u8>) -> Result<String> {
within_byte_limit(file_name, &bytes)?;
Ok(self.insert_image_resource_bytes("", file_name, bytes))
}
fn add_image_resource_prefixed(&mut self, prefix: &str, file_name: &str, bytes: Vec<u8>, max_texels: u64) -> Result<String> {
if bytes.len() > MAX_BYTES {
return Err(EngineError::Other(format!("{file_name} is larger than {} MB", MAX_BYTES >> 20)));
}
within_byte_limit(file_name, &bytes)?;
let image = texturecraft_formats::decode_image_within(&bytes, max_texels).map_err(|error| EngineError::Other(format!("{file_name}: {error}")))?;
let name = self.insert_image_resource_bytes(prefix, file_name, bytes);
self.images.insert(name.clone(), decoded(image));
Ok(name)
}
/// Store `bytes` under a unique, sanitized name from `file_name` and `prefix`; returns the name
fn insert_image_resource_bytes(&mut self, prefix: &str, file_name: &str, bytes: Vec<u8>) -> String {
let leaf = std::path::Path::new(file_name).file_name().and_then(|name| name.to_str()).unwrap_or("image");
let mut base = sanitize_resource_name(leaf);
@@ -116,9 +136,7 @@ impl Session {
let name = unique_resource_name(base, |name| self.doc.resources.contains_key(name) || crate::fill_alpha::library_alpha_of(name).is_some());
self.doc.resources.insert(name.clone(), Arc::new(bytes));
self.images.insert(name.clone(), decoded(image));
Ok(name)
name
}
/// Decode resources that are not decoded yet and forget removed ones (after undo, redo, load).
@@ -341,6 +359,7 @@ fn rename(s: &mut Session, p: &Value) -> Result<Value> {
if to == name {
return Ok(json!({ "name": name }));
}
if s.doc.resources.contains_key(&to) || crate::fill_alpha::library_alpha_of(&to).is_some() {
return Err(bad(command, format!("a resource named `{to}` exists already")));
}
@@ -348,6 +367,7 @@ fn rename(s: &mut Session, p: &Value) -> Result<Value> {
s.edit("Rename resource", |s| {
let bytes = s.doc.resources.remove(&name).ok_or_else(|| bad(command, format!("no resource `{name}`")))?;
s.doc.resources.insert(to.clone(), bytes);
// The Resources Updater keeps following the file the image came from
if let Some(source) = s.doc.project.resource_sources.remove(&name) {
s.doc.project.resource_sources.insert(to.clone(), source);
@@ -428,17 +448,23 @@ fn images_in_use(s: &Session) -> Vec<String> {
}
/// Drop resources unused by layers, mesh maps, paint tools or the environment (one undo step)
fn remove_unused(s: &mut Session, _: &Value) -> Result<Value> {
let used = images_in_use(s);
let unused: Vec<String> = s.doc.resources.keys().filter(|k| !used.contains(k)).cloned().collect();
fn remove_unused(session: &mut Session, _: &Value) -> Result<Value> {
let mut used = images_in_use(session);
used.sort_unstable();
let unused: Vec<_> = session.doc.resources.keys().filter(|name| used.binary_search(name).is_err()).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));
session.edit("Remove unused resources", |session| {
for name in &unused {
session.doc.resources.remove(name);
session.doc.project.resource_sources.remove(name);
}
Ok(())
})?;
s.sync_images();
session.sync_images();
}
Ok(json!({ "removed": unused }))
}
@@ -538,6 +564,7 @@ mod tests {
let renamed = crate::execute(&mut session, "resource.rename", &json!({"name": name, "to": "stone"})).unwrap()["name"].as_str().unwrap().to_string();
std::fs::write(&path, texturecraft_formats::gray16_png(1, 1, [0.75].into_iter()).unwrap()).unwrap();
// An equal-size file counts as changed once its time moved, as a later save's does
let later = std::time::SystemTime::now() + std::time::Duration::from_secs(10);
std::fs::File::options().write(true).open(&path).unwrap().set_modified(later).unwrap();
+168 -78
View File
@@ -5,8 +5,8 @@ use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use serde::{Deserialize, Serialize};
use texturecraft_compose::{BakedMaps, BelowCache, Composite, PaintTarget, PixelStore, StackKey, StrokePreview, covered_tiles};
use texturecraft_core::{Channel, Layer, LayerId, LayerKind, Project, TextureSet};
use texturecraft_compose::{BakedMaps, BelowCache, Composite, PaintTarget, PixelStore, SeamPaddingInput, StackKey, StrokePreview, covered_tiles};
use texturecraft_core::{Channel, ChannelFormat, Layer, LayerId, LayerKind, Project, TextureSet, UvPaddingMode};
use texturecraft_geom::glam::Vec2;
use texturecraft_geom::{Bvh, Mesh, OrbitCamera, UvGBuffer};
use texturecraft_paint::{BrushSettings, EyeDepth, Stroke, StrokeCanvas};
@@ -38,26 +38,11 @@ pub struct Document {
pub(crate) painted_regions: BTreeMap<usize, crate::bake::PaintedRegion>,
}
/// A released dab keeps priority until its display upload is sent.
#[derive(Clone)]
pub struct ReleasedDab {
tile: (u32, u32),
uploaded: Arc<AtomicBool>,
}
mod display_stroke_end;
mod released_dab;
impl ReleasedDab {
pub(crate) fn new(tile: (u32, u32)) -> Self {
Self { tile, uploaded: Arc::default() }
}
pub(crate) fn pending_tile(&self) -> Option<(u32, u32)> {
(!self.uploaded.load(Ordering::Acquire)).then_some(self.tile)
}
pub fn acknowledge_upload(&self) {
self.uploaded.store(true, Ordering::Release);
}
}
pub(crate) use display_stroke_end::DisplayStrokeEnd;
pub use released_dab::ReleasedDab;
/// Derived per-texture-set data (rebuilt when the mesh or resolution changes).
pub struct SetCache {
@@ -65,6 +50,10 @@ pub struct SetCache {
pub size: (u32, u32),
pub gbuf: Arc<UvGBuffer>,
pub dilation: DisplayPadding,
/// The set's UV padding mode and the display padding it gives
pub uv_padding: UvPaddingMode,
/// The channels' storage formats the composite was made with
pub formats: Vec<(Channel, ChannelFormat)>,
pub covered_tiles: Arc<Vec<(u32, u32)>>,
pub composite: Composite,
/// Tiles to recomposite.
@@ -89,17 +78,18 @@ pub struct SetCache {
}
impl SetCache {
pub(crate) fn new(mesh: &Mesh, ts: &TextureSet) -> SetCache {
pub(crate) fn new(mesh: &Arc<Mesh>, ts: &TextureSet) -> SetCache {
let (w, h) = ts.size();
let gbuf = Arc::new(UvGBuffer::new(mesh, ts.material, w, h));
// Padding stays inside each UV tile.
let covered = covered_tiles(&gbuf);
let dilation = DisplayPadding::new(&gbuf, !covered.is_empty(), ts.block_resolution());
let dilation = DisplayPadding::new(mesh, ts, &gbuf, !covered.is_empty(), ts.block_size());
let all: BTreeSet<(u32, u32)> = texturecraft_compose::all_tiles(w, h).into_iter().collect();
SetCache {
size: (w, h),
gbuf,
dilation,
uv_padding: ts.uv_padding,
formats: ts.formats(),
covered_tiles: Arc::new(covered),
composite: Composite { block_scales: ts.block_scales(), ..Composite::with_size(&ts.channel_list(), w, h) },
dirty: all,
@@ -151,6 +141,7 @@ impl SetCache {
if tiles.is_empty() {
return;
}
let margin = match self.paint_margin {
Some((cached, margin)) if cached == target => margin,
_ => {
@@ -170,12 +161,13 @@ impl SetCache {
let left = left.saturating_sub(radius);
let right = right.saturating_add(radius).min(last_x);
for row in top.saturating_sub(radius)..=bottom.saturating_add(radius).min(last_y) {
// Covered tiles are sorted by row, then column.
// Covered tiles are sorted by row, then column
let start = covered.partition_point(|&(tx, ty)| (ty, tx) < (row, left));
queue.extend(covered[start..].iter().take_while(|&&(tx, ty)| ty == row && tx <= right).copied());
}
};
// Coalesce expensive, overlapping halos without scanning distant atlas tiles.
// Coalesce expensive, overlapping halos without scanning distant atlas tiles
let diameter = (radius as usize).saturating_mul(2).saturating_add(1);
if diameter.saturating_mul(diameter).saturating_mul(tiles.len()) >= covered.len() {
let bounds = tiles.iter().fold(((last_x, last_y), (0, 0)), |((l, t), (r, b)), &(x, y)| ((l.min(x), t.min(y)), (r.max(x), b.max(y))));
@@ -190,6 +182,24 @@ impl SetCache {
}
}
fn has_channels(&self, set: &TextureSet) -> bool {
if self.composite.channels.len() != set.channels.len() {
return false;
}
if self.composite.channels.keys().copied().eq(set.channels.iter().map(|&(channel, _)| channel)) {
return true;
}
// Saved sets can list their channels in a different order from the composite
let mut present = [false; Channel::ALL.len()];
for &(channel, _) in &set.channels {
present[channel.index()] = true;
}
self.composite.channels.keys().all(|channel| present[channel.index()])
}
pub fn invalidate_all(&mut self) {
self.material_revision = self.material_revision.wrapping_add(1);
self.dirty.extend(self.covered_tiles.iter().copied());
@@ -200,6 +210,15 @@ impl SetCache {
}
}
/// The geometry needed to continue UV padding across the seams of this set
pub(crate) fn padding_seams<'a>(mesh: &'a Mesh, set: &TextureSet, grid: &'a UvGBuffer) -> Option<SeamPaddingInput<'a>> {
if set.uv_padding == UvPaddingMode::Space2d {
return None;
}
SeamPaddingInput::of_material(mesh, set.material, &grid.tri)
}
/// Active tool.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum Tool {
@@ -220,6 +239,12 @@ pub enum Tool {
impl Tool {
pub const ALL: [Tool; 9] =
[Tool::Paint, Tool::Eraser, Tool::Projection, Tool::PolygonFill, Tool::Smudge, Tool::Clone, Tool::ColorPicker, Tool::Path, Tool::GeometryMask];
/// The brush tools whose strokes the stencil shapes
pub fn uses_stencil(self) -> bool {
matches!(self, Tool::Paint | Tool::Eraser | Tool::Projection | Tool::Smudge | Tool::Clone)
}
pub fn label(self) -> &'static str {
match self {
Tool::Paint => "Paint",
@@ -291,7 +316,7 @@ impl ViewMode {
}
}
/// A screen-pinned image for the Projection tool (a stencil).
/// A screen-pinned image the brush tools paint through (a stencil)
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct StencilState {
/// Image resource name.
@@ -362,7 +387,7 @@ pub struct ToolState {
/// Polygon fill boxes in the 3D view select only the polygons the camera sees
#[serde(default = "default_fill_visible_only")]
pub fill_visible_only: bool,
/// Stencil used by the Projection tool.
/// Stencil the brush tools paint through (the Projection tool paints its colors)
#[serde(default)]
pub stencil: Option<StencilState>,
/// Placement the next stencil starts with: the last stencil's, kept when the stencil is
@@ -458,17 +483,6 @@ pub enum StackTarget {
Effect(LayerId),
}
/// Work left in the viewport after a stroke committed or was cancelled.
pub(crate) struct DisplayStrokeEnd {
pub id: u64,
pub ts: usize,
pub previous_revision: u64,
pub revision: u64,
pub tiles: BTreeSet<(u32, u32)>,
/// The other texture sets the stroke fed: set, revision before and revision after.
pub fed: Vec<(usize, u64, u64)>,
}
pub(crate) struct ActiveStroke {
pub display_id: u64,
pub display_tiles: BTreeSet<(u32, u32)>,
@@ -487,10 +501,12 @@ pub(crate) struct ActiveStroke {
/// What a mask stroke paints, resolved once so staging, preview and commit read one image
pub mask_gray: texturecraft_compose::MaskGray,
pub erase: bool,
/// Projection tool: the stencil captured with the stroke's camera.
/// The stencil captured with the stroke's camera.
pub stencil: Option<texturecraft_compose::Stencil>,
/// History snapshot taken when the stroke began.
pub before: Document,
/// Document revision before any edits made during the stroke.
pub start_revision: u64,
pub label: String,
/// The commit's destination tiles, copied as the stroke reaches them.
pub staging: texturecraft_paint::Staging,
@@ -566,6 +582,8 @@ pub struct Session {
pub caches: Vec<SetCache>,
pub(crate) undo: Vec<(String, Document)>,
pub(crate) redo: Vec<(String, Document)>,
/// New undo steps so far: it moves even when a full history keeps its length
steps_added: u64,
/// Set by [`crate::execute`] from a command's `merge` param: its edits continue the previous
/// undo step with the same label (a slider drag is one step however many values it applies).
pub(crate) merge_edits: bool,
@@ -610,8 +628,10 @@ pub struct Session {
pub quick_mask: crate::quick_mask::QuickMask,
/// A path sublayer is being repainted from its paths (the only way to paint into one).
pub(crate) painting_paths: bool,
/// Pixels of the paths below the one being edited, so live edits skip repainting them.
/// A path sublayer as last painted, so a repaint skips the paths an edit didn't reach.
pub(crate) path_cache: Option<crate::path_tool::PathCache>,
/// Tiles painted since `render_paths` cleared it (the footprint of one path).
pub(crate) path_tiles: std::collections::BTreeSet<(u32, u32)>,
/// A new path's live preview: the path becomes an undo step only when it is applied
pub(crate) path_draft: Option<crate::path_draft::PathDraft>,
/// Point changes of the path being edited: (earlier states for undo, undone states for redo)
@@ -635,7 +655,7 @@ pub struct Session {
/// are unchanged, so back-to-back dabs start instantly.
pub(crate) depth_cache: Option<DepthCache>,
/// Projection fill depth maps shared by this session's tile batches.
projector_depth_cache: texturecraft_compose::ProjectorDepthCache,
pub(crate) projector_depth_cache: texturecraft_compose::ProjectorDepthCache,
/// The polygon fill box being dragged
pub(crate) polygon_fill_drag: Option<crate::polygon_fill_drag::PolygonFillDrag>,
/// The user's export presets (kept when another project opens).
@@ -679,6 +699,7 @@ impl Session {
caches,
undo: Vec::new(),
redo: Vec::new(),
steps_added: 0,
merge_edits: false,
tool: ToolState::default(),
active_set: 0,
@@ -706,6 +727,7 @@ impl Session {
quick_mask: Default::default(),
painting_paths: false,
path_cache: None,
path_tiles: Default::default(),
path_draft: None,
path_steps: Default::default(),
path: None,
@@ -834,7 +856,8 @@ impl Session {
// -----------------------------------------------------------------------------------------
// History
/// Run an undoable edit. On error the document is left untouched.
/// Run an undoable edit. On error, or if `f` panics, the document is left untouched (other
/// session state, such as the selection, is not restored).
pub fn edit<T>(&mut self, label: &str, f: impl FnOnce(&mut Session) -> Result<T>) -> Result<T> {
self.edit_merging(label, self.merge_edits, f)
}
@@ -850,7 +873,18 @@ impl Session {
self.end_polygon_fill_box();
let before = self.doc.clone();
let result = change(self).and_then(|(value, changed)| {
// A panic inside `change` must not leave a half-edited document behind: the automation
// servers catch panics and keep serving this session. (On wasm a panic aborts, so
// there is nothing to restore.)
let ran = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| change(self)));
let result = match ran {
Ok(result) => result,
Err(panic) => {
self.restore_after_failed_edit(before);
std::panic::resume_unwind(panic);
}
};
let result = result.and_then(|(value, changed)| {
if changed && let Some(id) = self.doc.project.instance_cycle() {
return Err(EngineError::Other(format!("instance layer {} would draw itself", id.0)));
}
@@ -866,15 +900,21 @@ impl Session {
Ok(value)
}
Err(error) => {
self.doc = before;
// A failed repaint may have cached tiles from the discarded document
self.path_cache = None;
self.restore_after_failed_edit(before);
Err(error)
}
}
}
/// Put `before` back after an edit failed or panicked. The edit may have recomposited the
/// discarded document (draining the dirty tiles) or cached path tiles from it, so mark what
/// differs between the two dirty again, as undo does.
fn restore_after_failed_edit(&mut self, before: Document) {
let discarded = std::mem::replace(&mut self.doc, before);
self.path_cache = None;
self.invalidate_changed(&discarded);
}
pub(crate) fn push_history(&mut self, label: &str, before: Document) {
self.record(label, before, false);
}
@@ -891,7 +931,7 @@ impl Session {
if !self.painting_paths
&& let Some(draft) = self.path_draft.take()
{
self.undo.push((crate::path_tool::NEW_PATH_LABEL.to_string(), draft.base));
self.add_step(crate::path_tool::NEW_PATH_LABEL.to_string(), draft.base);
}
// Point changes of an edited path undo only until another step lands
@@ -901,11 +941,22 @@ impl Session {
self.mark_modified();
if !(merge && self.undo.last().is_some_and(|(l, _)| l == label)) {
self.undo.push((label.to_string(), before));
self.add_step(label.to_string(), before);
}
self.redo.clear();
}
/// Append an undo step, dropping the oldest ones from a full history
pub(crate) fn add_step(&mut self, label: String, before: Document) {
self.undo.push((label, before));
let over = self.undo.len().saturating_sub(MAX_HISTORY);
self.undo.drain(..over);
self.redo.clear();
// A repaint of paths runs strokes on a temporary history, none of which is a step
if !self.painting_paths {
self.steps_added = self.steps_added.wrapping_add(1);
}
}
/// A change from `other` to the current document that is not an undo step (a path preview)
@@ -980,6 +1031,13 @@ impl Session {
)
};
for (texture_set_index, cache) in self.caches.iter_mut().enumerate() {
// AO mixing changes the packed display tiles and the GPU program
let ao_mixing = |document: &Document| document.project.texture_sets.get(texture_set_index).map(|set| set.ao_mixing);
if ao_mixing(previous_document) != ao_mixing(&self.doc) {
cache.material_revision = cache.material_revision.wrapping_add(1);
cache.upload.extend(texturecraft_compose::all_tiles(cache.size.0, cache.size.1));
}
if uses_added_resource(texture_set_index) {
cache.invalidate_all();
continue;
@@ -1047,24 +1105,35 @@ impl Session {
/// Make caches agree with the project's texture sets (resolution or channel changes).
pub fn sync_caches(&mut self) {
let sets = self.doc.project.texture_sets.clone();
let sets = &self.doc.project.texture_sets;
self.caches.truncate(sets.len());
for (i, ts) in sets.iter().enumerate() {
match self.caches.get_mut(i) {
Some(c) if c.size == ts.size() => {
c.invalidate_paint_margin();
c.finished_dab = None;
let (want, scales) = (ts.channel_list(), ts.block_scales());
if c.composite.channels.keys().copied().collect::<Vec<_>>() != want || c.composite.block_scales != scales {
c.composite = Composite { block_scales: scales, ..Composite::with_size(&want, c.size.0, c.size.1) };
c.upload.extend(texturecraft_compose::all_tiles(c.size.0, c.size.1));
c.invalidate_all();
for (index, set) in sets.iter().enumerate() {
match self.caches.get_mut(index) {
Some(cache) if cache.size == set.size() => {
cache.invalidate_paint_margin();
cache.finished_dab = None;
if cache.uv_padding != set.uv_padding {
cache.uv_padding = set.uv_padding;
cache.dilation = DisplayPadding::new(&self.mesh, set, &cache.gbuf, !cache.covered_tiles.is_empty(), set.block_size());
cache.invalidate_all();
}
if !cache.formats.iter().copied().eq(set.iter_formats()) {
cache.formats = set.formats();
cache.invalidate_all();
}
let scales = set.block_scales();
if !cache.has_channels(set) || cache.composite.block_scales != scales {
cache.composite = Composite { block_scales: scales, ..Composite::with_size(&set.channel_list(), cache.size.0, cache.size.1) };
cache.upload.extend(texturecraft_compose::all_tiles(cache.size.0, cache.size.1));
cache.invalidate_all();
}
}
_ => {
let cache = SetCache::new(&self.mesh, ts);
if i < self.caches.len() {
self.caches[i] = cache;
let cache = SetCache::new(&self.mesh, set);
if index < self.caches.len() {
self.caches[index] = cache;
} else {
self.caches.push(cache);
}
@@ -1101,10 +1170,27 @@ impl Session {
/// The undone steps, the next one to redo first.
pub fn redo_labels(&self) -> Vec<String> {
self.redo.iter().rev().map(|(l, _)| l.clone()).collect()
self.iter_redo_labels().map(str::to_owned).collect()
}
/// Borrow undone step labels, with the next step to redo first
pub fn iter_redo_labels(&self) -> impl ExactSizeIterator<Item = &str> {
self.redo.iter().rev().map(|(label, _)| label.as_str())
}
/// Changes with every new undo step, not when a merged edit continues one
pub fn steps_added(&self) -> u64 {
self.steps_added
}
/// The done steps, the oldest first
pub fn history_labels(&self) -> Vec<String> {
self.undo.iter().map(|(l, _)| l.clone()).collect()
self.iter_history_labels().map(str::to_owned).collect()
}
/// Borrow the labels of completed steps, oldest first
pub fn iter_history_labels(&self) -> impl ExactSizeIterator<Item = &str> {
self.undo.iter().map(|(label, _)| label.as_str())
}
/// Undo a point edit, cancel an uncommitted path, or restore a document snapshot, in that order
@@ -1168,13 +1254,17 @@ impl Session {
self.invalidate_changed(other);
// An undone add or duplicate takes the selected effect away
if let StackTarget::Effect(e) = self.target
&& self.doc.project.effect(e).is_none()
if let StackTarget::Effect(effect_id) = self.target
&& self.doc.project.effect(effect_id).is_none()
{
let p = &other.project;
let content = p.effect(e).and_then(|(owner, _)| p.layers.get(&owner)).is_some_and(|l| l.content_effects.iter().any(|x| x.id == e));
let previous_project = &other.project;
let content = previous_project
.effect(effect_id)
.and_then(|(owner, _)| previous_project.layers.get(&owner))
.is_some_and(|layer| layer.content_effects.iter().any(|effect| effect.id == effect_id));
self.target = if content { StackTarget::Content } else { StackTarget::Mask };
}
let has_mask = self.selected_layer().and_then(|lid| self.doc.project.layer(self.doc.project.mask_owner(lid)).ok()).is_some_and(|l| l.mask.is_some());
if self.target == StackTarget::Mask && !has_mask {
self.target = StackTarget::Content;
@@ -1241,8 +1331,7 @@ impl Session {
pub fn update_for_view_where(&mut self, budget_ms: f64, clock: impl Fn() -> f64, demand: crate::TileDemand, include: impl Fn(usize) -> bool) -> bool {
let active = self.ts();
if active != self.cache_active {
// A third material replaces the previously parked one, even when the
// interactive slice ends before the compositor visits that texture set.
// A third material replaces the parked one even when its turn falls in a later slice
if let Some(displaced) = self.cache_previous.filter(|&ts| ts != active)
&& let Some(cache) = self.caches.get_mut(displaced)
{
@@ -1256,10 +1345,10 @@ impl Session {
}
let changed = self.update_tiles(budget_ms, clock, active, demand, include);
if let Some(previous) = self.cache_previous.filter(|&ts| self.caches.get(ts).is_some_and(|c| !c.below.is_empty())) {
// Retaining an idle material spends only the remainder of the normal band
// budget. The active material always gets first use of that budget.
// Only the active material can claim the full band budget
let allowance = self.caches.get(active).map_or(0, |c| c.below.limit());
// Instances in other sets can have live bands of their own.
// Instances in other sets can have live bands of their own
let spare = self
.caches
.iter()
@@ -1316,6 +1405,7 @@ impl Session {
if Some(ts) == self.cache_previous && cache.dirty.is_empty() && cache.settle.is_empty() && !cache.below.is_empty() {
continue;
}
cache.below.set_hot(hot);
cache.below.pass = cache.dirty.len() + cache.settle.len();
@@ -1432,14 +1522,14 @@ impl Session {
if i != ts && !sets.contains(&i) {
continue;
}
if Some(c.size) == size {
if changed_document {
c.material_revision = c.material_revision.wrapping_add(1);
}
c.queue_painted(&self.doc.project, i, target, &tiles, |c| if settle { &mut c.settle } else { &mut c.dirty });
} else if settle || changed_document {
// Resampled instances first see paint when its source pixels are committed (a
// settled stroke, or a document edit such as a path repaint)
// Resampled instances read committed source pixels
c.invalidate_all();
}
}
@@ -0,0 +1,12 @@
use super::BTreeSet;
/// Work left in the viewport after a stroke committed or was cancelled.
pub(crate) struct DisplayStrokeEnd {
pub id: u64,
pub ts: usize,
pub previous_revision: u64,
pub revision: u64,
pub tiles: BTreeSet<(u32, u32)>,
/// The other texture sets the stroke fed: set, revision before and revision after.
pub fed: Vec<(usize, u64, u64)>,
}
+22
View File
@@ -0,0 +1,22 @@
use super::{Arc, AtomicBool, Ordering};
/// A released dab keeps priority until its display upload is sent.
#[derive(Clone)]
pub struct ReleasedDab {
pub(super) tile: (u32, u32),
pub(super) uploaded: Arc<AtomicBool>,
}
impl ReleasedDab {
pub(crate) fn new(tile: (u32, u32)) -> Self {
Self { tile, uploaded: Arc::default() }
}
pub(crate) fn pending_tile(&self) -> Option<(u32, u32)> {
(!self.uploaded.load(Ordering::Acquire)).then_some(self.tile)
}
pub fn acknowledge_upload(&self) {
self.uploaded.store(true, Ordering::Release);
}
}
+495 -55
View File
@@ -1,7 +1,7 @@
//! Texture set commands (Texture Set List / Texture Set Settings).
use serde_json::{Value, json};
use texturecraft_core::{Channel, ChannelBlend, ChannelFormat};
use texturecraft_core::{AoMixing, Channel, ChannelBlend, ChannelFormat, HeightToNormalMethod, NormalMixing, UvPaddingMode};
use std::sync::Arc;
@@ -21,13 +21,23 @@ pub fn specs() -> Vec<CommandSpec> {
"Inspect texture set",
[],
None,
"{ts?} → {index, name, resolution, size: [w, h], uvTiles: [UDIM numbers] (empty: no UV tiles), tiles: [{udim, block: [x, y]}], channels, layers, baked, visible, active}",
"{ts?} → {index, name, originalName, description, resolution, height, size: [w, h], blockResolution, uvTiles: [UDIM numbers] (empty: no UV tiles), tiles: [{udim, block: [x, y], resolution, bakeEnabled}], channels: [{channel, format, shaded}], layers, parts, baked, visible, normalMixing, aoMixing, heightToNormal, uvPadding, active}",
always,
|s, p| Ok(crate::inspect::texture_set(s, ts_param(s, p, "textureSet.inspect")?))
),
cmd!("textureSet.resolution", "Texture set size", [], None, "{ts?, resolution: 128..8192 (power of two)}", always, resolution),
cmd!(
"textureSet.resolution",
"Texture set size",
[],
None,
"{ts?, resolution: 128..8192 (power of two, texels across), height?: 128..8192 (texels down; default = resolution, a square set)}",
always,
resolution
),
cmd!("textureSet.channel.add", "Add channel", [], None, "{ts?, channel}", always, |s, p| channel(s, p, true)),
cmd!("textureSet.channel.remove", "Remove channel", [], None, "{ts?, channel}", always, |s, p| channel(s, p, false)),
cmd!("textureSet.channels", "Add or remove channels", [], None, "{ts?, add?: [channel], remove?: [channel], allSets?}", always, channels),
cmd!("textureSet.channel.format", "Set channel format", [], None, "{ts?, channel, format}", always, channel_format),
cmd!("textureSet.visible", "Toggle texture set visibility", [], None, "{ts?, visible?}", always, visible),
cmd!(
"textureSet.visibility",
@@ -38,8 +48,24 @@ pub fn specs() -> Vec<CommandSpec> {
always,
visibility
),
cmd!("textureSet.rename", "Rename texture set", [], None, "{ts?, name}", always, rename),
cmd!("textureSet.settings", "Texture set settings", [], None, "{ts?, description?, heightStrength?, normalFormat?: openGl|directX}", always, settings),
cmd!(
"textureSet.rename",
"Rename texture set",
[],
None,
"{ts?, name} or {ts?, reset: true} (back to the mesh material's name, `originalName` in inspect)",
always,
rename
),
cmd!(
"textureSet.settings",
"Texture set settings",
[],
None,
"{ts?, description?, heightStrength?, normalMixing?: combine|replace, aoMixing?: multiply|none, heightToNormal?: sharp|smooth, uvPadding?: 3d|2d, normalFormat?: openGl|directX}",
always,
settings
),
cmd!(
"textureSet.parts",
"List mesh parts",
@@ -68,18 +94,21 @@ pub fn parts(s: &Session, ts: usize) -> Vec<String> {
}
pub(crate) fn ts_param(s: &Session, p: &Value, cmd: &str) -> Result<usize> {
match u64p(p, "ts") {
Some(t) if (t as usize) < s.set_count() => Ok(t as usize),
Some(t) => Err(bad(cmd, format!("no texture set {t}"))),
None => Ok(s.ts()),
if p.get("ts").is_none_or(Value::is_null) {
return Ok(s.ts());
}
let index = u64p(p, "ts").ok_or_else(|| bad(cmd, "valid `ts` index required"))?;
usize::try_from(index).ok().filter(|&index| index < s.set_count()).ok_or_else(|| bad(cmd, format!("no texture set {index}")))
}
fn select(s: &mut Session, p: &Value) -> Result<Value> {
let ts = u64p(p, "ts")
.map(|index| index as usize)
.filter(|index| *index < s.set_count())
.ok_or_else(|| bad("textureSet.select", "valid `ts` index required"))?;
let cmd = "textureSet.select";
if p.get("ts").is_none_or(Value::is_null) {
return Err(bad(cmd, "valid `ts` index required"));
}
let ts = ts_param(s, p, cmd)?;
select_set(s, ts)?;
Ok(json!({ "ts": ts }))
}
@@ -104,8 +133,12 @@ pub(crate) fn select_set(s: &mut Session, ts: usize) -> Result<()> {
fn resolution(s: &mut Session, p: &Value) -> Result<Value> {
let ts = ts_param(s, p, "textureSet.resolution")?;
let r = u64p(p, "resolution").ok_or_else(|| bad("textureSet.resolution", "`resolution` is required"))?;
let task = s.resize_task(ts, u32::try_from(r).unwrap_or(0))?;
let width = u64p(p, "resolution").ok_or_else(|| bad("textureSet.resolution", "`resolution` is required"))?;
let height = match p.get("height") {
None | Some(Value::Null) => width,
Some(_) => u64p(p, "height").ok_or_else(|| bad("textureSet.resolution", "`height` must be a number of texels"))?,
};
let task = s.resize_task_to(ts, u32::try_from(width).unwrap_or(0), u32::try_from(height).unwrap_or(0))?;
let out = task.run(&texturecraft_bake::Progress::new())?;
s.apply_resize(out)
}
@@ -116,9 +149,11 @@ fn resolution(s: &mut Session, p: &Value) -> Result<Value> {
pub struct ResizeTask {
ts: usize,
resolution: u32,
height: u32,
doc: Document,
mesh: Arc<Mesh>,
/// The session's revision and mesh when the task was made: the result applies only to them.
project_id: u64,
/// The revision and mesh used to calculate this result.
from: (u64, u64),
}
@@ -126,10 +161,12 @@ pub struct ResizeTask {
pub struct ResizeOutput {
ts: usize,
resolution: u32,
height: u32,
doc: Document,
/// The set's new caches (None when its UV tile layout moved: the session rebuilds them).
cache: Option<SetCache>,
log: crate::log::SessionLog,
project_id: u64,
from: (u64, u64),
}
@@ -148,10 +185,14 @@ impl ResizeTask {
mut accelerate: impl FnMut(&texturecraft_texel::TileImage, (u32, u32), &[u16]) -> Option<std::result::Result<texturecraft_texel::TileImage, String>>,
) -> Result<ResizeOutput> {
let start = Instant::now();
let ResizeTask { ts, resolution, mut doc, mesh, from } = self;
let ResizeTask { ts, resolution, height, mut doc, mesh, project_id, from } = self;
let set = doc.project.texture_set_mut(ts)?;
let old = set.clone();
set.resolution = resolution;
set.set_size(resolution, height);
if set.resolution_height.is_some() && !set.tile_resolutions.is_empty() {
return Err(bad("textureSet.resolution", "a texture set whose UV tiles have their own sizes stays square"));
}
crate::session::check_size(set)?;
let size = set.size();
let mut log = crate::log::SessionLog::new();
@@ -166,6 +207,7 @@ impl ResizeTask {
if cancelled() {
return image.clone();
}
if old.uv_tiles.is_empty() && image.allocated_count() > 0 && (image.width(), image.height()) != size {
let submitted = Instant::now();
if let Some(result) = accelerate(image, size, empty) {
@@ -175,6 +217,7 @@ impl ResizeTask {
gpu_images += 1;
return resized;
}
Err(reason) => {
fallback.get_or_insert(reason);
}
@@ -189,6 +232,7 @@ impl ResizeTask {
if cancelled() {
return Err(crate::EngineError::Other("Texture set resize was cancelled".into()));
}
progress.done.store(3_000, std::sync::atomic::Ordering::Relaxed);
let resampled = Instant::now();
let set = doc.project.texture_set(ts)?;
@@ -198,48 +242,70 @@ impl ResizeTask {
log.performance(format!("GPU paint resize used CPU fallback: {reason}"));
}
log.performance(format!(
"Resize of texture set {} from {} to {}: paint resampling {} ms (GPU {} images in {} ms including transfers), CPU UV cache {}",
"Resize of texture set {} from {} × {} to {} × {}: paint resampling {} ms (GPU {} images in {} ms including transfers), CPU UV cache {}",
ts + 1,
old.resolution,
old.height(),
resolution,
height,
resampled.duration_since(start).as_millis(),
gpu_images,
gpu_ms,
if cache.is_some() { format!("{} ms", resampled.elapsed().as_millis()) } else { "rebuilt on apply".into() }
));
Ok(ResizeOutput { ts, resolution, doc, cache, log, from })
Ok(ResizeOutput { ts, resolution, height, doc, cache, log, project_id, from })
}
}
impl ResizeOutput {
/// The texture set and resolution this resize is for.
pub fn target(&self) -> (usize, u32) {
(self.ts, self.resolution)
/// The texture set and requested width and height.
pub fn target(&self) -> (usize, u32, u32) {
(self.ts, self.resolution, self.height)
}
pub fn matches_session(&self, session: &Session) -> bool {
self.from == (session.revision, session.mesh_id) && !session.stroke_active()
self.project_id == session.project_id && self.from == (session.revision, session.mesh_id) && !session.stroke_active()
}
}
impl Session {
/// Prepare resizing texture set `ts` to `resolution` (a power of two, 128..8192).
/// Prepare resizing texture set `ts` to a square `resolution` (a power of two, 128..8192)
pub fn resize_task(&mut self, ts: usize, resolution: u32) -> Result<ResizeTask> {
let resolution = check_resolution(resolution)?;
self.doc.project.texture_set(ts)?;
self.cancel_stroke();
Ok(ResizeTask { ts, resolution, doc: self.doc.clone(), mesh: self.mesh.clone(), from: (self.revision, self.mesh_id) })
self.resize_task_to(ts, resolution, resolution)
}
/// Apply a finished resize as one undo step. When the document changed while it ran, the
/// resize runs again here on the current document.
pub fn apply_resize(&mut self, out: ResizeOutput) -> Result<Value> {
if !out.matches_session(self) {
let task = self.resize_task(out.ts, out.resolution)?;
return self.apply_resize(task.run(&texturecraft_bake::Progress::new())?);
/// Prepare resizing texture set `ts` to `width × height` texels (powers of two, 128..8192)
pub fn resize_task_to(&mut self, ts: usize, width: u32, height: u32) -> Result<ResizeTask> {
let (resolution, height) = (check_resolution(width)?, check_resolution(height)?);
self.doc.project.texture_set(ts)?;
self.cancel_stroke();
Ok(ResizeTask {
ts,
resolution,
height,
doc: self.doc.clone(),
mesh: self.mesh.clone(),
project_id: self.project_id,
from: (self.revision, self.mesh_id),
})
}
/// Apply a finished resize to its original project as one undo step. Edits made while the
/// resize ran are preserved by recomputing from the current document.
pub fn apply_resize(&mut self, mut out: ResizeOutput) -> Result<Value> {
if out.project_id != self.project_id {
return Err(bad("textureSet.resolution", "the project changed while the texture set was resizing"));
}
let ResizeOutput { ts, resolution, doc, cache, log, .. } = out;
if out.from != (self.revision, self.mesh_id) || self.stroke_active() {
let (ts, width, height) = (out.ts, out.resolution, out.height);
// Release the stale pixels and cache before building their replacement
drop(out);
out = self.resize_task_to(ts, width, height)?.run(&texturecraft_bake::Progress::new())?;
}
let ResizeOutput { ts, resolution, height, doc, cache, log, .. } = out;
let before = std::mem::replace(&mut self.doc, doc);
// Install the new caches before adding history to avoid rebuilding them
@@ -254,7 +320,7 @@ impl Session {
}
self.log.append(log);
self.push_history("Texture set size", before);
Ok(json!({ "ts": ts, "resolution": resolution }))
Ok(json!({ "ts": ts, "resolution": resolution, "height": height }))
}
}
@@ -274,15 +340,82 @@ fn channel(s: &mut Session, p: &Value, add: bool) -> Result<Value> {
Ok(Value::Null)
}
/// Add and remove several channels in one undo step, on one texture set or on all of them
fn channels(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "textureSet.channels";
let list = |key: &str| -> Result<Vec<Channel>> {
match p.get(key) {
None | Some(Value::Null) => Ok(Vec::new()),
Some(Value::Array(items)) => items
.iter()
.map(|item| {
let name = item.as_str().ok_or_else(|| bad(cmd, format!("`{key}` lists channel names")))?;
Channel::parse(name).ok_or_else(|| bad(cmd, format!("unknown channel `{name}`")))
})
.collect(),
Some(_) => Err(bad(cmd, format!("`{key}` must be a list of channels"))),
}
};
let add = list("add")?;
let remove = list("remove")?;
if remove.contains(&Channel::BaseColor) {
return Err(bad(cmd, "base color can't be removed"));
}
if let Some(both) = add.iter().find(|c| remove.contains(c)) {
return Err(bad(cmd, format!("{} is both added and removed", both.label())));
}
let all_sets = match p.get("allSets") {
None | Some(Value::Null) => false,
Some(value) => value.as_bool().ok_or_else(|| bad(cmd, "`allSets` must be a boolean"))?,
};
let sets: Vec<usize> = if all_sets { (0..s.set_count()).collect() } else { vec![ts_param(s, p, cmd)?] };
s.edit("Add or remove channels", |s| {
for &ts in &sets {
// A channel the set already has keeps its layers' channel switches
for &c in &add {
if !s.doc.project.texture_set(ts)?.has_channel(c) {
add_channel(s, ts, c)?;
}
}
s.doc.project.texture_set_mut(ts)?.channels.retain(|(c, _)| !remove.contains(c));
}
Ok(())
})?;
Ok(json!({ "ts": sets }))
}
/// Store a channel in another format; layer data keeps its precision, so a wider format brings back what was painted
fn channel_format(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "textureSet.channel.format";
let ts = ts_param(s, p, cmd)?;
let c = channel_param(cmd, p, "channel")?.ok_or_else(|| bad(cmd, "`channel` is required"))?;
let name = strp(p, "format").ok_or_else(|| bad(cmd, "`format` is required"))?;
let all = || ChannelFormat::ALL.map(ChannelFormat::label).join(", ");
let format = ChannelFormat::parse(name).ok_or_else(|| bad(cmd, format!("unknown format {name:?} ({})", all())))?;
s.edit("Channel format", |s| {
if s.doc.project.texture_set_mut(ts)?.set_channel_format(c, format) {
Ok(())
} else {
Err(bad(cmd, format!("the texture set has no {} channel", c.label())))
}
})?;
let float = matches!(format, ChannelFormat::L16F | ChannelFormat::Rgb16F | ChannelFormat::L32F | ChannelFormat::Rgb32F);
Ok(if float { json!({"note": "float formats are stored at 16 bits for now, and values stay in the channel's range"}) } else { Value::Null })
}
/// Add channel `c` to texture set `ts` (no-op when present) and enable it on the set's layers.
/// Call inside [`Session::edit`].
pub(crate) fn add_channel(s: &mut Session, ts: usize, c: Channel) -> Result<()> {
let set = s.doc.project.texture_set_mut(ts)?;
if !set.has_channel(c) {
set.channels.push((c, ChannelFormat::default_for(c)));
set.channels.sort_by_key(|(c, _)| c.index());
}
// Existing layers get the new channel enabled.
s.doc.project.texture_set_mut(ts)?.add_channel(c);
let ids: Vec<_> = s.doc.project.walk(ts).into_iter().map(|(id, _)| id).collect();
for id in ids {
if let Ok(l) = s.doc.project.layer_mut(id) {
@@ -321,13 +454,25 @@ fn visibility(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "visible": s.doc.project.texture_sets.iter().map(|t| t.visible).collect::<Vec<_>>() }))
}
/// Longest texture set name and description, in characters
const MAX_NAME_CHARS: usize = 128;
const MAX_DESCRIPTION_CHARS: usize = 4096;
/// Highest height strength a set takes
const MAX_HEIGHT_STRENGTH: f32 = 100.0;
fn rename(s: &mut Session, p: &Value) -> Result<Value> {
let ts = ts_param(s, p, "textureSet.rename")?;
let name = strp(p, "name")
.map(str::trim)
.filter(|n| !n.is_empty() && n.chars().count() <= 128)
.ok_or_else(|| bad("textureSet.rename", "`name` is required"))?
.to_string();
let name = if boolp(p, "reset") == Some(true) {
s.original_set_name(ts).ok_or_else(|| bad("textureSet.rename", "the mesh has no material name for this set"))?.to_string()
} else {
let name = strp(p, "name").map(str::trim).filter(|name| !name.is_empty());
let name = name.ok_or_else(|| bad("textureSet.rename", "`name` or `reset: true` is required"))?;
if name.chars().count() > MAX_NAME_CHARS {
return Err(bad("textureSet.rename", format!("`name` is at most {MAX_NAME_CHARS} characters")));
}
name.to_string()
};
s.edit("Rename texture set", |s| {
s.doc.project.texture_set_mut(ts)?.name = name;
Ok(())
@@ -335,29 +480,184 @@ fn rename(s: &mut Session, p: &Value) -> Result<Value> {
Ok(Value::Null)
}
impl Session {
/// The name set `ts` had when the mesh loaded: its material's name in the mesh
pub fn original_set_name(&self, ts: usize) -> Option<&str> {
let set = self.doc.project.texture_sets.get(ts)?;
self.mesh.materials.get(set.material).map(String::as_str).filter(|name| !name.trim().is_empty())
}
}
fn settings(s: &mut Session, p: &Value) -> Result<Value> {
let ts = ts_param(s, p, "textureSet.settings")?;
let nf = normal_format_param("textureSet.settings", p)?;
let normal_format = normal_format_param("textureSet.settings", p)?;
let normal_mixing = choice_param(p, "normalMixing", "normal mixing", NormalMixing::parse, &NormalMixing::ALL.map(NormalMixing::id))?;
let ao_mixing = choice_param(p, "aoMixing", "ambient occlusion mixing", AoMixing::parse, &AoMixing::ALL.map(AoMixing::id))?;
let height_to_normal =
choice_param(p, "heightToNormal", "height to normal method", HeightToNormalMethod::parse, &HeightToNormalMethod::ALL.map(HeightToNormalMethod::id))?;
let uv_padding = choice_param(p, "uvPadding", "UV padding", UvPaddingMode::parse, &UvPaddingMode::ALL.map(UvPaddingMode::id))?;
s.edit("Texture set settings", |s| {
if let Some(n) = nf {
s.doc.project.normal_format = n;
if let Some(format) = normal_format {
s.doc.project.normal_format = format;
}
let set = s.doc.project.texture_set_mut(ts)?;
if let Some(d) = strp(p, "description") {
set.description = d.chars().take(4096).collect();
if let Some(description) = strp(p, "description") {
set.description = description.chars().take(MAX_DESCRIPTION_CHARS).collect();
}
if let Some(h) = f32p(p, "heightStrength") {
set.height_strength = h.clamp(0.0, 100.0);
if let Some(strength) = f32p(p, "heightStrength") {
set.height_strength = strength.clamp(0.0, MAX_HEIGHT_STRENGTH);
}
if let Some(mixing) = normal_mixing {
set.normal_mixing = mixing;
}
if let Some(mixing) = ao_mixing {
set.ao_mixing = mixing;
}
if let Some(method) = height_to_normal {
set.height_to_normal = method;
}
if let Some(mode) = uv_padding {
set.uv_padding = mode;
}
Ok(())
})?;
Ok(Value::Null)
}
/// The optional setting `key` of `textureSet.settings`, one of `ids`
fn choice_param<T>(p: &Value, key: &str, what: &str, parse: fn(&str) -> Option<T>, ids: &[&str]) -> Result<Option<T>> {
let unknown = |value: &Value| bad("textureSet.settings", format!("unknown {what} {value} ({})", ids.join(" or ")));
match p.get(key) {
None | Some(Value::Null) => Ok(None),
Some(value @ Value::String(id)) => parse(id).map(Some).ok_or_else(|| unknown(value)),
Some(other) => Err(unknown(other)),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn channels_add_and_remove_together_in_one_undo_step_on_every_set() {
let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
let has = |s: &Session, ts: usize, c: Channel| s.doc.project.texture_sets[ts].has_channel(c);
assert!(has(&s, 1, Channel::Height) && !has(&s, 1, Channel::User3));
let edit = json!({"add": ["emissive", "User3"], "remove": ["height"], "allSets": true});
crate::execute(&mut s, "textureSet.channels", &edit).unwrap();
for ts in 0..2 {
assert!(has(&s, ts, Channel::Emissive) && has(&s, ts, Channel::User3) && !has(&s, ts, Channel::Height), "set {ts}");
}
crate::execute(&mut s, "edit.undo", &json!({})).unwrap();
for ts in 0..2 {
assert!(!has(&s, ts, Channel::Emissive) && !has(&s, ts, Channel::User3) && has(&s, ts, Channel::Height), "set {ts}");
}
// Without allSets only the chosen set changes
crate::execute(&mut s, "textureSet.channels", &json!({"ts": 1, "add": ["ior"]})).unwrap();
assert!(has(&s, 1, Channel::Ior) && !has(&s, 0, Channel::Ior));
assert!(crate::execute(&mut s, "textureSet.channels", &json!({"remove": ["baseColor"]})).is_err());
assert!(crate::execute(&mut s, "textureSet.channels", &json!({"add": ["ior"], "remove": ["ior"]})).is_err());
assert!(crate::execute(&mut s, "textureSet.channels", &json!({"add": ["nope"]})).is_err());
}
#[test]
fn channels_applied_to_every_set_keep_the_channels_a_layer_switched_off() {
let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
crate::execute(&mut s, "layer.add.fill", &json!({})).unwrap();
let layer = s.selected_layer().unwrap();
// Switched off, as layer.blend {enabled: false} leaves it
s.doc.project.layer_mut(layer).unwrap().channels.remove(&Channel::Roughness);
let layer_has_roughness = |s: &Session| s.doc.project.layer(layer).is_ok_and(|l| l.channels.contains_key(&Channel::Roughness));
assert!(!layer_has_roughness(&s));
// Apply to all Texture Sets sends every ticked channel, the ones the sets already have too
let ticked: Vec<&str> = s.doc.project.texture_sets[0].channel_list().iter().map(|c| c.id()).chain(["ior"]).collect();
crate::execute(&mut s, "textureSet.channels", &json!({"add": ticked, "allSets": true})).unwrap();
assert!(s.doc.project.texture_sets.iter().all(|set| set.has_channel(Channel::Ior)));
assert!(!layer_has_roughness(&s), "the layer's roughness stays off");
}
#[test]
fn invalid_set_selectors_cannot_edit_the_active_set() {
let mut session = crate::sample_session(128, 64).unwrap();
let before = session.doc.project.texture_sets[session.ts()].clone();
for ts in [json!("0"), json!(-1), json!(1_u64 << 32)] {
let params = json!({"ts": ts, "description": "wrong set"});
assert!(crate::execute(&mut session, "textureSet.settings", &params).is_err(), "{ts}");
assert_eq!(session.doc.project.texture_sets[session.ts()], before);
assert!(crate::execute(&mut session, "textureSet.select", &params).is_err(), "{ts}");
}
let invalid_scope = json!({"add": ["user7"], "allSets": "true"});
assert!(crate::execute(&mut session, "textureSet.channels", &invalid_scope).is_err());
assert_eq!(session.doc.project.texture_sets[session.ts()], before);
}
#[test]
fn malformed_size_and_setting_values_are_refused_and_change_nothing() {
let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
crate::execute(&mut s, "textureSet.resolution", &json!({"ts": 0, "resolution": 256, "height": 128})).unwrap();
let before = s.doc.project.texture_sets[0].clone();
assert!(crate::execute(&mut s, "textureSet.resolution", &json!({"ts": 0, "resolution": 512, "height": "256"})).is_err());
for (key, value) in [("normalMixing", json!(1)), ("aoMixing", json!(true)), ("heightToNormal", json!(["sharp"])), ("uvPadding", json!(2))] {
let mut params = json!({"ts": 0});
params[key] = value.clone();
assert!(crate::execute(&mut s, "textureSet.settings", &params).is_err(), "{key}: {value}");
}
assert_eq!(s.doc.project.texture_sets[0], before);
}
#[test]
fn a_sets_size_formats_and_settings_survive_save_and_reopen() {
let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
crate::execute(&mut s, "textureSet.resolution", &json!({"ts": 1, "resolution": 256, "height": 128})).unwrap();
crate::execute(&mut s, "textureSet.channel.format", &json!({"ts": 1, "channel": "roughness", "format": "L8"})).unwrap();
crate::execute(&mut s, "textureSet.channels", &json!({"ts": 1, "add": ["user7", "coatTangent"]})).unwrap();
let settings =
json!({"ts": 1, "normalMixing": "replace", "aoMixing": "none", "heightToNormal": "sharp", "uvPadding": "2d", "description": "Ünïcode 説明"});
crate::execute(&mut s, "textureSet.settings", &settings).unwrap();
let inspect = |s: &mut Session, ts: usize| crate::execute(s, "textureSet.inspect", &json!({"ts": ts})).unwrap();
let (first, second) = (inspect(&mut s, 0), inspect(&mut s, 1));
let mut back = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap();
for (ts, before) in [(0, first), (1, second)] {
let after = inspect(&mut back, ts);
for key in ["resolution", "height", "size", "channels", "normalMixing", "aoMixing", "heightToNormal", "uvPadding", "description"] {
assert_eq!(after[key], before[key], "set {ts} {key}");
}
}
assert_ne!(inspect(&mut back, 0)["uvPadding"], inspect(&mut back, 1)["uvPadding"], "each set keeps its own settings");
}
#[test]
fn rename_reset_restores_the_mesh_material_name() {
let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
let original = crate::execute(&mut s, "textureSet.inspect", &json!({"ts": 1})).unwrap()["name"].clone();
crate::execute(&mut s, "textureSet.rename", &json!({"ts": 1, "name": "Renamed"})).unwrap();
let inspect = crate::execute(&mut s, "textureSet.inspect", &json!({"ts": 1})).unwrap();
assert_eq!((&inspect["name"], &inspect["originalName"]), (&json!("Renamed"), &original));
crate::execute(&mut s, "textureSet.rename", &json!({"ts": 1, "reset": true})).unwrap();
assert_eq!(crate::execute(&mut s, "textureSet.inspect", &json!({"ts": 1})).unwrap()["name"], original);
assert!(crate::execute(&mut s, "textureSet.rename", &json!({"ts": 1})).is_err());
}
#[test]
fn a_too_long_name_is_refused_for_its_length_not_as_missing() {
let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
let long = "n".repeat(MAX_NAME_CHARS + 1);
let error = crate::execute(&mut s, "textureSet.rename", &json!({"ts": 1, "name": long})).unwrap_err().to_string();
assert!(error.contains("at most") && !error.contains("required"), "{error}");
assert!(crate::execute(&mut s, "textureSet.rename", &json!({"ts": 1, "name": "n".repeat(MAX_NAME_CHARS)})).is_ok());
}
#[test]
fn visibility_shows_hides_inverts_and_solos() {
// The material ball has two texture sets.
@@ -371,4 +671,144 @@ mod tests {
assert_eq!(run(json!({"mode": "showAll"})).unwrap(), json!([true, true]));
assert!(run(json!({"mode": "sideways"})).is_err() && run(json!({"mode": "solo", "ts": 9})).is_err());
}
#[test]
fn normal_mixing_replace_keeps_height_out_of_the_normal_and_undoes() {
let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
let mixing = |s: &Session| crate::inspect::texture_set(s, 0)["normalMixing"].clone();
assert_eq!(mixing(&s), json!("combine"));
crate::execute(&mut s, "textureSet.settings", &json!({"ts": 0, "normalMixing": "replace"})).unwrap();
assert_eq!(mixing(&s), json!("replace"));
assert!(!s.doc.project.texture_sets[0].height_in_normal() && s.doc.project.texture_sets[1].height_in_normal());
assert!(crate::execute(&mut s, "textureSet.settings", &json!({"normalMixing": "blend"})).is_err());
crate::execute(&mut s, "edit.undo", &Value::Null).unwrap();
assert_eq!(mixing(&s), json!("combine"));
}
#[test]
fn height_to_normal_method_is_set_by_command_and_undoes() {
let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
let method = |s: &Session, ts: usize| crate::inspect::texture_set(s, ts)["heightToNormal"].clone();
assert_eq!(method(&s, 0), json!("smooth"));
crate::execute(&mut s, "textureSet.settings", &json!({"ts": 0, "heightToNormal": "sharp"})).unwrap();
assert_eq!((method(&s, 0), method(&s, 1)), (json!("sharp"), json!("smooth")));
assert!(crate::execute(&mut s, "textureSet.settings", &json!({"heightToNormal": "blurry"})).is_err());
crate::execute(&mut s, "edit.undo", &Value::Null).unwrap();
assert_eq!(method(&s, 0), json!("smooth"));
}
#[test]
fn uv_padding_rebuilds_the_viewport_padding_and_undoes() {
// The ball's second set has texels just past its seams at this size
let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 512).unwrap();
let mode = |s: &Session| crate::inspect::texture_set(s, 1)["uvPadding"].clone();
let crosses_seams = |s: &Session| !s.caches[1].dilation.maps().crossed.is_empty();
assert_eq!((mode(&s), crosses_seams(&s)), (json!("3d"), true));
s.update();
crate::execute(&mut s, "textureSet.settings", &json!({"ts": 1, "uvPadding": "2d"})).unwrap();
assert_eq!((mode(&s), crosses_seams(&s)), (json!("2d"), false));
assert!(!s.caches[1].dirty.is_empty(), "the set recomposites with its new padding");
assert!(crate::execute(&mut s, "textureSet.settings", &json!({"uvPadding": "4d"})).is_err());
crate::execute(&mut s, "edit.undo", &Value::Null).unwrap();
assert_eq!((mode(&s), crosses_seams(&s)), (json!("3d"), true));
}
#[test]
fn channel_format_changes_what_the_viewport_holds_and_undoes() {
let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
let format = |s: &Session| {
let channels = crate::inspect::texture_set(s, 0)["channels"].clone();
channels.as_array().and_then(|list| list.iter().find(|entry| entry["channel"] == "roughness")).map(|entry| entry["format"].clone())
};
let roughness = |s: &mut Session| {
s.update();
let img = &s.caches[0].composite.channels[&Channel::Roughness];
let tile = s.caches[0].covered_tiles[0];
img.tile(tile.0, tile.1).map(<[u16]>::to_vec).unwrap_or_default()
};
crate::execute(&mut s, "textureSet.channel.format", &json!({"channel": "roughness", "format": "L16"})).unwrap();
// A roughness off the 8-bit grid, so 8 bits visibly round it
crate::execute(&mut s, "layer.add.fill", &json!({"roughness": 0.3013})).unwrap();
let sixteen = roughness(&mut s);
assert_eq!(format(&s), Some(json!("L16")));
crate::execute(&mut s, "textureSet.channel.format", &json!({"channel": "Roughness", "format": "l8"})).unwrap();
let eight = roughness(&mut s);
assert_eq!(format(&s), Some(json!("L8")));
assert_ne!(eight, sixteen, "the composite holds 8 bits");
let eight_bit_step = u16::MAX / u16::from(u8::MAX);
assert!(eight.iter().all(|v| v % eight_bit_step == 0), "every texel is on an 8-bit step");
let float = crate::execute(&mut s, "textureSet.channel.format", &json!({"channel": "height", "format": "L32F"})).unwrap();
assert!(float["note"].is_string(), "a float format says it holds 16 bits");
crate::execute(&mut s, "edit.undo", &Value::Null).unwrap();
assert!(crate::execute(&mut s, "textureSet.channel.format", &json!({"channel": "roughness", "format": "L4"})).is_err());
assert!(crate::execute(&mut s, "textureSet.channel.format", &json!({"channel": "emissive", "format": "L8"})).is_err());
crate::execute(&mut s, "edit.undo", &Value::Null).unwrap();
assert_eq!((format(&s), roughness(&mut s)), (Some(json!("L16")), sixteen));
}
#[test]
fn channels_added_after_a_format_is_set_keep_16_bits() {
let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
let format = |s: &Session, id: &str| {
let channels = crate::inspect::texture_set(s, 0)["channels"].clone();
channels.as_array().and_then(|list| list.iter().find(|entry| entry["channel"] == id)).map(|entry| entry["format"].clone())
};
crate::execute(&mut s, "textureSet.channel.format", &json!({"ts": 0, "channel": "roughness", "format": "L8"})).unwrap();
crate::execute(&mut s, "textureSet.channel.add", &json!({"ts": 0, "channel": "user3"})).unwrap();
crate::execute(&mut s, "textureSet.channels", &json!({"ts": 0, "add": ["user4"]})).unwrap();
assert_eq!((format(&s, "user3"), format(&s, "user4")), (Some(json!("L16")), Some(json!("L16"))));
assert_eq!(format(&s, "roughness"), Some(json!("L8")), "the set format stays");
}
#[test]
fn ao_mixing_resends_the_set_to_the_viewport_and_undoes() {
let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
s.update();
let _ = (s.take_uploads(0), s.take_uploads(1));
crate::execute(&mut s, "textureSet.settings", &json!({"ts": 0, "aoMixing": "none"})).unwrap();
assert_eq!(crate::inspect::texture_set(&s, 0)["aoMixing"], json!("none"));
assert!(!s.take_uploads(0).is_empty() && s.take_uploads(1).is_empty(), "only the changed set is resent");
assert!(crate::execute(&mut s, "textureSet.settings", &json!({"aoMixing": "screen"})).is_err());
crate::execute(&mut s, "edit.undo", &Value::Null).unwrap();
s.update();
assert_eq!(crate::inspect::texture_set(&s, 0)["aoMixing"], json!("multiply"));
assert!(!s.take_uploads(0).is_empty(), "undo resends the set too");
}
#[test]
fn channels_our_shader_ignores_are_added_marked_and_exported() {
let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
for channel in ["user3", "Displacement", "coat tangent"] {
crate::execute(&mut s, "textureSet.channel.add", &json!({"ts": 0, "channel": channel})).unwrap();
}
let channels = crate::inspect::texture_set(&s, 0)["channels"].clone();
let shaded = |id: &str| channels.as_array().and_then(|list| list.iter().find(|c| c["channel"] == id)).map(|c| c["shaded"].clone());
assert_eq!((shaded("user3"), shaded("displacement"), shaded("coatTangent")), (Some(json!(false)), Some(json!(false)), Some(json!(false))));
assert_eq!(shaded("baseColor"), Some(json!(true)));
let plan = crate::execute(&mut s, "export.plan", &json!({"preset": "Separate maps"})).unwrap();
let files: Vec<(Value, String)> =
plan.as_array().into_iter().flatten().map(|f| (f["ts"].clone(), f["file"].as_str().unwrap_or_default().to_ascii_lowercase())).collect();
for map in ["user3", "displacement", "coattangent"] {
let from = |ts: usize| files.iter().any(|(t, file)| *t == json!(ts) && file.contains(map));
assert!(from(0) && !from(1), "{map} exported only from the set that has it: {files:?}");
}
s.update();
let composite = &s.caches[0].composite;
assert!(composite.channels.contains_key(&Channel::User3) && composite.channels.contains_key(&Channel::CoatTangent));
}
}
+19 -4
View File
@@ -7,7 +7,7 @@ use std::borrow::Cow;
use std::collections::BTreeMap;
use serde_json::{Value, json};
use texturecraft_compose::{Composite, composite_tiles};
use texturecraft_compose::{Composite, PaddingMaps, composite_tiles};
use texturecraft_core::{Channel, LayerId, Project};
use texturecraft_geom::NO_TRI;
use texturecraft_texel::TILE;
@@ -82,9 +82,23 @@ impl Session {
pub(crate) fn document_sample(&self, ts: usize, x: u32, y: u32) -> Option<BTreeMap<Channel, [f32; 3]>> {
let cache = self.caches.get(ts)?;
let needs_padding = cache.gbuf.tri.get((y * cache.size.0 + x) as usize) == Some(&NO_TRI);
let (x, y) = if needs_padding { cache.dilation.source_for_sample(x, y).unwrap_or((x, y)) } else { (x, y) };
let composite = self.read_composite(ts, &[(x / TILE, y / TILE)], false)?;
Some(composite.channels.keys().map(|&channel| (channel, composite.value(channel, x, y))).collect())
let flat = if needs_padding { cache.dilation.source_for_sample(false, x, y).unwrap_or((x, y)) } else { (x, y) };
let across = if needs_padding && cache.dilation.needs_seam_padding() { cache.dilation.source_for_sample(true, x, y).unwrap_or(flat) } else { flat };
let to_tile = |(x, y)| (x / TILE, y / TILE);
let tiles = [to_tile(flat), to_tile(across)];
let count = if tiles[0] == tiles[1] { 1 } else { 2 };
let composite = self.read_composite(ts, &tiles[..count], false)?;
Some(
composite
.channels
.keys()
.map(|&channel| {
let (sx, sy) = if PaddingMaps::crosses_seams(channel) { across } else { flat };
(channel, composite.value(channel, sx, sy))
})
.collect(),
)
}
fn read_composite(&self, ts: usize, tiles: &[(u32, u32)], pad_output: bool) -> Option<Cow<'_, Composite>> {
@@ -93,6 +107,7 @@ impl Session {
if !document_in_solo && cache.dirty.is_empty() && cache.settle.is_empty() {
return Some(Cow::Borrowed(&cache.composite));
}
let pending = if document_in_solo {
Cow::Borrowed(tiles)
} else {
+24
View File
@@ -32,6 +32,8 @@ pub struct ProjectTemplate {
pub normal_format: NormalFormat,
/// Channels of every texture set, with their formats.
pub channels: Vec<(Channel, ChannelFormat)>,
/// Whether the channels hold their formats' precision ([`texturecraft_core::TextureSet::format_precision`]); older templates keep 16 bits
pub format_precision: bool,
/// Shader: PBR specular/glossiness instead of metallic/roughness.
pub spec_gloss: bool,
pub parallax: bool,
@@ -49,6 +51,7 @@ impl Default for ProjectTemplate {
resolution: 2048,
normal_format: NormalFormat::OpenGl,
channels: with_formats(&Channel::DEFAULT_SET),
format_precision: false,
spec_gloss: d.spec_gloss,
parallax: d.parallax,
ior: d.ior,
@@ -208,6 +211,7 @@ impl Session {
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();
set.format_precision = template.format_precision;
}
for (id, _) in project.walk(set_index) {
@@ -304,6 +308,7 @@ fn save(session: &mut Session, params: &Value) -> Result<Value> {
resolution: set.resolution,
normal_format: project.normal_format,
channels: set.channels.clone(),
format_precision: set.format_precision,
spec_gloss: display.spec_gloss,
parallax: display.parallax,
ior: display.ior,
@@ -443,6 +448,25 @@ mod tests {
assert!(execute(&mut s, "project.new", &json!({"template": "nope"})).is_err());
}
#[test]
fn a_template_keeps_the_channel_formats_picked_in_the_set_it_was_saved_from() {
let dir = std::env::temp_dir().join(format!("tc_template_formats_{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
s.load_templates(dir.clone());
execute(&mut s, "textureSet.channel.format", &json!({"channel": "roughness", "format": "L8"})).unwrap();
execute(&mut s, "project.template.save", &json!({"name": "Eight bit roughness"})).unwrap();
let mut fresh = Session::new_project("f", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
fresh.load_templates(dir.clone());
execute(&mut fresh, "project.new", &json!({"template": "Eight bit roughness"})).unwrap();
let held = |session: &Session, channel: Channel| session.doc.project.texture_sets[0].formats().into_iter().find(|(c, _)| *c == channel).map(|(_, f)| f);
assert_eq!(held(&fresh, Channel::Roughness), held(&s, Channel::Roughness));
assert_eq!(held(&fresh, Channel::Metallic), held(&s, Channel::Metallic), "the other channels keep 16 bits");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn save_current_settings_as_template_and_reload() {
let dir = std::env::temp_dir().join(format!("tc_templates_{}", std::process::id()));
+7 -2
View File
@@ -25,6 +25,7 @@ impl Session {
if w == 0 || h == 0 {
return TileDemand::default();
}
let size = Vec2::new(w as f32, h as f32);
let to_tile = |pixel: Vec2| ((pixel.x as u32).min(w - 1) / TILE, (pixel.y as u32).min(h - 1) / TILE);
let brush = self.stroke.as_ref().filter(|s| s.ts == ts && s.target.is_some()).and_then(|s| {
@@ -41,12 +42,15 @@ impl Session {
if !lo.is_finite() || !hi.is_finite() {
return None;
}
let (lo, hi) = (lo.max(Vec2::ZERO), hi.min(Vec2::ONE));
if !lo.cmplt(hi).all() {
return None;
}
let bounds = (to_tile(lo * size), to_tile((hi * size).ceil() - Vec2::ONE));
// A view of the entire atlas benefits from the usual block ordering.
// A view of the entire atlas benefits from the usual block ordering
(bounds != ((0, 0), ((w - 1) / TILE, (h - 1) / TILE))).then_some(bounds)
});
let brush = if self.stroke.is_some() { brush } else { cache.finished_dab.as_ref().and_then(crate::session::ReleasedDab::pending_tile) };
@@ -72,6 +76,7 @@ impl TileDemand {
if limit == 0 || pending.len() <= limit {
return tiles;
}
if let Some((x, y)) = self.brush {
if pending.remove(&(x, y)) {
tiles.push((x, y));
@@ -89,7 +94,7 @@ fn take_rect(pending: &mut BTreeSet<Tile>, lo: Tile, hi: Tile, limit: usize, til
let mut left = lo.0;
let start = tiles.len();
while left <= hi.0 && tiles.len() < limit {
// Seek to the next occupied column, then read only the requested rows in it.
// Seek to the next occupied column, then read only the requested rows in it
let Some(&(x, _)) = pending.range((left, lo.1)..=(hi.0, hi.1)).next() else { break };
tiles.extend(pending.range((x, lo.1)..=(x, hi.1)).take(limit - tiles.len()).copied());
let Some(next) = x.checked_add(1) else { break };
+31 -13
View File
@@ -12,6 +12,12 @@ use crate::fill_mode::FillMode;
use crate::session::{CloneFrom, CloneSource, StackTarget, Tool};
use crate::{Result, Session, cmd};
/// Brush size the UI's full size slider stands for
const MAX_BRUSH_SIZE: f32 = 0.25;
/// Full value of the UI's 0–100 brush scales
const PERCENT: f32 = 100.0;
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!("tool.paint", "Paint", ["Tools"], Some("1"), "{}", always, |s, _| set_tool(s, Tool::Paint)),
@@ -36,7 +42,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Brush settings",
[],
None,
"{size?: 0..100, flow?: 0..100, opacity?: 0..100, spacing?: 1..1000, hardness?: 0..100, angle?, followPath?, alignment?: tangent|camera, lazy?, jitterSize?, jitterAngle?, jitterFlow?, jitterPosition?, alpha?: procedural name | {image: resource name} | {library: id (alpha.list)}, alphaSizeX?: 5..100 and alphaSizeY?: 5..100 (percent of the stamp the alpha fills), alphaRoundness?: 0..100 (Round alpha only: 100 circle, 0 square), alphaContrast?: 1..8, alphaInvert?, backfaceCulling?, symmetryOn? (the toolbar toggle; off keeps the settings), symmetryX?, symmetryY?, symmetryZ?, symmetryRadial?: 0..32 copies around symmetryAxis?: x|y|z (default y), symmetryOffset?: [x, y, z] (world units from the mesh center, where the mirror planes and radial axis cross), symmetryAngleSpan?: 0..360 degrees the radial copies spread over, minSize?, smudgeStrength?: 0..100, cloneSource?: composite|layer (what the Clone tool copies), cloneAligned? (default true: the first stroke fixes the offset to the source for the following strokes; false: every stroke starts sampling at the source point), particles?: {enabled?, count?: 1..16, lifetime?: 1..128 steps, gravity?: 0..2}}",
"{size?: 0..100, flow?: 0..100, opacity?: 0..100, spacing?: 1..1000, hardness?: 0..100, angle?, followPath?, alignment?: tangent|camera, lazy?, jitterSize?, jitterAngle?, jitterFlow?, jitterPosition?, alpha?: procedural name | {image: resource name} | {library: id (alpha.list)}, alphaSizeX?: 5..100 and alphaSizeY?: 5..100 (percent of the stamp the alpha fills), alphaRoundness?: 0..100 (Round alpha only: 100 circle, 0 square), alphaContrast?: 1..8, alphaInvert?, backfaceCulling?, angleFade?: [from, to] degrees 0..90 (culled faces fade out between them), screenSpace? (the size follows the view), stampDepth?: 0.05..4, symmetryOn? (the toolbar toggle; off keeps the settings), symmetryX?, symmetryY?, symmetryZ?, symmetryRadial?: 0..32 copies around symmetryAxis?: x|y|z (default y), symmetryOffset?: [x, y, z] (world units from the mesh center, where the mirror planes and radial axis cross), symmetryAngleSpan?: 0..360 degrees the radial copies spread over, minSize?, sizePressure? (default true: pen pressure shrinks the size towards minSize), smudgeStrength?: 0..100, cloneSource?: composite|layer (what the Clone tool copies), cloneAligned? (default true: the first stroke fixes the offset to the source for the following strokes; false: every stroke starts sampling at the source point), particles?: {enabled?, count?: 1..16, lifetime?: 1..128 steps, gravity?: 0..2}}",
always,
brush
),
@@ -64,7 +70,7 @@ pub fn specs() -> Vec<CommandSpec> {
),
cmd!(
"tool.stencil",
"Projection stencil",
"Stencil",
[],
None,
"{image?: resource name, center?: [x,y] NDC, scale?: 0.01..10, rotation?: degrees, tile?, opacity?, clear?: bool}",
@@ -132,14 +138,17 @@ fn select(s: &mut Session, p: &Value) -> Result<Value> {
/// Brush values use the UI's 0–100 scales, so agents and the sliders speak the same numbers
fn brush(session: &mut Session, params: &Value) -> Result<Value> {
let mut settings = session.tool.brush.clone();
let percent = |key: &str| f32p(params, key).map(|value| value / 100.0);
let percent = |key: &str| f32p(params, key).map(|value| value / PERCENT);
if let Some(value) = percent("size") {
settings.size = value * 0.25;
settings.size = value * MAX_BRUSH_SIZE;
}
if let Some(value) = percent("minSize") {
settings.min_size = value;
}
if let Some(value) = boolp(params, "sizePressure") {
settings.size_pressure = value;
}
if let Some(value) = percent("flow") {
settings.flow = value;
@@ -174,11 +183,11 @@ fn brush(session: &mut Session, params: &Value) -> Result<Value> {
for (key, slot) in [("jitterSize", &mut settings.jitter_size), ("jitterAngle", &mut settings.jitter_angle), ("jitterFlow", &mut settings.jitter_flow)] {
if let Some(value) = f32p(params, key) {
*slot = value / 100.0;
*slot = value / PERCENT;
}
}
if let Some(value) = f32p(params, "jitterPosition") {
settings.jitter_position = value / 100.0;
settings.jitter_position = value / PERCENT;
}
let alpha = params.get("alpha");
@@ -215,6 +224,13 @@ fn brush(session: &mut Session, params: &Value) -> Result<Value> {
if let Some(value) = boolp(params, "backfaceCulling") {
settings.backface_culling = value;
}
if params.get("angleFade").is_some() {
let [from, to] = pair(params, "angleFade").ok_or_else(|| bad("tool.brush", "`angleFade` must be [from, to] in degrees"))?;
settings.angle_fade = (from, to);
}
if let Some(value) = f32p(params, "stampDepth") {
settings.depth = value;
}
if let Some(value) = boolp(params, "symmetryOn") {
settings.symmetry.enabled = value;
@@ -282,30 +298,32 @@ fn brush(session: &mut Session, params: &Value) -> Result<Value> {
}
}
if let Some(value) = f32p(params, "smudgeStrength") {
session.tool.smudge_strength = (value / 100.0).clamp(0.0, 1.0);
session.tool.smudge_strength = (value / PERCENT).clamp(0.0, 1.0);
}
session.revision = session.revision.wrapping_add(1);
Ok(brush_json(session))
}
/// The brush settings `tool.brush` reports, on the UI's 0–100 scales
pub(crate) fn brush_json(session: &Session) -> Value {
let settings = &session.tool.brush;
json!({
"size": settings.size / 0.25 * 100.0, "minSize": settings.min_size * 100.0, "flow": settings.flow * 100.0, "opacity": settings.opacity * 100.0,
"spacing": settings.spacing * 100.0, "hardness": settings.hardness * 100.0, "angle": settings.angle, "followPath": settings.follow_path,
"size": settings.size / MAX_BRUSH_SIZE * PERCENT, "minSize": settings.min_size * PERCENT, "sizePressure": settings.size_pressure, "flow": settings.flow * PERCENT, "opacity": settings.opacity * PERCENT,
"spacing": settings.spacing * PERCENT, "hardness": settings.hardness * PERCENT, "angle": settings.angle, "followPath": settings.follow_path,
"alignment": format!("{:?}", settings.alignment).to_lowercase(), "lazy": settings.lazy,
"alpha": match (&settings.alpha_image, &settings.alpha_library) {
(Some(name), _) => json!({ "image": name }),
(None, Some(id)) => json!({ "library": id }),
(None, None) => json!(settings.alpha.label()),
},
"alphaSizeX": settings.alpha_params.size_x * 100.0, "alphaSizeY": settings.alpha_params.size_y * 100.0,
"alphaRoundness": settings.alpha_params.roundness * 100.0, "alphaContrast": settings.alpha_params.contrast, "alphaInvert": settings.alpha_params.invert,
"backfaceCulling": settings.backface_culling, "symmetry": [settings.symmetry.x, settings.symmetry.y, settings.symmetry.z],
"alphaSizeX": settings.alpha_params.size_x * PERCENT, "alphaSizeY": settings.alpha_params.size_y * PERCENT,
"alphaRoundness": settings.alpha_params.roundness * PERCENT, "alphaContrast": settings.alpha_params.contrast, "alphaInvert": settings.alpha_params.invert,
"backfaceCulling": settings.backface_culling, "angleFade": [settings.angle_fade.0, settings.angle_fade.1], "screenSpace": settings.screen_space,
"stampDepth": settings.depth, "symmetry": [settings.symmetry.x, settings.symmetry.y, settings.symmetry.z],
"radialSymmetry": { "copies": settings.symmetry.radial, "axis": (["x", "y", "z"].get(settings.symmetry.axis as usize)) },
"symmetryOffset": settings.symmetry.offset, "symmetryOn": settings.symmetry.enabled, "symmetryAngleSpan": settings.symmetry.angle_span,
"material": session.tool.material, "smudgeStrength": session.tool.smudge_strength * 100.0, "particles": settings.particles,
"material": session.tool.material, "smudgeStrength": session.tool.smudge_strength * PERCENT, "particles": settings.particles,
"cloneSource": if session.tool.clone_from == CloneFrom::Layer { "layer" } else { "composite" },
"cloneAligned": session.tool.clone_aligned,
})
+37 -2
View File
@@ -50,6 +50,10 @@ fn tile_resolution(session: &mut Session, params: &Value) -> Result<Value> {
return Err(bad(COMMAND, format!("texture set \"{}\" has no UV tile {tile} (tiles: {:?})", texture_set.name, texture_set.uv_tiles)));
}
if texture_set.resolution_height.is_some() && resolution != texture_set.resolution {
return Err(bad(COMMAND, format!("UV tiles of a non-square texture set (\"{}\") can't have their own size", texture_set.name)));
}
let removes_override = resolution == texture_set.resolution && texture_set.tile_resolutions.contains_key(&tile);
if texture_set.tile_resolution(tile) == resolution && !removes_override {
return Ok(json!({ "ts": texture_set_index, "tile": tile, "resolution": resolution, "size": texture_set.size() }));
@@ -299,6 +303,11 @@ mod tests {
}
}
/// Width and height of a PNG file, read from its header
fn png_size(bytes: &[u8]) -> (u32, u32) {
image::ImageReader::with_format(std::io::Cursor::new(bytes), image::ImageFormat::Png).into_dimensions().unwrap()
}
/// Mean painted alpha over the covered texels of the set's current layout.
fn painted_fraction(s: &Session) -> f64 {
let id = s.doc.project.texture_sets[0].stack[0];
@@ -374,8 +383,6 @@ mod tests {
execute(&mut s, "textureSet.tile.resolution", &json!({"tile": 1002, "resolution": 128})).unwrap();
let opts = crate::file_cmds::export_options(&s, &json!({"preset": "Document channels + Normal + AO", "format": "png"}), "t").unwrap();
let files = s.export_files(&[0], &opts).unwrap();
// PNG: width and height are the big-endian words after the IHDR tag.
let png_size = |b: &[u8]| (u32::from_be_bytes(b[16..20].try_into().unwrap()), u32::from_be_bytes(b[20..24].try_into().unwrap()));
assert!(files.len() >= 4);
for f in &files {
let want = if f.name.contains("1002") { 128 } else { 256 };
@@ -383,6 +390,34 @@ mod tests {
}
}
#[test]
fn non_square_sets_keep_their_paint_export_wide_tiles_and_refuse_tile_sizes() {
let mut s = udim_session();
paint_all(&mut s, 50000);
execute(&mut s, "textureSet.resolution", &json!({"resolution": 256, "height": 128})).unwrap();
s.update();
let (w, h) = s.doc.project.texture_sets[0].size();
assert!(w > 2 * h, "two tiles side by side, each wider than tall: {:?}", (w, h));
assert_eq!((s.caches[0].gbuf.width, s.caches[0].gbuf.height), (w, h));
assert!(painted_fraction(&s) > 0.97);
let inspect = execute(&mut s, "textureSet.inspect", &json!({})).unwrap();
assert!(inspect["height"].as_u64() < inspect["resolution"].as_u64());
let opts = crate::file_cmds::export_options(&s, &json!({"preset": "Document channels + Normal + AO", "format": "png"}), "t").unwrap();
for f in &s.export_files(&[0], &opts).unwrap() {
let (fw, fh) = png_size(&f.bytes);
assert!(fw > fh, "{} is {fw}x{fh}", f.name);
}
assert!(execute(&mut s, "textureSet.tile.resolution", &json!({"tile": 1002, "resolution": 128})).is_err());
s.undo().unwrap();
assert_eq!(s.doc.project.texture_sets[0].size(), (512, 256));
// A set whose tiles have their own sizes stays square
execute(&mut s, "textureSet.tile.resolution", &json!({"tile": 1002, "resolution": 128})).unwrap();
assert!(execute(&mut s, "textureSet.resolution", &json!({"resolution": 256, "height": 128})).is_err());
}
/// Paint channel `c` of the first layer over every covered texel as `f(u)`, `u` the texel's
/// position across its own UV tile (0..1), so every tile shows the same pattern in UV space.
fn paint_across_tiles(s: &mut Session, c: Channel, f: impl Fn(f32) -> Vec<u16>) {
+18 -3
View File
@@ -42,7 +42,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Set view mode",
[],
None,
"{mode: material|uvChecker|normalHeightMesh (the normal the shading uses: mesh normal, Height channel slope and Normal channel; 2D view: the tangent-space normal)|image (an image resource shown as it is on the mesh and in the 2D view)|mask|<channel id>|map:<mesh map id>, image? (the resource, for image), layer? (for mask)}",
"{mode: material|uvChecker|normalHeightMesh (the normal the shading uses: mesh normal, Height channel slope and Normal channel; 2D view: the tangent-space normal)|image (an image resource shown as it is on the mesh and in the 2D view)|mask|<shaded channel id>|map:<mesh map id>, image? (the resource, for image), layer? (for mask)}",
always,
view
),
@@ -161,7 +161,7 @@ fn set_view(s: &mut Session, v: ViewMode) -> Result<Value> {
/// C and Shift+C: the set's channels, then "Normal+height+mesh", then round again
fn cycle_channel(s: &mut Session, d: i64) -> Result<Value> {
let mut views: Vec<ViewMode> = s.doc.project.texture_set(s.ts()).map(|t| t.channel_list()).unwrap_or_default().into_iter().map(ViewMode::Channel).collect();
let mut views: Vec<_> = s.doc.project.texture_sets.get(s.ts()).into_iter().flat_map(|set| set.viewport_channels()).map(ViewMode::Channel).collect();
if views.is_empty() {
return set_view(s, ViewMode::Material);
}
@@ -217,7 +217,14 @@ fn view(s: &mut Session, p: &Value) -> Result<Value> {
}
_ => match m.strip_prefix("map:") {
Some(id) => ViewMode::MeshMap(BakedMap::parse(id).ok_or_else(|| bad("viewport.view", format!("unknown mesh map `{id}`")))?),
None => ViewMode::Channel(Channel::parse(m).ok_or_else(|| bad("viewport.view", format!("unknown view mode `{m}`")))?),
None => {
let channel = Channel::parse(m).ok_or_else(|| bad("viewport.view", format!("unknown view mode `{m}`")))?;
if !channel.is_shaded() {
return Err(bad("viewport.view", format!("{} is stored for export and has no viewport view", channel.label())));
}
ViewMode::Channel(channel)
}
},
};
set_view(s, v)
@@ -501,14 +508,22 @@ mod tests {
assert!(channels.len() > 2);
assert_eq!(s.view, ViewMode::Material);
execute(&mut s, "textureSet.channel.add", &json!({"channel": "user31"})).unwrap();
let result = execute(&mut s, "viewport.view", &json!({"mode": "user31"}));
assert!(result.is_err(), "the viewport cannot display an export-only channel");
assert_eq!(s.view, ViewMode::Material);
// From the material C starts at the first channel
let mut seen = Vec::new();
for _ in 0..channels.len() + 2 {
seen.push(pressed(&mut s, "viewport.nextChannel"));
}
let mut expected = channels.clone();
expected.push(ViewMode::NormalHeightMesh);
expected.push(channels[0]);
assert_eq!(seen, expected, "channels, then Normal+height+mesh, then round again");
// Shift+C walks it backwards, and from the material starts at the last entry
+36 -1
View File
@@ -1,7 +1,7 @@
//! The layer toolbar's Add mask items that add a mask with an effect in it, and Add effect's colour selection: one undo step each, the new effect selected
use serde_json::{Value, json};
use texturecraft_engine::core::{Channel, CompareSource, EffectKind, LayerId, MaskBackground, Source};
use texturecraft_engine::core::{BlendMode, Channel, CompareSource, EffectKind, LayerId, MaskBackground, Source};
use texturecraft_engine::fill_alpha::resource_name;
use texturecraft_engine::geom::primitives;
use texturecraft_engine::paint::alphas;
@@ -75,6 +75,41 @@ fn a_height_combination_is_a_mask_comparing_this_layers_height_with_the_layers_b
assert_eq!(s.history_labels().last().map(String::as_str), Some("Add mask with height combination"));
}
#[test]
fn a_height_combination_makes_the_layers_height_blend_normal_in_the_same_step() {
let (mut s, layer) = fill();
execute(&mut s, "layer.blend", &json!({"layer": layer.0, "channel": "height", "enabled": true, "mode": "linearDodge"})).unwrap();
let height_mode = |s: &Session| s.doc.project.layer(layer).unwrap().channels.get(&Channel::Height).map(|blend| blend.mode);
let before = height_mode(&s);
assert!(before.is_some_and(|mode| mode != BlendMode::Normal), "the height starts out blending another way");
execute(&mut s, "mask.add.heightCombination", &json!({"layer": layer.0})).unwrap();
assert_eq!(height_mode(&s), Some(BlendMode::Normal));
execute(&mut s, "edit.undo", &Value::Null).unwrap();
assert_eq!(height_mode(&s), before, "one undo takes the mask and the blend back");
}
#[test]
fn an_instances_height_combination_sets_its_shared_height_blend_and_owns_its_mask() {
let (mut session, source) = fill();
execute(&mut session, "layer.blend", &json!({"layer": source.0, "channel": "height", "enabled": true, "mode": "linearDodge"})).unwrap();
let instance = execute(&mut session, "layer.instance", &json!({"layer": source.0})).unwrap()["layer"].as_u64().map(LayerId).unwrap();
let original_height_mode = session.doc.project.layer(source).unwrap().blend(Channel::Height).unwrap().mode;
execute(&mut session, "mask.add.heightCombination", &json!({"layer": instance.0})).unwrap();
let source_layer = session.doc.project.layer(source).unwrap();
assert_eq!(source_layer.blend(Channel::Height).unwrap().mode, BlendMode::Normal);
assert!(source_layer.mask.is_none(), "the source keeps its own mask state");
assert!(session.doc.project.layer(instance).unwrap().mask.is_some());
execute(&mut session, "edit.undo", &Value::Null).unwrap();
assert_eq!(session.doc.project.layer(source).unwrap().blend(Channel::Height).unwrap().mode, original_height_mode);
assert!(session.doc.project.layer(instance).unwrap().mask.is_none());
}
#[test]
fn color_selections_go_in_the_mask_and_are_selected() {
let (mut s, layer) = fill();
+6 -3
View File
@@ -2,7 +2,7 @@ use std::sync::Arc;
use serde_json::json;
use texturecraft_engine::bake::Progress;
use texturecraft_engine::core::BakedMap;
use texturecraft_engine::core::{AoMixing, BakedMap};
use texturecraft_engine::geom::{NO_TRI, UvGBuffer, primitives};
use texturecraft_engine::{Session, execute};
@@ -103,8 +103,11 @@ fn imported_mesh_maps_display_and_export_the_entire_overridden_tile() {
let map = BakedMap::AmbientOcclusion;
assert!((baked.scalar(map, 248, 120, (256, 128)).unwrap() - 240.0 / 255.0).abs() < 0.001);
let composite = &session.caches[0].composite;
let display = tile_bytes(composite, baked, DisplayKind::Orm, 5, 1);
assert_eq!(display[((56 * 64 + 56) * 4) as usize], 240, "the viewport samples the far corner of the smaller working tile");
let corner = ((56 * 64 + 56) * 4) as usize;
let display = tile_bytes(composite, baked, AoMixing::Multiply, DisplayKind::Orm, 5, 1);
assert_eq!(display[corner], 240, "the viewport samples the far corner of the smaller working tile");
let unmixed = tile_bytes(composite, baked, AoMixing::None, DisplayKind::Orm, 5, 1);
assert!(unmixed[corner] > display[corner], "ambient occlusion mixing None leaves the baked map out of the viewport");
let options = ExportOptions::new(ExportPreset {
name: "Bake detail".into(),
+72
View File
@@ -691,3 +691,75 @@ fn a_color_histogram_has_its_components_and_luminance() {
assert_eq!(counts(&histogram["bins"]), vec![2 * texels, 0, 0, texels]);
assert!(roughness.get("components").is_none(), "one value has no components");
}
#[test]
fn a_named_effect_moves_up_and_down_while_its_layer_content_is_selected() {
let mut s = session();
let layer = LayerId(id(execute(&mut s, "layer.add.fill", &Value::Null).unwrap(), "layer"));
let add = |s: &mut Session| id(execute(s, "effect.add.filter", &json!({"target": "content", "filter": "invert"})).unwrap(), "effect");
let (bottom, top) = (add(&mut s), add(&mut s));
let order = |s: &Session| s.doc.project.layers[&layer].content_effects.iter().map(|e| e.id.0).collect::<Vec<_>>();
execute(&mut s, "layer.select", &json!({"layer": layer.0})).unwrap();
s.target = StackTarget::Content;
execute(&mut s, "effect.moveUp", &json!({"effect": bottom})).unwrap();
assert_eq!(order(&s), [top, bottom]);
execute(&mut s, "effect.moveDown", &json!({"effect": bottom})).unwrap();
assert_eq!(order(&s), [bottom, top]);
}
#[test]
fn a_malformed_named_effect_does_not_move_the_selected_effect() {
let mut session = session();
let layer = id(execute(&mut session, "layer.add.fill", &Value::Null).unwrap(), "layer");
let add = |session: &mut Session| id(execute(session, "effect.add.filter", &json!({"target": "content", "filter": "invert"})).unwrap(), "effect");
let (bottom, _) = (add(&mut session), add(&mut session));
execute(&mut session, "layer.select", &json!({"layer": layer, "target": bottom})).unwrap();
let before = session.doc.project.clone();
let result = execute(&mut session, "effect.moveUp", &json!({"effect": "invalid"}));
assert!(result.unwrap_err().to_string().contains("must be an effect id"));
assert_eq!(session.doc.project, before);
}
#[test]
fn copying_a_named_effects_blending_preserves_an_anchor_selection() {
let mut session = session();
let layer = id(execute(&mut session, "layer.add.fill", &Value::Null).unwrap(), "layer");
let filter = id(execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert"})).unwrap(), "effect");
let anchor = id(execute(&mut session, "effect.add.anchor", &json!({"layer": layer})).unwrap(), "effect");
execute(&mut session, "layer.select", &json!({"layer": layer, "target": anchor})).unwrap();
let selection = session.selected_layer();
execute(&mut session, "effect.blending.copy", &json!({"effect": filter})).unwrap();
assert!(session.blending_clipboard.is_some(), "the command copies the named filter's blending");
assert_eq!(session.target, StackTarget::Effect(LayerId(anchor)));
assert_eq!(session.selected_layer(), selection);
}
#[test]
fn successive_effect_steps_can_share_one_undo_step() {
let mut session = session();
let layer = LayerId(id(execute(&mut session, "layer.add.fill", &Value::Null).unwrap(), "layer"));
let add = |session: &mut Session| id(execute(session, "effect.add.filter", &json!({"target": "content", "filter": "invert"})).unwrap(), "effect");
let (bottom, middle, top) = (add(&mut session), add(&mut session), add(&mut session));
let order = |session: &Session| session.doc.project.layers[&layer].content_effects.iter().map(|effect| effect.id.0).collect::<Vec<_>>();
let steps_before = session.history_labels().len();
execute(&mut session, "effect.moveUp", &json!({"effect": bottom})).unwrap();
execute(&mut session, "effect.moveUp", &json!({"effect": bottom, "merge": true})).unwrap();
let end = execute(&mut session, "effect.moveUp", &json!({"effect": bottom})).unwrap();
assert_eq!(order(&session), [middle, top, bottom]);
assert_eq!(end, json!({"moved": false}));
assert_eq!(session.history_labels().len(), steps_before + 1);
execute(&mut session, "edit.undo", &Value::Null).unwrap();
assert_eq!(order(&session), [bottom, middle, top]);
}
@@ -39,6 +39,7 @@ fn in_memory_psd_export_only_renders_the_first_plan_for_each_name() {
let small = options(SMALL_SIDE);
let large = options(4096);
let first = session.export_files(&[0], &small).unwrap();
assert!(first.len() > 1, "the mesh supplies multiple PSD tiles");
let jobs = std::iter::once((0, &small)).chain(std::iter::repeat_n((0, &large), 4));
+26
View File
@@ -70,6 +70,32 @@ fn planned_uv_tile_sizes_match_the_written_files() {
std::fs::remove_dir_all(directory).unwrap();
}
#[test]
fn rectangular_map_overrides_plan_the_dimensions_written_by_png_and_psd() {
let mut session = session();
execute(&mut session, "textureSet.resolution", &json!({"ts": 0, "resolution": 128, "height": 256})).unwrap();
let directory = tempfile::tempdir().unwrap();
let preset = json!({"name": "Mixed", "maps": [
{"file": "one", "format": "Png", "bit_depth": 8, "channels": [["L", {"Channel": {"channel": "Roughness"}}]]},
{"file": "two", "format": "Psd", "bit_depth": 8, "channels": [["L", {"Channel": {"channel": "Roughness"}}]]}
]});
let params = json!({"dir": directory.path(), "ts": 0, "preset": preset, "size": 256, "maps": [{"map": 0, "size": 128}, {"map": 1, "size": 128}]});
let files = execute(&mut session, "export.plan", &params).unwrap();
execute(&mut session, "file.exportTextures", &params).unwrap();
let files = files.as_array().unwrap();
assert_eq!(files.len(), 2, "{files:?}");
for file in files {
let bytes = std::fs::read(directory.path().join(file["file"].as_str().unwrap())).unwrap();
let (width_bytes, height_bytes) = if file["format"] == "psd" { (&bytes[18..22], &bytes[14..18]) } else { (&bytes[16..20], &bytes[20..24]) };
let (width, height) = (u32::from_be_bytes(width_bytes.try_into().unwrap()), u32::from_be_bytes(height_bytes.try_into().unwrap()));
assert_eq!(height, 2 * width, "{file}");
assert_eq!((file["size"].as_u64(), file["height"].as_u64()), (Some(u64::from(width)), Some(u64::from(height))), "{file}");
assert_eq!(file["size"], file["sourceSize"], "both maps override the export width with the source width");
}
}
#[test]
fn a_file_name_an_earlier_texture_set_exports_is_not_overwritten() {
let mut s = session();
+395
View File
@@ -0,0 +1,395 @@
//! Flattening a folder: a new fill layer above it reads one image per channel and its mask is baked, so the stack looks the same with the folder hidden
use serde_json::{Value, json};
use texturecraft_engine::core::{LayerId, LayerKind};
use texturecraft_engine::geom::glam::Vec2;
use texturecraft_engine::geom::primitives;
use texturecraft_engine::{Session, StackTarget, execute};
/// The test project's texture size
const RESOLUTION: u32 = 256;
/// Largest difference a flattened texel may show (16-bit images, straight values recovered from premultiplied ones)
const TOLERANCE: f32 = 4e-3;
fn session() -> Session {
let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, RESOLUTION).unwrap();
s.viewport = Vec2::new(400.0, 400.0);
s.camera.yaw = 0.0;
s.camera.pitch = 0.0;
s.update();
s
}
fn id(reply: Value) -> u64 {
reply["layer"].as_u64().unwrap()
}
fn stroke(s: &mut Session, size: u32, points: [[u32; 2]; 2]) {
execute(s, "tool.brush", &json!({"size": size, "hardness": 40})).unwrap();
execute(s, "tool.stroke", &json!({ "points": points })).unwrap();
}
/// Every channel's composited value at every texel
fn composite(s: &mut Session) -> Vec<[f32; 3]> {
s.update();
let channels = s.doc.project.texture_set(0).unwrap().channel_list();
let composite = &s.caches[0].composite;
channels.iter().flat_map(|c| (0..composite.height).flat_map(move |y| (0..composite.resolution).map(move |x| composite.value(*c, x, y)))).collect()
}
fn largest_difference(a: &[[f32; 3]], b: &[[f32; 3]]) -> f32 {
// `f32::max` drops a NaN operand, so a broken composite would compare as equal
assert!(a.iter().chain(b).flatten().all(|value| value.is_finite()), "the composite holds only finite values");
a.iter().zip(b).flat_map(|(a, b)| a.iter().zip(b).map(|(a, b)| (a - b).abs())).fold(0.0, f32::max)
}
#[test]
fn a_flattened_folder_looks_the_same_as_the_folder_and_undoes_in_one_step() {
let mut s = session();
id(execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 1.0], "roughness": 0.2, "height": -0.3})).unwrap());
let below = composite(&mut s);
// A folder over it: a masked red fill and a soft roughness stroke, with a stroke in the folder's own mask
let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap());
id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.2, 0.0], "roughness": 0.9, "height": 0.4})).unwrap());
s.target = StackTarget::Mask;
stroke(&mut s, 30, [[170, 200], [230, 200]]);
id(execute(&mut s, "layer.add.paint", &Value::Null).unwrap());
execute(&mut s, "tool.material", &json!({"channel": "roughness", "value": 0.6})).unwrap();
stroke(&mut s, 20, [[200, 160], [200, 240]]);
execute(&mut s, "layer.select", &json!({"layer": folder})).unwrap();
s.target = StackTarget::Mask;
stroke(&mut s, 40, [[160, 215], [240, 215]]);
let before = composite(&mut s);
assert!(largest_difference(&before, &below) > 0.1, "the folder shows over the layer below");
let flat = id(execute(&mut s, "layer.flatten", &json!({"layer": folder})).unwrap());
let after = composite(&mut s);
assert!(matches!(s.doc.project.layer(LayerId(flat)).unwrap().kind, LayerKind::Fill(_)), "the folder becomes a fill layer");
assert!(!s.doc.project.layer(LayerId(folder)).unwrap().visible, "the folder is hidden under it");
assert!(s.doc.project.layer(LayerId(flat)).unwrap().mask.is_some(), "the folder's mask is baked into the new layer");
assert!(largest_difference(&after, &before) < TOLERANCE, "{}", largest_difference(&after, &before));
let mut reopened = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap();
assert!(largest_difference(&composite(&mut reopened), &before) < TOLERANCE, "the baked images keep their coverage when reopened");
execute(&mut s, "edit.undo", &Value::Null).unwrap();
assert!(s.doc.project.layer(LayerId(flat)).is_err(), "one undo step removes the flattened layer");
assert!(s.doc.project.layer(LayerId(folder)).unwrap().visible, "and shows the folder again");
}
#[test]
fn a_flattened_folder_bakes_a_mask_that_reads_the_layers_below() {
let mut s = session();
id(execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 1.0], "height": -0.3})).unwrap());
id(execute(&mut s, "layer.add.paint", &Value::Null).unwrap());
execute(&mut s, "tool.material", &json!({"channel": "height", "value": 0.6})).unwrap();
stroke(&mut s, 40, [[160, 200], [240, 200]]);
let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap());
id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.2, 0.0], "height": 0.2})).unwrap());
execute(&mut s, "mask.add.heightCombination", &json!({"layer": folder})).unwrap();
let before = composite(&mut s);
id(execute(&mut s, "layer.flatten", &json!({"layer": folder})).unwrap());
assert!(largest_difference(&composite(&mut s), &before) < TOLERANCE, "{}", largest_difference(&composite(&mut s), &before));
}
/// Inside a folder, layers blending with Multiply, Screen or Overlay over the layers below the folder hide each part of the stack by a different amount: the flattened layer still shows what they did
#[test]
fn a_flattened_folder_looks_the_same_when_its_layers_blend_with_the_layers_below_it() {
for mode in ["multiply", "screen", "overlay"] {
let mut s = session();
id(execute(&mut s, "layer.add.fill", &json!({"color": [0.2, 0.5, 0.8], "roughness": 0.4})).unwrap());
let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap());
let inner = id(execute(&mut s, "layer.add.fill", &json!({"color": [0.9, 0.3, 0.1], "roughness": 0.7})).unwrap());
for channel in ["baseColor", "roughness"] {
execute(&mut s, "layer.blend", &json!({"layer": inner, "channel": channel, "mode": mode})).unwrap();
}
let before = composite(&mut s);
execute(&mut s, "layer.flatten", &json!({"layer": folder})).unwrap();
assert!(largest_difference(&composite(&mut s), &before) < TOLERANCE, "{mode}: {}", largest_difference(&composite(&mut s), &before));
}
}
/// A hidden folder shows nothing, so the layer it flattens into is hidden too
#[test]
fn a_hidden_folder_flattens_into_a_hidden_layer() {
let mut s = session();
id(execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 1.0]})).unwrap());
let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap());
id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.2, 0.0]})).unwrap());
execute(&mut s, "layer.visible", &json!({"layer": folder, "visible": false})).unwrap();
let before = composite(&mut s);
let flat = id(execute(&mut s, "layer.flatten", &json!({"layer": folder})).unwrap());
assert!(!s.doc.project.layer(LayerId(flat)).unwrap().visible, "the new layer is hidden like the folder");
assert!(largest_difference(&composite(&mut s), &before) < TOLERANCE, "the image does not change");
}
/// A generator whose micro height reads an anchor point bakes as the viewport shows it
#[test]
fn a_flattened_folder_keeps_a_generators_anchor_micro_height() {
let mut s = texturecraft_engine::sample_session(128, 64).unwrap();
let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap());
let low = id(execute(&mut s, "layer.add.fill", &json!({"height": 1.0})).unwrap());
execute(&mut s, "mask.add.black", &json!({"layer": low})).unwrap();
execute(&mut s, "effect.add.fill", &json!({"layer": low, "procedural": "checker", "scale": 4.0})).unwrap();
let anchor = execute(&mut s, "effect.add.anchor", &json!({"layer": low})).unwrap()["effect"].as_u64().unwrap();
let top = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0]})).unwrap());
execute(&mut s, "mask.add.black", &json!({"layer": top})).unwrap();
let generator = execute(&mut s, "effect.add.generator", &json!({"layer": top, "generator": "curvature"})).unwrap()["effect"].as_u64().unwrap();
execute(&mut s, "effect.set", &json!({"effect": generator, "microAnchor": anchor, "microAmount": 1.0})).unwrap();
let before = composite(&mut s);
execute(&mut s, "layer.flatten", &json!({"layer": folder})).unwrap();
assert!(largest_difference(&composite(&mut s), &before) < TOLERANCE, "{}", largest_difference(&composite(&mut s), &before));
}
/// A folder holding this one lays its Scale and Rotation on every fill inside it: the baked images stay where they were baked
#[test]
fn a_folder_flattened_inside_a_scaled_and_turned_folder_looks_the_same() {
let mut s = session();
id(execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 1.0]})).unwrap());
let outer = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap());
let inner = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap());
id(execute(&mut s, "layer.add.paint", &Value::Null).unwrap());
stroke(&mut s, 30, [[170, 190], [230, 210]]);
execute(&mut s, "folder.contents.set", &json!({"layer": outer, "scale": 2.0, "rotation": 45.0})).unwrap();
let before = composite(&mut s);
execute(&mut s, "layer.flatten", &json!({"layer": inner})).unwrap();
assert!(largest_difference(&composite(&mut s), &before) < TOLERANCE, "{}", largest_difference(&composite(&mut s), &before));
}
/// A fill reads one image again on every UV tile, so a folder of a set with several tiles is refused instead of baked wrong
#[test]
fn flattening_a_folder_over_several_uv_tiles_is_refused() {
let mut s = Session::new_project("t", primitives::udim_plane(), "builtin:udim_plane", None, 128).unwrap();
let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap());
let fill = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.2, 0.0]})).unwrap());
execute(&mut s, "mask.add.black", &json!({"layer": fill})).unwrap();
execute(&mut s, "effect.add.fill", &json!({"layer": fill, "procedural": "checker", "scale": 3.0})).unwrap();
assert!(s.doc.project.texture_sets[0].uv_tiles.len() > 1, "the plane spans two UV tiles");
let before = composite(&mut s);
let steps = s.history_labels().len();
let flattened = execute(&mut s, "layer.flatten", &json!({"layer": folder}));
if flattened.is_ok() {
assert!(largest_difference(&composite(&mut s), &before) < TOLERANCE, "baked wrong by {}", largest_difference(&composite(&mut s), &before));
}
assert!(flattened.is_err(), "refused");
assert_eq!(s.history_labels().len(), steps, "and nothing is changed");
}
/// A flatten that fails once its images are stored keeps none of their decoded pixels
#[test]
fn a_failed_folder_flatten_keeps_no_decoded_images() {
let mut s = session();
let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap());
id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.2, 0.0]})).unwrap());
let decoded = s.images.len();
// The new layer gets a taken id, so placing it in the stack fails after its images are in
s.doc.project.next_id = folder;
let flattened = execute(&mut s, "layer.flatten", &json!({"layer": folder}));
let error = flattened.unwrap_err().to_string();
assert!(error.contains("already exists"), "failed placing the new layer: {error}");
assert_eq!(s.images.len(), decoded);
}
/// A child reading an anchor point of the folder's own mask keeps what it read
#[test]
fn a_flattened_folder_keeps_what_a_child_reads_from_the_folder_mask() {
let mut s = session();
id(execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 1.0]})).unwrap());
let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap());
let child = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.2, 0.0]})).unwrap());
execute(&mut s, "mask.add.black", &json!({"layer": folder})).unwrap();
execute(&mut s, "effect.add.fill", &json!({"layer": folder, "target": "mask", "value": 0.4})).unwrap();
let anchor = execute(&mut s, "effect.add.anchor", &json!({"layer": folder, "target": "mask"})).unwrap()["effect"].as_u64().unwrap();
execute(&mut s, "mask.add.black", &json!({"layer": child})).unwrap();
execute(&mut s, "effect.add.fill", &json!({"layer": child, "target": "mask", "anchor": anchor})).unwrap();
let before = composite(&mut s);
execute(&mut s, "layer.flatten", &json!({"layer": folder})).unwrap();
assert!(largest_difference(&composite(&mut s), &before) < TOLERANCE, "{}", largest_difference(&composite(&mut s), &before));
}
/// An instance of a folder draws at its source's channel opacity, so it flattens at it
#[test]
fn a_flattened_folder_instance_keeps_the_folders_opacity() {
let mut s = session();
let base = id(execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 1.0]})).unwrap());
let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap());
id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.2, 0.0]})).unwrap());
execute(&mut s, "layer.blend", &json!({"layer": folder, "channel": "all", "opacity": 0.25})).unwrap();
// With the folder selected the instance would go inside it
execute(&mut s, "layer.select", &json!({"layer": base})).unwrap();
let instance = id(execute(&mut s, "layer.instance", &json!({"layer": folder})).unwrap());
execute(&mut s, "layer.move", &json!({"layer": instance, "above": folder})).unwrap();
execute(&mut s, "layer.visible", &json!({"layer": folder, "visible": false})).unwrap();
let before = composite(&mut s);
execute(&mut s, "layer.flatten", &json!({"layer": instance})).unwrap();
assert!(largest_difference(&composite(&mut s), &before) < TOLERANCE, "{}", largest_difference(&composite(&mut s), &before));
}
/// Hiding a folder takes its anchor points with it, so a layer outside reading one would change: refused, nothing touched
#[test]
fn flattening_a_folder_whose_anchor_point_is_read_outside_it_is_refused() {
let mut s = session();
let base = id(execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 1.0]})).unwrap());
let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap());
let child = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.2, 0.0], "roughness": 0.0})).unwrap());
let anchor = execute(&mut s, "effect.add.anchor", &json!({"layer": child})).unwrap()["effect"].as_u64().unwrap();
execute(&mut s, "layer.select", &json!({"layer": base})).unwrap();
let reader = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0]})).unwrap());
execute(&mut s, "layer.move", &json!({"layer": reader, "above": folder})).unwrap();
execute(&mut s, "mask.add.black", &json!({"layer": reader})).unwrap();
execute(&mut s, "effect.add.fill", &json!({"layer": reader, "target": "mask", "anchor": anchor, "anchorChannel": "roughness"})).unwrap();
let project = s.doc.project.clone();
assert!(execute(&mut s, "layer.flatten", &json!({"layer": folder})).is_err());
assert_eq!(s.doc.project, project, "nothing was added or hidden");
}
/// An instance's own mask goes with the hidden instance, and an outside layer stays on screen when only an instance of it sits in the folder
#[test]
fn flattening_is_refused_for_anchor_points_read_through_instances() {
let mut s = session();
let base = id(execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 1.0]})).unwrap());
let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap());
let child = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.2, 0.0]})).unwrap());
execute(&mut s, "layer.select", &json!({"layer": base})).unwrap();
let reader = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0]})).unwrap());
execute(&mut s, "mask.add.black", &json!({"layer": reader})).unwrap();
let read = |s: &mut Session, anchor: u64| {
execute(s, "effect.add.fill", &json!({"layer": reader, "target": "mask", "anchor": anchor})).unwrap();
};
let anchor = |s: &mut Session, layer: u64, target: &str| {
execute(s, "effect.add.anchor", &json!({"layer": layer, "target": target})).unwrap()["effect"].as_u64().unwrap()
};
// The anchor point sits in the instance's own mask
execute(&mut s, "layer.select", &json!({"layer": base})).unwrap();
let instance = id(execute(&mut s, "layer.instance", &json!({"layer": folder})).unwrap());
execute(&mut s, "layer.move", &json!({"layer": instance, "above": folder})).unwrap();
execute(&mut s, "layer.move", &json!({"layer": reader, "above": instance})).unwrap();
execute(&mut s, "mask.add.white", &json!({"layer": instance})).unwrap();
let own = anchor(&mut s, instance, "mask");
read(&mut s, own);
assert!(execute(&mut s, "layer.flatten", &json!({"layer": instance})).is_err(), "the instance's own anchor point is read outside it");
// The reader is also instanced inside the folder, and reads an anchor point there
execute(&mut s, "layer.remove", &json!({"layer": instance})).unwrap();
execute(&mut s, "layer.select", &json!({"layer": child})).unwrap();
execute(&mut s, "layer.instance", &json!({"layer": reader})).unwrap();
let inside = anchor(&mut s, child, "content");
read(&mut s, inside);
assert!(execute(&mut s, "layer.flatten", &json!({"layer": folder})).is_err(), "the instanced layer still reads from outside");
}
/// An instance above the folder draws a reader from inside it, without the anchor point that reader reads
#[test]
fn flattening_is_refused_when_an_instance_outside_draws_a_reader_from_inside() {
let mut s = session();
id(execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 1.0]})).unwrap());
let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap());
let child = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.2, 0.0]})).unwrap());
let anchor = execute(&mut s, "effect.add.anchor", &json!({"layer": child})).unwrap()["effect"].as_u64().unwrap();
let reader = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0]})).unwrap());
execute(&mut s, "mask.add.black", &json!({"layer": reader})).unwrap();
execute(&mut s, "effect.add.fill", &json!({"layer": reader, "target": "mask", "anchor": anchor})).unwrap();
execute(&mut s, "layer.select", &json!({"layer": child})).unwrap();
let instance = id(execute(&mut s, "layer.instance", &json!({"layer": reader})).unwrap());
execute(&mut s, "layer.move", &json!({"layer": instance, "above": folder})).unwrap();
let project = s.doc.project.clone();
assert!(execute(&mut s, "layer.flatten", &json!({"layer": folder})).is_err());
assert_eq!(s.doc.project, project, "nothing was added or hidden");
}
/// An instance with its own mask draws the folder's children without the folder's mask and its anchor points
#[test]
fn flattening_is_refused_when_a_masked_instance_draws_a_reader_of_the_folder_mask() {
let mut s = session();
let base = id(execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 1.0]})).unwrap());
let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap());
let child = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.2, 0.0]})).unwrap());
execute(&mut s, "mask.add.white", &json!({"layer": folder})).unwrap();
let anchor = execute(&mut s, "effect.add.anchor", &json!({"layer": folder, "target": "mask"})).unwrap()["effect"].as_u64().unwrap();
execute(&mut s, "mask.add.black", &json!({"layer": child})).unwrap();
execute(&mut s, "effect.add.fill", &json!({"layer": child, "target": "mask", "anchor": anchor})).unwrap();
execute(&mut s, "layer.select", &json!({"layer": base})).unwrap();
let instance = id(execute(&mut s, "layer.instance", &json!({"layer": folder})).unwrap());
execute(&mut s, "layer.move", &json!({"layer": instance, "above": folder})).unwrap();
execute(&mut s, "mask.add.white", &json!({"layer": instance})).unwrap();
assert!(execute(&mut s, "layer.flatten", &json!({"layer": folder})).is_err());
}
/// A mask comparing a channel the set no longer has reads the folder's layers holding only that channel, before and after
#[test]
fn a_flattened_folder_keeps_what_its_masks_compare_in_a_removed_channel() {
let mut s = session();
id(execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 1.0], "height": -0.3})).unwrap());
let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap());
id(execute(&mut s, "layer.add.paint", &Value::Null).unwrap());
execute(&mut s, "tool.material", &json!({"channel": "height", "value": 0.6})).unwrap();
stroke(&mut s, 40, [[160, 200], [240, 200]]);
let top = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.2, 0.0], "height": 0.2})).unwrap());
execute(&mut s, "mask.add.heightCombination", &json!({"layer": top})).unwrap();
execute(&mut s, "textureSet.channel.remove", &json!({"channel": "height"})).unwrap();
let before = composite(&mut s);
execute(&mut s, "layer.flatten", &json!({"layer": folder})).unwrap();
assert!(largest_difference(&composite(&mut s), &before) < TOLERANCE, "{}", largest_difference(&composite(&mut s), &before));
}
/// Linear dodge can take a folder's result past what an image holds, which the folder's opacity then mixes back: refused, not clipped
#[test]
fn flattening_a_folder_adding_up_past_white_is_refused() {
// The last folder's mask hides everything it adds, so nothing is clipped
for (added, masked, overflows) in [(0.25, false, false), (0.75, false, true), (0.75, true, false)] {
let mut s = session();
id(execute(&mut s, "layer.add.fill", &json!({"color": [0.2, 0.2, 0.2], "roughness": 0.5})).unwrap());
let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap());
let inner = id(execute(&mut s, "layer.add.fill", &json!({"color": [0.1, 0.1, 0.1], "roughness": added})).unwrap());
execute(&mut s, "layer.blend", &json!({"layer": inner, "channel": "roughness", "mode": "linearDodge"})).unwrap();
execute(&mut s, "layer.blend", &json!({"layer": folder, "channel": "all", "opacity": 0.5})).unwrap();
if masked {
execute(&mut s, "mask.add.black", &json!({"layer": folder})).unwrap();
}
let before = composite(&mut s);
let project = s.doc.project.clone();
let flattened = execute(&mut s, "layer.flatten", &json!({"layer": folder}));
if flattened.is_ok() {
assert!(largest_difference(&composite(&mut s), &before) < TOLERANCE, "baked wrong by {}", largest_difference(&composite(&mut s), &before));
}
assert_eq!(flattened.is_err(), overflows, "added roughness {added}, masked {masked}: {flattened:?}");
if overflows {
assert_eq!(s.doc.project, project, "nothing was added or hidden");
}
}
}
+56
View File
@@ -0,0 +1,56 @@
//! Generator effects are named after their kind, and a name taken from the kind follows a kind change
use serde_json::{Value, json};
use texturecraft_engine::core::LayerId;
use texturecraft_engine::{Session, execute};
/// A sample session with a new generator of `kind` on its top layer's mask
fn generator(kind: &str) -> (Session, LayerId) {
let mut session = texturecraft_engine::sample_session(256, 64).unwrap();
execute(&mut session, "layer.add.fill", &Value::Null).unwrap();
let added = execute(&mut session, "effect.add.generator", &json!({"generator": kind})).unwrap();
(session, LayerId(added["effect"].as_u64().unwrap()))
}
fn name(session: &Session, effect: LayerId) -> String {
session.doc.project.effect(effect).unwrap().1.name.clone()
}
fn set(session: &mut Session, effect: LayerId, params: Value) {
let mut params = params;
params["effect"] = json!(effect.0);
execute(session, "effect.set", &params).unwrap();
}
#[test]
fn a_new_generator_takes_its_kinds_name_and_keeps_following_it() {
let (mut session, effect) = generator("dirt");
assert_eq!(name(&session, effect), "Dirt");
set(&mut session, effect, json!({"generator": "curvature"}));
assert_eq!(name(&session, effect), "Curvature");
}
#[test]
fn a_chosen_name_survives_a_kind_change() {
let (mut session, effect) = generator("dirt");
set(&mut session, effect, json!({"name": "Grime"}));
set(&mut session, effect, json!({"generator": "curvature"}));
assert_eq!(name(&session, effect), "Grime");
set(&mut session, effect, json!({"generator": "dirt", "name": "Dust"}));
assert_eq!(name(&session, effect), "Dust", "a name given with the change wins");
}
#[test]
fn an_older_projects_generic_generator_name_follows_its_next_kind_change() {
let (mut session, effect) = generator("dirt");
set(&mut session, effect, json!({"name": "Generator"}));
set(&mut session, effect, json!({"generator": "curvature"}));
assert_eq!(name(&session, effect), "Curvature");
}
+18
View File
@@ -292,3 +292,21 @@ fn a_resampled_instance_refreshes_when_its_source_stroke_commits() {
s.end_stroke().unwrap();
assert!(!s.caches[1].dirty.is_empty(), "committed source pixels must be resampled");
}
#[test]
fn an_inherited_mask_effect_moves_from_another_texture_set_with_no_layer_selected() {
let mut s = session();
let source = id(execute(&mut s, "layer.add.fill", &Value::Null).unwrap(), "layer");
execute(&mut s, "mask.add.black", &json!({"layer": source.0})).unwrap();
let add = |s: &mut Session| id(execute(s, "effect.add.fill", &json!({"layer": source.0, "target": "mask", "value": 0.5})).unwrap(), "effect");
let (lower, upper) = (add(&mut s), add(&mut s));
execute(&mut s, "layer.instance", &json!({"layer": source.0, "ts": 1})).unwrap();
s.active_set = 1;
s.selected.clear();
execute(&mut s, "effect.move", &json!({"effect": lower.0, "index": 1})).unwrap();
let order: Vec<LayerId> = s.doc.project.layer(source).unwrap().mask.as_ref().unwrap().effects.iter().map(|effect| effect.id).collect();
assert_eq!(order, [upper, lower]);
assert_eq!(s.selected_layer(), None, "the selection stays as it was");
}
+33 -1
View File
@@ -3,7 +3,7 @@
//! act on every selected layer in one undo step.
use serde_json::{Value, json};
use texturecraft_engine::core::{LayerId, LayerKind};
use texturecraft_engine::core::{BlendMode, Channel, LayerId, LayerKind};
use texturecraft_engine::geom::primitives;
use texturecraft_engine::layer_selection::stack_rows;
use texturecraft_engine::{Session, execute};
@@ -523,3 +523,35 @@ fn moving_layers_into_a_folder_in_another_set_preserves_the_document() {
assert_eq!(s.history_labels(), history);
}
}
#[test]
fn a_rows_controls_act_on_its_layer_with_no_layer_selected() {
let mut s = session();
let [a, ..] = four(&mut s);
// An undo can leave no layer selected; the row's eye and blend menu still name their layer
s.selected.clear();
execute(&mut s, "layer.visible", &json!({"layer": a.0, "visible": false})).unwrap();
execute(&mut s, "layer.blend", &json!({"layer": a.0, "channel": "baseColor", "mode": "Multiply"})).unwrap();
let layer = s.doc.project.layer(a).unwrap();
assert!(!layer.visible, "the eye hid its layer");
assert_eq!(layer.blend(Channel::BaseColor).map(|b| b.mode), Some(BlendMode::Multiply), "the blend menu changed its layer");
assert_eq!(s.selected_layer(), None, "the selection stays as it was");
assert!(execute(&mut s, "layer.visible", &Value::Null).is_err(), "with no layer named, nothing is selected to act on");
}
#[test]
fn an_effect_rows_menu_moves_its_effect_with_no_layer_selected() {
let mut s = session();
let [a, ..] = four(&mut s);
let add =
|s: &mut Session| execute(s, "effect.add.filter", &json!({"layer": a.0, "target": "content", "filter": "invert"})).unwrap()["effect"].as_u64().unwrap();
let (lower, upper) = (add(&mut s), add(&mut s));
s.selected.clear();
execute(&mut s, "effect.move", &json!({"effect": lower, "index": 1})).unwrap();
let order: Vec<u64> = s.doc.project.layer(a).unwrap().content_effects.iter().map(|effect| effect.id.0).collect();
assert_eq!(order, [upper, lower]);
assert_eq!(s.selected_layer(), None, "the selection stays as it was");
}
+207
View File
@@ -0,0 +1,207 @@
//! Picking a layer on the mesh (R + click): the layers laying something down at a spot, top first, and selecting one of them
use serde_json::{Value, json};
use texturecraft_engine::core::{LayerId, LayerKind};
use texturecraft_engine::geom::glam::Vec2;
use texturecraft_engine::geom::primitives;
use texturecraft_engine::{Session, Solo, execute};
/// The middle of the sphere in the test viewport, where the lower paint layer is painted
const MIDDLE: [f32; 2] = [200.0, 200.0];
/// A spot on the sphere left of the middle, where only the upper paint layer is painted
const LEFT: [f32; 2] = [130.0, 200.0];
/// The test stack: (session, the fill at the bottom, a paint layer over the middle, a paint layer over the left spot above it)
fn stack() -> (Session, u64, u64, u64) {
let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 256).unwrap();
s.viewport = Vec2::new(400.0, 400.0);
s.camera.yaw = 0.0;
s.camera.pitch = 0.0;
let fill = id(execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 1.0]})).unwrap());
let middle = id(execute(&mut s, "layer.add.paint", &Value::Null).unwrap());
execute(&mut s, "tool.brush", &json!({"size": 20, "hardness": 100})).unwrap();
execute(&mut s, "tool.stroke", &json!({"points": [[190, 200], [210, 200]]})).unwrap();
let left = id(execute(&mut s, "layer.add.paint", &Value::Null).unwrap());
execute(&mut s, "tool.stroke", &json!({"points": [[125, 200], [135, 200]]})).unwrap();
s.update();
(s, fill, middle, left)
}
fn id(reply: Value) -> u64 {
reply["layer"].as_u64().unwrap()
}
fn click(s: &mut Session, [x, y]: [f32; 2]) -> Option<u64> {
execute(s, "layer.pickAt", &json!({"x": x, "y": y})).ok().map(id)
}
/// The layers `layer.layersAt` lists at a spot, top first, each with the channels it changes there
fn layers_at(s: &mut Session, [x, y]: [f32; 2]) -> Vec<(u64, Vec<String>)> {
let reply = execute(s, "layer.layersAt", &json!({"x": x, "y": y})).unwrap();
let channels = |row: &Value| row["channels"].as_array().unwrap().iter().map(|channel| channel.as_str().unwrap().to_owned()).collect();
reply["layers"].as_array().unwrap().iter().map(|row| (id(row.clone()), channels(row))).collect()
}
#[test]
fn a_spot_lists_the_layers_laying_something_there_top_first_and_a_pick_selects_the_one_asked_for() {
let (mut s, fill, middle, left) = stack();
execute(&mut s, "layer.blend", &json!({"layer": middle, "channel": "roughness", "opacity": 0.0})).unwrap();
let listed = layers_at(&mut s, MIDDLE);
let order: Vec<u64> = listed.iter().map(|(layer, _)| *layer).collect();
assert_eq!(order, [middle, fill], "the layer painted elsewhere is left out; the top one comes first");
assert!(
!listed[0].1.contains(&"roughness".to_owned()) && listed[1].1.contains(&"roughness".to_owned()),
"a channel at zero opacity is not among the ones the layer changes there"
);
assert_eq!(click(&mut s, MIDDLE), Some(middle), "a plain pick selects the top layer");
assert_eq!(click(&mut s, MIDDLE), Some(middle), "the same spot again keeps the top layer");
let picked = execute(&mut s, "layer.pickAt", &json!({"x": MIDDLE[0], "y": MIDDLE[1], "layer": fill})).map(id).ok();
assert_eq!(picked, Some(fill), "a listed layer is selected when asked for");
assert_eq!(s.selected_layer_id().map(|layer| layer.0), Some(fill));
assert!(
execute(&mut s, "layer.pickAt", &json!({"x": MIDDLE[0], "y": MIDDLE[1], "layer": left})).is_err(),
"a layer not laying anything down there is refused"
);
assert_eq!(click(&mut s, LEFT), Some(left), "another spot picks its own top layer");
}
#[test]
fn hidden_layers_and_channels_out_of_view_lay_nothing_down() {
let (mut s, fill, middle, _) = stack();
execute(&mut s, "layer.blend", &json!({"layer": middle, "channel": "baseColor", "opacity": 0.0})).unwrap();
execute(&mut s, "viewport.view", &json!({"mode": "baseColor"})).unwrap();
assert_eq!(click(&mut s, MIDDLE), Some(fill), "in the base colour view the layer at zero base colour opacity shows nothing");
execute(&mut s, "viewport.view", &json!({"mode": "material"})).unwrap();
assert_eq!(click(&mut s, MIDDLE), Some(middle), "the material view counts its other channels");
execute(&mut s, "layer.visible", &json!({"layer": middle, "visible": false})).unwrap();
assert_eq!(click(&mut s, MIDDLE), Some(fill), "a hidden layer is skipped");
}
#[test]
fn a_pick_opens_the_collapsed_folders_holding_the_picked_layer() {
let (mut s, _, middle, _) = stack();
execute(&mut s, "layer.group", &json!({"layer": middle})).unwrap();
let inner = s.selected_layer_id().unwrap();
execute(&mut s, "layer.group", &json!({"layer": inner.0})).unwrap();
let outer = s.selected_layer_id().unwrap();
for folder in [inner, outer] {
if let Some(LayerKind::Group { collapsed, .. }) = s.doc.project.layers.get_mut(&folder).map(|layer| &mut layer.kind) {
*collapsed = true;
}
}
assert_eq!(click(&mut s, MIDDLE), Some(middle));
let open = |folder| matches!(s.doc.project.layers[&folder].kind, LayerKind::Group { collapsed: false, .. });
assert!(open(inner) && open(outer), "both folders holding the picked layer are open");
}
/// Each height-combination mask compares with the layers below its own layer, not below another's
#[test]
fn a_height_combination_mask_is_read_against_the_layers_below_its_own_layer() {
let (mut s, ..) = stack();
let add = |s: &mut Session, height: f32| id(execute(s, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0], "height": height})).unwrap());
let base = add(&mut s, 0.0);
let lower = add(&mut s, 0.3);
execute(&mut s, "mask.add.heightCombination", &json!({"layer": lower})).unwrap();
let raised = add(&mut s, 0.6);
let upper = add(&mut s, 0.9);
execute(&mut s, "mask.add.heightCombination", &json!({"layer": upper})).unwrap();
for layer in [base, raised] {
execute(&mut s, "layer.blend", &json!({"layer": layer, "channel": "height", "mode": "Normal"})).unwrap();
}
execute(&mut s, "layer.blend", &json!({"layer": raised, "channel": "baseColor", "enabled": false})).unwrap();
s.update();
let listed: Vec<u64> = layers_at(&mut s, MIDDLE).into_iter().map(|(layer, _)| layer).collect();
assert!(listed.contains(&lower), "the lower combination shows over the base: {listed:?}");
assert!(listed.contains(&upper), "and so does the upper one: {listed:?}");
}
#[test]
fn a_pick_of_something_that_is_not_a_layer_id_is_refused() {
let (mut s, ..) = stack();
let selected = s.selected_layer();
let reply = execute(&mut s, "layer.pickAt", &json!({"x": MIDDLE[0], "y": MIDDLE[1], "layer": "fill"}));
assert!(reply.is_err(), "not silently replaced by the top layer: {reply:?}");
assert_eq!(s.selected_layer(), selected);
}
#[test]
fn a_soloed_layer_is_the_only_one_listed_and_picked() {
let (mut s, fill, ..) = stack();
s.set_solo(Some(Solo { layer: LayerId(fill), ignore_mask: false }));
s.update();
let order: Vec<u64> = layers_at(&mut s, MIDDLE).iter().map(|(layer, _)| *layer).collect();
assert_eq!(order, [fill], "the layers solo hides are not on screen");
assert_eq!(click(&mut s, MIDDLE), Some(fill));
}
#[test]
fn a_folder_instance_is_listed_once_and_picks_its_own_row() {
let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
s.viewport = Vec2::splat(400.0);
let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap());
id(execute(&mut s, "layer.add.fill", &json!({"color": [0.5, 0.1, 0.1]})).unwrap());
id(execute(&mut s, "layer.add.fill", &json!({"roughness": 0.25})).unwrap());
let instance = id(execute(&mut s, "layer.instance", &json!({"layer": folder, "ts": 1})).unwrap());
s.update();
let point = (100..300)
.step_by(10)
.flat_map(|y| (100..300).step_by(10).map(move |x| [x as f32, y as f32]))
.find(|point| {
s.texel_under(Vec2::from(*point), s.viewport).is_some_and(|(ts, (x, y))| {
let gbuf = &s.caches[ts].gbuf;
ts == 1 && gbuf.surface(&s.mesh, (y * gbuf.width + x) as usize).is_some()
})
})
.expect("a covered texel of the ball's second texture set");
let listed = layers_at(&mut s, point);
let picked = click(&mut s, point);
assert_eq!(listed.iter().map(|(layer, _)| *layer).collect::<Vec<_>>(), [instance]);
assert!(listed[0].1.iter().any(|channel| channel == "baseColor"));
assert!(listed[0].1.iter().any(|channel| channel == "roughness"));
assert_eq!(picked, Some(instance));
assert_eq!(s.ts(), 1);
assert_eq!(s.selected_layer(), Some(LayerId(instance)));
}
#[test]
fn a_layer_pick_passes_through_hidden_texture_sets() {
let rear = primitives::sphere(1.0, 48, 24);
let mut mesh = rear.clone();
for position in &mut mesh.positions {
position.z += 2.5;
}
mesh.append(&rear);
let mut s = Session::new_project("t", mesh, "builtin:sphere", None, 128).unwrap();
s.viewport = Vec2::splat(400.0);
s.camera.yaw = 0.0;
s.camera.pitch = 0.0;
let near = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.0, 0.0]})).unwrap());
execute(&mut s, "textureSet.select", &json!({"ts": 1})).unwrap();
let far = id(execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 1.0]})).unwrap());
s.update();
assert_eq!(click(&mut s, MIDDLE), Some(near), "the visible near sphere owns this pixel");
execute(&mut s, "textureSet.visible", &json!({"ts": 0, "visible": false})).unwrap();
let listed = layers_at(&mut s, MIDDLE);
let picked = click(&mut s, MIDDLE);
assert_eq!(listed.iter().map(|(layer, _)| *layer).collect::<Vec<_>>(), [far]);
assert_eq!(picked, Some(far));
assert_eq!(s.ts(), 1);
}

Some files were not shown because too many files have changed in this diff Show More