implot.cpp 140.6 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
// ImPlot v0.7 WIP
24
25
26
27
28
29
30
31
32
33

/*

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.

34
- 2020/08/28 (0.5) - ImPlotMarker_ can no longer be combined with bitwise OR, |. This features caused unecessary slow-down, and almost no one used it.
35
- 2020/08/25 (0.5) - ImPlotAxisFlags_Scientific was removed. Logarithmic axes automatically uses scientific notation.
36
- 2020/08/17 (0.5) - PlotText was changed so that text is centered horizontally and vertically about the desired point.
37
- 2020/08/16 (0.5) - An ImPlotContext must be explicitly created and destroyed now with `CreateContext` and `DestroyContext`. Previously, the context was statically initialized in this source file.
38
- 2020/06/13 (0.4) - The flags `ImPlotAxisFlag_Adaptive` and `ImPlotFlags_Cull` were removed. Both are now done internally by default.
39
- 2020/06/03 (0.3) - The signature and behavior of PlotPieChart was changed so that data with sum less than 1 can optionally be normalized. The label format can now be specified as well.
Evan Pezent's avatar
Evan Pezent 已提交
40
- 2020/06/01 (0.3) - SetPalette was changed to `SetColormap` for consistency with other plotting libraries. `RestorePalette` was removed. Use `SetColormap(ImPlotColormap_Default)`.
41
- 2020/05/31 (0.3) - Plot functions taking custom ImVec2* getters were removed. Use the ImPlotPoint* getter versions instead.
42
- 2020/05/29 (0.3) - The signature of ImPlotLimits::Contains was changed to take two doubles instead of ImVec2
43
- 2020/05/16 (0.2) - All plotting functions were reverted to being prefixed with "Plot" to maintain a consistent VerbNoun style. `Plot` was split into `PlotLine`
44
45
                     and `PlotScatter` (however, `PlotLine` can still be used to plot scatter points as `Plot` did before.). `Bar` is not `PlotBars`, to indicate
                     that multiple bars will be plotted.
46
47
- 2020/05/13 (0.2) - `ImMarker` was change to `ImPlotMarker` and `ImAxisFlags` was changed to `ImPlotAxisFlags`.
- 2020/05/11 (0.2) - `ImPlotFlags_Selection` was changed to `ImPlotFlags_BoxSelect`
ozlb's avatar
ozlb 已提交
48
- 2020/05/11 (0.2) - The namespace ImGui:: was replaced with ImPlot::. As a result, the following additional changes were made:
49
                     - Functions that were prefixed or decorated with the word "Plot" have been truncated. E.g., `ImGui::PlotBars` is now just `ImPlot::Bar`.
ozlb's avatar
ozlb 已提交
50
                       It should be fairly obvious what was what.
Evan Pezent's avatar
Evan Pezent 已提交
51
52
                     - Some functions have been given names that would have otherwise collided with the ImGui namespace. This has been done to maintain a consistent
                       style with ImGui. E.g., 'ImGui::PushPlotStyleVar` is now 'ImPlot::PushStyleVar'.
53
54
55
- 2020/05/10 (0.2) - The following function/struct names were changes:
                    - ImPlotRange       -> ImPlotLimits
                    - GetPlotRange()    -> GetPlotLimits()
Evan Pezent's avatar
Evan Pezent 已提交
56
                    - SetNextPlotRange  -> SetNextPlotLimits
57
58
59
60
61
62
                    - 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.

*/

63
#include "implot.h"
64
65
#include "implot_internal.h"

66
67
68
#ifdef _MSC_VER
#define sprintf sprintf_s
#endif
Evan Pezent's avatar
Evan Pezent 已提交
69

70
71
// Global plot context
ImPlotContext* GImPlot = NULL;
72

73
74
75
//-----------------------------------------------------------------------------
// Struct Implementations
//-----------------------------------------------------------------------------
Evan Pezent's avatar
Evan Pezent 已提交
76

77
78
79
80
ImPlotRange::ImPlotRange() {
    Min = NAN;
    Max = NAN;
}
81

epezent's avatar
epezent 已提交
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
ImPlotInputMap::ImPlotInputMap() {
    PanButton             = ImGuiMouseButton_Left;
    PanMod                = ImGuiKeyModFlags_None;
    FitButton             = ImGuiMouseButton_Left;
    ContextMenuButton     = ImGuiMouseButton_Right;
    BoxSelectButton       = ImGuiMouseButton_Right;
    BoxSelectMod          = ImGuiKeyModFlags_None;
    BoxSelectCancelButton = ImGuiMouseButton_Left;
    QueryButton           = ImGuiMouseButton_Middle;
    QueryMod              = ImGuiKeyModFlags_None;
    QueryToggleMod        = ImGuiKeyModFlags_Ctrl;
    HorizontalMod         = ImGuiKeyModFlags_Alt;
    VerticalMod           = ImGuiKeyModFlags_Shift;
}

Evan Pezent's avatar
Evan Pezent 已提交
97
ImPlotStyle::ImPlotStyle() {
98
99
100
101
102
103
104
105

    LineWeight       = 1;
    Marker           = ImPlotMarker_None;
    MarkerSize       = 4;
    MarkerWeight     = 1;
    FillAlpha        = 1;
    ErrorBarSize     = 5;
    ErrorBarWeight   = 1.5f;
ozlb's avatar
ozlb 已提交
106
    DigitalBitHeight = 8;
107
    DigitalBitGap    = 4;
108
    AntiAliasedLines = false;
109

epezent's avatar
epezent 已提交
110
111
112
113
114
115
116
117
    PlotBorderSize   = 1;
    MinorAlpha       = 0.25f;
    MajorTickLen     = ImVec2(10,10);
    MinorTickLen     = ImVec2(5,5);
    MajorTickSize    = ImVec2(1,1);
    MinorTickSize    = ImVec2(1,1);
    MajorGridSize    = ImVec2(1,1);
    MinorGridSize    = ImVec2(1,1);
118
    PlotPadding      = ImVec2(8,8);
epezent's avatar
epezent 已提交
119
120
121
122
    LabelPadding     = ImVec2(5,5);
    LegendPadding    = ImVec2(10,10);
    InfoPadding      = ImVec2(10,10);
    PlotMinSize      = ImVec2(300,225);
Evan Pezent's avatar
Evan Pezent 已提交
123

epezent's avatar
epezent 已提交
124
    ImPlot::StyleColorsAuto(this);
125
126
}

