Files
plotter/src/plot/ticks.cpp
T
Martino Ferrari 38ef459897
CI / debug (tests + all adapters) (push) Canceled after 0s
CI / coverage (floor + measured table) (push) Canceled after 0s
CI / asan (AddressSanitizer) (push) Canceled after 0s
feat(plot)!: harden pipeline, XY series, dash/markers, touch, packaging
Breaking: Series::gather emits x relative to x0() and takes a GatherMode;
consumers reconstruct absolute x in f64 before mapping (series.hpp documents
the contract).

Bugs, each pinned by a fail-before regression test:
- render: f32 staging quantised epoch-time x into 128 px columns; every
  data-space draw now stages to_space(x) - to_space(origin) with the origin
  folded into the offset uniform in f64 (epoch/zero-origin twins rasterise
  identically)
- ticks: major test was ULP-fragile and blanked epoch axes; majors are an
  integer-index test and are never truncated by the minor cap
- gather: LOD envelope emitted buckets straddling [begin,end); ceil/floor
  bucket edges + raw lead/trail spans
- live follow: log x axes held a linear span and zoomed every frame; span and
  offset now live in axis space (plot + both figure link-group paths)
- input: a zero-notch wheel disarmed auto_scale on every axis; dy==0 pans x,
  factor == 1 / inf refused in wheel and drag zoom
- render: the single text flush painted legend names over the crosshair
  readout panel; two batches, under flushed before the panel
- data: NaN dropped from min/max unless it seeded the fold; non-finite
  samples are now excluded from every aggregate and from cached bounds

Robustness: viewport normalisation (no clamp UB), non-finite range refusal,
pyramid level cap at 57 (no shift/div UB through public gather), rounded ring
capacity documented + pre-sized, GL blend func and UNPACK_ALIGNMENT
save/restore, Renderer::release_gl() teardown, u64 buffer epochs, annotation
captions clamped, button-aware GLFW row capture, cached figure row rects (no
per-event layout), ruler-pair measurement refused, span-nonfinite guards in
axis_ends.

Features: XY series (sorted x, binary-search neighbours/snap, LOD over sample
index); StreamSeries::freeze(); ArraySeries::push(); per-trace dash and
markers (scatter at width 0) with auto or literal stride; GatherMode
Envelope/Nearest/Mean via bucket_sum/sumsq; Style::line_aa_px; per-glyph text
colour (readout values in trace colour); wheel-dx x pan; arrow-key pan;
Escape cancels a drag and restores captured ranges; modifier-masked box zoom
(Shift both, Ctrl x, Alt y); double-click reset via PointerEvent::time_s;
ImGui key repeat unified; pinch gestures on Qt and GTK; pixelDelta wheel path
and DevicePixelRatioChange handling; GNUInstallDirs, SOVERSION,
SameMinorVersion, generated plot/version.hpp, relocatable plot.pc, licence
install, FILES_MATCHING, GitHub Actions CI (debug/coverage/asan).

Suite 283 -> 350 cases, 0 failed; coverage 93.9% (3730/3971) over 24 files,
floor 80/90 held; ASAN preset suite green; all four demos run headless (the
GTK scripted-resize check needs a window manager and fails identically on the
parent commit); readme_main.cpp committed and compiles with the README
command; pkg-config and find_package consumption verified from a relocated
install prefix.
2026-09-30 17:32:06 +02:00

235 lines
9.1 KiB
C++

