implot.cpp 111.8 KB
Newer Older
Evan Pezent's avatar
Evan Pezent 已提交
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// MIT License

// Copyright (c) 2020 Evan Pezent

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// ImPlot v0.2 WIP

/*

API BREAKING CHANGES
====================
Occasionally introducing changes that are breaking the API. We try to make the breakage minor and easy to fix.
Below is a change-log of API breaking changes only. If you are using one of the functions listed, expect to have to fix some code.
When you are not sure about a old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all implot files.
You can read releases logs https://github.com/epezent/implot/releases for more details.

- 2020/05/10 (0.2) - The following function/struct names were changes:
                    - ImPlotRange       -> ImPlotLimits
                    - GetPlotRange()    -> GetPlotLimits()
                    - SetNextPlotRange  -> SetNextPlotLimits 
                    - SetNextPlotRangeX -> SetNextPlotLimitsX
                    - SetNextPlotRangeY -> SetNextPlotLimitsY
- 2020/05/10 (0.2) - Plot queries are pixel based by default. Query rects that maintain relative plot position have been removed. This was done to support multi-y-axis.

*/

#ifdef _MSC_VER
#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
#endif
Evan Pezent's avatar
Evan Pezent 已提交
47
48
49
50
51

#ifndef IMGUI_DEFINE_MATH_OPERATORS
#define IMGUI_DEFINE_MATH_OPERATORS
#endif

52

Evan Pezent's avatar
Evan Pezent 已提交
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include <implot.h>
#include <imgui_internal.h>

#define IM_NORMALIZE2F_OVER_ZERO(VX, VY)                                                           \
    {                                                                                              \
        float d2 = VX * VX + VY * VY;                                                              \
        if (d2 > 0.0f) {                                                                           \
            float inv_len = 1.0f / ImSqrt(d2);                                                     \
            VX *= inv_len;                                                                         \
            VY *= inv_len;                                                                         \
        }                                                                                          \
    }

// Special Color used to specific that a plot item color should set determined automatically.
#define IM_COL_AUTO ImVec4(0,0,0,-1)
68
69
// The maximum number of support y-axes
#define MAX_Y_AXES 3
Evan Pezent's avatar
Evan Pezent 已提交
70
71
72
73
74
75
76
77

ImPlotStyle::ImPlotStyle() {
    LineWeight = 1;
    Marker = ImMarker_None;
    MarkerSize = 5;
    MarkerWeight = 1;
    ErrorBarSize = 5;
    ErrorBarWeight = 1.5;
ozlb's avatar
ozlb 已提交
78
    DigitalBitHeight = 8;
Evan Pezent's avatar
Evan Pezent 已提交
79
80
81
82
83
84
85
86
87
88
89

    Colors[ImPlotCol_Line]          = IM_COL_AUTO;
    Colors[ImPlotCol_Fill]          = IM_COL_AUTO;
    Colors[ImPlotCol_MarkerOutline] = IM_COL_AUTO;
    Colors[ImPlotCol_MarkerFill]    = IM_COL_AUTO;
    Colors[ImPlotCol_ErrorBar]      = IM_COL_AUTO;
    Colors[ImPlotCol_FrameBg]       = IM_COL_AUTO;
    Colors[ImPlotCol_PlotBg]        = IM_COL_AUTO;
    Colors[ImPlotCol_PlotBorder]    = IM_COL_AUTO;
    Colors[ImPlotCol_XAxis]         = IM_COL_AUTO;
    Colors[ImPlotCol_YAxis]         = IM_COL_AUTO;
90
91
    Colors[ImPlotCol_YAxis2]        = IM_COL_AUTO;
    Colors[ImPlotCol_YAxis3]        = IM_COL_AUTO;
Evan Pezent's avatar
Evan Pezent 已提交
92
    Colors[ImPlotCol_Selection]     = ImVec4(1,1,0,1);
ozlb's avatar
Curors    
ozlb 已提交
93
    Colors[ImPlotCol_Query]         = ImVec4(0,1,0,1);
94
    Colors[ImPlotCol_QueryX]        = ImVec4(1,0,0,1);
95
96
}

97
98
99
100
ImPlotRange::ImPlotRange() : Min(NAN), Max(NAN) {}

bool ImPlotRange::Contains(float v) const {
    return v >= Min && v <= Max;
101
102
}

103
104
105
106
107
108
109
110
float ImPlotRange::Size() const {
    return Max - Min;
}

ImPlotLimits::ImPlotLimits() {}

bool ImPlotLimits::Contains(const ImVec2& p) const {
    return X.Contains(p.x) && Y.Contains(p.y);
Evan Pezent's avatar
Evan Pezent 已提交
111
112
113
114
115
116
}

