Skip to content

fix(rgbw): NNLS out-of-hull projection (#2708) + in-test ground truth - #2709

Merged
zackees merged 2 commits into
masterfrom
fix/rgbw-ground-truth-test-2708
Jun 3, 2026
Merged

zackees merged 2 commits into
masterfrom
fix/rgbw-ground-truth-test-2708

Conversation

@zackees

@zackees zackees commented Jun 3, 2026 •

Copy link
Copy Markdown
Member

Closes #2708.

Single PR that lands both halves of the math-model gist's §3 + §5 contract:

  1. Implements the gist §3 NNLS out-of-hull projection in production code so sRGB-blue / Rec.2020-green inputs no longer collapse to (0,0,0,0).
  2. Ports the reference's strict sub-gamut + projection algorithm into the unit test as an independent ground-truth source, so future regressions in either the production code or the test mirror surface immediately.

#2708 — out-of-hull NNLS projection

When a source RGB triple mapped to an XYZ target outside the LED 4-emitter convex hull, the strict solver returned (0,0,0,0) because no sub-gamut triangle accepted the chromaticity. sRGB blue at xy ≈ (0.15, 0.06) was the canonical case — outside the LED's RBW and BGW triangles on the default profile.

Implementation:

  • colorimetric_detail::nnls3 (inline in rgbw_colorimetric.h): projected-gradient NNLS for 3×3 systems (500 iters @ step 0.01), matching the reference's scipy-less fallback. Alloc-free; only invoked when the target is out-of-hull.
  • project_to_hull (static in rgbw_colorimetric.cpp.hpp): runs NNLS in each of the three sub-gamuts (RGW / RBW / BGW), caps drive at 1.0 per sub-gamut, selects min-residual. Returns the achieved chromaticity at unit Y.
  • Wired into solve_strict_subgamut, solve_strict_subgamut_xy, and solve_wx_overdrive. The LUT builder reuses solve_strict_subgamut_xy so the rebuilt LUT cells contain projected RGBW for boundary samples.

In-test ground truth (no Python at test time)

tests/fl/gfx/rgbw_colorimetric.cpp gets two namespaces:

  • reference:: — port of xy_target_rgbw_model.py strict sub-gamut + §3 NNLS projection. Independent of production code.
  • fastled_mirror:: — text-copy of the production solver (kept in sync with .cpp.hpp for tests that can't link the colorimetric path).

Test cases

  1. FastLED strict subgamut agrees with reference port (in-hull) — 10 inputs (D65, primaries, secondaries, mixed). Asserts every channel within ±24 / 255 of the reference.
  2. out-of-hull sRGB blue: FastLED projects to match reference (#2708) — was the executable contract for bug(rgbw): out-of-hull source colors return (0,0,0,0) — missing NNLS projection (gist §3) #2708; now asserts FastLED produces non-trivial output AND matches the reference within ±1 / 255 (rounding only — both share the same NNLS).
  3. plus the existing source-space / boosted / Hermite tests from fix(rgbw): source RGB color space + differentiated boosted solver + Hermite LUT #2707.

Verification trail

Before trusting the C++ port as ground truth, three independent implementations were checked against each other on 14 test inputs across strict / boosted / native-gamut modes:

  1. Actual FastLED solver (production .cpp.hpp) — driven by a standalone harness compiled directly with clang++.
  2. C++ mirror in this test TU (fastled_mirror::strict_subgamut) — text-copy of the production code.
  3. Python mirror (compare_rgbw.py — scratch file, fetches the gist, mirrors FastLED's algorithm in Python).

All three produced bit-identical RGBW across every case before #2708 was implemented. After #2708, the reference port and FastLED now also agree on out-of-hull cases.

Drive-by fixes

  • src/platforms/arm/teensy/audio_input_teensy_config.h gains // IWYU pragma: private.
  • ci/lint_cpp/rust_bridge.py drops a redundant except KeyboardInterrupt: raise that the KBI checker flagged. Plain re-raise was a no-op.

Test plan

  • bash lint clean (Python, C++, JS)
  • bash test --cpp --clean passes 308/308 including the new ground-truth cases
  • sRGB pure blue now produces non-trivial RGBW matching the reference
  • CI green
  • CodeRabbit review addressed

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added a Python RGBW comparison tool to run FastLED vs. reference colorimetric models and diagnostics.
    • Improved RGBW solver behavior to project out-of-gamut targets onto the achievable gamut (preserves non-zero, chromatically consistent outputs).
  • Tests

    • Added ground-truth regression tests validating strict-subgamut and projected solutions against the reference model, including an out-of-gamut blue case.
  • Chores

    • Minor lint/config header annotation update.

…follow-up)

Adds two new test cases to fl_gfx_rgbw_colorimetric:

1. FastLED strict subgamut agrees with reference port (in-hull)
   Ports the math-model gist's strict sub-gamut + §3 NNLS hull projection
   into the test TU (`reference::strict_with_projection`). For ten in-hull
   inputs (D65 white, mid grey, red, green, cyan, magenta, yellow, cool
   blue, orange, dim grey), asserts every channel of FastLED's output
   stays within ±24 / 255 of the reference. FastLED's solver is mirrored
   inline (`fastled_mirror::strict_subgamut`) — exact text-copy of the
   production .cpp.hpp so the test exercises identical logic without
   depending on FASTLED_RGBW_COLORIMETRIC at library-build time.

2. out-of-hull sRGB blue: FastLED zeroes while reference projects
   Documents #2708 as an executable contract. sRGB pure blue at xy ≈
   (0.15, 0.06) lies outside all three LED sub-gamuts on the default
   profile; FastLED currently returns (0,0,0,0) while the reference's
   NNLS projection produces a real RGBW. When #2708 lands, this test
   fails and the assertion gets flipped to agree with the reference.

The reference port lives entirely in this TU — no Python at test time,
no new dependencies. NNLS is the same projected-gradient fallback the
reference uses on platforms without scipy (500 iters @ step 0.01).

Verification trail: while writing the test, a standalone harness drove
FastLED's actual solver code byte-for-byte (separate from this test TU)
and was compared against compare_rgbw.py (which mirrors the C++ logic
in Python). All three matched bit-exactly across strict/boosted/native
modes on 14 test inputs before the mirror was trusted as the in-test
ground truth.

Drive-by:
- Add IWYU pragma: private to audio_input_teensy_config.h (PostToolUse
  stop hook caught the missing pragma on the file I edited in #2707).
- Drop redundant `except KeyboardInterrupt: raise` in
  ci/lint_cpp/rust_bridge.py — KBI checker rule wants either an explicit
  _thread.interrupt_main() call or no catch at all. Plain `raise` was a
  no-op anyway since unhandled KI propagates naturally.

References:
- Math model gist: https://gist.github.com/JChalka/915603d7930b7216d5c5aae834ec2ea9
- Reference implementation gist: https://gist.github.com/JChalka/cebc5a018066cae05d98cf9088c3b3b9
- Comparison harness: compare_rgbw.py (uncommitted scratch file —
  fetches the gist, mirrors FastLED's algorithm in Python, prints
  side-by-side delta vs. the reference).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@coderabbitai

coderabbitai Bot commented Jun 3, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

This PR adds Python and C++ validation for FastLED's RGBW colorimetric solvers (strict and boosted), implements out-of-hull NNLS projection and an inline 3×3 NNLS helper, adds comparison tooling and tests, and applies small lint/header cleanup.

Changes

RGBW Colorimetric Validation Framework

Layer / File(s) Summary
Test scope and reference profile
compare_rgbw.py
Defines reference LED primaries, Rec709/D65 source inputs, and labeled test RGB cases; adds formatting helpers for output.
Color math primitives and profile caching
compare_rgbw.py
Implements xyY→XYZ, 3×3 inversion, source-space matrix construction, barycentric coordinate checks, and ProfileCache precomputations.
FastLED solver implementations
compare_rgbw.py
Adds FastLED-style strict-subgamut and wx-overdrive solver code paths and dispatch/quantization entrypoint.
Reference model integration
compare_rgbw.py
Wraps the external reference solver for 8-bit inputs, forwarding method/gamut/transfer/output-bit-depth parameters.
Python comparison framework and diagnostics
compare_rgbw.py
Runs strict vs. reference and boosted vs. reference comparisons, computes per-case deltas and aggregate L1/max errors, adds native-gamut diagnostic pass, and provides main() script entrypoint.
C++ mirror and projection updates
src/fl/gfx/rgbw_colorimetric.cpp.hpp, src/fl/gfx/rgbw_colorimetric.h, tests/fl/gfx/rgbw_colorimetric.cpp
Adds project_to_hull out-of-hull projection, integrates projection into solve_strict_subgamut/solve_strict_subgamut_xy/solve_wx_overdrive, introduces inline nnls3 helper, and adds ground-truth tests comparing FastLED mirror against reference projection.

Maintenance Updates

Layer / File(s) Summary
Linter and header cleanup
ci/lint_cpp/rust_bridge.py, src/platforms/arm/teensy/audio_input_teensy_config.h
Removes redundant KeyboardInterrupt re-raise from JSON decode handling; adds // IWYU pragma: private annotation to Teensy audio input header.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related issues

Possibly related PRs

Poem

🐰 I hopped through matrices, primaries, and white,
Projected stray blues back into the light.
I rounded the floats, checked each tiny delta,
And chirped as test green matched reference shelter.
Hooray — colors aligned, the rabbit takes a bite.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 56.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ 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 accurately summarizes the main change: adding NNLS out-of-hull projection to RGBW colorimetric solvers and test ground-truth verification, matching the commit message and PR objectives.
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/rgbw-ground-truth-test-2708

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 Infer (1.2.0)
tests/fl/gfx/rgbw_colorimetric.cpp

tests/fl/gfx/rgbw_colorimetric.cpp:19:10: fatal error: 'test.h' file not found
19 | #include "test.h"
| ^~~~~~~~
1 error generated.
Error: the following clang command did not run successfully:
/opt/infer-linux-x86_64-v1.2.0/lib/infer/facebook-clang-plugins/clang/install/bin/clang-18
@/tmp/coderabbit-infer/2cfc4720024ccd75d5a573f5221e257767686193-03cd3d9f6fe614dd/tmp/clang_command_.tmp.4aa1fb.txt
++Contents of '/tmp/coderabbit-infer/2cfc4720024ccd75d5a573f5221e257767686193-03cd3d9f6fe614dd/tmp/clang_command_.tmp.4aa1fb.txt':
"-cc1" "-load"
"/opt/infer-linux-x86_64-v1.2.0/lib/infer/infer/bin/../../facebook-clang-plugins/libtooling/build/FacebookClangPlugin.dylib"
"-add-plugin" "BiniouASTExporter" "-plugin-arg-BiniouASTExporter" "-"
"-plugin-arg-BiniouASTExporter" "PREPEND_CURRENT_DIR=1"
"-plugin-arg-BiniouASTExporter" "MAX_STRING_SIZE=65535" "-cc1" "-triple"
"x86_64-unknown-linux-gnu" "-emit-obj" "-mrelax-all" "-disable-free"
"-clea

... [truncated 1070 characters] ...

/lib/clang/18/include"
"-internal-isystem" "/usr/local/include" "-internal-isystem"
"/usr/lib/gcc/x86_64-linux-gnu/12/../../../../x86_64-linux-gnu/include"
"-internal-externc-isystem" "/usr/include/x86_64-linux-gnu"
"-internal-externc-isystem" "/include" "-internal-externc-isystem"
"/usr/include" "-Wno-ignored-optimization-argument" "-Wno-everything"
"-fdeprecated-macro" "-ferror-limit" "19" "-fgnuc-version=4.2.1"
"-fskip-odr-check-in-gmf" "-fcxx-exceptions" "-fexceptions"
"-D__GCC_HAVE_DWARF2_CFI_ASM=1" "-o"
"/tmp/coderabbit-infer/03cd3d9f6fe614dd/file.o" "-x" "c++"
"tests/fl/gfx/rgbw_colorimetric.cpp" "-O0" "-fno-builtin" "-include"
"/opt/infer-linux-x86_64-v1.2.0/lib/infer/infer/bin/../lib/clang_wrappers/global_defines.h"
"-Wno-everything"


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@fastled-project-sync fastled-project-sync Bot moved this to Triage in FastLED Tracker Jun 3, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 5

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@compare_rgbw.py`:
- Around line 269-275: Replace ambiguous Unicode glyphs in the diagnostic print
strings by using ASCII equivalents: change "Profile: %d×%d×%d × %d-LED
primaries..." to use "x" (e.g. "%dx%dx%d x %d-LED primaries..."), change the
header separator "FastLED − Ref (∆R,G,B,W)" to use plain hyphen and ASCII
delta/name (e.g. "FastLED - Ref (dR,dG,dB,dW)" or "FastLED - Ref
(ΔR,ΔG,ΔB,ΔW)"), and replace any "ρ" with "rho" in the other print strings;
update the literal strings used in the print(...) calls shown so all occurrences
(including the other grouped print statements at the same blocks) use ASCII-only
glyphs.
- Line 48: Update the function signatures to follow the repo contract: add
explicit type annotations for all parameters and return types and remove any
default parameter values. Specifically modify build_source_matrix(xy_r, xy_g,
xy_b, xy_w)->tuple[np.ndarray, bool] to include typed parameters, annotate
barycentric_xy, ProfileCache.__init__, solve_wx_overdrive, fastled_rgb_to_rgbw,
ref_rgb_to_rgbw, fmt, and main with explicit parameter and return types, and
remove defaults from solve_wx_overdrive, fastled_rgb_to_rgbw, and
ref_rgb_to_rgbw so no parameters have default values; ensure signatures match
the code usage sites after changes.
- Around line 81-106: ProfileCache currently ingests raw dicts and handles
positional tuples from helpers, so change the pipeline to use typed `@dataclass`
carriers and runtime validation: define dataclasses for the input profile (e.g.,
ProfileSpec) and for multi-value returns (e.g., XYZResult, InvertResult,
SourceMatrixResult), annotate functions xyY_to_XYZ, invert3x3, and
build_source_matrix to return those dataclasses instead of tuples, and decorate
dataclasses with `@typechecked` so invalid shapes/keys fail at construction; then
update ProfileCache.__init__ to accept a ProfileSpec (or construct one at its
start) and use field names (e.g., .xy_r, .lum_r, .P_W) and the new return types
(e.g., InvertResult.inv) when building P_RGB/P_RGW/P_RBW/P_BGW and computing
self.P_RGB_inv/self.d_W to ensure schema/shape validation occurs at data
boundaries.
- Around line 263-264: The delta function delta(a, b) currently computes b - a
but tables label the column as "FastLED - Ref"; change the implementation to
return tuple(int(a[i]) - int(b[i]) for i in range(4)) so the sign matches the
"FastLED - Ref" label (or alternatively update the label wherever delta is
used). Locate the delta function and adjust its return expression (or the
labeling logic) so per-case channel diagnostics reflect FastLED minus Reference
correctly.

In `@tests/fl/gfx/rgbw_colorimetric.cpp`:
- Around line 518-544: In build_cache, when build_source_matrix fails you only
flip cache->has_source_space but do not clear cache->M_src; change build_cache
so that after calling build_source_matrix you set cache->has_source_space =
result and if result is false zero out ProfileCache::M_src (e.g., set all
elements to 0) to match the production fallback behavior and keep the mirror
cache identical.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: ff9d5fd2-30ce-4509-8877-7e9e2720111e

📥 Commits

Reviewing files that changed from the base of the PR and between 6cd4a07 and 762c341.

📒 Files selected for processing (4)
  • ci/lint_cpp/rust_bridge.py
  • compare_rgbw.py
  • src/platforms/arm/teensy/audio_input_teensy_config.h
  • tests/fl/gfx/rgbw_colorimetric.cpp
💤 Files with no reviewable changes (1)
  • ci/lint_cpp/rust_bridge.py

Comment thread compare_rgbw.py Resolved
Comment thread compare_rgbw.py Resolved
Comment thread compare_rgbw.py Resolved
Comment thread compare_rgbw.py Resolved
Comment thread tests/fl/gfx/rgbw_colorimetric.cpp Resolved
Implements gist §3 hull projection so that source colors mapping outside
the LED 4-emitter convex hull (e.g. sRGB pure blue at xy ≈ 0.15, 0.06)
no longer collapse to (0,0,0,0). The strict and overdrive solvers now
project out-of-hull XYZ targets to the nearest achievable point inside
the LED hull before triangle routing.

Implementation
==============

- `colorimetric_detail::nnls3` (inline in rgbw_colorimetric.h): projected-
  gradient NNLS for 3x3 systems (500 iters @ step 0.01), matching the
  reference's scipy-less fallback. Cheap (~50 µs on an MCU at -O2) and
  alloc-free; only invoked when the target is out-of-hull, never on the
  in-hull fast path.

- `project_to_hull` (static in rgbw_colorimetric.cpp.hpp): for an
  out-of-hull XYZ target, runs NNLS in each of the three sub-gamuts
  (RGW/RBW/BGW), caps drive at 1.0 per sub-gamut, and selects the one
  with smallest residual. Returns the achieved chromaticity at unit Y
  for the strict triangle solve to route on.

- Wired into `solve_strict_subgamut`, `solve_strict_subgamut_xy`, and
  `solve_wx_overdrive`. The LUT builder's grid points run through
  `solve_strict_subgamut_xy` so the rebuilt LUT cells contain projected
  RGBW for boundary samples — no separate dispatch-side projection
  needed for the LUT lookup path.

Tests
=====

The "out-of-hull sRGB blue" test added in 762c341 documented #2708 as an
executable contract — it asserted FastLED returned zeros while reference
projected. Flipped to assert FastLED now matches the reference within
±1/255 (rounding only — both share the same NNLS implementation).

The `fastled_mirror::strict_subgamut` test helper gains a verbatim copy
of `project_to_hull` so the mirror continues to match production
behavior. All 308 unit tests pass clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@zackees zackees changed the title test(rgbw): in-test ground-truth port of the math-model reference fix(rgbw): NNLS out-of-hull projection (#2708) + in-test ground truth Jun 3, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

♻️ Duplicate comments (1)
tests/fl/gfx/rgbw_colorimetric.cpp (1)

518-544: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Mirror diverges from production: missing M_src zeroing on degenerate source space.

The production build_profile_cache (lines 76–79 in rgbw_colorimetric.cpp.hpp) explicitly zeros M_src when has_source_space is false, but this mirror only flips the flag. Although M_src won't be read when has_source_space == false, the mirror should match the production fallback to maintain the "exact text-copy" contract stated in lines 504–506.

🔧 Suggested fix
     matvec3(cache->P_RGB_inv, cache->P_W, cache->d_W);
     cache->has_source_space = (p->input_xy_w[1] > 1e-6f) &&
         build_source_matrix(p->input_xy_r, p->input_xy_g, p->input_xy_b,
                             p->input_xy_w, cache->M_src);
+    if (!cache->has_source_space) {
+        for (int i = 0; i < 3; ++i) {
+            for (int j = 0; j < 3; ++j) {
+                cache->M_src[i][j] = 0.0f;
+            }
+        }
+    }
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/fl/gfx/rgbw_colorimetric.cpp` around lines 518 - 544, The mirror
implementation of build_cache sets cache->has_source_space based on
build_source_matrix but does not zero cache->M_src when the source space is
degenerate; update build_cache so that after computing cache->has_source_space
(using build_source_matrix with p->input_xy_r/g/b/w) you explicitly zero
cache->M_src (e.g., set all 9 elements to 0 or memset) when has_source_space is
false, keeping the same behavior as the production build_profile_cache and
ensuring build_cache, cache->M_src, cache->has_source_space, and
build_source_matrix remain consistent.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Duplicate comments:
In `@tests/fl/gfx/rgbw_colorimetric.cpp`:
- Around line 518-544: The mirror implementation of build_cache sets
cache->has_source_space based on build_source_matrix but does not zero
cache->M_src when the source space is degenerate; update build_cache so that
after computing cache->has_source_space (using build_source_matrix with
p->input_xy_r/g/b/w) you explicitly zero cache->M_src (e.g., set all 9 elements
to 0 or memset) when has_source_space is false, keeping the same behavior as the
production build_profile_cache and ensuring build_cache, cache->M_src,
cache->has_source_space, and build_source_matrix remain consistent.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 535f6888-d18e-403d-90de-5fafe37c8497

📥 Commits

Reviewing files that changed from the base of the PR and between 762c341 and 2cfc472.

📒 Files selected for processing (3)
  • src/fl/gfx/rgbw_colorimetric.cpp.hpp
  • src/fl/gfx/rgbw_colorimetric.h
  • tests/fl/gfx/rgbw_colorimetric.cpp

@zackees
zackees merged commit 7412393 into master Jun 3, 2026
7 checks passed
@fastled-project-sync fastled-project-sync Bot moved this from Triage to Done in FastLED Tracker Jun 3, 2026
zackees added a commit that referenced this pull request Jun 3, 2026
- Drop compare_rgbw.py. It was a one-off developer harness used during
  the gist-vs-FastLED verification (now permanently captured by the
  in-test reference port). CodeRabbit flagged it for type-annotation /
  dataclass / signature-policy issues that would be valid for production
  Python but are noise on a scratch file; cleanest fix is to not ship it.
- Mirror the production cache builder's M_src zero-init on
  build_source_matrix failure. Matches the "exact text-copy" contract
  the comment promises and keeps the mirror byte-faithful to production.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
zackees added a commit that referenced this pull request Jun 3, 2026
#2711)

* fix(rgbw): default source = native LED gamut + D65; named-gamut opt-in (#2710)

Closes #2710.

#2705 added the source-RGB → LED-XYZ transform with `kRgbwDefaultProfile`
defaulting to Rec709/sRGB primaries + D65. That silently clipped saturated
inputs to the sRGB sub-volume of the LED's native gamut — `RGB=(255,0,0)`
on a typical SK6812 strip drove the LED red diode to ~70 % of its
capability, leaving the rest unreachable through the public API.

Flips the default to **native LED gamut + D65 white**:
  - `kRgbwDefaultProfile.input_xy_r/g/b` now mirror the profile's own
    LED `xy_r/g/b` (was sRGB), so saturated inputs hit the LED gamut at
    full saturation.
  - `input_xy_w` stays at D65 so neutral inputs land on a standard
    daylight white.
  - Same applies to `kRgbwwDefaultProfile` (RGBWW warm + cool paths).

Adds a small opt-in API for users who explicitly want standard
color-space input semantics:

    enum class InputGamut : u8 {
        Native, Rec709, Rec2020, DciP3D65, DciP3D60
    };
    void set_input_gamut(DiodeProfile* profile, InputGamut g) noexcept;
    void set_input_gamut(DiodeProfile* profile, InputGamut g,
                         const float white_xy[2]) noexcept;

Users with sRGB content (ambilight, video bridges) write one line at
setup: `fl::set_input_gamut(&my_profile, fl::InputGamut::Rec709);`. The
white-override overload covers niche cases like D50 photography workflow
or D60 ACES theatrical mastering.

Tests
=====
- `default profile carries native-LED + D65 source space (#2710)` —
  asserts input_xy_* mirror xy_* and input_xy_w == D65.
- `source matrix matches published sRGB->XYZ matrix (Rec709 opt-in)` —
  the existing sRGB matrix-derivation check now opts into Rec709 via
  set_input_gamut() before building M_src.
- `set_input_gamut: Native copies LED primaries` — trashes input_xy_*
  then proves Native restores them from xy_*.
- `set_input_gamut: named gamuts populate canonical primaries` —
  hits Rec709 / Rec2020 / DCI-P3 D65 / DCI-P3 D60 and asserts canonical
  primary + white-point values.
- `set_input_gamut: white override honored` — covers the overload that
  takes a custom white (D50 in the test).
- `set_input_gamut: null profile is a no-op` — defensive guard parity
  with `set_rgbw_colorimetric_profile(nullptr)`.

Drive-by
========
Removes `compare_rgbw.py`, a one-off scratch comparison harness that
slipped into master via #2709's squash-merge despite being deleted on
the branch.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* chore(ci): apply ruff format drift

bash lint reformatted three CI files during PR #2711 review work. No
functional change — purely line-break/whitespace adjustments that ruff
flagged as drift from the current format profile.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(rgbw): address CodeRabbit review on #2711

Three follow-ups from the CodeRabbit review:

1. **(major) Cache invalidation on in-place gamut mutation** —
   set_input_gamut() rewrites profile->input_xy_* in place, but the
   ColorimetricCacheHolder and LutStateHolder are keyed on (profile_ptr,
   cct). Without invalidation, the cache held stale M_src/LUT entries
   after a gamut switch on the currently active profile, producing
   deterministic wrong colors. Now the active per-process caches are
   evicted whenever set_input_gamut() mutates a profile that matches
   the cache key. No-op in the FASTLED_RGBW_COLORIMETRIC=0 build (no
   cache exists to invalidate).

2. **(contract) white_xy doc mismatch** — The header doc said the
   `white_xy` override "must point to a 2-float array" but the impl
   already accepted nullptr as "use the gamut's reference white"
   (equivalent to the 2-arg overload). Doc now matches behavior. Kept
   the raw-array signature instead of switching to fl::span<const
   float, 2> — the header sits low in the include graph and pulling
   fl/stl/span.h here would be a heavier change than the contract bug
   warrants; the 2-arg overload remains the recommended call site for
   the default-white path.

3. **(nitpick) RGBWW native-gamut guard** — Added an explicit test
   asserting kRgbwwDefaultProfile.warm_path / cool_path keep
   input_xy_* mirroring xy_* and input_xy_w pinned at D65. Symmetric
   to the existing assertion at rgbw_colorimetric.cpp:252-272; locks
   the native-LED-gamut contract on both warm and cool paths so future
   chromaticity retuning can't silently desync source from emitter.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* docs(cpp): wrap fl::set_input_gamut on CFastLED per Public Settings Pattern

`fl::set_input_gamut` (#2710) is a library-wide global setter. Under the
Public Settings Pattern in agents/docs/cpp-standards.md, every public
fl:: global setter must ship with a thin inline `CFastLED` wrapper that
becomes the documented user-facing call site. The two-arg and three-arg
overloads now have matching `CFastLED::setInputGamut` wrappers.

Removes the implicit grandfathered exception this function was relying
on in PR #2715 — that PR's follow-up commit explicitly dropped the
allowlist, so this wrapper is now required before merge rather than
deferred.

Co-Authored-By: Claude Opus 4.7 <[email protected]>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

bug(rgbw): out-of-hull source colors return (0,0,0,0) — missing NNLS projection (gist §3)

1 participant