epezent's avatar
epezent 已提交
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
namespace ImPlot {

const char* GetStyleColorName(ImPlotCol col) {
    static const char* col_names[] = {
        "Line",
        "Fill",
        "MarkerOutline",
        "MarkerFill",
        "ErrorBar",
        "FrameBg",
        "PlotBg",
        "PlotBorder",
        "LegendBg",
        "LegendBorder",
        "LegendText",
        "TitleText",
        "InlayText",
        "XAxis",
        "XAxisGrid",
        "YAxis",
        "YAxisGrid",
        "YAxis2",
        "YAxisGrid2",
        "YAxis3",
        "YAxisGrid3",
        "Selection",
        "Query",
        "Crosshairs"
    };
    return col_names[col];
}

159
160
161
162
163
const char* GetMarkerName(ImPlotMarker marker) {
    switch (marker) {
        case ImPlotMarker_None:     return "None";
        case ImPlotMarker_Circle:   return "Circle";
        case ImPlotMarker_Square:   return "Square";
164
165
166
167
168
169
170
171
        case ImPlotMarker_Diamond:  return "Diamond";
        case ImPlotMarker_Up:       return "Up";
        case ImPlotMarker_Down:     return "Down";
        case ImPlotMarker_Left:     return "Left";
        case ImPlotMarker_Right:    return "Right";
        case ImPlotMarker_Cross:    return "Cross";
        case ImPlotMarker_Plus:     return "Plus";
        case ImPlotMarker_Asterisk: return "Asterisk";
172
173
174
175
        default:                    return "";
    }
}

epezent's avatar
epezent 已提交
176
177
178
179
180
181
182
183
184
185
ImVec4 GetAutoColor(ImPlotCol idx) {
    ImVec4 col(0,0,0,1);
    switch(idx) {
        case ImPlotCol_Line:          return col; // these are plot dependent!
        case ImPlotCol_Fill:          return col; // these are plot dependent!
        case ImPlotCol_MarkerOutline: return col; // these are plot dependent!
        case ImPlotCol_MarkerFill:    return col; // these are plot dependent!
        case ImPlotCol_ErrorBar:      return ImGui::GetStyleColorVec4(ImGuiCol_Text);
        case ImPlotCol_FrameBg:       return ImGui::GetStyleColorVec4(ImGuiCol_FrameBg);
        case ImPlotCol_PlotBg:        return ImGui::GetStyleColorVec4(ImGuiCol_WindowBg);
epezent's avatar
epezent 已提交
186
        case ImPlotCol_PlotBorder:    return ImGui::GetStyleColorVec4(ImGuiCol_Border);
epezent's avatar
epezent 已提交
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
        case ImPlotCol_LegendBg:      return ImGui::GetStyleColorVec4(ImGuiCol_PopupBg);
        case ImPlotCol_LegendBorder:  return GetStyleColorVec4(ImPlotCol_PlotBorder);
        case ImPlotCol_LegendText:    return GetStyleColorVec4(ImPlotCol_InlayText);
        case ImPlotCol_TitleText:     return ImGui::GetStyleColorVec4(ImGuiCol_Text);
        case ImPlotCol_InlayText:     return ImGui::GetStyleColorVec4(ImGuiCol_Text);
        case ImPlotCol_XAxis:         return ImGui::GetStyleColorVec4(ImGuiCol_Text);
        case ImPlotCol_XAxisGrid:     return GetStyleColorVec4(ImPlotCol_XAxis) * ImVec4(1,1,1,0.25f);
        case ImPlotCol_YAxis:         return ImGui::GetStyleColorVec4(ImGuiCol_Text);
        case ImPlotCol_YAxisGrid:     return GetStyleColorVec4(ImPlotCol_YAxis) * ImVec4(1,1,1,0.25f);
        case ImPlotCol_YAxis2:        return ImGui::GetStyleColorVec4(ImGuiCol_Text);
        case ImPlotCol_YAxisGrid2:    return GetStyleColorVec4(ImPlotCol_YAxis2) * ImVec4(1,1,1,0.25f);
        case ImPlotCol_YAxis3:        return ImGui::GetStyleColorVec4(ImGuiCol_Text);
        case ImPlotCol_YAxisGrid3:    return GetStyleColorVec4(ImPlotCol_YAxis3) * ImVec4(1,1,1,0.25f);
        case ImPlotCol_Selection:     return ImVec4(1,1,0,1);
        case ImPlotCol_Query:         return ImVec4(0,1,0,1);
        case ImPlotCol_Crosshairs:    return GetStyleColorVec4(ImPlotCol_PlotBorder);
        default: return col;
    }
205
206
}

epezent's avatar
epezent 已提交
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
struct ImPlotStyleVarInfo {
    ImGuiDataType   Type;
    ImU32           Count;
    ImU32           Offset;
    void*           GetVarPtr(ImPlotStyle* style) const { return (void*)((unsigned char*)style + Offset); }
};

static const ImPlotStyleVarInfo GPlotStyleVarInfo[] =
{
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImPlotStyle, LineWeight)       }, // ImPlotStyleVar_LineWeight
    { ImGuiDataType_S32,   1, (ImU32)IM_OFFSETOF(ImPlotStyle, Marker)           }, // ImPlotStyleVar_Marker
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImPlotStyle, MarkerSize)       }, // ImPlotStyleVar_MarkerSize
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImPlotStyle, MarkerWeight)     }, // ImPlotStyleVar_MarkerWeight
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImPlotStyle, FillAlpha)        }, // ImPlotStyleVar_FillAlpha
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImPlotStyle, ErrorBarSize)     }, // ImPlotStyleVar_ErrorBarSize
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImPlotStyle, ErrorBarWeight)   }, // ImPlotStyleVar_ErrorBarWeight
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImPlotStyle, DigitalBitHeight) }, // ImPlotStyleVar_DigitalBitHeight
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImPlotStyle, DigitalBitGap)    }, // ImPlotStyleVar_DigitalBitGap

    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImPlotStyle, PlotBorderSize)   }, // ImPlotStyleVar_PlotBorderSize
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImPlotStyle, MinorAlpha)       }, // ImPlotStyleVar_MinorAlpha
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImPlotStyle, MajorTickLen)     }, // ImPlotStyleVar_MajorTickLen
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImPlotStyle, MinorTickLen)     }, // ImPlotStyleVar_MinorTickLen
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImPlotStyle, MajorTickSize)    }, // ImPlotStyleVar_MajorTickSize
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImPlotStyle, MinorTickSize)    }, // ImPlotStyleVar_MinorTickSize
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImPlotStyle, MajorGridSize)    }, // ImPlotStyleVar_MajorGridSize
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImPlotStyle, MinorGridSize)    }, // ImPlotStyleVar_MinorGridSize
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImPlotStyle, PlotPadding)      }, // ImPlotStyleVar_PlotPadding
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImPlotStyle, LabelPadding)     }, // ImPlotStyleVar_LabelPaddine
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImPlotStyle, LegendPadding)    }, // ImPlotStyleVar_LegendPadding
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImPlotStyle, InfoPadding)      }, // ImPlotStyleVar_InfoPadding
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImPlotStyle, PlotMinSize)      }  // ImPlotStyleVar_PlotMinSize
};

static const ImPlotStyleVarInfo* GetPlotStyleVarInfo(ImPlotStyleVar idx) {
    IM_ASSERT(idx >= 0 && idx < ImPlotStyleVar_COUNT);
    IM_ASSERT(IM_ARRAYSIZE(GPlotStyleVarInfo) == ImPlotStyleVar_COUNT);
    return &GPlotStyleVarInfo[idx];
}
Evan Pezent's avatar
Evan Pezent 已提交
246

247
//-----------------------------------------------------------------------------
248
// Generic Helpers
249
//-----------------------------------------------------------------------------
Evan Pezent's avatar
Evan Pezent 已提交
250