namespace ImGui {

namespace {

117
118
119
//-----------------------------------------------------------------------------
// Private Utils
//-----------------------------------------------------------------------------
Evan Pezent's avatar
Evan Pezent 已提交
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137

/// Returns true if a flag is set
template <typename TSet, typename TFlag>
inline bool HasFlag(TSet set, TFlag flag) {
    return (set & flag) == flag;
}

/// Flips a flag in a flagset
template <typename TSet, typename TFlag> 
inline void FlipFlag(TSet& set, TFlag flag) {
    HasFlag(set, flag) ? set &= ~flag : set |= flag;
}

/// Linearly remaps float x from [x0 x1] to [y0 y1].
inline float Remap(float x, float x0, float x1, float y0, float y1) {
    return y0 + (x - x0) * (y1 - y0) / (x1 - x0);
}

138
/// Turns NANs to 0s
Evan Pezent's avatar
Evan Pezent 已提交
139
inline float ConstrainNan(float val) {
140
    return isnan(val) ? 0 : val;
Evan Pezent's avatar
Evan Pezent 已提交
141
142
}

143
/// Turns INFINITYs to FLT_MAXs
Evan Pezent's avatar
Evan Pezent 已提交
144
145
146
147
inline float ConstrainInf(float val) {
    return val == INFINITY ? FLT_MAX : val == -INFINITY ? -FLT_MAX : val;
}

148
/// Turns numbers less than or equal to 0 to 0.001 (sort of arbitrary, is there a better way?)
Evan Pezent's avatar
Evan Pezent 已提交
149
inline float ConstrainLog(float val) {
150
    return val <= 0 ? 0.001f : val;
Evan Pezent's avatar
Evan Pezent 已提交
151
152
}

153
/// Returns true if val is NAN or INFINITY
Evan Pezent's avatar
Evan Pezent 已提交
154
inline bool NanOrInf(float val) {
155
    return val == INFINITY || val == -INFINITY || isnan(val);
Evan Pezent's avatar
Evan Pezent 已提交
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
}

/// Utility function to that rounds x to powers of 2,5 and 10 for generating axis labels
/// Taken from Graphics Gems 1 Chapter 11.2, "Nice Numbers for Graph Labels"
inline double NiceNum(double x, bool round) {
    double f;  /* fractional part of x */
    double nf; /* nice, rounded fraction */
    int expv = (int)floor(log10(x));
    f = x / ImPow(10.0, (double)expv); /* between 1 and 10 */
    if (round)
        if (f < 1.5)
            nf = 1;
        else if (f < 3)
            nf = 2;
        else if (f < 7)
            nf = 5;
        else
            nf = 10;
    else if (f <= 1)
        nf = 1;
    else if (f <= 2)
        nf = 2;
    else if (f <= 5)
        nf = 5;
    else
        nf = 10;
    return nf * ImPow(10.0, expv);
}

/// Draws vertical text. The position is the bottom left of the text rect.
inline void AddTextVertical(ImDrawList *DrawList, const char *text, ImVec2 pos, ImU32 text_color) {
    pos.x                   = IM_ROUND(pos.x);
    pos.y                   = IM_ROUND(pos.y);
    ImFont *           font = GImGui->Font;
    const ImFontGlyph *glyph;
    char               c;
    while ((c = *text++)) {
        glyph = font->FindGlyph(c);
        if (!glyph)
            continue;

        DrawList->PrimReserve(6, 4);
        DrawList->PrimQuadUV(
            pos + ImVec2(glyph->Y0, -glyph->X0), pos + ImVec2(glyph->Y0, -glyph->X1),
            pos + ImVec2(glyph->Y1, -glyph->X1), pos + ImVec2(glyph->Y1, -glyph->X0),

            ImVec2(glyph->U0, glyph->V0), ImVec2(glyph->U1, glyph->V0),
            ImVec2(glyph->U1, glyph->V1), ImVec2(glyph->U0, glyph->V1), text_color);
        pos.y -= glyph->AdvanceX;
    }
}

/// Calculates the size of vertical text
inline ImVec2 CalcTextSizeVertical(const char *text) {
    ImVec2 sz = CalcTextSize(text);
    return ImVec2(sz.y, sz.x);
}

214
215
216
217
218
219
220
221
222
} // private namespace

//-----------------------------------------------------------------------------
// Forwards
//-----------------------------------------------------------------------------

ImVec4 NextColor();

//-----------------------------------------------------------------------------
Evan Pezent's avatar
Evan Pezent 已提交
223
// Structs
224
225
//-----------------------------------------------------------------------------

Evan Pezent's avatar
Evan Pezent 已提交
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242

/// Tick mark info
struct ImTick {
    ImTick(double value, bool major, bool render_label = true) { 
        PlotPos = value;
        Major = major;
        RenderLabel = render_label;
    }
    double PlotPos;
    float  PixelPos;
    bool   Major;
    ImVec2 Size;
    int    TextOffset;
    bool   RenderLabel;
};

struct ImPlotItem {
243
244
245
246
247
248
249
    ImPlotItem() {
        Show = true; 
        Highlight = false;
        Color = NextColor(); 
        NameOffset = -1; 
        ID = 0;  
    }
Evan Pezent's avatar
Evan Pezent 已提交
250
251
    ~ImPlotItem() { ID = 0; }
    bool Show;
252
    bool Highlight;
Evan Pezent's avatar
Evan Pezent 已提交
253
254
255
256
257
258
259
260
261
    ImVec4 Color;
    int NameOffset;
    ImGuiID ID;
};

/// Plot axis structure. You shouldn't need to construct this!
struct ImPlotAxis {
    ImPlotAxis() { 
        Dragging = false;
262
263
        Range.Min = 0;
        Range.Max = 1;
Evan Pezent's avatar
Evan Pezent 已提交
264
265
        Divisions = 3; 
        Subdivisions = 10; 
266
        Flags = PreviousFlags = ImAxisFlags_Default; 
Evan Pezent's avatar
Evan Pezent 已提交
267
268
    }
    bool Dragging;
269
    ImPlotRange Range;
Evan Pezent's avatar
Evan Pezent 已提交
270
271
    int Divisions;
    int Subdivisions;
272
    ImAxisFlags Flags, PreviousFlags;
Evan Pezent's avatar
Evan Pezent 已提交
273
274
275
276
277
};

/// Holds Plot state information that must persist between frames
struct ImPlot {
    ImPlot() {
278
        Selecting = Querying = Queried = DraggingQuery = false;
Evan Pezent's avatar
Evan Pezent 已提交
279
        SelectStart =  QueryStart = ImVec2(0,0);
280
281
        Flags = PreviousFlags = ImPlotFlags_Default;
        DraggingQueryX[0] = DraggingQueryX[1] = false;
Evan Pezent's avatar
Evan Pezent 已提交
282
        ColorIdx = 0;
283
        CurrentYAxis = 0;
Evan Pezent's avatar
Evan Pezent 已提交
284
285
286
287
288
289
    }
    ImPool<ImPlotItem> Items;

    ImRect BB_Legend;
    bool Selecting;
    ImVec2 SelectStart;
Evan Pezent's avatar
Evan Pezent 已提交
290
291
292
    bool Querying;
    bool Queried;
    ImVec2 QueryStart;
293
294
    ImRect QueryRect; // relative to BB_grid!!
    bool DraggingQuery;
295
296
297
298

    bool DraggingQueryX[2];
    ImRect QueryRectX[2]; // relative to BB_grid!!
    ImPlotLimits QueryRangeX;
ozlb's avatar
ozlb 已提交
299

Evan Pezent's avatar
Evan Pezent 已提交
300
    ImPlotAxis XAxis;
301
302
    ImPlotAxis YAxis[MAX_Y_AXES];

303

304
    ImPlotFlags Flags, PreviousFlags;
Evan Pezent's avatar
Evan Pezent 已提交
305
    int ColorIdx;
306
    int CurrentYAxis;
Evan Pezent's avatar
Evan Pezent 已提交
307
308
309
};

struct ImNextPlotData {
310
    ImNextPlotData() : HasXRange{}, HasYRange{} {}
Evan Pezent's avatar
Evan Pezent 已提交
311
    ImGuiCond XRangeCond;
312
    ImGuiCond YRangeCond[MAX_Y_AXES];
Evan Pezent's avatar
Evan Pezent 已提交
313
    bool HasXRange;
314
315
316
    bool HasYRange[MAX_Y_AXES];
    ImPlotRange X;
    ImPlotRange Y[MAX_Y_AXES];
Evan Pezent's avatar
Evan Pezent 已提交
317
318
319
320
};

/// Holds Plot state information that must persist only between calls to BeginPlot()/EndPlot()
struct ImPlotContext {
321
    ImPlotContext() : RenderX(), RenderY() {
Evan Pezent's avatar
Evan Pezent 已提交
322
        CurrentPlot = NULL;
323
        FitThisFrame = FitX = false;
Evan Pezent's avatar
Evan Pezent 已提交
324
325
        RestorePlotPalette();
    }
326

Evan Pezent's avatar
Evan Pezent 已提交
327
328
329
330
331
    /// ALl Plots    
    ImPool<ImPlot> Plots;
    /// Current Plot
    ImPlot* CurrentPlot;
    // Legend
332
333
    ImVector<int> LegendIndices;    
    ImGuiTextBuffer LegendLabels;
Evan Pezent's avatar
Evan Pezent 已提交
334
335
336
337
338
339
340
    // Bounding regions    
    ImRect BB_Frame;
    ImRect BB_Canvas;
    ImRect BB_Grid;
    // Hover states
    bool Hov_Frame;
    bool Hov_Grid;
341
    // Cached Colors
Evan Pezent's avatar
Evan Pezent 已提交
342
343
344
    ImU32 Col_Frame, Col_Bg, Col_Border, 
          Col_Txt, Col_TxtDis, 
          Col_SlctBg, Col_SlctBd,
345
          Col_QryBg, Col_QryBd,
346
347
348
349
350
351
352
353
354
355
356
          Col_QryX;
    struct AxisColor {
        AxisColor() : Major(), Minor(), Txt() {}
        ImU32 Major, Minor, Txt;
    };
    AxisColor Col_X;
    AxisColor Col_Y[MAX_Y_AXES];
    // Tick marks
    ImVector<ImTick> XTicks,  YTicks[MAX_Y_AXES];
    ImGuiTextBuffer XTickLabels, YTickLabels[MAX_Y_AXES];
    float AxisLabelReference[MAX_Y_AXES];
357
    // Transformation cache
358
359
360
361
362
363
364
    ImRect PixelRange[MAX_Y_AXES];
    // linear scale (slope)
    float Mx;
    float My[MAX_Y_AXES];
    // log scale denominator
    float LogDenX;
    float LogDenY[MAX_Y_AXES];
Evan Pezent's avatar
Evan Pezent 已提交
365
366

