mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
Imported documents need durable conversion evidence and native pixel operations before XCF conversion can produce editable PhotoCraft data. This adds bounded document/report types, lossless pattern construction and `.pcraft` persistence, plus native HDR, percentile, noise, convolution, Average, coverage and matting kernels and checked Smart-filter mixing. Runtime color models/depths are retained; source attachments remain inert. Native SVG operations retain parsing, lowering, rendering and parser-tree destruction on one bounded worker, including nested resources; WebAssembly reports a controlled error for depths requiring native isolation. Native filter corrections cover matte black points and signed HDR, extent-wide Smart-filter coverage, flat-image identity Auto Levels, opaque FillHoles capability, exact unselected channel preservation, coverage-preserving Average selection and bounded pattern expansion. Checked Smart-filter mixing rejects nonfinite native F32 samples, preserves unchanged Normal pixels without regenerating CMYK separations, and recovers representable alpha mixtures after an overflowing difference. HDR blend overflow retries use cold F64 arithmetic while retaining ordinary finite results and integer-depth behavior. Both opaque and alpha-bearing F32 mask recovery retain signed/HDR colors. Stored pattern declarations remain lossless and inert. Dense PSD/PAT/ASL pattern export now checks dimensions and one shared plane-allocation budget before conversion. PAT/ASL report conversion errors; PSD/PSB report named omission warnings. Matching raw PSD pattern blocks remain verbatim. CMYK offsets retain the established brightness convention. Command registration, XCF decoding and frontend workflows follow in dependent parts. The contributor entry is the author's existing chosen entry. <!-- native-foundations-fixes-20261107:start --> Small noise, convolution and point-operation edits admit their clipped work area on large owners while retaining output/workspace limits and whole-owner FillHoles bounds. HDR toning retains skipped transparent native samples. Normal Smart-filter strength interpolates stored CMYK/Lab/ink planes with premultiplied coverage, preserving unchanged channels. Bitmap Custom Pattern reads compact patterns in bounded row bands and ranks the complete map once. Embedded SVG isolation failures propagate independently of strict mode; ordinary invalid images can still be omitted, and private native parses share the complete-operation worker. The import-report regression now primes the layer blob cache and requires its specific limit diagnostic. <!-- native-foundations-fixes-20261107:end --> <!-- adversarial-5810371597:start --> Import-report accounting uses portable fixed costs. HDR scene means use F64. Bitmap pattern ranking preflights a 256 MiB input/order/output budget, uses fallible allocation and heap-scratch-free sorting. Average uses the supplied image domain and retains one global mean across output tiles. Non-Normal Smart-filter coverage is classified once across the complete mixing extent. A fallible filter dispatcher and engine error conversion preserve checked native diagnostics and cancellation. Smart-filter engine integration remains in part 5 (#11032). <!-- adversarial-5810371597:end --> ## Six-part series Each branch is hosted in Terra854/photocraft, and every PR targets storytold/photocraft:main. Merge in the order below. Later drafts currently show cumulative diffs while prerequisites are unmerged; their descriptions link to isolated comparisons. Rebase each part onto current upstream main after its prerequisites merge, including squash-merge ancestry, and rerun affected checks before requesting review. | Part | Upstream PR | Fork branch | Scope | | --- | --- | --- | --- | | 1 | [#11009](https://github.com/storytold/photocraft/pull/11009) | xcf-support-v2-01-import-data | Document/native-format data and pixel foundations | | 2 | [#11029](https://github.com/storytold/photocraft/pull/11029) | xcf-support-v2-02-decoder | Bounded transport/records, precision, metadata, editable text and paths | | 3 | [#11030](https://github.com/storytold/photocraft/pull/11030) | xcf-support-v2-03-effects-core | Native effect frames and primary tone/color/spatial/resource/transform adapters | | 4 | [#11031](https://github.com/storytold/photocraft/pull/11031) | xcf-support-v2-04-effects-graphs | Remaining adapters, bounded graph lowering, coverage installation and source evidence | | 5 | [#11032](https://github.com/storytold/photocraft/pull/11032) | xcf-support-v2-05-engine | Native commands, import preparation, historical choices, editing and persistence workflows | | 6 | [#11033](https://github.com/storytold/photocraft/pull/11033) | xcf-support-v2-06-frontends | Desktop/web UI, CLI/MCP, translations, GPU diagnostics and qualification/docs | The full integration remains preserved on `xcf-support-v2`; original #7098 remains available for reference. ## Validation <!-- main-catchup-0d08cb7dd:start --> Updated to upstream `main` at `0d08cb7dd` and restacked all six branches. Part 1 is `640a01f43`; full integration is `24cd17301`. The final six-part tree exactly matches the full integration tree. The merge preserves both upstream's new tests/crop translations and the XCF historical-open tests/report labels. The automation adapter now preserves import-source protection across multiple granted read roots: relative source names cover every matching candidate so newly shadowing files cannot expose the original to overwrite, while absolute source names remain precise. Existing ordered reads and implicit-save provenance are retained. Read-only import source identity is kept independently of whether its library root grants an implicit Save target. Focused regressions cover source aliases, removed files, denied candidates, changing root precedence, and read-only library imports; the Windows escape fixture also uses a real junction when symlink privileges are unavailable. The new upstream UI import fixture also uses the native import outcome type. Local validation passed affected host all-target checks, core and native frontend/automation unit and integration suites, forced-Vulkan GPU unit and integration suites, pinned IO corpora, strict all-target Clippy, formatting, layering, panel command dispatch, WASM, adversarial command tests, and the quick CPU performance harness. Offscreen historical-XCF prompt and conversion-report captures were reviewed. The first two PR boundaries also passed independent all-target engine checks. Tests used the pinned craft-fonts input, four Rayon workers, serial tests for large fixtures and opt-level=0 for engine/UI test glue; pixel/format crates retained their repository settings. Quick mode uses small documents and does not enforce full-size budgets. The part 1 push triggered fresh [CI](https://github.com/storytold/photocraft/actions/runs/42885527754) and [SonarCloud](https://github.com/storytold/photocraft/actions/runs/42885527740) runs. After upstream approval, CI passed the Linux gate, Windows unit/integration tests, no-HEIF tests, pinned corpora and web build. SonarCloud's instrumented archive, coverage shards and actual scan remain skipped behind its token guard; its outer green status does not mean coverage ran. Catching up with main therefore retriggered normal tests but did not remove that SonarCloud skip. Older validation below remains evidence for its explicitly named earlier commits. <!-- main-catchup-0d08cb7dd:end --> <!-- average-no-extent-4517477902:start --> Average no-extent follow-up at part 1 `f8ddb626f` (full integration `882def329`), carried through all six branches. The checked Average dispatcher now uses the requested `area` when no owner extent is supplied; an explicit extent retains its existing clipping behavior. Other filters, the Average pixel kernel and resource admission are unchanged. The new regression fails against the preceding revision and passes with the fix. It covers `apply`, one-pixel explicit tiling, and the cancellable tiled API at 8/16/32-bit, signed/HDR colors, hidden RGB, native alpha preservation, unchanged source data and pixels outside the requested area. Validation passed the algorithm unit/integration suite (935 tests; 27 existing ignored), strict all-target algorithm Clippy, formatting, layering, WASM (24 crates plus HEIF), and independent all-target engine checks of the first two PR boundaries. The broader suites below remain evidence for their named earlier commits and were not rerun for this dispatcher-only follow-up. <!-- average-no-extent-4517477902:end --> <!-- review-20261110:start --> Review follow-up at part 1 `a3144d559` (full integration `b5fd3e211`), carried through all six branches. Average admits long thin regions within its existing pixel/workspace budgets, clamps finite selection coverage, and uses owner extents for off-canvas replay. HDR Toning also adapts over the owner extent. Pattern GPU uploads now use bounded bands; the warning-free `document_to_psd` API returns `Result` on pattern export failure and reuses prepared pattern blocks. Warning-enabled exports retain explicit omission warnings. Five filter regressions fail against the previous revision and pass with the fixes. Local validation passed 1,597 algorithm/compositor/GPU tests with Vulkan, all 129 GPU integration tests separately on DX12 with FXC (the app uses FXC when no bundled DXC is present), a separate forced DX12 pattern upload/readback test, 1,144 IO unit and 675 pinned IO integration tests, 10 affected engine tests, strict all-target Clippy, formatting, layering, WASM and quick CPU performance checks. The first two PR boundaries passed independent all-target engine checks. This Intel driver's DX12/DXC configuration rejects the unchanged `fs_adjust` pipeline (`0x80070057`); DX12/FXC and Vulkan both pass. The full workspace suite was not rerun; earlier broad evidence below remains tied to its named commits. Quick performance mode does not enforce full-size budgets. A separate 24 MP signed/HDR RGBA32F public Average-kernel probe retained exact mean RGB and original alpha. Three alternating runs had medians of 1,274.713 ms before and 1,259.885 ms after; this small difference is within run variation and is not a speedup claim. The Minor/Poor-tradeoff report-deserialization finding remains open and documented. Encoded records are capped at 32 MiB and individual arrays are bounded, but compact targets can still amplify transient decoded memory before aggregate validation rejects the report. Early shared-budget deserialization is not implemented in this follow-up. <!-- review-20261110:end --> <!-- main-catchup-7c64653d5:start --> Updated to upstream `main` at `7c64653d5` and restacked all six branches. Part 1 is `cbf068d5f`; full integration is `206f71012`. The full integration tree exactly matches part 6. The merge retains main's alpha-preserving Average behavior with bounded checked processing, and uses it consistently for XCF coverage conversion and native replay. Historical XCF normalization and import preparation now run through main's resumable Place flow and Open as Smart Object; regression tests cover source byte order and native Edit Contents. XCF report/filter labels also cover the seven languages main promoted to menu-complete status. The current tree passed affected host all-target checks, core/IO, GPU, engine and frontend suites, strict all-target Clippy, formatting, layering, panel command dispatch, WASM and the web build, adversarial command tests, pinned IO corpora and the quick CPU performance harness. Offscreen historical-XCF prompt and conversion-report captures were reviewed. The first two PR boundaries also passed independent all-target engine checks. Tests used CI-pinned craft-fonts `b076417b5880bd4154bd22f00695b1d28c6bea83`, four Rayon workers, serial tests for RAM-heavy suites and opt-level=0 for engine/UI test glue; pixel and format crates kept repository settings. Quick performance mode uses smaller documents and does not enforce full-size budgets. Older measurements below remain evidence for their named earlier commits. <!-- main-catchup-7c64653d5:end --> <!-- percentile-owner-4502952267:start --> Percentile owner-bounds follow-up at part 1 `93946db04` (full integration `f7264af14`): nonempty owner bounds now supply edge samples without a dense whole-owner admission check. The unchanged preflight still bounds clipped output, padded halo, workspace and CPU work; dense-image adapter limits remain in place. Two new regressions failed with `InvalidGeometry` before the fix and pass afterward, covering small edits on 81 MP and wider sparse owners, clamped-edge oracles, fractional selections, source preservation, clipped requests, invalid domains, oversized output, work limits and cancellation. This follow-up passed 903 algorithm tests (887 unit + 16 integration; 27 existing ignored), all-target strict algorithm Clippy, formatting, layering and WASM (24 crates plus the HEIF configuration). Only sampling-bound admission changed; percentile processing and resource-preflight code are byte-for-byte unchanged. The broader qualification below remains tied to its explicitly named earlier commits; the full workspace suite was not rerun for this one-file follow-up. <!-- percentile-owner-4502952267:end --> <!-- native-foundations-validation-20261107:start --> The production fixes at part 1 `c16e274b8` (full integration `6f8349cd5`) passed 7,245 affected algorithm/compositor/document/engine/native-format/IO tests across 46 binaries, with 65 existing ignored tests, plus doctests, affected all-target strict Clippy, layering, WASM, adversarial command tests, formatting and the pinned IO corpus (1,107 unit + 661 integration tests, 26 existing ignored). The final diagnostics regressions also passed independently on the foundation and full integration branches. The first PR passed an independent all-target engine check. Tests used four Rayon/test workers and the existing CI font pin; engine test glue used opt-level=0, and the foundation-only diagnostic probe also used opt-level=0 for its algorithm dependency. The full integration tree exactly matches the final sixth branch. Paired 24 MP release probes used three timed repetitions per version after warm-ups, alternating order, matching inlining controls, opaque parameters and a current public-API control, with four Rayon workers. Timings are completed operations on this host. | Probe | Before (ms) | After (ms) | Public API (ms) | | --- | ---: | ---: | ---: | | HDR toning | 830.3 | 834.4 | 791.2 | | Rgb-Normal | 1070.5 | 1069.3 | 1079.7 | | Cmyk-Normal | 683.0 | 669.7 | 691.5 | | Rgb-Multiply | 1103.1 | 1303.3 | 1297.5 | The extent-wide coverage prepass adds 200.2 ms (18.2%) in the alpha-preserving Multiply case. This is the measured cost of applying one consistent coverage rule; the Normal RGB/CMYK controls remain near baseline. The uniform HDR probe's middle-gray output changed from 0.200004 to 0.180000 (target 0.18); the public control agrees. Mixer probes check native colors and alpha at sampled positions. The quick CPU application harness also completed; its saved cross-machine comparison was skipped, and quick mode does not apply full-size budgets. No budgets or baselines changed. <!-- native-foundations-validation-20261107:end --> Earlier validation of full integration `c003e3f50`, before these follow-up fixes, completed the upstream `main` catch-up at `c101cbfb7` on 2026-11-07. The cumulative series passed affected host all-target checks, foundation and IO suites, GPU, engine and frontend suites, strict Clippy, layering, WASM, adversarial command tests, formatting, pinned IO corpora and the quick CPU performance harness. Offscreen historical-XCF prompt and conversion-report captures were reviewed. Local tests used CI-pinned craft-fonts `b076417b5880bd4154bd22f00695b1d28c6bea83`, four Rayon workers and temporary opt-level=0 overrides for engine/UI test glue; pixel and format crates retained repository settings. The full UI library passed 5,330 tests, and the final dialog-dispatch cleanup passed 945 focused dialog tests. The decoder and engine PR boundaries also passed independent all-target checks. The full `xcf-support-v2` integration tree matches the final sixth branch exactly. SVG stack regressions retain their 512 KiB caller, isolated complete native lifecycle and 100 retained group levels. The matched performance figures below were measured before this main integration; the HDR recovery arithmetic and bounded tile implementation are preserved. Forward filter-mask mixing retains its existing four-buffer allocation optimization and arithmetic. Its matched 24 MP RGBA32F probes measured opaque pixels at 392.410→182.842 ms, semitransparent pixels at 383.321→179.916 ms, and signed HDR pixels at 373.696→183.903 ms (five-run medians, 50–53% faster). Inverse filter-mask recovery now processes at most eight native tiles in parallel, with four reusable scratch buffers per slot and ordered surface publication. Small inputs, one-worker operation and WebAssembly use the same serial tile helper. All F64 and integer pixel arithmetic is unchanged. Bitwise regressions compare full/partial/missing tiles, negative coordinates, differing defaults and hidden/zero-alpha outputs across 30 format combinations; an explicit one-worker/two-worker comparison checks both execution paths. Matched 24 MP HDR inverse-recovery public-API probes measured 166.972→90.565 ms (opaque, 45.8% faster), and 433.325→130.707 ms (semitransparent, 69.8% faster). Five-run medians use four Rayon workers on this host; all runs assert recovered HDR samples at three positions. The existing F64 precision and HDR saturation bounds are preserved. Mask recovery retains signed/HDR colors, extreme finite values, subnormals and exact full coverage. The PSD/PSB regression uses a real blur on spatially varying HDR pixels and partial masks; raw exported channels must match the unmasked filter result, and reimported Smart caches must match independently authored masked values. The prior quick CPU application harness completed. Its saved cross-machine baseline comparison was skipped, so the paired public-API measurements above provide the direct before/after evidence. No performance budgets or baselines changed. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **New Features** * Added image adjustments and filters for averaging, channel noise, convolution, percentile effects, alpha and coverage editing, black matte removal, HDR toning, and automatic tone, contrast, and color correction. * Added Smart-filter blending controls for opacity and blend modes. * Import-conversion information is preserved when saving and reopening documents. * **Improvements** * Improved handling of deeply nested SVGs and large patterns, with bounded pattern processing and warnings when pattern export is not possible. * Improved stability when blending extreme HDR values and applying filters to HDR images. * Improved transparency handling for channel-selective filters and added clearer feedback when image processing or export cannot be completed. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
376 lines
18 KiB
Rust
376 lines
18 KiB
Rust
//! Patterns: tiles used by Pattern Overlay, pattern fill layers, pattern strokes, Edit › Fill
|
||
//! and brush textures. Pure data; rendering lives in `photocraft-compose`, the PSD mapping
|
||
//! (`Patt`/`Pat2`/`Pat3` global blocks) in `photocraft-io`.
|
||
|
||
use photocraft_color::SampleType;
|
||
use photocraft_geom::Rect;
|
||
use photocraft_raster::{AllocationError, Interrupt, Surface};
|
||
|
||
/// Largest pattern edge a file may declare (the PSD reader's limit; Define Pattern stops at 8000).
|
||
pub const MAX_EDGE: u32 = 30_000;
|
||
|
||
/// Most pixels a pattern may have to be painted (Define Pattern's 8000 × 8000 fits). Larger
|
||
/// patterns paint nothing.
|
||
pub const MAX_PAINT_PIXELS: u64 = 1 << 26;
|
||
|
||
/// A bounded, cancellable pattern hash could not be completed.
|
||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||
pub enum PatternBuildError {
|
||
InvalidDimensions,
|
||
ScratchLimit { required: usize, available: usize },
|
||
Allocation(AllocationError),
|
||
Cancelled,
|
||
}
|
||
|
||
impl std::fmt::Display for PatternBuildError {
|
||
/// Report pattern dimension, scratch, allocation and cancellation failures with the relevant bounded-build context.
|
||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||
match self {
|
||
Self::InvalidDimensions => f.write_str("pattern dimensions exceed native edge or paint limits"),
|
||
Self::ScratchLimit { required, available } => write!(f, "pattern hash needs {required} scratch bytes; {available} available"),
|
||
Self::Allocation(error) => error.fmt(f),
|
||
Self::Cancelled => f.write_str("pattern creation cancelled"),
|
||
}
|
||
}
|
||
}
|
||
|
||
impl std::error::Error for PatternBuildError {
|
||
/// Expose an underlying allocation failure while keeping validation and cancellation errors self-contained.
|
||
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
|
||
match self {
|
||
Self::Allocation(error) => Some(error),
|
||
_ => None,
|
||
}
|
||
}
|
||
}
|
||
/// Most bytes of working copy the CPU compositor holds for one pattern (`photocraft-compose`
|
||
/// checks the two agree at build time). See [`Pattern::working_bytes`]. A browser tab has far less
|
||
/// memory than a desktop process, and a failed allocation there aborts the tab, so the web build
|
||
/// holds half as much: an 8-bit pattern paints up to 33,554,432 px (about 5792²) there.
|
||
#[cfg(not(target_arch = "wasm32"))]
|
||
pub const MAX_WORKING_BYTES: u64 = 256 << 20;
|
||
/// See the desktop value above.
|
||
#[cfg(target_arch = "wasm32")]
|
||
pub const MAX_WORKING_BYTES: u64 = 128 << 20;
|
||
|
||
/// Rows of a pattern read at a time where a whole-tile `f32` copy would cost 16 bytes per pixel.
|
||
pub const BAND_ROWS: u32 = 256;
|
||
|
||
/// One pattern tile. Pixels cover `0..width × 0..height` of `surface`, in any pixel format
|
||
/// (depth and colour model are the pattern's own, as in Photoshop).
|
||
#[derive(Clone, Debug, PartialEq)]
|
||
pub struct Pattern {
|
||
/// Unique id (a UUID string, as Photoshop's `Idnt`).
|
||
pub id: String,
|
||
/// Name as stored (Photoshop's built-ins use `$$$/Patterns/…=Display Name`; see
|
||
/// [`Pattern::display_name`]).
|
||
pub name: String,
|
||
pub width: u32,
|
||
pub height: u32,
|
||
pub surface: Surface,
|
||
}
|
||
|
||
/// 64-bit FNV-1a, used for deterministic pattern ids.
|
||
fn fnv(h: u64, bytes: &[u8]) -> u64 {
|
||
bytes.iter().fold(h, |h, b| (h ^ u64::from(*b)).wrapping_mul(0x0100_0000_01b3))
|
||
}
|
||
|
||
impl Pattern {
|
||
/// Construct a pattern using at most one fallibly allocated normalized pixel
|
||
/// row while hashing. The id matches [`Self::new`] for the same input.
|
||
///
|
||
/// `max_scratch_bytes` is the caller's remaining allowance for the temporary
|
||
/// hash row; the already-owned surface must be accounted for separately.
|
||
/// Native edge/paint limits and scratch size are checked before allocation.
|
||
/// Cancellation is checked before each row and before committing the result.
|
||
pub fn try_new_in(
|
||
name: impl Into<String>,
|
||
surface: Surface,
|
||
width: u32,
|
||
height: u32,
|
||
max_scratch_bytes: usize,
|
||
ctl: &Interrupt<'_>,
|
||
) -> Result<Pattern, PatternBuildError> {
|
||
ctl.check().map_err(|_| PatternBuildError::Cancelled)?;
|
||
if width == 0 || height == 0 || width > MAX_EDGE || height > MAX_EDGE || u64::from(width) * u64::from(height) > MAX_PAINT_PIXELS {
|
||
return Err(PatternBuildError::InvalidDimensions);
|
||
}
|
||
let row_bytes = usize::try_from(width)
|
||
.ok()
|
||
.and_then(|w| w.checked_mul(surface.channels()))
|
||
.and_then(|n| n.checked_mul(std::mem::size_of::<f32>()))
|
||
.ok_or(PatternBuildError::Allocation(AllocationError::SizeOverflow))?;
|
||
if row_bytes > max_scratch_bytes {
|
||
return Err(PatternBuildError::ScratchLimit { required: row_bytes, available: max_scratch_bytes });
|
||
}
|
||
let name = name.into();
|
||
let mut h1 = fnv(0xcbf2_9ce4_8422_2325, name.as_bytes());
|
||
h1 = fnv(h1, &width.to_le_bytes());
|
||
h1 = fnv(h1, &height.to_le_bytes());
|
||
// Dimensions are already bounded by MAX_EDGE < i32::MAX.
|
||
for y in 0..height {
|
||
ctl.check().map_err(|_| PatternBuildError::Cancelled)?;
|
||
let row = surface.try_read_region(Rect::new(0, y as i32, width as i32, (y + 1) as i32)).map_err(PatternBuildError::Allocation)?;
|
||
for value in row {
|
||
h1 = fnv(h1, &value.to_bits().to_le_bytes());
|
||
}
|
||
}
|
||
ctl.check().map_err(|_| PatternBuildError::Cancelled)?;
|
||
let h2 = fnv(h1 ^ 0x9e37_79b9_7f4a_7c15, format!("{:?}", surface.format()).as_bytes());
|
||
let id = format!("{:08x}-{:04x}-{:04x}-{:04x}-{:012x}", (h1 >> 32) as u32, (h1 >> 16) as u16, h1 as u16, (h2 >> 48) as u16, h2 & 0xffff_ffff_ffff);
|
||
Ok(Pattern { id, name, width, height, surface })
|
||
}
|
||
|
||
/// A pattern with an id derived from its name and pixels (same content → same id, so
|
||
/// defining a pattern is deterministic and replayable).
|
||
pub fn new(name: impl Into<String>, surface: Surface, width: u32, height: u32) -> Pattern {
|
||
let name = name.into();
|
||
let mut h1 = fnv(0xcbf2_9ce4_8422_2325, name.as_bytes());
|
||
h1 = fnv(h1, &width.to_le_bytes());
|
||
h1 = fnv(h1, &height.to_le_bytes());
|
||
// The samples row by row, a band at a time: the same sequence as one read of the whole
|
||
// tile, without a full-size `f32` copy of a large pattern.
|
||
let mut band = Vec::new();
|
||
for top in (0..height).step_by(BAND_ROWS as usize) {
|
||
let bottom = (top + BAND_ROWS).min(height);
|
||
surface.read_region_into(Rect::new(0, top as i32, width as i32, bottom as i32), &mut band);
|
||
for v in &band {
|
||
h1 = fnv(h1, &v.to_bits().to_le_bytes());
|
||
}
|
||
}
|
||
let h2 = fnv(h1 ^ 0x9e37_79b9_7f4a_7c15, format!("{:?}", surface.format()).as_bytes());
|
||
let id = format!("{:08x}-{:04x}-{:04x}-{:04x}-{:012x}", (h1 >> 32) as u32, (h1 >> 16) as u16, h1 as u16, (h2 >> 48) as u16, h2 & 0xffff_ffff_ffff);
|
||
Pattern { id, name, width, height, surface }
|
||
}
|
||
|
||
/// The name shown in UIs: Photoshop's localisation keys (`$$$/Patterns/…=Water`) show
|
||
/// the text after `=`; trailing NULs are dropped.
|
||
pub fn display_name(&self) -> &str {
|
||
display_name(&self.name)
|
||
}
|
||
|
||
/// The tile's rectangle.
|
||
pub fn rect(&self) -> Rect {
|
||
Rect::new(0, 0, self.width as i32, self.height as i32)
|
||
}
|
||
|
||
/// Whether the tile has pixels.
|
||
pub fn is_empty(&self) -> bool {
|
||
self.width == 0 || self.height == 0
|
||
}
|
||
|
||
/// Pixels in the tile (`width × height`, never overflowing).
|
||
pub fn pixel_count(&self) -> u64 {
|
||
u64::from(self.width) * u64::from(self.height)
|
||
}
|
||
|
||
/// Bytes of working copy the compositor holds to paint this pattern. One that fits is expanded
|
||
/// to premultiplied `f32` RGBA (16 per pixel). A pattern too large for that is held at its own
|
||
/// depth instead, straight RGBA at 4 bytes per pixel for 8 bits and 8 for 16 bits: exactly its
|
||
/// values, in a quarter or half the memory. A float one has no smaller exact form.
|
||
pub fn working_bytes(&self) -> u64 {
|
||
working_bytes_for(self.pixel_count(), self.surface.format().sample)
|
||
}
|
||
|
||
/// Why this pattern paints nothing, for the person or agent who chose it; `None` when it
|
||
/// paints. A pattern too large for the compositor's working copy renders as transparent, so
|
||
/// every command that picks a pattern, and the import that brought it in, says so.
|
||
pub fn paint_problem(&self) -> Option<String> {
|
||
if self.is_paintable() {
|
||
return None;
|
||
}
|
||
if self.is_empty() {
|
||
return Some("it is empty".into());
|
||
}
|
||
let sample = self.surface.format().sample;
|
||
Some(format!(
|
||
"it is {} × {} px at {} bits per channel, and a pattern of that depth paints up to {} px in all",
|
||
self.width,
|
||
self.height,
|
||
sample.bytes() * 8,
|
||
max_paint_pixels(sample)
|
||
))
|
||
}
|
||
|
||
/// Whether the tile has pixels and is small enough to paint (see [`MAX_PAINT_PIXELS`] and
|
||
/// [`MAX_WORKING_BYTES`]).
|
||
pub fn is_paintable(&self) -> bool {
|
||
!self.is_empty() && self.pixel_count() <= MAX_PAINT_PIXELS && self.working_bytes() <= MAX_WORKING_BYTES
|
||
}
|
||
}
|
||
|
||
/// [`Pattern::working_bytes`] of a pattern of `pixels` pixels with `sample` samples.
|
||
pub fn working_bytes_for(pixels: u64, sample: SampleType) -> u64 {
|
||
let expanded = pixels.saturating_mul(16);
|
||
if expanded <= MAX_WORKING_BYTES {
|
||
return expanded;
|
||
}
|
||
match sample {
|
||
SampleType::U8 => pixels.saturating_mul(4),
|
||
SampleType::U16 => pixels.saturating_mul(8),
|
||
SampleType::F32 => expanded,
|
||
}
|
||
}
|
||
|
||
/// Most pixels a pattern with `sample` samples may have and still paint: [`MAX_PAINT_PIXELS`] for
|
||
/// 8 bits, fewer where the working copy is larger per pixel.
|
||
pub fn max_paint_pixels(sample: SampleType) -> u64 {
|
||
match sample {
|
||
SampleType::U8 => MAX_PAINT_PIXELS,
|
||
SampleType::U16 => MAX_PAINT_PIXELS.min(MAX_WORKING_BYTES / 8),
|
||
SampleType::F32 => MAX_PAINT_PIXELS.min(MAX_WORKING_BYTES / 16),
|
||
}
|
||
}
|
||
|
||
/// Display form of a stored pattern name (see [`Pattern::display_name`]).
|
||
pub fn display_name(name: &str) -> &str {
|
||
let n = name.trim_end_matches('\0');
|
||
match n.strip_prefix("$$$/").and_then(|r| r.split_once('=')) {
|
||
Some((_, shown)) => shown,
|
||
None => n,
|
||
}
|
||
}
|
||
|
||
/// Finds a pattern by id, else by stored name, else by display name (case-insensitive).
|
||
pub fn find<'a>(patterns: &'a [Pattern], id: &str, name: &str) -> Option<&'a Pattern> {
|
||
if !id.is_empty()
|
||
&& let Some(p) = patterns.iter().find(|p| p.id == id)
|
||
{
|
||
return Some(p);
|
||
}
|
||
if name.is_empty() {
|
||
return None;
|
||
}
|
||
patterns.iter().find(|p| p.name == name).or_else(|| patterns.iter().find(|p| p.display_name().eq_ignore_ascii_case(display_name(name))))
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use super::*;
|
||
use photocraft_color::PixelFormat;
|
||
|
||
#[test]
|
||
fn ids_are_deterministic_and_lookup_falls_back_to_names() {
|
||
let mut s = Surface::new(PixelFormat::RGBA8);
|
||
s.fill_rect(Rect::new(0, 0, 4, 4), &[1.0, 0.0, 0.0, 1.0]);
|
||
let a = Pattern::new("$$$/Patterns/Defaults/Water=Water", s.clone(), 4, 4);
|
||
let b = Pattern::new("$$$/Patterns/Defaults/Water=Water", s.clone(), 4, 4);
|
||
assert_eq!(a.id, b.id);
|
||
assert_eq!(a.id.len(), 36);
|
||
assert_ne!(Pattern::new("Other", s, 4, 4).id, a.id);
|
||
assert_eq!(a.display_name(), "Water");
|
||
let list = vec![a.clone()];
|
||
assert!(find(&list, &a.id, "").is_some());
|
||
assert!(find(&list, "nope", "water").is_some());
|
||
assert!(find(&list, "nope", "").is_none());
|
||
}
|
||
|
||
#[test]
|
||
/// Compare streamed pattern creation with the existing content IDs across modes/depths, alpha layouts and sparse
|
||
/// row/tile boundaries.
|
||
fn bounded_row_hash_matches_existing_ids_for_native_depths_models_and_alpha() {
|
||
use photocraft_color::{ColorMode, SampleType};
|
||
for mode in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk] {
|
||
for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
|
||
for alpha in [false, true] {
|
||
let format = PixelFormat::new(mode, depth, alpha);
|
||
let mut surface = Surface::new(format);
|
||
// Cross both a tile and a row boundary, including sparse pixels.
|
||
let rect = Rect::new(0, 0, 67, 3);
|
||
let values = (0..67 * 3 * format.channels()).map(|n| (n % 19) as f32 / 16.0 - 0.125).collect::<Vec<_>>();
|
||
surface.write_region(rect, &values);
|
||
let existing = Pattern::new("Original row hash", surface.clone(), 67, 4);
|
||
let streamed = Pattern::try_new_in("Original row hash", surface, 67, 4, 67 * format.channels() * 4, &Interrupt::NONE).unwrap();
|
||
assert_eq!(streamed, existing, "{mode:?}/{depth:?}/alpha={alpha}");
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
/// Refuse invalid dimensions and insufficient row scratch before reading or allocating pixel data.
|
||
fn bounded_hash_rejects_hostile_extents_and_scratch_before_pixel_reads() {
|
||
for (width, height) in [(0, 1), (1, 0), (MAX_EDGE + 1, 1), (1, MAX_EDGE + 1), (MAX_EDGE, MAX_EDGE), (u32::MAX, 1)] {
|
||
let result = Pattern::try_new_in("Too large", Surface::new(PixelFormat::RGBA8), width, height, usize::MAX, &Interrupt::NONE);
|
||
assert_eq!(result, Err(PatternBuildError::InvalidDimensions));
|
||
}
|
||
assert_eq!(
|
||
Pattern::try_new_in("No scratch", Surface::new(PixelFormat::RGBA8), 30000, 1, 0, &Interrupt::NONE),
|
||
Err(PatternBuildError::ScratchLimit { required: 30000 * 4 * 4, available: 0 })
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
/// Verify cancellation is checked both before pattern work and during row-wise hashing.
|
||
fn bounded_hash_checks_cancellation_before_and_between_rows() {
|
||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||
let cancelled = || true;
|
||
assert_eq!(
|
||
Pattern::try_new_in("Cancelled", Surface::new(PixelFormat::RGBA8), 1, 1, 16, &Interrupt::cancel_only(&cancelled)),
|
||
Err(PatternBuildError::Cancelled)
|
||
);
|
||
let checks = AtomicUsize::new(0);
|
||
let cancel = || checks.fetch_add(1, Ordering::Relaxed) >= 3;
|
||
let result = Pattern::try_new_in("Mid-row cancellation", Surface::new(PixelFormat::RGBA8), 1, 20, 16, &Interrupt::cancel_only(&cancel));
|
||
assert_eq!(result, Err(PatternBuildError::Cancelled));
|
||
assert_eq!(checks.load(Ordering::Relaxed), 4);
|
||
}
|
||
|
||
/// The id is a hash of every sample in row-major order; reading a tall pattern a band of rows
|
||
/// at a time must give the id one whole read gave, or saved documents would lose their
|
||
/// pattern links.
|
||
#[test]
|
||
fn the_id_of_a_tall_pattern_matches_a_single_read_of_it() {
|
||
let (w, h) = (7u32, BAND_ROWS * 2 + 37);
|
||
let mut s = Surface::new(PixelFormat::RGBA8);
|
||
for y in 0..h as i32 {
|
||
for x in 0..w as i32 {
|
||
s.fill_rect(Rect::new(x, y, x + 1, y + 1), &[(x % 5) as f32 / 4.0, (y % 7) as f32 / 6.0, ((x + y) % 3) as f32 / 2.0, 1.0]);
|
||
}
|
||
}
|
||
let name = "tall";
|
||
let mut h1 = fnv(0xcbf2_9ce4_8422_2325, name.as_bytes());
|
||
h1 = fnv(h1, &w.to_le_bytes());
|
||
h1 = fnv(h1, &h.to_le_bytes());
|
||
for v in s.read_region(Rect::new(0, 0, w as i32, h as i32)) {
|
||
h1 = fnv(h1, &v.to_bits().to_le_bytes());
|
||
}
|
||
let h2 = fnv(h1 ^ 0x9e37_79b9_7f4a_7c15, format!("{:?}", s.format()).as_bytes());
|
||
let expected =
|
||
format!("{:08x}-{:04x}-{:04x}-{:04x}-{:012x}", (h1 >> 32) as u32, (h1 >> 16) as u16, h1 as u16, (h2 >> 48) as u16, h2 & 0xffff_ffff_ffff);
|
||
assert_eq!(Pattern::new(name, s, w, h).id, expected);
|
||
}
|
||
|
||
#[test]
|
||
fn working_bytes_keep_a_pattern_exact_in_less_memory() {
|
||
let sparse =
|
||
|format: PixelFormat, width: u32, height: u32| Pattern { id: String::new(), name: String::new(), width, height, surface: Surface::new(format) };
|
||
let float = PixelFormat::new(photocraft_color::ColorMode::Rgb, SampleType::F32, true);
|
||
// What fits is expanded as before.
|
||
assert_eq!(sparse(PixelFormat::RGBA8, 10, 10).working_bytes(), 1600);
|
||
assert_eq!(sparse(float, 4096, 4096).working_bytes(), MAX_WORKING_BYTES);
|
||
// Past that, a pattern is held at its own depth.
|
||
assert_eq!(sparse(PixelFormat::RGBA8, 8000, 8000).working_bytes(), 256_000_000);
|
||
assert_eq!(sparse(PixelFormat::RGBA16, 5000, 5000).working_bytes(), 200_000_000);
|
||
assert!(sparse(PixelFormat::RGBA8, 8000, 8000).is_paintable());
|
||
assert!(sparse(PixelFormat::RGBA16, 5792, 5792).is_paintable());
|
||
assert!(!sparse(PixelFormat::RGBA16, 8000, 8000).is_paintable(), "512 MB at 16 bits");
|
||
assert!(!sparse(float, 4097, 4096).is_paintable(), "float has no smaller exact form");
|
||
assert!(!sparse(PixelFormat::RGBA8, 9000, 8000).is_paintable());
|
||
assert!(!sparse(PixelFormat::RGBA8, 0, 8).is_paintable());
|
||
}
|
||
|
||
#[test]
|
||
fn a_pattern_that_paints_nothing_says_why() {
|
||
let sparse =
|
||
|format: PixelFormat, width: u32, height: u32| Pattern { id: String::new(), name: String::new(), width, height, surface: Surface::new(format) };
|
||
let float = PixelFormat::new(photocraft_color::ColorMode::Rgb, SampleType::F32, true);
|
||
assert_eq!(sparse(PixelFormat::RGBA8, 8000, 8000).paint_problem(), None);
|
||
assert_eq!(sparse(PixelFormat::RGBA8, 0, 4).paint_problem().as_deref(), Some("it is empty"));
|
||
let reason = sparse(float, 5000, 5000).paint_problem().expect("float 5000 x 5000 paints nothing");
|
||
assert!(reason.contains("5000 × 5000") && reason.contains("32 bits") && reason.contains("16777216"), "{reason}");
|
||
let reason = sparse(PixelFormat::RGBA16, 8000, 8000).paint_problem().expect("16-bit 8000 x 8000 paints nothing");
|
||
assert!(reason.contains("16 bits") && reason.contains("33554432"), "{reason}");
|
||
}
|
||
}
|