-
Notifications
You must be signed in to change notification settings - Fork 99
/
Copy pathgcodetools-dev.py
executable file
·7876 lines (6856 loc) · 300 KB
/
gcodetools-dev.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
# -*- coding: utf-8 -*-
"""
Comments starting "#LT" or "#CLT" are by Chris Lusby Taylor who rewrote the engraving function in 2011.
History of CLT changes to engraving and other functions it uses:
9 May 2011 Changed test of tool diameter to square it
10 May Note that there are many unused functions, including:
bound_to_bound_distance, csp_curvature_radius_at_t,
csp_special_points, csplength, rebuild_csp, csp_slope,
csp_simple_bound_to_point_distance, csp_bound_to_point_distance,
bez_at_t, bez_to_point_distance, bez_normalized_slope, matrix_mul, transpose
Fixed csp_point_inside_bound() to work if x outside bounds
20 May Now encoding the bisectors of angles.
23 May Using r/cos(a) instead of normalised normals for bisectors of angles.
23 May Note that Z values generated for engraving are in pixels, not mm.
Removed the biarc curves - straight lines are better.
24 May Changed Bezier slope calculation to be less sensitive to tiny differences in points.
Added use of self.options.engraving_newton_iterations to control accuracy
25 May Big restructure and new recursive function.
Changed the way I treat corners - I now find if the centre of a proposed circle is
within the area bounded by the line being tested and the two angle bisectors at
its ends. See get_radius_to_line().
29 May Eliminating redundant points. If A,B,C colinear, drop B
30 May Eliminating redundant lines in divided Beziers. Changed subdivision of lines
7Jun Try to show engraving in 3D
8 Jun Displaying in stereo 3D.
Fixed a bug in bisect - it could go wrong due to rounding errors if
1+x1.x2+y1.y2<0 which should never happen. BTW, I spotted a non-normalised normal
returned by csp_normalized_normal. Need to check for that.
9 Jun Corrected spelling of 'definition' but still match previous 'defention' and 'defenition' if found in file
Changed get_tool to find 1.6.04 tools or new tools with corrected spelling
10 Jun Put 3D into a separate layer called 3D, created unless it already exists
Changed csp_normalized_slope to reject lines shorter than 1e-9.
10 Jun Changed all dimensions seen by user to be mm/inch, not pixels. This includes
tool diameter, maximum engraving distance, tool shape and all Z values.
12 Jun ver 208 Now scales correctly if orientation points moved or stretched.
12 Jun ver 209. Now detect if engraving toolshape not a function of radius
Graphics now indicate Gcode toolpath, limited by min(tool diameter/2,max-dist)
TODO Change line division to be recursive, depending on what line is touched. See line_divide
engraving() functions (c) 2011 Chris Lusby Taylor, [email protected]
Copyright (C) 2009 Nick Drobchenko, [email protected]
based on gcode.py (C) 2007 hugomatic...
based on addnodes.py (C) 2005,2007 Aaron Spike, [email protected]
based on dots.py (C) 2005 Aaron Spike, [email protected]
based on interp.py (C) 2005 Aaron Spike, [email protected]
based on bezmisc.py (C) 2005 Aaron Spike, [email protected]
based on cubicsuperpath.py (C) 2005 Aaron Spike, [email protected]
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
"""
###
### Gcodetools v 1.7 dev
###
gcodetools_current_version = "1.7"
import inkex, simplestyle, simplepath
import cubicsuperpath, simpletransform, bezmisc
from simplepath import formatPath
import os
from math import *
import math
import bezmisc
import re
import copy
import sys
import time
import cmath
import numpy
import codecs
import random
import gettext
import string
_ = gettext.gettext
from biarc import *
from points import P
import ast
### Check if inkex has errormsg (0.46 version does not have one.) Could be removed later.
if "errormsg" not in dir(inkex):
inkex.errormsg = lambda msg: sys.stderr.write((unicode(msg) + "\n").encode("UTF-8"))
### Creates new-style dxf-point
def generate_gcodetools_point(xc, yc,layer):
path= 'm %s,%s 2.9375,-6.34375 0.8125,1.90625 6.84375,-6.84375 0,0 0.6875,0.6875 -6.84375,6.84375 1.90625,0.8125 z' % (xc,yc)
attribs = {'d': path, inkex.addNS('dxfpoint','inkscape'):'1', 'style': 'stroke:#ff0000;fill:#ff0000'}
inkex.etree.SubElement(layer, 'path', attribs)
def bezierslopeatt(((bx0,by0),(bx1,by1),(bx2,by2),(bx3,by3)),t):
ax,ay,bx,by,cx,cy,x0,y0=bezmisc.bezierparameterize(((bx0,by0),(bx1,by1),(bx2,by2),(bx3,by3)))
dx=3*ax*(t**2)+2*bx*t+cx
dy=3*ay*(t**2)+2*by*t+cy
if dx==dy==0 :
dx = 6*ax*t+2*bx
dy = 6*ay*t+2*by
if dx==dy==0 :
dx = 6*ax
dy = 6*ay
if dx==dy==0 :
print_("Slope error x = %s*t^3+%s*t^2+%s*t+%s, y = %s*t^3+%s*t^2+%s*t+%s, t = %s, dx==dy==0" % (ax,bx,cx,dx,ay,by,cy,dy,t))
print_(((bx0,by0),(bx1,by1),(bx2,by2),(bx3,by3)))
dx, dy = 1, 1
return dx,dy
bezmisc.bezierslopeatt = bezierslopeatt
def ireplace(self,old,new,count=0):
pattern = re.compile(re.escape(old),re.I)
return re.sub(pattern,new,self,count)
def isset(variable):
# VARIABLE NAME SHOULD BE A STRING! Like isset("foobar")
return variable in locals() or variable in globals()
################################################################################
###
### Debug Levels
###
################################################################################
debug_level = {
"offset": 0b000001*256,
"offset clip": 0b000010*256,
"point inside": 0b1000000*256,
"split_by_points": 0b000010*256,
"intersect": 0b000100*256,
"check_intersection": 0b001000*256,
"bounds": 0b010000*256,
"intersect_bounds_trees": 0b10000000000000000000000*256,
"timing": 0b1000000000000000000000*256,
}
debug_classes = {
"Biarc" : ["intersect","offset","split_by_points","intersect_bounds_trees"],
"Arc" : ["intersect","check_intersections"],
"Line" : ["intersect","check_intersections"],
}
class Debugger:
def get_debug_level(self, level_name=None, fname=None) :
if gcodetools.options.debug_level<16 : return False
if fname==None : fname = inspect.stack()[1][3]
if level_name != None : level_name.lower()
return (
fname in debug_level and gcodetools.options.debug_level & debug_level[fname]
or (level_name in debug_level and (gcodetools.options.debug_level & debug_level[level_name]))
)
def add_debugger_to_class(self,cl) :
if "debugger" in cl.__dict__ : return
cl.debugger = True
if cl.__name__ in debug_classes :
for method in cl.__dict__ :
if method in debug_classes[cl.__name__] :
cl.__dict__[method] = self.debug_decorator(cl.__dict__[method],cl.__name__)
def debug_decorator(self, func, cl) :
def g(*args, **kwargs):
ret = func(*args, **kwargs)
self.debug(args,ret,func,cl)
return ret
return g
def debug(self,args,ret,func,cl) :
if cl not in debug_classes :
return
fname = func.__name__
if self.get_debug_level(fname=fname) :
if (cl in ["Arc","Line"] and fname == "intersect") :
for point in ret :
draw_pointer(point, figure="cross", width=.1, color="green", text="Proofed intersect point %s"%point)
if (cl in ["Arc","Line"] and fname == "check_intersection") :
for point in arg :
draw_pointer(point, figure="cross", width=.1, color="red", text="Check intersect point %s"%point)
if (fname == "intersect_bounds_trees") :
a,b = args
for i,j,bounds in ret :
for p in bounds :
a.draw_bounds(a.items[i][p[0]])
b.draw_bounds(b.items[j][p[1]])
if (fname == "split_by_points") :
args[0].draw(width=.1, color="red")
#warn(func, cl)
#pass
#[warn(i) for i in inspect.stack()]
#warn( )
debugger = Debugger()
################################################################################
###
### Styles and additional parameters
###
################################################################################
pi2 = pi*2
straight_tolerance = 0.0001
straight_distance_tolerance = 0.0001
engraving_tolerance = 0.00001
loft_lengths_tolerance = 0.0000001
TURN_KNIFE_ANGLE_TOLERANCE = 1e-3 # in radians - tolerance on which we should get tangetn knife up tu turn it
EMC_TOLERANCE_EQUAL = 0.00001
options = {}
defaults = {
'header': """
(Header)
(Generated by gcodetools from Inkscape.)
(Using default header. To add your own header create file "header" in the output dir.)
M3
(Header end.)
""",
'footer': """
(Footer)
M5
G00 X0.0000 Y0.0000
M2
(Using default footer. To add your own footer create file "footer" in the output dir.)
(end)
"""
}
intersection_recursion_depth = 10
intersection_tolerance = 0.00001
styles = {
"in_out_path_style" : simplestyle.formatStyle({ 'stroke': '#0072a7', 'fill': 'none', 'stroke-width':'1', 'marker-mid':'url(#InOutPathMarker)' }),
"loft_style" : {
'main curve': simplestyle.formatStyle({ 'stroke': '#88f', 'fill': 'none', 'stroke-width':'1', 'marker-end':'url(#Arrow2Mend)' }),
},
"biarc_style" : {
'biarc0': simplestyle.formatStyle({ 'stroke': '#88f', 'fill': 'none', "marker-end":"url(#DrawCurveMarker)", 'stroke-width':'1' }),
'biarc1': simplestyle.formatStyle({ 'stroke': '#8f8', 'fill': 'none', "marker-end":"url(#DrawCurveMarker)", 'stroke-width':'1' }),
'line': simplestyle.formatStyle({ 'stroke': '#f88', 'fill': 'none', "marker-end":"url(#DrawCurveMarker)", 'stroke-width':'1' }),
'area': simplestyle.formatStyle({ 'stroke': '#777', 'fill': 'none', "marker-end":"url(#DrawCurveMarker)", 'stroke-width':'0.1' }),
},
"biarc_style_dark" : {
'biarc0': simplestyle.formatStyle({ 'stroke': '#33a', 'fill': 'none', "marker-end":"url(#DrawCurveMarker)", 'stroke-width':'1' }),
'biarc1': simplestyle.formatStyle({ 'stroke': '#3a3', 'fill': 'none', "marker-end":"url(#DrawCurveMarker)", 'stroke-width':'1' }),
'line': simplestyle.formatStyle({ 'stroke': '#a33', 'fill': 'none', "marker-end":"url(#DrawCurveMarker)", 'stroke-width':'1' }),
'area': simplestyle.formatStyle({ 'stroke': '#222', 'fill': 'none', "marker-end":"url(#DrawCurveMarker)", 'stroke-width':'0.3' }),
},
"biarc_style_dark_area" : {
'biarc0': simplestyle.formatStyle({ 'stroke': '#33a', 'fill': 'none', "marker-end":"url(#DrawCurveMarker)", 'stroke-width':'0.1' }),
'biarc1': simplestyle.formatStyle({ 'stroke': '#3a3', 'fill': 'none', "marker-end":"url(#DrawCurveMarker)", 'stroke-width':'0.1' }),
'line': simplestyle.formatStyle({ 'stroke': '#a33', 'fill': 'none', "marker-end":"url(#DrawCurveMarker)", 'stroke-width':'0.1' }),
'area': simplestyle.formatStyle({ 'stroke': '#222', 'fill': 'none', "marker-end":"url(#DrawCurveMarker)", 'stroke-width':'0.3' }),
},
"biarc_style_i" : {
'biarc0': simplestyle.formatStyle({ 'stroke': '#880', 'fill': 'none', "marker-end":"url(#DrawCurveMarker)", 'stroke-width':'1' }),
'biarc1': simplestyle.formatStyle({ 'stroke': '#808', 'fill': 'none', "marker-end":"url(#DrawCurveMarker)", 'stroke-width':'1' }),
'line': simplestyle.formatStyle({ 'stroke': '#088', 'fill': 'none', "marker-end":"url(#DrawCurveMarker)", 'stroke-width':'1' }),
'area': simplestyle.formatStyle({ 'stroke': '#999', 'fill': 'none', "marker-end":"url(#DrawCurveMarker)", 'stroke-width':'0.3' }),
},
"biarc_style_dark_i" : {
'biarc0': simplestyle.formatStyle({ 'stroke': '#dd5', 'fill': 'none', "marker-end":"url(#DrawCurveMarker)", 'stroke-width':'1' }),
'biarc1': simplestyle.formatStyle({ 'stroke': '#d5d', 'fill': 'none', "marker-end":"url(#DrawCurveMarker)", 'stroke-width':'1' }),
'line': simplestyle.formatStyle({ 'stroke': '#5dd', 'fill': 'none', "marker-end":"url(#DrawCurveMarker)", 'stroke-width':'1' }),
'area': simplestyle.formatStyle({ 'stroke': '#aaa', 'fill': 'none', "marker-end":"url(#DrawCurveMarker)", 'stroke-width':'0.3' }),
},
"biarc_style_lathe_feed" : {
'biarc0': simplestyle.formatStyle({ 'stroke': '#07f', 'fill': 'none', "marker-end":"url(#DrawCurveMarker)", 'stroke-width':'.4' }),
'biarc1': simplestyle.formatStyle({ 'stroke': '#0f7', 'fill': 'none', "marker-end":"url(#DrawCurveMarker)", 'stroke-width':'.4' }),
'line': simplestyle.formatStyle({ 'stroke': '#f44', 'fill': 'none', "marker-end":"url(#DrawCurveMarker)", 'stroke-width':'.4' }),
'area': simplestyle.formatStyle({ 'stroke': '#aaa', 'fill': 'none', "marker-end":"url(#DrawCurveMarker)", 'stroke-width':'0.3' }),
},
"biarc_style_lathe_passing feed" : {
'biarc0': simplestyle.formatStyle({ 'stroke': '#07f', 'fill': 'none', "marker-end":"url(#DrawCurveMarker)", 'stroke-width':'.4' }),
'biarc1': simplestyle.formatStyle({ 'stroke': '#0f7', 'fill': 'none', "marker-end":"url(#DrawCurveMarker)", 'stroke-width':'.4' }),
'line': simplestyle.formatStyle({ 'stroke': '#f44', 'fill': 'none', "marker-end":"url(#DrawCurveMarker)", 'stroke-width':'.4' }),
'area': simplestyle.formatStyle({ 'stroke': '#aaa', 'fill': 'none', "marker-end":"url(#DrawCurveMarker)", 'stroke-width':'0.3' }),
},
"biarc_style_lathe_fine feed" : {
'biarc0': simplestyle.formatStyle({ 'stroke': '#7f0', 'fill': 'none', "marker-end":"url(#DrawCurveMarker)", 'stroke-width':'.4' }),
'biarc1': simplestyle.formatStyle({ 'stroke': '#f70', 'fill': 'none', "marker-end":"url(#DrawCurveMarker)", 'stroke-width':'.4' }),
'line': simplestyle.formatStyle({ 'stroke': '#744', 'fill': 'none', "marker-end":"url(#DrawCurveMarker)", 'stroke-width':'.4' }),
'area': simplestyle.formatStyle({ 'stroke': '#aaa', 'fill': 'none', "marker-end":"url(#DrawCurveMarker)", 'stroke-width':'0.3' }),
},
"area artefact": simplestyle.formatStyle({ 'stroke': '#ff0000', 'fill': '#ffff00', 'stroke-width':'1' }),
"area artefact arrow": simplestyle.formatStyle({ 'stroke': '#ff0000', 'fill': '#ffff00', 'stroke-width':'1' }),
"dxf_points": simplestyle.formatStyle({ "stroke": "#ff0000", "fill": "#ff0000"}),
"dxf_points_save": simplestyle.formatStyle({ "stroke": "#ff0000", "fill": "none"}),
}
for style in styles :
s = styles[style]
for i in ['biarc0','biarc1'] :
if i in s :
si = simplestyle.parseStyle(s[i])
si["marker-start"] = "url(#DrawCurveMarker_r)"
del( si["marker-end"] )
styles[style][i[:-1]+"_r"+i[-1]] = simplestyle.formatStyle(si)
def get_style(stype, reverse=None, i=None, name=None, color = None, width = None) :
if stype == 'biarc' and i==None : i=0
if i!=None : i=i%2
if reverse : stype+="_r"
if name==None : name = "biarc_style"
style = styles[name]
if i!=None : stype += "%s"%i
style = style[stype]
if color != None or width != None :
style = simplestyle.parseStyle(style)
if color!=None : style["stroke"]=color
if width!=None : style["stroke-width"]=width
style = simplestyle.formatStyle(style)
return str(style)
################################################################################
### Gcode additional functions
################################################################################
def gcode_comment_str(s, replace_new_line = False):
if replace_new_line :
s = re.sub(r"[\n\r]+", ".", s)
res = ""
if s[-1] == "\n" : s = s[:-1]
for a in s.split("\n") :
if a != "" :
res += "(" + re.sub(r"[\(\)\\\n\r]", ".", a) + ")\n"
else :
res += "\n"
return res
################################################################################
### Cubic Super Path additional functions
################################################################################
def csp_from_polyline(line) :
return [ [ [point[:] for k in range(3) ] for point in subline ] for subline in line ]
def csp_clean(csp) :
csp = csp_remove_zerro_segments(csp)
for i in range(len(csp)) :
if (P(csp[i][0][1])-P(csp[i][-1][1])).l2()<1e-10 :
csp[i][0][0] = csp[i][-1][0]
csp[i][-1][2] = csp[i][0][2]
return csp
def csp_remove_zerro_segments(csp, tolerance = 1e-7):
res = []
for subpath in csp:
if len(subpath) > 0 :
res.append([subpath[0]])
for sp1,sp2 in zip(subpath,subpath[1:]) :
if point_to_point_d2(sp1[1],sp2[1])<=tolerance and point_to_point_d2(sp1[2],sp2[1])<=tolerance and point_to_point_d2(sp1[1],sp2[0])<=tolerance :
res[-1][-1][2] = sp2[2]
else :
res[-1].append(sp2)
return res
def point_inside_csp(p,csp, on_the_path = True) :
# we'll do the raytracing and see how many intersections are there on the ray's way.
# if number of intersections is even then point is outside.
# ray will be x=p.x and y=>p.y
# you can assing any value to on_the_path, by dfault if point is on the path
# function will return thai it's inside the path.
x,y = p
ray_intersections_count = 0
for subpath in csp :
for i in range(1, len(subpath)) :
sp1, sp2 = subpath[i-1], subpath[i]
ax,ay,bx,by,cx,cy,dx,dy = csp_parameterize(sp1,sp2)
if ax==0 and bx==0 and cx==0 and dx==x :
#we've got a special case here
b = csp_true_bounds( [[sp1,sp2]])
if b[1][1]<=y<=b[3][1] :
# points is on the path
return on_the_path
else :
# we can skip this segment because it wont influence the answer.
pass
else:
for t in csp_line_intersection([x,y],[x,y+5],sp1,sp2) :
if t == 0 or t == 1 :
#we've got another special case here
x1,y1 = csp_at_t(sp1,sp2,t)
if y1==y :
# the point is on the path
return on_the_path
# if t == 0 we sould have considered this case previously.
if t == 1 :
# we have to check the next segmant if it is on the same side of the ray
st_d = csp_normalized_slope(sp1,sp2,1)[0]
if st_d == 0 : st_d = csp_normalized_slope(sp1,sp2,0.99)[0]
for j in range(1, len(subpath)+1):
if (i+j) % len(subpath) == 0 : continue # skip the closing segment
sp11,sp22 = subpath[(i-1+j) % len(subpath)], subpath[(i+j) % len(subpath)]
ax1,ay1,bx1,by1,cx1,cy1,dx1,dy1 = csp_parameterize(sp1,sp2)
if ax1==0 and bx1==0 and cx1==0 and dx1==x : continue # this segment parallel to the ray, so skip it
en_d = csp_normalized_slope(sp11,sp22,0)[0]
if en_d == 0 : en_d = csp_normalized_slope(sp11,sp22,0.01)[0]
if st_d*en_d <=0 :
ray_intersections_count += 1
break
else :
x1,y1 = csp_at_t(sp1,sp2,t)
if y1==y :
# the point is on the path
return on_the_path
else :
if y1>y and 3*ax*t**2 + 2*bx*t + cx !=0 : # if it's 0 the path only touches the ray
ray_intersections_count += 1
return ray_intersections_count%2 == 1
def csp_close_all_subpaths(csp, tolerance = 0.000001):
for i in range(len(csp)):
if point_to_point_d2(csp[i][0][1] , csp[i][-1][1])> tolerance**2 :
csp[i][-1][2] = csp[i][-1][1][:]
csp[i] += [ [csp[i][0][1][:] for j in range(3)] ]
else:
if csp[i][0][1] != csp[i][-1][1] :
csp[i][-1][1] = csp[i][0][1][:]
return csp
def csp_simple_bound(csp):
minx,miny,maxx,maxy = None,None,None,None
for subpath in csp:
for sp in subpath :
for p in sp:
minx = min(minx,p[0]) if minx!=None else p[0]
miny = min(miny,p[1]) if miny!=None else p[1]
maxx = max(maxx,p[0]) if maxx!=None else p[0]
maxy = max(maxy,p[1]) if maxy!=None else p[1]
return minx,miny,maxx,maxy
def csp_segment_to_bez(sp1,sp2) :
return sp1[1:]+sp2[:2]
def bound_to_bound_distance(sp1,sp2,sp3,sp4) :
min_dist = 1e100
max_dist = 0
points1 = csp_segment_to_bez(sp1,sp2)
points2 = csp_segment_to_bez(sp3,sp4)
for i in range(4) :
for j in range(4) :
min_, max_ = line_to_line_min_max_distance_2(points1[i-1], points1[i], points2[j-1], points2[j])
min_dist = min(min_dist,min_)
max_dist = max(max_dist,max_)
print_("bound_to_bound", min_dist, max_dist)
return min_dist, max_dist
def csp_to_point_distance(csp, p, dist_bounds = [0,1e100], tolerance=.01) :
min_dist = [1e100,0,0,0]
for j in range(len(csp)) :
for i in range(1,len(csp[j])) :
d = csp_seg_to_point_distance(csp[j][i-1],csp[j][i],p,sample_points = 5, tolerance = .01)
if d[0] < dist_bounds[0] :
# draw_pointer( list(csp_at_t(subpath[dist[2]-1],subpath[dist[2]],dist[3]))
# +list(csp_at_t(csp[dist[4]][dist[5]-1],csp[dist[4]][dist[5]],dist[6])),"red","line", comment = sqrt(dist[0]))
return [d[0],j,i,d[1]]
else :
if d[0] < min_dist[0] : min_dist = [d[0],j,i,d[1]]
return min_dist
def csp_seg_to_point_distance(sp1,sp2,p,sample_points = 5, tolerance = .01) :
ax,ay,bx,by,cx,cy,dx,dy = csp_parameterize(sp1,sp2)
dx, dy = dx-p[0], dy-p[1]
if sample_points < 2 : sample_points = 2
d = min( [(p[0]-sp1[1][0])**2 + (p[1]-sp1[1][1])**2,0.], [(p[0]-sp2[1][0])**2 + (p[1]-sp2[1][1])**2,1.] )
for k in range(sample_points) :
t = float(k)/(sample_points-1)
i = 0
while i==0 or abs(f)>0.000001 and i<20 :
t2,t3 = t**2,t**3
f = (ax*t3+bx*t2+cx*t+dx)*(3*ax*t2+2*bx*t+cx) + (ay*t3+by*t2+cy*t+dy)*(3*ay*t2+2*by*t+cy)
df = (6*ax*t+2*bx)*(ax*t3+bx*t2+cx*t+dx) + (3*ax*t2+2*bx*t+cx)**2 + (6*ay*t+2*by)*(ay*t3+by*t2+cy*t+dy) + (3*ay*t2+2*by*t+cy)**2
if df!=0 :
t = t - f/df
else :
break
i += 1
if 0<=t<=1 :
p1 = csp_at_t(sp1,sp2,t)
d1 = (p1[0]-p[0])**2 + (p1[1]-p[1])**2
if d1 < d[0] :
d = [d1,t]
return d
def csp_seg_to_csp_seg_distance(sp1,sp2,sp3,sp4, dist_bounds = [0,1e100], sample_points = 5, tolerance=.01) :
# check the ending points first
dist = csp_seg_to_point_distance(sp1,sp2,sp3[1],sample_points, tolerance)
dist += [0.]
if dist[0] <= dist_bounds[0] : return dist
d = csp_seg_to_point_distance(sp1,sp2,sp4[1],sample_points, tolerance)
if d[0]<dist[0] :
dist = d+[1.]
if dist[0] <= dist_bounds[0] : return dist
d = csp_seg_to_point_distance(sp3,sp4,sp1[1],sample_points, tolerance)
if d[0]<dist[0] :
dist = [d[0],0.,d[1]]
if dist[0] <= dist_bounds[0] : return dist
d = csp_seg_to_point_distance(sp3,sp4,sp2[1],sample_points, tolerance)
if d[0]<dist[0] :
dist = [d[0],1.,d[1]]
if dist[0] <= dist_bounds[0] : return dist
sample_points -= 2
if sample_points < 1 : sample_points = 1
ax1,ay1,bx1,by1,cx1,cy1,dx1,dy1 = csp_parameterize(sp1,sp2)
ax2,ay2,bx2,by2,cx2,cy2,dx2,dy2 = csp_parameterize(sp3,sp4)
# try to find closes points using Newtons method
for k in range(sample_points) :
for j in range(sample_points) :
t1,t2 = float(k+1)/(sample_points+1), float(j)/(sample_points+1)
t12, t13, t22, t23 = t1*t1, t1*t1*t1, t2*t2, t2*t2*t2
i = 0
F1, F2, F = [0,0], [[0,0],[0,0]], 1e100
x,y = ax1*t13+bx1*t12+cx1*t1+dx1 - (ax2*t23+bx2*t22+cx2*t2+dx2), ay1*t13+by1*t12+cy1*t1+dy1 - (ay2*t23+by2*t22+cy2*t2+dy2)
while i<2 or abs(F-Flast)>tolerance and i<30 :
#draw_pointer(csp_at_t(sp1,sp2,t1))
f1x = 3*ax1*t12+2*bx1*t1+cx1
f1y = 3*ay1*t12+2*by1*t1+cy1
f2x = 3*ax2*t22+2*bx2*t2+cx2
f2y = 3*ay2*t22+2*by2*t2+cy2
F1[0] = 2*f1x*x + 2*f1y*y
F1[1] = -2*f2x*x - 2*f2y*y
F2[0][0] = 2*(6*ax1*t1+2*bx1)*x + 2*f1x*f1x + 2*(6*ay1*t1+2*by1)*y +2*f1y*f1y
F2[0][1] = -2*f1x*f2x - 2*f1y*f2y
F2[1][0] = -2*f2x*f1x - 2*f2y*f1y
F2[1][1] = -2*(6*ax2*t2+2*bx2)*x + 2*f2x*f2x - 2*(6*ay2*t2+2*by2)*y + 2*f2y*f2y
F2 = inv_2x2(F2)
if F2!=None :
t1 -= ( F2[0][0]*F1[0] + F2[0][1]*F1[1] )
t2 -= ( F2[1][0]*F1[0] + F2[1][1]*F1[1] )
t12, t13, t22, t23 = t1*t1, t1*t1*t1, t2*t2, t2*t2*t2
x,y = ax1*t13+bx1*t12+cx1*t1+dx1 - (ax2*t23+bx2*t22+cx2*t2+dx2), ay1*t13+by1*t12+cy1*t1+dy1 - (ay2*t23+by2*t22+cy2*t2+dy2)
Flast = F
F = x*x+y*y
else :
break
i += 1
if F < dist[0] and 0<=t1<=1 and 0<=t2<=1:
dist = [F,t1,t2]
if dist[0] <= dist_bounds[0] :
return dist
return dist
def csp_to_csp_distance(csp1,csp2, dist_bounds = [0,1e100], tolerance=.01) :
dist = [1e100,0,0,0,0,0,0]
for i1 in range(len(csp1)) :
for j1 in range(1,len(csp1[i1])) :
for i2 in range(len(csp2)) :
for j2 in range(1,len(csp2[i2])) :
d = csp_seg_bound_to_csp_seg_bound_max_min_distance(csp1[i1][j1-1],csp1[i1][j1],csp2[i2][j2-1],csp2[i2][j2])
if d[0] >= dist_bounds[1] : continue
if d[1] < dist_bounds[0] : return [d[1],i1,j1,1,i2,j2,1]
d = csp_seg_to_csp_seg_distance(csp1[i1][j1-1],csp1[i1][j1],csp2[i2][j2-1],csp2[i2][j2], dist_bounds, tolerance=tolerance)
if d[0] < dist[0] :
dist = [d[0], i1,j1,d[1], i2,j2,d[2]]
if dist[0] <= dist_bounds[0] :
return dist
if dist[0] >= dist_bounds[1] :
return dist
return dist
# draw_pointer( list(csp_at_t(csp1[dist[1]][dist[2]-1],csp1[dist[1]][dist[2]],dist[3]))
# + list(csp_at_t(csp2[dist[4]][dist[5]-1],csp2[dist[4]][dist[5]],dist[6])), "#507","line")
def csp_split(sp1,sp2,t=.5) :
[x1,y1],[x2,y2],[x3,y3],[x4,y4] = sp1[1], sp1[2], sp2[0], sp2[1]
x12 = x1+(x2-x1)*t
y12 = y1+(y2-y1)*t
x23 = x2+(x3-x2)*t
y23 = y2+(y3-y2)*t
x34 = x3+(x4-x3)*t
y34 = y3+(y4-y3)*t
x1223 = x12+(x23-x12)*t
y1223 = y12+(y23-y12)*t
x2334 = x23+(x34-x23)*t
y2334 = y23+(y34-y23)*t
x = x1223+(x2334-x1223)*t
y = y1223+(y2334-y1223)*t
return [sp1[0],sp1[1],[x12,y12]], [[x1223,y1223],[x,y],[x2334,y2334]], [[x34,y34],sp2[1],sp2[2]]
def csp_true_bounds(csp) :
# Finds minx,miny,maxx,maxy of the csp and return their (x,y,i,j,t)
minx = [float("inf"), 0, 0, 0]
maxx = [float("-inf"), 0, 0, 0]
miny = [float("inf"), 0, 0, 0]
maxy = [float("-inf"), 0, 0, 0]
for i in range(len(csp)):
for j in range(1,len(csp[i])):
ax,ay,bx,by,cx,cy,x0,y0 = bezmisc.bezierparameterize((csp[i][j-1][1],csp[i][j-1][2],csp[i][j][0],csp[i][j][1]))
roots = cubic_solver(0, 3*ax, 2*bx, cx) + [0,1]
for root in roots :
if type(root) is complex and abs(root.imag)<1e-10:
root = root.real
if type(root) is not complex and 0<=root<=1:
y = ay*(root**3)+by*(root**2)+cy*root+y0
x = ax*(root**3)+bx*(root**2)+cx*root+x0
maxx = max([x,y,i,j,root],maxx)
minx = min([x,y,i,j,root],minx)
roots = cubic_solver(0, 3*ay, 2*by, cy) + [0,1]
for root in roots :
if type(root) is complex and root.imag==0:
root = root.real
if type(root) is not complex and 0<=root<=1:
y = ay*(root**3)+by*(root**2)+cy*root+y0
x = ax*(root**3)+bx*(root**2)+cx*root+x0
maxy = max([y,x,i,j,root],maxy)
miny = min([y,x,i,j,root],miny)
maxy[0],maxy[1] = maxy[1],maxy[0]
miny[0],miny[1] = miny[1],miny[0]
return minx,miny,maxx,maxy
############################################################################
### csp_segments_intersection(sp1,sp2,sp3,sp4)
###
### Returns array containig all intersections between two segmets of cubic
### super path. Results are [ta,tb], or [ta0, ta1, tb0, tb1, "Overlap"]
### where ta, tb are values of t for the intersection point.
############################################################################
def csp_segments_intersection(sp1,sp2,sp3,sp4) :
a, b = csp_segment_to_bez(sp1,sp2), csp_segment_to_bez(sp3,sp4)
def polish_intersection(a,b,ta,tb, tolerance = intersection_tolerance) :
ax,ay,bx,by,cx,cy,dx,dy = bezmisc.bezierparameterize(a)
ax1,ay1,bx1,by1,cx1,cy1,dx1,dy1 = bezmisc.bezierparameterize(b)
i = 0
F, F1 = [.0,.0], [[.0,.0],[.0,.0]]
while i==0 or (abs(F[0])**2+abs(F[1])**2 > tolerance and i<10):
ta3, ta2, tb3, tb2 = ta**3, ta**2, tb**3, tb**2
F[0] = ax*ta3+bx*ta2+cx*ta+dx-ax1*tb3-bx1*tb2-cx1*tb-dx1
F[1] = ay*ta3+by*ta2+cy*ta+dy-ay1*tb3-by1*tb2-cy1*tb-dy1
F1[0][0] = 3*ax *ta2 + 2*bx *ta + cx
F1[0][1] = -3*ax1*tb2 - 2*bx1*tb - cx1
F1[1][0] = 3*ay *ta2 + 2*by *ta + cy
F1[1][1] = -3*ay1*tb2 - 2*by1*tb - cy1
det = F1[0][0]*F1[1][1] - F1[0][1]*F1[1][0]
if det!=0 :
F1 = [ [ F1[1][1]/det, -F1[0][1]/det], [-F1[1][0]/det, F1[0][0]/det] ]
ta = ta - ( F1[0][0]*F[0] + F1[0][1]*F[1] )
tb = tb - ( F1[1][0]*F[0] + F1[1][1]*F[1] )
else: break
i += 1
return ta, tb
def recursion(a,b, ta0,ta1,tb0,tb1, depth_a,depth_b) :
global bezier_intersection_recursive_result
if a==b :
bezier_intersection_recursive_result += [[ta0,tb0,ta1,tb1,"Overlap"]]
return
tam, tbm = (ta0+ta1)/2, (tb0+tb1)/2
if depth_a>0 and depth_b>0 :
a1,a2 = bez_split(a,0.5)
b1,b2 = bez_split(b,0.5)
if bez_bounds_intersect(a1,b1) : recursion(a1,b1, ta0,tam,tb0,tbm, depth_a-1,depth_b-1)
if bez_bounds_intersect(a2,b1) : recursion(a2,b1, tam,ta1,tb0,tbm, depth_a-1,depth_b-1)
if bez_bounds_intersect(a1,b2) : recursion(a1,b2, ta0,tam,tbm,tb1, depth_a-1,depth_b-1)
if bez_bounds_intersect(a2,b2) : recursion(a2,b2, tam,ta1,tbm,tb1, depth_a-1,depth_b-1)
elif depth_a>0 :
a1,a2 = bez_split(a,0.5)
if bez_bounds_intersect(a1,b) : recursion(a1,b, ta0,tam,tb0,tb1, depth_a-1,depth_b)
if bez_bounds_intersect(a2,b) : recursion(a2,b, tam,ta1,tb0,tb1, depth_a-1,depth_b)
elif depth_b>0 :
b1,b2 = bez_split(b,0.5)
if bez_bounds_intersect(a,b1) : recursion(a,b1, ta0,ta1,tb0,tbm, depth_a,depth_b-1)
if bez_bounds_intersect(a,b2) : recursion(a,b2, ta0,ta1,tbm,tb1, depth_a,depth_b-1)
else : # Both segments have been subdevided enougth. Let's get some intersections :).
intersection, t1, t2 = straight_segments_intersection([a[0]]+[a[3]],[b[0]]+[b[3]])
if intersection :
if intersection == "Overlap" :
t1 = ( max(0,min(1,t1[0]))+max(0,min(1,t1[1])) )/2
t2 = ( max(0,min(1,t2[0]))+max(0,min(1,t2[1])) )/2
bezier_intersection_recursive_result += [[ta0+t1*(ta1-ta0),tb0+t2*(tb1-tb0)]]
global bezier_intersection_recursive_result
bezier_intersection_recursive_result = []
recursion(a,b,0.,1.,0.,1.,intersection_recursion_depth,intersection_recursion_depth)
intersections = bezier_intersection_recursive_result
for i in range(len(intersections)) :
if len(intersections[i])<5 or intersections[i][4] != "Overlap" :
intersections[i] = polish_intersection(a,b,intersections[i][0],intersections[i][1])
return intersections
def csp_segments_true_intersection(sp1,sp2,sp3,sp4) :
intersections = csp_segments_intersection(sp1,sp2,sp3,sp4)
res = []
for intersection in intersections :
if (
(len(intersection)==5 and intersection[4] == "Overlap" and (0<=intersection[0]<=1 or 0<=intersection[1]<=1) and (0<=intersection[2]<=1 or 0<=intersection[3]<=1) )
or ( 0<=intersection[0]<=1 and 0<=intersection[1]<=1 )
) :
res += [intersection]
return res
def csp_get_t_at_curvature(sp1,sp2,c, sample_points = 16):
# returns a list containning [t1,t2,t3,...,tn], 0<=ti<=1...
if sample_points < 2 : sample_points = 2
tolerance = .0000000001
res = []
ax,ay,bx,by,cx,cy,dx,dy = csp_parameterize(sp1,sp2)
for k in range(sample_points) :
t = float(k)/(sample_points-1)
i, F = 0, 1e100
while i<2 or abs(F)>tolerance and i<17 :
try : # some numerical calculation could exceed the limits
t2 = t*t
#slopes...
f1x = 3*ax*t2+2*bx*t+cx
f1y = 3*ay*t2+2*by*t+cy
f2x = 6*ax*t+2*bx
f2y = 6*ay*t+2*by
f3x = 6*ax
f3y = 6*ay
d = (f1x**2+f1y**2)**1.5
F1 = (
( (f1x*f3y-f3x*f1y)*d - (f1x*f2y-f2x*f1y)*3.*(f2x*f1x+f2y*f1y)*((f1x**2+f1y**2)**.5) ) /
((f1x**2+f1y**2)**3)
)
F = (f1x*f2y-f1y*f2x)/d - c
t -= F/F1
except:
break
i += 1
if 0<=t<=1 and F<=tolerance:
if len(res) == 0 :
res.append(t)
for i in res :
if abs(t-i)<=0.001 :
break
if not abs(t-i)<=0.001 :
res.append(t)
return res
def csp_max_curvature(sp1,sp2):
ax,ay,bx,by,cx,cy,dx,dy = csp_parameterize(sp1,sp2)
tolerance = .0001
F = 0.
i = 0
while i<2 or F-Flast<tolerance and i<10 :
t = .5
f1x = 3*ax*t**2 + 2*bx*t + cx
f1y = 3*ay*t**2 + 2*by*t + cy
f2x = 6*ax*t + 2*bx
f2y = 6*ay*t + 2*by
f3x = 6*ax
f3y = 6*ay
d = pow(f1x**2+f1y**2,1.5)
if d != 0 :
Flast = F
F = (f1x*f2y-f1y*f2x)/d
F1 = (
( d*(f1x*f3y-f3x*f1y) - (f1x*f2y-f2x*f1y)*3.*(f2x*f1x+f2y*f1y)*pow(f1x**2+f1y**2,.5) ) /
(f1x**2+f1y**2)**3
)
i+=1
if F1!=0:
t -= F/F1
else:
break
else: break
return t
def csp_curvature_at_t(sp1,sp2,t, depth = 3) :
ax,ay,bx,by,cx,cy,dx,dy = bezmisc.bezierparameterize(csp_segment_to_bez(sp1,sp2))
#curvature = (x'y''-y'x'') / (x'^2+y'^2)^1.5
f1x = 3*ax*t**2 + 2*bx*t + cx
f1y = 3*ay*t**2 + 2*by*t + cy
f2x = 6*ax*t + 2*bx
f2y = 6*ay*t + 2*by
d = (f1x**2+f1y**2)**1.5
if d != 0 :
return (f1x*f2y-f1y*f2x)/d
else :
t1 = f1x*f2y-f1y*f2x
if t1 > 0 : return 1e100
if t1 < 0 : return -1e100
# Use the Lapitals rule to solve 0/0 problem for 2 times...
t1 = 2*(bx*ay-ax*by)*t+(ay*cx-ax*cy)
if t1 > 0 : return 1e100
if t1 < 0 : return -1e100
t1 = bx*ay-ax*by
if t1 > 0 : return 1e100
if t1 < 0 : return -1e100
if depth>0 :
# little hack ;^) hope it wont influence anything...
return csp_curvature_at_t(sp1,sp2,t*1.004, depth-1)
return 1e100
def csp_curvature_radius_at_t(sp1,sp2,t) :
c = csp_curvature_at_t(sp1,sp2,t)
if c == 0 : return 1e100
else: return 1/c
def csp_special_points(sp1,sp2) :
# special points = curvature == 0
ax,ay,bx,by,cx,cy,dx,dy = bezmisc.bezierparameterize((sp1[1],sp1[2],sp2[0],sp2[1]))
a = 3*ax*by-3*ay*bx
b = 3*ax*cy-3*cx*ay
c = bx*cy-cx*by
roots = cubic_solver(0, a, b, c)
res = []
for i in roots :
if type(i) is complex and i.imag==0:
i = i.real
if type(i) is not complex and 0<=i<=1:
res.append(i)
return res
def csp_subpath_ccw(subpath):
# Remove all zerro length segments
s = 0
#subpath = subpath[:]
if (P(subpath[-1][1])-P(subpath[0][1])).l2() > 1e-10 :
subpath[-1][2] = subpath[-1][1]
subpath[0][0] = subpath[0][1]
subpath += [ [subpath[0][1],subpath[0][1],subpath[0][1]] ]
pl = subpath[-1][2]
for sp1 in subpath:
for p in sp1 :
s += (p[0]-pl[0])*(p[1]+pl[1])
pl = p
return s<0
def csp_at_t(sp1,sp2,t):
ax,bx,cx,dx = sp1[1][0], sp1[2][0], sp2[0][0], sp2[1][0]
ay,by,cy,dy = sp1[1][1], sp1[2][1], sp2[0][1], sp2[1][1]
x1, y1 = ax+(bx-ax)*t, ay+(by-ay)*t
x2, y2 = bx+(cx-bx)*t, by+(cy-by)*t
x3, y3 = cx+(dx-cx)*t, cy+(dy-cy)*t
x4,y4 = x1+(x2-x1)*t, y1+(y2-y1)*t
x5,y5 = x2+(x3-x2)*t, y2+(y3-y2)*t
x,y = x4+(x5-x4)*t, y4+(y5-y4)*t
return [x,y]
def csp_at_length(sp1,sp2,l=0.5, tolerance = 0.01):
bez = (sp1[1][:],sp1[2][:],sp2[0][:],sp2[1][:])
t = bezmisc.beziertatlength(bez, l, tolerance)
return csp_at_t(sp1,sp2,t)
def csp_splitatlength(sp1, sp2, l = 0.5, tolerance = 0.01):
bez = (sp1[1][:],sp1[2][:],sp2[0][:],sp2[1][:])
t = bezmisc.beziertatlength(bez, l, tolerance)
return csp_split(sp1, sp2, t)
def cspseglength(sp1,sp2, tolerance = 0.01):
bez = (sp1[1][:],sp1[2][:],sp2[0][:],sp2[1][:])
return bezmisc.bezierlength(bez, tolerance)
def csplength(csp):
total = 0
lengths = []
for sp in csp:
for i in xrange(1,len(sp)):
l = cspseglength(sp[i-1],sp[i])
lengths.append(l)
total += l
return lengths, total
def csp_segments(csp):
l, seg = 0, [0]
for sp in csp:
for i in xrange(1,len(sp)):
l += cspseglength(sp[i-1],sp[i])
seg += [ l ]
if l>0 :
seg = [seg[i]/l for i in xrange(len(seg))]
return seg,l
def rebuild_csp (csp, segs, s=None):
# rebuild_csp adds to csp control points making it's segments looks like segs
if s==None : s, l = csp_segments(csp)
if len(s)>len(segs) : return None
segs = segs[:]
segs.sort()
for i in xrange(len(s)):
d = None
for j in xrange(len(segs)):
d = min( [abs(s[i]-segs[j]),j], d) if d!=None else [abs(s[i]-segs[j]),j]
del segs[d[1]]
for i in xrange(len(segs)):
for j in xrange(0,len(s)):
if segs[i]<s[j] : break
if s[j]-s[j-1] != 0 :
t = (segs[i] - s[j-1])/(s[j]-s[j-1])
sp1,sp2,sp3 = csp_split(csp[j-1],csp[j], t)
csp = csp[:j-1] + [sp1,sp2,sp3] + csp[j+1:]
s = s[:j] + [ s[j-1]*(1-t)+s[j]*t ] + s[j:]
return csp, s
def csp_slope(sp1,sp2,t):
bez = (sp1[1][:],sp1[2][:],sp2[0][:],sp2[1][:])
return bezmisc.bezierslopeatt(bez,t)
def csp_line_intersection(l1,l2,sp1,sp2):
dd=l1[0]
cc=l2[0]-l1[0]
bb=l1[1]
aa=l2[1]-l1[1]
if aa==cc==0 : return []
if aa:
coef1=cc/aa
coef2=1
else:
coef1=1
coef2=aa/cc
bez = (sp1[1][:],sp1[2][:],sp2[0][:],sp2[1][:])
ax,ay,bx,by,cx,cy,x0,y0=bezmisc.bezierparameterize(bez)
a=coef1*ay-coef2*ax
b=coef1*by-coef2*bx
c=coef1*cy-coef2*cx
d=coef1*(y0-bb)-coef2*(x0-dd)
roots = cubic_solver(a,b,c,d)
retval = []
for i in roots :
if type(i) is complex and abs(i.imag)<1e-7:
i = i.real
if type(i) is not complex and -1e-10<=i<=1.+1e-10:
retval.append(i)
return retval
def csp_split_by_two_points(sp1,sp2,t1,t2) :
if t1>t2 : t1, t2 = t2, t1
if t1 == t2 :
sp1,sp2,sp3 = csp_split(sp1,sp2,t)
return [sp1,sp2,sp2,sp3]
elif t1 <= 1e-10 and t2 >= 1.-1e-10 :
return [sp1,sp1,sp2,sp2]
elif t1 <= 1e-10:
sp1,sp2,sp3 = csp_split(sp1,sp2,t2)
return [sp1,sp1,sp2,sp3]
elif t2 >= 1.-1e-10 :
sp1,sp2,sp3 = csp_split(sp1,sp2,t1)
return [sp1,sp2,sp3,sp3]
else:
sp1,sp2,sp3 = csp_split(sp1,sp2,t1)
sp2,sp3,sp4 = csp_split(sp2,sp3,(t2-t1)/(1-t1) )
return [sp1,sp2,sp3,sp4]
def csp_seg_split(sp1,sp2, points):
# points is float=t or list [t1, t2, ..., tn]