    // Data extents
367
368
369
370
371
    ImPlotRange ExtentsX;
    ImPlotRange ExtentsY[MAX_Y_AXES];

    bool FitThisFrame; bool FitX;
    bool FitY[MAX_Y_AXES] = {};
Evan Pezent's avatar
Evan Pezent 已提交
372
373
    int VisibleItemCount;
    // Render flags
374
    bool RenderX, RenderY[MAX_Y_AXES];
Evan Pezent's avatar
Evan Pezent 已提交
375
    // Mouse pos
376
    ImVec2 LastMousePos[MAX_Y_AXES];
Evan Pezent's avatar
Evan Pezent 已提交
377
378
379
380
381
    // Style
    ImVector<ImVec4> ColorMap;
    ImPlotStyle Style;
    ImVector<ImGuiColorMod> ColorModifiers;  // Stack for PushStyleColor()/PopStyleColor()
    ImVector<ImGuiStyleMod> StyleModifiers;  // Stack for PushStyleVar()/PopStyleVar()
ozlb's avatar
ozlb 已提交
382
383
384
    ImNextPlotData NextPlotData;        
    // Digital plot item count
    int DigitalPlotItemCnt;
ozlb's avatar
ozlb 已提交
385
    int DigitalPlotOffset;
Evan Pezent's avatar
Evan Pezent 已提交
386
387
388
389
390
};

/// Global plot context
static ImPlotContext gp;

391
392
393
394
395
396
//-----------------------------------------------------------------------------
// Utils
//-----------------------------------------------------------------------------

/// Returns the next unused default plot color
ImVec4 NextColor() {
397
    ImVec4 col  = gp.ColorMap[gp.CurrentPlot->ColorIdx % gp.ColorMap.size()];
398
399
    gp.CurrentPlot->ColorIdx++;
    return col;
400
}
Evan Pezent's avatar
Evan Pezent 已提交
401

402
inline void FitPoint(const ImVec2& p) {
403
404
    ImPlotRange* extents_x = &gp.ExtentsX;
    ImPlotRange* extents_y = &gp.ExtentsY[gp.CurrentPlot->CurrentYAxis];
405
    if (!NanOrInf(p.x)) {
406
407
        extents_x->Min = p.x < extents_x->Min ? p.x : extents_x->Min;
        extents_x->Max = p.x > extents_x->Max ? p.x : extents_x->Max;
408
409
    }
    if (!NanOrInf(p.y)) {
410
411
        extents_y->Min = p.y < extents_y->Min ? p.y : extents_y->Min;
        extents_y->Max = p.y > extents_y->Max ? p.y : extents_y->Max;
412
413
414
415
416
417
418
419
420
421
    }
}

//-----------------------------------------------------------------------------
// Coordinate Transforms
//-----------------------------------------------------------------------------

inline void UpdateTransformCache() {
    // get pixels for transforms

422
423
424
425
426
427
428
429
430
431
432
433
434
    for (int i = 0; i < MAX_Y_AXES; i++) {
        gp.PixelRange[i] = ImRect(HasFlag(gp.CurrentPlot->XAxis.Flags, ImAxisFlags_Invert) ? gp.BB_Grid.Max.x : gp.BB_Grid.Min.x,
                                  HasFlag(gp.CurrentPlot->YAxis[i].Flags, ImAxisFlags_Invert) ? gp.BB_Grid.Min.y : gp.BB_Grid.Max.y,
                                  HasFlag(gp.CurrentPlot->XAxis.Flags, ImAxisFlags_Invert) ? gp.BB_Grid.Min.x : gp.BB_Grid.Max.x,
                                  HasFlag(gp.CurrentPlot->YAxis[i].Flags, ImAxisFlags_Invert) ? gp.BB_Grid.Max.y : gp.BB_Grid.Min.y);

        gp.My[i] = (gp.PixelRange[i].Max.y - gp.PixelRange[i].Min.y) / gp.CurrentPlot->YAxis[i].Range.Size();
    }
    gp.LogDenX = log10(gp.CurrentPlot->XAxis.Range.Max / gp.CurrentPlot->XAxis.Range.Min);
    for (int i = 0; i < MAX_Y_AXES; i++) {
        gp.LogDenY[i] = log10(gp.CurrentPlot->YAxis[i].Range.Max / gp.CurrentPlot->YAxis[i].Range.Min);
    }
    gp.Mx = (gp.PixelRange[0].Max.x - gp.PixelRange[0].Min.x) / gp.CurrentPlot->XAxis.Range.Size();
435
}
Evan Pezent's avatar
Evan Pezent 已提交
436

437
inline ImVec2 PixelsToPlot(float x, float y, int y_axis_in = -1) {
438
    IM_ASSERT_USER_ERROR(gp.CurrentPlot != NULL, "PixelsToPlot() Needs to be called between BeginPlot() and EndPlot()!");
439
    const int y_axis = y_axis_in >= 0 ? y_axis_in : gp.CurrentPlot->CurrentYAxis;
440
    ImVec2 plt;
441
442
    plt.x = (x - gp.PixelRange[y_axis].Min.x) / gp.Mx + gp.CurrentPlot->XAxis.Range.Min;
    plt.y = (y - gp.PixelRange[y_axis].Min.y) / gp.My[y_axis] + gp.CurrentPlot->YAxis[y_axis].Range.Min;
443
    if (HasFlag(gp.CurrentPlot->XAxis.Flags, ImAxisFlags_LogScale)) {
444
445
        float t = (plt.x - gp.CurrentPlot->XAxis.Range.Min) / gp.CurrentPlot->XAxis.Range.Size();
        plt.x = pow(10.0f, t * gp.LogDenX) * gp.CurrentPlot->XAxis.Range.Min;
446
    }
447
448
449
    if (HasFlag(gp.CurrentPlot->YAxis[y_axis].Flags, ImAxisFlags_LogScale)) {
        float t = (plt.y - gp.CurrentPlot->YAxis[y_axis].Range.Min) / gp.CurrentPlot->YAxis[y_axis].Range.Size();
        plt.y = pow(10.0f, t * gp.LogDenY[y_axis]) * gp.CurrentPlot->YAxis[y_axis].Range.Min;
450
451
452
453
    }
    return plt;
}

454
inline ImVec2 PlotToPixels(float x, float y, int y_axis_in = -1) {
455
    IM_ASSERT_USER_ERROR(gp.CurrentPlot != NULL, "PlotToPixels() Needs to be called between BeginPlot() and EndPlot()!");
456
    const int y_axis = y_axis_in >= 0 ? y_axis_in : gp.CurrentPlot->CurrentYAxis;
457
458
    ImVec2 pix;
    if (HasFlag(gp.CurrentPlot->XAxis.Flags, ImAxisFlags_LogScale)) {
459
460
        float t = log10(x / gp.CurrentPlot->XAxis.Range.Min) / gp.LogDenX;
        x       = ImLerp(gp.CurrentPlot->XAxis.Range.Min, gp.CurrentPlot->XAxis.Range.Max, t);
461
    }             
462
463
464
    if (HasFlag(gp.CurrentPlot->YAxis[y_axis].Flags, ImAxisFlags_LogScale)) {
        float t = log10(y / gp.CurrentPlot->YAxis[y_axis].Range.Min) / gp.LogDenY[y_axis];
        y       = ImLerp(gp.CurrentPlot->YAxis[y_axis].Range.Min, gp.CurrentPlot->YAxis[y_axis].Range.Max, t);
465
    }
466
467
    pix.x = gp.PixelRange[y_axis].Min.x + gp.Mx * (x - gp.CurrentPlot->XAxis.Range.Min);
    pix.y = gp.PixelRange[y_axis].Min.y + gp.My[y_axis] * (y - gp.CurrentPlot->YAxis[y_axis].Range.Min);
468
469
470
    return pix;
}

471
472
ImVec2 PixelsToPlot(const ImVec2& pix, int y_axis) {
    return PixelsToPlot(pix.x, pix.y, y_axis);
473
474
}

475
476
ImVec2 PlotToPixels(const ImVec2& plt, int y_axis) {
    return PlotToPixels(plt.x, plt.y, y_axis);
477
478
479
}

struct Plt2PixLinLin {
480
    Plt2PixLinLin(int y_axis_in) : y_axis(y_axis_in) {}
481

482
483
484
485
    ImVec2 operator()(const ImVec2& plt) { return (*this)(plt.x, plt.y); }
    ImVec2 operator()(float x, float y) {
        return { gp.PixelRange[y_axis].Min.x + gp.Mx * (x - gp.CurrentPlot->XAxis.Range.Min),
                 gp.PixelRange[y_axis].Min.y + gp.My[y_axis] * (y - gp.CurrentPlot->YAxis[y_axis].Range.Min) };
486
487
    }

488
489
    int y_axis;
};
490
491

struct Plt2PixLogLin {
492
493
494
495
496
497
498
499
    Plt2PixLogLin(int y_axis_in) : y_axis(y_axis_in) {}

