`format_time()` picked its sub-second rung from the raw value, so three significant figures of a value just under a rung's top rounded to 1000 and `%.3g` wrote that as an exponent: a one-second tick computed as 0.9999999 s read `1e+03ms`. The rung is now chosen by the rounded mantissa, which is the same 999.5 check `format_si()` already made for the SI prefixes, and a value that rounds to a whole second leaves the sub-second branch entirely.
285 lines
12 KiB
C++
285 lines
12 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);
|
|
|
|
// `0.9995` and not `1.0`: three significant figures of 0.9999 s are `1e+03ms`, so a value
|
|
// that *rounds* to a second belongs to the whole-second branch below, which writes it `1s`.
|
|
// The same spill one rung down is handled inside the ladder.
|
|
if (t < 0.9995) {
|
|
// Sub-second: the prefix that keeps the mantissa in [1, 1000) -- the same rule the SI
|
|
// formatter uses on a y axis, and the reading a zoomed-in window needs. A fixed
|
|
// millisecond unit printed `0.005ms` where `5us` is what the axis is showing, and
|
|
// `1e-05ms` where `10ns` is. The micro sign is the UTF-8 sequence the embedded font has a
|
|
// glyph for (see `format_si`), not a Latin-1 byte.
|
|
// Exactly zero carries no unit, the same convention `format_si` states: every prefixed
|
|
// form of it is "0" with a unit the value does not have.
|
|
if (t == 0.0) {
|
|
std::snprintf(buf, n, "0");
|
|
return;
|
|
}
|
|
static const struct {
|
|
f64 scale;
|
|
const char* unit;
|
|
} kUnits[] = {
|
|
{1.0e-3, "ms"},
|
|
{1.0e-6, "\u00b5s"},
|
|
{1.0e-9, "ns"},
|
|
{1.0e-12, "ps"},
|
|
};
|
|
// The rung is picked by the *rounded* mantissa, which is what `format_si`'s own 999.5
|
|
// check buys there: 0.9999 ms is `999.9µs` before rounding and `1e+03µs` after, so it is
|
|
// the millisecond rung's value and reads `1ms`. Testing the raw `t < u.scale` let the
|
|
// mantissa reach 1000 at every rung boundary.
|
|
for (const auto& u : kUnits) {
|
|
if (t < u.scale * 0.9995) continue;
|
|
std::snprintf(buf, n, "%s%.3g%s", sign, t / u.scale, u.unit);
|
|
return;
|
|
}
|
|
// Below a picosecond nothing on a time axis reads in prefixed units; plain seconds keep
|
|
// the fallback's own precision rather than inventing one.
|
|
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,
|
|
f64 origin) {
|
|
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
|
|
|
|
// The major walk starts on the *origin's* grid: with an origin the ticks a host reads are
|
|
// round numbers relative to it (0, 0.5ms, 1ms of the window it zoomed into), which is the
|
|
// whole point of having one. `origin = 0` is the plain absolute grid.
|
|
const f64 first_major = origin + std::ceil((lo - origin) / 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;
|
|
|
|
// The walk starts at `ceil(lo / stride) * stride`, which is not representable
|
|
// whenever the stride is not a power of two -- 0.1 and 0.2 are the common ones --
|
|
// so a range that straddles the origin never lands *on* it: [-1, 1] stepped by 0.1
|
|
// reaches -1.39e-16 where it means zero, and that renders as `-139a`, a label from
|
|
// the far end of the SI table sitting between `-500m` and `500m`. Deriving `v` by
|
|
// multiplication instead of accumulation does not help, because the error is
|
|
// already in `first`.
|
|
//
|
|
// Every tick is an integer multiple of the stride, so the smallest magnitude a
|
|
// *non-zero* tick can have is the stride itself, while the residue is a few ULP of
|
|
// the range -- a relative gap of some ten orders of magnitude. Anything inside a
|
|
// millionth of the stride is therefore the zero tick and nothing else, and it is
|
|
// stored as exactly `0.0` rather than merely labelled as such: `Axis::refresh()`
|
|
// re-formats a time axis from `tick.value`, where the same residue reads
|
|
// `3.19e-13ms`.
|
|
const f64 zero_tol = (include_minors ? minor_step : step) * 1e-6;
|
|
|
|
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;
|
|
// The walk variable itself is left alone: `minor_index_is_major` counts indices
|
|
// from `first_major` and both operands have to stay on the walk's own grid.
|
|
tick.value = std::fabs(v) < zero_tol ? 0.0 : 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(tick.value, 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
|