-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathplot.h
1813 lines (1687 loc) · 57.5 KB
/
plot.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
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
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
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
246
247
248
249
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
275
276
277
278
279
280
281
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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
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
567
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
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
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
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
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
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/** Signalsmith's Basic C++ Plots - https://signalsmith-audio.co.uk/code/plot/
@copyright Licensed as 0BSD. If you need anything else, get in touch. */
#ifndef SIGNALSMITH_PLOT_H
#define SIGNALSMITH_PLOT_H
#include <fstream>
#include <memory>
#include <functional>
#include <vector>
#include <cmath>
#include <sstream>
namespace signalsmith { namespace plot {
/** @defgroup Plots Plots
@brief Basic C++ plotting
To use, set up a `Figure` or `Plot2D`, add elements to it, and then write with `.write("output.svg")`.
\image html default-2d.svg An example plot
Elements are drawn hierarchically, but generally in reverse order, so you should add your most important elements first.
Elements can have a "style index" which simultaneously loops through colour/dash/hatch sequences, for increased greyscale/colourblind support.
\image html style-sequence.svg
@{
@file
**/
static double estimateUtf8Width(const char *utf8Str);
/** Plotting style, used for both layout and SVG rendering.
Colour/dash/hatch styles are defined as CSS classes, assigned to elements based on their integer style index. CSS is written inline in the SVG, and can be extended/overridden with `.cssPrefix`/`.cssSuffix`.
\image html custom-2d.svg
It generates CSS classes from `.colours` (`svg-plot-sN`/`svg-plot-fN`/`svg-plot-tN` for stroke/fill/text), `.dashes` (`svg-plot-dN`) and `.hatches` (`svg-plot-hN`), where `N` is the index - e.g. there are six colours by default, generating `svg-plot-s0` to `svg-plot-s5`.
*/
class PlotStyle {
public:
double scale = 1; ///< scales the entire plot (including adjusting the precision)
double padding = 10;
double lineWidth = 1.5, precision = 100;
double markerSize = 3.25;
double tickH = 4, tickV = 4;
// Text
double labelSize = 12, valueSize = 10;
double fontAspectRatio = 1; ///< scales size estimates, if using a particularly wide font
double textPadding = 5, lineHeight = 1.2;
// Fills
double fillOpacity = 0.28;
double hatchWidth = 1, hatchSpacing = 3;
double animation = 2; ///< Animation duration
std::string scriptHref = "", scriptSrc = "";
std::string cssPrefix = "", cssSuffix = "";
std::vector<std::string> colours = {"#0073E6", "#CC0000", "#00B300", "#806600", "#E69900", "#CC00CC"};
std::vector<std::vector<double>> dashes = {{}, {1.2, 1.2}, {2.8, 1.6}, {5, 4}, {4, 1, 1, 1, 1, 1}, {10, 3}, {4, 2, 1, 2}};
/// SVG literals for the markers. These should be centered on `(0, 0)` and look correct next to a filled circle of radius 1. They will be given both a stroke and fill-class, so they should specify `fill="none"`/`stroke="none"` if fill/stroke is not wanted.
std::vector<std::string> markers = {
"<circle cx=\"0\" cy=\"0\" r=\"1\" stroke=\"none\"/>",
"<path d=\"M0 0.9 -0.9 0 0 -0.9 0.9 0Z\" fill=\"#FFFA\" stroke-linejoin=\"miter\" stroke-width=\"0.5\"/>",
"<path fill=\"none\" d=\"M0 -1.2 0 1.2 M -1.2 0 1.2 0\" stroke-width=\"0.6\"/>",
"<circle cx=\"0\" cy=\"0\" fill=\"#FFFA\" r=\"0.82\" stroke-width=\"0.55\"/>",
"<path stroke=\"none\" d=\"M0 -1.25 1.25 0.9 -1.25 0.9Z\"/>",
// spares:
//"<path fill=\"none\" d=\"M-0.9 -0.9 0.9 0.9 M -0.9 0.9 0.9 -0.9\" stroke-width=\"0.65\"/>",
//"<rect x=\"-0.9\" y=\"-0.9\" width=\"1.8\" height=\"1.8\" stroke=\"none\"/>",
};
struct Hatch {
std::vector<double> angles;
double lineScale = 1, spaceScale=1;
Hatch() {}
Hatch(double angle) : angles({angle}) {}
Hatch(std::vector<double> angles, double scale=1) : angles(angles), lineScale(scale), spaceScale(scale) {}
Hatch(std::vector<double> angles, double lineScale, double spaceScale) : angles(angles), lineScale(lineScale), spaceScale(spaceScale) {}
};
std::vector<Hatch> hatches = {{}, {-50}, {{30}, 0.9, 0.8}, {{8, 93}, 0.7, 1}};
struct Counter {
int colour, dash, hatch, marker;
Counter(int colour, int dash, int hatch, int marker) : colour(colour), dash(dash), hatch(hatch), marker(marker) {}
Counter(int index=0) : colour(index), dash(index), hatch(index), marker(index) {}
/// Increment the counter, and return the previous value
Counter bump() {
Counter result = *this;
++colour;
++dash;
++hatch;
++marker;
return result;
}
Counter withColour(int index) {
return Counter(index, dash, hatch, marker);
}
Counter withDash(int index) {
return Counter(colour, index, hatch, marker);
}
Counter withHatch(int index) {
return Counter(colour, dash, index, marker);
}
Counter withMarker(int index) {
return Counter(colour, dash, hatch, index);
}
};
std::string strokeClass(const Counter &counter) const {
if (counter.colour < 0 || colours.size() == 0) return "svg-plot-s";
return "svg-plot-s" + std::to_string(counter.colour%(int)colours.size());
}
std::string fillClass(const Counter &counter) const {
if (counter.colour < 0 || colours.size() == 0) return "svg-plot-f";
return "svg-plot-f" + std::to_string(counter.colour%(int)colours.size());
}
std::string textClass(const Counter &counter) const {
if (counter.colour < 0 || colours.size() == 0) return "svg-plot-t";
return "svg-plot-t" + std::to_string(counter.colour%(int)colours.size());
}
std::string dashClass(const Counter &counter) const {
if (counter.dash < 0 || dashes.size() == 0) return "svg-plot-d";
return "svg-plot-d" + std::to_string(counter.dash%(int)dashes.size());
}
std::string hatchClass(const Counter &counter) const {
if (counter.hatch < 0 || hatches.size() == 0) return "svg-plot-h";
return "svg-plot-h" + std::to_string(counter.hatch%(int)hatches.size());
}
std::string markerId(const Counter &counter) const {
return "svg-plot-marker" + std::to_string(std::abs(counter.marker)%(int)markers.size());
}
const std::string & markerRaw(const Counter &counter) const {
int index = std::abs(counter.marker)%(int)markers.size();
return markers[index];
}
void css(std::ostream &o) const {
o << cssPrefix;
o << R"CSS(
.svg-plot {
stroke-linecap: butt;
stroke-linejoin: round;
}
.svg-plot-bg {
fill: none;
stroke: none;
}
.svg-plot-axis {
stroke: none;
fill: #FFFFFFD9;
}
.svg-plot-legend {
stroke: none;
fill: #FFFFFFE4;
}
.svg-plot-line {
stroke: blue;
fill: none;
stroke-width: )CSS" << lineWidth << R"CSS(px;
stroke-linejoin: round;
}
.svg-plot-fill {
stroke: none;
opacity: )CSS" << fillOpacity << R"CSS(;
}
.svg-plot-major {
stroke: #000;
stroke-width: 1px;
stroke-linecap: square;
fill: none;
}
.svg-plot-minor {
stroke: #0000004D;
stroke-width: 0.5px;
stroke-dasharray: 0.5 1.5;
stroke-linecap: round;
fill: none;
}
.svg-plot-tick {
stroke: #000;
fill: none;
stroke-width: 1px;
stroke-linecap: butt;
}
.svg-plot-value, .svg-plot-label {
font-family: Arial,sans-serif;
fill: #000;
stroke: #FFFFFF48;
stroke-width: 2.5px;
paint-order: stroke fill;
text-anchor: middle;
dominant-baseline: central;
alignment-baseline: baseline;
}
.svg-plot-label {
font-size: )CSS" << labelSize << R"CSS(px;
}
.svg-plot-value {
font-size: )CSS" << valueSize << R"CSS(px;
}
.svg-plot-hatch {
stroke: #FFF;
stroke-width: )CSS" << hatchWidth << R"CSS(px;
}
.svg-plot-marker {
transform: scale()CSS" << markerSize << R"CSS();
}
.svg-plot-s {
stroke: #000;
}
.svg-plot-f, .svg-plot-t {
fill: #000;
}
)CSS";
for (size_t i = 0; i < colours.size(); ++i) {
o << ".svg-plot-s" << i << "{stroke:" << colours[i] << "}\n";
o << ".svg-plot-f" << i << ",.svg-plot-t" << i << "{fill:" << colours[i] << "}\n";
}
for (size_t i = 0; i < dashes.size(); ++i) {
auto &d = dashes[i];
if (d.size() == 0) {
o << ".svg-plot-d" << i << "{stroke-width:" << (0.9*lineWidth) << "px}\n";
} else {
o << ".svg-plot-d" << i << "{stroke-dasharray:";
for (auto &v : d) o << " " << (v*lineWidth);
o << "}\n";
}
}
for (size_t i = 0; i < hatches.size(); ++i) {
auto &h = hatches[i];
if (h.angles.size()) {
o << ".svg-plot-h" << i << "{mask:url(#svg-plot-hatch" << i << ")}\n";
} else {
// Compensate for the fact that it's not hatched
o << ".svg-plot-h" << i << "{opacity:" << (fillOpacity*(hatchWidth/hatchSpacing*0.75 + 0.25)) << "}\n";
}
}
for (size_t i = 0; i < hatches.size(); ++i) {
auto &h = hatches[i];
if (h.lineScale != 1) {
o << "#svg-plot-hatch" << i << "-pattern{stroke-width:" << hatchWidth*h.lineScale << "px}\n";
}
}
o << cssSuffix;
}
};
struct Bounds {
double left = 0, right = 0, top = 0, bottom = 0;
bool set = false;
Bounds() {}
Bounds(double left, double right, double top, double bottom) : left(left), right(right), top(top), bottom(bottom), set(true) {}
double width() const {
return right - left;
}
double height() const {
return bottom - top;
}
Bounds & expandTo(const Bounds &other) {
left = std::min(left, other.left);
top = std::min(top, other.top);
right = std::max(right, other.right);
bottom = std::max(bottom, other.bottom);
return *this;
}
Bounds pad(double hPad, double vPad) {
return {left - hPad, right + hPad, top - vPad, bottom + vPad};
}
Bounds pad(double padding) {
return pad(padding, padding);
}
};
struct Point2D {
double x, y;
};
/// Wrapper for slightly more semantic code when writing SVGs
class SvgWriter {
std::ostream &output;
std::vector<Bounds> clipStack;
long idCounter = 0;
double precision, invPrecision;
public:
SvgWriter(std::ostream &output, Bounds bounds, double precision) : output(output), clipStack({bounds}), precision(precision), invPrecision(1.0/precision) {}
SvgWriter & raw() {
return *this;
}
template<class First, class ...Args>
SvgWriter & raw(First &&first, Args &&...args) {
output << first;
return raw(args...);
}
SvgWriter & write() {
return *this;
}
template<class First, class ...Args>
SvgWriter & write(First &&v, Args &&...args) {
// Only strings get escaped
return raw(v).write(args...);
}
template<class ...Args>
SvgWriter & write(const char *str, Args &&...args) {
while (*str) {
if (*str == '<') {
output << "<";
} else if (*str == '&') {
output << "&";
} else if (*str == '"') {
output << """;
} else {
output << (*str);
}
++str;
}
return write(args...);
}
template<class ...Args>
SvgWriter & write(std::string str, Args &&...args) {
return write(str.c_str(), args...);
}
template<class ...Args>
SvgWriter & attr(const char *name, Args &&...args) {
return raw(" ", name, "=\"").write(args...).raw("\"");
}
SvgWriter & pushClip(Bounds b, double dataCheckPadding) {
clipStack.push_back(b.pad(dataCheckPadding));
auto clipId = elementId("clip");
tag("clipPath").attr("id", clipId);
rect(b.left, b.top, b.width(), b.height());
raw("</clipPath>");
tag("g").attr("clip-path", "url(#", clipId, ")");
return *this;
}
SvgWriter & popClip() {
clipStack.resize(clipStack.size() - 1);
return raw("</g>");
}
std::string elementId(std::string prefix) {
return prefix + std::to_string(idCounter++);
}
/// XML tag helper, closing the tag when it's destroyed
struct Tag {
SvgWriter &writer;
bool active = true;
bool selfClose;
Tag(SvgWriter &writer, bool selfClose=false) : writer(writer), selfClose(selfClose) {}
// Move-construct only
Tag(Tag &&other) : writer(other.writer), selfClose(other.selfClose) {
other.active = false;
}
~Tag() {
if (active) writer.raw(selfClose ? "/>" : ">");
}
template<class ...Args>
Tag & attr(const char *name, Args &&...args) & {
writer.attr(name, args...);
return *this;
}
template<class ...Args>
Tag && attr(const char *name, Args &&...args) && {
writer.attr(name, args...);
return std::move(*this);
}
};
Tag tag(const char *name, bool selfClose=false) {
raw("<", name);
return Tag(*this, selfClose);
}
Tag line(double x1, double y1, double x2, double y2) {
return tag("line", true).attr("x1", x1).attr("x2", x2).attr("y1", y1).attr("y2", y2);
}
Tag rect(double x, double y, double w, double h) {
return tag("rect", true).attr("x", x).attr("y", y).attr("width", w).attr("height", h);
}
double round(double v) {
return std::round(v*precision)*invPrecision;
};
bool animated = false;
enum class PointState {start, outOfBounds, singlePoint, pendingLine};
PointState pointState = PointState::start;
char outOfBoundsMask = 0; // tracks which direction(s) we are out of bounds
Point2D lastDrawn, prevPoint;
double totalPendingError = 0;
void startPath() {
pointState = PointState::start;
outOfBoundsMask = 0;
prevPoint.x = prevPoint.y = -1e300;
raw("M");
}
void endPath() {
if (pointState == PointState::pendingLine) {
raw(" ", round(prevPoint.x), " ", round(prevPoint.y));
}
}
void addPoint(double x, double y, bool alwaysInclude=false) {
if (std::isnan(x) || std::isnan(y)) return;
auto clip = clipStack.back();
/// Bitmask indicating which direction(s) the point is outside the bounds
char mask = (clip.left > x)
| (2*(clip.right < x))
| (4*(clip.top > y))
| (8*(clip.bottom < y));
if (alwaysInclude) mask = 0;
outOfBoundsMask &= mask;
if (!outOfBoundsMask) {
if (pointState == PointState::outOfBounds) {
// Draw the most recent out-of-bounds point
raw(" ", round(prevPoint.x), " ", round(prevPoint.y));
lastDrawn = prevPoint;
pointState = PointState::singlePoint;
}
if (pointState == PointState::singlePoint) {
pointState = PointState::pendingLine;
totalPendingError = 0;
} else if (pointState == PointState::pendingLine) {
// Approximate the pending point as being on the line from last-drawn point -> current
double d1 = std::hypot(prevPoint.x - lastDrawn.x, prevPoint.y - lastDrawn.y);
double d2 = std::hypot(x - lastDrawn.x, y - lastDrawn.y);
double scale = d2 ? d1/d2 : 0;
double extX = lastDrawn.x + (x - lastDrawn.x)*scale;
double extY = lastDrawn.y + (y - lastDrawn.y)*scale;
// How far off would that be?
totalPendingError += std::hypot(extX - prevPoint.x, extY - prevPoint.y);
if (totalPendingError > invPrecision) {
// Would be too much accumulated error. Draw the pending segment, and start a new one.
raw(" ", round(prevPoint.x), " ", round(prevPoint.y));
lastDrawn = prevPoint;
totalPendingError = 0;
}
} else { // start
raw(" ", round(x), " ", round(y));
lastDrawn = {x, y};
pointState = PointState::singlePoint;
}
outOfBoundsMask = mask;
if (outOfBoundsMask && pointState != PointState::start) {
if (pointState == PointState::pendingLine) {
raw(" ", round(prevPoint.x), " ", round(prevPoint.y));
}
raw(" ", round(x), " ", round(y)); // Draw the first out-of-bounds point
pointState = PointState::outOfBounds;
}
}
prevPoint = {x, y};
}
};
/** Any drawable element.
Each element can draw to three layers: fill, stroke and label. Child elements are drawn in reverse order, so the earliest ones are drawn on top of each layer.
Copy/assign is disabled, to prevent accidental copying when you should be holding a reference.
*/
class SvgDrawable {
std::vector<std::unique_ptr<SvgDrawable>> children, layoutChildren;
bool hasLayout = false;
protected:
Bounds bounds;
void invalidateLayout() {
hasLayout = bounds.set = false;
for (auto &c : children) c->invalidateLayout();
layoutChildren.resize(0);
}
virtual void layout(const PlotStyle &style) {
hasLayout = true;
auto processChild = [&](std::unique_ptr<SvgDrawable> &child) {
child->layoutIfNeeded(style);
if (bounds.set) {
if (child->bounds.set) bounds.expandTo(child->bounds);
} else {
bounds = child->bounds;
}
};
for (auto &c : layoutChildren) processChild(c);
for (auto &c : children) processChild(c);
};
/// These children are removed when the layout is invalidated
void addLayoutChild(SvgDrawable *child) {
layoutChildren.emplace_back(child);
}
public:
SvgDrawable() {}
virtual ~SvgDrawable() {}
SvgDrawable(const SvgDrawable &other) = delete;
SvgDrawable & operator =(const SvgDrawable &other) = delete;
Bounds layoutIfNeeded(const PlotStyle &style) {
if (!hasLayout) this->layout(style);
return bounds;
}
/// Takes ownership of the child
void addChild(SvgDrawable *child, bool front=false) {
if (front) {
children.emplace(children.begin(), child);
} else {
children.emplace_back(child);
}
}
virtual void writeData(SvgWriter &svg, const PlotStyle &style) {
for (int i = layoutChildren.size() - 1; i >= 0; --i) {
layoutChildren[i]->writeData(svg, style);
}
for (int i = children.size() - 1; i >= 0; --i) {
children[i]->writeData(svg, style);
}
}
virtual void writeLabel(SvgWriter &svg, const PlotStyle &style) {
for (int i = layoutChildren.size() - 1; i >= 0; --i) {
layoutChildren[i]->writeLabel(svg, style);
}
for (int i = children.size() - 1; i >= 0; --i) {
children[i]->writeLabel(svg, style);
}
}
/** Creates a frame from the current stat, and optionally clears the state ready for the next frame.
The time is the start-time of the frame being created.
\image html animation.svg "Two lines with a different number of frames" */
virtual void toFrame(double time, bool clear=true) {
for (auto &c : children) c->toFrame(time, clear);
}
/// Sets loop time (or < 0 to disable)
virtual void loopFrame(double loopTime) {
for (auto &c : children) c->loopFrame(loopTime);
}
/// Removes all animation frames. Mostly useful if re-using the diagram for multiple animations.
virtual void clearFrames() {
for (auto &c : children) c->clearFrames();
}
};
/// Top-level objects which can generate SVG files
class SvgFileDrawable : public SvgDrawable {
public:
virtual PlotStyle defaultStyle() const {
PlotStyle result;
#ifdef SIGNALSMITH_PLOT_DEFAULT_STYLE
SIGNALSMITH_PLOT_DEFAULT_STYLE((PlotStyle &)result);
#endif
return result;
}
void write(std::ostream &o, const PlotStyle &style) {
this->invalidateLayout();
this->layout(style);
// Add padding
auto bounds = this->bounds.pad(style.padding);
int scale10 = 1;
while (style.scale > scale10*4) scale10 *= 10;
SvgWriter svg(o, bounds, style.precision*scale10);
svg.raw("<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"no\"?>\n<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n");
svg.tag("svg").attr("version", "1.1").attr("class", "svg-plot")
.attr("xmlns", "http://www.w3.org/2000/svg")
.attr("width", bounds.width()*style.scale, "pt").attr("height", bounds.height()*style.scale, "pt")
.attr("viewBox", bounds.left, " ", bounds.top, " ", bounds.width(), " ", bounds.height())
.attr("preserveAspectRatio", "xMidYMid");
svg.rect(this->bounds.left, this->bounds.top, this->bounds.width(), this->bounds.height())
.attr("class", "svg-plot-bg");
this->writeData(svg, style);
this->writeLabel(svg, style);
int maxBounds = std::ceil(std::max(
std::max(std::abs(this->bounds.left), std::abs(this->bounds.right)),
std::max(std::abs(this->bounds.top), std::abs(this->bounds.bottom))
)*std::sqrt(2));
svg.raw("<defs>");
for (size_t i = 0; i < style.markers.size(); ++i) {
svg.tag("g").attr("id", style.markerId(i)).attr("class", "svg-plot-marker");
svg.raw(style.markerRaw(i)).raw("</g>");
}
for (size_t i = 0; i < style.hatches.size(); ++i) {
auto &hatch = style.hatches[i];
if (!hatch.angles.size()) continue;
svg.tag("mask").attr("id", "svg-plot-hatch", i);
for (double angle : hatch.angles) {
svg.rect(-maxBounds, -maxBounds, 2*maxBounds, 2*maxBounds)
.attr("fill", "url(#svg-plot-hatch", i, "-pattern)")
.attr("style", "transform:rotate(", angle, "deg)");
}
svg.raw("</mask>");
double spacing = style.hatchSpacing*hatch.spaceScale;
svg.tag("pattern").attr("patternUnits", "userSpaceOnUse")
.attr("id", "svg-plot-hatch", i, "-pattern").attr("class", "svg-plot-hatch")
.attr("x", 0).attr("y", 0).attr("width", 10).attr("height", spacing);
svg.tag("line", true).attr("x1", -1).attr("x2", 11).attr("y1", spacing*0.5).attr("y2", spacing*0.5)
.attr("stroke", "#FFF").attr("fill", "none");
svg.tag("rect", true).attr("x", -1).attr("y", -1).attr("width", 12).attr("height", 12)
.attr("fill", "#FFF2").attr("stroke", "none");
svg.raw("</pattern>");
}
svg.raw("</defs>");
svg.raw("<style>");
std::stringstream cssStream;
style.css(cssStream);
std::string css = cssStream.str();
const char *cPtr = css.c_str();
// Strip whitespace that doesn't appear between letters/numbers
bool letter = false, letterThenWhitespace = false;
while (*cPtr) {
char c = *(cPtr++);
if (c == '\t' || c == '\n' || c == ' ') {
letterThenWhitespace = letter;
} else {
letter = (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '.' || c == ')' || c == ']';
if (letterThenWhitespace && letter) o << ' ';
letterThenWhitespace = false;
o << c;
}
}
svg.raw("</style>");
if (style.scriptSrc.size() > 0) {
svg.raw("<script>").write(style.scriptSrc).raw("</script>");
}
if (style.scriptHref.size()) svg.tag("script", true).attr("href", style.scriptHref);
svg.raw("</svg>");
}
void write(const std::string &svgFile, const PlotStyle &style) {
std::ofstream s(svgFile);
write(s, style);
}
// If we aren't given a style, use the default one
void write(std::ostream &o) {
this->write(o, this->defaultStyle());
}
void write(const std::string &svgFile) {
write(svgFile, this->defaultStyle());
}
/// Draws when this object goes out of scope
struct ScheduledWrite {
SvgFileDrawable &drawable;
PlotStyle style;
std::string svgFile;
ScheduledWrite(SvgFileDrawable &drawable, const PlotStyle &style, const std::string &svgFile) : drawable(drawable), style(style), svgFile(svgFile) {}
ScheduledWrite(const ScheduledWrite &other) = delete;
ScheduledWrite(ScheduledWrite &&other) : drawable(other.drawable), style(other.style), svgFile(other.svgFile) {
other.svgFile = "";
};
~ScheduledWrite() {
if (svgFile.size() > 0) drawable.write(svgFile, style);
}
};
ScheduledWrite writeLater(const std::string &svgFile) {
return ScheduledWrite{*this, this->defaultStyle(), svgFile};
}
};
/// A labelled point on an axis.
struct Tick {
double value;
std::string name;
enum class Strength {major, minor, tick};
Strength strength = Strength::tick;
Tick(double value, std::string name) : value(value), name(name) {}
template<typename T>
Tick(T v) : value(double(v)) {
name = (std::stringstream() << value).str();
}
};
/** A map from values to screen-space.
Individual grid/ticks can be added with `.major()`/`.minor()`/`.tick()`.
\code
axis.major(4); // default label
axis.major(5, "five"); // explicit label
\endcode
Multiple grids/ticks can be added using `.majors()`/`.minors()`/`.ticks()`, which accept a variable number of values:
\code
axis.majors(0, 10).minors(2, 4, 6, 8);
\endcode
*/
class Axis {
std::function<double(double)> unitMap;
double autoMin, autoMax;
bool hasAutoValue = false;
bool autoScale, autoLabel;
std::string _label = "";
std::vector<Axis *> linked;
Axis *linkedParent = nullptr;
void removeLinkedParent() {
if (!linkedParent) return;
for (auto iter = linkedParent->linked.begin(); iter != linkedParent->linked.end(); ++iter) {
if (*iter == this) {
linkedParent->linked.erase(iter);
linkedParent = nullptr;
return;
}
}
linkedParent = nullptr;
}
public:
double drawLow, drawHigh;
double drawMin() const {
return std::min(drawLow, drawHigh);
}
double drawMax() const {
return std::max(drawLow, drawHigh);
}
double drawSize() const {
return std::abs(drawHigh - drawLow);
}
/// Not associated with a particular line by default, but can be
PlotStyle::Counter styleIndex = -1;
Axis(double drawLow, double drawHigh) : drawLow(drawLow), drawHigh(drawHigh) {
linear(0, 1);
autoScale = true;
autoLabel = true;
}
explicit Axis(const Axis &other) = default;
~Axis() {
removeLinkedParent();
for (auto other : linked) other->removeLinkedParent();
}
/// Register a value for the auto-scale
void autoValue(double v) {
if (linkedParent) return linkedParent->autoValue(v);
if (!autoScale) return;
if (!hasAutoValue) {
autoMin = autoMax = v;
hasAutoValue = true;
} else {
autoMin = std::min(autoMin, v);
autoMax = std::max(autoMax, v);
}
// TODO: why doesn't this cause an infinite loop?
for (auto other : linked) other->autoValue(v);
}
void autoSetup() {
if (hasAutoValue) {
if (autoScale) linear(autoMin, autoMax);
if (autoLabel) minors(autoMin, autoMax);
}
for (auto other : linked) other->autoSetup();
}
/// Prevent auto-labelling
Axis & blank(bool includeLinked=false) {
tickList.clear();
autoLabel = false;
if (includeLinked) {
for (auto other : linked) other->blank();
}
return *this;
}
/// Clear the names from any existing labels
Axis & blankLabels(bool includeLinked=false) {
for (auto &t : tickList) t.name = "";
_label = "";
if (includeLinked) {
for (auto other : linked) other->blankLabels();
}
return *this;
}
/// Copy ticks/label from another axis, optionally removing their text
Axis & copyFrom(Axis &other, bool clearLabels=false) {
unitMap = other.unitMap;
for (Tick tick : other.tickList) {
if (clearLabels) tick.name = "";
tickList.push_back(tick);
}
autoMin = other.autoMin;
autoMax = other.autoMax;
hasAutoValue = other.hasAutoValue;
autoScale = other.autoScale;
autoLabel = other.autoLabel;
for (auto &t : tickList) {
autoValue(t.value);
}
if (other._label.size()) this->_label = other._label;
this->flipped = other.flipped;
for (auto o : linked) o->copyFrom(other, clearLabels);
return *this;
}
/// Link this axis to another, copying any ticks/labels set later as well
Axis & linkFrom(Axis &other) {
removeLinkedParent();
copyFrom(other);
other.linked.push_back(this);
linkedParent = &other;
return *this;
}
/// Whether the axis should draw on the non-default side (e.g. right/top)
bool flipped = false;
Axis & flip(bool flip=true) {
flipped = flip;
for (auto other : linked) other->flip(flip);
return *this;
}
/// Sets the label, and optionally style to match a particular line.
Axis & label(std::string l, PlotStyle::Counter index=-1) {
_label = l;
styleIndex = index;
for (auto other : linked) other->label(l, index);
return *this;
}
const std::string & label() const {
return _label;
}
Axis & range(std::function<double(double)> valueToUnit) {
autoScale = false;
unitMap = valueToUnit;
for (auto other : linked) other->range(valueToUnit);
return *this;
}
Axis & range(double map(double)) {
return range(std::function<double(double)>(map));
}
Axis & range(std::function<double(double)> map, double lowValue, double highValue) {
double lowMapped = map(lowValue), highMapped = map(highValue);
return range([=](double v) {
double mapped = map(v);
return (mapped - lowMapped)/(highMapped - lowMapped);
});
}
Axis & range(double map(double), double lowValue, double highValue) {
return range(std::function<double(double)>(map), lowValue, highValue);
}
Axis & linear(double low, double high) {
return range([=](double v) {
return (v - low)/(high - low);
});
}
double map(double v) {
double unit = unitMap(v);
return drawLow + unit*(drawHigh - drawLow);
}
std::vector<Tick> tickList;
template<class ...Args>
Axis & major(Args &&...args) {
Tick t(args...);
autoValue(t.value);
t.strength = Tick::Strength::major;
tickList.push_back(t);
autoLabel = false;
for (auto other : linked) other->major(args...);
return *this;
}
template<class ...Args>
Axis & minor(Args &&...args) {
Tick t(args...);
autoValue(t.value);
t.strength = Tick::Strength::minor;
tickList.push_back(t);
autoLabel = false;
for (auto other : linked) other->minor(args...);
return *this;
}
template<class ...Args>
Axis & tick(Args &&...args) {
Tick t(args...);
autoValue(t.value);
t.strength = Tick::Strength::tick;
tickList.push_back(t);
autoLabel = false;
for (auto other : linked) other->tick(args...);
return *this;
}
Axis &majors() {
return *this;
}
template<class ...Args>
Axis &majors(Tick tick, Args ...args) {
return major(tick).majors(args...);
}
Axis &minors() {
autoLabel = false;
return *this;
}
template<class ...Args>
Axis &minors(Tick tick, Args ...args) {
return minor(tick).minors(args...);
}
Axis & ticks() {
autoLabel = false;
return *this;
}
template<class ...Args>
Axis & ticks(Tick t, Args ...args) {
return tick(t).ticks(args...);
}
};
class TextLabel : public SvgDrawable {
double textWidth = 0;
void write(SvgWriter &svg, double fontSize) {
{
auto text = svg.tag("text").attr("class", cssClass);
double tx = drawAt.x, ty = drawAt.y;
if (alignment > 0.5) {
text.attr("style", "text-anchor:start");
tx += textWidth*(alignment - 1);
} else if (alignment < -0.5) {
text.attr("style", "text-anchor:end");
tx += textWidth*(alignment + 1);
} else {
tx += textWidth*alignment;
}
ty -= fontSize*0.1; // Just a vertical alignment tweak
if (vertical) {
text.attr("x", 0).attr("y", 0)
.attr("transform", "rotate(-90) translate(", -ty, " ", tx, ")");
} else {
text.attr("x", tx).attr("y", ty);
}
}
svg.write(text);
svg.raw("</text>");
}
protected:
Point2D drawAt;
double alignment = 0; // 0=centre, 1=left, -1=right
std::string text, cssClass;
bool vertical, isValue;
void layout(const PlotStyle &style) override {
double x = drawAt.x, y = drawAt.y;
double fontSize = isValue ? style.valueSize : style.labelSize;
// Assume all text/labels are UTF-8
textWidth = estimateUtf8Width(text.c_str())*fontSize*style.fontAspectRatio;
if (vertical) {
this->bounds = {x - fontSize*0.5, x + fontSize*0.5, y - textWidth*(alignment - 1)*0.5, y - textWidth*(alignment + 1)*0.5};
} else {
this->bounds = {x + textWidth*(alignment - 1)*0.5, x + textWidth*(alignment + 1)*0.5, y - fontSize*0.5, y + fontSize*0.5};
}
SvgDrawable::layout(style);
}
public:
TextLabel(Point2D at, double alignment, std::string text, std::string cssClass="svg-plot-label", bool vertical=false, bool isValue=false) : drawAt(at), alignment(alignment), text(text), cssClass(cssClass), vertical(vertical), isValue(isValue) {}
void writeLabel(SvgWriter &svg, const PlotStyle &style) override {
write(svg, isValue ? style.valueSize : style.labelSize);
}
};
/** A line on a 2D plot, with fill and/or stroke
\image html filled-circles.svg
*/
class Line2D : public SvgDrawable {
bool _drawLine = true;
bool _drawFill = false;
bool hasFillToX = false, hasFillToY = false;
Point2D fillToPoint;
Line2D *fillToLine = nullptr;
Axis &axisX, &axisY;
std::vector<Point2D> points;
struct Marker {
Point2D point;
int shape;
};
std::vector<Marker> markers;
struct Frame {
double time;
std::vector<Point2D> points;
std::vector<Marker> markers;
};
double framesLoopTime = 0;
std::vector<Frame> frames;
Point2D latest{0, 0};
template<class WriteValue>
void writeAnimationAttrs(SvgWriter &svg, WriteValue &&writeValue) {
double lastFrame = frames.back().time;
double framesEnd = std::max(framesLoopTime, lastFrame);