Chromatic Adaptation Dynamic Developer Reference
Architecture and maintenance notes for the standalone chromatic adaptation lab, including the page shell, state object, CAT matrices, image pipeline, chart rendering, batch analysis, exports, URL state, public API, and Library preset binding.
Overview
Chromatic Adaptation Dynamic is a standalone IIFE-based browser tool. The HTML shell owns SEO, tab structure, controls, result canvases, and documentation panes. The JS module owns all color math, image processing, timeline state, chart rendering, exports, URL restore, and the small page API used by integrations. There is no build-time dependency and no network math path.
1. File map
+- Tool shell:
tool/general/colorimetry/chromatic-adaptation-dynamic/index.htmlcontains metadata, hero copy, guide, tabs, controls, result canvases, standards, formulas, references, research notes, and script import. - Tool engine:
js/tool/chromatic-adaptation-dynamic.jsis a standalone IIFE that owns utilities, CAT matrices, illuminants, color conversions, render state, image loading, adaptation, charts, exports, events, URL restore, and public API. - Library integration:
js/library/tool-bindings.jsregisters the path as tool idchromatic-adaptationwith asset typepreset. - Shared shell CSS: the page imports main, color science, unified, dark mode, legal, color science lab, and analyzer styles.
- Discovery: documentation metadata lives in
data/documentation.jsonand generated RSS, sitemap, PWA, and search files after docs are added.
2. Page shell and UI contract
+- App root:
#cad-appis the application container and#mainis the tool workspace. - Tabs: buttons use
data-cad-taband panels use idsp-cad-lab,p-cad-actions,p-cad-standards,p-cad-formulas,p-cad-refs, andp-cad-research. - Guide:
#cad-guideand#cad-guide-dismissprovide the quick start surface. - Controls: hidden inputs under custom dropdowns are the source of truth for illuminants and CAT method.
- Canvas ids: output canvases are
cad-orig-canvas,cad-adapt-canvas,cad-hist-canvas,cad-curve-canvas,cad-state-canvas,cad-lms-canvas,cad-spd-canvas, andcad-compare-canvas. - Action ids: exports and analysis use
cad-export-json,cad-export-frame,cad-share-btn,cad-copy-share,cad-copy-link,cad-compare-btn, andcad-batch-run.
3. State model and inputs
+
The module-level S object is the single runtime state store. Most UI events update
S, then call onParamChange() or runAdaptation().
- Illuminant state:
srcIllumdefaults to D65 anddstIllumdefaults to D50. - Model state:
catMethoddefaults tobradford. - Timing state:
delay,tau,strength,initAdapt,time, andfpsdefine the animation and adaptation curve. - Local adaptation state:
tauLocal,delayLocal, andmixdrive luminance-weighted per-pixel state blending. - Stored experiment state:
gamma,radius,localStrength,tile, anduseGPUare synchronized and exported. The current CPU render path primarily uses sRGB conversion, luminance modulation,mix, and HDR tonemap. - Runtime state:
srcImageData,animating,animId, andlastFrameTimeshould not be serialized directly except through the public API's filtered copy. - Sync:
syncAllInputs()pushes state into DOM controls and labels after URL restore or API restore.
4. Color math and CAT matrices
+- Utility math: helpers cover clamp, rounding, HEX parsing, sRGB transfer, 3x3 matrix multiplication, matrix inverse, determinant, and Frobenius norm.
- CAT registry:
CATSstores Bradford, Von Kries, CAT02, CAT16, Sharp, CMCCAT2000, HPE, and XYZ Scaling matrices. Inverses are cached during bootstrap. - Illuminants:
ILLUMstores CIE xy, CCT, and label data for D65, D50, D55, D60, D75, A, B, C, E, F2, F7, and F11. - White conversion:
illumXYZ(name)converts xy white points into normalized XYZ with Y = 1. - Adapt matrix:
buildAdaptMatrix(catKey, srcIllum, dstIllum, degree)projects source and destination whites into the CAT response space, builds a partial diagonal scale, and returns the full matrix plus LMS diagnostics. - Lab and LCh:
xyzToLab()andlabToLCh()support batch output and color-difference analysis. - CIEDE2000:
deltaE00()implements the color-difference metric used by batch and multi-method comparison. - SPD helpers: CIE daylight basis arrays and Planck-style generation power the source and destination spectral overlay.
5. Image pipeline and timeline
+- Image loading:
loadImage()reads a local data URL, scales to a maximum 480 by 320, draws tocad-orig-canvas, storesImageData, and syncs the adapted canvas size. - Sample image:
loadSample()creates a 360 by 240 HSL gradient viagenerateSampleImage(). - Adaptation curve:
adaptationState(t, A0, Ainf, tau, delay)returns A0 before delay and exponential movement toward Ainf after delay. - Render loop:
runAdaptation()iterates each pixel, converts sRGB to linear RGB, converts to XYZ, applies the active CAT matrix, converts back through inverse sRGB, and writes the adapted canvas. - Local modulation: per-pixel Y luminance adjusts tau and delay. The final degree
blends local state and global state through
S.mix. - HDR option:
reinhardTonemap()compresses linear output when HDR Tonemap is enabled. - Animation:
startAnimation(),animLoop(),stopAnimation(), andresetAnimation()run a five-second requestAnimationFrame timeline.
6. Charts and diagnostics
+- Histogram:
drawHistogram(imageData)builds RGB channel histograms from the adapted frame. - State map:
drawStateMap(srcData, globalAt)visualizes local adaptation degree as grayscale image data. - Curve:
drawAdaptCurve()plots A(t) over the fixed five-second timeline and marks the current time. - LMS bars:
drawLMSBars(adapt)compares source and destination cone-response channels for the active CAT. - SPD overlay:
drawSPD()draws source and destination spectral power distributions fromilluminantSPD(). - Matrix panel:
renderMatrixInfo()writes the active 3x3 matrix, determinant, Frobenius norm, LMS values, and scale factors intocad-matrix-output. - Responsive redraw: window resize redraws SPD and adaptation curve after a short debounce.
7. Exports, share URL, and batch
+- JSON export:
exportJSON()serializes state, active matrix, LMS values, scale factors, and determinant to a downloadable JSON file. - Frame export:
exportFrame()downloadscad-adapt-canvasas a PNG usingtoDataURL(). - Share URL:
shareURL()encodessrc,dst,cat,tau,delay,str,init, andtquery parameters. - URL restore:
restoreURL()reads those query parameters at boot and validates illuminant and CAT keys before applying them. - Batch:
runBatch()accepts valid HEX rows, caps analysis at 50 colors, transforms each value, and reports adapted HEX, Delta E 2000, L*, C*, and hue. - Comparison:
runComparison()evaluates all CAT methods on eight standard test colors and reports mean, median, min, max, determinant, and matrix norm. - Clipboard: copy actions use
navigator.clipboard.writeText()and report status through the toast surface.
8. Public API and library binding
+- Namespace: the page exposes
window.AAChromaticAdaptation. - getState: returns a JSON-safe copy of
S, removessrcImageDataandanimId, and addshasSourceImageplusanimatingflags. - restoreState: merges saved object values into
S, preserves the current image data, stops animation, syncs DOM controls, and re-renders throughonParamChange(). - Library match:
attachTool()matches/tool/general/colorimetry/chromatic-adaptation-dynamic/. - Library metadata: tool id is
chromatic-adaptation, name isChromatic Adaptation, category isColorimetry, and asset type ispreset. - Capture: the current binding uses
captureFormPreset()with nameAdaptation presetand preview labelChromatic adaptation. - Restore: the current binding uses generic form restore triggers
cad-apply,cad-render, andcad-update. If richer restore is needed, bridge directly towindow.AAChromaticAdaptation.restoreState().
9. Extension checklist
+- Add new CAT methods to
CATSwithname,short, and 3x3 matrix values, then confirm the inverse is not singular. - Add new illuminants to
ILLUMwith xy, CCT, and display label data, then update the HTML dropdowns. - Keep hidden dropdown inputs and labels synchronized when adding values or changing ids.
- Wire any new state field into
S, slider maps, value labels, JSON export,getState(), and restore paths. - If a control should affect rendering, route it through
runAdaptation(),drawStateMap(), or the relevant chart function, not only through export state. - Keep URL parameters compact and backward compatible; do not place image data in share URLs.
- Update batch analysis when new color spaces or metrics are added.
- Update Library capture if richer canvas thumbnails or direct API restore becomes necessary.
- Update user and developer documentation, documentation JSON, RSS, sitemaps, PWA cache manifest, and search index.
- Run rendering, export, restore, and accessibility smoke tests after any math or UI change.
10. Testing and risk notes
+- Boot: page loads, tabs switch, guide can dismiss, sample loads, and initial SPD, curve, LMS, and matrix diagnostics render.
- Inputs: source and destination illuminants, swap, CAT method, timing sliders, local modulation, time scrubber, FPS, Live, HDR, and stored experimental toggles sync correctly.
- Animation: Space, Animate, Pause, Reset, and end-of-timeline behavior do not leave stale animation frames running.
- Rendering: sample and uploaded images produce nonblank original and adapted canvases, histogram, state map, LMS, SPD, and curve output at multiple viewport sizes.
- Math: smoke test D65 to D50 Bradford, CAT16, CAT02, XYZ Scaling, determinant output, Delta E 2000 values, LCh conversion, and HDR tonemap paths.
- Actions: JSON export includes state and matrix data, PNG export downloads a current frame, share URL restores parameters, comparison table renders, and batch caps at 50 valid HEX rows.
- Library: save the preset, restore saved controls, and confirm the tool can rerender after restore.
- Risk: CAT matrix, sRGB transfer, Lab, or Delta E changes will shift all image output, batch tables, comparisons, and exported JSON. Keep any mathematical change deliberate and documented.