Skip to content

LR-EDIT-EFFECTS-GRAIN: replace grid noise with signed particle grain - #2330

Open
SourceFelony wants to merge 2 commits into
storytold:mainfrom
SourceFelony:experiment/medium-film-grain
Open

SourceFelony wants to merge 2 commits into
storytold:mainfrom
SourceFelony:experiment/medium-film-grain

Conversation

@SourceFelony

@SourceFelony SourceFelony commented Oct 19, 2026 •

Copy link
Copy Markdown

Summary

Replace the smooth grid/value-noise grain overlay with a small, independently authored signed-particle renderer. This is an alternative approach to the texture problem described in #801 and the existing particle-grain proposal in #1060, not a continuation of that PR.

The goal is a simpler film-inspired texture while retaining the existing Amount, Size and Roughness controls. This implementation has been visually evaluated on photographic sky and detail regions. It is an artistic approximation, not an exact Boolean-model implementation, measured film-stock simulation, or claim of Lightroom parity.

Changes

  • Sum seeded, continuously positioned Gaussian particle footprints in absolute oriented source coordinates, with native-source scaling and approximate reduction filtering.
  • Remove the previous CPU grid-noise renderer and WGSL grain kernel/parameters. There is no legacy renderer selector.
  • Route active grain through the existing CPU fallback. Zero grain and disabled Effects remain GPU eligible.
  • Normalize missing, legacy and mediumParticlesV1 process inputs to the sole current renderer, preserving existing numeric values. Unknown process names are rejected. Canonical serialization changes settings/cache keys to avoid reusing old-grain renders.
  • Default Roughness and its control reset to 0; Amount remains 0 and Size 25. Suggested comparison settings: Amount 40, Size 25, Roughness 0, seed 2026.
  • Add render/export, migration, presets, copy/paste, sync, Auto Sync, undo/redo and GPU-eligibility regressions; document the method and limits in docs/experimental-medium-grain.md.

Intentional behavior change and limitations

Existing edits containing grain render differently. Numeric settings load unchanged, but the previous texture is not preserved. Older released applications do not understand the new process and should not be used to round-trip these edits.

Active grain is CPU-only and forces the entire request onto CPU, even when a GPU is available. This is a material tradeoff compared with the GPU-enabled alternative in #1060. Earlier single runs on an M1 Max with concurrent compilation took 2.05 seconds total for a 2000×1333 preview and 10.96 seconds for a 7728×5152 native export. These are qualified observations, not controlled benchmarks or performance-parity claims.

Gaussian aperture filtering, finite tail truncation and extreme-reduction fade-out are approximations. The implementation does not reproduce the Boolean reference's occupancy statistics or claim exact downsampling equivalence. GPU implementation, measured-stock calibration and further performance work are outside this PR. No personal photographs, comparison fixtures, or external reference implementation are committed.

Please evaluate the texture/complexity tradeoff and intentional appearance break against #1060 rather than treating this as an assertion that one model is universally preferable.

Verification

Rebased onto d999e382bafbb5d5c54482fdb1d11f6a63bfdf69.

  • cargo xtask ci: all eight gates passed on macOS arm64, Rust 1.97.1, Apple M1 Max Metal. Includes formatting, strict all-targets workspace Clippy, HEIF, tests, parity, layers, assets and 29 WASM compile checks.
  • Workspace summaries: 4,186 passed, 0 failed, 35 ignored. The CI report also explicitly records 165 availability skips: 137 corpus, 20 fonts and 8 models. Those unavailable checks were not exercised.
  • 11 focused tests passed: 7 pipeline, 2 engine and 2 GPU. The zero/disabled-grain Metal comparison actually executed.
  • Photographic comparison visually approved in the local experimental app. Automated app screenshots used the documented headless capture fallback; native compositor screenshot acceptance is not claimed.
  • WASM was compile-checked, not browser-executed. Windows/Linux runtime coverage is not claimed.

Maintainer review and repository CI are still required. Please do not merge solely on the local verification report.

