// SPDX-License-Identifier: MIT // SPDX-FileCopyrightText: 2026 Martino Ferrari #include #include #include #include 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(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(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(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(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& 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(px) / static_cast(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