forked from matplotlib/matplotlib
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_backend_agg.cpp
More file actions
1715 lines (1416 loc) · 48.8 KB
/
_backend_agg.cpp
File metadata and controls
1715 lines (1416 loc) · 48.8 KB
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
/* A rewrite of _backend_agg using PyCXX to handle ref counting, etc..
*/
#include <iostream>
#include <fstream>
#include <cmath>
#include <cstdio>
#include <stdexcept>
#include <png.h>
#include <time.h>
#include <algorithm>
#include "agg_conv_curve.h"
#include "agg_conv_transform.h"
#include "agg_image_accessors.h"
#include "agg_renderer_primitives.h"
#include "agg_scanline_storage_aa.h"
#include "agg_scanline_storage_bin.h"
#include "agg_span_allocator.h"
#include "agg_span_image_filter_gray.h"
#include "agg_span_image_filter_rgba.h"
#include "agg_span_interpolator_linear.h"
#include "util/agg_color_conv_rgb8.h"
#include "ft2font.h"
#include "_image.h"
#include "_backend_agg.h"
#include "mplutils.h"
#include "swig_runtime.h"
#include "MPL_isnan.h"
#define PY_ARRAY_TYPES_PREFIX NumPy
#include "numpy/arrayobject.h"
#include "agg_py_transforms.h"
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
#ifndef M_PI_4
#define M_PI_4 0.785398163397448309616
#endif
#ifndef M_PI_2
#define M_PI_2 1.57079632679489661923
#endif
/*
Convert dashes from the Python representation as nested sequences to
the C++ representation as a std::vector<std::pair<double, double> >
(GCAgg::dash_t)
*/
void convert_dashes(const Py::Tuple& dashes, double dpi, GCAgg::dash_t& dashes_out,
double& dashOffset_out) {
if (dashes.length()!=2)
throw Py::ValueError(Printf("Dash descriptor must be a length 2 tuple; found %d", dashes.length()).str());
dashes_out.clear();
dashOffset_out = 0.0;
if (dashes[0].ptr() == Py_None)
return;
dashOffset_out = double(Py::Float(dashes[0])) * dpi/72.0;
Py::SeqBase<Py::Object> dashSeq = dashes[1];
size_t Ndash = dashSeq.length();
if (Ndash % 2 != 0)
throw Py::ValueError(Printf("Dash sequence must be an even length sequence; found %d", Ndash).str());
dashes_out.clear();
dashes_out.reserve(Ndash / 2);
double val0, val1;
for (size_t i = 0; i < Ndash; i += 2) {
val0 = double(Py::Float(dashSeq[i])) * dpi/72.0;
val1 = double(Py::Float(dashSeq[i+1])) * dpi/72.0;
dashes_out.push_back(std::make_pair(val0, val1));
}
}
Py::Object BufferRegion::to_string(const Py::Tuple &args) {
// owned=true to prevent memory leak
return Py::String(PyString_FromStringAndSize((const char*)data, height*stride), true);
}
template<class VertexSource> class conv_quantize
{
public:
conv_quantize(VertexSource& source, bool quantize) :
m_source(&source), m_quantize(quantize) {}
void rewind(unsigned path_id) {
m_source->rewind(path_id);
}
unsigned vertex(double* x, double* y) {
unsigned cmd = m_source->vertex(x, y);
if (m_quantize && agg::is_vertex(cmd)) {
*x = round(*x) + 0.5;
*y = round(*y) + 0.5;
}
return cmd;
}
private:
VertexSource* m_source;
bool m_quantize;
};
GCAgg::GCAgg(const Py::Object &gc, double dpi) :
dpi(dpi), isaa(true), linewidth(1.0), alpha(1.0),
dashOffset(0.0)
{
_VERBOSE("GCAgg::GCAgg");
linewidth = points_to_pixels ( gc.getAttr("_linewidth") ) ;
alpha = Py::Float( gc.getAttr("_alpha") );
color = get_color(gc);
_set_antialiased(gc);
_set_linecap(gc);
_set_joinstyle(gc);
_set_dashes(gc);
_set_clip_rectangle(gc);
_set_clip_path(gc);
}
GCAgg::GCAgg(double dpi) :
dpi(dpi), isaa(true), linewidth(1.0), alpha(1.0),
dashOffset(0.0)
{
}
void
GCAgg::_set_antialiased(const Py::Object& gc) {
_VERBOSE("GCAgg::antialiased");
isaa = Py::Int( gc.getAttr( "_antialiased") );
}
agg::rgba
GCAgg::get_color(const Py::Object& gc) {
_VERBOSE("GCAgg::get_color");
Py::Tuple rgb = Py::Tuple( gc.getAttr("_rgb") );
double alpha = Py::Float( gc.getAttr("_alpha") );
double r = Py::Float(rgb[0]);
double g = Py::Float(rgb[1]);
double b = Py::Float(rgb[2]);
return agg::rgba(r, g, b, alpha);
}
double
GCAgg::points_to_pixels( const Py::Object& points) {
_VERBOSE("GCAgg::points_to_pixels");
double p = Py::Float( points ) ;
return p * dpi/72.0;
}
void
GCAgg::_set_linecap(const Py::Object& gc) {
_VERBOSE("GCAgg::_set_linecap");
std::string capstyle = Py::String( gc.getAttr( "_capstyle" ) );
if (capstyle=="butt")
cap = agg::butt_cap;
else if (capstyle=="round")
cap = agg::round_cap;
else if(capstyle=="projecting")
cap = agg::square_cap;
else
throw Py::ValueError(Printf("GC _capstyle attribute must be one of butt, round, projecting; found %s", capstyle.c_str()).str());
}
void
GCAgg::_set_joinstyle(const Py::Object& gc) {
_VERBOSE("GCAgg::_set_joinstyle");
std::string joinstyle = Py::String( gc.getAttr("_joinstyle") );
if (joinstyle=="miter")
join = agg::miter_join;
else if (joinstyle=="round")
join = agg::round_join;
else if(joinstyle=="bevel")
join = agg::bevel_join;
else
throw Py::ValueError(Printf("GC _joinstyle attribute must be one of butt, round, projecting; found %s", joinstyle.c_str()).str());
}
void
GCAgg::_set_dashes(const Py::Object& gc) {
//return the dashOffset, dashes sequence tuple.
_VERBOSE("GCAgg::_set_dashes");
Py::Object dash_obj( gc.getAttr( "_dashes" ) );
if (dash_obj.ptr() == Py_None) {
dashes.clear();
return;
}
convert_dashes(dash_obj, dpi, dashes, dashOffset);
}
void
GCAgg::_set_clip_rectangle( const Py::Object& gc) {
//set the clip rectangle from the gc
_VERBOSE("GCAgg::_set_clip_rectangle");
Py::Object o ( gc.getAttr( "_cliprect" ) );
cliprect = o;
}
void
GCAgg::_set_clip_path( const Py::Object& gc) {
//set the clip path from the gc
_VERBOSE("GCAgg::_set_clip_path");
Py::Object method_obj = gc.getAttr("get_clip_path");
Py::Callable method(method_obj);
Py::Tuple path_and_transform = method.apply(Py::Tuple());
if (path_and_transform[0].ptr() != Py_None) {
clippath = path_and_transform[0];
clippath_trans = py_to_agg_transformation_matrix(path_and_transform[1]);
}
}
const size_t
RendererAgg::PIXELS_PER_INCH(96);
RendererAgg::RendererAgg(unsigned int width, unsigned int height, double dpi,
int debug) :
width(width),
height(height),
dpi(dpi),
NUMBYTES(width*height*4),
debug(debug)
{
_VERBOSE("RendererAgg::RendererAgg");
unsigned stride(width*4);
pixBuffer = new agg::int8u[NUMBYTES];
renderingBuffer = new agg::rendering_buffer;
renderingBuffer->attach(pixBuffer, width, height, stride);
alphaBuffer = new agg::int8u[NUMBYTES];
alphaMaskRenderingBuffer = new agg::rendering_buffer;
alphaMaskRenderingBuffer->attach(alphaBuffer, width, height, stride);
alphaMask = new alpha_mask_type(*alphaMaskRenderingBuffer);
//jdh
pixfmtAlphaMask = new agg::pixfmt_gray8(*alphaMaskRenderingBuffer);
rendererBaseAlphaMask = new renderer_base_alpha_mask_type(*pixfmtAlphaMask);
rendererAlphaMask = new renderer_alpha_mask_type(*rendererBaseAlphaMask);
scanlineAlphaMask = new agg::scanline_p8();
slineP8 = new scanline_p8;
slineBin = new scanline_bin;
pixFmt = new pixfmt(*renderingBuffer);
rendererBase = new renderer_base(*pixFmt);
rendererBase->clear(agg::rgba(1, 1, 1, 0));
rendererAA = new renderer_aa(*rendererBase);
rendererBin = new renderer_bin(*rendererBase);
theRasterizer = new rasterizer();
//theRasterizer->filling_rule(agg::fill_even_odd);
//theRasterizer->filling_rule(agg::fill_non_zero);
};
template<class R>
void
RendererAgg::set_clipbox(const Py::Object& cliprect, R rasterizer) {
//set the clip rectangle from the gc
_VERBOSE("RendererAgg::set_clipbox");
double l, b, r, t;
if (py_convert_bbox(cliprect.ptr(), l, b, r, t)) {
rasterizer->clip_box(int(round(l)) + 1, height - int(round(b)),
int(round(r)), height - int(round(t)));
}
_VERBOSE("RendererAgg::set_clipbox done");
}
std::pair<bool, agg::rgba>
RendererAgg::_get_rgba_face(const Py::Object& rgbFace, double alpha) {
_VERBOSE("RendererAgg::_get_rgba_face");
std::pair<bool, agg::rgba> face;
if (rgbFace.ptr() == Py_None) {
face.first = false;
}
else {
face.first = true;
Py::Tuple rgb = Py::Tuple(rgbFace);
face.second = rgb_to_color(rgb, alpha);
}
return face;
}
SnapData
SafeSnap::snap (const float& x, const float& y) {
xsnap = (int)x + 0.5;
ysnap = (int)y + 0.5;
if ( first || ( (xsnap!=lastxsnap) || (ysnap!=lastysnap) ) ) {
lastxsnap = xsnap;
lastysnap = ysnap;
lastx = x;
lasty = y;
first = false;
return SnapData(true, xsnap, ysnap);
}
// ok both are equal and we need to do an offset
if ( (x==lastx) && (y==lasty) ) {
// no choice but to return equal coords; set newpoint = false
lastxsnap = xsnap;
lastysnap = ysnap;
lastx = x;
lasty = y;
return SnapData(false, xsnap, ysnap);
}
// ok the real points are not identical but the rounded ones, so do
// a one pixel offset
if (x>lastx) xsnap += 1.;
else if (x<lastx) xsnap -= 1.;
if (y>lasty) ysnap += 1.;
else if (y<lasty) ysnap -= 1.;
lastxsnap = xsnap;
lastysnap = ysnap;
lastx = x;
lasty = y;
return SnapData(true, xsnap, ysnap);
}
template<class Path>
bool should_snap(Path& path, const agg::trans_affine& trans) {
// If this contains only straight horizontal or vertical lines, quantize to nearest
// pixels
double x0, y0, x1, y1;
unsigned code;
if (path.total_vertices() > 5)
return false;
code = path.vertex(&x0, &y0);
trans.transform(&x0, &y0);
while ((code = path.vertex(&x1, &y1)) != agg::path_cmd_stop) {
trans.transform(&x1, &y1);
switch (code) {
case agg::path_cmd_curve3:
case agg::path_cmd_curve4:
path.rewind(0);
return false;
case agg::path_cmd_line_to:
if (!(fabs(x0 - x1) < 1e-4 || fabs(y0 - y1) < 1e-4)) {
path.rewind(0);
return false;
}
}
x0 = x1;
y0 = y1;
}
path.rewind(0);
return true;
}
Py::Object
RendererAgg::copy_from_bbox(const Py::Tuple& args) {
//copy region in bbox to buffer and return swig/agg buffer object
args.verify_length(1);
Py::Object box_obj = args[0];
double l, b, r, t;
if (!py_convert_bbox(box_obj.ptr(), l, b, r, t))
throw Py::TypeError("Invalid bbox provided to copy_from_bbox");
agg::rect_i rect((int)l, height - (int)t, (int)r, height - (int)b);
BufferRegion* reg = NULL;
try {
reg = new BufferRegion(rect, true);
} catch (...) {
throw Py::MemoryError("RendererAgg::copy_from_bbox could not allocate memory for buffer");
}
if (!reg) {
throw Py::MemoryError("RendererAgg::copy_from_bbox could not allocate memory for buffer");
}
agg::rendering_buffer rbuf;
rbuf.attach(reg->data, reg->width, reg->height, reg->stride);
pixfmt pf(rbuf);
renderer_base rb(pf);
rb.copy_from(*renderingBuffer, &rect, -rect.x1, -rect.y1);
return Py::asObject(reg);
}
Py::Object
RendererAgg::restore_region(const Py::Tuple& args) {
//copy BufferRegion to buffer
args.verify_length(1);
BufferRegion* region = static_cast<BufferRegion*>(args[0].ptr());
if (region->data==NULL)
return Py::Object();
//throw Py::ValueError("Cannot restore_region from NULL data");
agg::rendering_buffer rbuf;
rbuf.attach(region->data,
region->width,
region->height,
region->stride);
rendererBase->copy_from(rbuf, 0, region->rect.x1, region->rect.y1);
return Py::Object();
}
bool RendererAgg::render_clippath(const Py::Object& clippath, const agg::trans_affine& clippath_trans) {
typedef agg::conv_transform<PathIterator> transformed_path_t;
typedef agg::conv_curve<transformed_path_t> curve_t;
bool has_clippath = (clippath.ptr() != Py_None);
if (has_clippath &&
(clippath.ptr() != lastclippath.ptr() ||
clippath_trans != lastclippath_transform)) {
agg::trans_affine trans(clippath_trans);
trans *= agg::trans_affine_scaling(1.0, -1.0);
trans *= agg::trans_affine_translation(0.0, (double)height);
PathIterator clippath_iter(clippath);
rendererBaseAlphaMask->clear(agg::gray8(0, 0));
transformed_path_t transformed_clippath(clippath_iter, trans);
agg::conv_curve<transformed_path_t> curved_clippath(transformed_clippath);
theRasterizer->add_path(curved_clippath);
rendererAlphaMask->color(agg::gray8(255, 255));
agg::render_scanlines(*theRasterizer, *scanlineAlphaMask, *rendererAlphaMask);
lastclippath = clippath;
lastclippath_transform = clippath_trans;
}
return has_clippath;
}
#define MARKER_CACHE_SIZE 512
Py::Object
RendererAgg::draw_markers(const Py::Tuple& args) {
typedef agg::conv_transform<PathIterator> transformed_path_t;
typedef conv_quantize<transformed_path_t> quantize_t;
typedef agg::conv_curve<transformed_path_t> curve_t;
typedef agg::conv_stroke<curve_t> stroke_t;
typedef agg::pixfmt_amask_adaptor<pixfmt, alpha_mask_type> pixfmt_amask_type;
typedef agg::renderer_base<pixfmt_amask_type> amask_ren_type;
typedef agg::renderer_scanline_aa_solid<amask_ren_type> amask_aa_renderer_type;
typedef agg::renderer_scanline_bin_solid<amask_ren_type> amask_bin_renderer_type;
args.verify_length(5, 6);
Py::Object gc_obj = args[0];
Py::Object marker_path_obj = args[1];
agg::trans_affine marker_trans = py_to_agg_transformation_matrix(args[2]);
Py::Object path_obj = args[3];
agg::trans_affine trans = py_to_agg_transformation_matrix(args[4]);
Py::Object face_obj;
if (args.size() == 6)
face_obj = args[5];
// Deal with the difference in y-axis direction
marker_trans *= agg::trans_affine_scaling(1.0, -1.0);
trans *= agg::trans_affine_scaling(1.0, -1.0);
trans *= agg::trans_affine_translation(0.0, (double)height);
PathIterator marker_path(marker_path_obj);
transformed_path_t marker_path_transformed(marker_path, marker_trans);
curve_t marker_path_curve(marker_path_transformed);
PathIterator path(path_obj);
bool snap = should_snap(path, trans);
transformed_path_t path_transformed(path, trans);
GCAgg gc = GCAgg(gc_obj, dpi);
quantize_t path_quantized(path_transformed, snap);
path_quantized.rewind(0);
facepair_t face = _get_rgba_face(face_obj, gc.alpha);
//maxim's suggestions for cached scanlines
agg::scanline_storage_aa8 scanlines;
theRasterizer->reset();
theRasterizer->reset_clipping();
rendererBase->reset_clipping(true);
agg::int8u staticFillCache[MARKER_CACHE_SIZE];
agg::int8u staticStrokeCache[MARKER_CACHE_SIZE];
agg::int8u* fillCache = NULL;
agg::int8u* strokeCache = NULL;
try {
unsigned fillSize = 0;
if (face.first) {
theRasterizer->add_path(marker_path_curve);
agg::render_scanlines(*theRasterizer, *slineP8, scanlines);
fillSize = scanlines.byte_size();
if (fillSize < MARKER_CACHE_SIZE)
fillCache = staticFillCache;
else
fillCache = new agg::int8u[fillSize];
scanlines.serialize(fillCache);
}
stroke_t stroke(marker_path_curve);
stroke.width(gc.linewidth);
stroke.line_cap(gc.cap);
stroke.line_join(gc.join);
theRasterizer->reset();
theRasterizer->add_path(stroke);
agg::render_scanlines(*theRasterizer, *slineP8, scanlines);
unsigned strokeSize = scanlines.byte_size();
if (strokeSize < MARKER_CACHE_SIZE)
strokeCache = staticStrokeCache;
else
strokeCache = new agg::int8u[strokeSize];
scanlines.serialize(strokeCache);
theRasterizer->reset_clipping();
rendererBase->reset_clipping(true);
set_clipbox(gc.cliprect, rendererBase);
bool has_clippath = render_clippath(gc.clippath, gc.clippath_trans);
double x, y;
agg::serialized_scanlines_adaptor_aa8 sa;
agg::serialized_scanlines_adaptor_aa8::embedded_scanline sl;
if (has_clippath) {
while (path_quantized.vertex(&x, &y) != agg::path_cmd_stop) {
pixfmt_amask_type pfa(*pixFmt, *alphaMask);
amask_ren_type r(pfa);
amask_aa_renderer_type ren(r);
if (face.first) {
ren.color(face.second);
sa.init(fillCache, fillSize, x, y);
agg::render_scanlines(sa, sl, ren);
}
ren.color(gc.color);
sa.init(strokeCache, strokeSize, x, y);
agg::render_scanlines(sa, sl, ren);
}
} else {
while (path_quantized.vertex(&x, &y) != agg::path_cmd_stop) {
if (face.first) {
rendererAA->color(face.second);
sa.init(fillCache, fillSize, x, y);
agg::render_scanlines(sa, sl, *rendererAA);
}
rendererAA->color(gc.color);
sa.init(strokeCache, strokeSize, x, y);
agg::render_scanlines(sa, sl, *rendererAA);
}
}
} catch(...) {
if (fillCache != staticFillCache)
delete[] fillCache;
if (strokeCache != staticStrokeCache)
delete[] strokeCache;
throw;
}
if (fillCache != staticFillCache)
delete[] fillCache;
if (strokeCache != staticStrokeCache)
delete[] strokeCache;
return Py::Object();
}
/**
* This is a custom span generator that converts spans in the
* 8-bit inverted greyscale font buffer to rgba that agg can use.
*/
template<class ChildGenerator>
class font_to_rgba
{
public:
typedef ChildGenerator child_type;
typedef agg::rgba8 color_type;
typedef typename child_type::color_type child_color_type;
typedef agg::span_allocator<child_color_type> span_alloc_type;
private:
child_type* _gen;
color_type _color;
span_alloc_type _allocator;
public:
font_to_rgba(child_type* gen, color_type color) :
_gen(gen),
_color(color) {
}
void generate(color_type* output_span, int x, int y, unsigned len)
{
_allocator.allocate(len);
child_color_type* input_span = _allocator.span();
_gen->generate(input_span, x, y, len);
do {
*output_span = _color;
output_span->a = input_span->v;
++output_span;
++input_span;
} while (--len);
}
void prepare()
{
_gen->prepare();
}
};
// MGDTODO: Support clip paths
Py::Object
RendererAgg::draw_text_image(const Py::Tuple& args) {
_VERBOSE("RendererAgg::draw_text");
typedef agg::span_allocator<agg::gray8> gray_span_alloc_type;
typedef agg::span_allocator<agg::rgba8> color_span_alloc_type;
typedef agg::span_interpolator_linear<> interpolator_type;
typedef agg::image_accessor_clip<agg::pixfmt_gray8> image_accessor_type;
typedef agg::span_image_filter_gray_2x2<image_accessor_type, interpolator_type>
image_span_gen_type;
typedef font_to_rgba<image_span_gen_type> span_gen_type;
typedef agg::renderer_scanline_aa<renderer_base, color_span_alloc_type, span_gen_type>
renderer_type;
args.verify_length(5);
FT2Image *image = static_cast<FT2Image*>(args[0].ptr());
if (!image->get_buffer())
return Py::Object();
int x(0),y(0);
try {
x = Py::Int( args[1] );
y = Py::Int( args[2] );
}
catch (Py::TypeError) {
//x,y out of range; todo issue warning?
return Py::Object();
}
double angle = Py::Float( args[3] );
GCAgg gc = GCAgg(args[4], dpi);
theRasterizer->reset_clipping();
rendererBase->reset_clipping(true);
set_clipbox(gc.cliprect, theRasterizer);
const unsigned char* const buffer = image->get_buffer();
agg::rendering_buffer srcbuf
((agg::int8u*)buffer, image->get_width(),
image->get_height(), image->get_width());
agg::pixfmt_gray8 pixf_img(srcbuf);
agg::trans_affine mtx;
mtx *= agg::trans_affine_translation(0, -(int)image->get_height());
mtx *= agg::trans_affine_rotation(-angle * agg::pi / 180.0);
mtx *= agg::trans_affine_translation(x, y);
agg::path_storage rect;
rect.move_to(0, 0);
rect.line_to(image->get_width(), 0);
rect.line_to(image->get_width(), image->get_height());
rect.line_to(0, image->get_height());
rect.line_to(0, 0);
agg::conv_transform<agg::path_storage> rect2(rect, mtx);
agg::trans_affine inv_mtx(mtx);
inv_mtx.invert();
agg::image_filter_lut filter;
filter.calculate(agg::image_filter_spline16());
interpolator_type interpolator(inv_mtx);
color_span_alloc_type sa;
image_accessor_type ia(pixf_img, 0);
image_span_gen_type image_span_generator(ia, interpolator, filter);
span_gen_type output_span_generator(&image_span_generator, gc.color);
renderer_type ri(*rendererBase, sa, output_span_generator);
theRasterizer->add_path(rect2);
agg::render_scanlines(*theRasterizer, *slineP8, ri);
return Py::Object();
}
// MGDTODO: Support clip paths
Py::Object
RendererAgg::draw_image(const Py::Tuple& args) {
_VERBOSE("RendererAgg::draw_image");
args.verify_length(4, 6);
float x = Py::Float(args[0]);
float y = Py::Float(args[1]);
Image *image = static_cast<Image*>(args[2].ptr());
Py::Object box_obj = args[3];
Py::Object clippath;
agg::trans_affine clippath_trans;
if (args.size() == 6) {
clippath = args[4];
clippath_trans = py_to_agg_transformation_matrix(args[5], false);
}
theRasterizer->reset_clipping();
rendererBase->reset_clipping(true);
set_clipbox(box_obj, rendererBase);
Py::Tuple empty;
pixfmt pixf(*(image->rbufOut));
image->flipud_out(empty);
rendererBase->blend_from(pixf, 0, (int)x, (int)(height-(y+image->rowsOut)));
image->flipud_out(empty);
return Py::Object();
}
template<class path_t>
void RendererAgg::_draw_path(path_t& path, bool has_clippath,
const facepair_t& face, const GCAgg& gc) {
typedef agg::conv_stroke<path_t> stroke_t;
typedef agg::conv_dash<path_t> dash_t;
typedef agg::conv_stroke<dash_t> stroke_dash_t;
typedef agg::pixfmt_amask_adaptor<pixfmt, alpha_mask_type> pixfmt_amask_type;
typedef agg::renderer_base<pixfmt_amask_type> amask_ren_type;
typedef agg::renderer_scanline_aa_solid<amask_ren_type> amask_aa_renderer_type;
typedef agg::renderer_scanline_bin_solid<amask_ren_type> amask_bin_renderer_type;
// Render face
if (face.first) {
theRasterizer->add_path(path);
if (gc.isaa) {
if (has_clippath) {
pixfmt_amask_type pfa(*pixFmt, *alphaMask);
amask_ren_type r(pfa);
amask_aa_renderer_type ren(r);
ren.color(face.second);
agg::render_scanlines(*theRasterizer, *slineP8, ren);
} else {
rendererAA->color(face.second);
agg::render_scanlines(*theRasterizer, *slineP8, *rendererAA);
}
} else {
if (has_clippath) {
pixfmt_amask_type pfa(*pixFmt, *alphaMask);
amask_ren_type r(pfa);
amask_bin_renderer_type ren(r);
ren.color(face.second);
agg::render_scanlines(*theRasterizer, *slineP8, ren);
} else {
rendererBin->color(face.second);
agg::render_scanlines(*theRasterizer, *slineP8, *rendererBin);
}
}
}
// Render stroke
if (gc.linewidth != 0.0) {
double linewidth = gc.linewidth;
if (!gc.isaa) {
if (linewidth < 0.5)
linewidth = 0.5;
else
linewidth = round(linewidth);
}
if (gc.dashes.size() == 0) {
stroke_t stroke(path);
stroke.width(linewidth);
stroke.line_cap(gc.cap);
stroke.line_join(gc.join);
theRasterizer->add_path(stroke);
} else {
dash_t dash(path);
for (GCAgg::dash_t::const_iterator i = gc.dashes.begin();
i != gc.dashes.end(); ++i) {
double val0 = i->first;
double val1 = i->second;
if (!gc.isaa) {
val0 = (int)val0 + 0.5;
val1 = (int)val1 + 0.5;
}
dash.add_dash(val0, val1);
}
stroke_dash_t stroke(dash);
stroke.line_cap(gc.cap);
stroke.line_join(gc.join);
stroke.width(linewidth);
theRasterizer->add_path(stroke);
}
if (gc.isaa) {
if (has_clippath) {
pixfmt_amask_type pfa(*pixFmt, *alphaMask);
amask_ren_type r(pfa);
amask_aa_renderer_type ren(r);
ren.color(gc.color);
agg::render_scanlines(*theRasterizer, *slineP8, ren);
} else {
rendererAA->color(gc.color);
agg::render_scanlines(*theRasterizer, *slineP8, *rendererAA);
}
} else {
if (has_clippath) {
pixfmt_amask_type pfa(*pixFmt, *alphaMask);
amask_ren_type r(pfa);
amask_bin_renderer_type ren(r);
ren.color(gc.color);
agg::render_scanlines(*theRasterizer, *slineP8, ren);
} else {
rendererBin->color(gc.color);
agg::render_scanlines(*theRasterizer, *slineBin, *rendererBin);
}
}
}
}
Py::Object
RendererAgg::draw_path(const Py::Tuple& args) {
typedef agg::conv_transform<PathIterator> transformed_path_t;
typedef conv_quantize<transformed_path_t> quantize_t;
typedef agg::conv_curve<quantize_t> curve_t;
_VERBOSE("RendererAgg::draw_path");
args.verify_length(3, 4);
Py::Object gc_obj = args[0];
Py::Object path_obj = args[1];
agg::trans_affine trans = py_to_agg_transformation_matrix(args[2]);
Py::Object face_obj;
if (args.size() == 4)
face_obj = args[3];
PathIterator path(path_obj);
GCAgg gc = GCAgg(gc_obj, dpi);
facepair_t face = _get_rgba_face(face_obj, gc.alpha);
theRasterizer->reset_clipping();
rendererBase->reset_clipping(true);
set_clipbox(gc.cliprect, theRasterizer);
bool has_clippath = render_clippath(gc.clippath, gc.clippath_trans);
trans *= agg::trans_affine_scaling(1.0, -1.0);
trans *= agg::trans_affine_translation(0.0, (double)height);
bool snap = should_snap(path, trans);
transformed_path_t tpath(path, trans);
quantize_t quantized(tpath, snap);
curve_t curve(quantized);
if (snap)
gc.isaa = false;
_draw_path(curve, has_clippath, face, gc);
return Py::Object();
}
template<class PathGenerator, int check_snap, int has_curves>
Py::Object
RendererAgg::_draw_path_collection_generic
(agg::trans_affine master_transform,
const Py::Object& cliprect,
const Py::Object& clippath,
const agg::trans_affine& clippath_trans,
const PathGenerator& path_generator,
const Py::SeqBase<Py::Object>& transforms_obj,
const Py::Object& offsets_obj,
const agg::trans_affine& offset_trans,
const Py::Object& facecolors_obj,
const Py::Object& edgecolors_obj,
const Py::SeqBase<Py::Float>& linewidths,
const Py::SeqBase<Py::Object>& linestyles_obj,
const Py::SeqBase<Py::Int>& antialiaseds) {
typedef agg::conv_transform<typename PathGenerator::path_iterator> transformed_path_t;
typedef conv_quantize<transformed_path_t> quantize_t;
typedef agg::conv_curve<quantize_t> quantized_curve_t;
typedef agg::conv_curve<transformed_path_t> curve_t;
GCAgg gc(dpi);
PyArrayObject* offsets = NULL;
PyArrayObject* facecolors = NULL;
PyArrayObject* edgecolors = NULL;
try {
offsets = (PyArrayObject*)PyArray_FromObject(offsets_obj.ptr(), PyArray_DOUBLE, 0, 2);
if (!offsets ||
(PyArray_NDIM(offsets) == 2 && PyArray_DIM(offsets, 1) != 2) ||
(PyArray_NDIM(offsets) == 1 && PyArray_DIM(offsets, 0) != 0)) {
throw Py::ValueError("Offsets array must be Nx2");
}
PyArrayObject* facecolors = (PyArrayObject*)PyArray_FromObject
(facecolors_obj.ptr(), PyArray_DOUBLE, 1, 2);
if (!facecolors ||
(PyArray_NDIM(facecolors) == 1 && PyArray_DIM(facecolors, 0) != 0) ||
(PyArray_NDIM(facecolors) == 2 && PyArray_DIM(facecolors, 1) != 4))
throw Py::ValueError("Facecolors must be a Nx4 numpy array or empty");
PyArrayObject* edgecolors = (PyArrayObject*)PyArray_FromObject
(edgecolors_obj.ptr(), PyArray_DOUBLE, 1, 2);
if (!edgecolors ||
(PyArray_NDIM(edgecolors) == 1 && PyArray_DIM(edgecolors, 0) != 0) ||
(PyArray_NDIM(edgecolors) == 2 && PyArray_DIM(edgecolors, 1) != 4))
throw Py::ValueError("Edgecolors must be a Nx4 numpy array");
size_t Npaths = path_generator.num_paths();
size_t Noffsets = offsets->dimensions[0];
size_t N = std::max(Npaths, Noffsets);
size_t Ntransforms = std::min(transforms_obj.length(), N);
size_t Nfacecolors = facecolors->dimensions[0];
size_t Nedgecolors = edgecolors->dimensions[0];
size_t Nlinewidths = linewidths.length();
size_t Nlinestyles = std::min(linestyles_obj.length(), N);
size_t Naa = antialiaseds.length();
if ((Nfacecolors == 0 && Nedgecolors == 0) || Npaths == 0)
return Py::Object();
size_t i = 0;
// Convert all of the transforms up front
typedef std::vector<agg::trans_affine> transforms_t;
transforms_t transforms;
transforms.reserve(Ntransforms);
for (i = 0; i < Ntransforms; ++i) {
agg::trans_affine trans = py_to_agg_transformation_matrix
(transforms_obj[i], false);
trans *= master_transform;
transforms.push_back(trans);
}
// Convert all the dashes up front
typedef std::vector<std::pair<double, GCAgg::dash_t> > dashes_t;
dashes_t dashes;
dashes.resize(Nlinestyles);
i = 0;
for (dashes_t::iterator d = dashes.begin();
d != dashes.end(); ++d, ++i) {
convert_dashes(Py::Tuple(linestyles_obj[i]), dpi, d->second, d->first);
}
// Handle any clipping globally
theRasterizer->reset_clipping();
rendererBase->reset_clipping(true);
set_clipbox(cliprect, theRasterizer);
bool has_clippath = render_clippath(clippath, clippath_trans);
// Set some defaults, assuming no face or edge
gc.linewidth = 0.0;
facepair_t face;
face.first = Nfacecolors != 0;
agg::trans_affine trans;
bool snap = false;
for (i = 0; i < N; ++i) {
typename PathGenerator::path_iterator path = path_generator(i);
if (Ntransforms) {
trans = transforms[i % Ntransforms];
} else {
trans = master_transform;
}
if (Noffsets) {