Summary by CodeRabbit

  • New Features

    • Grain now uses an experimental particle-based rendering style, with repeatable results for a fixed seed and consistent appearance across aligned crops and previews.
    • Existing grain settings load with their numeric values preserved, including settings saved with the legacy process name.
  • Changes

    • The default grain roughness is now zero. Active grain renders on the CPU; requests with grain disabled or zero amount can still use GPU rendering.
    • Saving settings records the canonical grain process name.

John Kittleson and others added 2 commits October 19, 2026 09:43
Migrate existing grain settings to the sole particle renderer, preserve numeric edits, and explicitly fall back from GPU for active grain. Add render/export, settings, sync and undo regressions; document the intentional appearance break and approximation/performance limits.

Co-authored-by: Hermes Agent <hermes@nousresearch.com>
Full cargo xtask ci passed all eight gates on the rebased implementation; record the expanded upstream workspace coverage. Optional corpus, font and model skips remain explicitly disclosed.

Co-authored-by: Hermes Agent <hermes@nousresearch.com>
@coderabbitai

coderabbitai Bot commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 049b3ad3-5181-49e4-93b3-725332fc5066
📥 Commits

Reviewing files that changed from the base of the PR and between d999e38 and dd7537d.

⛔ Files ignored due to path filters: 1
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing: 18
  • crates/develop/src/controls.rs
  • crates/develop/src/settings.rs
  • crates/engine/src/lib.rs
  • crates/engine/src/tests_medium_grain.rs
  • crates/engine/src/tests_process.rs
  • crates/gpu/Cargo.toml
  • crates/gpu/src/ctx.rs
  • crates/gpu/src/lib.rs
  • crates/gpu/src/params.rs
  • crates/gpu/src/wgsl/finish.wgsl
  • crates/gpu/tests/equivalence.rs
  • crates/gpu/tests/medium_grain.rs
  • crates/pipeline/src/finish.rs
  • crates/pipeline/src/grain.rs
  • crates/pipeline/src/lib.rs
  • crates/pipeline/tests/medium_grain.rs
  • docs/experimental-medium-grain.md
  • docs/parity-checklist.md
💤 Files with no reviewable changes: 1
  • crates/gpu/src/params.rs

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

📝 Walkthrough

The grain settings now identify the mediumParticlesV1 process, and the CPU pipeline uses signed particles to render grain. Requests with active grain bypass GPU rendering. Tests and documentation cover settings compatibility, rendering behavior, and GPU eligibility.

Changes: Grain renderer

