forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

color_ui.rs645 lines, 26.3 KiBHistoryRawDownload
1//! The colour card's numbers and its histogram.
2
3use crate::*;
4use crate::ui::type_scale::{self, Typeset};
5use gpui::{Rgba, fill};
6
7/// The colour card's four controls, in the order it lists them: what each is
8/// called and the range it moves in. The order is `ColorParams`' own, which is
9/// what [`color_band`] indexes.
10pub(crate) const COLOR_BANDS: [(&str, f32, f32); 4] = [
11 ("Brightness", -1., 1.),
12 ("Contrast", 0., 2.),
13 ("Saturation", 0., 2.),
14 ("Tint", -1., 1.),
15];
16
17/// A press of a nudge key: a fortieth of a band's range, so a slider crosses it
18/// in forty presses and every stop is a number the file can write. A drag lands
19/// on the same grid ([`Player::drag_color`]), so the pointer and the keyboard
20/// cannot reach two different sets of values.
21pub(crate) const COLOR_STEP: f32 = 0.05;
22
23/// The card's width: the longest label has to fit on its line beside the value
24/// without truncating (measured against "Tint (cool–warm)").
25pub(crate) const COLOR_W: f32 = 460.;
26/// A bar's width for the pointer tests to drive. The card's bars fill the row
27/// now, so nothing in the app reads this.
28#[cfg(test)]
29pub(crate) const COLOR_BAR_W: f32 = 240.;
30
31/// The histogram's bins. 64 is four codes of an 8-bit ramp per bin: fine enough
32/// to see a grade tilt, coarse enough that a subsampled count is not noise.
33pub(crate) const HIST_BINS: usize = 64;
34
35/// How many pixels of a frame the histogram reads. The stride is
36/// `pixels / HIST_SAMPLES` (1920x1080 -> every 253rd pixel), which is a
37/// thousandth of the frame and walks across columns rather than down one.
38pub(crate) const HIST_SAMPLES: usize = 8_192;
39
40/// The histogram box. Shorter than the equalizer's curve because the slider
41/// rows stand under it and the card still has to fit a 360 px window.
42pub(crate) const HIST_H: f32 = 96.;
43
44/// A slider value on the [`COLOR_STEP`] grid: what a drag rounds to, so the
45/// pointer stops where the arrow keys do and "0.35" on screen is the number the
46/// file writes rather than a rounding of one.
47pub(crate) fn color_snap(value: f32) -> f32 {
48 (value / COLOR_STEP).round() * COLOR_STEP
49}
50
51/// How the frame on screen is spread across the tone range: `HIST_BINS` counts
52/// of its luma, read off the BGRA the decoder handed over -- which is the
53/// *graded* picture, because the grade is folded into the conversion
54/// (`engine::convert::i420_to_bgra_with`). So what this counts is what the eye
55/// is looking at, and moving a slider moves it.
56///
57/// Every [`HIST_SAMPLES`]th-of-a-frame pixel, not every pixel: a shape drawn
58/// from eight thousand samples is the same shape, at a thousandth of the reads.
59pub(crate) fn histogram(bgra: &[u8]) -> [u32; HIST_BINS] {
60 let pixels = bgra.len() / 4;
61 let stride = (pixels / HIST_SAMPLES).max(1);
62 let mut bins = [0u32; HIST_BINS];
63 for p in (0..pixels).step_by(stride) {
64 let px = &bgra[p * 4..];
65 // BGRA on the wire. Rec. 709 weights in 256ths (54 + 183 + 19 is 256),
66 // so the luma stays in 0..=255 with no division.
67 let luma = (54 * u32::from(px[2]) + 183 * u32::from(px[1]) + 19 * u32::from(px[0])) >> 8;
68 bins[luma as usize * HIST_BINS / 256] += 1;
69 }
70 bins
71}
72
73/// The luma counts drawn as one line across the box, tallest bin to the top.
74///
75/// Square root, not linear: a shot with a big flat area (a night sky, a title
76/// card) puts one bin so far above the rest that a linear graph is a single
77/// spike beside a flat line, and the tilt a grade puts in the rest is exactly
78/// what the card is for.
79pub(crate) fn hist_curves(bins: [u32; HIST_BINS]) -> impl IntoElement {
80 canvas(
81 |_, _, _| (),
82 move |bounds, _, window, _| {
83 let (o, s) = (bounds.origin, bounds.size);
84 // Never zero, so an unpumped (all-zero) histogram is a flat line
85 // rather than a division by nothing.
86 let top = bins.iter().copied().max().unwrap_or(0).max(1) as f32;
87 let mut path = PathBuilder::stroke(px(1.5));
88 for (bin, &count) in bins.iter().enumerate() {
89 let at = point(
90 o.x + s.width * (bin as f32 / (HIST_BINS - 1) as f32),
91 o.y + s.height * (1. - (count as f32 / top).sqrt()),
92 );
93 match bin {
94 0 => path.move_to(at),
95 _ => path.line_to(at),
96 }
97 }
98 if let Ok(path) = path.build() {
99 window.paint_path(path, rgb(HIST_INK()[1]));
100 }
101 },
102 )
103 .absolute()
104 .size_full()
105}
106
107// -- the look: wheels, curves and a LUT, and the scopes ------------------------
108
109/// The colour card's sections, one shown at a time so the card stays the height
110/// it was: the four sliders, the wheels, the curves, the LUT. The order is the
111/// order the grade runs in, bar the sliders, which are what a grade starts with.
112#[derive(Clone, Copy, Debug, PartialEq, Eq)]
113pub(crate) enum ColorSection {
114 Basic,
115 Wheels,
116 Curves,
117 Lut,
118}
119
120pub(crate) const COLOR_SECTIONS: [(ColorSection, &str); 4] = [
121 (ColorSection::Basic, "Basic"),
122 (ColorSection::Wheels, "Wheels"),
123 (ColorSection::Curves, "Curves"),
124 (ColorSection::Lut, "Look file"),
125];
126
127/// What the graph over the controls shows.
128#[derive(Clone, Copy, Debug, PartialEq, Eq)]
129pub(crate) enum ScopeView {
130 Histogram,
131 Waveform,
132 Vectorscope,
133 Parade,
134}
135
136pub(crate) const SCOPE_VIEWS: [(ScopeView, &str); 4] = [
137 (ScopeView::Histogram, "Histogram"),
138 (ScopeView::Waveform, "Waveform"),
139 (ScopeView::Vectorscope, "Vectorscope"),
140 (ScopeView::Parade, "RGB parade"),
141];
142
143/// Columns the waveform and parade are counted into.
144pub(crate) const SCOPE_COLS: usize = 48;
145
146/// The wheels the Wheels section picks between, in `engine::color::Wheels`' order.
147pub(crate) const WHEEL_NAMES: [&str; 3] = ["Lift", "Gamma", "Gain"];
148/// What each wheel does, for its tooltip.
149pub(crate) const WHEEL_WHY: [&str; 3] = [
150 "Raises or lowers the blacks; white stays where it is",
151 "Bends the mid-tones; black and white stay",
152 "Scales the whole channel from black: the highlights move most",
153];
154/// The channel rows of a wheel and the curves' channel picker, in
155/// `engine::color::CHANNELS`' order.
156pub(crate) const CHANNEL_NAMES: [&str; 4] = ["Master", "Red", "Green", "Blue"];
157/// The five points of a curve the Curves section edits: their inputs and names.
158pub(crate) const CURVE_GRID: [(f32, &str); 5] =
159 [(0.0, "Blacks"), (0.25, "Shadows"), (0.5, "Mid-tones"), (0.75, "Highlights"), (1.0, "Whites")];
160
161/// Slider slots: the four basic bands, then a wheel's four channels, the five
162/// curve points and the LUT's intensity. One recorded bar box each.
163pub(crate) const WHEEL_BAND: usize = 4;
164pub(crate) const CURVE_BAND: usize = WHEEL_BAND + 4;
165pub(crate) const LUT_BAND: usize = CURVE_BAND + CURVE_GRID.len();
166pub(crate) const COLOR_SLOTS: usize = LUT_BAND + 1;
167
168/// The bands a section's arrows walk.
169pub(crate) fn section_bands(section: ColorSection) -> std::ops::Range<usize> {
170 match section {
171 ColorSection::Basic => 0..COLOR_BANDS.len(),
172 ColorSection::Wheels => WHEEL_BAND..CURVE_BAND,
173 ColorSection::Curves => CURVE_BAND..LUT_BAND,
174 ColorSection::Lut => LUT_BAND..COLOR_SLOTS,
175 }
176}
177
178/// A band's name, range and keyboard step.
179pub(crate) fn band_spec(band: usize) -> (&'static str, f32, f32, f32) {
180 match band {
181 0..WHEEL_BAND => {
182 let (name, lo, hi) = COLOR_BANDS[band];
183 (name, lo, hi, COLOR_STEP)
184 }
185 WHEEL_BAND..CURVE_BAND => (CHANNEL_NAMES[band - WHEEL_BAND], -1., 1., 0.01),
186 CURVE_BAND..LUT_BAND => (CURVE_GRID[band - CURVE_BAND].1, 0., 1., 0.01),
187 _ => ("Intensity", 0., 1., COLOR_STEP),
188 }
189}
190
191/// The value of `band` in `params`, with `wheel` and `curve` the Wheels and
192/// Curves sections' picks. A curve point reads the curve's output at that input,
193/// whatever points the curve was made of.
194pub(crate) fn band_value(params: &ColorParams, band: usize, wheel: usize, curve: usize) -> f32 {
195 let look = &params.look;
196 match band {
197 0..WHEEL_BAND => *band_mut(&mut params.clone(), band),
198 WHEEL_BAND..CURVE_BAND => wheel_of(&look.wheels, wheel)[band - WHEEL_BAND],
199 CURVE_BAND..LUT_BAND => curve_at(&look.curves[curve], CURVE_GRID[band - CURVE_BAND].0),
200 _ => look.lut_mix,
201 }
202}
203
204/// [`band_value`]'s writer. Moving a curve point rebuilds that curve on the
205/// five-point grid (each point at the output the curve had there), so an
206/// all-diagonal grid is the straight curve again.
207pub(crate) fn set_band(params: &mut ColorParams, band: usize, wheel: usize, curve: usize, value: f32) {
208 let look = &mut params.look;
209 match band {
210 0..WHEEL_BAND => *band_mut(params, band) = value,
211 WHEEL_BAND..CURVE_BAND => {
212 let w = &mut look.wheels;
213 let slot = match wheel {
214 0 => &mut w.lift,
215 1 => &mut w.gamma,
216 _ => &mut w.gain,
217 };
218 slot[band - WHEEL_BAND] = value;
219 }
220 CURVE_BAND..LUT_BAND => {
221 let c = &look.curves[curve];
222 let mut pts: Vec<[f32; 2]> = CURVE_GRID.iter().map(|&(x, _)| [x, curve_at(c, x)]).collect();
223 pts[band - CURVE_BAND][1] = value;
224 look.curves[curve] = if pts.iter().all(|p| (p[0] - p[1]).abs() < 1e-6) {
225 engine::color::Curve::default()
226 } else {
227 engine::color::Curve::new(&pts).unwrap_or_default()
228 };
229 }
230 _ => look.lut_mix = value,
231 }
232}
233
234/// A band's neutral value: what Reset puts back.
235pub(crate) fn band_neutral(band: usize) -> f32 {
236 match band {
237 0..WHEEL_BAND => *band_mut(&mut ColorParams::default(), band),
238 WHEEL_BAND..CURVE_BAND => 0.,
239 CURVE_BAND..LUT_BAND => CURVE_GRID[band - CURVE_BAND].0,
240 _ => 1.,
241 }
242}
243
244fn wheel_of(w: &engine::color::Wheels, wheel: usize) -> [f32; 4] {
245 match wheel {
246 0 => w.lift,
247 1 => w.gamma,
248 _ => w.gain,
249 }
250}
251
252/// A curve's output at input `x`.
253pub(crate) fn curve_at(c: &engine::color::Curve, x: f32) -> f32 {
254 if c.points().is_empty() {
255 return x;
256 }
257 let t = c.sampled(257);
258 t[(x.clamp(0., 1.) * 256.).round() as usize]
259}
260
261/// `color` at `alpha` (0..255) as a gpui colour.
262fn ink(color: u32, alpha: u8) -> Rgba {
263 rgba((color << 8) | u32::from(alpha))
264}
265
266/// Count to alpha: square root, so a sparse trace still shows beside a dense one
267/// (the histogram's own reason).
268fn glow(count: u32, top: u32) -> u8 {
269 if count == 0 {
270 return 0;
271 }
272 (40. + 215. * (count as f32 / top.max(1) as f32).sqrt()).min(255.) as u8
273}
274
275/// The scopes drawn in the graph box: the waveform, the vectorscope or the RGB
276/// parade of the frame on screen, counted at low resolution
277/// ([`engine::scopes::compute`]). Theme inks: the histogram's three. Each one
278/// carries a faint graticule and its labels in the caption ink, so a reading
279/// can be taken off it: 0 to 100 percent lines on the two level scopes, and a
280/// centre cross, a ring and the six colour targets on the vectorscope.
281pub(crate) fn scope_canvas(view: ScopeView, scopes: Option<engine::scopes::Scopes>) -> impl IntoElement {
282 let (head, foot) = plot_inset(view);
283 let gutter = plot_gutter(view);
284 let plot = canvas(
285 |_, _, _| (),
286 move |bounds, _, window, _| {
287 let (o, sz) = (bounds.origin, bounds.size);
288 let levels = engine::scopes::LEVELS;
289 let cell = |x0: f32, y0: f32, w: f32, h: f32| {
290 Bounds::new(point(o.x + px(x0), o.y + px(y0)), size(px(w), px(h)))
291 };
292 let (w, h) = (f32::from(sz.width), f32::from(sz.height));
293 let [red, green, blue] = HIST_INK();
294 // The graticule goes down first, so the trace is drawn over it.
295 let faint = ink(INK3(), GRATICULE_ALPHA);
296 match view {
297 ScopeView::Histogram => {}
298 ScopeView::Waveform | ScopeView::Parade => {
299 for f in GRATICULE_LEVELS {
300 window.paint_quad(fill(cell(0., (h * (1. - f)).clamp(0., h - 1.), w, 1.), faint));
301 }
302 if view == ScopeView::Parade {
303 for k in 1..3 {
304 window.paint_quad(fill(cell(w * k as f32 / 3., 0., 1., h), faint));
305 }
306 }
307 }
308 ScopeView::Vectorscope => {
309 let (cx, cy) = (w / 2., h / 2.);
310 let rr = w.min(h) / 2. - VECTOR_RING_INSET;
311 window.paint_quad(fill(cell(cx, 0., 1., h), faint));
312 window.paint_quad(fill(cell(0., cy, w, 1.), faint));
313 let mut ring = PathBuilder::stroke(px(1.));
314 for i in 0..=72 {
315 let a = i as f32 / 72. * std::f32::consts::TAU;
316 let at = point(o.x + px(cx + rr * a.cos()), o.y + px(cy + rr * a.sin()));
317 match i {
318 0 => ring.move_to(at),
319 _ => ring.line_to(at),
320 }
321 }
322 if let Ok(ring) = ring.build() {
323 window.paint_path(ring, faint);
324 }
325 for (_, cb, cr) in VECTOR_TARGETS {
326 let (dx, dy) = unit(cb, cr);
327 window.paint_quad(fill(cell(cx + rr * dx - 1.5, cy - rr * dy - 1.5, 3., 3.), ink(INK3(), 0x90)));
328 }
329 }
330 }
331 let Some(s) = &scopes else {
332 return;
333 };
334 match view {
335 ScopeView::Histogram => {}
336 ScopeView::Waveform => {
337 let top = s.wave.iter().copied().max().unwrap_or(1);
338 let (cw, ch) = (w / s.cols as f32, h / levels as f32);
339 for lvl in 0..levels {
340 for col in 0..s.cols {
341 let a = glow(s.wave[lvl * s.cols + col], top);
342 if a > 0 {
343 let y = h - (lvl + 1) as f32 * ch;
344 window.paint_quad(fill(cell(col as f32 * cw, y, cw, ch), ink(green, a)));
345 }
346 }
347 }
348 }
349 ScopeView::Parade => {
350 let third = w / 3.;
351 let (cw, ch) = (third / s.cols as f32, h / levels as f32);
352 for (k, color) in [red, green, blue].into_iter().enumerate() {
353 let grid = &s.parade[k];
354 let top = grid.iter().copied().max().unwrap_or(1);
355 for lvl in 0..levels {
356 for col in 0..s.cols {
357 let a = glow(grid[lvl * s.cols + col], top);
358 if a > 0 {
359 let x = k as f32 * third + col as f32 * cw;
360 let y = h - (lvl + 1) as f32 * ch;
361 window.paint_quad(fill(cell(x, y, cw, ch), ink(color, a)));
362 }
363 }
364 }
365 }
366 }
367 ScopeView::Vectorscope => {
368 let n = engine::scopes::VECTOR;
369 let side = w.min(h);
370 let (x0, y0, c) = ((w - side) / 2., (h - side) / 2., side / n as f32);
371 let top = s.vector.iter().copied().max().unwrap_or(1);
372 for row in 0..n {
373 for col in 0..n {
374 let a = glow(s.vector[row * n + col], top);
375 if a > 0 {
376 window.paint_quad(fill(cell(x0 + col as f32 * c, y0 + row as f32 * c, c, c), ink(green, a)));
377 }
378 }
379 }
380 }
381 }
382 },
383 )
384 .absolute()
385 .left(px(gutter))
386 .right_0()
387 .top(px(head))
388 .bottom(px(foot));
389 div()
390 .absolute()
391 .size_full()
392 .child(plot)
393 .children(scope_labels(view))
394}
395
396/// The strip above and below a parade's traces: the R/G/B names sit in the top one, and the
397/// bottom one gives the 0% label room below its line. Other scopes use the whole box.
398const PARADE_HEAD: f32 = 16.;
399const PARADE_FOOT: f32 = 20.;
400
401/// The (top, bottom) inset of a scope's traces inside the graph box.
402fn plot_inset(view: ScopeView) -> (f32, f32) {
403 match view {
404 ScopeView::Parade => (PARADE_HEAD, PARADE_FOOT),
405 _ => (0., 0.),
406 }
407}
408
409/// The left strip that holds a level scope's percent labels, clear of its traces.
410/// Other scopes have no labels down the side, so they keep the whole box.
411/// Sized for the widest percent label, "100%", at the caption size with room to spare for the
412/// glyphs' real width, so a label is never cut at the box's left edge.
413fn axis_gutter() -> f32 {
414 crate::ui::popup::text_w("100%", type_scale::CAPTION_PX, false) * 1.2 + 8.
415}
416
417fn plot_gutter(view: ScopeView) -> f32 {
418 match view {
419 ScopeView::Waveform | ScopeView::Parade => axis_gutter(),
420 _ => 0.,
421 }
422}
423
424/// The graticule's level lines, as fractions of the scope's height: 0 to 100 percent.
425const GRATICULE_LEVELS: [f32; 5] = [0., 0.25, 0.5, 0.75, 1.];
426
427/// The graticule's line strength: the caption ink at a low alpha, so it reads as a guide.
428const GRATICULE_ALPHA: u8 = 0x38;
429
430/// How far the vectorscope's ring sits in from the box's edge, so the target
431/// letters have room outside it.
432const VECTOR_RING_INSET: f32 = 14.;
433
434/// The six colour targets on a vectorscope, each as the Cb and Cr its full-scale
435/// colour lands on in the engine's own units ([`engine::scopes::compute`]).
436const VECTOR_TARGETS: [(&str, f32, f32); 6] = [
437 ("R", -0.161, 0.445),
438 ("Mg", 0.316, 0.373),
439 ("B", 0.478, -0.072),
440 ("Cy", 0.161, -0.445),
441 ("G", -0.316, -0.373),
442 ("Yl", -0.478, 0.072),
443];
444
445/// A target's direction on the ring, unit length, with Cr up (screen y is down, so
446/// the caller flips the sign for the screen).
447fn unit(cb: f32, cr: f32) -> (f32, f32) {
448 let len = cb.hypot(cr).max(f32::EPSILON);
449 (cb / len, cr / len)
450}
451
452/// The labels over a scope's graticule, in the caption ink. The canvas paints the
453/// lines; the words are plain text laid over it.
454fn scope_labels(view: ScopeView) -> Vec<Div> {
455 let label = |text: &str| {
456 div()
457 .absolute()
458 .type_style(type_scale::caption())
459 .text_color(rgb(INK3()))
460 .whitespace_nowrap()
461 .child(text.to_string())
462 };
463 // The percent labels sit in the gutter, right-aligned to the box, centred on their line.
464 let level = |text: &str, y: f32| {
465 label(text)
466 .left_0()
467 .w(px(axis_gutter() - 4.))
468 .flex()
469 .justify_end()
470 .top(px(y - 6.))
471 };
472 match view {
473 ScopeView::Histogram => Vec::new(),
474 ScopeView::Waveform | ScopeView::Parade => {
475 let parade = view == ScopeView::Parade;
476 let (head, foot) = plot_inset(view);
477 let plot_h = HIST_H - head - foot;
478 let mut out: Vec<Div> = GRATICULE_LEVELS
479 .iter()
480 .map(|&f| level(&format!("{:.0}%", f * 100.), head + plot_h * (1. - f)))
481 .collect();
482 if parade {
483 for (k, name) in ["R", "G", "B"].into_iter().enumerate() {
484 out.push(
485 div()
486 .absolute()
487 .left(relative(k as f32 / 3.))
488 .w(relative(1. / 3.))
489 .top_0()
490 .h(px(PARADE_HEAD))
491 .flex()
492 .items_center()
493 .justify_center()
494 .type_style(type_scale::caption())
495 .text_color(rgb(INK3()))
496 .child(name),
497 );
498 }
499 }
500 out
501 }
502 ScopeView::Vectorscope => {
503 // The ring is `VECTOR_RING_INSET` in from the scope's side, and the labels sit
504 // just outside it, centred on the box.
505 let lr = HIST_H / 2. - VECTOR_RING_INSET + 9.;
506 VECTOR_TARGETS
507 .iter()
508 .map(|&(name, cb, cr)| {
509 let (dx, dy) = unit(cb, cr);
510 div()
511 .absolute()
512 .left(relative(0.5))
513 .top(relative(0.5))
514 .ml(px(lr * dx - 8.))
515 .mt(px(-lr * dy - 7.))
516 .w(px(16.))
517 .h(px(14.))
518 .flex()
519 .items_center()
520 .justify_center()
521 .type_style(type_scale::caption())
522 .text_color(rgb(INK3()))
523 .child(name)
524 })
525 .collect()
526 }
527 }
528}
529
530/// The picked curve drawn over the graph: the line, and the five grid points as
531/// small squares, in the channel's ink (master in the light ink).
532pub(crate) fn curve_overlay(curve: engine::color::Curve, channel: usize) -> impl IntoElement {
533 canvas(
534 |_, _, _| (),
535 move |bounds, _, window, _| {
536 let (o, s) = (bounds.origin, bounds.size);
537 let inks = HIST_INK();
538 let color = if channel == 0 { INK1() } else { inks[channel - 1] };
539 let t = curve.sampled(65);
540 let mut path = PathBuilder::stroke(px(1.5));
541 for (i, &y) in t.iter().enumerate() {
542 let at = point(o.x + s.width * (i as f32 / 64.), o.y + s.height * (1. - y));
543 match i {
544 0 => path.move_to(at),
545 _ => path.line_to(at),
546 }
547 }
548 if let Ok(path) = path.build() {
549 window.paint_path(path, rgb(color));
550 }
551 for &(x, _) in &CURVE_GRID {
552 let y = curve_at(&curve, x);
553 let c = point(o.x + s.width * x - px(3.), o.y + s.height * (1. - y) - px(3.));
554 window.paint_quad(fill(Bounds::new(c, size(px(6.), px(6.))), rgb(color)));
555 }
556 },
557 )
558 .absolute()
559 .size_full()
560}
561
562// -- the colour wheels ----------------------------------------------------------
563
564/// How far a puck at the rim of a wheel pushes a channel: the wheel's R, G and B
565/// offsets are `WHEEL_REACH` times the puck's position, so the rim is a strong
566/// but usable tint and the sliders' -1..1 range stays far beyond it.
567pub(crate) const WHEEL_REACH: f32 = 0.5;
568
569/// The R, G, B offsets a puck at `(x, y)` (right and up, the unit disc) stands
570/// for: the hue is the angle (red at 3 o'clock, green at 7, blue at 11) and the
571/// saturation the distance, so the three offsets always sum to zero and the
572/// wheel tints without moving the master.
573pub(crate) fn wheel_offsets(x: f32, y: f32) -> [f32; 3] {
574 let len = x.hypot(y);
575 let k = if len > 1. { 1. / len } else { 1. };
576 let (x, y) = (x * k, y * k);
577 let h = 3f32.sqrt() / 2.;
578 [WHEEL_REACH * x, WHEEL_REACH * (-x / 2. + h * y), WHEEL_REACH * (-x / 2. - h * y)]
579}
580
581/// [`wheel_offsets`]' inverse: where the puck sits for an RGB offset (any mean the
582/// three share is the master's business, not the pad's, and is dropped).
583pub(crate) fn wheel_puck(r: f32, g: f32, b: f32) -> (f32, f32) {
584 let x = (2. * r - g - b) / 3. / WHEEL_REACH;
585 let y = (g - b) / 3f32.sqrt() / WHEEL_REACH;
586 let len = x.hypot(y);
587 if len > 1. { (x / len, y / len) } else { (x, y) }
588}
589
590/// A wheel's RGB offsets snapped to the hundredth the sliders land on.
591pub(crate) fn wheel_snap(v: f32) -> f32 {
592 ((v / 0.01).round() * 0.01).clamp(-1., 1.)
593}
594
595/// A wheel's pad: the hue/saturation disc, a cross through the centre and the
596/// puck at `(x, y)` (the unit disc, up positive).
597pub(crate) fn wheel_disc(x: f32, y: f32) -> impl IntoElement {
598 canvas(
599 |_, _, _| (),
600 move |bounds, _, window, _| {
601 let (w, h) = (f32::from(bounds.size.width), f32::from(bounds.size.height));
602 let (cx, cy) = (f32::from(bounds.origin.x) + w / 2., f32::from(bounds.origin.y) + h / 2.);
603 let radius = w.min(h) / 2. - 1.;
604 let (wedges, rings) = (48, 5);
605 let at = |s: f32, a: f32| point(px(cx + radius * s * a.cos()), px(cy - radius * s * a.sin()));
606 for ring in 0..rings {
607 let (s0, s1) = (ring as f32 / rings as f32, (ring + 1) as f32 / rings as f32);
608 for i in 0..wedges {
609 let a0 = i as f32 / wedges as f32 * std::f32::consts::TAU;
610 let a1 = (i + 1) as f32 / wedges as f32 * std::f32::consts::TAU;
611 let (r, g, b) = engine::decode::viz_hsv_rgb(i as f32 / wedges as f32 * 360., (s0 + s1) / 2. * 0.8, 0.55);
612 let mut path = PathBuilder::fill();
613 path.add_polygon(&[at(s0, a0), at(s0, a1), at(s1, a1), at(s1, a0)], false);
614 if let Ok(path) = path.build() {
615 window.paint_path(path, rgb((u32::from(r) << 16) | (u32::from(g) << 8) | u32::from(b)));
616 }
617 }
618 }
619 for (a0, a1) in [(std::f32::consts::PI, 0.), (-std::f32::consts::FRAC_PI_2, std::f32::consts::FRAC_PI_2)] {
620 let mut line = PathBuilder::stroke(px(1.));
621 line.move_to(at(1., a0));
622 line.line_to(at(1., a1));
623 if let Ok(line) = line.build() {
624 window.paint_path(line, rgba(DARK_SEAM()));
625 }
626 }
627 let (mx, my) = (cx + radius * x, cy - radius * y);
628 for (r, color, wd) in [(6., 0x000000, 3.), (6., INK1(), 1.5)] {
629 let mut ring = PathBuilder::stroke(px(wd));
630 let pts: Vec<_> = (0..20)
631 .map(|k| {
632 let a = k as f32 / 20. * std::f32::consts::TAU;
633 point(px(mx + r * a.cos()), px(my + r * a.sin()))
634 })
635 .collect();
636 ring.add_polygon(&pts, true);
637 if let Ok(ring) = ring.build() {
638 window.paint_path(ring, rgb(color));
639 }
640 }
641 },
642 )
643 .absolute()
644 .size_full()
645}