-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathEleksmaker_hatch.py
1719 lines (1468 loc) · 75.2 KB
/
Eleksmaker_hatch.py
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
#!/usr/bin/env python
# eggbot_hatch.py
#
# Generate hatch fills for the closed paths (polygons) in the currently
# selected document elements. If no elements are selected, then all the
# polygons throughout the document are hatched. The fill rule is an odd/even
# rule: odd numbered intersections (1, 3, 5, etc.) are a hatch line entering
# a polygon while even numbered intersections (2, 4, 6, etc.) are the same
# hatch line exiting the polygon.
#
# This extension first decomposes the selected <path>, <rect>, <line>,
# <polyline>, <polygon>, <circle>, and <ellipse> elements into individual
# moveto and lineto coordinates using the same procedure that eggbot.py uses
# for plotting. These coordinates are then used to build vertex lists.
# Only the vertex lists corresponding to polygons (closed paths) are
# kept. Note that a single graphical element may be composed of several
# subpaths, each subpath potentially a polygon.
#
# Once the lists of all the vertices are built, potential hatch lines are
# "projected" through the bounding box containing all of the vertices.
# For each potential hatch line, all intersections with all the polygon
# edges are determined. These intersections are stored as decimal fractions
# indicating where along the length of the hatch line the intersection
# occurs. These values will always be in the range [0, 1]. A value of 0
# indicates that the intersection is at the start of the hatch line, a value
# of 0.5 midway, and a value of 1 at the end of the hatch line.
#
# For a given hatch line, all the fractional values are sorted and any
# duplicates removed. Duplicates occur, for instance, when the hatch
# line passes through a polygon vertex and thus intersects two edges
# segments of the polygon: the end of one edge and the start of
# another.
#
# Once sorted and duplicates removed, an odd/even rule is applied to
# determine which segments of the potential hatch line are within
# polygons. These segments found to be within polygons are then saved
# and become the hatch fill lines which will be drawn.
#
# With each saved hatch fill line, information about which SVG graphical
# element it is within is saved. This way, the hatch fill lines can
# later be grouped with the element they are associated with. This makes
# it possible to manipulate the two -- graphical element and hatch lines --
# as a single object within Inkscape.
#
# Note: we also save the transformation matrix for each graphical element.
# That way, when we group the hatch fills with the element they are
# filling, we can invert the transformation. That is, in order to compute
# the hatch fills, we first have had apply ALL applicable transforms to
# all the graphical elements. We need to do that so that we know where in
# the drawing each of the graphical elements are relative to one another.
# However, this means that the hatch lines have been computed in a setting
# where no further transforms are needed. If we then put these hatch lines
# into the same groups as the elements being hatched in the ORIGINAL
# drawing, then the hatch lines will have transforms applied again. So,
# once we compute the hatch lines, we need to invert the transforms of
# the group they will be placed in and apply this inverse transform to the
# hatch lines. Hence the need to save the transform matrix for every
# graphical element.
# Written by Daniel C. Newman for the Eggbot Project
# dan dot newman at mtbaldy dot us
# Last updated 28 November 2010
# 15 October 2010
# Updated by Windell H. Oskay, 6/14/2012
# Added tolerance parameter
# Update by Daniel C. Newman, 6/20/2012
# Add min span/gap width
# Updated by Windell H. Oskay, 1/8/2016
# Added live preview and correct issue with nonzero min gap
# https://github.com/evil-mad/EggBot/issues/32
# Updated by Sheldon B. Michaels, 1/11/2016 thru 3/15/2016
# shel at shel dot net
# Added feature: Option to inset the hatch segments from boundaries
# Added feature: Option to join hatch segments that are "nearby", to minimize pen lifts
# The joins are made using cubic Bezier segments.
# https://github.com/evil-mad/EggBot/issues/36
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
import inkex
import simplepath
import simpletransform
import simplestyle
import cubicsuperpath
import cspsubdiv
import bezmisc
import math
import plot_utils # https://github.com/evil-mad/plotink
N_PAGE_WIDTH = 3200
N_PAGE_HEIGHT = 800
F_MINGAP_SMALL_VALUE = 0.0000000001 # Was 0.00001 in the original version which did not have joined lines.
# Reducing this by a factor of 10^5 decreased probability of occurrence of
# the bug in the original, which got confused when the path barely
# grazed a corner.
BEZIER_OVERSHOOT_MULTIPLIER = 0.75 # evaluation of cubic Bezier curve equation value,
# at x = 0, with
# endpoints at ( -0.5, 0 ), ( +0.5, 0 )
# and control points at ( -0.5, 1.0 ), ( +0.5, 1.0 )
RADIAN_TOLERANCE_FOR_COLINEAR = 0.1 # Pragmatically adjusted to allow adjacent segments from the same scan line, even short ones,
# to be classified as having the same angle
RADIAN_TOLERANCE_FOR_ALTERNATING_DIRECTION = 0.1 # Pragmatic adjustment again, as with colinearity tolerance
RECURSION_LIMIT = 500 # Pragmatic - if too high, risk runtime python error; if too low, miss some chances for reducing pen lifts
EXTREME_POSITIVE_NUMBER = float( 1.0E70 )
EXTREME_NEGATIVE_NUMBER = float( -1.0E70 )
MIN_HATCH_LENGTH_AS_FRACTION_OF_HATCH_SPACING = 0.25 # set minimum hatch length to some function
# (e.g. this multiplier) of the hatch spacing
'''
Geometry 101: Determining if two lines intersect
A line L is defined by two points in space P1 and P2. Any point P on the
line L satisfies
P = P1 + s (P2 - P1)
for some value of the real number s in the range (-infinity, infinity).
If we confine s to the range [0, 1] then we've described the line segment
with end points P1 and P2.
Consider now the line La defined by the points P1 and P2, and the line Lb
defined by the points P3 and P4. Any points Pa and Pb on the lines La and
Lb therefore satisfy
Pa = P1 + sa (P2 - P1)
Pb = P3 + sb (P4 - P3)
for some values of the real numbers sa and sb. To see if these two lines
La and Lb intersect, we wish to see if there are finite values sa and sb
for which
Pa = Pb
Or, equivalently, we ask if there exists values of sa and sb for which
the equation
P1 + sa (P2 - P1) = P3 + sb (P4 - P3)
holds. If we confine ourselves to a two-dimensional plane, and take
P1 = (x1, y1)
P2 = (x2, y2)
P3 = (x3, y3)
P4 = (x4, y4)
we then find that we have two equations in two unknowns, sa and sb,
x1 + sa ( x2 - x1 ) = x3 + sb ( x4 - x3 )
y1 + sa ( y2 - y1 ) = y3 + sb ( y4 - y3 )
Solving these two equations for sa and sb yields,
sa = [ ( y1 - y3 ) ( x4 - x3 ) - ( y4 - y3 ) ( x1 - x3 ) ] / d
sb = [ ( y1 - y3 ) ( x2 - x1 ) - ( y2 - y1 ) ( x1 - x3 ) ] / d
where the denominator, d, is given by
d = ( y4 - y3 ) ( x2 - x1 ) - ( y2 - y1 ) ( x4 - x3 )
Substituting these back for the point (x, y) of intersection gives
x = x1 + sa ( x2 - x1 )
y = y1 + sa ( y2 - y1 )
Note that
1. The lines are parallel when d = 0
2. The lines are coincident d = 0 and the numerators for sa & sb are zero
3. For line segments, sa and sb are in the range [0, 1]; any value outside
that range indicates that the line segments do not intersect.
'''
def intersect( P1, P2, P3, P4 ):
'''
Determine if two line segments defined by the four points P1 & P2 and
P3 & P4 intersect. If they do intersect, then return the fractional
point of intersection "sa" along the first line at which the
intersection occurs.
'''
# Precompute these values -- note that we're basically shifting from
#
# P = P1 + s (P2 - P1)
#
# to
#
# P = P1 + s D
#
# where D is a direction vector. The solution remains the same of
# course. We'll just be computing D once for each line rather than
# computing it a couple of times.
D21x = P2[0] - P1[0]
D21y = P2[1] - P1[1]
D43x = P4[0] - P3[0]
D43y = P4[1] - P3[1]
# Denominator
d = D21x * D43y - D21y * D43x
# Return now if the denominator is zero
if d == 0:
return float( -1 )
# For our purposes, the first line segment given
# by P1 & P2 is the LONG hatch line running through
# the entire drawing. And, P3 & P4 describe the
# usually much shorter line segment from a polygon.
# As such, we compute sb first as it's more likely
# to indicate "no intersection". That is, sa is
# more likely to indicate an intersection with a
# much a long line containing P3 & P4.
nb = ( P1[1] - P3[1] ) * D21x - ( P1[0] - P3[0] ) * D21y
# Could first check if abs(nb) > abs(d) or if
# the signs differ.
sb = float( nb ) / float( d )
if ( sb < 0 ) or ( sb > 1 ):
return float( -1 )
na = ( P1[1] - P3[1] ) * D43x - ( P1[0] - P3[0] ) * D43y
sa = float( na ) / float( d )
if ( sa < 0 ) or ( sa > 1 ):
return float( -1 )
return sa
def interstices( self, P1, P2, paths, hatches, bHoldBackHatches, fHoldBackSteps ):
'''
For the line L defined by the points P1 & P2, determine the segments
of L which lie within the polygons described by the paths stored in
"paths"
P1 -- (x,y) coordinate [list]
P2 -- (x,y) coordinate [list]
paths -- Dictionary of all the paths to check for intersections
When an intersection of the line L is found with a polygon edge, then
the fractional distance along the line L is saved along with the
lxml.etree node which contained the intersecting polygon edge. This
fractional distance is always in the range [0, 1].
Once all polygons have been checked, the list of fractional distances
corresponding to intersections is sorted and any duplicates removed.
It is then assumed that the first intersection is the line L entering
a polygon; the second intersection the line leaving the polygon. This
line segment defined by the first and second intersection points is
thus a hatch fill line we sought to generate. In general, our hatch
fills become the line segments described by intersection i and i+1
with i an odd value (1, 3, 5, ...). Since we know the lxml.etree node
corresponding to each intersection, we can then correlate the hatch
fill lines to the graphical elements in the original SVG document.
This enables us to group hatch lines with the elements being hatched.
The hatch line segments are returned by populating a dictionary.
The dictionary is keyed off of the lxml.etree node pointer. Each
dictionary value is a list of 4-tuples,
(x1, y1, x2, y2)
where (x1, y1) and (x2, y2) are the (x,y) coordinates of the line
segment's starting and ending points.
'''
dAndA = []
# P1 & P2 is the hatch line
# P3 & P4 is the polygon edge to check
for path in paths:
for subpath in paths[path]:
P3 = subpath[0]
for P4 in subpath[1:]:
s = intersect( P1, P2, P3, P4 )
if ( s >= 0.0 ) and ( s <= 1.0 ):
# Save this intersection point along the hatch line
if bHoldBackHatches:
# We will need to know how the hatch meets the polygon segment, so that we can
# calculate the end of a shorter line that stops short
# of the polygon segment.
# We compute the angle now while we have the information required,
# but do _not_ apply it now, as we need the real,original, intersects
# for the odd/even inside/outside operations yet to come.
# Note that though the intersect() routine _could_ compute the join angle,
# we do it here because we go thru here much less often than we go thru intersect().
angleHatchRadians = math.atan2( -( P2[1] - P1[1] ) ,( P2[0] - P1[0] ) ) # from P1 toward P2, cartesian coordinates
angleSegmentRadians = math.atan2( -( P4[1] - P3[1] ) ,( P4[0] - P3[0] ) ) # from P3 toward P4, cartesian coordinates
angleDifferenceRadians = angleHatchRadians - angleSegmentRadians
# coerce to range -pi to +pi
if ( angleDifferenceRadians > math.pi ):
angleDifferenceRadians -= 2 * math.pi
elif (angleDifferenceRadians < -math.pi ):
angleDifferenceRadians += 2 * math.pi
fSinOfJoinAngle = math.sin( angleDifferenceRadians )
fAbsSinOfJoinAngle = abs( fSinOfJoinAngle )
if (fAbsSinOfJoinAngle != 0.0): # Worrying about case of intersecting a segment parallel to the hatch
fPreliminaryLengthToBeRemovedFromPt = fHoldBackSteps / fAbsSinOfJoinAngle
bUnconditionallyExciseHatch = False
else: # if (fSinOfJoinAngle != 0.0):
bUnconditionallyExciseHatch = True
# if (fAbsSinOfJoinAngle != 0.0): else:
if ( not bUnconditionallyExciseHatch):
# if ( fPreliminaryLengthToBeRemovedFromPt > ( distance from intersection to relevant end + fHoldbackSteps ) ):
# fFinalLengthToBeRemovedFromPt = ( distance from intersection to relevant end + fHoldbackSteps )
# The relevant end of the segment is the end from which the hatch approaches at an acute angle.
I = [0,0]
I[0] = P1[0] + s * ( P2[0] - P1[0] ) # compute intersection point of hatch with segment
I[1] = P1[1] + s * ( P2[1] - P1[1] ) # intersecting hatch line starts at P1, vectored toward P2,
# but terminates at intersection I
# Note that atan2 returns answer in range -pi to pi
# Which end is the approach end of the hatch to the segment?
# The dot product tells the answer:
# if dot product is positive, P2 is at the P4 end,
# else P2 is at the P3 end
# We really don't need to take the time to actually take
# the cosine of the angle, we are just interested in
# the quadrant within which the angle lies.
# I'm sure there is an elegant way to do this, but I'll settle for results just now.
# If the angle is in quadrants I or IV then P4 is the relevant end, otherwise P3 is
# nb: Y increases down, rather than up
# nb: difference angle has been forced to the range -pi to +pi
if ( abs(angleDifferenceRadians) < math.pi / 2 ):
# It's near the P3 the relevant end from which the hatch departs
fDistanceFromIntersectionToRelevantEnd = math.hypot( P3[0] - I[0], P3[1] - I[1] )
fDistanceFromIntersectionToIrrelevantEnd = math.hypot( P4[0] - I[0], P4[1] - I[1] )
else: # if ( abs(angleDifferenceRadians) < math.pi / 2 )
# It's near the P4 end from which the hatch departs
fDistanceFromIntersectionToRelevantEnd = math.hypot( P4[0] - I[0], P4[1] - I[1] )
fDistanceFromIntersectionToIrrelevantEnd = math.hypot( P3[0] - I[0], P3[1] - I[1] )
# if ( abs(angleDifferenceRadians) < math.pi / 2 ): else:
# Now, the problem defined in issue 22 is that we may not need to remove the
# entire preliminary length we've calculated. This problem occurs because
# we have so far been considering the polygon segment as a line of infinite extent.
# Thus, we may be holding back at a point where no holdback is required, when
# calculated holdback is well beyond the position of the segment end.
# To make matters worse, we do not currently know whether we're
# starting a hatch or terminating a hatch, because the duplicates have
# yet to be removed. All we can do then, is calculate the required
# line shortening for both possibilities - and then choose the correct
# one after duplicate-removal, when actually finalizing the hatches.
# Let's see if either end, or perhaps both ends, has a case of excessive holdback
# First, default assumption is that neither end has excessive holdback
fFinalLengthToBeRemovedFromPtWhenStartingHatch = fPreliminaryLengthToBeRemovedFromPt
fFinalLengthToBeRemovedFromPtWhenEndingHatch = fPreliminaryLengthToBeRemovedFromPt
# Now check each of the two ends
if ( fPreliminaryLengthToBeRemovedFromPt > ( fDistanceFromIntersectionToRelevantEnd + fHoldBackSteps ) ):
# Yes, would be excessive holdback approaching from this direction
fFinalLengthToBeRemovedFromPtWhenStartingHatch = fDistanceFromIntersectionToRelevantEnd + fHoldBackSteps
# if ( fPreliminaryLengthToBeRemovedFromPt > ( fDistanceFromIntersectionToRelevantEnd + fHoldBackSteps ) ):
if ( fPreliminaryLengthToBeRemovedFromPt > ( fDistanceFromIntersectionToIrrelevantEnd + fHoldBackSteps ) ):
# Yes, would be excessive holdback approaching from other direction
fFinalLengthToBeRemovedFromPtWhenEndingHatch = fDistanceFromIntersectionToIrrelevantEnd + fHoldBackSteps
# if ( fPreliminaryLengthToBeRemovedFromPt > ( fDistanceFromIntersectionToIrrelevantEnd + fHoldBackSteps ) ):
dAndA.append( ( s, path, fFinalLengthToBeRemovedFromPtWhenStartingHatch, fFinalLengthToBeRemovedFromPtWhenEndingHatch ) )
else: # if ( not bUnconditionallyExciseHatch):
dAndA.append( ( s, path, 123456.0, 123456.0 ) ) # Mark for complete hatch excision, hatch is parallel to segment
# Just a random number guaranteed large enough to be longer than any hatch length
# if ( not bUnconditionallyExciseHatch): else :
else: # if bHoldBackHatches:
dAndA.append( ( s, path, 0, 0 ) ) # zero length to be removed from hatch
# if bHoldBackHatches: else:
# if ( s >= 0.0 ) and ( s <= 1.0 ):
P3 = P4
# for P4 in subpath[1:]:
# for subpath in paths[path]:
# for path in paths:
# Return now if there were no intersections
if len( dAndA ) == 0:
return None
dAndA.sort()
# Remove duplicate intersections. A common case where these arise
# is when the hatch line passes through a vertex where one line segment
# ends and the next one begins.
# Having sorted the data, it's trivial to just scan through
# removing duplicates as we go and then truncating the array
n = len( dAndA )
ilast = i = 1
last = dAndA[0]
while i < n:
if ( ( abs( dAndA[i][0] - last[0] ) ) > F_MINGAP_SMALL_VALUE ):
dAndA[ilast] = last = dAndA[i]
ilast += 1
i += 1
dAndA = dAndA[:ilast]
if len( dAndA ) < 2:
return
# Now, entries with even valued indices into sa[] are where we start
# a hatch line and odd valued indices where we end the hatch line.
last_dAndA = None
i = 0
while i < ( len( dAndA ) - 1 ):
#for i in range( 0, len( sa ) - 1, 2 ):
if not hatches.has_key( dAndA[i][1] ):
hatches[dAndA[i][1]] = []
x1 = P1[0] + dAndA[i][0] * ( P2[0] - P1[0] )
y1 = P1[1] + dAndA[i][0] * ( P2[1] - P1[1] )
x2 = P1[0] + dAndA[i+1][0] * ( P2[0] - P1[0] )
y2 = P1[1] + dAndA[i+1][0] * ( P2[1] - P1[1] )
# These are the hatch ends if we are _not_ holding off from the boundary.
if not bHoldBackHatches:
hatches[dAndA[i][1]].append( [[x1, y1], [x2, y2]] )
else: # if not bHoldBackHatches:
# User wants us to perform a pseudo inset operation.
# We will accomplish this by trimming back the ends of the hatches.
# The amount by which to trim back depends on the angle between the
# intersecting hatch line with the intersecting polygon segment, and
# may well be different at the two different ends of the hatch line.
# To visualize this, imagine a hatch intersecting a segment that is
# close to parallel with it. The length of the hatch would have to be
# drastically reduced in order that its closest approach to the
# segment be reduced to the desired distance.
# Imagine a Cartesian coordinate system, with the X axis representing the
# polygon segment, and a line running through the origin with a small
# positive slope being the intersecting hatch line.
# We see that we want a Y value of the specified hatch width, and that
# at that Y, the distance from the origin to that point is the
# hypotenuse of the triangle.
# Y / cutlength = sin(angle)
# therefore:
# cutlength = Y / sin(angle)
# Fortunately, we have already stored this angle for exactly this purpose.
# For each end, trim back the hatch line by the amount required by
# its own angle. If the resultant diminished hatch is too short,
# remove it from consideration by marking it as already drawn - a
# fiction, but is much quicker than actually removing the hatch from the list.
fMinAllowedHatchLength = self.options.hatchSpacing * MIN_HATCH_LENGTH_AS_FRACTION_OF_HATCH_SPACING
fInitialHatchLength = math.hypot( x2 - x1, y2 - y1 )
# We did as much as possible of the inset operation back when we were finding intersections.
# We did it back then because at that point we knew more about the geometry than we know now.
# Now we don't know where the ends of the segments are, so we can't address issue 22 here.
fLengthToBeRemovedFromPt1 = dAndA[i][3]
fLengthToBeRemovedFromPt2 = dAndA[i+1][2]
if ( ( fInitialHatchLength - ( fLengthToBeRemovedFromPt1 + fLengthToBeRemovedFromPt2 ) ) \
<= \
fMinAllowedHatchLength ):
pass # Just don't insert it into the hatch list
else: # if (...too short...):
'''
Use:
def RelativeControlPointPosition( self, distance, fDeltaX, fDeltaY, deltaX, deltaY ):
# returns the point, relative to 0, 0 offset by deltaX, deltaY,
# which extends a distance of "distance" at a slope defined by fDeltaX and fDeltaY
'''
pt1 = self.RelativeControlPointPosition( fLengthToBeRemovedFromPt1, x2 - x1, y2 - y1, x1, y1 )
pt2 = self.RelativeControlPointPosition( fLengthToBeRemovedFromPt2, x1 - x2, y1 - y2, x2, y2 )
hatches[dAndA[i][1]].append( [[pt1[0], pt1[1]], [pt2[0], pt2[1]]] )
# if (...too short...): else:
# if not bHoldBackHatches: else:
# Remember the relative start and end of this hatch segment
last_dAndA = [ dAndA[i], dAndA[i+1] ]
i = i + 2
# while i < ( len( dAndA ) - 1 ):
def inverseTransform ( tran ):
'''
An SVG transform matrix looks like
[ a c e ]
[ b d f ]
[ 0 0 1 ]
And it's inverse is
[ d -c cf - de ]
[ -b a be - af ] * ( ad - bc ) ** -1
[ 0 0 1 ]
And, no reasonable 2d coordinate transform will have
the products ad and bc equal.
SVG represents the transform matrix column by column as
matrix(a b c d e f) while Inkscape extensions store the
transform matrix as
[[a, c, e], [b, d, f]]
To invert the transform stored Inskcape style, we wish to
produce
[[d/D, -c/D, (cf - de)/D], [-b/D, a/D, (be-af)/D]]
where
D = 1 / (ad - bc)
'''
D = tran[0][0] * tran[1][1] - tran[1][0] * tran[0][1]
if D == 0:
return None
return [[tran[1][1]/D, -tran[0][1]/D,
(tran[0][1]*tran[1][2] - tran[1][1]*tran[0][2])/D],
[-tran[1][0]/D, tran[0][0]/D,
(tran[1][0]*tran[0][2] - tran[0][0]*tran[1][2])/D]]
def subdivideCubicPath( sp, flat, i=1 ):
"""
Break up a bezier curve into smaller curves, each of which
is approximately a straight line within a given tolerance
(the "smoothness" defined by [flat]).
This is a modified version of cspsubdiv.cspsubdiv() rewritten
to avoid recurrence.
"""
while True:
while True:
if i >= len( sp ):
return
p0 = sp[i - 1][1]
p1 = sp[i - 1][2]
p2 = sp[i][0]
p3 = sp[i][1]
b = ( p0, p1, p2, p3 )
if cspsubdiv.maxdist( b ) > flat:
break
i += 1
one, two = bezmisc.beziersplitatt( b, 0.5 )
sp[i - 1][2] = one[1]
sp[i][0] = two[2]
p = [one[2], one[3], two[1]]
sp[i:1] = [p]
def distanceSquared( P1, P2 ):
'''
Pythagorean distance formula WITHOUT the square root. Since
we just want to know if the distance is less than some fixed
fudge factor, we can just square the fudge factor once and run
with it rather than compute square roots over and over.
'''
dx = P2[0] - P1[0]
dy = P2[1] - P1[1]
return ( dx * dx + dy * dy )
class Eggbot_Hatch( inkex.Effect ):
def __init__( self ):
inkex.Effect.__init__( self )
self.xmin, self.ymin = ( float( 0 ), float( 0 ) )
self.xmax, self.ymax = ( float( 0 ), float( 0 ) )
self.paths = {}
self.grid = []
self.hatches = {}
self.transforms = {}
# For handling an SVG viewbox attribute, we will need to know the
# values of the document's <svg> width and height attributes as well
# as establishing a transform from the viewbox to the display.
self.docWidth = float( N_PAGE_WIDTH )
self.docHeight = float( N_PAGE_HEIGHT )
self.docTransform = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]
self.OptionParser.add_option(
"--holdBackSteps", action="store", type="float",
dest="holdBackSteps", default=3.0,
help="How far hatch strokes stay from boundary (steps)" )
self.OptionParser.add_option(
"--hatchScope", action="store", type="float",
dest="hatchScope", default=3.0,
help="Radius searched for segments to join (units of hatch width)" )
self.OptionParser.add_option(
"--holdBackHatchFromEdges", action="store", dest="holdBackHatchFromEdges",
type="inkbool", default=True,
help="Stay away from edges, so no need for inset" )
self.OptionParser.add_option(
"--reducePenLifts", action="store", dest="reducePenLifts",
type="inkbool", default=True,
help="Reduce plotting time by joining some hatches" )
self.OptionParser.add_option(
"--crossHatch", action="store", dest="crossHatch",
type="inkbool", default=False,
help="Generate a cross hatch pattern" )
self.OptionParser.add_option(
"--hatchAngle", action="store", type="float",
dest="hatchAngle", default=90.0,
help="Angle of inclination for hatch lines" )
self.OptionParser.add_option(
"--hatchSpacing", action="store", type="float",
dest="hatchSpacing", default=10.0,
help="Spacing between hatch lines" )
self.OptionParser.add_option(
"--tolerance", action="store", type="float",
dest="tolerance", default=20.0,
help="Allowed deviation from original paths" )
self.OptionParser.add_option( "--tab", #NOTE: value is not used.
action="store", type="string", dest="tab", default="splash",
help="The active tab when Apply was pressed" )
def getDocProps( self ):
'''
Get the document's height and width attributes from the <svg> tag.
Use a default value in case the property is not present or is
expressed in units of percentages.
'''
self.docHeight = plot_utils.getLength( self, 'height', N_PAGE_HEIGHT )
self.docWidth = plot_utils.getLength( self, 'width', N_PAGE_WIDTH )
if ( self.docHeight == None ) or ( self.docWidth == None ):
return False
else:
return True
def handleViewBox( self ):
'''
Set up the document-wide transform in the event that the document has an SVG viewbox
'''
if self.getDocProps():
viewbox = self.document.getroot().get( 'viewBox' )
if viewbox:
vinfo = viewbox.strip().replace( ',', ' ' ).split( ' ' )
if ( vinfo[2] != 0 ) and ( vinfo[3] != 0 ):
sx = self.docWidth / float( vinfo[2] )
sy = self.docHeight / float( vinfo[3] )
self.docTransform = simpletransform.parseTransform( 'scale(%f,%f)' % (sx, sy) )
def addPathVertices( self, path, node=None, transform=None ):
'''
Decompose the path data from an SVG element into individual
subpaths, each starting with an absolute move-to (x, y)
coordinate followed by one or more absolute line-to (x, y)
coordinates. Each subpath is stored as a list of (x, y)
coordinates, with the first entry understood to be a
move-to coordinate and the rest line-to coordinates. A list
is then made of all the subpath lists and then stored in the
self.paths dictionary using the path's lxml.etree node pointer
as the dictionary key.
'''
if ( not path ) or ( len( path ) == 0 ):
return
# parsePath() may raise an exception. This is okay
sp = simplepath.parsePath( path )
if ( not sp ) or ( len( sp ) == 0 ):
return
# Get a cubic super duper path
p = cubicsuperpath.CubicSuperPath( sp )
if ( not p ) or ( len( p ) == 0 ):
return
# Apply any transformation
if transform != None:
simpletransform.applyTransformToPath( transform, p )
# Now traverse the simplified path
subpaths = []
subpath_vertices = []
for sp in p:
# We've started a new subpath
# See if there is a prior subpath and whether we should keep it
if len( subpath_vertices ):
if distanceSquared( subpath_vertices[0], subpath_vertices[-1] ) < 1:
# Keep the prior subpath: it appears to be a closed path
subpaths.append( subpath_vertices )
subpath_vertices = []
subdivideCubicPath( sp, float( self.options.tolerance / 100 ) )
for csp in sp:
# Add this vertex to the list of vertices
subpath_vertices.append( csp[1] )
# Handle final subpath
if len( subpath_vertices ):
if distanceSquared( subpath_vertices[0], subpath_vertices[-1] ) < 1:
# Path appears to be closed so let's keep it
subpaths.append( subpath_vertices )
# Empty path?
if len( subpaths ) == 0:
return
# And add this path to our dictionary of paths
self.paths[node] = subpaths
# And save the transform for this element in a dictionary keyed
# by the element's lxml node pointer
self.transforms[node] = transform
def getBoundingBox( self ):
'''
Determine the bounding box for our collection of polygons
'''
self.xmin, self.xmax = EXTREME_POSITIVE_NUMBER, EXTREME_NEGATIVE_NUMBER
self.ymin, self.ymax = EXTREME_POSITIVE_NUMBER, EXTREME_NEGATIVE_NUMBER
for path in self.paths:
for subpath in self.paths[path]:
for vertex in subpath:
if vertex[0] < self.xmin:
self.xmin = vertex[0]
elif vertex[0] > self.xmax:
self.xmax = vertex[0]
if vertex[1] < self.ymin:
self.ymin = vertex[1]
elif vertex[1] > self.ymax:
self.ymax = vertex[1]
# for vertex in subpath:
# for subpath in self.paths[path]:
# for path in self.paths:
def recursivelyTraverseSvg( self, aNodeList,
matCurrent=[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]],
parent_visibility='visible' ):
'''
Recursively walk the SVG document, building polygon vertex lists
for each graphical element we support.
Rendered SVG elements:
<circle>, <ellipse>, <line>, <path>, <polygon>, <polyline>, <rect>
Supported SVG elements:
<group>, <use>
Ignored SVG elements:
<defs>, <eggbot>, <metadata>, <namedview>, <pattern>
All other SVG elements trigger an error (including <text>)
'''
for node in aNodeList:
# Ignore invisible nodes
v = node.get( 'visibility', parent_visibility )
if v == 'inherit':
v = parent_visibility
if v == 'hidden' or v == 'collapse':
pass
# first apply the current matrix transform to this node's tranform
matNew = simpletransform.composeTransform( matCurrent,
simpletransform.parseTransform( node.get( "transform" ) ) )
if node.tag == inkex.addNS( 'g', 'svg' ) or node.tag == 'g':
self.recursivelyTraverseSvg( node, matNew, parent_visibility=v )
elif node.tag == inkex.addNS( 'use', 'svg' ) or node.tag == 'use':
# A <use> element refers to another SVG element via an xlink:href="#blah"
# attribute. We will handle the element by doing an XPath search through
# the document, looking for the element with the matching id="blah"
# attribute. We then recursively process that element after applying
# any necessary (x,y) translation.
#
# Notes:
# 1. We ignore the height and width attributes as they do not apply to
# path-like elements, and
# 2. Even if the use element has visibility="hidden", SVG still calls
# for processing the referenced element. The referenced element is
# hidden only if its visibility is "inherit" or "hidden".
refid = node.get( inkex.addNS( 'href', 'xlink' ) )
if not refid:
pass
# [1:] to ignore leading '#' in reference
path = '//*[@id="%s"]' % refid[1:]
refnode = node.xpath( path )
if refnode:
x = float( node.get( 'x', '0' ) )
y = float( node.get( 'y', '0' ) )
# Note: the transform has already been applied
if ( x != 0 ) or ( y != 0 ):
matNew2 = composeTransform( matNew, parseTransform( 'translate(%f,%f)' % (x,y) ) )
else:
matNew2 = matNew
v = node.get( 'visibility', v )
self.recursivelyTraverseSvg( refnode, matNew2, parent_visibility=v )
elif node.tag == inkex.addNS( 'path', 'svg' ):
path_data = node.get( 'd')
if path_data:
self.addPathVertices( path_data, node, matNew )
elif node.tag == inkex.addNS( 'rect', 'svg' ) or node.tag == 'rect':
# Manually transform
#
# <rect x="X" y="Y" width="W" height="H"/>
#
# into
#
# <path d="MX,Y lW,0 l0,H l-W,0 z"/>
#
# I.e., explicitly draw three sides of the rectangle and the
# fourth side implicitly
# Create a path with the outline of the rectangle
x = float( node.get( 'x' ) )
y = float( node.get( 'y' ) )
if ( not x ) or ( not y ):
pass
w = float( node.get( 'width', '0' ) )
h = float( node.get( 'height', '0' ) )
a = []
a.append( ['M ', [x, y]] )
a.append( [' l ', [w, 0]] )
a.append( [' l ', [0, h]] )
a.append( [' l ', [-w, 0]] )
a.append( [' Z', []] )
self.addPathVertices( simplepath.formatPath( a ), node, matNew )
elif node.tag == inkex.addNS( 'line', 'svg' ) or node.tag == 'line':
# Convert
#
# <line x1="X1" y1="Y1" x2="X2" y2="Y2/>
#
# to
#
# <path d="MX1,Y1 LX2,Y2"/>
x1 = float( node.get( 'x1' ) )
y1 = float( node.get( 'y1' ) )
x2 = float( node.get( 'x2' ) )
y2 = float( node.get( 'y2' ) )
if ( not x1 ) or ( not y1 ) or ( not x2 ) or ( not y2 ):
pass
a = []
a.append( ['M ', [x1, y1]] )
a.append( [' L ', [x2, y2]] )
self.addPathVertices( simplepath.formatPath( a ), node, matNew )
elif node.tag == inkex.addNS( 'polyline', 'svg' ) or node.tag == 'polyline':
# Convert
#
# <polyline points="x1,y1 x2,y2 x3,y3 [...]"/>
#
# to
#
# <path d="Mx1,y1 Lx2,y2 Lx3,y3 [...]"/>
#
# Note: we ignore polylines with no points
pl = node.get( 'points', '' ).strip()
if pl == '':
pass
pa = pl.split()
d = "".join( ["M " + pa[i] if i == 0 else " L " + pa[i] for i in range( 0, len( pa ) )] )
self.addPathVertices( d, node, matNew )
elif node.tag == inkex.addNS( 'polygon', 'svg' ) or node.tag == 'polygon':
# Convert
#
# <polygon points="x1,y1 x2,y2 x3,y3 [...]"/>
#
# to
#
# <path d="Mx1,y1 Lx2,y2 Lx3,y3 [...] Z"/>
#
# Note: we ignore polygons with no points
pl = node.get( 'points', '' ).strip()
if pl == '':
pass
pa = pl.split()
d = "".join( ["M " + pa[i] if i == 0 else " L " + pa[i] for i in range( 0, len( pa ) )] )
d += " Z"
self.addPathVertices( d, node, matNew )
elif node.tag == inkex.addNS( 'ellipse', 'svg' ) or \
node.tag == 'ellipse' or \
node.tag == inkex.addNS( 'circle', 'svg' ) or \
node.tag == 'circle':
# Convert circles and ellipses to a path with two 180 degree arcs.
# In general (an ellipse), we convert
#
# <ellipse rx="RX" ry="RY" cx="X" cy="Y"/>
#
# to
#
# <path d="MX1,CY A RX,RY 0 1 0 X2,CY A RX,RY 0 1 0 X1,CY"/>
#
# where
#
# X1 = CX - RX
# X2 = CX + RX
#
# Note: ellipses or circles with a radius attribute of value 0 are ignored
if node.tag == inkex.addNS( 'ellipse', 'svg' ) or node.tag == 'ellipse':
rx = float( node.get( 'rx', '0' ) )
ry = float( node.get( 'ry', '0' ) )
else:
rx = float( node.get( 'r', '0' ) )
ry = rx
if rx == 0 or ry == 0:
pass
cx = float( node.get( 'cx', '0' ) )
cy = float( node.get( 'cy', '0' ) )
x1 = cx - rx
x2 = cx + rx
d = 'M %f,%f ' % ( x1, cy ) + \
'A %f,%f ' % ( rx, ry ) + \
'0 1 0 %f,%f ' % ( x2, cy ) + \
'A %f,%f ' % ( rx, ry ) + \
'0 1 0 %f,%f' % ( x1, cy )
self.addPathVertices( d, node, matNew )
elif node.tag == inkex.addNS( 'pattern', 'svg' ) or node.tag == 'pattern':
pass
elif node.tag == inkex.addNS( 'metadata', 'svg' ) or node.tag == 'metadata':
pass
elif node.tag == inkex.addNS( 'defs', 'svg' ) or node.tag == 'defs':
pass
elif node.tag == inkex.addNS( 'namedview', 'sodipodi' ) or node.tag == 'namedview':
pass
elif node.tag == inkex.addNS( 'eggbot', 'svg' ) or node.tag == 'eggbot':
pass
elif node.tag == inkex.addNS( 'text', 'svg' ) or node.tag == 'text':
inkex.errormsg( 'Warning: unable to draw text, please convert it to a path first.' )
pass
elif not isinstance( node.tag, basestring ):
pass
else:
inkex.errormsg( 'Warning: unable to draw object <%s>, please convert it to a path first.' % node.tag )
pass
# for node in aNodeList:
# def recursivelyTraverseSvg( self, aNodeList,...