    ImVec2 operator()(const ImVec2& plt) { return (*this)(plt.x, plt.y); }
    ImVec2 operator()(float x, float y) {
        float t = log10(x / gp.CurrentPlot->XAxis.Range.Min) / gp.LogDenX;
        x       = ImLerp(gp.CurrentPlot->XAxis.Range.Min, gp.CurrentPlot->XAxis.Range.Max, t);
        return { gp.PixelRange[y_axis].Min.x + gp.Mx * (x - gp.CurrentPlot->XAxis.Range.Min),
                 gp.PixelRange[y_axis].Min.y + gp.My[y_axis] * (y - gp.CurrentPlot->YAxis[y_axis].Range.Min) };
500
    }
501
502

    int y_axis;
503
504
505
};

struct Plt2PixLinLog {
506
507
508
509
510
511
512
513
    Plt2PixLinLog(int y_axis_in) : y_axis(y_axis_in) {}

    ImVec2 operator()(const ImVec2& plt) { return (*this)(plt.x, plt.y); }
    ImVec2 operator()(float x, float y) {
        float t = log10(y / gp.CurrentPlot->YAxis[y_axis].Range.Min) / gp.LogDenY[y_axis];
        y       = ImLerp(gp.CurrentPlot->YAxis[y_axis].Range.Min, gp.CurrentPlot->YAxis[y_axis].Range.Max, t);
        return { gp.PixelRange[y_axis].Min.x + gp.Mx * (x - gp.CurrentPlot->XAxis.Range.Min),
                 gp.PixelRange[y_axis].Min.y + gp.My[y_axis] * (y - gp.CurrentPlot->YAxis[y_axis].Range.Min) };
514
    }
515
516

    int y_axis;
517
518
519
};

struct Plt2PixLogLog {
520
521
522
523
524
525
526
527
528
529
    Plt2PixLogLog(int y_axis_in) : y_axis(y_axis_in) {}

    ImVec2 operator()(const ImVec2& plt) { return (*this)(plt.x, plt.y); }
    ImVec2 operator()(float x, float y) {
        float t = log10(x / gp.CurrentPlot->XAxis.Range.Min) / gp.LogDenX;
        x       = ImLerp(gp.CurrentPlot->XAxis.Range.Min, gp.CurrentPlot->XAxis.Range.Max, t);
        t       = log10(y / gp.CurrentPlot->YAxis[y_axis].Range.Min) / gp.LogDenY[y_axis];
        y       = ImLerp(gp.CurrentPlot->YAxis[y_axis].Range.Min, gp.CurrentPlot->YAxis[y_axis].Range.Max, t);
        return { gp.PixelRange[y_axis].Min.x + gp.Mx * (x - gp.CurrentPlot->XAxis.Range.Min),
                 gp.PixelRange[y_axis].Min.y + gp.My[y_axis] * (y - gp.CurrentPlot->YAxis[y_axis].Range.Min) };
530
    }
531
532