Layer / File(s) Summary
Grain process settings and compatibility
crates/develop/src/settings.rs, crates/develop/src/controls.rs, crates/engine/src/*, crates/pipeline/tests/medium_grain.rs, docs/experimental-medium-grain.md
Grain settings add a process field with MediumParticlesV1 as the default and "legacy" as an alias. The default roughness changes to 0. Tests cover normalization across settings, presets, sync, undo/redo, and sidecars.
CPU particle rendering
crates/pipeline/src/grain.rs, crates/pipeline/src/finish.rs, crates/pipeline/src/lib.rs, crates/pipeline/tests/medium_grain.rs, docs/experimental-medium-grain.md, docs/parity-checklist.md
The pipeline creates seeded particle grain and applies its residual during finishing. Tests cover repeatability, crop and preview behavior, exports, and no-op conditions. Documentation describes the renderer, its limitations, and validation.
GPU fallback for active grain
crates/gpu/Cargo.toml, crates/gpu/src/*, crates/gpu/tests/*
try_render returns Fallback::NotTried when effects are enabled and grain amount is positive. GPU grain shader code and parameters are removed. GPU tests cover fallback eligibility and equivalence cases without active grain.

Priority: ➖ Normal

Estimated code review effort: 4 (Complex) | ~45 minutes

Change: Feature

Sequence Diagram(s)

sequenceDiagram
  participant Caller
  participant try_render
  participant finish_with
  participant Particles
  Caller->>try_render: Request render with active grain
  try_render-->>Caller: Return Fallback::NotTried
  Caller->>finish_with: Render on CPU
  finish_with->>Particles: Compute grain residual
Loading

Suggested reviewers: echelon

Merge Risk: 🔵 Low · up to dd753

Existing grain edits will render differently, and older app versions should not be used to round-trip them. Active grain now renders on the CPU, which may be slower. No concrete defect was found, so this is mergeable with awareness of these documented tradeoffs.

Security architecture risk: 🔵 Low · up to dd753

Existing grain edits intentionally change appearance and may render more slowly. No new privilege or data-access path was identified in the reviewed changes, but saved-history recovery and broader security coverage remain incomplete.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The demonstrated new exposure is settings- and image-dependent CPU computation within the existing render caller. The inspected flow establishes no new credential, tenant, network, or privileged execution transition. This conclusion is limited to the traced rendering and settings paths.

Trust Boundaries and Controls

  • observed — The process name selects no arbitrary implementation: the enum has one supported variant, and legacy is only an alias. The reported high-fanout rendering seam is a test function, not a newly exposed production endpoint.

Resilience and Maintainability Implications

  • observed — The grain admission decision occurs before GPU device acquisition and render-side cache work, so it does not introduce a partially completed GPU-to-CPU transition. CPU-only rendering can increase latency; particle work is bounded, but total decode and output-buffer resource limits remain those of the existing pipeline.
Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 70.37% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 27 functions across 13 files. (4 skipped:… Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title clearly and concisely describes the main change: replacing the existing grain noise implementation with signed particle grain.
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Docstring Coverage

Explanation

Docstring coverage is 70.37% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 27 functions across 13 files. (4 skipped: 4 unsupported.)

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

  • Fix all pre-merge checks with AI
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Warning

Some tools did not complete. Review the errors below.

🔧 Clippy (1.98.1)

Clippy execution timed out

Comment @coderabbitai help to get the list of available commands.

@FredApps FredApps left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I read the whole diff (grain.rs, the finish.rs and GPU removals, settings.rs, the three new test files and the docs). I haven't built or run it (no cargo here), and I can't judge how the grain looks, so this is by my reading. I'm leaving this as a comment and not an approval: it replaces the grain renderer for everyone, makes it slower by the PR's own numbers, and its author asks for a maintainer's decision against #1060 (open, with a review from AlexChambers). That choice isn't mine to make, and I have two smaller points on top.

What I checked (and it holds).

  • try_render returns Fallback::NotTried when section_enabled("effects") && grain.amount > 0.0, the same condition FinishParams::new uses for effects and the amount, and try_render has one non-gpu caller on main (engine/src/media.rs:1055) which falls back to the CPU on any Err, so the "callers render every NotTried request on the CPU" claim is true.
  • The removed constants (GRAIN_HASH, the GRAIN_H* WGSL consts, the four grain FinishParams fields) have no other user on the PR head; the leftover params.rs and finish.wgsl hunks are only those.
  • Particles is bounded: the loop covers extent of at most about 3.5σ at the base variance (a handful of 2 px cells per axis), the coordinates are range-checked, and a grain at pitch ≥ 32 returns None before any work. I found no panic path, and negative cell indices only go through wrapping_mul on as u32.
  • GrainProcess takes legacy and mediumParticlesV1 and rejects other strings; stored amount, size, roughness and seed load unchanged.

1. Decision (hold for a maintainer): one renderer, CPU only, an appearance break, against #1060.

  • Every photo with grain amount > 0 leaves the GPU for the whole request, not only for the grain. The PR's own table (a private 7728 × 5152 source, one M1 Max run, forced CPU, with concurrent compilation) has the native export finishing in 5,225 ms with grain against 1,194 ms without (4.4×), 10.96 s against 6.51 s in total, and the docs say both native runs "miss the repository's ≤1s/24MP export aspiration". The author calls these observations, not benchmarks, and I agree they can't be used as a measurement either way. Rule 5 asks for a measured gain on a speed change; this is the reverse, a measured loss, and nothing says how the dragged-draft path behaves (the docs say the GPU capability heuristic is unchanged, so drafts may be slower).
  • Every saved edit with grain renders differently (the description and the docs say so), and older builds render their own old grain from the same file, so one catalog opened on two versions shows two looks.
  • There is no selector, so a maintainer can't ship this beside #1060's renderer and compare; if the project prefers #1060's GPU approach this PR is the wrong one, and if this one is preferred #1060 should be closed. Please don't merge before that is settled in one place.

2. The Roughness default changes from 50 to 0, and not only for the new renderer. controls.rs and Grain::default both move to 0. Anything that reaches roughness through the default now differs, not only the "reset" button: the built-in preset at engine/src/presets.rs:263 sets just {"amount": 15.0}, the XMP import maps GrainFrequency to grain.roughness (crs.rs:385) and so a file with GrainAmount but no GrainFrequency lands on 0 instead of 50, and --set grain.amount=… on the CLI does too. The description says only that the Roughness reset default is 0. If 0 is needed for the particle model, keep the old default for those paths (or state what changes for them); if it isn't, leave 50 as it was.

3. Question on provenance of the constants. The docs call the work "original clean-room Rust", but BASE_VARIANCE = 0.8² + 0.65²/4 and the size mapping (0.25 + 0.016·size)/0.65 come from "the selected reference aperture" and "the Medium target" of a "Boolean disk reference" that the docs never name. Please name that reference and its licence, and say whether its source (not only the paper) was read. The "Experimental fork" and "This fork has one renderer" wording in settings.rs and the parity checklist reads oddly in this repo; please say what is meant or drop it.

No UI strings are added, so no catalogs are affected, and the parity row moving from ✅ to 🟡 matches the PR text.

Validation request (head dd7537d2af310b5caf9d34c0d8a9d974e82fbd45; after the decision above):

  • os: linux and windows (the local run is macOS arm64 only, as the description says)
  • commands: cargo fmt --all -- --check; cargo clippy --workspace --all-targets --locked --offline -- -D warnings; cargo test -p lightcraft-pipeline -p lightcraft-engine -p lightcraft-gpu --locked --offline; cargo xtask ci; export the same raw at native size with grain 0 and grain 40 (LIGHTCRAFT_GPU=0 for both, and once on the GPU for the no-grain case) and report the wall times; a drag in Develop with grain 40 on a 24 MP photo
  • expected: all pass, 0 ignored, and no unexplained availability skips for the grain tests; export times of the same order as the PR's table
  • holds: the renderer decision against #1060 (point 1); the roughness default (point 2); the reference named (point 3); no receipt on Linux or Windows for this head

@FredApps FredApps left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code-only review at dd7537d; no CI has run on this head yet.

This changes how existing edits render without a new process, which docs/process-versions.md forbids ("A change that alters how existing settings render ships as a new process. V1 is frozen."). The description says existing edits containing grain "render differently", and crates/develop/src/settings.rs:606 maps the old process (legacy, and a missing field) onto the new renderer, while crates/pipeline/src/finish.rs deletes the grid-noise path outright.

  • Add the particle grain as the next Process (and keep the grid-noise grain for the earlier ones, branching in finish::base_tone's way on s.process.process()), so photos keep their look until Update to Current Process. Add the process to the cache key of any stage it changes.
  • The new GrainProcess enum duplicates what ProcessVersion is for; drop it, and keep settings_saved_before_process_versions_load_as_v1 passing.
  • Removing the GPU grain path (crates/gpu/src/lib.rs:470 returns NotTried for any active grain) sends the whole render to the CPU for every photo with grain. The author's own timings in the description are single runs on one machine; please keep GPU grain for the earlier process, and give a hardware log if the new one stays CPU-only.
  • Roughness default 50 to 0 (crates/develop/src/controls.rs:253) is a separate change to the controls; keep it out of this PR or justify it with the process change.
    Drop the "this fork" wording in the comments too.

@OneSlips

Copy link
Copy Markdown
Contributor

For the maintainers' choice between this PR and #1060, here are the concrete differences as of today, from both descriptions and the code.

Existing edits.

GPU.

Defaults and saved files.

Use. I tuned #1060's grain by hand on my own wedding work, 45 MP Canon EOS R5 C raws, since mid-October. I wanted texture I could leave visible without the softening Lightroom's grain adds, which is why I'd always kept Lightroom's grain very low.

If the project prefers this PR's look, #1060 picks the grain model per process (one match arm). This model could then be added as another process, rather than replacing the grain for everyone's existing edits.

@wanikhawar wanikhawar left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This changes crates/gpu/Cargo.toml: please confirm any new dependency's licence is on standards/licences.md (rule 26), and record where the particle-grain approach comes from (rule 24). It conflicts with main and has no CI results; please rebase.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants