-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathjngen.h
7293 lines (5930 loc) · 179 KB
/
jngen.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
/*
Copyright (c) 2016-2018 Ivan Smirnov
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.
*/
/*
This file is automatically generated and is not supposed to be edited
directly. Source code can be found on https://github.com/ifsmirnov/jngen.
Follow the same link for docs and reference.
*/
#define JNGEN_VERSION 0.1
// https://github.com/ifsmirnov/jngen/issues/5
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wconversion"
// this warning is buggy in clang >= 5
#if __clang_major__ >= 5
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-lambda-capture"
#endif
#define JNGEN_DEFINE_CHAINING_TRAITS_FIELD(Class, name) \
int _ ## name = 0; \
Class& name(int val = 1) { _ ## name = val; return *this; }
#define JNGEN_CHAINING_TRAITS_INNER_0(Class)
#define JNGEN_CHAINING_TRAITS_INNER_1(Class, arg) JNGEN_DEFINE_CHAINING_TRAITS_FIELD(Class, arg)
#define JNGEN_CHAINING_TRAITS_INNER_2(Class, arg, ...) JNGEN_DEFINE_CHAINING_TRAITS_FIELD(Class, arg) JNGEN_CHAINING_TRAITS_INNER_1(Class, __VA_ARGS__)
#define JNGEN_CHAINING_TRAITS_INNER_3(Class, arg, ...) JNGEN_DEFINE_CHAINING_TRAITS_FIELD(Class, arg) JNGEN_CHAINING_TRAITS_INNER_2(Class, __VA_ARGS__)
#define JNGEN_CHAINING_TRAITS_INNER_4(Class, arg, ...) JNGEN_DEFINE_CHAINING_TRAITS_FIELD(Class, arg) JNGEN_CHAINING_TRAITS_INNER_3(Class, __VA_ARGS__)
#define JNGEN_CHAINING_TRAITS_INNER_5(Class, arg, ...) JNGEN_DEFINE_CHAINING_TRAITS_FIELD(Class, arg) JNGEN_CHAINING_TRAITS_INNER_4(Class, __VA_ARGS__)
#define JNGEN_CHAINING_TRAITS_INNER_6(Class, arg, ...) JNGEN_DEFINE_CHAINING_TRAITS_FIELD(Class, arg) JNGEN_CHAINING_TRAITS_INNER_5(Class, __VA_ARGS__)
#define JNGEN_CHAINING_TRAITS_INNER_7(Class, arg, ...) JNGEN_DEFINE_CHAINING_TRAITS_FIELD(Class, arg) JNGEN_CHAINING_TRAITS_INNER_6(Class, __VA_ARGS__)
#define JNGEN_CHAINING_TRAITS_INNER_8(Class, arg, ...) JNGEN_DEFINE_CHAINING_TRAITS_FIELD(Class, arg) JNGEN_CHAINING_TRAITS_INNER_7(Class, __VA_ARGS__)
#define JNGEN_CHAINING_TRAITS_INNER_9(Class, arg, ...) JNGEN_DEFINE_CHAINING_TRAITS_FIELD(Class, arg) JNGEN_CHAINING_TRAITS_INNER_8(Class, __VA_ARGS__)
#define JNGEN_CHAINING_TRAITS_INNER_10(Class, arg, ...) JNGEN_DEFINE_CHAINING_TRAITS_FIELD(Class, arg) JNGEN_CHAINING_TRAITS_INNER_9(Class, __VA_ARGS__)
#define JNGEN_CHAINING_TRAITS_INNER_11(Class, arg, ...) JNGEN_DEFINE_CHAINING_TRAITS_FIELD(Class, arg) JNGEN_CHAINING_TRAITS_INNER_10(Class, __VA_ARGS__)
#define JNGEN_CHAINING_TRAITS_INNER_12(Class, arg, ...) JNGEN_DEFINE_CHAINING_TRAITS_FIELD(Class, arg) JNGEN_CHAINING_TRAITS_INNER_11(Class, __VA_ARGS__)
#define JNGEN_CHAINING_TRAITS_INNER_13(Class, arg, ...) JNGEN_DEFINE_CHAINING_TRAITS_FIELD(Class, arg) JNGEN_CHAINING_TRAITS_INNER_12(Class, __VA_ARGS__)
#define JNGEN_CHAINING_TRAITS_INNER_14(Class, arg, ...) JNGEN_DEFINE_CHAINING_TRAITS_FIELD(Class, arg) JNGEN_CHAINING_TRAITS_INNER_13(Class, __VA_ARGS__)
#define JNGEN_CHAINING_TRAITS_INNER_15(Class, arg, ...) JNGEN_DEFINE_CHAINING_TRAITS_FIELD(Class, arg) JNGEN_CHAINING_TRAITS_INNER_14(Class, __VA_ARGS__)
#define JNGEN_CHAINING_TRAITS_INNER_16(Class, arg, ...) JNGEN_DEFINE_CHAINING_TRAITS_FIELD(Class, arg) JNGEN_CHAINING_TRAITS_INNER_15(Class, __VA_ARGS__)
#define JNGEN_CHAINING_TRAITS_INNER_17(Class, arg, ...) JNGEN_DEFINE_CHAINING_TRAITS_FIELD(Class, arg) JNGEN_CHAINING_TRAITS_INNER_16(Class, __VA_ARGS__)
#define JNGEN_CHAINING_TRAITS_INNER_18(Class, arg, ...) JNGEN_DEFINE_CHAINING_TRAITS_FIELD(Class, arg) JNGEN_CHAINING_TRAITS_INNER_17(Class, __VA_ARGS__)
#define JNGEN_CHAINING_TRAITS_INNER_19(Class, arg, ...) JNGEN_DEFINE_CHAINING_TRAITS_FIELD(Class, arg) JNGEN_CHAINING_TRAITS_INNER_18(Class, __VA_ARGS__)
#define JNGEN_CHAINING_TRAITS_INNER_20(Class, arg, ...) JNGEN_DEFINE_CHAINING_TRAITS_FIELD(Class, arg) JNGEN_CHAINING_TRAITS_INNER_19(Class, __VA_ARGS__)
#define JNGEN_GET_CHAINING_TRAITS_INNER_IMPL(p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, x, ...) x
#define JNGEN_GET_CHAINING_TRAITS_INNER(...) JNGEN_GET_CHAINING_TRAITS_INNER_IMPL(\
__VA_ARGS__,\
JNGEN_CHAINING_TRAITS_INNER_20,\
JNGEN_CHAINING_TRAITS_INNER_19,\
JNGEN_CHAINING_TRAITS_INNER_18,\
JNGEN_CHAINING_TRAITS_INNER_17,\
JNGEN_CHAINING_TRAITS_INNER_16,\
JNGEN_CHAINING_TRAITS_INNER_15,\
JNGEN_CHAINING_TRAITS_INNER_14,\
JNGEN_CHAINING_TRAITS_INNER_13,\
JNGEN_CHAINING_TRAITS_INNER_12,\
JNGEN_CHAINING_TRAITS_INNER_11,\
JNGEN_CHAINING_TRAITS_INNER_10,\
JNGEN_CHAINING_TRAITS_INNER_9,\
JNGEN_CHAINING_TRAITS_INNER_8,\
JNGEN_CHAINING_TRAITS_INNER_7,\
JNGEN_CHAINING_TRAITS_INNER_6,\
JNGEN_CHAINING_TRAITS_INNER_5,\
JNGEN_CHAINING_TRAITS_INNER_4,\
JNGEN_CHAINING_TRAITS_INNER_3,\
JNGEN_CHAINING_TRAITS_INNER_2,\
JNGEN_CHAINING_TRAITS_INNER_1,\
JNGEN_CHAINING_TRAITS_INNER_0)
#define JNGEN_CHAINING_TRAITS(Class, ...) \
struct Class { JNGEN_GET_CHAINING_TRAITS_INNER(__VA_ARGS__)(Class, __VA_ARGS__) };
namespace jngen {
struct Config {
bool generateLargeObjects = false;
bool largeOptionIndices = false;
bool normalizeEdges = true;
};
#ifdef JNGEN_DECLARE_ONLY
extern
#endif
Config config;
} // namespace jngen
using jngen::config;
#include <chrono>
#include <cstdlib>
#include <iostream>
#include <map>
#include <stdexcept>
#include <string>
#include <type_traits>
#include <vector>
#ifdef JNGEN_DECLARE_ONLY
#define JNGEN_EXTERN extern
#else
#define JNGEN_EXTERN
#endif
namespace jngen {
class Exception : public std::runtime_error {
public:
explicit Exception(const std::string& s) :
std::runtime_error("Assertion `" + s + "' failed.")
{ }
Exception(const std::string& assertMsg, const std::string& expl) :
std::runtime_error(expl + " (assertion `" + assertMsg + "' failed).")
{ }
};
class InternalException : public Exception {
public:
explicit InternalException(const std::string& s) : Exception(s) {}
InternalException(const std::string& assertMsg, const std::string& expl) :
Exception(assertMsg, expl)
{ }
};
} // namespace jngen
#define JNGEN_ENSURE1(exType, cond)\
do\
if (!(cond)) {\
throw exType(#cond);\
}\
while (false)
#define JNGEN_ENSURE2(exType, cond, msg)\
do\
if (!(cond)) {\
throw exType(#cond, msg);\
}\
while (false)
#define JNGEN_GET_MACRO(_1, _2, NAME, ...) NAME
#define ensure(...) JNGEN_GET_MACRO(__VA_ARGS__, JNGEN_ENSURE2, JNGEN_ENSURE1)\
(jngen::Exception, __VA_ARGS__)
#define ENSURE(...) JNGEN_GET_MACRO(__VA_ARGS__, JNGEN_ENSURE2, JNGEN_ENSURE1)\
(jngen::InternalException, __VA_ARGS__)
namespace jngen {
template<typename ... Args>
std::string format(const std::string& fmt, Args... args) {
constexpr static char BUF_SIZE = 64;
static char BUFFER[BUF_SIZE];
int bufSize = BUF_SIZE;
char *buf = BUFFER;
while (true) {
int ret = std::snprintf(buf, bufSize, fmt.c_str(), args...);
if (ret < bufSize) {
break;
}
if (bufSize != BUF_SIZE) {
delete[] buf;
}
bufSize *= 2;
buf = new char[bufSize];
}
std::string result(buf);
if (bufSize != BUF_SIZE) {
delete[] buf;
}
return result;
}
class ContextTimer {
public:
ContextTimer(const std::string& name) : name_(name) {
start_ = std::chrono::steady_clock::now();
}
ContextTimer() : ContextTimer("") {}
ContextTimer(const ContextTimer&) = delete;
ContextTimer& operator=(const ContextTimer&) = delete;
ContextTimer(ContextTimer&&) = delete;
ContextTimer& operator=(ContextTimer&&) = delete;
~ContextTimer() {
auto dif = std::chrono::steady_clock::now() - start_;
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(dif);
if (!name_.empty()) {
std::cerr << "[" << name_ << "] ";
}
std::cerr << ms.count() << " ms\n";
}
private:
std::string name_;
std::chrono::steady_clock::time_point start_;
};
template<typename F>
auto distribution(int n, F&& f) -> std::map<decltype(f()), int> {
std::map<decltype(f()), int> dist;
for (int i = 0; i < n; ++i) {
++dist[f()];
}
return dist;
}
inline void checkLargeParameter(int n) {
if (!config.generateLargeObjects) {
constexpr static int BOUND = 5e6;
ensure(
n <= BOUND,
"If you want to generate an object of size > 5'000'000, please set "
"'config.generateLargeObjects = true'.");
}
}
// Some type traits helpers. Based on ideas from TCPPPL v4.
template<bool B, typename T = void>
using enable_if_t = typename std::enable_if<B, T>::type;
template<typename T>
using decay_t = typename std::decay<T>::type;
namespace util {
inline long long gcd(long long a, long long b) {
if (a < 0) {
a = -a;
}
if (b < 0) {
b = -b;
}
while (a && b) {
if (a > b) {
a %= b;
} else {
b %= a;
}
}
return a + b;
}
inline std::vector<std::string> split(std::string s, char delimiter) {
auto strip = [](std::string s) {
size_t l = 0;
while (l < s.size() && s[l] == ' ') {
++l;
}
s = s.substr(l);
while (!s.empty() && s.back() == ' ') {
s.pop_back();
}
return s;
};
std::vector<std::string> result;
s += delimiter;
std::string cur;
for (char c: s) {
if (c == delimiter) {
result.push_back(strip(cur));
cur.clear();
} else {
cur += c;
}
}
return result;
}
} // namespace util
} // namespace jngen
using jngen::format;
using jngen::ContextTimer;
using jngen::distribution;
#include <string>
#include <utility>
#include <vector>
#include <string>
namespace jngen {
namespace drawing {
using Color = std::string;
struct DrawingEngineState {
double width;
Color stroke;
Color fill;
double opacity;
};
class DrawingEngine {
public:
DrawingEngine() {}
virtual ~DrawingEngine() {}
virtual void drawPoint(double x, double y) = 0;
virtual void drawCircle(double x, double y, double r) = 0;
virtual void drawSegment(double x1, double y1, double x2, double y2) = 0;
virtual void drawPolygon(
const std::vector<std::pair<double, double>>& vertices) = 0;
virtual void drawText(
double x, double y, const std::string& s) = 0;
virtual void setWidth(double width) = 0;
virtual void setStroke(Color color) = 0;
virtual void setFill(Color color) = 0;
virtual void setOpacity(double opacity) = 0;
virtual double width() const = 0;
virtual Color stroke() const = 0;
virtual Color fill() const = 0;
virtual double opacity() const = 0;
DrawingEngineState saveState() {
return { width(), stroke(), fill(), opacity() };
}
void restoreState(const DrawingEngineState& state) {
setWidth(state.width);
setStroke(state.stroke);
setFill(state.fill);
setOpacity(state.opacity);
}
};
}} // namespace jngen::drawing
#include <sstream>
#include <string>
namespace jngen {
namespace drawing {
class SvgEngine : public DrawingEngine {
public:
SvgEngine(double x1 = 0, double y1 = 0, double x2 = 50, double y2 = 50);
virtual ~SvgEngine() {}
virtual void drawPoint(double x, double y) override;
virtual void drawCircle(double x, double y, double r) override;
virtual void drawSegment(
double x1, double y1, double x2, double y2) override;
virtual void drawPolygon(
const std::vector<std::pair<double, double>>& vertices) override;
virtual void drawText(
double x, double y, const std::string& s) override;
virtual void setWidth(double width) override;
virtual void setStroke(Color color) override;
virtual void setFill(Color color) override;
virtual void setOpacity(double opacity) override;
virtual double width() const override { return width_; }
virtual Color stroke() const override { return strokeColor_; }
virtual Color fill() const override { return fillColor_; }
virtual double opacity() const override { return opacity_; }
std::string serialize() const;
private:
double lerpX(double x) const;
double lerpY(double y) const;
double scaleSize(double size) const;
std::string getStyle() const;
std::ostringstream output_;
double width_;
Color strokeColor_;
Color fillColor_;
double opacity_;
double x1_, y1_, x2_, y2_; // borders
};
}} // namespace jngen::drawing
#ifndef JNGEN_DECLARE_ONLY
#define JNGEN_INCLUDE_SVG_ENGINE_INL_H
#ifndef JNGEN_INCLUDE_SVG_ENGINE_INL_H
#error File "svg_engine_inl.h" must not be included directly.
#endif
#include <cmath>
#include <cstdlib>
namespace jngen {
namespace drawing {
static char buf[10000];
constexpr static double WIDTH_SCALE = 8;
constexpr static double CANVAS_SIZE = 2000;
constexpr static int FONT_SIZE = 64;
namespace {
const char* colorToString(const Color& color) {
const static char* NONE = "none";
if (color.empty()) {
return NONE;
}
return color.c_str();
}
// Given x \in [l, r], return linear interpolation to [L, R]
double lerp(double x, double l, double r, double L, double R) {
return L + (R - L) * ((x - l) / (r - l));
}
} // namespace
SvgEngine::SvgEngine(double x1, double y1, double x2, double y2) :
width_(1.0),
opacity_(1.0),
x1_(x1),
y1_(y1),
x2_(x2),
y2_(y2)
{ }
void SvgEngine::drawPoint(double x, double y) {
x = lerpX(x);
y = lerpY(y);
double w = width_ * WIDTH_SCALE * 1.5;
std::sprintf(
buf,
"<circle cx='%f' cy='%f' r='%f' fill='%s' opacity='%f'/>",
x, y, w, colorToString(strokeColor_), opacity_
);
output_ << buf << "\n";
}
void SvgEngine::drawCircle(double x, double y, double r) {
x = lerpX(x);
y = lerpY(y);
r = scaleSize(r);
std::sprintf(
buf,
"<circle cx='%f' cy='%f' r='%f' style='%s'/>",
x, y, r, getStyle().c_str()
);
output_ << buf << "\n";
}
void SvgEngine::drawPolygon(
const std::vector<std::pair<double, double>>& points)
{
output_ << "<polygon points='";
for (const auto& point: points) {
output_ << lerpX(point.first) << "," << lerpY(point.second) << " ";
}
output_ << "' style='" << getStyle() << "'/>\n";
}
void SvgEngine::drawSegment(
double x1, double y1, double x2, double y2)
{
x1 = lerpX(x1);
y1 = lerpY(y1);
x2 = lerpX(x2);
y2 = lerpY(y2);
if (std::fabs(x1 - x2) < 1e-9) {
x1 = std::round(x1);
x2 = std::round(x2);
}
if (std::fabs(y1 - y2) < 1e-9) {
y1 = std::round(y1);
y2 = std::round(y2);
}
std::sprintf(
buf,
"<line x1='%f' y1='%f' x2='%f' y2='%f' style='%s'/>",
x1, y1, x2, y2, getStyle().c_str()
);
output_ << buf << "\n";
}
void SvgEngine::drawText(
double x, double y, const std::string& s)
{
x = std::round(lerpX(x));
y = std::round(lerpY(y));
std::sprintf(
buf,
"<text x='%f' y='%f' font-size='%d' font-family='Helvetica'>%s</text>",
x, y, FONT_SIZE, s.c_str()
);
output_ << buf << "\n";
}
void SvgEngine::setWidth(double width) {
width_ = width;
}
void SvgEngine::setStroke(Color color) {
strokeColor_ = color;
}
void SvgEngine::setFill(Color color) {
fillColor_ = color;
}
void SvgEngine::setOpacity(double opacity) {
opacity_ = opacity;
}
std::string SvgEngine::serialize() const {
int offset = std::sprintf(
buf,
"<svg xmlns='http://www.w3.org/2000/svg' "
"viewBox='%f %f %f %f'>\n",
0.0, 0.0, CANVAS_SIZE, CANVAS_SIZE * (y2_ - y1_) / (x2_ - x1_)
);
std::sprintf(
buf + offset,
"<circle cx='%f' cy='%f' r='%f' fill='white'/>\n",
CANVAS_SIZE/2, CANVAS_SIZE/2,
std::hypot(CANVAS_SIZE, CANVAS_SIZE * (y2_ - y1_) / (x2_ - x1_))
);
return buf + output_.str() + "</svg>\n";
}
double SvgEngine::lerpX(double x) const {
return lerp(x, x1_, x2_, 0., CANVAS_SIZE);
}
double SvgEngine::lerpY(double y) const {
return lerp(y, y2_, y1_, 0., CANVAS_SIZE * (y2_ - y1_) / (x2_ - x1_));
}
double SvgEngine::scaleSize(double size) const {
return size * CANVAS_SIZE / (x2_ - x1_);
}
std::string SvgEngine::getStyle() const {
static char buf[1024];
std::sprintf(
buf,
"stroke-width:%f;stroke:%s;fill:%s;opacity:%f",
width_ * WIDTH_SCALE,
colorToString(strokeColor_),
colorToString(fillColor_),
opacity_
);
return buf;
}
}} // namespace jngen::drawing
#undef JNGEN_INCLUDE_SVG_ENGINE_INL_H
#endif // JNGEN_DECLARE_ONLY
#include <algorithm>
#include <cmath>
#include <fstream>
#include <functional>
#include <initializer_list>
#include <map>
#include <memory>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
namespace jngen {
namespace drawing {
class Drawer {
public:
Drawer();
template<typename P>
void point(const P& p);
template<typename T>
void point(T x, T y);
template<typename P>
void circle(const P& p, double radius);
template<typename T>
void circle(T x, T y, double radius);
template<typename P>
void segment(const P& p1, const P& p2);
template<typename T>
void segment(T x1, T y1, T x2, T y2);
template<typename P>
void polygon(const std::vector<P>& points);
template<typename P>
void polygon(std::initializer_list<P> points);
void setWidth(double width);
void setColor(const std::string& color);
void setStroke(const std::string& color);
void setFill(const std::string& color);
void setOpacity(double opacity);
void enableGrid(bool value) {
gridEnabled_ = value;
}
void dumpSvg(const std::string& filename);
private:
struct Point {
double x, y;
Point() {}
Point(double x, double y) : x(x), y(y) {}
};
template<typename T>
Point extractCoords(const T& pt) {
return Point(pt.x, pt.y);
}
template<typename T>
Point extractCoords(const std::pair<T, T>& pt) {
return Point(pt.first, pt.second);
}
typedef std::function<void(DrawingEngine*)> DrawRequest;
typedef std::pair<Point, Point> Bbox;
static Bbox emptyBbox();
static Bbox unite(const Bbox& lhs, const Bbox& rhs);
static Bbox bbox(const Point& p);
static Bbox bbox(const std::pair<Point, double>& circle);
Bbox getBbox() const;
static Bbox viewportByBbox(const Bbox& bbox);
void drawAll();
void drawGrid(const Bbox& bbox);
std::vector<DrawRequest> requests_;
DrawingEngine* engine_;
Bbox bbox_;
int requestId_ = 0;
bool gridEnabled_ = true;
};
template<typename P>
void Drawer::point(const P& p_) {
Point p = extractCoords(p_);
bbox_ = unite(bbox_ , bbox(Point(p.x, p.y)));
requests_.push_back([p](DrawingEngine* engine) {
engine->drawPoint(p.x, p.y);
});
}
template<typename T>
void Drawer::point(T x, T y) {
point(Point(x, y));
}
template<typename P>
void Drawer::circle(const P& p_, double radius) {
Point p = extractCoords(p_);
bbox_ = unite(bbox_ , bbox({Point(p.x, p.y), radius}));
requests_.push_back([p, radius](DrawingEngine* engine) {
engine->drawCircle(p.x, p.y, radius);
});
}
template<typename T>
void Drawer::circle(T x, T y, double radius) {
circle(Point(x, y), radius);
}
template<typename P>
void Drawer::segment(const P& p1_, const P& p2_) {
Point p1 = extractCoords(p1_);
Point p2 = extractCoords(p2_);
bbox_ = unite(bbox_ , bbox(Point(p1.x, p1.y)));
bbox_ = unite(bbox_ , bbox(Point(p2.x, p2.y)));
requests_.push_back([p1, p2](DrawingEngine* engine) {
engine->drawSegment(p1.x, p1.y, p2.x, p2.y);
});
}
template<typename T>
void Drawer::segment(T x1, T y1, T x2, T y2) {
segment(Point(x1, y1), Point(x2, y2));
}
template<typename P>
void Drawer::polygon(const std::vector<P>& points) {
for (const auto& p: points) {
bbox_ = unite(bbox_, bbox(extractCoords(p)));
}
requests_.push_back([points, this](DrawingEngine* engine) {
std::vector<std::pair<double, double>> enginePoints;
for (const auto& p: points) {
Point pt = extractCoords(p);
enginePoints.emplace_back(pt.x, pt.y);
}
engine->drawPolygon(enginePoints);
});
}
template<typename P>
void Drawer::polygon(std::initializer_list<P> points) {
polygon(std::vector<P>(points.begin(), points.end()));
}
#ifndef JNGEN_DECLARE_ONLY
Drawer::Drawer() : bbox_(emptyBbox()) {
setFill("");
setStroke("black");
}
void Drawer::setWidth(double width) {
requests_.push_back([width](DrawingEngine* engine) {
engine->setWidth(width);
});
}
void Drawer::setColor(const std::string& color) {
setStroke(color);
setFill(color);
}
void Drawer::setStroke(const std::string& color) {
requests_.push_back([color](DrawingEngine* engine) {
engine->setStroke(color);
});
}
void Drawer::setFill(const std::string& color) {
requests_.push_back([color](DrawingEngine* engine) {
engine->setFill(color);
});
}
void Drawer::setOpacity(double opacity) {
requests_.push_back([opacity](DrawingEngine* engine) {
engine->setOpacity(opacity);
});
}
Drawer::Bbox Drawer::emptyBbox() {
const static double inf = 1e18;
return { Point{inf, inf}, Point{-inf, -inf} };
}
Drawer::Bbox Drawer::unite(const Bbox& lhs, const Bbox& rhs) {
return Bbox{
Point{
std::min(lhs.first.x, rhs.first.x),
std::min(lhs.first.y, rhs.first.y)},
Point{
std::max(lhs.second.x, rhs.second.x),
std::max(lhs.second.y, rhs.second.y)}
};
}
Drawer::Bbox Drawer::bbox(const Point& p) {
return {p, p};
}
Drawer::Bbox Drawer::bbox(const std::pair<Point, double>& circle) {
Point p;
double radius;
std::tie(p, radius) = circle;
return {
Point{p.x - radius, p.y - radius},
Point{p.x + radius, p.y + radius}
};
}
/*
Given a bbox of points, returns a bbox with following properties:
- at least 5% margin at each side is blank
- side lengths differ by at most 1.6
- side length is at least 10
- if it is possible to include (0, 0), include it explicitly
*/
Drawer::Bbox Drawer::viewportByBbox(const Bbox& bbox) {
constexpr static double MIN_SIZE = 10.0;
constexpr static double MAX_RATIO = 1.6;
constexpr static double MARGIN_RATIO = 0.05;
constexpr static double MAX_RELATIVE_DISTANCE_TO_ZERO = 0.2;
double lx = bbox.first.x;
double rx = bbox.second.x;
double ly = bbox.first.y;
double ry = bbox.second.y;
auto extendToSize = [&](double& l, double &r, double size) {
double shift = (size - (r - l)) / 2;
l -= shift;
r += shift;
};
auto extendInterval = [&](double& l, double &r) {
if (r - l < MIN_SIZE) {
if (l >= -1e-9 && r < MIN_SIZE) {
l = 0;
r = MIN_SIZE;
} else if (r <= 1e-9 && l >= -MIN_SIZE) {
l = -MIN_SIZE;
r = 0;
} else {
extendToSize(l, r, MIN_SIZE);
}
}
if ((l > 0 || r < 0) && std::min(std::abs(l), std::abs(r)) <=
(r - l) * MAX_RELATIVE_DISTANCE_TO_ZERO)
{
if (l > 0) {
l = 0;
} else {
r = 0;
}
}
double margin = (r - l) * MARGIN_RATIO;
l -= margin;
r += margin;
};
extendInterval(lx, rx);
extendInterval(ly, ry);
if ((rx - lx) / (ry - ly) > MAX_RATIO) {
extendToSize(ly, ry, (rx - lx) / MAX_RATIO);
} else if ((ry - ly) / (rx - lx) > MAX_RATIO) {
extendToSize(lx, rx, (ry - ly) / MAX_RATIO);
}
return { Point(lx, ly), Point(rx, ry) };
}
void Drawer::drawAll() {
for (const auto& request: requests_) {
request(engine_);
}
}
void Drawer::drawGrid(const Bbox& bbox) {
const static std::vector<int> STEP_DELTA = {20, 25, 20};
// Step goes like 1, 2, 5, 10, 20, 50, 100, ...
constexpr static int SMALL_IN_BIG = 5;
constexpr static int THRESHOLD = 8;
constexpr static int MAX_SPREAD_TO_DRAW_ALL_TICKS = 13;
constexpr static double TEXT_OFFSET_RATIO = 0.01;
auto savedState = engine_->saveState();
int step = 5;
double spread = std::min(
bbox.second.x - bbox.first.x,
bbox.second.y - bbox.first.y);
size_t deltaPos = 2;
while (spread / step > THRESHOLD) {
step = step * STEP_DELTA[deltaPos] / 10;
if (++deltaPos == STEP_DELTA.size()) {
deltaPos = 0;
}
}
engine_->setWidth(0.5);
engine_->setStroke("lightgrey");
double smallStep = 1.0 * step / SMALL_IN_BIG;
for (
double tick = std::ceil(bbox.first.x / smallStep) * smallStep;
tick < bbox.second.x;
tick += smallStep)
{
if (std::lround(tick) % step != 0) {
engine_->drawSegment(tick, bbox.first.y, tick, bbox.second.y);
}
}
for (
double tick = std::ceil(bbox.first.y / smallStep) * smallStep;
tick < bbox.second.y;
tick += smallStep)
{
if (std::lround(tick) % step != 0) {
engine_->drawSegment(bbox.first.x, tick, bbox.second.x, tick);
}
}
engine_->setWidth(0.75);
engine_->setStroke("grey");
for (
double tick = std::ceil(bbox.first.x / step) * step;
tick < bbox.second.x;
tick += step)
{
engine_->drawSegment(tick, bbox.first.y, tick, bbox.second.y);
}
for (
double tick = std::ceil(bbox.first.y / step) * step;
tick < bbox.second.y;
tick += step)
{
engine_->drawSegment(bbox.first.x, tick, bbox.second.x, tick);
}
const double textOffsetX =
(bbox.second.x - bbox.first.x) * TEXT_OFFSET_RATIO;
const double textOffsetY =
(bbox.second.y - bbox.first.y) * TEXT_OFFSET_RATIO;
auto format = [](double x) {
static char buf[10];
std::sprintf(buf, "%d", int(std::lround(x)));
return std::string(buf);
};
if (spread < MAX_SPREAD_TO_DRAW_ALL_TICKS) {
step = 1;
}
for (
double tick = std::ceil(bbox.first.y / step) * step;
tick < bbox.second.y;
tick += step)
{
engine_->drawText(
bbox.first.x + textOffsetX, tick + textOffsetX, format(tick));
}
for (
double tick = std::ceil(bbox.first.x / step) * step;
tick < bbox.second.x;
tick += step)
{
engine_->drawText(
tick + textOffsetY, bbox.first.y + textOffsetY, format(tick));
}