-
Notifications
You must be signed in to change notification settings - Fork 1
/
LineRiderP_1.5d.py
1887 lines (1762 loc) · 70.2 KB
/
LineRiderP_1.5d.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
#LineRiderP_1.5b.py
#David Lu + delu + section A
from Tkinter import *
import Tkinter, tkMessageBox
import time
import math
import random
import os
import copy
import pickle
#import cucumber
#import cherry
#import pomegranate
#collision detection adapted from
#www.t3hprogrammer.com/research/line-circle-collision/tutorial
#rigid body dynamics adapted from
#www.gpgstudy.com/gpgiki/GDC 2001%3A Advanced Character Physics
"""
x, y are coordinates
r is a position vector made of <x,y>
p is a point that is interacting with physics
p, q are arbitrary coordinates (x, y)
u, v are arbitrary vectors <x, y>
line is a line segment made of two position vectors
cnstr is a constraint made of two points
"""
###############################################################################
# ~ VECTORS 'N STUFF ~
###############################################################################
class vector(object):
#slots for optimization...?
# __slots__ = ('x', 'y')
def __init__(self, x, y = 0):
if type(x) == tuple:
x, y = x[0], x[1]
self.x = float(x)
self.y = float(y)
def __repr__(self):
return "vector"+str((self.x, self.y))
#vector addition/subtraction
def __add__(self, other):
return vector(self.x+other.x, self.y+other.y)
def __sub__(self, other):
return vector(self.x-other.x, self.y-other.y)
def __iadd__(self,other):
self.x += other.x; self.y += other.y
return self
def __isub__(self,other):
self.x -= other.x; self.y -= other.y
return self
#scalar multiplication/division
def __mul__(self, other):
"""exception: if other is also a vector, DOT PRODUCT
I do it all the time in my 3d calc hw anyways :|"""
if isinstance(other, vector):
return dot(self, other)
else: return vector(self.x*other, self.y*other)
def __div__(self, other):
return vector(self.x/other, self.y/other)
def __imul__(self,other):
self.x *= other; self.y *= other
return self
def __idiv__(self, other):
self.x /= other; self.y /= other
return self
def magnitude2(self):
"""the square of the magnitude of this vector"""
return distance2((self.x, self.y), (0,0))
def magnitude(self):
"""magnitude of this vector)"""
return distance((self.x, self.y), (0,0))
def normalize(self):
"""unit vector. same direction but with a magnitude of 1"""
if (self.x, self.y) == (0,0): return vector(0,0)
else: return self/self.magnitude()
def rotate(self, other):
"""rotates vector in radians"""
x = self.x*math.cos(other) - self.y*math.sin(other)
y = self.x*math.sin(other) + self.y*math.cos(other)
return vector(x, y)
def getAngle(self):
"""gets angle of vector relative to x axis"""
return math.atan2(self.y, self.x)
# x**0.5 is annoying to compute, in python and in real life, it's a bit faster
def distance2(p, q):
"""distance squared between these points"""
if isinstance(p, vector) and isinstance(q, vector):
return (p.x-q.x)**2 + (p.y-q.y)**2
else:
return (p[0]-q[0])**2 + (p[1]-q[1])**2
def distance(p, q):
"""distance between these points"""
return distance2(p, q)**0.5
def dot(u, v):
"""dot product of these vectors, a scalar"""
return u.x*v.x + u.y*v.y
def cross(u, v):
"""magnitude of the cross product of these vectors"""
return det(u.x, u.y, v.x, v.y)
###############################################################################
# ~ MOAR LINEAR ALGEBRA ~
###############################################################################
class Line(object):
"""lines are defined by two points, p1 and p2"""
# __slots__ = ('r1', 'r2') #I ANTICIPATE THOUSANDS OF LINES
def __init__(self, r1, r2):
#points are position vectors
if isinstance(r1, vector) and isinstance(r2, vector):
self.r1 = r1
self.r2 = r2
else: #inputs are tuples
self.r1 = vector(r1[0], r1[1])
self.r2 = vector(r2[0], r2[1])
def __repr__(self):
return "Line"+str((self.r1, self.r2, self.lineType))
def linearEquation(self):
"""in the form of ax+by=c"""
a = self.r2.y - self.r1.y
b = self.r1.x - self.r2.x
c = a*self.r1.x + b*self.r1.y
return a, b, c
class Point(object):
"""points have position and velocity implied by previous position"""
def __init__(self, *args):
x, y = args[0], args[1]
#current position
self.r = vector(x, y)
#position one frame before. no value, set to same as x,y
if len(args) == 2:
x0, y0 = x, y
self.r0 = vector(x0, y0)
def __repr__(self):
return "Point"+str( (self.r, self.r0) )
def intersectPoint(line1, line2):
"""Returns the coordinates of intersection between line segments.
If the lines are not intersecting, returns None."""
a1,b1,c1 = line1.linearEquation()
a2,b2,c2 = line2.linearEquation()
d = det(a1, b1, a2, b2)
if d == 0: return None
x = 1.0*det(c1, b1, c2, b2)/d
y = 1.0*det(a1, c1, a2, c2)/d
intersection = vector(x, y)
if (isInLineRegion(intersection, line1)
and isInLineRegion(intersection, line2)):
return intersection #position vector of point of intersection
def det(a, b, c, d):
"""determinant"""
# | a b |
# | c d |
return a*d - b*c
def isInLineRegion(r, line):
"""rectangular region defined by endpoints of a line segment or points"""
return isInRegion(r, line.r1, line.r2)
def isInRegion(r, pnt1, pnt2):
if isinstance(pnt1, vector):
x1, x2, y1, y2 = pnt1.x, pnt2.x, pnt1.y, pnt2.y
else:
x1, x2, y1, y2 = pnt1[0], pnt2[0], pnt1[1], pnt2[1]
if isinstance(r, vector):
rx, ry = r.x, r.y
else:
rx, ry = r[0], r[1]
x1, x2 = min(x1, x2), max(x1, x2)
y1, y2 = min(y1, y2), max(y1, y2)
isInRect = x1<= rx <=x2 and y1<= ry <=y2
isOnHLine = x1==x2 and almostEqual(x1,rx) and y1 <= ry <= y2
isOnVLine = y1==y2 and almostEqual(y1,ry) and x1 <= rx <= x2
return isInRect or isOnHLine or isOnVLine
def almostEqual(a, b):
return abs(a-b) < canvas.data.epsilon/100
def closestPointOnLine(r, line):
"""closest point on a line to a point(position vector)"""
a, b, c1 = line.linearEquation()
c2 = -b*r.x + a*r.y
d = det(a, b, -b, a)
if d == 0:
point = r #POINT IS ON LINE
else:
x = det(a, b, c2, c1)/d
y = det(a, -b, c1, c2)/d
point = vector(x, y) #it's a position vector!
return point
def distanceFromLine(r, line):
"""distance between a point and a line segment"""
linePoint = closestPointOnLine(r, line)
if isInLineRegion(linePoint, line):
dist = distance(r, linePoint)
else:
dist = min(distance(r, line.r1), distance(r, line.r2))
return dist
###############################################################################
# ~ POINT-LINE COLLISIONS OH SNAP ~
###############################################################################
class solidLine(Line):
"""collidable lines"""
def __init__(self, r1, r2, lineType):
super(solidLine, self).__init__(r1, r2)
# self.dir = (self.r2-self.r1).normalize() #direction the line points in
#normal to line, 90 degrees ccw (to the left). DARN YOU FLIPPED COORDINATES
# self.norm = vector(self.dir.y, -self.dir.x)
self.type = lineType
def __repr__(self):
return "solidLine"+str((self.r1, self.r2, self.type))
#new resolveCollision, evaluates the closest line first, then reevaluates
#that means the original order of lines DOESN'T MATTER
def resolveCollision(pnt):
"""takes a solid point, finds and resolves collisions,
and returns the acceleration lines it collided with"""
hasCollided = True
a = canvas.data.acc
maxiter = canvas.data.maxiter
accLines = set()
while hasCollided == True and maxiter > 0:
hasCollided = False
#get the lines the point may collide with
lines = getCollisionLines(pnt)
#get the collision points of the lines the point actually collides with
collidingLines, collisionPoints, intersections = getCollidingLines(pnt, lines)
#no collisions? break
if collisionPoints == []:
break
elif len(collisionPoints) >1:
#more than one collision points: get the intersection point closest to the point
futurePoint = closestCollisionPoint(pnt, intersections, collisionPoints)
index=collisionPoints.index(futurePoint)
collidingLine = collidingLines[index]
else:
futurePoint = collisionPoints[0]
collidingLine = collidingLines[0]
#set future point to above point, evaluate acc line if necessary
pnt.r = futurePoint
if collidingLine.type == "acc":
accLines.add(collidingLine)
hasCollided = True
maxiter -= 1
if canvas.data.viewCollisions:
canvas.data.collisionPoints += [copy.copy(futurePoint)]
sensitiveButt(pnt)
return accLines
#repeat if there was a collision
def getCollidingLines(pnt, lines):
""""returns a list of the lines "pnt" actually collides with
and the respective intersection points"""
collisionPoints = []
collidingLines = []
intersections = []
for line in lines:
point = getCollision(pnt, line)
if point != None:
collidingLines += [line]
collisionPoints += [point[0]]
intersections += [point[1]]
return collidingLines, collisionPoints, intersections
def closestPoint(pnt, points):
closestPoint = points[0] #first point
minDist = distance(closestPoint,pnt)
for point in points[1:]:
dist = distance(point,pnt)
if dist < minDist:
minDist = dist
closestPoint = point
return closestPoint
def closestCollisionPoint(pnt, intersections, collisionPoints):
closestIntersection = closestPoint(pnt.r0, intersections)
i = intersections.index(closestIntersection)
return collisionPoints[i]
def getCollisionLines(pnt):
"""returns a set of lines that exist in the same cells as the point"""
vLine = Line(pnt.r0, pnt.r)
cells = getGridCells(vLine) #list of cell positions
lines = set()
solids = canvas.grid.solids
for gPos in cells:
cell = solids.get(gPos, set())
lines |= cell #add to set of lines to check collisions
return lines
def getCollision(pnt, line):
"""returns the position after collision(if it exists)"""
trajectory = Line(pnt.r, pnt.r0)
intersection = intersectPoint(trajectory, line)
thickness = canvas.data.lineThickness + canvas.data.epsilon
if intersection != None:
#if intersecting, project position onto line
futurePos = closestPointOnLine(pnt.r, line)
#line thickness
futurePos += (futurePos-pnt.r).normalize()*thickness
# print "intersection!"
return futurePos, intersection
elif distanceFromLine(pnt.r, line) < canvas.data.lineThickness:
#if inside line, do same as above except reverse direction of epsilon
futurePos = closestPointOnLine(pnt.r, line)
futurePos += (pnt.r-futurePos).normalize()*thickness
# print "inside line! Moving", pnt.r, "to", futurePos
return futurePos, pnt.r #pnt.r is in hte line: it's the intersection
else: return None
def sideOfLine(pnt, line):
"""the side of the line that the point collides with"""
#dot product of the normal and velocity
velocity = pnt.r - pnt.r0
side = velocity*line.norm
#the sign determines the side the point is colliding with the line
#-1 is right, +1 is left, to coorespond with the side of the normal
if side>0: return -1
elif side<0: return 1
else: return 0 # THIS IS GONNA BUG THE HELL OUT OF ME AHHHHHHHHH
###############################################################################
# ~ RIGID BODY DYNAMICS WHAT EVEN ~
###############################################################################
class Constraint():
def __init__(self, pnt1, pnt2, restLength):
#p1 and p2 are points
self.pnt1, self.pnt2 = pnt1, pnt2
self.restLength = restLength
def __repr__(self):
return str((self.pnt1, self.pnt2, self.restLength))
def resolveConstraint(cnstr):
"""resolves a given constraint"""
delta = cnstr.pnt1.r - cnstr.pnt2.r
deltaLength = delta.magnitude()
diff = (deltaLength-cnstr.restLength)/deltaLength
cnstr.pnt1.r -= delta*diff/2
cnstr.pnt2.r += delta*diff/2
def resolveScarf(cnstr):
"""one sided constraints"""
delta = cnstr.pnt1.r - cnstr.pnt2.r
deltaLength = delta.magnitude()
diff = (deltaLength-cnstr.restLength)/deltaLength
cnstr.pnt2.r += delta*diff
def resolveLegs(cnstr):
"""the constraint can only take on a minimum length"""
delta = cnstr.pnt1.r - cnstr.pnt2.r
deltaLength = delta.magnitude()
diff = (deltaLength-cnstr.restLength)/deltaLength
if diff < 0: #length is too small
cnstr.pnt1.r -= delta*diff/2
cnstr.pnt2.r += delta*diff/2
def checkEndurance(cnstr):
"""if the ratio of the difference of length is beyond a certain
limit, destroy line rider's attachment to the sled"""
endurance = canvas.data.endurance
delta = cnstr.pnt1.r - cnstr.pnt2.r
deltaLength = delta.magnitude()
diff = (deltaLength-cnstr.restLength)
ratio = abs(diff/cnstr.restLength)
if ratio > endurance:
#remove constraints
killBosh()
def killBosh():
if canvas.rider.onSled:
canvas.rider.constraints = canvas.rider.constraints[:-8]
canvas.rider.onSled = False
def sensitiveButt(pnt):
if pnt == canvas.rider.points[0]:
#LINE RIDER'S BUTT IS SENSITIVE. TOUCH IT AND HE FALLS OFF THE SLED.
killBosh()
###############################################################################
# ~ OBEY MY PHYSICS, DARN IT ~
###############################################################################
def freeFall(pnt, mass=1):
"""All points are independent, acting only on inertia, drag, and gravity
The velocity is implied with the previous position"""
velocity = pnt.r - pnt.r0
pnt.r = pnt.r + velocity*canvas.data.drag*mass + canvas.data.grav
def updatePositions():
if canvas.data.viewCollisions:
canvas.data.collisionPoints = []
for pnt in canvas.rider.points:
#first, update points based on inertia, gravity, and drag
pastPos = pnt.r
freeFall(pnt)
pnt.r0 = pastPos
#scarves are special :|
for pnt in canvas.rider.scarf:
pastPos = pnt.r
freeFall(pnt, 0.5)
pnt.r0 = pastPos
#add in the acceleration lines from previous step
accQueue = canvas.rider.accQueueNow
a = canvas.data.acc
for pnt, lines in accQueue.iteritems():
for line in lines:
acc = (line.r2 - line.r1).normalize()
acc *= a
pnt.r += acc
canvas.rider.accQueuePast = copy.copy(canvas.rider.accQueueNow)
canvas.rider.accQueueNow = dict() #empty queue after
for i in xrange(canvas.data.iterations):
#collisions get priority to prevent phasing through lines
for cnstr in canvas.rider.legsC:
resolveLegs(cnstr)
if canvas.rider.onSled:
for cnstr in canvas.rider.slshC:
checkEndurance(cnstr)
for cnstr in canvas.rider.constraints:
resolveConstraint(cnstr)
for pnt in canvas.rider.points:
accLines = resolveCollision(pnt)
if len(accLines)>0: #contains lines
canvas.rider.accQueueNow[pnt] = accLines
scarfStrength = 1
#again, scarves are special
for i in xrange(scarfStrength):
for cnstr in canvas.rider.scarfCnstr:
resolveScarf(cnstr)
# canvas.data.tracer += [canvas.rider.pos.r]
###############################################################################
# ~OPTIMIZATION PRIME~
###############################################################################
#perhaps the least intuitive part of this program.
#the grid is canvas.grid, a dictionary of tuples that coorespond to
#what line exists in the block the coordinates point to
#credits to my brother for explaining how this works
def getGridCells(line):
"""returns a list of the cells the line exists in"""
firstCell = gridPos(line.r1)
lastCell = gridPos(line.r2)
if firstCell[0] > lastCell[0]: #going in negative x direction MAKES BUGS
#JUST FLIP'EM
firstCell, lastCell = lastCell, firstCell
cells = [firstCell]
gridInts = getGridInts(line, firstCell, lastCell)
cell = firstCell
for x in sorted(gridInts): #ordered by which cell the line enters
dcor = gridInts[x]
cell = cell[0]+dcor[0], cell[1]+dcor[1]
cells += [cell]
# if lastCell not in cells:
# cells += [lastCell]
return cells
def gridFloor(x):
return int(x - x%canvas.data.gridSize)
def gridPos(pnt):
return gridFloor(pnt.x), gridFloor(pnt.y)
def getGridInts(line, firstCell, lastCell):
a, b, c = line.linearEquation()
dx = dy = canvas.data.gridSize #defined to be always positive
if lastCell[1] < firstCell[1]: #y is decreasing
dy *= -1
gridInts = {}
xInc, yInc = (dx, 0), (0, dy)
#normally, I would just use x = (c-b*y)/a
if b==0: #a might be 0 so SWAP VALUES
b, a = a, b
yInc, xInc = xInc, yInc
dy, dx = dx, dy
firstCell = firstCell[1], firstCell[0]
lastCell = lastCell[1], lastCell[0]
#vertical line intersections, exclude 0th line
for x in xrange(firstCell[0], lastCell[0], dx):
x += dx
gridInts[x] = xInc
#horizontal line intersections, exclude 0th line
for y in xrange(firstCell[1], lastCell[1], dy):
if dy>0:
y += dy
x = (c-b*y)/a
gridInts[x] = yInc
return gridInts
def resetGrid():
for line in canvas.track.lines:
addToGrid(line)
def addToGrid(line):
cells = getGridCells(line)
if line.type == "scene":
grid = canvas.grid.scenery
else:
grid = canvas.grid.solids
for cell in cells:
lines = grid.get(cell, set([]) )
lines |= set([line])
grid[cell] = lines
def removeFromGrid(line):
"""removes the line in the cells the line exists in"""
removedCells = getGridCells(line) #list of cell positions
if line.type == "scene":
grid = canvas.grid.scenery
else:
grid = canvas.grid.solids
for gPos in removedCells:
cell = grid[gPos]
#SET OF LINES, REMEMBER?
cell.remove(line)
if len(cell)==0: #get rid of the cell entirely if no lines
grid.pop(gPos)
def gridNeighbors(pos):
"""returns a list of the positions of the cells at and around the pos"""
cells = {}
x, y = gridPos(pos)
g = canvas.data.gridSize
return [(x,y),(x+g,y),(x+g,y+g),(x,y+g),(x-g,y+g),
(x-g,y),(x-g,y-g),(x,y-g),(x+g,y-g) ]
def gridInScreen():
"""returns a list of visible cells"""
#absolute positions
topLeft = gridPos(canvas.data.topLeft)
bottomRight = gridPos(canvas.data.bottomRight)
x1, x2 = topLeft[0], bottomRight[0]
y1, y2 = topLeft[1], bottomRight[1]
g = canvas.data.gridSize
cols = xrange(x1, x2+g, g)
rows = xrange(y1, y2+g, g)
cells = [ (x,y) for x in cols for y in rows]
return cells
###############################################################################
# ~ EDITING COMMANDS TO EDIT SH*T ~
###############################################################################
def undoCmd():
if len(canvas.data.undoStack)==0:
pass
else:
obj, command = canvas.data.undoStack.pop(-1) #last action
command(obj, undo=True)
def redoCmd():
if len(canvas.data.redoStack)==0:
pass
else:
obj, command = canvas.data.redoStack.pop(-1)
command(obj, redo=True)
def addLine(line, undo=False, redo=False):
"""adds a single line to the track"""
if len(canvas.track.lines) == 0:
canvas.track.startPoint = line.r1 - vector(0,30)
makeRider()
canvas.track.lines += [line]
addToGrid(line)
inverse = (line, removeLine)
addToHistory(inverse, undo, redo)
def removeLine(line, undo=False, redo=False):
"""removes a single line from the track"""
canvas.track.lines.remove(line)
removeFromGrid(line)
inverse = (line, addLine)
addToHistory(inverse, undo, redo)
def addToHistory(action, undo, redo):
undoStack = canvas.data.undoStack
redoStack = canvas.data.redoStack
if undo: #call from undo, put in redo stack
redoStack += [action]
else: #else, put in undo stack
undoStack += [action]
if len(undoStack)>500: #it's up to the user to back up :|
undoStack.pop(0)
if not redo and not undo: #eg call from line tool
redoStack = [] #clear redo stack
trackModified()
def inversePZ(pnt):
"""turns relative position to absolute"""
return (pnt-canvas.data.center)/canvas.track.zoom + canvas.data.cam
def inWindow(pos):
return isInRegion(pos,vector(0,0), canvas.data.windowSize)
def pencil(event):
pos = vector(event.x, event.y)
if canvas.data.pause == True and inWindow(pos):
pos = inversePZ(pos)
if event.type == "4": #pressed
canvas.data.tempPoint = pos
elif event.type == "6" and canvas.data.tempPoint != None: #moved
#to avoid making lines of 0 length
minLen = tools.snapRadius/canvas.track.zoom
if distance(canvas.data.tempPoint, pos) > minLen:
lineType = tools.lineType
line = solidLine(canvas.data.tempPoint, pos, lineType)
addLine(line)
canvas.data.tempPoint = pos
elif event.type == "5":
canvas.data.tempPoint = None
def makeLine(event):
pos = vector(event.x, event.y)
if canvas.data.pause == True and inWindow(pos):
pos = inversePZ(pos)
if tools.snap == True:
pos = closestPointToLinePoint(pos)
if event.type == "4": #pressed
canvas.data.tempPoint = pos
elif event.type == "5" and canvas.data.tempPoint != None: #released
canvas.data.tempLine = None
lineType = tools.lineType
minLen = tools.snapRadius/canvas.track.zoom
#to avoid making lines of 0 length
if distance(canvas.data.tempPoint, pos) > minLen:
line = solidLine(canvas.data.tempPoint, pos, lineType)
addLine(line)
canvas.data.tempPoint = None
elif event.type == "6" and canvas.data.tempPoint != None: #moved
canvas.data.tempLine = Line(canvas.data.tempPoint, pos)
def eraser(event):
pos = vector(event.x, event.y)
if canvas.data.pause == True and event.type != "5" and inWindow(pos):
pos = inversePZ(pos)
removedLines = removeLinesList(pos)
if len(removedLines) > 0:
for line in removedLines:
if line in canvas.track.lines:
removeLine(line)
def closestPointToLinePoint(pos):
"""finds the closest endpoint of a line segment to a given point"""
closestPoint = pos
minDist = tools.snapRadius/canvas.track.zoom
for line in linesInScreen():
dist = distance(line.r1, pos)
if dist < minDist:
minDist = dist
closestPoint = line.r1
dist = distance(line.r2, pos)
if dist < minDist:
minDist = dist
closestPoint = line.r2
return closestPoint
def removeLinesList(pos):
"""returns a set of lines to be removed, part of the eraser"""
z = canvas.track.zoom
removedLines = set()
radius = tools.eraserRadius
cells = gridNeighbors(pos) #list of 9 closest cell positions
for gPos in cells: #each cell has a position/key on the grid/dict
cell = canvas.grid.solids.get(gPos, set() ) #each cell is a set of lines
for line in cell:
if distanceFromLine(pos, line)*z <= radius:
removedLines |= set([line])
cell = canvas.grid.scenery.get(gPos, set() )
for line in cell:
if distanceFromLine(pos, line)*z <= radius:
removedLines |= set([line])
return removedLines
def pan(event):
if canvas.data.pause or not canvas.data.follow:
z = canvas.track.zoom
pos = (event.x, event.y)
if event.type == "4": #pressed
canvas.data.tempCam = pos
elif event.type == "5": #released
pass
elif event.type == "6": #moved
pan = vector(canvas.data.tempCam) - vector(pos)
canvas.track.panPos += pan/z
canvas.data.tempCam = pos
def zoom(event):
if event.type=="4": #pressed
tools.tempZoom = event.y
# cor = inversePZ(vector(event.x, event.y))
# print cor.x, cor.y
elif event.type=="6": #moved
delta = event.y - tools.tempZoom
zoom = 0.99**(delta)
zoom *= canvas.track.zoom
if ( (0.1 < zoom and delta > 0) or
(10 > zoom and delta < 0) ):
canvas.track.zoom = zoom
tools.tempZoom = event.y
def zoomM(event):
if (event.delta%120)==0:
event.delta /= 120
zoom = 1.1**(event.delta)
zoom *= canvas.track.zoom
if ( (0.1 < zoom and event.delta < 0) or
(10 > zoom and event.delta > 0) ):
canvas.track.zoom = zoom
def stop():
canvas.data.pause = True
canvas.data.slowmo = False
resetRider()
def playPause(): #technically toggles between play and pause
canvas.data.pause = not canvas.data.pause
if canvas.data.pause and canvas.data.follow: #pausing
canvas.track.panPos = canvas.rider.pos.r-canvas.data.center
elif not canvas.data.pause:
canvas.data.tempLine = None
def flag():
canvas.data.flag = True
canvas.data.flagBosh = copy.deepcopy(canvas.rider)
#very tricky part here
# canvas.data.flagBosh.accQueueNow = copy.copy(
# canvas.data.flagBosh.accQueuePast)
def resetFlag():
canvas.data.flag = False
def playFromBeginning():
canvas.data.pause = False
resetRider(True)
def resetRider(fromBeginning=False):
canvas.data.tracer = []
if fromBeginning or not canvas.data.flag:
makeRider()
else:
canvas.rider = copy.deepcopy(canvas.data.flagBosh)
###############################################################################
# ~ I'M TRYING MY BEST TO PREVENT LINE RIDER GRIEF ~
###############################################################################
def trackModified(isMdfy=True):
canvas.data.modified = isMdfy
showMdfy()
def showMdfy():
if canvas.data.modified:
canvas.data.message="*"
else: canvas.data.message=""
def newTrack():
if canvas.data.modified:
if tkMessageBox.askokcancel(
"Unsaved changes!", "Unsaved changes!\nContinue?"):
init()
resetRider()
else:
init()
resetRider()
def loadTrack():
window = Toplevel()
window.title("Load Track")
loadWindow = Listbox(window)
loadWindow.pack()
def exit():
window.destroy()
if os.path.isdir("savedLines"):
def doLoad():
loadWindow.delete(0, END)
for track in os.listdir("savedLines"):
loadWindow.insert(0, track)
def load():
name = loadWindow.get(ACTIVE)
path = "savedLines/"+ name
backupLines = canvas.track.lines
backupStart = canvas.track.startPoint
init()
resetRider()
with open(path, "rb") as track:
try:
canvas.track = pickle.load(track) #ACTUAL LOADING
except Exception as error: #in case it's not a valid file
canvas.track.lines = backupLines
canvas.track.startPoint = backupStart
loadWindow.delete(0, END)
loadWindow.insert(0, "Y U NO LOAD")
loadWindow.insert(END, "VALID TRACK")
print error
window.after(1000, doLoad)
makeRider()
resetGrid()
cancelButton.config(text="Close")
loadButton.config(text="Load", command=load)
cancelButton = Button(window, text="Cancel", command=exit)
loadButton = Button(window, text="Ok", command=doLoad)
loadButton.pack()
cancelButton.pack()
if canvas.data.modified:
loadWindow.insert(0, "Unsaved changes!")
loadWindow.insert(END, "Continue?")
else:
doLoad()
else:
loadWindow.insert(0, "savedLines folder")
loadWindow.insert(END, "does not exist!")
cancelButton = Button(window, text="Okay ):", command=exit)
loadWindow.pack()
def saveTrack():
window = Toplevel()
window.title("Save Track")
saveWindow = Entry(window)
saveWindow.insert(0, canvas.track.name)
def exit():
window.destroy()
def saveAttempt():
name = saveWindow.get()
canvas.track.name = name
path = "savedLines/"+ name
def save():
saveWindow.delete(0, END)
try:
with open(path, "wb") as track:
pickle.dump(canvas.track, track) #ACTUAL SAVING
saveWindow.insert(0, "Saved!")
trackModified(False)
window.after(1000, exit)
except Exception as error:
saveWindow.insert(0, "Failed to save! D:")
print error
window.after(1000, lambda: undo(False))
def undo(YN = True):
saveWindow.delete(0, END)
saveWindow.insert(0, name)
loadButton.config(text="Save", command=saveAttempt)
if YN:
cancelButton.destroy()
if not os.path.isdir("savedLines"):
os.mkdir("savedLines")
if os.path.isfile(path):
saveWindow.delete(0, END)
saveWindow.insert(0, "Overwrite track?")
loadButton.config(text="Yes", command=save)
cancelButton = Button(window, text="No", command=undo)
cancelButton.pack()
else:
save()
loadButton = Button(window, text="Save", command=saveAttempt)
saveWindow.pack()
loadButton.pack()
def fastSave():
name = canvas.track.name
if (name == "ONEXITSAVE_" or name == "Untitled"
or not os.path.isdir("savedLines")):
saveTrack() #save as
else:
path = "savedLines/"+name
try:
with open(path, "wb") as track:
pickle.dump(canvas.track, track)
trackModified()
canvas.data.message = "Saved!"
except Exception as error:
canvas.data.message = "Failed to save! D:"
print error
canvas.after(1000, showMdfy)
def onExitSave(root):
if not os.path.isdir("savedLines"):
os.mkdir("savedLines")
path = "savedLines/ONEXITSAVE_"
canvas.track.name = "ONEXITSAVE_"
try:
with open(path, "wb") as track:
pickle.dump(canvas.track, track)
except Exception as error:
print error
if not canvas.data.modified or tkMessageBox.askokcancel(
"Unsaved changes!","Failed to save! D:\nExit anyways?"):
root.destroy()
root.destroy()
def reloadOnExitSave():
path = "savedLines/ONEXITSAVE_"
if os.path.isfile(path):
with open(path, "r") as track:
canvas.track = pickle.load(track)
resetGrid()
###############################################################################
# ~ HOLY RUN ON, BATMAN ~
###############################################################################
def LmousePressed(event):
tool = tools.leftTool
tool(event)
def RmousePressed(event):
tool = tools.rightTool
tool(event)
def MmousePressed(event):
zoom(event)
redrawAll()
def setupWindow(root):
root.title("Line Rider Python")
def displayT(boolean, m1, m2):
if boolean: message = m1
else: message = m2
canvas.data.message = " "+message
canvas.after(1000, showMdfy)
menubar = Menu(root)
root.config(menu=menubar)
#FILE
fileMenu = Menu(menubar, tearoff=False)
fileMenu.add_command(label="new (ctrl+n)", command = newTrack )
fileMenu.add_command(label="load (ctrl+o)", command = loadTrack)
fileMenu.add_command(label="save (ctrl+s)", command = saveTrack)
menubar.add_cascade(label="File", menu=fileMenu)
#EDIT
def undo():
if canvas.data.pause: undoCmd()
def redo():
if canvas.data.pause: redoCmd()
def snap():
tools.snap = not tools.snap
displayT(tools.snap,"Line snapping on","Line snapping off")
editMenu = Menu(menubar, tearoff=False)
editMenu.add_command(label="undo (ctrl+z)", command = undo)
editMenu.add_command(label="redo (ctrl+shift+z)", command = redo)
editMenu.add_command(label="toggle line snapping (s)", command = snap)
menubar.add_cascade(label="Edit", menu=editMenu)
#TOOLS
def setLTool(tool):
tools.leftTool = tool
def setRTool(tool):
tools.rightTool = tool
def setLine(lineType):
tools.lineType = lineType
toolMenu = Menu(menubar)
toolMenu.add_command(label="pencil (q)", command=lambda:setLTool(pencil))
toolMenu.add_command(label="line (w)", command= lambda: setLTool(makeLine))
types = Menu(toolMenu)
types.add_command(label="solid (1)", command= lambda:setLine("solid"))
types.add_command(label="acceleration (2)", command=lambda:setLine("acc"))
types.add_command(label="scenery (3)", command=lambda:setLine("scene"))
toolMenu.add_cascade(label="line type", menu=types)
toolMenu.add_command(label="eraser (e)", command= lambda: setLTool(eraser))
# toolMenu.add_separator()
# toolMenu.add_command(label="pan", command=setRTool(pan))
menubar.add_cascade(label="Tools", menu=toolMenu)
#view
def viewVector():
canvas.data.viewVector = not canvas.data.viewVector
displayT(canvas.data.viewVector,"Showing velocity","Hiding velocity")
def viewPoints():
canvas.data.viewPoints = not canvas.data.viewPoints
displayT(canvas.data.viewPoints,"Showing snapping points",
"Hiding snapping points")
def viewLines():
canvas.data.viewLines = not canvas.data.viewLines
displayT(canvas.data.viewLines, "Showing lines", "Hiding lines")
def viewGrid():
canvas.data.viewGrid = not canvas.data.viewGrid
displayT(canvas.data.viewGrid, "Showing grid", "hiding grid")
def viewStatus():
canvas.data.viewStatus = not canvas.data.viewStatus
displayT(canvas.data.viewStatus, "Showing status messages",
"Status messages are hidden, how can you see this?")
def viewCollisions():
canvas.data.viewCollisions = not canvas.data.viewCollisions
displayT(canvas.data.viewCollisions, "Showing collision points",
"Hiding collision points")
def goToStart():
if canvas.data.pause:
canvas.track.panPos = canvas.track.startPoint-canvas.data.center
def lastLine():
if canvas.data.pause and len(canvas.track.lines)>0:
lastLine = canvas.track.lines[-1].r2
canvas.track.panPos = lastLine - canvas.data.center
def followRider():
canvas.data.follow = not canvas.data.follow
displayT(canvas.data.follow, "Following rider", "Not following rider")
def viewThinLines():
canvas.data.viewThinLines = not canvas.data.viewThinLines
displayT(canvas.data.viewThinLines, "Viewing normal lines",
"Viewing normal lines")
viewMenu = Menu(menubar)
viewMenu.add_command(label="velocity vectors (v)", command=viewVector)