// SPDX-License-Identifier: MIT
// SPDX-FileCopyrightText: 2026 Martino Ferrari
#include <plot/plot/ticks.hpp>
#include <cmath>
#include <cstdio>
#include <cstring>
namespace plot {
namespace {
/// Longest label a tick keeps before falling back to `%.3g`.
constexpr usize kMaxLabelChars = 12;
/// Scratch for one label; longest possible output is a `%.3g` fallback plus a
/// prefix plus a unit, far under this.
constexpr usize kLabelBuf = 64;
/// SI prefixes indexed by engineering exponent / 3, from 10^-24 to 10^24. The
/// micro sign is UTF-8 U+00B5 (0xC2 0xB5), not the Greek mu U+03BC: the bitmap
/// font has a glyph for U+00B5 and would draw a missing-glyph box for U+03BC.
struct SiPrefix {
int index;
const char* text;
};
constexpr SiPrefix kPrefixes[] = {
{-8, "y"}, {-7, "z"}, {-6, "a"}, {-5, "f"}, {-4, "p"}, {-3, "n"}, {-2, "\xC2\xB5"},
{-1, "m"}, {0, ""}, {1, "k"}, {2, "M"}, {3, "G"}, {4, "T"}, {5, "P"},
{6, "E"}, {7, "Z"}, {8, "Y"},
};
const char* prefix_for(int index) noexcept {
for (const SiPrefix& p : kPrefixes) {
if (p.index == index) return p.text;
}
return "";
}
/// `%.3g` with a NUL-terminated, never-overflowing write. Used for every value
/// the SI path refuses.
void fallback_number(f64 v, const char* unit, char* buf, usize n) noexcept {
std::snprintf(buf, n, "%.3g%s", v, unit);
}
} // namespace
void format_si(f64 v, char* buf, usize n, const char* unit) {
if (buf == nullptr || n == 0) return;
buf[0] = '\0';
const char* const u = unit != nullptr ? unit : "";
if (!std::isfinite(v)) {
fallback_number(v, u, buf, n);
return;
}
if (v == 0.0) {
std::snprintf(buf, n, "0%s", u);
return;
}
// Engineering exponent: |v| == scaled * 10^(3*e3) with scaled in [1, 1000).
const f64 magnitude = std::fabs(v);
const int e3 = static_cast<int>(std::floor(std::log10(magnitude) / 3.0));
if (e3 < kPrefixes[0].index || e3 > kPrefixes[sizeof(kPrefixes) / sizeof(kPrefixes[0]) - 1].index) {
fallback_number(v, u, buf, n);
return;
}
f64 scaled = v / std::pow(10.0, 3.0 * static_cast<f64>(e3));
int index = e3;
// Rounding to three significant digits must not spill the scale: 999.9 goes
// to 1.00 of the next prefix rather than to `1e+03` of this one.
if (std::fabs(scaled) >= 999.5) {
index = e3 + 1;
if (index > kPrefixes[sizeof(kPrefixes) / sizeof(kPrefixes[0]) - 1].index) {
fallback_number(v, u, buf, n);
return;
}
scaled = v / std::pow(10.0, 3.0 * static_cast<f64>(index));
}
std::snprintf(buf, n, "%.3g%s%s", scaled, prefix_for(index), u);
if (std::strlen(buf) > kMaxLabelChars) {
// A 12-character budget keeps axis labels readable; anything longer is a
// scientific-notation value the caller is better served by verbatim.
fallback_number(v, u, buf, n);
}
}
void format_time(f64 seconds, char* buf, usize n) {
if (buf == nullptr || n == 0) return;
buf[0] = '\0';
if (!std::isfinite(seconds)) {
std::snprintf(buf, n, "%.3g", seconds);
return;
}
const char* const sign = seconds < 0.0 ? "-" : "";
const f64 t = std::fabs(seconds);
if (t < 1.0) {
// Sub-second: milliseconds. The 999.5 cut keeps %.3g out of scientific
// notation (it would print "1e+03ms") right below the one-second boundary.
const f64 ms = t * 1000.0;
if (ms < 999.5) {
std::snprintf(buf, n, "%s%.3gms", sign, ms);
} else {
std::snprintf(buf, n, "%s%.3gs", sign, t);
}
return;
}
// ONE rounding decision for the whole value. Deriving the fields from a single
// rounded second count is what keeps a field from reaching its radix: rounding
// the seconds leftover independently would print 119.5 s as "1:60".
const f64 whole = std::round(t);
if (whole >= 86400.0) {
// At or above a day the day field appears, so the h:mm:ss shape never sees an
// hour of 24 or more.
std::snprintf(buf, n, "%s%.3gd", sign, whole / 86400.0);
return;
}
const auto total = static_cast<unsigned long long>(whole);
if (whole >= 3600.0) {
std::snprintf(buf, n, "%s%llu:%02llu:%02llu", sign, total / 3600ull,
(total / 60ull) % 60ull, total % 60ull);
} else if (whole >= 60.0) {
std::snprintf(buf, n, "%s%llu:%02llu", sign, total / 60ull, total % 60ull);
} else {
std::snprintf(buf, n, "%s%.3gs", sign, t);
}
}
void generate_ticks(Range range, f32 px, f32 min_px, std::vector<Tick>& out, bool include_minors) {
out.clear();
const f64 lo = range.min;
const f64 hi = range.max;
const f64 span = hi - lo;
// Non-finite endpoints, an inverted range and a zero span (a collapsed range,
// e.g. the x bounds of a single-sample series) all have nothing to tick.
if (!std::isfinite(lo) || !std::isfinite(hi) || !(span > 0.0)) return;
if (!(px > 0.0f) || !(min_px > 0.0f)) return;
const f64 target = std::max(1.0, static_cast<f64>(px) / static_cast<f64>(min_px));
const f64 raw_step = span / target;
if (!std::isfinite(raw_step) || !(raw_step > 0.0)) return;
const f64 magnitude = std::pow(10.0, std::floor(std::log10(raw_step)));
if (!std::isfinite(magnitude) || !(magnitude > 0.0)) return;
const f64 normalised = raw_step / magnitude; // in [1, 10)
// Round the step UP to the next 1/2/5 x 10^n, so the major spacing really does
// meet min_px instead of landing just under it.
const f64 step = magnitude * (normalised <= 1.0 ? 1.0
: normalised <= 2.0 ? 2.0
: normalised <= 5.0 ? 5.0
: 10.0);
if (!std::isfinite(step) || !(step > 0.0)) return; // span so large the step overflowed
const f64 first_major = std::ceil(lo / step) * step;
if (!std::isfinite(first_major)) return;
// Minor ticks subdivide the major step: by 4 when the step's leading digit is
// 2, by 5 for 1 and 5 (and for a step of 10, i.e. a leading 1 one decade up).
const f64 lead = step / magnitude;
const f64 minor_ratio = (lead > 1.5 && lead < 3.0) ? 4.0 : 5.0;
const f64 minor_step = step / minor_ratio;
if (!std::isfinite(minor_step) || !(minor_step > 0.0)) return;
// Minors subdivide the major step an exact integer number of times, so the
// major/minor split is an *integer-index* test: a tick is a major when its
// minor index, counted from `first_major`, is a multiple of the ratio. Both
// operands of the index are exact for the windows axes actually show --
// `v - first_major` is the difference of two near doubles (Sterbenz-exact), and
// rounding the small quotient lands on the index the grid defines -- so no float
// tolerance is needed and none is applied. The old `|v - round(v/step)*step| <=
// step*1e-9` test fought a ULP-sized residue that an epoch origin produces
// whenever the step is not a power of two (v/step carries a rounding error of a
// few ULP of 1.75e9, i.e. far more than step*1e-9) and misclassified its majors;
// the index here has no residue to fight.
const auto minor_index_is_major = [&](f64 v) {
const f64 index = std::round((v - first_major) / minor_step);
return std::fmod(index, minor_ratio) == 0.0;
};
// Mutable: once the minors are capped the walk steps the major stride (see the
// cap branch below).
f64 stride = include_minors ? minor_step : step;
const f64 first = include_minors ? std::ceil(lo / minor_step) * minor_step : first_major;
if (!std::isfinite(first)) return;
char label[kLabelBuf];
usize minors = 0;
for (f64 v = first; v <= hi + stride * 1e-9;) {
const bool major = !include_minors || minor_index_is_major(v);
if (!major && minors >= kMaxTicks) {
// The cap counts minors only, and the majors are never truncated: an axis
// dense enough to want more subdivisions than fit loses its *subdivisions*,
// not its labels, so the far end of the axis keeps its numbers. From here on
// the walk steps the major stride; the next major at or after `v` is
// re-seated onto the major grid explicitly, because continuing from an
// off-grid minor with the new stride would visit only off-grid points and
// silently drop every remaining label. `minors >= kMaxTicks` is also the
// guard that keeps a hostile request (px towering over min_px) from stepping
// a minor stride across the whole range after the cap; the majors-only walk
// is as long as the caller's own pixel count asked it to be.
stride = step;
const f64 major_index = std::ceil((v - first_major) / step - 1e-9);
f64 reseat = first_major + major_index * step;
if (reseat < v) reseat = first_major + (major_index + 1.0) * step;
v = reseat;
continue;
}
if (!major) ++minors;
Tick tick;
tick.value = v;
tick.major = major;
if (major) {
// format_si owns both label guards: it never writes past the buffer, and it
// falls back to %.3g for a non-finite value or a label over 12 characters.
format_si(v, label, sizeof label);
tick.label = label;
}
out.push_back(std::move(tick));
const f64 next = v + stride;
// No progress would mean an infinite loop on a denormal stride far from the
// origin; stop instead of spinning.
if (!(next > v)) break;
v = next;
}
}
} // namespace plot