    int y_axis;
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
};

//-----------------------------------------------------------------------------
// Legend Utils
//-----------------------------------------------------------------------------

ImPlotItem* RegisterItem(const char* label_id) {
    ImGuiID id = ImGui::GetID(label_id);
    ImPlotItem* item = gp.CurrentPlot->Items.GetOrAddByKey(id);
    int idx = gp.CurrentPlot->Items.GetIndex(item);
    item->ID = id;
    gp.LegendIndices.push_back(idx);
    item->NameOffset = gp.LegendLabels.size();
    gp.LegendLabels.append(label_id, label_id + strlen(label_id) + 1);
    if (item->Show)
        gp.VisibleItemCount++;
    return item;
}

int GetLegendCount() {
    return gp.LegendIndices.size();
}

ImPlotItem* GetLegendItem(int i) {
    return gp.CurrentPlot->Items.GetByIndex(gp.LegendIndices[i]);
}

const char* GetLegendLabel(int i) {
    ImPlotItem* item  = gp.CurrentPlot->Items.GetByIndex(gp.LegendIndices[i]);
    IM_ASSERT(item->NameOffset != -1 && item->NameOffset < gp.LegendLabels.Buf.Size);
    return gp.LegendLabels.Buf.Data + item->NameOffset;
}

//-----------------------------------------------------------------------------
Evan Pezent's avatar
Evan Pezent 已提交
567
// Tick Utils
568
//-----------------------------------------------------------------------------
Evan Pezent's avatar
Evan Pezent 已提交
569

570
inline void GetTicks(const ImPlotRange& scale, int nMajor, int nMinor, bool logscale, ImVector<ImTick> &out) {
Evan Pezent's avatar
Evan Pezent 已提交
571
572
    out.shrink(0);
    if (logscale) {
573
        if (scale.Min <= 0 || scale.Max <= 0)
Evan Pezent's avatar
Evan Pezent 已提交
574
            return;
575
576
        int exp_min = (int)(ImFloor(log10(scale.Min)));
        int exp_max = (int)(ImCeil(log10(scale.Max)));
Evan Pezent's avatar
Evan Pezent 已提交
577
578
579
580
        for (int e = exp_min - 1; e < exp_max + 1; ++e) {
            double major1 = ImPow(10, (double)(e));
            double major2 = ImPow(10, (double)(e + 1));
            double interval = (major2 - major1) / 9;
581
            if (major1 >= (scale.Min - FLT_EPSILON) && major1 <= (scale.Max + FLT_EPSILON))
Evan Pezent's avatar
Evan Pezent 已提交
582
583
584
                out.push_back(ImTick(major1, true));
            for (int i = 1; i < 9; ++i) {
                double minor = major1 + i * interval;
585
                if (minor >= (scale.Min - FLT_EPSILON) && minor <= (scale.Max + FLT_EPSILON))
Evan Pezent's avatar
Evan Pezent 已提交
586
587
588
589
590
                    out.push_back(ImTick(minor, false, false));
            }
        }
    }
    else {
591
        const double range    = NiceNum(scale.Max - scale.Min, 0);
Evan Pezent's avatar
Evan Pezent 已提交
592
        const double interval = NiceNum(range / (nMajor - 1), 1);
593
594
        const double graphmin = floor(scale.Min / interval) * interval;
        const double graphmax = ceil(scale.Max / interval) * interval;
Evan Pezent's avatar
Evan Pezent 已提交
595
        for (double major = graphmin; major < graphmax + 0.5 * interval; major += interval) {
596
            if (major >= scale.Min && major <= scale.Max)
Evan Pezent's avatar
Evan Pezent 已提交
597
598
599
                out.push_back(ImTick(major, true));
            for (int i = 1; i < nMinor; ++i) {
                double minor = major + i * interval / nMinor;
600
                if (minor >= scale.Min && minor <= scale.Max)
Evan Pezent's avatar
Evan Pezent 已提交
601
602
603
604
605
606
607
608
609
                    out.push_back(ImTick(minor, false));
            }
        }
    }
}

inline void LabelTicks(ImVector<ImTick> &ticks, bool scientific, ImGuiTextBuffer& buffer) {
    buffer.Buf.resize(0);
    char temp[32];
610
    for (ImTick &tk : ticks) {
Evan Pezent's avatar
Evan Pezent 已提交
611
612
613
614
615
616
617
618
619
620
621
622
        if (tk.RenderLabel) {
            tk.TextOffset = buffer.size();
            if (scientific)
                sprintf(temp, "%.0e", tk.PlotPos);
            else
                sprintf(temp, "%g", tk.PlotPos);
            buffer.append(temp, temp + strlen(temp) + 1);
            tk.Size = CalcTextSize(buffer.Buf.Data + tk.TextOffset);
        }
    }
}

623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
namespace {
struct AxisState {
    ImPlotAxis* axis;
    bool has_range;
    ImGuiCond range_cond;
    bool present;
    int present_so_far;
    bool flip;
    bool lock_min;
    bool lock_max;
    bool lock;

    AxisState(ImPlotAxis& axis_in, bool has_range_in, ImGuiCond range_cond_in,
              bool present_in, int previous_present)
            : axis(&axis_in),
              has_range(has_range_in),
              range_cond(range_cond_in),
              present(present_in),
              present_so_far(previous_present + (present ? 1 : 0)),
              flip(HasFlag(axis->Flags, ImAxisFlags_Invert)),
              lock_min(HasFlag(axis->Flags, ImAxisFlags_LockMin)),
              lock_max(HasFlag(axis->Flags, ImAxisFlags_LockMax)),
              lock(present && ((lock_min && lock_max) || (has_range && range_cond == ImGuiCond_Always))) {}

    AxisState()
            : axis(),
              has_range(),
              range_cond(),
              present(),
              present_so_far(),
              flip(),
              lock_min(),
              lock_max(),
              lock() {}
};

void UpdateAxisColor(int axis_flag, ImPlotContext::AxisColor* col) {
    const ImVec4 col_Axis = gp.Style.Colors[axis_flag].w == -1 ? ImGui::GetStyle().Colors[ImGuiCol_Text] * ImVec4(1, 1, 1, 0.25f) : gp.Style.Colors[axis_flag];
    col->Major = GetColorU32(col_Axis);
    col->Minor = GetColorU32(col_Axis * ImVec4(1, 1, 1, 0.25f));
    col->Txt   = GetColorU32({col_Axis.x, col_Axis.y, col_Axis.z, 1});
}

ImRect GetAxisScale(int y_axis, float tx, float ty, float zoom_rate) {
    return ImRect(
            PixelsToPlot(gp.BB_Grid.Min - gp.BB_Grid.GetSize() * ImVec2(tx * zoom_rate, ty * zoom_rate), y_axis),
            PixelsToPlot(gp.BB_Grid.Max + gp.BB_Grid.GetSize() * ImVec2((1 - tx) * zoom_rate, (1 - ty) * zoom_rate), y_axis));
}

class YPadCalculator {
  public:
    YPadCalculator(const AxisState* axis_states, const float* max_label_widths, float txt_off)
            : AxisStates(axis_states), MaxLabelWidths(max_label_widths), TxtOff(txt_off) {}

    float operator()(int y_axis) {
        ImPlot& plot = *gp.CurrentPlot;
        if (!AxisStates[y_axis].present) { return 0; }
        // If we have more than 1 axis present before us, then we need
        // extra space to account for our tick bar.
        float pad_result = 0;
        if (AxisStates[y_axis].present_so_far >= 3) {
            pad_result += 6.0f;
        }
        if (!HasFlag(plot.YAxis[y_axis].Flags, ImAxisFlags_TickLabels)) {
            return pad_result;
        }
        pad_result += MaxLabelWidths[y_axis] + TxtOff;
        return pad_result;
    }

