/
ted-editor.py
2581 lines (2320 loc) · 101 KB
/
ted-editor.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
import colorsys
import math as m
import pickle
import sys
import time
import collections
import tkinter as tk
from copy import deepcopy
from enum import Enum
from tkinter import filedialog
import numpy as np
from PIL import ImageTk, Image
import src.linalg as la
import src.read_ted as ted
from src import CanvasX as CX, raildefs
import src.biarc as biarc
from src.fsm import SavedFSM
######################################################################
class Heightmap:
def __init__(self, file, half_width):
self.heightmap = np.load(file)
self.half_width = half_width
print("loaded heightmap from", file)
def heightAt(self,p):
def interpol_bi(im, x, y):
x = np.asarray(x)
y = np.asarray(y)
x0 = np.floor(x).astype(int)
x1 = x0 + 1
y0 = np.floor(y).astype(int)
y1 = y0 + 1
x0 = np.clip(x0, 0, im.shape[1] - 1)
x1 = np.clip(x1, 0, im.shape[1] - 1)
y0 = np.clip(y0, 0, im.shape[0] - 1)
y1 = np.clip(y1, 0, im.shape[0] - 1)
Ia = im[y0, x0]
Ib = im[y1, x0]
Ic = im[y0, x1]
Id = im[y1, x1]
wa = (x1 - x) * (y1 - y)
wb = (x1 - x) * (y - y0)
wc = (x - x0) * (y1 - y)
wd = (x - x0) * (y - y0)
return wa * Ia + wb * Ib + wc * Ic + wd * Id
# 2d numpy array containing the data
hmm = self.heightmap["heightmap"]
# height values corresponding to 0 and 1 in the height map
hme = self.heightmap["extents"]
hmw = hmm.shape[0]
hmh = hmm.shape[1]
ex = self.half_width
ip = (p + ex) / (2 * ex) * la.coords(hmw, hmh)
hs = interpol_bi(hmm, ip[0], ip[1])
return hs * hme[1] + (1 - hs) * hme[0]
######################################################################
# global variables
the_scenery = {
"Andalusia" : {"id": 3,
"ct": "hm/andalusia-contours.npz",
"npz": "hm/andalusia.npz",
"ex": 3499.99975586,
"rd": "rd/andalusia.raildef"},
"Eifel" : {"id": 2,
"ct": "hm/eiffel-contours.npz",
"npz": "hm/eiffel.npz",
"ex": 9600.0,
"rd": "rd/eifel.raildef"},
"Eifel Flat" : {"id": 5,
"ct": "hm/eiffel-flat-contours.npz",
"npz": "hm/eiffel-flat.npz",
"ex": 9600.0,
"rd": "rd/eifel-flat.raildef"},
"Death Valley": {"id": 1,
"ct": "hm/death-valley-contours.npz",
"npz": "hm/death-valley.npz",
"ex": 3592.67358398,
"rd": "rd/death-valley.raildef"},
}
the_scenery = collections.OrderedDict(sorted(the_scenery.items()))
the_heightmap = Heightmap(the_scenery["Andalusia"]["npz"],
the_scenery["Andalusia"]["ex"])
###########################################################################
# enable imports in third party directory eledit
sys.path.append("eledit")
import eledit.eledit as eed
import eledit.readfile_2 as eed_rf2
import src.upload_ted as ut
###########################################################################
class Biarc:
def __init__(self, p0, t0, p1, t1, r):
self.p0 = p0
self.p1 = p1
self.t0 = la.unit(t0)
self.t1 = la.unit(t1)
self.r = r
self.JC = biarc.biarc_joint_circle(p0, t0, p1, t1)
self.J = biarc.biarc_joint_point(self.JC, r)
self.Jt = biarc.biarc_tangent_at_joint_point(self.J, p0, t0)
self.h1 = biarc.bezier_circle_from_two_points_and_tangent(self.p0, self.J, self.t0)
self.h2 = biarc.bezier_circle_from_two_points_and_tangent(self.J, self.p1, self.Jt)
self.cp1 = biarc.circleparam(self.p0, self.J, self.t0)
self.cp2 = biarc.circleparam(self.J, self.p1, self.Jt)
def joint(self):
return self.J
def circleparameters(self):
c1, k1, a1, l1 = self.cp1
c2, k2, a2, l2 = self.cp2
return c1, k1, a1, l1, c2, k2, a2, l2
def length(self):
c1, k1, a1, l1 = self.cp1
c2, k2, a2, l2 = self.cp2
return l1 + l2
def offset(self, o):
b = deepcopy(self)
b.h1 = biarc.offset_circle(b.h1, o)
b.h2 = biarc.offset_circle(b.h2, o)
b.JC = biarc.offset_circle(b.JC, o)
b.p0 = biarc.bezier2_h(0, b.h1)
b.J = biarc.bezier2_h(1, b.h1)
b.p1 = biarc.bezier2_h(1, b.h2)
b.cp1 = biarc.circleparam(b.p0, b.J, b.t0)
b.cp2 = biarc.circleparam(b.J, b.p1, b.Jt)
return b
def transform(self, xform):
self.p0 = biarc.transform_point(self.p0, xform)
self.p1 = biarc.transform_point(self.p1, xform)
self.t0 = la.unit(biarc.transform_vector(self.t0, xform))
self.t1 = la.unit(biarc.transform_vector(self.t1, xform))
self.JC = biarc.transform_bezier_circle(self.JC, xform)
self.J = biarc.transform_point(self.J, xform)
self.Jt = la.unit(biarc.transform_vector(self.Jt, xform))
self.h1 = biarc.transform_bezier_circle(self.h1, xform)
self.h2 = biarc.transform_bezier_circle(self.h2, xform)
self.cp1 = biarc.circleparam(self.p0, self.J, self.t0)
self.cp2 = biarc.circleparam(self.J, self.p1, self.Jt)
def t_and_hs_of_rsl(self, rsl):
c1, k1, a1, l1, c2, k2, a2, l2 = self.circleparameters()
s = rsl * (l1 + l2)
rs = 0
if s < l1:
rs = s / l1
t = biarc.bc_arclen_t(rs, a1)
return t, self.h1
else:
rs = (s - l1) / l2
t = biarc.bc_arclen_t(rs, a2)
return t, self.h2
def eval(self, rsl):
"""eval biarc at rsl from 0 to 1, meaning arc length/total biarc length"""
t, hs = self.t_and_hs_of_rsl(rsl)
return biarc.bezier2_h(t, hs)
def eval_t(self, rsl):
"""eval biarc tangent at rsl from 0 to 1, meaning arc length/total biarc length"""
t, hs = self.t_and_hs_of_rsl(rsl)
return la.unit(biarc.bezier2_dr(t, hs))
def evalJ(self, t):
"""eval joint circle from -1 to 1"""
return biarc.circle2_h(t, self.JC)
def dist_sqr_at_l(self, p):
"""return squared distance and arc length at nearest point to p on biarc"""
p1, t1, cha1 = biarc.point_on_circle(self.p0, self.J, self.t0, p)
p2, t2, cha2 = biarc.point_on_circle(self.J, self.p1, self.Jt, p)
c1, k1, a1, l1, c2, k2, a2, l2 = self.circleparameters()
mind, minl = None, None
if 0 < t1 < 1:
mind = la.norm2(p1 - p)
aa1 = 2 * m.acos(cha1)
minl = aa1 / abs(k1) if k1 != 0 else t1 * l1
if 0 < t2 < 1 and (not mind or la.norm2(p2 - p) < mind):
mind = la.norm2(p2 - p)
aa2 = 2 * m.acos(cha2)
minl = l1 + (aa2 / abs(k2) if k2 != 0 else t2 * l2)
return mind, minl
###########################################################################
class Straight:
def __init__(self, p0, p1):
self.p0 = p0
self.p1 = p1
def length(self):
return la.norm(self.p1 - self.p0)
def offset(self, o):
pt = la.perp2ccw(la.unit(self.p1 - self.p0))
return Straight(self.p0 + pt * o, self.p1 + pt * o)
def eval(self, t):
return biarc.lerp(t, self.p0, self.p1)
def eval_t(self, t):
return la.unit(self.p1 - self.p0)
def dist_sqr_at_l(self, p):
"""return squared distance to p and length of segment at nearest point"""
def line_seg_distance_sqr_and_length(p0, p1, p):
chord = p0 - p1
top = p0 - p
pa = la.para(top, chord)
if la.dot(pa, chord) < 0:
return la.norm2(p - p0), 0 # distance to first point
elif la.norm2(chord) < la.norm2(pa):
return la.norm2(p - p1), la.norm(chord) # distance to last point
else:
return la.norm2(la.perp(top, chord)), la.norm(pa) # distance to line segment
return line_seg_distance_sqr_and_length(self.p0, self.p1, p)
def transform(self, xform):
self.p0 = biarc.transform_point(self.p0, xform)
self.p1 = biarc.transform_point(self.p1, xform)
def circleparameters(self):
c1, k1, a1, l1 = (0, 0), 0, 0, la.norm(self.p0 - self.p1)
c2, k2, a2, l2 = (0, 0), 0, 0, 0
return c1, k1, a1, l1, c2, k2, a2, l2
###########################################################################
class CCPoint:
def __init__(self, point=la.coords(0, 0), tangent=None):
self.point = point
self.tangent = tangent
###########################################################################
class SegType(Enum):
Straight = 1
Biarc = 2
###########################################################################
def canvas_create_circle(canvas, p, r, **kw):
"convenience canvas draw routine"
return canvas.create_oval([p[0] - r, p[1] - r, p[0] + r, p[1] + r], **kw)
###########################################################################
class Banking:
def __init__(self, angle=0, prev_len=0, next_len=0):
self.angle = angle
self.prev_len = prev_len
self.next_len = next_len
def reverse(self):
self.angle = -self.angle
self.prev_len, self.next_len = self.next_len, self.prev_len
###########################################################################
class CCSegment:
def __init__(self, p1, p2, type=SegType.Straight, biarc_r=0.5):
self.ps = p1
self.pe = p2
self.type = type
self.biarc_r = biarc_r
self.banking = [Banking(), Banking()]
self.heights = [[], []]
self.seg = None
self.heights_need_update = True
self.setup()
def setup(self):
if self.type is SegType.Straight:
self.ps.tangent = self.pe.tangent = la.unit(self.pe.point - self.ps.point)
self.seg = Straight(self.ps.point, self.pe.point)
#self.np = 2
else:
if self.pe.tangent is None:
self.pe.tangent = la.unit(la.refl(self.ps.tangent,
self.ps.point - self.pe.point))
self.seg = Biarc(self.ps.point, self.ps.tangent,
self.pe.point, self.pe.tangent,
self.biarc_r)
self.heights_need_update = True
def offset(self,o):
return self.seg.offset(o)
def length(self):
return self.seg.length()
def eval(self,t):
return self.seg.eval(t)
def eval_t(self,t):
return self.seg.eval_t(t)
def shapeparameters(self):
""" returns end points, lengths, curvature, center of circle of subsegments"""
divl = 4.0
mindiv = 6
if self.type is SegType.Straight:
l = self.length()
div = max(mindiv, int(m.ceil(l / divl)))
return [(self.pe.point, l, div, 0, la.coords(0, 0))]
else:
c1, k1, a1, l1, c2, k2, a2, l2 = self.seg.circleparameters()
div1 = max(mindiv, int(m.ceil(l1 / divl)))
div2 = max(mindiv, int(m.ceil(l2 / divl)))
return [(self.seg.J, l1, div1, k1, c1), (self.pe.point, l2, div2, k2, c2)]
def num_subsegments(self):
return len(self.shapeparameters())
def set_heights(self, heights):
self.heights = heights
self.heights_need_update = False
sys.stdout.flush()
def calc_heights(self, heightmap):
sps = self.shapeparameters()
hs = heightmap.heightAt(self.ps.point)
for j, sp in enumerate(sps):
hgts = []
ep, l, div, k, center = sp
he = heightmap.heightAt(ep)
for d in range(div):
hgts.append(hs * (div - d) / div + he * d / div)
self.heights[j] = hgts
hs = he
self.heights_need_update = False
def reverse(self):
# reverse endpoints from point array
self.ps, self.pe = self.pe, self.ps
# reverse biarc parameter
self.biarc_r = 1 - self.biarc_r
# banking and height data reverse
self.banking.reverse()
for b in self.banking:
b.reverse()
self.heights.reverse()
for h in self.heights:
h.reverse()
self.setup()
#self.heights_need_update = False
def transform(self, xform):
self.seg.transform(xform)
# TODO: scale offset without altering width
#for i, p in enumerate(self.poly):
# self.poly[i] = biarc.transform_point(p, xform)
###########################################################################
def offsetLine(segment, ts, te, o, n):
so = segment.offset(o)
ots = ts
ote = te
if isinstance(segment, Biarc):
c1, k1, a1, l1, c2, k2, a2, l2 = segment.circleparameters()
oc1, ok1, oa1, ol1, oc2, ok2, oa2, ol2 = so.circleparameters()
ss = ts * (l1 + l2)
se = te * (l1 + l2)
if ss < l1:
oss = ss / l1 * ol1
ots = oss / (ol1 + ol2)
else:
oss = ol1 + (ss - l1) / l2 * ol2
ots = oss / (ol1 + ol2)
if se < l1:
ose = se / l1 * ol1
ote = ose / (ol1 + ol2)
else:
ose = ol1 + (se - l1) / l2 * ol2
ote = ose / (ol1 + ol2)
cas = []
nn = max(n, 2)
for j in range(nn):
# TODO: distribute points evenly over both segments of biarc
t = biarc.lerp(j / (nn - 1), ots, ote)
p = so.eval(t)
cas.append(p)
return cas
def offsetPolygon(segment, ts, te, o1, o2, n):
return offsetLine(segment, ts, te, o1, n) + offsetLine(segment, te, ts, o2, n)
###########################################################################
class ControlCurve:
def __init__(self,width):
self.width = width
self.scenery = None
self.isOpen = True
self.point = []
self.segment = []
self.checkpoint = []
self.road = []
self.deco = []
def __segmentsof(self, cp):
return [s for s in self.segment if s.ps is cp or s.pe is cp]
def __neighborsof(self, seg):
return [s for s in self.segment if seg.ps is s.pe or seg.pe is s.ps]
def __setupCp(self, cp):
so = self.__segmentsof(cp)
for s in so:
if s.type is SegType.Straight:
return self.__setupSeg(s)
else:
s.setup()
return so
def __setupSeg(self, seg):
seg.setup()
nb = self.__neighborsof(seg)
for s in nb:
s.setup()
nb.append(seg)
return nb
def length(self):
"total length of control curve"
tl = 0
for s in self.segment:
tl += s.length()
return tl
def segmentAndTAt(self, l):
seg = None
tl = l
sl = 0
while not seg:
for s in self.segment:
sl = s.length()
if tl > sl:
tl -= sl
else:
seg = s
break
t = tl / sl
return seg, t
def pointAt(self, l):
s, t = self.segmentAndTAt(l)
# print("pointAt",l,s,t,s.seg.eval(t))
return s.eval(t)
def tangentAt(self, l):
s, t = self.segmentAndTAt(l)
return s.eval_t(t)
def pointAndTangentAt(self, l):
s, t = self.segmentAndTAt(l)
return s.eval(t), s.eval_t(t)
def nearest(self, p):
mind = 100000000
minl = None
tl = 0
for s in self.segment:
d, l = s.seg.dist_sqr_at_l(p)
if d is not None and mind > d:
mind = d
minl = tl + l
# print("shorter!",d,l)
tl += s.seg.length()
return minl
# internal functions
def fixedSegmentPoints(self, seg):
# return all points that have to move to leave seg fixed
cps = set()
cps.add(seg.ps)
cps.add(seg.pe)
for s in self.__neighborsof(seg):
if s.type is SegType.Straight:
cps.add(s.ps)
cps.add(s.pe)
return cps
# manipulation methods:
def setTangent(self, cp, t):
cp.tangent = t
return self.__setupCp(cp)
def setPointAndTangent(self, cp, p, t):
cp.point = p
cp.tangent = t
return self.__setupCp(cp)
def transformPoints(self, cps, xform):
segments = []
for cp in cps:
cp.point = biarc.transform_point(cp.point, xform)
cp.tangent = la.unit(biarc.transform_vector(cp.tangent, xform))
so = self.__segmentsof(cp)
for s in so:
if s.type is SegType.Straight:
so.extend(self.__neighborsof(s))
segments.extend(so)
transformable = set()
reset = set()
for s in segments:
if s in reset:
reset.remove(s)
transformable.add(s)
else:
reset.add(s)
for s in transformable:
s.transform(xform)
for s in reset:
self.__setupSeg(s)
return reset.union(transformable)
def movePoint(self, cp, vec):
cp.point = cp.point + vec
return self.__setupCp(cp)
def moveJoint(self, seg, p):
J = seg.seg.joint()
p0 = seg.ps.point
t0 = seg.ps.tangent
p1 = seg.pe.point
t1 = seg.pe.tangent
tj = biarc.biarc_joint_circle_tangent(p0, t0, p1, t1)
pc, t, a = biarc.point_on_circle(p0, p1, tj, p)
seg.biarc_r = t
seg.setup()
d = pc - J # displacement of joint point
# print (pc,seg.seg.joint(),pc2,pc2-pc)
return [seg], d[0], d[1]
def tangentUpdateable(self, cp):
for s in self.__segmentsof(cp):
# print(" ",s.type,s.ps.point,s.pe.point)
if s.type is SegType.Straight:
return False
return True
# all manipulating functions return the affected segments
def toggleOpen(self, *args):
if self.isOpen:
close = CCSegment(self.point[-1], self.point[0], SegType.Biarc, *args)
self.segment.append(close)
self.isOpen = False
return close
else:
rem = self.segment.pop()
self.isOpen = True
return rem
# returns the new point, the new segments and all affected segments
def changeType(self, seg):
if seg is self.segment[0]: # first segment has to stay straight
return []
if seg.type is SegType.Biarc:
for s in self.__neighborsof(seg):
if s.type == SegType.Straight:
return []
seg.type = SegType.Straight
else:
seg.type = SegType.Biarc
return self.__setupSeg(seg)
def insertPoint(self, seg, p, *args):
"""insert a control point and return the point, the newly created segment and the affected segments of this operation"""
cp = CCPoint(p)
if not self.point: # first point
self.point.append(cp)
return cp, None, None
if not self.segment and len(self.point) == 1: # first segment
args = [SegType.Straight if x == SegType.Biarc else x for x in args]
newseg = CCSegment(self.point[0], cp, *args)
self.point.append(cp)
self.segment.append(newseg)
return cp, newseg, newseg
si = None
if seg is None: # append at end
si = len(self.segment)
newseg = CCSegment(self.point[si], cp, *args)
else: # split an existing segment
pe, seg.pe = seg.pe, cp
seg.setup()
newseg = CCSegment(cp, pe, *args)
si = self.segment.index(seg)
self.point.insert(si + 2, cp)
self.segment.insert(si + 1, newseg)
aff = self.__setupSeg(newseg)
return cp, newseg, aff
def appendPoint(self, p, *args):
return self.insertPoint(None, p, *args)
def removePoint(self, cp):
if cp is self.point[0] or cp is self.point[1]:
return [] # don't remove first point or segment
segs = self.__segmentsof(cp)
if len(segs) > 1:
segs[1].ps = segs[0].ps
self.point.remove(cp)
self.segment.remove(segs[0])
aff = []
if len(segs) > 1:
aff = self.__setupSeg(segs[1])
# add removed segs[0] to clear canvas items in redraw
return [segs[0]] + aff
def reverse(self):
# reverse lists and reset start to old point 1 and segment 0
self.point.reverse()
self.point.insert(0, self.point.pop())
self.point.insert(0, self.point.pop())
self.segment.reverse()
self.segment.insert(0, self.segment.pop())
# reverse tangents
for p in self.point:
p.tangent = -p.tangent
# print("point",p.point,p.tangent)
# reverse start and end points in segments
for s in self.segment:
s.reverse()
# print("segment",s.type,s.ps.point,s.pe.point)
# print(self.pointAt(0))
return self.segment # all are affected
def offsetPolygonAt(self, ls, le, o1, o2 = None):
""" constructs an offset polygon of width w along the track from ls to le"""
if o2 is None:
o2 = o1/2
o1 = -o1/2
tls = min(ls, le)
tle = max(ls, le)
sl = 0
front = []
back = []
for s in self.segment:
sl = s.length()
if tls < sl:
ts = tls / sl if tls > 0 else 0
te = tle / sl if tle < sl else 1
front += offsetLine(s.seg, ts, te, o1, 16)
back += offsetLine(s.seg, ts, te, o2, 16)
tls -= sl
tle -= sl
if tls <= 0 and tle <= 0:
break
back.reverse()
return front + back
def drawSegment(self, seg, canvas, inclText=True, **config):
# returns a list of the cids of the canvas items or
# None if segment isn't in the curve
def segmentOffsetPoly(seg,width):
front = []
back = []
shapes = seg.shapeparameters()
sl = seg.length()
dl = 0
o = width/2
for j, shape in enumerate(shapes):
ep, l, div, k, center = shape
n = max(2,min(32,int(abs(3 * 2*k*m.pi)*l)))
s = dl/sl
e = (dl+l)/sl
front += offsetLine(seg,s,e,-o,n)
back += offsetLine(seg,s,e,+o,n)
dl += l
back.reverse()
return front+back
def segmentDraw(seg, canvas, cids=None, **kw):
if not cids: cids = []
poly = segmentOffsetPoly(seg,self.width)
cids.append(canvas.create_polygon([(x[0], x[1]) for x in poly], **kw))
return cids
def segmentText(seg, canvas, cids=None, **kw):
if not cids: cids = []
shapes = seg.shapeparameters()
sl = seg.length()
dl = 0
for j, shape in enumerate(shapes):
ep, l, div, k, center = shape
if abs(k) < 1 / 300:
stext = "\n{:.0f}".format(l)
else:
stext = "{:.0f} R\n{:.0f}".format(1 / k, l)
h = seg.eval(0.5 * (dl+l) / sl)
cids.append(canvas.create_text([h[0], h[1]],
text=stext,
tags="segment"))
dl += l
return cids
def segmentExtra(self, canvas, cids=None, **kw):
if not cids: cids = []
# if self.type is SegType.Straight:
# return cids
# t1 = biarc.bezier2_dr(1, self.seg.h1)
# t2 = biarc.bezier2_dr(0, self.seg.h2)
# J = self.seg.joint()
# cids.append(canvas.create_line([self.ps.point[0], self.ps.point[1], self.pe.point[0], self.pe.point[1]],
# tags="segment"))
# cids.append(canvas.create_line([J[0], J[1], J[0] + t1[0], J[1] + t1[1]], tags="segment"))
# cas = []
# nn = 32
# cj, kj, aj, lj = self.seg.circleparameters()
# for j in range(nn):
# t = biarc.lerp(j / (nn - 1), -1, 1)
# tt = biarc.bc_arclen_t(abs(t), aj if t > 0 else 2 * m.pi - aj)
# p = self.seg.evalJ(tt if t > 0 else -tt)
# cas.append(p)
# cids.append(canvas.create_line([(x[0], x[1]) for x in cas], tags="segment"))
return cids
if seg in self.segment:
cids = segmentDraw(seg,canvas,**config)
if inclText:
segmentText(seg,canvas, cids, **config)
# segmentExtra(seg,canvas,cids,**config)
return cids
else:
return None
def draw(self, canvas, inclText=True, **config):
# returns a map of segments to a list of cids of the canvas items
seg2cids = {}
for s in self.segment:
seg2cids[s] = self.drawSegment(s, canvas, inclText, **config)
return seg2cids
def importTed(self, tedfile):
hdr = ted.ted_data_to_tuple("header", ted.header, tedfile, 0)
cps = ted.ted_data_to_tuple_list("cp", ted.cp, tedfile,
hdr.cp_offset, hdr.cp_count)
banks = ted.ted_data_to_tuple_list("bank", ted.segment, tedfile,
hdr.bank_offset, hdr.bank_count)
heights = ted.ted_data_to_tuple_list("height", ted.height, tedfile,
hdr.height_offset, hdr.height_count)
checkps = ted.ted_data_to_tuple_list("checkpoints", ted.checkpoint, tedfile,
hdr.checkpoint_offset, hdr.checkpoint_count)
road = ted.ted_data_to_tuple_list("road", ted.road, tedfile,
hdr.road_offset, hdr.road_count)
deco = ted.ted_data_to_tuple_list("decoration", ted.decoration, tedfile,
hdr.decoration_offset, hdr.decoration_count)
self.width = hdr.road_width
self.scenery = hdr.scenery
self.isOpen = True
self.point = []
self.segment = []
self.road = []
self.deco = []
self.checkpoint = []
def set_banking(banking, bank):
banking.angle = bank.banking
banking.prev_len = bank.transition_prev_vlen
banking.next_len = bank.transition_next_vlen
def get_segment_heights(heights, bank):
sh = [heights[j].height for j in range(bank.total_divisions,
bank.total_divisions + bank.divisions)]
return sh
for i, cp in enumerate(cps):
prev = cps[i - 1]
lx = (cps[i - 1].x - cp.x)
ly = (cps[i - 1].y - cp.y)
l = m.sqrt(lx * lx + ly * ly)
if ted.SegType(cp.segtype) == ted.SegType.Straight:
# straight segment
p, seg, _ = self.appendPoint(la.coords(cp.x, cp.y), SegType.Straight)
if seg:
set_banking(seg.banking[0], banks[i - 1])
hs = get_segment_heights(heights, banks[i - 1])
seg.set_heights([hs, []])
# second arc of biarc segment
segarc2 = (ted.SegType(cp.segtype) == ted.SegType.Arc2CCW or
ted.SegType(cp.segtype) == ted.SegType.Arc2CW)
prevsegarc1 = (ted.SegType(prev.segtype) == ted.SegType.Arc1CCW or
ted.SegType(cp.segtype) == ted.SegType.Arc1CW)
segnearly = ted.SegType(cp.segtype) == ted.SegType.NearlyStraight
prevsegnearly = ted.SegType(prev.segtype) == ted.SegType.NearlyStraight
if segarc2 or segnearly and (prevsegarc1 or prevsegnearly):
p1 = la.coords(cps[i - 0].x, cps[i - 0].y)
joint = la.coords(cps[i - 1].x, cps[i - 1].y)
p0 = la.coords(cps[i - 2].x, cps[i - 2].y)
dx = (cp.x - cp.center_x)
dy = (cp.y - cp.center_y)
if ted.SegType(cp.segtype) == ted.SegType.Arc2CCW:
t = la.unit(la.coords(dy, -dx))
if ted.SegType(cp.segtype) == ted.SegType.Arc2CW:
t = la.unit(la.coords(-dy, dx))
if ted.SegType(cp.segtype) == ted.SegType.NearlyStraight:
t = la.unit(la.coords(cp.x - prev.x, cp.y - prev.y))
biarc_r = la.norm(joint - p0) / (la.norm(joint - p0) + la.norm(joint - p1))
# biarc_r = bezier_circle_parameter(p0,p1,self.cc.point[-1].tangent,joint)
p, seg, _ = self.appendPoint(la.coords(cp.x, cp.y), SegType.Biarc, biarc_r)
p.tangent = t
set_banking(seg.banking[0], banks[i - 2])
set_banking(seg.banking[1], banks[i - 1])
hs1 = get_segment_heights(heights, banks[i - 2])
hs2 = get_segment_heights(heights, banks[i - 1])
seg.set_heights([hs1, hs2])
# ted file contains first point as last point if track is closed, fix it:
if hdr.is_loop:
self.segment[-1].pe = self.segment[0].ps
self.segment[-1].setup()
self.point.pop() # remove duplicated last point
self.isOpen = False
for s in self.segment: # quick fix for setup update madness while importing
s.heights_need_update = False
def neighborhood(iterable):
iterator = iter(iterable)
prev = None
current = next(iterator) # throws StopIteration if empty.
for next_item in iterator:
yield (prev, current, next_item)
prev,current = current,next_item
yield (prev, current, None)
for c in checkps:
self.checkpoint.append(c.vpos3d)
for r in road:
self.road.append(r)
for d in deco:
self.deco.append(d)
def exportTed(self):
# convert ted
TedCp = ted.ted_data_tuple("cp", ted.cp)
TedSeg = ted.ted_data_tuple("segment", ted.segment)
segs = []
total_l = 0
total_div = 0
total_heights = []
eps = 2 ** -16
# control points always include first point, first segment is always straight
cps = [TedCp(segtype=int(ted.SegType.Straight.value),
x=self.segment[0].ps.point[0],
y=self.segment[0].ps.point[1],
center_x=0,
center_y=0)]
for i, seg in enumerate(self.segment):
if seg.heights_need_update:
seg.calc_heights(the_heightmap)
for j, sp in enumerate(seg.shapeparameters()):
ep, l, div, k, center = sp
bk = seg.banking[j]
hgts = seg.heights[j]
bdiv = len(hgts)
if seg.type is SegType.Straight:
segtype = ted.SegType.Straight
elif abs(k) < eps:
segtype = ted.SegType.NearlyStraight
elif j == 0:
segtype = ted.SegType.Arc1CW if k > 0 else ted.SegType.Arc1CCW
elif j == 1:
segtype = ted.SegType.Arc2CW if k > 0 else ted.SegType.Arc2CCW
cps.append(TedCp(segtype=int(segtype.value),
x=ep[0],
y=ep[1],
center_x=center[0],
center_y=center[1]))
segs.append(TedSeg(banking=bk.angle,
transition_prev_vlen=bk.prev_len,
transition_next_vlen=bk.next_len,
divisions=bdiv,
total_divisions=total_div,
vstart=total_l,
vlen=l))
# print("seg",l,div,total_div,l,total_l)
total_l += l
total_div += bdiv
total_heights.extend(hgts)
TedHgt = ted.ted_data_tuple("height", ted.height)
tedheights = []
for h in total_heights:
tedheights.append(TedHgt(height=h))
# always include first height value as last (TODO: check if valid for open tracks)
tedheights.append(tedheights[0])
eldiff = max(total_heights) - min(total_heights)
TedCheck = ted.ted_data_tuple("checkpoint", ted.checkpoint)
chps = []
for cp in self.checkpoint:
chps.append(TedCheck(vpos3d = cp))
# convert road railunits
TedRoad = ted.ted_data_tuple("road", ted.road)
roads = [] # holds new road elements, can be more or less than elements in self.road
for r in self.road: # all road elements in the imported ted file
roads.append(TedRoad(uuid=r.uuid,
side=r.side,
vstart3d=r.vstart3d,
vend3d=r.vend3d))
# convert decoration railunits
TedDeco = ted.ted_data_tuple("deco", ted.decoration)
decos = []
for d in self.deco:
decos.append(TedDeco(uuid=d.uuid,
side=d.side,
vstart3d=d.vstart3d,
vend3d=d.vend3d,
tracktype=d.tracktype))
# build new tedfile
TedHdr = ted.ted_data_tuple("hdr", ted.header)
hdr = TedHdr(id=b"GT6TED\0\0",
version=104,
scenery=self.scenery,
road_width=self.width,
track_width_a=self.width,
track_width_b=self.width,
track_length=total_l,
datetime=int(time.time()),
is_loop=0 if self.isOpen else 1,
home_straight_length=700,
elevation_diff=eldiff,
num_corners=4, # TODO: calc
finish_line=0,
start_line=412.0769348144531, # TODO: from raildef
empty1_offset=0,
empty1_count=0,
empty2_offset=0,
empty2_count=0,
empty3_offset=0,
empty3_count=0)
tedsz = (ted.ted_data_size(ted.header) +
ted.ted_data_size(ted.cp) * len(cps) +
ted.ted_data_size(ted.segment) * len(segs) +
ted.ted_data_size(ted.height) * len(tedheights) +
ted.ted_data_size(ted.checkpoint) * len(chps) +
ted.ted_data_size(ted.road) * len(roads) +
ted.ted_data_size(ted.decoration) * len(decos))
tedfile = bytearray(b'\x00' * tedsz)
hdr = hdr._replace(scenery=self.scenery,
track_length=total_l,
elevation_diff=eldiff)
hdrsz = ted.ted_data_size(ted.header)
# o = ted.tuple_to_ted_data(hdr,ted.header,self.tedfile,0)
hdr = hdr._replace(cp_offset=hdrsz, cp_count=len(cps))
o = ted.tuple_list_to_ted_data(cps, ted.cp, tedfile, hdr.cp_offset, hdr.cp_count)
hdr = hdr._replace(bank_offset=o, bank_count=len(segs))
o = ted.tuple_list_to_ted_data(segs, ted.segment, tedfile, hdr.bank_offset, hdr.bank_count)
hdr = hdr._replace(height_offset=o, height_count=len(tedheights))
o = ted.tuple_list_to_ted_data(tedheights, ted.height, tedfile, hdr.height_offset, hdr.height_count)
hdr = hdr._replace(checkpoint_offset=o, checkpoint_count=len(chps))
o = ted.tuple_list_to_ted_data(chps, ted.checkpoint, tedfile, hdr.checkpoint_offset, hdr.checkpoint_count)
hdr = hdr._replace(road_offset=o, road_count=len(roads))
o = ted.tuple_list_to_ted_data(roads, ted.road, tedfile, hdr.road_offset, hdr.road_count)
hdr = hdr._replace(decoration_offset=o, decoration_count=len(decos))
o = ted.tuple_list_to_ted_data(decos, ted.decoration, tedfile, hdr.decoration_offset, hdr.decoration_count)
ted.tuple_to_ted_data(hdr, ted.header, tedfile, 0)
return tedfile
###########################################################################
def rgb2hex(rgb_tuple):
""" convert an (R, G, B) tuple to #RRGGBB """
return '#%02x%02x%02x' % tuple(int(x * 255) for x in rgb_tuple)
def hex2rgb(hexstring):
""" convert #RRGGBB to an (R, G, B) tuple """
hexstring = hexstring.strip()
if hexstring[0] == '#': hexstring = hexstring[1:]
if len(hexstring) != 6:
raise ValueError("input #%s is not in #RRGGBB format" % hexstring)
r, g, b = hexstring[:2], hexstring[2:4], hexstring[4:]
r, g, b = [int(n, 16) for n in (r, g, b)]
return r / 255, g / 255, b / 255
def rgb_lighten_saturate(rgb, dl,ds):
hls = colorsys.rgb_to_hls(*rgb)
hls = (hls[0], hls[1] + dl, hls[2] + ds)
return colorsys.hls_to_rgb(*hls)
def hex_lighten_saturate(hexstr, dl, ds):
hls = colorsys.rgb_to_hls(*hex2rgb(hexstr))
hls = (hls[0], hls[1] + dl, hls[2] + ds)
return rgb2hex(colorsys.hls_to_rgb(*hls))
def style_active(style, lighten, saturate, thicken):
if "fill" in style and style["fill"]:
style["activefill"] = hex_lighten_saturate(style["fill"], lighten, saturate)
if "outline" in style:
style["activeoutline"] = hex_lighten_saturate(style["outline"], lighten, saturate)
if "width" in style:
style["activewidth"] = style["width"] + thicken
return style
def style_modified(style, lighten, saturate, thicken):
style = deepcopy(style)
if "fill" in style and style["fill"]:
style["fill"] = hex_lighten_saturate(style["fill"], lighten, saturate)
if "activefill" in style and style["activefill"]:
style["activefill"] = hex_lighten_saturate(style["activefill"], lighten, saturate)
if "outline" in style:
style["outline"] = hex_lighten_saturate(style["outline"], lighten, saturate)
if "activeoutline" in style:
style["activeoutline"] = hex_lighten_saturate(style["activeoutline"], lighten, saturate)
if "width" in style:
style["width"] = style["width"] + thicken
if "activewidth" in style:
style["activewidth"] = style["activewidth"] + thicken
return style
def style_config_mod(cfg, lighten, saturate, thicken):
style = {}