251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
void AddTextVertical(ImDrawList *DrawList, ImVec2 pos, ImU32 col, const char *text_begin, const char* text_end) {
    if (!text_end)
        text_end = text_begin + strlen(text_begin);
    ImGuiContext& g = *GImGui;
    ImFont* font = g.Font;
    pos.x = IM_FLOOR(pos.x + font->DisplayOffset.y);
    pos.y = IM_FLOOR(pos.y + font->DisplayOffset.x);
    const char* s = text_begin;
    const int vtx_count = (int)(text_end - s) * 4;
    const int idx_count = (int)(text_end - s) * 6;
    DrawList->PrimReserve(idx_count, vtx_count);
    const float scale = g.FontSize / font->FontSize;
    while (s < text_end) {
        unsigned int c = (unsigned int)*s;
        if (c < 0x80) {
            s += 1;
        }
        else {
            s += ImTextCharFromUtf8(&c, s, text_end);
            if (c == 0) // Malformed UTF-8?
                break;
        }
        const ImFontGlyph * glyph = font->FindGlyph((ImWchar)c);
        if (glyph == NULL)
Evan Pezent's avatar
Evan Pezent 已提交
275
            continue;
276
277
278
279
280
281
        DrawList->PrimQuadUV(pos + ImVec2(glyph->Y0, -glyph->X0) * scale, pos + ImVec2(glyph->Y0, -glyph->X1) * scale,
                             pos + ImVec2(glyph->Y1, -glyph->X1) * scale, pos + ImVec2(glyph->Y1, -glyph->X0) * scale,
                             ImVec2(glyph->U0, glyph->V0), ImVec2(glyph->U1, glyph->V0),
                             ImVec2(glyph->U1, glyph->V1), ImVec2(glyph->U0, glyph->V1),
                             col);
        pos.y -= glyph->AdvanceX * scale;
Evan Pezent's avatar
Evan Pezent 已提交
282
283
284
    }
}