  private:
    const AxisState* const AxisStates;
    const float* const MaxLabelWidths;
    const float TxtOff;
};
}  // namespace

700
//-----------------------------------------------------------------------------
Evan Pezent's avatar
Evan Pezent 已提交
701
// BeginPlot()
702
//-----------------------------------------------------------------------------
Evan Pezent's avatar
Evan Pezent 已提交
703

704
bool BeginPlot(const char* title, const char* x_label, const char* y_label, const ImVec2& size, ImPlotFlags flags, ImAxisFlags x_flags, ImAxisFlags y_flags, ImAxisFlags y2_flags, ImAxisFlags y3_flags) {
Evan Pezent's avatar
Evan Pezent 已提交
705
706
707
708
709
710
711
712
713
714
715
716
717
718

    IM_ASSERT_USER_ERROR(gp.CurrentPlot == NULL, "Mismatched BeginPlot()/EndPlot()!");

    // FRONT MATTER  -----------------------------------------------------------

    ImGuiContext &G      = *GImGui;
    ImGuiWindow * Window = G.CurrentWindow;
    if (Window->SkipItems) {
        gp.NextPlotData = ImNextPlotData();
        return false;
    }

    const ImGuiID     ID       = Window->GetID(title);
    const ImGuiStyle &Style    = G.Style;
719
    const ImGuiIO &   IO       = GetIO();    
Evan Pezent's avatar
Evan Pezent 已提交
720
721
722
723
724

    bool just_created = gp.Plots.GetByKey(ID) == NULL;    
    gp.CurrentPlot = gp.Plots.GetOrAddByKey(ID);
    ImPlot &plot = *gp.CurrentPlot;

725
726
    plot.CurrentYAxis = 0;

Evan Pezent's avatar
Evan Pezent 已提交
727
    if (just_created) {
728
729
730
731
732
        plot.Flags          = flags;
        plot.XAxis.Flags    = x_flags;
        plot.YAxis[0].Flags = y_flags;
        plot.YAxis[1].Flags = y2_flags;
        plot.YAxis[2].Flags = y3_flags;
Evan Pezent's avatar
Evan Pezent 已提交
733
    }
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
    else {
        // TODO: Check which individual flags changed, and only reset those! 
        // There's probably an easy bit mask trick I'm not aware of.
        if (flags != plot.PreviousFlags) 
            plot.Flags = flags;            
        if (y_flags != plot.YAxis[0].PreviousFlags)
            plot.YAxis[0].PreviousFlags = y_flags;
        if (y2_flags != plot.YAxis[1].PreviousFlags)
            plot.YAxis[1].PreviousFlags = y2_flags;
        if (y3_flags != plot.YAxis[2].PreviousFlags)
            plot.YAxis[2].PreviousFlags = y3_flags;
    }

    plot.PreviousFlags          = flags;
    plot.XAxis.PreviousFlags    = x_flags;
    plot.YAxis[0].PreviousFlags = y_flags;
    plot.YAxis[1].PreviousFlags = y2_flags;
    plot.YAxis[2].PreviousFlags = y3_flags;
Evan Pezent's avatar
Evan Pezent 已提交
752

753
754
755
756
757
758
759
760
761
    // capture scroll with a child region
    if (!HasFlag(plot.Flags, ImPlotFlags_NoChild)) {
        ImGui::BeginChild(title, size);
        Window = ImGui::GetCurrentWindow();
        Window->ScrollMax.y = 1.0f;
    }

    ImDrawList &DrawList = *Window->DrawList;

Evan Pezent's avatar
Evan Pezent 已提交
762
763
764
765
766
    // NextPlotData -----------------------------------------------------------

    if (gp.NextPlotData.HasXRange) {
        if (just_created || gp.NextPlotData.XRangeCond == ImGuiCond_Always)
        {
767
            plot.XAxis.Range = gp.NextPlotData.X;
Evan Pezent's avatar
Evan Pezent 已提交
768
769
770
        }
    }

771
772
773
774
775
776
    for (int i = 0; i < MAX_Y_AXES; i++) {
        if (gp.NextPlotData.HasYRange[i]) {
            if (just_created || gp.NextPlotData.YRangeCond[i] == ImGuiCond_Always)
            {
                plot.YAxis[i].Range = gp.NextPlotData.Y[i];
            }
Evan Pezent's avatar
Evan Pezent 已提交
777
778
779
780
        }
    }

    // AXIS STATES ------------------------------------------------------------
781
782
783
784
785
786
787
    AxisState x(plot.XAxis, gp.NextPlotData.HasXRange, gp.NextPlotData.XRangeCond, true, 0);
    AxisState y[MAX_Y_AXES];
    y[0] = AxisState(plot.YAxis[0], gp.NextPlotData.HasYRange[0], gp.NextPlotData.YRangeCond[0], true, 0);
    y[1] = AxisState(plot.YAxis[1], gp.NextPlotData.HasYRange[1], gp.NextPlotData.YRangeCond[1],
                     HasFlag(plot.Flags, ImPlotFlags_YAxis2), y[0].present_so_far);
    y[2] = AxisState(plot.YAxis[2], gp.NextPlotData.HasYRange[2], gp.NextPlotData.YRangeCond[2],
                     HasFlag(plot.Flags, ImPlotFlags_YAxis3), y[1].present_so_far);
Evan Pezent's avatar
Evan Pezent 已提交
788

789
    const bool lock_plot  = x.lock && y[0].lock && y[1].lock && y[2].lock;
Evan Pezent's avatar
Evan Pezent 已提交
790
791
792

    // CONSTRAINTS ------------------------------------------------------------

793
794
795
796
797
798
    plot.XAxis.Range.Min = ConstrainNan(ConstrainInf(plot.XAxis.Range.Min));
    plot.XAxis.Range.Max = ConstrainNan(ConstrainInf(plot.XAxis.Range.Max));
    for (int i = 0; i < MAX_Y_AXES; i++) {
        plot.YAxis[i].Range.Min = ConstrainNan(ConstrainInf(plot.YAxis[i].Range.Min));
        plot.YAxis[i].Range.Max = ConstrainNan(ConstrainInf(plot.YAxis[i].Range.Max));
    }
Evan Pezent's avatar
Evan Pezent 已提交
799
800

    if (HasFlag(plot.XAxis.Flags, ImAxisFlags_LogScale))
801
        plot.XAxis.Range.Min = ConstrainLog(plot.XAxis.Range.Min);
Evan Pezent's avatar
Evan Pezent 已提交
802
    if (HasFlag(plot.XAxis.Flags, ImAxisFlags_LogScale))
803
804
805
806
807
808
809
        plot.XAxis.Range.Max = ConstrainLog(plot.XAxis.Range.Max);
    for (int i = 0; i < MAX_Y_AXES; i++) {
        if (HasFlag(plot.YAxis[i].Flags, ImAxisFlags_LogScale))
            plot.YAxis[i].Range.Min = ConstrainLog(plot.YAxis[i].Range.Min);
        if (HasFlag(plot.YAxis[i].Flags, ImAxisFlags_LogScale))
            plot.YAxis[i].Range.Max = ConstrainLog(plot.YAxis[i].Range.Max);
    }
Evan Pezent's avatar
Evan Pezent 已提交
810

811
812
813
814
815
816
    if (plot.XAxis.Range.Max <= plot.XAxis.Range.Min)
        plot.XAxis.Range.Max = plot.XAxis.Range.Min + FLT_EPSILON;
    for (int i = 0; i < MAX_Y_AXES; i++) {
        if (plot.YAxis[i].Range.Max <= plot.YAxis[i].Range.Min)
            plot.YAxis[i].Range.Max = plot.YAxis[i].Range.Min + FLT_EPSILON;
    }
Evan Pezent's avatar
Evan Pezent 已提交
817
818
819
820
821
822
823

    // adaptive divisions
    if (HasFlag(plot.XAxis.Flags, ImAxisFlags_Adaptive)) {
        plot.XAxis.Divisions = (int)IM_ROUND(0.003 * gp.BB_Canvas.GetWidth());
        if (plot.XAxis.Divisions < 2)
            plot.XAxis.Divisions = 2; 
    }
824
825
826
827
828
829
    for (int i = 0; i < MAX_Y_AXES; i++) {
        if (HasFlag(plot.YAxis[i].Flags, ImAxisFlags_Adaptive)) {
            plot.YAxis[i].Divisions = (int)IM_ROUND(0.003 * gp.BB_Canvas.GetHeight());
            if (plot.YAxis[i].Divisions < 2)
                plot.YAxis[i].Divisions = 2;
        }
Evan Pezent's avatar
Evan Pezent 已提交
830
831
832
833
834
835
836
837
    }

    // COLORS -----------------------------------------------------------------

    gp.Col_Frame  = gp.Style.Colors[ImPlotCol_FrameBg].w     == -1 ? GetColorU32(ImGuiCol_FrameBg)    : GetColorU32(gp.Style.Colors[ImPlotCol_FrameBg]);
    gp.Col_Bg     = gp.Style.Colors[ImPlotCol_PlotBg].w      == -1 ? GetColorU32(ImGuiCol_WindowBg)   : GetColorU32(gp.Style.Colors[ImPlotCol_PlotBg]);
    gp.Col_Border = gp.Style.Colors[ImPlotCol_PlotBorder].w  == -1 ? GetColorU32(ImGuiCol_Text, 0.5f) : GetColorU32(gp.Style.Colors[ImPlotCol_PlotBorder]);

838
839
840
841
    UpdateAxisColor(ImPlotCol_XAxis, &gp.Col_X);
    UpdateAxisColor(ImPlotCol_YAxis, &gp.Col_Y[0]);
    UpdateAxisColor(ImPlotCol_YAxis2, &gp.Col_Y[1]);
    UpdateAxisColor(ImPlotCol_YAxis3, &gp.Col_Y[2]);
Evan Pezent's avatar
Evan Pezent 已提交
842
843
844
845
846

    gp.Col_Txt    = GetColorU32(ImGuiCol_Text);
    gp.Col_TxtDis = GetColorU32(ImGuiCol_TextDisabled);
    gp.Col_SlctBg = GetColorU32(gp.Style.Colors[ImPlotCol_Selection] * ImVec4(1,1,1,0.25f));
    gp.Col_SlctBd = GetColorU32(gp.Style.Colors[ImPlotCol_Selection]);
847
848
    gp.Col_QryBg =  GetColorU32(gp.Style.Colors[ImPlotCol_Query] * ImVec4(1,1,1,0.25f));
    gp.Col_QryBd =  GetColorU32(gp.Style.Colors[ImPlotCol_Query]);
Evan Pezent's avatar
Evan Pezent 已提交
849

850
851
    gp.Col_QryX =  GetColorU32(gp.Style.Colors[ImPlotCol_QueryX]);

Evan Pezent's avatar
Evan Pezent 已提交
852
853
854
855
856
857
858
859
860
    // BB AND HOVER -----------------------------------------------------------

    // frame
    const ImVec2 frame_size = CalcItemSize(size, 100, 100);
    gp.BB_Frame = ImRect(Window->DC.CursorPos, Window->DC.CursorPos + frame_size);
    ItemSize(gp.BB_Frame);
    if (!ItemAdd(gp.BB_Frame, 0, &gp.BB_Frame)) {
        gp.NextPlotData = ImNextPlotData();
        gp.CurrentPlot = NULL;
861
862
        if (!HasFlag(plot.Flags, ImPlotFlags_NoChild))
            ImGui::EndChild();
Evan Pezent's avatar
Evan Pezent 已提交
863
864
865
866
867
868
869
870
        return false;
    }
    gp.Hov_Frame = ItemHoverable(gp.BB_Frame, ID);
    RenderFrame(gp.BB_Frame.Min, gp.BB_Frame.Max, gp.Col_Frame, true, Style.FrameRounding);

    // canvas bb
    gp.BB_Canvas = ImRect(gp.BB_Frame.Min + Style.WindowPadding, gp.BB_Frame.Max - Style.WindowPadding);     

871
872
    gp.RenderX = (HasFlag(plot.XAxis.Flags, ImAxisFlags_GridLines) ||
                    HasFlag(plot.XAxis.Flags, ImAxisFlags_TickMarks) ||
Evan Pezent's avatar
Evan Pezent 已提交
873
                    HasFlag(plot.XAxis.Flags, ImAxisFlags_TickLabels)) &&  plot.XAxis.Divisions > 1;
874
875
876
877
878
879
880
    for (int i = 0; i < MAX_Y_AXES; i++) {
        gp.RenderY[i] =
                y[i].present &&
                (HasFlag(plot.YAxis[i].Flags, ImAxisFlags_GridLines) || 
                 HasFlag(plot.YAxis[i].Flags, ImAxisFlags_TickMarks) || 
                 HasFlag(plot.YAxis[i].Flags, ImAxisFlags_TickLabels)) &&  plot.YAxis[i].Divisions > 1;
    }
Evan Pezent's avatar
Evan Pezent 已提交
881
882
883

    // get ticks
    if (gp.RenderX)
884
885
886
887
888
889
        GetTicks(plot.XAxis.Range, plot.XAxis.Divisions, plot.XAxis.Subdivisions, HasFlag(plot.XAxis.Flags, ImAxisFlags_LogScale), gp.XTicks);
    for (int i = 0; i < MAX_Y_AXES; i++) {
        if (gp.RenderY[i]) {
            GetTicks(plot.YAxis[i].Range, plot.YAxis[i].Divisions, plot.YAxis[i].Subdivisions, HasFlag(plot.YAxis[i].Flags, ImAxisFlags_LogScale), gp.YTicks[i]);
        }
    }
Evan Pezent's avatar
Evan Pezent 已提交
890
891
892
893
894

    // label ticks
    if (HasFlag(plot.XAxis.Flags, ImAxisFlags_TickLabels))
        LabelTicks(gp.XTicks, HasFlag(plot.XAxis.Flags, ImAxisFlags_Scientific), gp.XTickLabels);

895
896
897
898
899
900
901
902
    float max_label_width[MAX_Y_AXES] = {};
    for (int i = 0; i < MAX_Y_AXES; i++) {
        if (y[i].present && HasFlag(plot.YAxis[i].Flags, ImAxisFlags_TickLabels)) {
            LabelTicks(gp.YTicks[i], HasFlag(plot.YAxis[i].Flags, ImAxisFlags_Scientific), gp.YTickLabels[i]);
            for (ImTick &yt : gp.YTicks[i]) {
                max_label_width[i] = yt.Size.x > max_label_width[i] ? yt.Size.x : max_label_width[i];
            }
        }
Evan Pezent's avatar
Evan Pezent 已提交
903
904
905
906
907
908
909
910
    }

    // grid bb
    const ImVec2 title_size = CalcTextSize(title, NULL, true);
    const float txt_off     = 5;
    const float txt_height  = GetTextLineHeight();
    const float pad_top     = title_size.x > 0.0f ? txt_height + txt_off : 0;
    const float pad_bot     = (HasFlag(plot.XAxis.Flags, ImAxisFlags_TickLabels) ? txt_height + txt_off : 0) + (x_label ? txt_height + txt_off : 0);
911
912
913
914
    YPadCalculator y_axis_pad(y, max_label_width, txt_off);
    const float pad_left    = y_axis_pad(0) + (y_label ? txt_height + txt_off : 0);
    const float pad_right   = y_axis_pad(1) + y_axis_pad(2);
    gp.BB_Grid            = ImRect(gp.BB_Canvas.Min + ImVec2(pad_left, pad_top), gp.BB_Canvas.Max - ImVec2(pad_right, pad_bot));
Evan Pezent's avatar
Evan Pezent 已提交
915
916
917
    gp.Hov_Grid           = gp.BB_Grid.Contains(IO.MousePos);

    // axis region bbs
918
    const ImRect xAxisRegion_bb(gp.BB_Grid.Min + ImVec2(10, 0), ImVec2(gp.BB_Grid.Max.x, gp.BB_Frame.Max.y) - ImVec2(10, 0));
Evan Pezent's avatar
Evan Pezent 已提交
919
    const bool   hov_x_axis_region = xAxisRegion_bb.Contains(IO.MousePos);
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949

    // The left labels are referenced to the left of the bounding box.
    gp.AxisLabelReference[0] = gp.BB_Grid.Min.x;
    // If Y axis 1 is present, its labels will be referenced to the
    // right of the bounding box.
    gp.AxisLabelReference[1] = gp.BB_Grid.Max.x;
    // The third axis may be either referenced to the right of the
    // bounding box, or 6 pixels further past the end of the 2nd axis.
    gp.AxisLabelReference[2] =
            !y[1].present ?
            gp.BB_Grid.Max.x :
            (gp.AxisLabelReference[1] + y_axis_pad(1) + 6);

    ImRect yAxisRegion_bb[MAX_Y_AXES];
    yAxisRegion_bb[0] = ImRect({gp.BB_Frame.Min.x, gp.BB_Grid.Min.y}, {gp.BB_Grid.Min.x + 6, gp.BB_Grid.Max.y - 10});
    // The auxiliary y axes are off to the right of the BB grid.
    yAxisRegion_bb[1] = ImRect({gp.BB_Grid.Max.x - 6, gp.BB_Grid.Min.y},
                               gp.BB_Grid.Max + ImVec2(y_axis_pad(1), 0));
    yAxisRegion_bb[2] = ImRect({gp.AxisLabelReference[2] - 6, gp.BB_Grid.Min.y},
                               yAxisRegion_bb[1].Max + ImVec2(y_axis_pad(2), 0));

    ImRect centralRegion({gp.BB_Grid.Min.x + 6, gp.BB_Grid.Min.y},
                         {gp.BB_Grid.Max.x - 6, gp.BB_Grid.Max.y});
    
    const bool hov_y_axis_region[MAX_Y_AXES] = {
        y[0].present && (yAxisRegion_bb[0].Contains(IO.MousePos) || centralRegion.Contains(IO.MousePos)),
        y[1].present && (yAxisRegion_bb[1].Contains(IO.MousePos) || centralRegion.Contains(IO.MousePos)),
        y[2].present && (yAxisRegion_bb[2].Contains(IO.MousePos) || centralRegion.Contains(IO.MousePos)),
    };
    const bool any_hov_y_axis_region = hov_y_axis_region[0] || hov_y_axis_region[1] || hov_y_axis_region[2];
Evan Pezent's avatar
Evan Pezent 已提交
950
951

    // legend hovered from last frame
952
953
954
    const bool hov_legend = HasFlag(plot.Flags, ImPlotFlags_Legend) ? gp.Hov_Frame && plot.BB_Legend.Contains(IO.MousePos) : false;   

    bool hov_query = false;
955
956
957
958
959
960
    if (gp.Hov_Frame && gp.Hov_Grid && plot.Queried && !plot.Querying) {
        ImRect bb_query = plot.QueryRect;

        bb_query.Min += gp.BB_Grid.Min;
        bb_query.Max += gp.BB_Grid.Min;

961
962
963
964
965
966
967
968
969
        hov_query = bb_query.Contains(IO.MousePos);
    }

    // QUERY DRAG -------------------------------------------------------------
    if (plot.DraggingQuery && (IO.MouseReleased[0] || !IO.MouseDown[0])) {
        plot.DraggingQuery = false;
    }
    if (plot.DraggingQuery) {        
        SetMouseCursor(ImGuiMouseCursor_ResizeAll);
970
971
        plot.QueryRect.Min += IO.MouseDelta;
        plot.QueryRect.Max += IO.MouseDelta;
972
    }
973
    if (gp.Hov_Frame && gp.Hov_Grid && hov_query && !plot.DraggingQuery && !plot.Selecting && !hov_legend) {
974
        SetMouseCursor(ImGuiMouseCursor_ResizeAll);
975
976
        const bool any_y_dragging = plot.YAxis[0].Dragging || plot.YAxis[1].Dragging || plot.YAxis[2].Dragging;
        if (IO.MouseDown[0] && !plot.XAxis.Dragging && !any_y_dragging) {
977
978
979
            plot.DraggingQuery = true;
        }        
    }    
Evan Pezent's avatar
Evan Pezent 已提交
980

981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
    //QUERY X
    bool hov_queryX[2];
    for (size_t i = 0; i < 2; i++)
    {
        hov_queryX[i] = plot.QueryRectX[i].Contains(IO.MousePos);
        //x limits
        bool xAtMax = false;
        if (plot.QueryRectX[i].Min.x <= gp.BB_Grid.Min.x) {
            plot.QueryRectX[i].Min.x = gp.BB_Grid.Min.x;
        }
        if (plot.QueryRectX[i].Max.x >= (gp.BB_Grid.Max.x)) {
            plot.QueryRectX[i].Max.x = gp.BB_Grid.Max.x;
            xAtMax = true;
        }
        //min cursor "line" width
        if ((plot.QueryRectX[i].Max.x - plot.QueryRectX[i].Min.x) < 3) {
            if (xAtMax)
                plot.QueryRectX[i].Min.x = plot.QueryRectX[i].Max.x - 3;
            else
                plot.QueryRectX[i].Max.x = plot.QueryRectX[i].Min.x + 3;
为了加快浏览速度,不会显示所有历史记录。 查看完整的 blame