-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
2331 lines (1690 loc) · 65 KB
/
utils.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 os
import random
import re
import math
import platform
import subprocess
import portion
import colorama
import numpy as np
import pygame
from PIL import Image, ImageFilter, ImageFont, ImageDraw
APPLE_YRES = 64*3 # 192
APPLE_XRES = 40*7 # 280
APPLE_HGR_PIXELS_PER_BYTE = 7
TRACKS_PER_DISK = 35
SECTORS_PER_TRACK = 16
SECTOR_SIZE = 256
DISK_SIZE = TRACKS_PER_DISK*SECTORS_PER_TRACK*256
def np_append_row( a, v = 0):
return np.append( a, [ [v] * a.shape[1] ], axis=0)
fsbt_sectors_read_order = [ (1,2), (1,4), (1,6), (1,8), (1,10), (1,12), (1,14),
(1,1), (1,3), (1,5), (1,7), (1,9), (1,11), (1,13), (1,15),
(2,0), (2,2), (2,4), (2,6), (2,8), (2,10), (2,12), (2,14),
(2,1), (2,3), (2,5), (2,7), (2,9), (2,11), (2,13), (2,15) ]
def configure_boot_code( fout, loader_size, page_base):
pages = (loader_size + 255) // 256
assert 0 < pages <= 15+16, f"FSTBT.S supports up to 31 sectors, no more. You asked {pages} pages"
page_map = [0] * len(fsbt_sectors_read_order)
for page in range( pages):
if page <= 14:
# First sector is the boot sector
track,sector = 1, 1 + page
else:
track,sector = 2, page - 15
for i,disk_pos in enumerate(fsbt_sectors_read_order):
if (track, sector) == disk_pos:
page_map[ i] = page + page_base
break
i = len(page_map)
while not page_map[i-1]:
i -= 1
page_map = page_map[0:i]
# for i,disk_pos in enumerate(fsbt_sectors_read_order):
# if i < len(page_map):
# print( "{:0X}\t{}".format( page_map[i], disk_pos))
# else:
# print( "--\t{}".format( disk_pos))
fout.write("!byte {}\n".format(
",".join(
[ f"${p:X}" for p in page_map] )))
fout.write("!byte $C0\n")
class AppleDisk:
DOS_SECTORS_MAP = [0x0, 0x7, 0xe, 0x6, 0xd, 0x5, 0xc, 0x4,
0xb, 0x3, 0xa, 0x2, 0x9, 0x1, 0x8, 0xf]
def __init__( self, filename = None):
self.filename = filename
self.sector_map = [ [None] * SECTORS_PER_TRACK for i in range(TRACKS_PER_DISK)]
self.set_track_sector( 0,0)
if not filename:
self._disk = bytearray( DISK_SIZE)
else:
with open(filename,"rb") as fin:
self._disk = bytearray(fin.read( DISK_SIZE))
def set_filename(self, filename):
self.filename = filename
def set_sector(self, track : int, logical_sector : int, data : bytearray):
""" Write data to a specific secto
"""
assert len(data) == SECTOR_SIZE
assert type(data) == bytearray
assert 0 <= track < TRACKS_PER_DISK
assert 0 <= logical_sector < SECTORS_PER_TRACK
sector = self.DOS_SECTORS_MAP[logical_sector]
track_offset = track * SECTORS_PER_TRACK * SECTOR_SIZE
dsk_ofs = track_offset + sector*SECTOR_SIZE
self._disk[dsk_ofs:dsk_ofs+SECTOR_SIZE] = data
def track(self):
return self._track
def sector(self):
return self._sector
def set_track_sector( self, track, sector):
""" Reset curren track/sector position
"""
self._track, self._sector = track, sector
def write_data( self, data, load_page, ident=None):
""" Write data in contiguous sector. Operates as a stream.
That is, the track/sector position will be moved from
sector to sector, track to track, to write all the data.
In this way, you can call this function to write contiguous
data (for example, complete file) one by one.
Return a tuple (first sector pos, first track pos, last
sector pos, last track pos).
"""
assert data
first_sector = self._track, self._sector
sectors_written = 0
data = bytearray(data)
#print( "Writing {} bytes from T:{} S:{}".format(len(data), self._track, self._sector))
for offset in range( 0, len(data), SECTOR_SIZE ):
if len(data) - offset >= SECTOR_SIZE:
s = data[offset:offset+SECTOR_SIZE]
else:
s = data[offset:len(data)]
s.extend( [0] * (SECTOR_SIZE - len(s)))
assert len(s) == SECTOR_SIZE
#print(f"Writing {self._track}/{self._sector}, offset {offset:x}")
last_sector = self._track, self._sector
self.set_sector( self._track, self._sector, bytearray(s))
sectors_written += 1
self.sector_map[self._track][self._sector] = ident
#if len(data) - offset > SECTOR_SIZE:
if self._sector < SECTORS_PER_TRACK-1:
self._sector += 1
else:
self._sector = 0
self._track += 1
if self._track >= TRACKS_PER_DISK:
print("!!!!! ERROR !!!!! Disk full")
return False
# self.toc.append( (first_sector[0],first_sector[1],
# last_sector[0],last_sector[1],
# load_page, label) )
#print("init_track_read {},{},{},{},${:x}\t; {} bytes, {} pages".format( first_sector[0],first_sector[1],last_sector[0],last_sector[1], load_page, len(data), (len(data) + 255)//SECTOR_SIZE))
#print(f"{sectors_written} sectors written")
return (first_sector[0],first_sector[1],
last_sector[0],last_sector[1],
load_page)
def save(self):
assert self.filename, "Please specify a proper filename first"
with open(self.filename, "wb") as fout:
fout.write(self._disk)
class LoaderTOC:
def __init__( self, disk_path):
# The first sector is the boot sector
self._file_list = []
self._disk = AppleDisk()
self._disk.set_filename(disk_path)
def add_file( self, path, start_page, nickname):
assert path and start_page and nickname
self._file_list.append( (path, start_page, nickname) )
def add_files( self, d):
for line in d:
self.add_file( *line)
def _make_toc_files( self, path, toc):
with open( os.path.join( path, "toc_equs.inc"),"w") as fout:
for l in toc:
if "=" in l:
fout.write(f"{l}\n")
with open( os.path.join( path, "toc_data.inc"),"w") as fout:
for l in toc:
if "=" not in l:
fout.write(f"{l}\n")
def generate_unconfigured_toc( self, path):
toc = []
# The first file is expected to be the loader
for i, entry in enumerate( self._file_list[1:]):
filepath, page_base, label = entry
uplbl = label.upper()
toc.append(f"FILE_{uplbl} = {i}")
toc.append(f"FILE_{uplbl}_LOAD_ADDR = ${page_base:X}00")
if os.path.exists(filepath):
s = os.path.getsize(filepath)
else:
s = 0
toc.append(f"FILE_{uplbl}_SIZE = {s}")
toc.append("\t.byte 0,0,0,0,0")
self._make_toc_files( path, toc)
def update_file( self, path, start_page, nickname):
success = False
for i, entry in enumerate( self._file_list):
filepath, page_base, label = entry
if label == nickname:
self._file_list[i] = (path, start_page, nickname)
success =True
break
assert success, f"The file with nickname {nickname} it not in the TOC"
def set_boot_sector( self, path):
self._disk.set_track_sector( 0, 0)
with open( path, "rb") as fin:
self._disk.write_data( fin.read(), 0x08)
def generate_disk( self, path):
# We write the loader once (it will be rewritten
# when the TOC will be fully known). This is just to
# position the other file (ie not the loader) correctly
# on the disk.
self._disk.set_track_sector( 0, 1)
toc = []
entry_ndx = 0
for i, entry in enumerate(self._file_list):
filepath, page_base, label = entry
if i == 5:
if self._disk.sector() != 0:
self._disk.set_track_sector( self._disk.track() + 1, 0)
with open( filepath,"rb") as fin:
data = fin.read()
ident = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"[i]
t = self._disk.write_data( data, page_base, ident)
if not t:
print(f"!!!! ERROR !!!!! Unable to add {filepath} to disk")
break
size = len(data)
assert size > 0, f"empty file ? {filepath}"
end = ((page_base * 256 + size - 1) & 0xFF00) + 0xFF
print(f"[{ident}] ${page_base:02X}00 - ${end:04X}: {filepath}, {size} bytes, label:{label}")
if i > 0:
# Skip the loader, cos it won't load itself :-)
uplbl = label.upper()
toc.append(f"FILE_{uplbl} = {entry_ndx}")
toc.append(f"FILE_{uplbl}_LOAD_ADDR = ${page_base:X}00")
s = os.path.getsize(filepath)
toc.append(f"FILE_{uplbl}_SIZE = {s}")
s = ".byte {},{},{},{},${:X}\t; {}".format(*t, label)
toc.append( s)
entry_ndx += 1
self._make_toc_files( path, toc)
def save( self):
free_sectors = 0
self._disk.save()
print("-"*37)
print(" 1111111111222222222223333")
print(" 01234567890123456789012345678901234")
print("-"*37)
sector_map = self._disk.sector_map
for sector in range( SECTORS_PER_TRACK):
all_sect = [sector_map[t][sector] for t in range(TRACKS_PER_DISK)]
t = ""
for i,s in enumerate( all_sect):
if s is not None:
t += s
elif i == sector == 0 :
t += '*'
else:
t += '.'
free_sectors +=1
print(f"{sector:X} {t}")
print()
used_sectors = TRACKS_PER_DISK*SECTORS_PER_TRACK - free_sectors
print("{} free sectors = {} bytes; {} sectors used = {} bytes".format(free_sectors, free_sectors*SECTOR_SIZE, used_sectors, used_sectors*SECTOR_SIZE))
print("-"*45)
class FixedPoint:
def __init__(self, x = 0):
if x >= 0:
self.x = x
else:
self.x = 65536 + x
def add( self, fp : "FixedPoint"):
return FixedPoint( (self.x + fp.x) & 65535)
def __str__( self):
if self.x & 32768 == 0:
f = self.x / 256
else:
f = - (65536-self.x) / 256
return str(f)
vertex_id = 1
class Vertex:
def __init__(self,x,y,z=0):
global vertex_id
# NAsty !!!! The type of _vec will depend
# on the type of its value ! if they(re all
# ints, it'll bt np.int, else np.float !
self._vec = np.array( [x,y,z] )
self._id = vertex_id
vertex_id += 1
def as_array(self):
return [self._vec[0],self._vec[1],self._vec[2]]
def grab_id( self, other):
self._id = other._id
return self
@property
def vid(self):
return self._id
@property
def x(self):
return self._vec[0]
@property
def y(self):
return self._vec[1]
@property
def z(self):
return self._vec[2]
def z_cleared(self):
return Vertex( self.x, self.y, 0)
def cross( self, other):
v = np.cross( self._vec, other._vec)
return Vertex( v[0], v[1], v[2] )
def round( self):
v = self
r = lambda n: int( round( n))
return Vertex( r(v.x), r(v.y), v.z)
def translate( self, v):
self._vec[0] += v.x
self._vec[1] += v.y
self._vec[2] += v.z
def scale( self, v):
self._vec[0] *= v
self._vec[1] *= v
self._vec[2] *= v
def norm( self):
# FIXME use numpy euclidean L2 norm
# https://iq.opengenus.org/norm-method-of-numpy-in-python/
return math.sqrt( sum( [ c**2 for c in self._vec]))
def normalize( self):
n = self.norm()
v = self._vec
return Vertex( v[0]/n, v[1]/n, v[2]/n )
def __mul__(self,other):
if type(other) == Vertex:
return np.dot( self._vec, other._vec)
else:
v = self._vec
return Vertex( v[0]*other, v[1]*other, v[2]*other )
def __add__(self,other):
v = self._vec + other._vec
return Vertex( v[0], v[1], v[2] )
def __sub__(self,other):
v = self._vec - other._vec
return Vertex( v[0], v[1], v[2] )
def __str__(self):
return "{:.2f},{:.2f},{:.2f}".format(self.x, self.y, self.z)
def __format__( self, format_spec):
return "{:.2f},{:.2f},{:.2f}".format(self.x, self.y, self.z)
def bounding_box( points):
assert points
tl_x, tl_y = points[0].x, points[0].y
br_x, br_y = points[0].x, points[0].y
for p in points[1:]:
#print(p)
tl_x = min( tl_x, p.x)
tl_y = max( tl_y, p.y)
br_x = max( br_x, p.x)
br_y = min( br_y, p.y)
return Vertex(tl_x,tl_y), Vertex( br_x, br_y)
class Edge:
def __init__( self, v1, v2):
self.v1, self.v2 = v1, v2
def points( self):
return [self.v1, self.v2]
def length(self):
return (self.v1 - self.v2).norm()
@property
def ray( self):
return self.v2 - self.v1
@property
def orig(self):
return self.v1
def __format__( self, z):
return f"edge: {self.v1} -> {self.v2}"
def LinePlaneCollision(planeNormal, planePoint, rayDirection, rayPoint, epsilon=1e-6):
# from https://rosettacode.org/wiki/Find_the_intersection_of_a_line_with_a_plane#Python
ndotu = planeNormal * rayDirection
if abs(ndotu) < epsilon:
return None
w = rayPoint - planePoint
si = (planeNormal * w) * (-1/ ndotu)
Psi = w + rayDirection * si + planePoint
return Psi
def bound_by( x, a,b):
if x < a:
return a
elif x > b:
return b
else:
return x
EPSILON = 1e-6
class Triangle:
def __init__( self, a : Vertex, b : Vertex, c : Vertex):
self.a,self.b,self.c = a,b,c
def __format__(self,fmt):
return f"[Tri: {self.a} | {self.b} | {self.c}]"
def vertices( self):
return [self.a,self.b,self.c]
def normal( self):
ab = self.b - self.a
ac = self.c - self.a
return ab.cross(ac).normalize()
def locate_point( self, p):
v_u = self.b - self.a
v_v = self.c - self.a
ap = p - self.a
u = ap*v_u * (1/ (v_u.norm()**2))
v = ap*v_v * (1/ (v_v.norm()**2))
return u,v
def edges( self):
return [ Edge( self.a, self.b),
Edge( self.b, self.c),
Edge( self.c, self.a) ]
def intersect_segment( self, r :Edge):
ERROR = None
v0 = self.a
v1 = self.b
v2 = self.c
v0v1 = v1 - v0
v0v2 = v2 - v0
pvec = r.ray.cross(v0v2)
det = v0v1 * pvec # Dot product
if det > -EPSILON and det < EPSILON:
return ERROR
invDet = 1 / det
tvec = r.orig - v0
u = (tvec * pvec) * invDet # dot product then scalar product
if u < 0 -EPSILON or u > 1 + EPSILON:
# print( f"bad u:{u}")
return ERROR
qvec = tvec.cross(v0v1)
v = (r.ray * qvec) * invDet
if v < 0 - EPSILON or u + v > 1 + EPSILON:
# print( f"bad v u:{u}, u:{v}")
return ERROR
t = (v0v2 * qvec) * invDet
#assert not math.isnan(t) and not math.isnan(u) and not math.isnan(v)
return ( t,u,v)
def read_wavefront(fpath):
""" Reads a wave front .obj file (can be exported
by Blender easily.
"""
vertices = []
faces = []
with open(fpath, "r") as fin:
for l in fin.readlines():
line = l.strip()
if line[0] == 'v':
v = [float(x) for x in line[2:].split()]
v = Vertex(v[0], v[1], v[2])
vertices.append(v)
print(v)
elif line[0] == 'f':
d = line[2:].split()
v = [vertices[int(t.split("//")[0]) - 1] for t in d]
t = Face(v[0], v[1], v[2], hidden=False)
faces.append(t)
print(t)
else:
print(line)
print(f"{len(vertices)} vertices, {len(faces)} faces")
return vertices, faces
def all_edges_intersections( tri, edges):
# print(f"all_edges_intersections : {tri}")
intersections = []
for edge in edges:
res = tri.intersect_segment( edge)
if res is not None:
t,u,v = res
if abs(t) < EPSILON:
t = 0
elif abs(t-1) < EPSILON:
t = 1
if 0 <= t <= 1:
inter = edge.orig + (edge.ray * t)
intersections.append( inter)
# print( f" Intersects with {edge} -> t={t}, point:{inter}")
# print( f" edge.orig : {edge.orig} edge_dir*t : {edge.ray*t}")
# print( "{}*{}={}".format( edge.ray.x, t, edge.ray.x * t))
return intersections
def intersect_triangle( view_tri, tri):
"""The view triangle is the one defined by a vertex located at the
view point (A) and a segment of which we're interested in computing
the visibility (BC).
We'll intersect that view triangle with all other triangles in
the scene.
The intersection between view triangle and another triangle is
made of 0,1 or 2 points of intersection. 0 means no intersection,
1 means both triangle are just touching each other in a locus made
of one point, 2 means there's an intersection locus made of a
segment.
Given an intersection segment, I1-I2, we're interested in
knowing how much of BC is hidden. To to that we simply
project I1 on BC along A-I1 (let P1 that point) and I2 on
BC along A-I2 (P2).
At this point we know that BC minus P1P2 is visible and
that BP1 an P2C are the visible parts (provided P1 is closer
to B than P2, which depends on the triangle positions).
"""
# print("---------- intersect_triangle")
intersections1 = all_edges_intersections( tri, view_tri.edges())
intersections2 = all_edges_intersections( view_tri, tri.edges())
intersections = intersections1 + intersections2
#print(f"self collisions {inter}, t={t} between edge {self_edge} and {tri}")
# Now I project each intersection along a line
# A (= self.a) - I on the segment BC (so basically, I compute
# the intersection between AI and BC.
# I cannot compute the intersection directly because
# I fear rounding errors that could lead to AI and BC
# to not intersect at all.
#
# So I do it by computing the intersection between
# a plane orthogonal to ABC, passing through IA
# and BC.
inter_ts = []
ab = view_tri.b - view_tri.a
ac = view_tri.c - view_tri.a
bc = Edge( ab, ac)
special_t_0 = False
special_t_1 = False
for inter in intersections:
if (inter - view_tri.b).norm() < 1e-6:
special_t_0 = True
continue
elif (inter - view_tri.c).norm() < 1e-6:
special_t_1 = True
continue
# All vectors are relative to A
ai = inter - view_tri.a
iplane_org = ai
iplane_norm_base = ai.cross( view_tri.normal())
iplane_norm = iplane_norm_base.normalize()
edge_inter = LinePlaneCollision( iplane_norm, iplane_org, bc.ray, bc.orig)
#print( edge_inter)
if edge_inter is None:
#continue
print(f"{self}")
print(f"{tri}")
print( iplane_org)
print( iplane_norm)
print( f"bc.orig = {bc.orig}")
print( f"bc.ray = {bc.ray}")
raise Exception("was expecting an intersection")
assert bc.ray.norm() > 0
t = (edge_inter - ab) * bc.ray * (1/(bc.ray.norm()**2))
#print(t)
if math.isnan(t):
print("---Error!")
print(f"{self} --- {tri}")
print( f"inter: {inter} - self.a : {view_tri.a}")
print(f"iplane = org:{iplane_org} -- norm_base:{iplane_norm_base} norm:{iplane_norm}")
print("self normal : {}".format( view_tri.normal()))
print(f"bc = org:{bc.orig} -- dir:{bc.ray}")
print(f"edge_inter = org:{edge_inter}")
raise Exception("NaN spotted")
if abs(t) < EPSILON:
t = 0
elif abs(1-t) < EPSILON:
t = 1
else:
t = bound_by(t,0,1)
inter_ts.append(t)
if len(inter_ts) == 0:
return None
elif len(inter_ts) == 1:
# At least one real intersection
if special_t_0:
inter_ts.append(0)
elif special_t_1:
inter_ts.append(1)
if not (len(inter_ts) == 0 or len(inter_ts) >= 2):
print(f"\nUnexpected number of intersections : {len(inter_ts)}. View-tri {view_tri}; other-tri : {tri}")
print(f"Special t : {special_t_0} {special_t_1}")
print("Intersections 1 : {}".format( [str(i) for i in intersections1]))
print("Intersections 2 : {}".format( [str(i) for i in intersections2]))
# raise Exception("")
inter_ts = []
if inter_ts:
inter_ts = [t for t in sorted( inter_ts)]
cleaned_ts = [ inter_ts[0] ]
for i in range( 1, len( inter_ts)):
if abs(inter_ts[i] - cleaned_ts[-1]) > EPSILON:
assert not math.isnan( inter_ts[i] )
cleaned_ts.append( inter_ts[i] )
assert len( cleaned_ts) in (1, 2), f"unexpected length : {len( cleaned_ts)}"
if len( cleaned_ts) == 1:
return None
assert cleaned_ts[0] < cleaned_ts[1], f"{cleaned_ts[0]} >? {cleaned_ts[1]} -- {inter_ts}"
# Invisible t's interval
t_interval = portion.closed( cleaned_ts[0], cleaned_ts[1])
#print( f"returning : {t_interval}")
return t_interval
else:
return None
class EdgeChain:
def __init__( self):
self._edges = []
self.first_point = self.last_point = None
@property
def edges( self):
return self._edges
def can_add_edge( self, edge):
return not self._edges or self.first_point in edge.points() or self.last_point in edge.points()
def add_edge( self, edge):
assert edge
if not self._edges:
self._edges = [edge]
self.first_point, self.last_point = edge.points()
elif self.first_point in edge.points():
self._edges = [edge] + self._edges
if edge.v1 != self.first_point:
self.first_point = edge.v1
else:
self.first_point = edge.v2
elif self.last_point in edge.points():
self._edges = self._edges + [edge]
if edge.v1 != self.last_point:
self.last_point = edge.v1
else:
self.last_point = edge.v2
else:
print("oups!")
print("Adding : {:x}-{:x}".format( id(edge.v1), id(edge.v2) ))
print("first:{:X}".format( id(self.first_point) ))
for e in self._edges:
print("{:X}-{:X}".format( id(e.v1), id(e.v2) ))
print("last:{:X}".format( id(self.last_point) ))
raise Exception(f"{edge} can't be added to the chain {self}")
def __len__( self):
return len( self.edges)
def __format__( self, z):
c = "_".join( [ "{}".format(e) for e in self._edges] )
return f"{id(self.first_point)} | {c} | {id(self.last_point)}"
def can_merge_with( self, chain):
assert type(chain) == EdgeChain
ends = [self.first_point, self.last_point]
return chain.first_point in ends or chain.last_point in ends
def merge( self, chain):
assert self.can_merge_with( chain)
print("-"*80)
# print( f"{self}")
# print( f"{chain}")
if chain.last_point in (self.first_point, self.last_point):
for e in reversed(chain._edges):
self.add_edge(e)
else:
for e in chain._edges:
print("merging : {:x}-{:x}".format( id(e.v1), id(e.v2) ))
self.add_edge(e)
class EdgePool:
def __init__( self):
self._edges = []
def edges(self):
return self._edges
def add_edge( self, edge):
assert edge not in self._edges
self._edges.append( edge)
def add_edges( self, edges):
for edge in edges:
self.add_edge( edge)
def make_chains( self):
best_c = None
for i in range(10):
c = self._make_chains( random.sample( self._edges, k=len(self._edges)))
if best_c is None or len(c) < len(best_c):
best_c = c
# 139 => 1005 edges
return best_c
def _make_chains( self, edges):
chains = []
for edge in edges:
connectable_chain = None
edge_added_to_chain = False
for chain in chains:
if chain.can_add_edge( edge):
chain.add_edge( edge)
edge_added_to_chain = True
break
if not edge_added_to_chain:
chain = EdgeChain()
chain.add_edge( edge)
chains.append( chain)
for i in range( len( chains)):
a = chains[i]
merged = False
for j in range( i+1, len(chains)):
b = chains[j]
if a.can_merge_with( b):
b.merge(a)
merged = True
break
if merged:
chains[i] = None
chains = [c for c in chains if c]
assert len( edges) == sum( [len(c) for c in chains])
# print("Merge result")
# for i, chain in enumerate( chains):
# print(f"Chain {i} {len(chain)}")
# print_chain( chain)
return chains
def special_points( v):
top = v[0]
top_ndx = 0
for i,p in enumerate( v[1:]):
if p.y < top.y:
top = p
top_ndx = i+1
# Find left and right vectors
v_left = v[top_ndx - 1]
v_right = v[top_ndx - 2]
if (v_left - top).z_cleared().cross((v_right - top).z_cleared()).z > 0:
v_left, v_right = v_right, v_left
return top, v_left, v_right
class Face:
def set_vertices( self, vert):
self.vertices = vert
a,b,c = vert[0],vert[1],vert[2]
self.normal = (b-a).cross(c-a)
self.edges = len( self.vertices)
return self
def __init__( self, a, b, c = None, z = None, hidden=True):
if z: # 4 sides
self.vertices = [a,b,c,z]
self.normal = (b-a).cross(c-a)
self.edges = 4
elif c: # 3 sides
self.vertices = [a,b,c]
self.normal = (b-a).cross(c-a)
self.edges = 3
else: # 1 side
assert hidden == False
self.vertices = [a,b]
self.edges = 1
self.hidden = hidden
self.xformed_vertices = None
self.number = None
def topmost_point(self):
top = self.xformed_vertices[0]
top_ndx = 0
for i,p in enumerate(self.xformed_vertices[1:]):
if p.y < top.y:
top = p
top_ndx = i+1
return top, top_ndx
def compute_z_slope_along_x( self, v = None):
if v is None:
assert self.xformed_vertices
v = self.xformed_vertices
top, v1, v2 = special_points(v)
# print("Compute")
# print( str( top))
# print( str( v1))
# print( str( v2))
y = min( v1.y, v2.y) - top.y
# Compute intersection of line Y=y with left and right vectors
# (coordinates relative to top of the triangle)
# for i in range(10):
# y = (min( v1.y, v2.y) - top.y) * (i+1) / 10
d1 = v1 - top