-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprecalc.py
2144 lines (1530 loc) · 61.8 KB
/
precalc.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
# ;;; This code is (c) 2020 Stéphane Champailler
# ;;; It is published under the terms of the
# ;;; GUN GPL License Version 3.
# The "before it's too late" demo
# By Wiz/Imphobia!
# In memory of my scene years and its seasons.
# 617D draw hline full
import glob
import pickle
import array
import sys
import os
from collections import OrderedDict
import io
import math
import random
from PIL import Image
import pygame
import numpy as np
import networkx as nx
import portion
from utils import *
#from parse_svg import parse_animals
#from gz3 import longest_paths_search
HGR_OFFSET = 2
# t = (portion.open(1,2) | portion.open(3,4) | portion.open(5,6)) | portion.open(1.5,3.5)
# print( t)
# for i in t:
# print(i)
# print( len(t))
# print("empty")
# for t in portion.empty():
# print("***" + str(t))
# a = portion.closed( 0,1)
# print( ~a)
# # --> (-inf,0) | (1,+inf) : correct !
# special = ~a & portion.closed(0,1)
# print( special)
# # --> () : correct !
# print( special.empty)
# print( portion.to_data( special))
# # --> [(False, inf, -inf, False)] : ???
# #exit()
# tri = Triangle( Vertex(-1,-1,0), Vertex(0,+1,0), Vertex(+1,-1,0) )
# print( tri.intersect_segment( Edge( Vertex(0,0,-1), Vertex(0,0,+1 ) )))
# tri = Triangle( Vertex(+1,-1,0), Vertex(0,+1,0), Vertex(-1,-1,0) )
# print( tri.intersect_segment( Edge( Vertex(0,0,-1), Vertex(0,0,+1 ) )))
# t = Triangle( Vertex(+1,-1,0), Vertex(0,+1,0), Vertex(-1,-1,0) )
# t2 = Triangle( Vertex(+1,-1,-1), Vertex(0,+1,0), Vertex(-1,-1,+1) )
# intersect_triangle( t, t2)
# print("---")
# t = Triangle( Vertex(0,0,-10), Vertex(-1,0,+10), Vertex(+1,0,+10) )
# t2 = Triangle( Vertex(-10,-1,0), Vertex(0,+1,0), Vertex(+1,-1,0) )
# intersect_triangle( t, t2)
PICTURE_LOAD = 0xFD
END_OF_TRACK = 0xFE
END_OF_MOVIE = 0xFF
MAX_BLOCKS = 1000
#SHAPE = "Iceberg"
#SHAPE = "XWing"
#SHAPE = "Ogon"
#SHAPE = "Tetrahedron"
SHAPE = "Cube"
#SHAPE = "Cube2"
#SHAPE="Grid"
DEBUG = False
TILE_SIZE = APPLE_HGR_PIXELS_PER_BYTE
# ; total 16 bytes for one line of a tile
# ; 8*16 = 128 bytes for a tile
# ; for 8 pixels tile size, I have 8+8+8+8=32 tiles, each of which is rolled on 8 positions => 8*32 = 256 tiles
# ; A tile needs max 2*8 bytes => tile date = 16*256 = 4096 bytes
# ; given the number of tiles, precalc the code is not possible.
# -----------------------------------------------------------------
# Other way
# Tak a mostly vertical line
# split it into parts of 8 pixels tall
# dtermine the x1 where the line enter a tile and the x2 where it leaves it
# locate a tile with an index (x1, x2)
def enumerate_x( x1 : int, y1 : int, x2 : int, y2 : int):
assert is_int(x1) and is_int(x2) and is_int(y1) and is_int(y2)
dx,dy = x2 - x1, y2 - y1
slope = dx/dy
xs = []
x = x1
for i in range( dy+1):
rx = int(round(x))
assert x1 <= rx <= x2 or x1 >= rx >= x2
xs.append( rx)
x += slope
return xs
def draw_vline( npa, x1, y1, x2, y2, color):
# Draw a mostly vertical line
assert 0 <= x1 < npa.shape[1], "bad x1: 0 <= {} < {}".format(x1, npa.shape[1])
assert 0 <= x2 < npa.shape[1]
assert 0 <= y1 < npa.shape[0]
assert 0 <= y2 < npa.shape[0]
dx,dy = x2 - x1, y2 - y1
slope = dx/dy
assert abs(slope) <= 1, "The line is not mostly vertical"
# a = Vertex( x1, y1)
# b = Vertex( x2, y2)
# points = full_enum(a,b)
# for p in points:
# npa[ int(p.y) ][ int(p.x) ] = 1
# return
xs = enumerate_x(x1, y1, x2, y2)
y = y1
for i in range( dy+1):
npa[y][xs[i]] = 1
y += 1
def draw_hline( npa, x1, y1, x2, y2, color):
a = Vertex( x1, y1)
b = Vertex( x2, y2)
points = full_enum(a,b)
for p in points:
npa[ int(p.y) ][ int(p.x) ] = 1
speed = [2, 2]
black = 0, 0, 0
# https://www.youtube.com/watch?v=juXlFqhKrEM
# 255 images en 13 secondes => 19 fps
# my engine : 29*2 in 2.39s => 24 fps (zoom factor = 250)
# zoom factor = 500 : 29*2 in 4.22s => 13fps
# 45 / 4 = 11 fps
# 70/8.3 = 8.4
Vtx = Vertex
faces = []
SPEED = math.pi / 50
axis2 = [-0.5,0.5,1]
if SHAPE == "Iceberg":
vertices, faces = read_wavefront("data/iceberg.obj")
T = Vertex(0,+2,0)
for v in vertices:
v.scale( 0.5)
v.translate( T)
NB_FRAMES = 2
MAX_BLOCKS = 3
ATTENUATION = math.pi
ZOOM=400
axis = [0,1,0]
axis2 = [0,1,0]
if SHAPE == "XWing":
# See Inksacpe schematics
COCKPIT_WIDTH = 0.8
a = Vtx(-COCKPIT_WIDTH,.5,-.3)
b = Vtx(-COCKPIT_WIDTH,0.3,-.8)
g = Vtx(-COCKPIT_WIDTH,-.6,-.8)
e = Vtx(-COCKPIT_WIDTH,-.6,+2)
f = Vtx(-COCKPIT_WIDTH,.5,+2)
c = Vtx(-0.2,-0.1,-6.5)
d = Vtx(-0.2,-0.5,-6.5)
a2 = Vtx(COCKPIT_WIDTH,.5,-.3)
b2 = Vtx(COCKPIT_WIDTH,.3,-.8)
g2 = Vtx(COCKPIT_WIDTH,-.6,-.8)
e2 = Vtx(COCKPIT_WIDTH,-.6,+2)
f2 = Vtx(COCKPIT_WIDTH,.5,+2)
c2 = c + Vtx(0.4,0,0)
d2 = d + Vtx(0.4,0,0)
w1 = Vtx( COCKPIT_WIDTH+0.05, 0.2, +0.5)
w2 = Vtx( COCKPIT_WIDTH+0.05, 0.2, +2)
w3 = Vtx( COCKPIT_WIDTH+0.05+4, 0.8, +1.5)
w4 = Vtx( COCKPIT_WIDTH+0.05+4, 0.8, +0.5)
w5 = Vtx( COCKPIT_WIDTH+0.05+4, 0.8, -2)
wa1 = Vtx( COCKPIT_WIDTH+0.05, -0.2, +0.5)
wa2 = Vtx( COCKPIT_WIDTH+0.05, -0.2, +2)
wa3 = Vtx( COCKPIT_WIDTH+0.05+4, -0.8, +1.5)
wa4 = Vtx( COCKPIT_WIDTH+0.05+4, -0.8, +0.5)
wa5 = Vtx( COCKPIT_WIDTH+0.05+4, -0.8, -2)
rw1 = Vtx( -COCKPIT_WIDTH-0.05, 0.2, +0.5)
rw2 = Vtx( -COCKPIT_WIDTH-0.05, 0.2, +2)
rw3 = Vtx( -COCKPIT_WIDTH-0.05-4, 0.8, +1.5)
rw4 = Vtx( -COCKPIT_WIDTH-0.05-4, 0.8, +0.5)
rw5 = Vtx( -COCKPIT_WIDTH-0.05-4, 0.8, -2)
rwa1 = Vtx( -COCKPIT_WIDTH-0.05, -0.2, +0.5)
rwa2 = Vtx( -COCKPIT_WIDTH-0.05, -0.2, +2)
rwa3 = Vtx( -COCKPIT_WIDTH-0.05-4, -0.8, +1.5)
rwa4 = Vtx( -COCKPIT_WIDTH-0.05-4, -0.8, +0.5)
rwa5 = Vtx( -COCKPIT_WIDTH-0.05-4, -0.8, -2)
faces += [ Face( a,a,a, hidden=False).set_vertices([a,b,g,e,f]),
Face( a,a,a, hidden=False).set_vertices([b,c,d,g]),
Face( a,a,a, hidden=False).set_vertices([a2,b2,g2,e2,f2]),
Face( a,a,a, hidden=False).set_vertices([b2,c2,d2,g2]),
Face( a,a,a, hidden=False).set_vertices([d,d2,g2,e2,e,g]),
Face( a,a,a, hidden=False).set_vertices([c,c2,b2,b]),
Face( a,a,a, hidden=False).set_vertices([a,a2,f2,f]),
Face( a,a,a, hidden=False).set_vertices([a,a2,b2,b]),
Face( a,a,a, hidden=False).set_vertices([c,c2,d2,d]),
Face( a,a,a, hidden=False).set_vertices([e,e2,f2,f]),
Face( w3,w5, hidden=False),
Face( wa3,wa5, hidden=False),
Face( rw3,rw5, hidden=False),
Face( rwa3,rwa5, hidden=False),
Face( a,a,a, hidden=False).set_vertices([w1,w2,w3,w4]),
Face( a,a,a, hidden=False).set_vertices([wa1,wa2,wa3,wa4]),
Face( a,a,a, hidden=False).set_vertices([rw1,rw2,rw3,rw4]),
Face( a,a,a, hidden=False).set_vertices([rwa1,rwa2,rwa3,rwa4])
]
# engines
faces.extend( block( Vtx(0.3,0.3,2), Vtx(COCKPIT_WIDTH+0.2,0.51,0.9)))
faces.extend( block( Vtx(0.3,0.3,2), Vtx(-COCKPIT_WIDTH-0.2,0.51,0.9)))
faces.extend( block( Vtx(0.3,0.3,2), Vtx(COCKPIT_WIDTH+0.2,-0.51,0.9)))
faces.extend( block( Vtx(0.3,0.3,2), Vtx(-COCKPIT_WIDTH-0.2,-0.51,0.9)))
NB_FRAMES = 200
MAX_BLOCKS = 3
ATTENUATION = math.pi
ZOOM=200
axis = [3,2,0.5]
if SHAPE == "Tetrahedron":
HIDDEN_FACES = True
NB_FRAMES = 2400
ATTENUATION = math.pi
ZOOM=600
axis = [3,2,0.5]
ta = Vtx(-1,-1,0)
tb = Vtx(+1,-1,0)
tc = Vtx(0,+1,-1)
td = Vtx(0,+1,+1)
faces += [ Face(ta,tb,tc, hidden=HIDDEN_FACES),
Face(ta,td,tb, hidden=HIDDEN_FACES),
Face( tc,tb,td, hidden=HIDDEN_FACES),
Face( tc,td,ta, hidden=HIDDEN_FACES) ]
# Cube ---------------------------------------------------------------
if SHAPE == "Cube":
ATTENUATION = 2*math.pi
ZOOM=500
HIDDEN_FACES = True
NB_FRAMES = 500 # 700 # 220*6
MAX_BLOCKS = 4
#NB_FRAMES = 220
axis = [3,2,0.5]
ap = Vtx(-1,-1,-1)
bp = Vtx(+1,-1,-1)
cp = Vtx(+1,+1,-1)
dp = Vtx(-1,+1,-1)
app = Vtx(-1,-1,1)
bpp = Vtx(+1,-1,1)
cpp = Vtx(+1,+1,1)
dpp = Vtx(-1,+1,1)
faces += [ Face( ap,bp,cp,dp,hidden=HIDDEN_FACES), # front
Face( dpp,cpp,bpp,app,hidden=HIDDEN_FACES),
Face( cp,cpp,dpp,dp,hidden=HIDDEN_FACES),
Face( bp,bpp,cpp,cp,hidden=HIDDEN_FACES),
Face( ap,app,bpp,bp,hidden=HIDDEN_FACES),
Face( dp,dpp,app,ap,hidden=HIDDEN_FACES),
]
if SHAPE == "Cube2":
ATTENUATION = math.pi * 1.7
ZOOM=400
HIDDEN_FACES = True
NB_FRAMES = 300 # 900
SPEED = math.pi / 120
axis = [3,2,0.5]
axis2 = [-0.5,0.5,1]
faces += cube( 1, Vtx(-0.99,0,+1))
faces += cube( 0.5, Vtx(-0.99,0,-0.8))
faces += cube( 0.3, Vtx(+0.4,-0.3,-1))
faces += cube( 0.5, Vtx(+0.8,-0.3,+1))
#faces += cube( 0.5, Vtx(+0.8,+1,+1))
# Ogon ---------------------------------------------------------------
if SHAPE == "Ogon":
ATTENUATION = 1*math.pi
ZOOM = 600 # 170
HIDDEN_FACES = True
NB_FRAMES = 10 # 300*3
axis = [3,2,0.5]
axis2 = [-0.5,0.5,1]
a = Vtx(-0.75,-0.75,-1)
b = Vtx(+0.75,-0.75,-1)
c = Vtx(+0.75,+0.75,-1)
d = Vtx(-0.75,+0.75,-1)
ap = Vtx(-1,-1,0)
bp = Vtx(+1,-1,0)
cp = Vtx(+1,+1,0)
dp = Vtx(-1,+1,0)
app = Vtx(-1,-1,1)
bpp = Vtx(+1,-1,1)
cpp = Vtx(+1,+1,1)
dpp = Vtx(-1,+1,1)
appp = Vtx(-0.5,-0.5,2)
bppp = Vtx(+0.5,-0.5,2)
cppp = Vtx(+0.5,+0.5,2)
dppp = Vtx(-0.5,+0.5,2)
faces = [ Face(a,b,c,d, hidden=HIDDEN_FACES), # front
Face( d,c,cp,dp, hidden=HIDDEN_FACES), # top
Face( b,a,ap,bp, hidden=HIDDEN_FACES), # bottom
Face( a,d,dp,ap, hidden=HIDDEN_FACES), # left
Face( b,bp,cp,c, hidden=HIDDEN_FACES), # right
Face(ap,app,bpp,bp, hidden=HIDDEN_FACES),
Face(bp,bpp,cpp,cp, hidden=HIDDEN_FACES),
Face(dp,cp,cpp,dpp, hidden=HIDDEN_FACES),
Face(ap,dp,dpp,app, hidden=HIDDEN_FACES),
Face(app,appp,bppp,bpp, hidden=HIDDEN_FACES),
Face(bpp,bppp,cppp,cpp, hidden=HIDDEN_FACES),
Face(dpp,cpp,cppp,dppp, hidden=HIDDEN_FACES),
Face(app,dpp,dppp,appp, hidden=HIDDEN_FACES),
Face(dppp,cppp,bppp,appp, hidden=HIDDEN_FACES), #rear
]
# Grid ------------------------------------------------------
# NB_FRAMES = 60
# ATTENUATION = 0.5
# ZOOM = 300
# faces = []
# ty=0.5
# N=4
# for i in range(0,+N+1):
# if i < 4:
# a = Vtx(-5,i*0.3 + ty,0)
# b = Vtx(+5,i*0.3 + ty,0)
# faces.append( Face( a,b, hidden=False))
# if i != 100:
# a = Vtx((i-N//2 - 1)*0.5,+ty,0)
# b = Vtx((i-N//2 - 1)*3,+10.5+ty,0)
# faces.append( Face( a,b, hidden=False))
# axis = [0,0,1]
# -----------------------------------------------------------
Z_CAMERA = 10 # 10
def fusion_edges( faces):
edge_vertices = dict()
for face in faces:
for i in range( len(face.xformed_vertices)):
a = face.xformed_vertices[i]
b = face.xformed_vertices[i-1] # Will wrap !
if a.vid < b.vid:
edge_id = (a.vid, b.vid)
else:
edge_id = (b.vid, a.vid)
if edge_id not in edge_vertices:
edge_vertices[edge_id] = Edge(a,b)
return edge_vertices
def export_faces( faces, rot):
xv = dict()
for face in faces:
vp = []
for v in face.vertices:
# Avoid recomputing vertices
if v.vid not in xv:
xv[v.vid] = Vtx( *rotate_quat( rot, [v.x,v.y,v.z])).grab_id(v)
vp.append( xv[v.vid])
face.xformed_vertices = vp
# Split a face in triangles if it has more than 3 vertices
atriangles = []
for face in faces:
if face.edges >= 3:
fv = face.xformed_vertices
for i in range(len(fv) - 3 + 1):
atriangles.append( Triangle( fv[0], fv[i+1],fv[i+2]))
edges = fusion_edges( faces).values()
draw_edge = []
eye = Vertex( 0,0,-Z_CAMERA)
for edge in edges:
view_triangle = Triangle( eye, edge.v1, edge.v2)
# Compare the edge to all the triangles
all_ts = []
for triangle in atriangles:
# t represents the interval(s) where view_triangle
# is hidden by triangle.
t = intersect_triangle( view_triangle, triangle)
if t:
all_ts.append(t)
if all_ts:
# At least some portions of the possible t are
# hidden => some may be visible.
a = all_ts[0]
for i in range(1, len(all_ts)):
a = a | all_ts[i]
# Because we use closed intervals, it may be possible
# we end up with one-point wide intervals here !
to_draw = ~a & portion.closed(0,1)
if not to_draw.empty:
for i in to_draw:
v0 = edge.orig + edge.ray * i.lower
v1 = edge.orig + edge.ray * i.upper
if (v0 - v1).norm() > 0.001:
draw_edge.append( Edge(v0,v1))
else:
# Nothing is invisble => everything is visible
if edge.length() > 0.001:
draw_edge.append( edge)
with open("/tmp/graph.txt","w") as fout:
min_id = min([min(e.v1.vid, e.v2.vid) for e in draw_edge])
for e in draw_edge:
fout.write(f"{e.v1.vid - min_id} {e.v2.vid - min_id}\n")
print(f"{e.v1.vid} - {e.v1}\t{e.v2}\t{e.length()}")
return draw_edge
# Animate
def persp( v, zoom = 350):
# Z points away from us
d = (v.z + Z_CAMERA) / zoom
return Vtx( v.x / d + APPLE_XRES / 2,
v.y / d + APPLE_YRES / 2,
v.z*100) # see Vertex construtor and round operation
def object_to_graph( frame_lines):
points = dict()
edges = set()
print(frame_lines)
for ax, ay, bx, by in frame_lines:
if (ax,ay) not in points:
points[(ax,ay)] = len(points)
a = points[(ax,ay)]
if (bx,by) not in points:
points[(bx,by)] = len(points)
b = points[(bx,by)]
if a > b:
a,b=b,a
edges.add( (a,b) )
return edges
def load_frame_segments():
frames_segments = []
with open("/tmp/edges.txt","r") as fin:
for line in fin.readlines():
frame_segments = []
for a in line.strip().split(",")[:-1]:
segments = [int(x) for x in a.strip().split(' ')]
frame_segments.append(tuple(segments))
frames_segments.append(frame_segments)
print(frames_segments)
return frames_segments
def animate_3D( screen):
recorder_frames = []
theta = 0
beta = 0
zscreen = ZBuffer( APPLE_XRES, APPLE_YRES)
RUNNING, PAUSE = 0, 1
state = RUNNING
total_chains = 0
for i,face in enumerate(faces):
face.number = (i+1)*8 # will be a color
for frame_ndx in range(NB_FRAMES):
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_p:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_r:
break
#screen.fill(black)
beta += SPEED
theta = math.sin(frame_ndx * 2*math.pi / NB_FRAMES) *ATTENUATION
rot = mult_quat( angle_axis_quat(theta, axis), angle_axis_quat(beta, axis2))
# drawn_edges = set()
frame_lines = []
# xv = dict()
# t_y = -0
# for face in faces:
# vp = []
# for v in face.vertices:
# # Avoid recomputing vertices
# if v.vid not in xv:
# xv[v.vid] = persp( Vtx( *rotate_quat( rot, [v.x,v.y,v.z])), ZOOM).grab_id(v)
# vp.append( xv[v.vid])
# # print(len(xv))
# # print([v.vid for v in vp])
# # vp = [ persp( Vtx( *rotate_quat( rot, [v.x,v.y,v.z])), ZOOM).grab_id(v)
# # for v in face.vertices ]
# face.xformed_vertices = vp
# if face.hidden:
# v1 = vp[0] - vp[1]
# v2 = vp[0] - vp[2]
# if v1.cross(v2).z < 0:
# #pass
# continue
# #zscreen.draw_face( face)
# for i in range( face.edges):
# a,b = vp[i], vp[(i+1)%len(face.vertices)]
# # Get id's of edge end points
# k = min( a.vid, b.vid), max( a.vid, b.vid)
# if k not in drawn_edges:
# drawn_edges.add( k)
# # pygame.draw.line( screen, (255,255,255),
# # (a.x,a.y + t_y),
# # (b.x,b.y + t_y), 1)
# # frame_lines.append( (a.x,a.y + t_y,
# # b.x,b.y + t_y) )
# edge_cache = dict()
# for face in faces:
# for i in range( len(face.xformed_vertices)):
# a = face.xformed_vertices[i]
# b = face.xformed_vertices[i-1]
# if a.vid < b.vid:
# edge_id = (a.vid, b.vid)
# else:
# edge_id = (b.vid, a.vid)
# if edge_id not in edge_cache:
# edge_cache[edge_id] = set([face])
# else:
# edge_cache[edge_id].add( face)
# segments = []
# for key, sup_faces in edge_cache.items():
# assert len(sup_faces) == 2
# #print([f.number for f in sup_faces])
# segments.extend( zscreen.draw_line( xv[key[0]], xv[key[1]], 255, [f.number for f in sup_faces]))
screen.fill( (0,0,0) )
# zscreen.show_pygame( screen)
# for a,b in segments:
# pygame.draw.line( screen, (0,0,255),
# (a.x,a.y),
# (b.x,b.y), 1)
# frame_lines.append( (a.x,a.y,
# b.x,b.y) )
clipped_edges = export_faces( faces, rot)
def persp2( a):
assert not math.isnan(a.x), f"{a}"
assert not math.isnan(a.y), f"{a}"
z = ZOOM / ( a.z + Z_CAMERA)
return Vertex( round(a.x*z) + APPLE_XRES / 2,
round(a.y*z) + APPLE_YRES / 2, 0)
drawn_edges = 0
for e in clipped_edges:
#print( f"{e}")
a = persp2( e.v1)
b = persp2( e.v2)
if (a-b).norm() >= 2:
drawn_edges += 1
pygame.draw.line( screen, (0,255,0),
(a.x,a.y),
(b.x,b.y), 1)
frame_lines.append( (a.x,a.y,b.x,b.y) )
print( f"Frame {frame_ndx}/{NB_FRAMES} {len(faces)} faces, {drawn_edges} drawn edges")
# for x,y in points.keys():
# pygame.draw.line( screen, (255,255,255),
# (x,y),
# (x+1,y+1), 1)
# g = nx.Graph()
# g.add_edges_from( edges)
# print("Graph : {} nodes, {} edges".format( len(g.nodes), len(g.edges)))
# print( "Frame {} : Edge pool size : {} edges".format(len(recorder_frames), len(edge_pool._edges)))
# c = edge_pool.make_chains()
# total_chains += len(c)
# print( " {} chains, total {}".format( len( c), total_chains))
recorder_frames.append( frame_lines)
#zscreen.clear()
pygame.display.flip()
return recorder_frames
# edges = parse_animals( screen)
# recorder_frames = []
# for i in range( 200):
# frame = []
# for e in edges:
# tx = -i
# frame.append( [e.v1.x + tx, e.v1.y, e.v2.x + tx, e.v2.y] )
# recorder_frames.append( frame)
# pygame.quit()
# def draw_triangle_edges( scren, v1, v2, v3, color):
# vert = [ v1, v2, v3]
# left = full_enum( vert[0], vert[1])
# right = full_enum( vert[0], vert[2])
# bottom = full_enum( vert[1], vert[2])
# for i in range( len(left)):
# screen.draw_pixel( left[i], color, offset=1)
# for i in range( len(right)):
# screen.draw_pixel( right[i], color, offset=1)
# for i in range( len( bottom)):
# screen.draw_pixel( bottom[i], color, offset=1)
# def cross(a, b):
# c = [a[1]*b[2] - a[2]*b[1],
# a[2]*b[0] - a[0]*b[2],
# a[0]*b[1] - a[1]*b[0]]
# return c
def seven_bits_split(t):
# t is a double tile
assert (TILE_SIZE + 1) % 8 == 0, "This works only with 7 bits wide tiles"
assert t.shape[0] == TILE_SIZE, "The tiles' height is not right"
assert t.shape[1] == 2*TILE_SIZE, "I need 2 tiles side by side"
# Split the "double tile" in two tiles
t1, t2 = np.hsplit(t, 2)
# The most significant bit is the one for the color selection in
# Apple 2's HGR, we leave it at zero.
column = np.zeros( (TILE_SIZE,1,), dtype=np.bool_)
t1 = np.concatenate( (column, t1), axis=1)
t2 = np.concatenate( (column, t2), axis=1)
#image_to_ascii( np.concatenate( (t1, t2), axis=1), grid_size=8)
bm1 = np.packbits( t1, axis=1).flatten()
bm2 = np.packbits( t2, axis=1).flatten()
return bm1, bm2
def gen_code_vertical_tile_draw( fo, page):
labels = []
nops_labels = []
early_out_count = 1
fo.write("""
; Optimizing the BPL away is not worth it.
; A branch takes 2 or 3 cycles, but setting it up with self modifying code
; is at least 10 times that. So it's worth only for tall lines.
""")
for y in range(0,APPLE_YRES):
code = ""
if y % 6 == 0:
eo_label = f"early_out_p{page}_{early_out_count}"
code += f"""
BVC {eo_label}_skip ; always taken
{eo_label}:
RTS
{eo_label}_skip:
"""
early_out_count += 1
if page == 1:
prefix = ""
line_base = hgr_address(y, page=0x2000 + HGR_OFFSET)
else:
prefix = "p2_"
line_base = hgr_address(y, page=0x4000 + HGR_OFFSET)
nop_label = f"{prefix}pcsm{y}"
labels.append( "{}line{}".format(prefix, y))
nops_labels.append( nop_label)
# The self modified NOP will be replaced by DEX or INX.
# When BPL is self mod to soething else, remember
# that the INY before is increased but it is not tested
# So testing Y on being 0 doesn't work ('cos you might
# skip that 0). So one has to use a test that is a bit
# stronger (BMI/BPL).
# DEY approach
# DEY works well with BPL : 6,5,4..,1,0 : once at zero, addr+Y still wroks fine
# INY approach with BPL :
# 254,255,0,1 => problem, once at zero,
# addr+Y wraps by 256 bytes ! So we need to prevent 0. So we
# could use BEQ. Problem with BEQ is because self mod. If BEQ
# is self modded when Y reaches 0, the next iteration will be
# Y = 1 and BEQ won't trigger... Solution 1, join BPL and BEQ,
# but that's two instructions instead of one Solution 2,
# ensure that the BEQ is never self modded at the wrong
# position.
if y > 0:
nop_label_code = ""
else:
nop_label_code = f"{nop_label}:\n"
code += f"""
{prefix}line{y}:
LDA (tile_ptr),Y \t; 5+ (+ = page boundary)
ROR \t; 2
AND {line_base},X\t; 4+
STA {line_base},X\t; 5
DEY \t; 2 (affects only flags N(egative) and Z(ero) (cleared or set), not overflow(N)
{nop_label_code}
BMI {eo_label}\t; 2/3+
BCC @skip \t; 2/3+
TXA \t; 2
ADC x_shift \t; 3 (zero page)
TAX \t; 2
CLC \t; 2
\t; total = 23 (no break) or 32 (break)
@skip:
"""
if y > 0:
code = strip_asm_comments( code)
fo.write( code)
fo.write("\tRTS\n")
make_lo_hi_ptr_table( fo, prefix + "line_ptrs", labels)
# make_lo_hi_ptr_table( fo, "nops_ptrs", nops_labels)
def gen_code_vertical_tile_draw_no_tilebreaks( fo, page):
labels = []
nops_labels = []
early_out_count = 1
if page == 1:
prefix = "notb_"
else:
prefix = "notb_p2_"
for y in range(0,APPLE_YRES):
code = ""
if y % 11 == 0:
eo_label = f"{prefix}early_out_p{page}_{early_out_count}"
code += f"""
BVC {eo_label}_skip ; always taken
{eo_label}:
RTS
{eo_label}_skip:
"""
early_out_count += 1
if page == 1:
line_base = hgr_address(y, 0x2000 + HGR_OFFSET)
else:
line_base = hgr_address(y, 0x4000 + HGR_OFFSET)
nop_label = f"{prefix}pcsm{y}"
labels.append( f"{prefix}line{y}")
nops_labels.append( nop_label)
if y > 0:
nop_label_code = ""
else:
nop_label_code = f"{nop_label}:\n"
code += f"""
{prefix}line{y}:
LDA (tile_ptr),Y\t; 5+ (+ = page boundary)
AND {line_base},X\t; 4+
STA {line_base},X\t; 5
DEY\t; 2 (affects only flags N(egative) and Z(ero) (cleared or set), not overflow(N)
{nop_label_code}
BMI {eo_label}\t; 2/3
"""
if y > 0:
code = strip_asm_comments(code)
fo.write( code)
fo.write("\tRTS\n")
make_lo_hi_ptr_table( fo, prefix + "line_ptrs", labels)
# make_lo_hi_ptr_table( fo, "nops_ptrs", nops_labels)
def gen_code_vertical_tile_blank( fo, page):
labels = []
nops_labels = []
early_out_count = 1
for y in range(0,APPLE_YRES):
if y % 19 == 0:
# % 19 to make sure we use that BVC construct
# the less often possible (so that we avoid
# as many branches as we can)
eo_label = f"blank_early_out_p{page}_{early_out_count}"
#fo.write(f"\tCLV\n")
# The BVC is just here to skip the RTS.
# See optimisation about BMI; RTS below.
fo.write(f"\tBVC {eo_label}_skip\t; always taken\n")
fo.write(f"{eo_label}:\n\tRTS\n")
fo.write(f"{eo_label}_skip:\n")
early_out_count += 1
if page == 1:
prefix = ""
line_base = hgr_address(y, 0x2000 + HGR_OFFSET)
else:
prefix = "p2_"
line_base = hgr_address(y, 0x4000 + HGR_OFFSET)
labels.append( "{}blank_line{}".format(prefix, y))