diff --git a/plotjuggler_base/include/PlotJuggler/reactive_function.h b/plotjuggler_base/include/PlotJuggler/reactive_function.h index cf05e4229..2ee525672 100644 --- a/plotjuggler_base/include/PlotJuggler/reactive_function.h +++ b/plotjuggler_base/include/PlotJuggler/reactive_function.h @@ -25,7 +25,7 @@ struct TimeseriesRef void set(unsigned index, double x, double y); - double atTime(double t) const; + double atTime(double t, MatchType match_type) const; int getRawIndexAtTime(double t) const; @@ -63,6 +63,11 @@ struct CreatedSeriesXY : public CreatedSeriesBase CreatedSeriesXY(PlotDataMapRef* data_map, const std::string& name); }; +enum class MatchType { + Exact, // Returns an index only if the exact time is found + Nearest // Returns the nearest time index (current behavior) +}; + //----------------------- class ReactiveLuaFunction : public PJ::TransformFunction diff --git a/plotjuggler_base/src/reactive_function.cpp b/plotjuggler_base/src/reactive_function.cpp index b861b87ec..a5a6124cf 100644 --- a/plotjuggler_base/src/reactive_function.cpp +++ b/plotjuggler_base/src/reactive_function.cpp @@ -185,15 +185,34 @@ void TimeseriesRef::set(unsigned index, double x, double y) p = { x, y }; } -double TimeseriesRef::atTime(double t) const +double TimeseriesRef::atTime(double t, MatchType match_type) const { - int i = _plot_data->getIndexFromX(t); - return _plot_data->at(i).y; + auto index = getRawIndexAtTime(t, match_type); + if (!index) + { + throw std::runtime_error("Time point not found for exact match requirement"); + } + return _plot_data->at(*index).y; } -int TimeseriesRef::getRawIndexAtTime(double t) const +std::optional TimeseriesRef::getRawIndexAtTime(double t, MatchType match_type) const { - return _plot_data->getIndexFromX(t); + if (match_type == MatchType::Exact) + { + auto it = std::find_if( + _plot_data->begin(), + _plot_data->end(), + [t](const auto& point) { return point.x == t; }); + if (it != _plot_data->end()) + { + return std::distance(_plot_data->begin(), it); + } + return std::nullopt; // Exact time not found + } + else + { + return _plot_data->getIndexFromX(t); // Nearest match + } } unsigned TimeseriesRef::size() const