285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
double NiceNum(double x, bool round) {
    double f;  /* fractional part of x */
    double nf; /* nice, rounded fraction */
    int expv = (int)floor(ImLog10(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);
Evan Pezent's avatar
Evan Pezent 已提交
308
309
}

310
//-----------------------------------------------------------------------------
311
// Context Utils
312
313
//-----------------------------------------------------------------------------

314
315
ImPlotContext* CreateContext() {
    ImPlotContext* ctx = IM_NEW(ImPlotContext)();
316
    Initialize(ctx);
317
318
319
320
321
322
323
324
325
326
327
    if (GImPlot == NULL)
        SetCurrentContext(ctx);
    return ctx;
}

void DestroyContext(ImPlotContext* ctx) {
    if (ctx == NULL)
        ctx = GImPlot;
    if (GImPlot == ctx)
        SetCurrentContext(NULL);
    IM_DELETE(ctx);
328
}
329
330
331
332
333
334
335
336

ImPlotContext* GetCurrentContext() {
    return GImPlot;
}

void SetCurrentContext(ImPlotContext* ctx) {
    GImPlot = ctx;
}
Evan Pezent's avatar
Evan Pezent 已提交
337

338
339
void Initialize(ImPlotContext* ctx) {
    Reset(ctx);
340
    ctx->Colormap = GetColormap(ImPlotColormap_Default, &ctx->ColormapSize);
341
342
343
344
345
346
347
}

void Reset(ImPlotContext* ctx) {
    // end child window if it was made
    if (ctx->ChildWindowMade)
        ImGui::EndChild();
    ctx->ChildWindowMade = false;
epezent's avatar
epezent 已提交
348
    // reset the next plot/item data
349
    ctx->NextPlotData = ImPlotNextPlotData();
350
    ctx->NextItemStyle = ImPlotItemStyle();
351
352
353
354
355
356
    // reset items count
    ctx->VisibleItemCount = 0;
    // reset legend items
    ctx->LegendIndices.shrink(0);
    ctx->LegendLabels.Buf.shrink(0);
    // reset ticks/labels
epezent's avatar
epezent 已提交
357
    ctx->XTicks.Reset();
358
    for (int i = 0; i < 3; ++i) {
epezent's avatar
epezent 已提交
359
        ctx->YTicks[i].Reset();
360
    }
epezent's avatar
epezent 已提交
361
362
    // reset extents/fit
    ctx->FitThisFrame = false;
363
364
365
    ctx->FitX = false;
    ctx->ExtentsX.Min = HUGE_VAL;
    ctx->ExtentsX.Max = -HUGE_VAL;
366
    for (int i = 0; i < IMPLOT_Y_AXES; i++) {
367
368
369
370
371
372
373
374
375
        ctx->ExtentsY[i].Min = HUGE_VAL;
        ctx->ExtentsY[i].Max = -HUGE_VAL;
        ctx->FitY[i] = false;
    }
    // reset digital plot items count
    ctx->DigitalPlotItemCnt = 0;
    ctx->DigitalPlotOffset = 0;
    // nullify plot
    ctx->CurrentPlot = NULL;
376
    ctx->CurrentItem = NULL;
377
378
}

379
//-----------------------------------------------------------------------------
380
// Plot Utils
381
382
//-----------------------------------------------------------------------------

383
384
385
386
387
388
389
390
ImPlotState* GetPlot(const char* title) {
    ImGuiWindow*   Window = GImGui->CurrentWindow;
    const ImGuiID  ID     = Window->GetID(title);
    return GImPlot->Plots.GetByKey(ID);
}

ImPlotState* GetCurrentPlot() {
    return GImPlot->CurrentPlot;
391
392
}

epezent's avatar
epezent 已提交
393
394
395
396
void BustPlotCache() {
    GImPlot->Plots.Clear();
}

397
void FitPoint(const ImPlotPoint& p) {
398
    ImPlotContext& gp = *GImPlot;
399
400
401
402
403
    const int y_axis  = gp.CurrentPlot->CurrentYAxis;
    ImPlotRange& ex_x = gp.ExtentsX;
    ImPlotRange& ex_y = gp.ExtentsY[y_axis];
    const bool log_x  = ImHasFlag(gp.CurrentPlot->XAxis.Flags, ImPlotAxisFlags_LogScale);
    const bool log_y  = ImHasFlag(gp.CurrentPlot->YAxis[y_axis].Flags, ImPlotAxisFlags_LogScale);
epezent's avatar
epezent 已提交
404
    if (!ImNanOrInf(p.x) && !(log_x && p.x <= 0)) {
405
406
        ex_x.Min = p.x < ex_x.Min ? p.x : ex_x.Min;
        ex_x.Max = p.x > ex_x.Max ? p.x : ex_x.Max;
407
    }
epezent's avatar
epezent 已提交
408
    if (!ImNanOrInf(p.y) && !(log_y && p.y <= 0)) {
409
410
        ex_y.Min = p.y < ex_y.Min ? p.y : ex_y.Min;
        ex_y.Max = p.y > ex_y.Max ? p.y : ex_y.Max;
411
412
413
414
    }
}

//-----------------------------------------------------------------------------
415
// Coordinate Utils
416
417
//-----------------------------------------------------------------------------

418
void UpdateTransformCache() {
419
    ImPlotContext& gp = *GImPlot;
420
    // get pixels for transforms
421
    for (int i = 0; i < IMPLOT_Y_AXES; i++) {
422
423
424
425
        gp.PixelRange[i] = ImRect(ImHasFlag(gp.CurrentPlot->XAxis.Flags, ImPlotAxisFlags_Invert) ? gp.BB_Plot.Max.x : gp.BB_Plot.Min.x,
                                  ImHasFlag(gp.CurrentPlot->YAxis[i].Flags, ImPlotAxisFlags_Invert) ? gp.BB_Plot.Min.y : gp.BB_Plot.Max.y,
                                  ImHasFlag(gp.CurrentPlot->XAxis.Flags, ImPlotAxisFlags_Invert) ? gp.BB_Plot.Min.x : gp.BB_Plot.Max.x,
                                  ImHasFlag(gp.CurrentPlot->YAxis[i].Flags, ImPlotAxisFlags_Invert) ? gp.BB_Plot.Max.y : gp.BB_Plot.Min.y);
426
427
        gp.My[i] = (gp.PixelRange[i].Max.y - gp.PixelRange[i].Min.y) / gp.CurrentPlot->YAxis[i].Range.Size();
    }
428
    gp.LogDenX = ImLog10(gp.CurrentPlot->XAxis.Range.Max / gp.CurrentPlot->XAxis.Range.Min);
429
430
    for (int i = 0; i < IMPLOT_Y_AXES; i++)
        gp.LogDenY[i] = ImLog10(gp.CurrentPlot->YAxis[i].Range.Max / gp.CurrentPlot->YAxis[i].Range.Min);
431
    gp.Mx = (gp.PixelRange[0].Max.x - gp.PixelRange[0].Min.x) / gp.CurrentPlot->XAxis.Range.Size();
432
}
Evan Pezent's avatar
Evan Pezent 已提交
433

434
ImPlotPoint PixelsToPlot(float x, float y, int y_axis_in) {
435
    ImPlotContext& gp = *GImPlot;
Evan Pezent's avatar
Evan Pezent 已提交
436
    IM_ASSERT_USER_ERROR(gp.CurrentPlot != NULL, "PixelsToPlot() needs to be called between BeginPlot() and EndPlot()!");
437
    const int y_axis = y_axis_in >= 0 ? y_axis_in : gp.CurrentPlot->CurrentYAxis;
Evan Pezent's avatar
Evan Pezent 已提交
438
    ImPlotPoint plt;
439
440
    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;
441
    if (ImHasFlag(gp.CurrentPlot->XAxis.Flags, ImPlotAxisFlags_LogScale)) {
442
443
        double t = (plt.x - gp.CurrentPlot->XAxis.Range.Min) / gp.CurrentPlot->XAxis.Range.Size();
        plt.x = ImPow(10, t * gp.LogDenX) * gp.CurrentPlot->XAxis.Range.Min;
444
    }
445
    if (ImHasFlag(gp.CurrentPlot->YAxis[y_axis].Flags, ImPlotAxisFlags_LogScale)) {
446
447
        double t = (plt.y - gp.CurrentPlot->YAxis[y_axis].Range.Min) / gp.CurrentPlot->YAxis[y_axis].Range.Size();
        plt.y = ImPow(10, t * gp.LogDenY[y_axis]) * gp.CurrentPlot->YAxis[y_axis].Range.Min;
448
449
450
451
    }
    return plt;
}

Evan Pezent's avatar
Evan Pezent 已提交
452
ImPlotPoint PixelsToPlot(const ImVec2& pix, int y_axis) {
Evan Pezent's avatar
Evan Pezent 已提交
453
454
455
456
    return PixelsToPlot(pix.x, pix.y, y_axis);
}

// This function is convenient but should not be used to process a high volume of points. Use the Transformer structs below instead.
457
ImVec2 PlotToPixels(double x, double y, int y_axis_in) {
458
    ImPlotContext& gp = *GImPlot;
Evan Pezent's avatar
Evan Pezent 已提交
459
    IM_ASSERT_USER_ERROR(gp.CurrentPlot != NULL, "PlotToPixels() needs to be called between BeginPlot() and EndPlot()!");
460
    const int y_axis = y_axis_in >= 0 ? y_axis_in : gp.CurrentPlot->CurrentYAxis;
461
    ImVec2 pix;
462
    if (ImHasFlag(gp.CurrentPlot->XAxis.Flags, ImPlotAxisFlags_LogScale)) {
463
        double t = ImLog10(x / gp.CurrentPlot->XAxis.Range.Min) / gp.LogDenX;
Evan Pezent's avatar
Evan Pezent 已提交
464
        x       = ImLerp(gp.CurrentPlot->XAxis.Range.Min, gp.CurrentPlot->XAxis.Range.Max, (float)t);
Evan Pezent's avatar
Evan Pezent 已提交
465
    }
466
    if (ImHasFlag(gp.CurrentPlot->YAxis[y_axis].Flags, ImPlotAxisFlags_LogScale)) {
467
        double t = ImLog10(y / gp.CurrentPlot->YAxis[y_axis].Range.Min) / gp.LogDenY[y_axis];
Evan Pezent's avatar
Evan Pezent 已提交
468
        y       = ImLerp(gp.CurrentPlot->YAxis[y_axis].Range.Min, gp.CurrentPlot->YAxis[y_axis].Range.Max, (float)t);
469
    }
Evan Pezent's avatar
Evan Pezent 已提交
470
471
    pix.x = (float)(gp.PixelRange[y_axis].Min.x + gp.Mx * (x - gp.CurrentPlot->XAxis.Range.Min));
    pix.y = (float)(gp.PixelRange[y_axis].Min.y + gp.My[y_axis] * (y - gp.CurrentPlot->YAxis[y_axis].Range.Min));
472
473
474
    return pix;
}

Evan Pezent's avatar
Evan Pezent 已提交
475
// This function is convenient but should not be used to process a high volume of points. Use the Transformer structs below instead.
Evan Pezent's avatar
Evan Pezent 已提交
476
ImVec2 PlotToPixels(const ImPlotPoint& plt, int y_axis) {
477
    return PlotToPixels(plt.x, plt.y, y_axis);
478
479
}

480
481
482
483
484
485
486
487
488
//-----------------------------------------------------------------------------
// Legend Utils
//-----------------------------------------------------------------------------

int GetLegendCount() {
    ImPlotContext& gp = *GImPlot;
    return gp.LegendIndices.size();
}

489
const char* GetLegendLabel(int i) {
490
    ImPlotContext& gp = *GImPlot;
491
492
493
494
495
496
    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 已提交
497
// Tick Utils
498
//-----------------------------------------------------------------------------
Evan Pezent's avatar
Evan Pezent 已提交
499

epezent's avatar
epezent 已提交
500
501
502
503
void LabelTickDefault(ImPlotTick& tick, ImGuiTextBuffer& buffer) {
    char temp[32];
    if (tick.ShowLabel) {
        tick.BufferOffset = buffer.size();
504
        snprintf(temp, 32, "%.10g", tick.PlotPos);
epezent's avatar
epezent 已提交
505
506
507
508
509
510
511
512
513
        buffer.append(temp, temp + strlen(temp) + 1);
        tick.LabelSize = ImGui::CalcTextSize(buffer.Buf.Data + tick.BufferOffset);
    }
}

void LabelTickScientific(ImPlotTick& tick, ImGuiTextBuffer& buffer) {
    char temp[32];
    if (tick.ShowLabel) {
        tick.BufferOffset = buffer.size();
514
515
516
517
518
519
        snprintf(temp, 32, "%.0E", tick.PlotPos);
        buffer.append(temp, temp + strlen(temp) + 1);
        tick.LabelSize = ImGui::CalcTextSize(buffer.Buf.Data + tick.BufferOffset);
    }
}

epezent's avatar
epezent 已提交
520
void AddTicksDefault(const ImPlotRange& range, int nMajor, int nMinor, ImPlotTickCollection& ticks) {
521
    const double nice_range = NiceNum(range.Size() * 0.99, false);
epezent's avatar
epezent 已提交
522
    const double interval   = NiceNum(nice_range / (nMajor - 1), true);
523
524
525
    const double graphmin   = floor(range.Min / interval) * interval;
    const double graphmax   = ceil(range.Max / interval) * interval;
    for (double major = graphmin; major < graphmax + 0.5 * interval; major += interval) {
526
        if (range.Contains(major))
epezent's avatar
epezent 已提交
527
            ticks.AddTick(major, true, true, LabelTickDefault);
528
529
        for (int i = 1; i < nMinor; ++i) {
            double minor = major + i * interval / nMinor;
530
531
            if (range.Contains(minor))
                ticks.AddTick(minor, false, true, LabelTickDefault);
532
        }
epezent's avatar
epezent 已提交
533
    }
534
535
}

epezent's avatar
epezent 已提交
536
void AddTicksLogarithmic(const ImPlotRange& range, int nMajor, ImPlotTickCollection& ticks) {
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
    if (range.Min <= 0 || range.Max <= 0)
        return;
    double log_min = ImLog10(range.Min);
    double log_max = ImLog10(range.Max);
    int exp_step  = ImMax(1,(int)(log_max - log_min) / nMajor);
    int exp_min   = (int)log_min;
    int exp_max   = (int)log_max;
    if (exp_step != 1) {
        while(exp_step % 3 != 0)       exp_step++; // make step size multiple of three
        while(exp_min % exp_step != 0) exp_min--;  // decrease exp_min until exp_min + N * exp_step will be 0
    }
    for (int e = exp_min - exp_step; e < (exp_max + exp_step); e += exp_step) {
        double major1 = ImPow(10, (double)(e));
        double major2 = ImPow(10, (double)(e + 1));
        double interval = (major2 - major1) / 9;
552
553
        if (major1 >= (range.Min - DBL_EPSILON) && major1 <= (range.Max + DBL_EPSILON))
            ticks.AddTick(major1, true, true, LabelTickScientific);
554
555
556
557
558
        for (int j = 0; j < exp_step; ++j) {
            major1 = ImPow(10, (double)(e+j));
            major2 = ImPow(10, (double)(e+j+1));
            interval = (major2 - major1) / 9;
            for (int i = 1; i < (9 + (int)(j < (exp_step - 1))); ++i) {
Evan Pezent's avatar
Evan Pezent 已提交
559
                double minor = major1 + i * interval;
560
561
562
                if (minor >= (range.Min - DBL_EPSILON) && minor <= (range.Max + DBL_EPSILON))
                    ticks.AddTick(minor, false, false, LabelTickScientific);

epezent's avatar
epezent 已提交
563
            }
Evan Pezent's avatar
Evan Pezent 已提交
564
565
566
567
        }
    }
}

epezent's avatar
epezent 已提交
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
void AddTicksCustom(const double* values, const char** labels, int n, ImPlotTickCollection& ticks) {
    for (int i = 0; i < n; ++i) {
        ImPlotTick tick(values[i], false, true);
        if (labels != NULL) {
            tick.BufferOffset = ticks.Labels.size();
            ticks.Labels.append(labels[i], labels[i] + strlen(labels[i]) + 1);
            tick.LabelSize = ImGui::CalcTextSize(labels[i]);
        }
        else {
            LabelTickDefault(tick, ticks.Labels);
        }
        ticks.AddTick(tick);
    }
}

//-----------------------------------------------------------------------------
// Time Ticks and Utils
//-----------------------------------------------------------------------------

// this may not be thread safe?
static const double TimeUnitSpans[ImPlotTimeUnit_COUNT] = {
    0.000001, 
    0.001, 
    1, 
    60, 
    3600, 
    86400, 
    2629800, 
    31557600
};

inline ImPlotTimeUnit GetUnitForRange(double range) {
    static double cutoffs[ImPlotTimeUnit_COUNT] = {0.001, 1, 60, 3600, 86400, 2629800, 31557600, IMPLOT_MAX_TIME};
    for (int i = 0; i < ImPlotTimeUnit_COUNT; ++i) {
        if (range <= cutoffs[i])
            return (ImPlotTimeUnit)i;
    }
    return ImPlotTimeUnit_Yr;
}

608
609
610
611
612
613
614
615
616
617
618
619
inline int LowerBoundStep(int max_divs, const int* divs, const int* step, int size) {
    if (max_divs < divs[0])
        return 0;
    for (int i = 1; i < size; ++i) {
        if (max_divs < divs[i])
            return step[i-1];
    }
    return step[size-1];
}

inline int GetTimeStep(int max_divs, ImPlotTimeUnit unit) {
    if (unit == ImPlotTimeUnit_Ms || unit == ImPlotTimeUnit_Us) {
epezent's avatar
epezent 已提交
620
621
622
        static const int step[] = {500,250,200,100,50,25,20,10,5,2,1};
        static const int divs[] = {2,4,5,10,20,40,50,100,200,500,1000};
        return LowerBoundStep(max_divs, divs, step, 11);
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
    }
    if (unit == ImPlotTimeUnit_S || unit == ImPlotTimeUnit_Min) {
        static const int step[] = {30,15,10,5,1};
        static const int divs[] = {2,4,6,12,60};
        return LowerBoundStep(max_divs, divs, step, 5);
    }
    else if (unit == ImPlotTimeUnit_Hr) {
        static const int step[] = {12,6,3,2,1};
        static const int divs[] = {2,4,8,12,24};
        return LowerBoundStep(max_divs, divs, step, 5);
    }
    else if (unit == ImPlotTimeUnit_Day) {
        static const int step[] = {14,7,2,1};
        static const int divs[] = {2,4,14,28};
        return LowerBoundStep(max_divs, divs, step, 4);
    }
    else if (unit == ImPlotTimeUnit_Mo) {
        static const int step[] = {6,3,2,1};
        static const int divs[] = {2,4,6,12};
        return LowerBoundStep(max_divs, divs, step, 4);
    }
    return 0;
}

epezent's avatar
epezent 已提交
647
648
649
650
651
652
653
654
655
656
657
658
659
inline time_t MakeGmTime(const struct tm *ptm) {
    time_t secs = 0;
    int year = ptm->tm_year + 1900;
    for (int y = 1970; y < year; ++y) 
        secs += (IsLeapYear(y)? 366: 365) * 86400;    
    for (int m = 0; m < ptm->tm_mon; ++m) 
        secs += GetDaysInMonth(year, m) * 86400;    
    secs += (ptm->tm_mday - 1) * 86400;
    secs += ptm->tm_hour       * 3600;
    secs += ptm->tm_min        * 60;
    secs += ptm->tm_sec;
    return secs;
}
660

epezent's avatar
epezent 已提交
661
662
663
664
665
666
667
668
669
670
671
672
inline tm* GetGmTime(const time_t* time, tm* tm)
{
#ifdef _WIN32
  if (gmtime_s(tm, time) == 0)
    return tm;
  else
    return NULL;
#else
  return gmtime_r(time, tm);
#endif
}

epezent's avatar
epezent 已提交
673
674
ImPlotTime AddTime(const ImPlotTime& t, ImPlotTimeUnit unit, int count) {
    ImPlotTime t_out = t;
epezent's avatar
epezent 已提交
675
    switch(unit) {
epezent's avatar
epezent 已提交
676
677
678
679
680
681
        case ImPlotTimeUnit_Us:  return ImPlotTime(t.S, t.Us + count);
        case ImPlotTimeUnit_Ms:  return ImPlotTime(t.S, t.Us + count * 1000);
        case ImPlotTimeUnit_S:   t_out.S  += count;         break;
        case ImPlotTimeUnit_Min: t_out.S  += count * 60;    break;
        case ImPlotTimeUnit_Hr:  t_out.S  += count * 3600;  break;
        case ImPlotTimeUnit_Day: t_out.S  += count * 86400; break;
epezent's avatar
epezent 已提交
682
683
        case ImPlotTimeUnit_Yr:  count *= 12; // fall-through
        case ImPlotTimeUnit_Mo:  for (int i = 0; i < count; ++i) {
epezent's avatar
epezent 已提交
684
                                     GetGmTime(&t.S, &GImPlot->Tm);
epezent's avatar
epezent 已提交
685
                                     int days = GetDaysInMonth(GImPlot->Tm.tm_year, GImPlot->Tm.tm_mon);
epezent's avatar
epezent 已提交
686
                                     t_out = AddTime(t_out, ImPlotTimeUnit_Day, days);
epezent's avatar
epezent 已提交
687
                                 }
epezent's avatar
epezent 已提交
688
689
                                 break;
        default:                 break;
epezent's avatar
epezent 已提交
690
    }
epezent's avatar
epezent 已提交
691
    return t_out;
epezent's avatar
epezent 已提交
692
693
}

epezent's avatar
epezent 已提交
694
695
ImPlotTime FloorTime(const ImPlotTime& t, ImPlotTimeUnit unit) {
    GetGmTime(&t.S, &GImPlot->Tm);
epezent's avatar
epezent 已提交
696
697
    GImPlot->Tm.tm_isdst = -1;
    switch (unit) {
epezent's avatar
epezent 已提交
698
699
700
        case ImPlotTimeUnit_S:   return ImPlotTime(t.S, 0);
        case ImPlotTimeUnit_Ms:  return ImPlotTime(t.S, (t.Us / 1000) * 1000);
        case ImPlotTimeUnit_Us:  return t;
epezent's avatar
epezent 已提交
701
702
703
704
705
        case ImPlotTimeUnit_Yr:  GImPlot->Tm.tm_mon  = 0; // fall-through
        case ImPlotTimeUnit_Mo:  GImPlot->Tm.tm_mday = 1; // fall-through
        case ImPlotTimeUnit_Day: GImPlot->Tm.tm_hour = 0; // fall-through
        case ImPlotTimeUnit_Hr:  GImPlot->Tm.tm_min  = 0; // fall-through
        case ImPlotTimeUnit_Min: GImPlot->Tm.tm_sec  = 0; break;
epezent's avatar
epezent 已提交
706
        default:                 return t;
epezent's avatar
epezent 已提交
707
    }
epezent's avatar
epezent 已提交
708
    return ImPlotTime(MakeGmTime(&GImPlot->Tm),0);
epezent's avatar
epezent 已提交
709
710
}

epezent's avatar
epezent 已提交
711
ImPlotTime CeilTime(const ImPlotTime& t, ImPlotTimeUnit unit) {
epezent's avatar
epezent 已提交
712
713
714
    return AddTime(FloorTime(t, unit), unit, 1);
}

epezent's avatar
epezent 已提交
715
716
717
718
719
720
ImPlotTime RoundTime(const ImPlotTime& t, ImPlotTimeUnit unit) {
    ImPlotTime t1 = FloorTime(t, unit);
    ImPlotTime t2 = AddTime(t1,unit,1);
    if (t1.S == t2.S)
        return t.Us - t1.Us < t2.Us - t.Us ? t1 : t2;
    return t.S - t1.S < t2.S - t.S ? t1 : t2;
epezent's avatar
epezent 已提交
721
722
}

epezent's avatar
epezent 已提交
723
int GetYear(const ImPlotTime& t) {
epezent's avatar
epezent 已提交
724
    tm& Tm = GImPlot->Tm;
epezent's avatar
epezent 已提交
725
    GetGmTime(&t.S, &Tm);
epezent's avatar
epezent 已提交
726
727
728
    return Tm.tm_year + 1900;
}

epezent's avatar
epezent 已提交
729
ImPlotTime MakeYear(int year) {
epezent's avatar
epezent 已提交
730
731
732
733
734
735
736
737
738
739
740
741
    int yr = year - 1900;
    if (yr < 0)
        yr = 0;
    GImPlot->Tm = tm();
    GImPlot->Tm.tm_year = yr;
    GImPlot->Tm.tm_sec  = 1;
    time_t s = MakeGmTime(&GImPlot->Tm);
    if (s < 0)
        s = 0;
    return (double)s;
}

epezent's avatar
epezent 已提交
742
int FormatTime(const ImPlotTime& t, char* buffer, int size, ImPlotTimeFmt fmt) {
epezent's avatar
epezent 已提交
743
    tm& Tm = GImPlot->Tm;
epezent's avatar
epezent 已提交
744
    GetGmTime(&t.S, &Tm);
epezent's avatar
epezent 已提交
745
746

    const char* ap = Tm.tm_hour < 12 ? "am" : "pm";
epezent's avatar
epezent 已提交
747
748
    const int us   = t.Us % 1000;
    const int ms   = t.Us / 1000;
epezent's avatar
epezent 已提交
749
750
751
752
753
754
755
756
757
758
759
    const int sec  = Tm.tm_sec;
    const int min  = Tm.tm_min;
    const int hr   = (Tm.tm_hour == 0 || Tm.tm_hour == 12) ? 12 : Tm.tm_hour % 12;
    const int day  = Tm.tm_mday;
    const int mon  = Tm.tm_mon + 1;
    const int year = Tm.tm_year + 1900;
    const int yr   = year % 100;

    static const char mnames[12][4] = {"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};

    switch(fmt) {        
epezent's avatar
epezent 已提交
760
761
        case ImPlotTimeFmt_Us:            return snprintf(buffer, size, ".%03d %03d", ms, us);                                               
        case ImPlotTimeFmt_SUs:           return snprintf(buffer, size, ":%02d.%03d %03d", sec, ms, us);                                     
epezent's avatar
epezent 已提交
762
763
764
765
766
767
768
769
770
771
        case ImPlotTimeFmt_SMs:           return snprintf(buffer, size, ":%02d.%03d", sec, ms);                                     
        case ImPlotTimeFmt_S:             return snprintf(buffer, size, ":%02d", sec);                                         
        case ImPlotTimeFmt_HrMinS:        return snprintf(buffer, size, "%d:%02d:%02d%s", hr, min, sec, ap);                        
        case ImPlotTimeFmt_HrMin:         return snprintf(buffer, size, "%d:%02d%s", hr, min, ap);                                  
        case ImPlotTimeFmt_Hr:            return snprintf(buffer, size, "%u%s", hr, ap);                                            
        case ImPlotTimeFmt_DayMo:         return snprintf(buffer, size, "%d/%d", mon, day);                                         
        case ImPlotTimeFmt_DayMoHrMin:    return snprintf(buffer, size, "%d/%d %u:%02d%s", mon, day, hr, min, ap);                  
        case ImPlotTimeFmt_DayMoYr:       return snprintf(buffer, size, "%d/%d/%d", mon, day, yr);                                  
        case ImPlotTimeFmt_DayMoYrHrMin:  return snprintf(buffer, size, "%d/%d/%d %u:%02d%s", mon, day, yr, hr, min, ap);           
        case ImPlotTimeFmt_DayMoYrHrMinS: return snprintf(buffer, size, "%d/%d/%d %u:%02d:%02d%s", mon, day, yr, hr, min, sec, ap); 
epezent's avatar
epezent 已提交
772
        case ImPlotTimeFmt_MoYr:          return snprintf(buffer, size, "%s %d", mnames[Tm.tm_mon], year);
epezent's avatar
epezent 已提交
773
774
775
        case ImPlotTimeFmt_Mo:            return snprintf(buffer, size, "%s", mnames[Tm.tm_mon]);                                   
        case ImPlotTimeFmt_Yr:            return snprintf(buffer, size, "%d", year);                                                
        default:                          return 0;                                                                                   
epezent's avatar
epezent 已提交
776
777
778
779
780
781
782
783
784
785
786
787
    }
}

void PrintTime(double t, ImPlotTimeFmt fmt) { 
    static char buff[32];  
    FormatTime(t, buff, 32, fmt); 
    printf("%s\n",buff); 
}

// Returns the nominally largest possible width for a time format
inline float GetTimeLabelWidth(ImPlotTimeFmt fmt) {
    switch (fmt) {
epezent's avatar
epezent 已提交
788
789
        case ImPlotTimeFmt_Us:            return ImGui::CalcTextSize(".888 888").x;             // .428 552
        case ImPlotTimeFmt_SUs:           return ImGui::CalcTextSize(":88.888 888").x;          // :29.428 552
epezent's avatar
epezent 已提交
790
791
792
793
794
795
796
797
798
799
        case ImPlotTimeFmt_SMs:           return ImGui::CalcTextSize(":88.888").x;             // :29.428
        case ImPlotTimeFmt_S:             return ImGui::CalcTextSize(":88").x;                 // :29
        case ImPlotTimeFmt_HrMinS:        return ImGui::CalcTextSize("88:88:88pm").x;          // 7:21:29pm
        case ImPlotTimeFmt_HrMin:         return ImGui::CalcTextSize("88:88pm").x;             // 7:21pm
        case ImPlotTimeFmt_Hr:            return ImGui::CalcTextSize("8pm").x;                 // 7pm
        case ImPlotTimeFmt_DayMo:         return ImGui::CalcTextSize("88/88").x;               // 10/3
        case ImPlotTimeFmt_DayMoHrMin:    return ImGui::CalcTextSize("88/88 88:88pm").x;       // 10/3 7:21pm
        case ImPlotTimeFmt_DayMoYr:       return ImGui::CalcTextSize("88/88/88").x;            // 10/3/1991
        case ImPlotTimeFmt_DayMoYrHrMin:  return ImGui::CalcTextSize("88/88/88 88:88pm").x;    // 10/3/91 7:21pm
        case ImPlotTimeFmt_DayMoYrHrMinS: return ImGui::CalcTextSize("88/88/88 88:88:88pm").x; // 10/3/91 7:21:29pm
epezent's avatar
epezent 已提交
800
        case ImPlotTimeFmt_MoYr:          return ImGui::CalcTextSize("MMM 8888").x;            // Oct 1991
epezent's avatar
epezent 已提交
801
802
803
        case ImPlotTimeFmt_Mo:            return ImGui::CalcTextSize("MMM").x;                 // Oct
        case ImPlotTimeFmt_Yr:            return ImGui::CalcTextSize("8888").x;                // 1991
        default:                          return 0;
epezent's avatar
epezent 已提交
804
805
806
807
808
809
810
811
812
813
814
815
    }
}

inline void LabelTickTime(ImPlotTick& tick, ImGuiTextBuffer& buffer, ImPlotTimeFmt fmt) {
    char temp[32];
    if (tick.ShowLabel) {
        tick.BufferOffset = buffer.size();
        FormatTime(tick.PlotPos, temp, 32, fmt);
        buffer.append(temp, temp + strlen(temp) + 1);
        tick.LabelSize = ImGui::CalcTextSize(buffer.Buf.Data + tick.BufferOffset);
    }
}
epezent's avatar
epezent 已提交
816

epezent's avatar
epezent 已提交
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
static const ImPlotTimeFmt TimeFormatLevel0[ImPlotTimeUnit_COUNT] = {
    ImPlotTimeFmt_Us,
    ImPlotTimeFmt_SMs,
    ImPlotTimeFmt_S,
    ImPlotTimeFmt_HrMin,
    ImPlotTimeFmt_Hr,
    ImPlotTimeFmt_DayMo,
    ImPlotTimeFmt_Mo,
    ImPlotTimeFmt_Yr
};

static const ImPlotTimeFmt TimeFormatLevel1[ImPlotTimeUnit_COUNT] = {
    ImPlotTimeFmt_HrMin,
    ImPlotTimeFmt_HrMinS,
    ImPlotTimeFmt_HrMin,
    ImPlotTimeFmt_HrMin,
    ImPlotTimeFmt_DayMo,
    ImPlotTimeFmt_DayMo,
epezent's avatar
epezent 已提交
835
    ImPlotTimeFmt_MoYr,
epezent's avatar
epezent 已提交
836
837
838
839
840
841
842
843
844
845
    ImPlotTimeFmt_Yr
};

static const ImPlotTimeFmt TimeFormatLevel1First[ImPlotTimeUnit_COUNT] = {
    ImPlotTimeFmt_DayMoYrHrMinS,
    ImPlotTimeFmt_DayMoYrHrMinS,
    ImPlotTimeFmt_DayMoYrHrMin,
    ImPlotTimeFmt_DayMoYrHrMin,
    ImPlotTimeFmt_DayMoYr,
    ImPlotTimeFmt_DayMoYr,
epezent's avatar
epezent 已提交
846
    ImPlotTimeFmt_MoYr,
epezent's avatar
epezent 已提交
847
848
849
    ImPlotTimeFmt_Yr
};

epezent's avatar
epezent 已提交
850
void AddTicksTime(const ImPlotRange& range, float plot_width, ImPlotTickCollection& ticks) {
851
    // get units for level 0 and level 1 labels
epezent's avatar
epezent 已提交
852
853
    const ImPlotTimeUnit unit0 = GetUnitForRange(range.Size() / (plot_width / 100)); // level = 0 (top)
    const ImPlotTimeUnit unit1 = unit0 + 1;                                          // level = 1 (bottom)
epezent's avatar
epezent 已提交
854
855
856
857
858
859

    // get time format specs
    const ImPlotTimeFmt fmt0 = TimeFormatLevel0[unit0];
    const ImPlotTimeFmt fmt1 = TimeFormatLevel1[unit1];
    const ImPlotTimeFmt fmtf = TimeFormatLevel1First[unit1];

epezent's avatar
epezent 已提交
860
861
862
    const ImPlotTime t_min(range.Min);
    const ImPlotTime t_max(range.Max);

epezent's avatar
epezent 已提交
863
    // maximum allowable density of labels
epezent's avatar
epezent 已提交
864
    const float max_density       = 0.5f;
epezent's avatar
epezent 已提交
865
866

    // book keeping
epezent's avatar
epezent 已提交
867
868
    bool first = true;
    const char* last_major = NULL;
epezent's avatar
epezent 已提交
869

870
871
872
873
    if (unit0 != ImPlotTimeUnit_Yr) {
        // pixels per major (level 1) division
        const float pix_per_major_div = plot_width / (float)(range.Size() / TimeUnitSpans[unit1]);
        // nominal pixels taken up by minor (level 0) label
epezent's avatar
epezent 已提交
874
        const float minor_label_width = GetTimeLabelWidth(fmt0);
875
876
877
878
879
        // the maximum number of minor (level 0) labels that can fit between major (level 1) divisions
        const int   minor_per_major   = (int)(max_density * pix_per_major_div / minor_label_width);
        // the minor step size (level 0)
        const int step = GetTimeStep(minor_per_major, unit0);
        // generate ticks
epezent's avatar
epezent 已提交
880
881
882
883
        ImPlotTime t1 = FloorTime(ImPlotTime(range.Min), unit1);
        t1 = t1;
        while (t1 < t_max) {
            if (t1 >= t_min && t1 <= t_max) {
epezent's avatar
epezent 已提交
884
                // minor level 0 tick
epezent's avatar
epezent 已提交
885
                ImPlotTick tick_min(t1.ToDouble(),true,true);
epezent's avatar
epezent 已提交
886
                tick_min.Level = 0;
epezent's avatar
epezent 已提交
887
                LabelTickTime(tick_min,ticks.Labels,fmt0);
epezent's avatar
epezent 已提交
888
                ticks.AddTick(tick_min);
epezent's avatar
epezent 已提交
889
                // major level 1 tick
epezent's avatar
epezent 已提交
890
                ImPlotTick tick_maj(t1.ToDouble(),true,true);
epezent's avatar
epezent 已提交
891
892
893
894
895
896
897
898
899
900
901
902
                tick_maj.Level = 1;
                LabelTickTime(tick_maj,ticks.Labels,first ? fmtf : fmt1); 
                const char* this_major = ticks.Labels.Buf.Data + tick_maj.BufferOffset; 
                if (last_major == NULL)  
                    last_major = this_major;
                else if (strcmp(last_major,this_major) == 0) 
                    tick_maj.ShowLabel = false;
                else
                    last_major = this_major;                          
                ticks.AddTick(tick_maj);                

                if (first) first = false;
epezent's avatar
epezent 已提交
903
904
            }
            // add minor ticks up until next major
epezent's avatar
epezent 已提交
905
906
907
            const ImPlotTime t2 = AddTime(t1, unit1, 1);   
            if (minor_per_major > 1 && (t_min <= t2 && t1 <= t_max)) {
                ImPlotTime t12 = AddTime(t1, unit0, step);
908
                while (t12 < t2) {
epezent's avatar
epezent 已提交
909
910
911
                    float px_to_t2 = (float)((t2 - t12).ToDouble()/range.Size()) * plot_width;
                    if (t12 >= t_min && t12 <= t_max) {
                        ImPlotTick tick(t12.ToDouble(),false,px_to_t2 >= minor_label_width);
epezent's avatar
epezent 已提交
912
                        tick.Level =  0;
epezent's avatar
epezent 已提交
913
                        LabelTickTime(tick,ticks.Labels,fmt0);
epezent's avatar
epezent 已提交
914
                        ticks.AddTick(tick);
epezent's avatar
epezent 已提交
915
916
917
918
919
920
921
                        // if (first) {
                        //     ImPlotTick tick_maj(t12,true,true);
                        //     tick_maj.Level = 1;
                        //     LabelTickTime(tick_maj,ticks.Labels,TimeFormatLevel1[unit1]);
                        //     ticks.AddTick(tick_maj);
                        //     first = false;
                        // }
epezent's avatar
epezent 已提交
922
                    }
923
924
                    t12 = AddTime(t12, unit0, step);
                }                
epezent's avatar
epezent 已提交
925
            }
epezent's avatar
epezent 已提交
926
            t1 = t2;
epezent's avatar
epezent 已提交
927
928
929
        }
    }
    else {
930
931
        const float label_width = GetTimeLabelWidth(TimeFormatLevel0[ImPlotTimeUnit_Yr]);
        const int   max_labels  = (int)(max_density * plot_width / label_width);
epezent's avatar
epezent 已提交
932
933
        const int year_min      = GetYear(range.Min);
        const int year_max      = GetYear(CeilTime(range.Max, ImPlotTimeUnit_Yr));
934
935
936
        const double nice_range = NiceNum((year_max - year_min)*0.99,false);
        const double interval   = NiceNum(nice_range / (max_labels - 1), true);
        const int graphmin      = (int)(floor(year_min / interval) * interval);
epezent's avatar
epezent 已提交
937
        const int step          = (int)interval <= 0 ? 1 : (int)interval;
epezent's avatar
epezent 已提交
938
        ImPlotTime t1 = MakeYear(graphmin);
939
        while (t1 < range.Max) {
epezent's avatar
epezent 已提交
940
941
            if (t1 >= t_min && t1 <= t_max) {
                ImPlotTick tick(t1.ToDouble(), true, true);
942
943
944
945
                tick.Level = 0;
                LabelTickTime(tick, ticks.Labels, TimeFormatLevel0[ImPlotTimeUnit_Yr]);
                ticks.AddTick(tick);
            }
epezent's avatar
epezent 已提交
946
            t1 = AddTime(t1, ImPlotTimeUnit_Yr, step);            
947
        }        
948
    }
949
950
}

951
952
953
954
//-----------------------------------------------------------------------------
// Axis Utils
//-----------------------------------------------------------------------------

epezent's avatar
epezent 已提交
955
956
957
958
959
960
961
void UpdateAxisColors(int axis_flag, ImPlotAxisColor* col) {
    const ImVec4 col_label = GetStyleColorVec4(axis_flag);
    const ImVec4 col_grid  = GetStyleColorVec4(axis_flag + 1);
    col->Major  = ImGui::GetColorU32(col_grid);
    col->Minor  = ImGui::GetColorU32(col_grid*ImVec4(1,1,1,GImPlot->Style.MinorAlpha));
    col->MajTxt = ImGui::GetColorU32(col_label);
    col->MinTxt = ImGui::GetColorU32(col_label);
962
963
}

epezent's avatar
epezent 已提交
964

965
//-----------------------------------------------------------------------------
Evan Pezent's avatar
Evan Pezent 已提交
966
// BeginPlot()
967
//-----------------------------------------------------------------------------
Evan Pezent's avatar
Evan Pezent 已提交
968

969
bool BeginPlot(const char* title, const char* x_label, const char* y_label, const ImVec2& size, ImPlotFlags flags, ImPlotAxisFlags x_flags, ImPlotAxisFlags y_flags, ImPlotAxisFlags y2_flags, ImPlotAxisFlags y3_flags) {
970
    IM_ASSERT_USER_ERROR(GImPlot != NULL, "No current context. Did you call ImPlot::CreateContext() or ImPlot::SetCurrentContext()?");
971
    ImPlotContext& gp = *GImPlot;
Evan Pezent's avatar
Evan Pezent 已提交
972
973
974
975
976
977
978
    IM_ASSERT_USER_ERROR(gp.CurrentPlot == NULL, "Mismatched BeginPlot()/EndPlot()!");

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

    ImGuiContext &G      = *GImGui;
    ImGuiWindow * Window = G.CurrentWindow;
    if (Window->SkipItems) {
979
        Reset(GImPlot);
Evan Pezent's avatar
Evan Pezent 已提交
980
981
982
983
984
        return false;
    }

    const ImGuiID     ID       = Window->GetID(title);
    const ImGuiStyle &Style    = G.Style;
Evan Pezent's avatar
Evan Pezent 已提交
985
    const ImGuiIO &   IO       = ImGui::GetIO();
Evan Pezent's avatar
Evan Pezent 已提交
986

Evan Pezent's avatar
Evan Pezent 已提交
987
    bool just_created = gp.Plots.GetByKey(ID) == NULL;
988
    gp.CurrentPlot    = gp.Plots.GetOrAddByKey(ID);
ozlb's avatar
ozlb 已提交
989
    ImPlotState &plot = *gp.CurrentPlot;
Evan Pezent's avatar
Evan Pezent 已提交
990

991
992
    plot.CurrentYAxis = 0;

Evan Pezent's avatar
Evan Pezent 已提交
993
    if (just_created) {
994
995
996
997
998
        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 已提交
999
    }
1000
    else {
为了加快浏览速度,不会显示所有历史记录。 查看完整的 blame