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
|
-
!
-
|
|
|
|
|
!
-
|
!
-
!
-
!
-
!
-
!
-
!
-
!
-
!
-
!
-
!
-
|
!
-
!
-
!
-
!
-
!
-
!
-
!
-
!
-
|
|
|
|
!
-
|
!
-
!
-
!
-
!
-
!
-
!
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
!
-
|
!
-
!
-
!
-
!
-
!
-
!
-
!
-
|
|
!
-
!
-
!
-
!
-
!
-
!
-
!
-
!
-
!
-
!
-
!
-
!
-
!
-
!
-
|
|
|
|
|
|
|
|
|
|
|
|
!
-
!
-
!
-
!
-
!
-
|
!
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
!
-
|
|
|
!
-
!
| import math
from tkinter import *
import tkinter.font as tkFont
import matrix
import copy
import threading
import re
import socket
import time
import readchar
from Cube import Cube
class Space:
''' Coordiante-system: Right-handed, Matrices are column-major ones '''
WIDTH = 1280.0
HEIGHT = 960.0
SPEED = 0.05
EPSILON = 1.0e-8
ZERO = EPSILON
def __init__(self):
print("start Space.__init__")
self.root = Tk()
self.root.resizable(False, False)
self.root.title('3D')
left = (self.root.winfo_screenwidth() - Space.WIDTH) / 2
top = (self.root.winfo_screenheight() - Space.HEIGHT) / 2
self.root.geometry('%dx%d+%d+%d' % (Space.WIDTH, Space.HEIGHT, left, top))
self.graph = Canvas(self.root, width=Space.WIDTH, height=Space.HEIGHT, background='black')
self.graph.pack()
self.walls = [matrix.Vector3D(7.0, 0.0, 0.0), matrix.Vector3D(-7.0, 0.0, 0.0), matrix.Vector3D(0.0, 7.0, 0.0), matrix.Vector3D(0.0, -7.0, 0.0), matrix.Vector3D(0.0, 0.0, 7.0), matrix.Vector3D(0.0, 0.0, -7.0)]
self.wallsnormals = [matrix.Vector3D(-1.0, 0.0, 0.0), matrix.Vector3D(1.0, 0.0, 0.0), matrix.Vector3D(0.0, -1.0, 0.0), matrix.Vector3D(0.0, 1.0, 0.0), matrix.Vector3D(0.0, 0.0, -1.0), matrix.Vector3D(0.0, 0.0, 1.0)]
self.ang = [0.0, 0.0, 0.0] self.trans = [0.0, 0.0, 2.0]
self.Scale = matrix.Matrix(4, 4)
Scalex = 1.0
Scaley = 1.0
Scalez = 1.0
self.Scale[(0,0)] = Scalex
self.Scale[(1,1)] = Scaley
self.Scale[(2,2)] = Scalez
self.Shearxy = matrix.Matrix(4, 4)
self.Shearxy[(0,2)] = 0.0
self.Shearxy[(1,2)] = 0.0
self.Shearxz = matrix.Matrix(4, 4)
self.Shearxz[(0,1)] = 0.0
self.Shearxz[(2,1)] = 0.0
self.Shearyz = matrix.Matrix(4, 4)
self.Shearyz[(1,0)] = 0.0
self.Shearyz[(2,0)] = 0.0
self.Shear = self.Shearxy*self.Shearxz*self.Shearyz
self.Rotx = matrix.Matrix(4,4)
self.Roty = matrix.Matrix(4,4)
self.Rotz = matrix.Matrix(4,4)
self.Tr = matrix.Matrix(4, 4)
self.Tr[(0,3)] = self.trans[0]
self.Tr[(1,3)] = self.trans[1]
self.Tr[(2,3)] = self.trans[2]
self.Proj = matrix.Matrix(4, 4)
fov = 60.0 zfar = 100.0
znear = 0.1
S = 1/(math.tan(math.radians(fov/2)))
A = Space.WIDTH/Space.HEIGHT
self.Proj[(0,0)] = S/A
self.Proj[(1,1)] = S
self.Proj[(2,2)] = (zfar+znear)/(znear-zfar)
self.Proj[(3,2)] = -1.0
self.Proj[(2,3)] = 2*(zfar*znear)/(znear-zfar)
self.toSC = matrix.Matrix(4, 4)
self.toSC[(0,0)] = Space.WIDTH/2
self.toSC[(1,1)] = -Space.HEIGHT/2
self.toSC[(0,3)] = Space.WIDTH/2
self.toSC[(1,3)] = Space.HEIGHT/2
self.root.bind("<Key>", self.keycallback)
self.fnt = tkFont.Font(family='Helvetica', size=12, weight='bold')
cube1=Cube(self)
cube1.set_name("s*")
self.cube1=cube1
self.polygons_3D=[cube1]
self.update(self.polygons_3D)
def start_3d(self):
self.root.mainloop()
def lookUpCube(self,name):
for i in range(len(self.polygons_3D)):
cx=self.polygons_3D[i]
if name==cx.name :
return cx
return None
def update(self,polygons_3D):
self.graph.delete(ALL)
self.Rotx[(1,1)] = math.cos(math.radians(360.0-self.ang[0]))
self.Rotx[(1,2)] = -math.sin(math.radians(360.0-self.ang[0]))
self.Rotx[(2,1)] = math.sin(math.radians(360.0-self.ang[0]))
self.Rotx[(2,2)] = math.cos(math.radians(360.0-self.ang[0]))
self.Roty[(0,0)] = math.cos(math.radians(360.0-self.ang[1]))
self.Roty[(0,2)] = math.sin(math.radians(360.0-self.ang[1]))
self.Roty[(2,0)] = -math.sin(math.radians(360.0-self.ang[1]))
self.Roty[(2,2)] = math.cos(math.radians(360.0-self.ang[1]))
self.Rotz[(0,0)] = math.cos(math.radians(360.0-self.ang[2]))
self.Rotz[(0,1)] = -math.sin(math.radians(360.0-self.ang[2]))
self.Rotz[(1,0)] = math.sin(math.radians(360.0-self.ang[2]))
self.Rotz[(1,1)] = math.cos(math.radians(360.0-self.ang[2]))
self.Rot = self.Rotx*self.Roty*self.Rotz
self.Tr[(0,3)] = -self.trans[0]
self.Tr[(1,3)] = -self.trans[1]
self.Tr[(2,3)] = -self.trans[2]
self.Tsf = self.Scale*self.Shear*self.Rot*self.Tr
for ic in range(len(polygons_3D)):
cubex=polygons_3D[ic]
cubex.update()
cubefaces=cubex.cubefaces
cls=cubex.cls
for i in range(len(cubefaces)):
poly = [] for j in range(len(cubefaces[0])):
cube=cubex.cube
v = cube[cubefaces[i][j]]
r=self.Tsf*v
poly.append(r)
n=self.calcNormalVec(poly)
if not self.isPolygonFrontFace(poly[0], n): continue
poly2d = []
inviewingvolume = False
for j in range(len(poly)):
ps =self.Proj*poly[j]
p=self.toSC*ps
x=int(p.x)
y = int(p.y)
poly2d.append((x, y))
if (-1.0 <= ps.x <= 1.0) and (-1.0 <= ps.y <= 1.0) and (-1.0 <= ps.z <= 1.0):
inviewingvolume = True
if inviewingvolume:
self.graph.create_polygon(*poly2d, fill=cls[i])
cfx=cubex.cfaces
xface=cfx[i]
xface_led=xface[0]
for k in range(len(xface_led)): v=xface_led[k]
r=self.Tsf*v
ps=self.Proj*r
p = self.toSC*ps
x, y = int(p.x), int(p.y)
self.graph.create_rectangle(x, y, x+3, y+3, fill="magenta")
v=xface[1] r=self.Tsf*v
ps=self.Proj*r
p=self.toSC*ps
x,y=int(p.x), int(p.y)
self.graph.create_rectangle(x,y, x+3, y+3, fill="cyan")
txt1 = 'xpos: '+str(self.trans[0])+' ypos: '+str(self.trans[1])+' zpos: '+str(self.trans[2])
txt2 = 'xrot: '+str(self.ang[0])+' yrot: '+str(self.ang[1])+' zrot: '+str(self.ang[2])
self.idTxt1 = self.graph.create_text(30,30, text=txt1, fill='white', anchor=SW, font=self.fnt)
self.idTxt2 = self.graph.create_text(30,60, text=txt2, fill='white', anchor=SW, font=self.fnt)
vFwd = self.getForwardVec2(self.ang[1])
txt3 = 'Fwd: '+str(vFwd)
self.idTxt3 = self.graph.create_text(30,90, text=txt3, fill='white', anchor=SW, font=self.fnt)
def isPolygonFrontFace(self, v, n): '''v is a vertex of the polygon, n is the normal-vector of the polygon.'''
c = matrix.Vector3D(0.0, 0.0, 1.0)
vv = v-c
r = vv.dot(n)
return r < 0.0
def calcNormalVec(self, p):
'''p is an array of vertices of the polygon/face'''
v1 = p[0]-p[1]
v2 = p[0]-p[3]
v = v1.cross(v2)
v.normalize()
return v
def getForwardVec1(self): m = self.Rot.invert()
f1 = m[(0,2)]
f2 = m[(1,2)]
f3 = m[(2,2)]
v = matrix.Vector3D(f1, f2, f3)
v.normalize()
return -v
def getForwardVec2(self, yrot): f1 = -math.sin(math.radians(yrot))
f2 = 0.0
f3 = -math.cos(math.radians(yrot))
v = matrix.Vector3D(f1, f2, f3)
return v
def isCollisionPlanes(self, campos, camdir):
num = len(self.walls)
for i in range(num):
iscol, dist = self.isCollisionPlane(self.walls[i], self.wallsnormals[i], campos, camdir)
if iscol and dist < 0.1:
return True
return False
def isCollisionPlane(self, p, n, campos, camdir):
'''instead of pointonplane (p) and normalofplane (n) we could pass a polygon and calculate its normal vector here. campos is the position of the camera and camdir is the forward vector of the camera'''
dist = 0.0
dotprod = camdir.dot(n)
if ((dotprod < Space.ZERO) and (dotprod > -Space.ZERO)):
return False, dist
dist = (n.dot(p-campos))/dotprod
if (dist < -Space.ZERO):
return False, dist
return True, dist
def isCollisionCube(self, campos,polygons_3D):
'''Checks if the camera is inside the cube (this is the bounding-box-technique (bbt) but we have a cube so we do not need to calculate a bb) '''
for i in range(len(polygons_3D)):
cube=(polygons_3D[i]).cube
cubefaces=(polygons_3D[i]).cubefaces
if (campos.z >= cube[cubefaces[0][0]].z and campos.z <= cube[cubefaces[2][0]].z) and (campos.y >= cube[cubefaces[5][0]].y and
campos.y <= cube[cubefaces[4][0]].y) and (campos.x >= cube[cubefaces[3][0]].x and campos.x <= cube[cubefaces[1][0]].x):
return True
return False
def keycallback(self, event):
if event.keysym == 'Up':
vFwd = self.getForwardVec2(self.ang[1])
pos = matrix.Vector3D(self.trans[0]+vFwd.x*Space.SPEED, self.trans[1], self.trans[2]+vFwd.z*Space.SPEED)
if self.isCollisionPlanes(pos, vFwd):
return
if self.isCollisionCube(pos,self.polygons_3D):
return
self.trans[0] += vFwd.x*Space.SPEED
self.trans[2] += vFwd.z*Space.SPEED
elif event.keysym == 'Down':
vFwd = self.getForwardVec2(self.ang[1])
vBck = -vFwd
pos = matrix.Vector3D(self.trans[0]-vFwd.x*Space.SPEED, self.trans[1], self.trans[2]-vFwd.z*Space.SPEED)
if self.isCollisionPlanes(pos, vBck):
return
if self.isCollisionCube(pos,self.polygons_3D):
return
self.trans[0] -= vFwd.x*Space.SPEED
self.trans[2] -= vFwd.z*Space.SPEED
elif event.keysym == 'Right':
self.ang[1] -= 1.5
elif event.keysym == 'Left':
self.ang[1] += 1.5
elif event.keysym == 'u':
pos = matrix.Vector3D(self.trans[0], self.trans[1]+Space.SPEED, self.trans[2])
vUp = matrix.Vector3D(0.0, 1.0, 0.0)
if self.isCollisionPlanes(pos, vUp):
return
if self.isCollisionCube(pos,self.polygons_3D):
return
self.trans[1] += Space.SPEED
elif event.keysym == 'd':
pos = matrix.Vector3D(self.trans[0], self.trans[1]-Space.SPEED, self.trans[2])
vDwn = matrix.Vector3D(0.0, -1.0, 0.0)
if self.isCollisionPlanes(pos, vDwn):
return
if self.isCollisionCube(pos,self.polygons_3D):
return
self.trans[1] -= Space.SPEED
elif event.keysym == 'Escape':
self.quit()
if self.ang[1] >= 360.0:
self.ang[1] -= 360.0
if self.ang[1] < 0.0:
self.ang[1] += 360.0
self.update(self.polygons_3D)
def quit(self):
self.root.quit()
def client_start(self):
""" start client """
print("start client_start")
handle_thread = threading.Thread(target=self.handler, daemon=True)
self.parse("send up \"str (this s* f2d1 next s*4 f4d1)\".")
self.parse("send up \"str (this s*4 f2d1 next s*44 f4d1)\".")
self.update(self.polygons_3D)
handle_thread = threading.Thread(target=self.handler, daemon=True)
handle_thread.start()
def handler(self):
""" receive commands from terminal """
while True:
print("input...")
line=input()
self.parse(line)
self.update(self.polygons_3D)
def clear(self):
self.polygons_3D=[self.cube1]
self.update(self.polygons_3D)
def parse(self,line):
print(line)
p=line.find("send up ")
if(p<0):
return
xl=line[(p+len("send up ")):]
px=parser(xl)
px.rb()
if not (px.key("\"")):
return
if not px.key("str "):
return
px.rb()
if not px.key("("):
return
px.rb()
if not px.key("this "):
return
px.rb()
xn=[""]
if not px.d_name(xn):
return
px.rb()
dn1=xn[0]
cn=[(0,0)]
if not px.connect(cn):
return
cn1=cn[0]
px.rb()
if not px.key("next "):
return
px.rb()
xn=[""]
if not px.d_name(xn):
return
dn2=xn[0]
px.rb()
if not px.connect(cn):
return
cn2=cn[0]
px.rb()
if not px.key(")"):
return
px.rb()
if not px.key("\""):
return
px.rb()
if not px.key("."):
return
print("dn1="+dn1)
cube1=self.lookUpCube(dn1)
if cube1 == None:
print("new "+dn1)
cube1=Cube(self)
cube1.set_name(dn1)
self.polygons_3D.append(cube1)
print("dn2="+dn2)
cube2=self.lookUpCube(dn2)
if cube2 == None:
print("new "+dn2)
cube2=Cube(self)
cube2.set_name(dn2)
self.polygons_3D.append(cube2)
print(cn1)
print(cn2)
if1=cn1[0]
if2=cn2[0]
id1=cn1[1]
id2=cn2[1]
v2=cube1.get_next_place_position(if1)
cube2.moveTo(v2.x,v2.y,v2.z)
cube1.rotate_nextdoor_cube_until_match_the_face(if1, cube2, if2)
cube1.rotate_nextdoor_cube_until_match_the_direction(if1,cube2,if2,id2)
self.update(self.polygons_3D)
class parser:
def __init__(self,line):
self.line=line
print("parser init "+line)
def alpha(self,p2a):
c=self.line[0]
p2a[0]=c
if(c.isalpha()):
self.line=self.line[1:]
return True
return False
def digit(self,p2i):
c=self.line[0]
if(c.isdigit()):
p2i[0]=int(c)
self.line=self.line[1:]
return True
return False
def d_name(self,xn):
cl=['']
if not self.alpha(cl):
return False
xn[0]=xn[0]+cl[0]
if not self.key("*"):
return False
xn[0]=xn[0]+"*"
dx=[0]
while self.digit(dx):
xn[0]=xn[0]+str(dx[0])
return True
def connect(self,tx):
if not self.key("f"):
return False
fx=[0]
if not self.digit(fx):
return False
if not self.key("d"):
return False
dx=[0]
if not self.digit(dx):
return False
tx[0]=(fx[0],dx[0])
return True
def key(self,key):
tf=self.line.startswith(key)
print(tf)
if(self.line.startswith(key)):
lk=len(key)
self.line=self.line[lk:]
return True
return False
def rb(self):
while self.key(' '):
continue
class Chat_Client:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
HOST = '192.168.4.1'
PORT = 23
def __init__(self):
print("start Chat_Client.__init__")
def set_space(self,space):
self.space=space
def start_input_thread(self):
handle_thread2 = threading.Thread(target=self.start_input, args=(self.sock,), daemon=True)
handle_thread2.start()
def start_input(self,sock):
print("sock=")
print(sock)
print("input...")
line=""
cx=bytearray(8)
while True:
try:
line=input()
if line=="clear.":
self.send_message("srr.")
self.space.clear()
else:
for i in range(len(line)):
c=line[i]
sock.sendall(c.encode('ascii',errors='replace'))
time.sleep(0.01)
except:
print("error")
def send_message_nl(self,py2x_message):
msg=py2x_message+'\n'
self.sock.sendall(msg.encode('ascii',errors='replace'))
def send_message(self,py2x_message):
msg=py2x_message
self.sock.sendall(msg.encode('ascii',errors='replace'))
def parse(self,line):
vf.parse(line)
def client_start(self):
"""start client"""
self.sock.connect((self.HOST, self.PORT))
handle_thread = threading.Thread(target=self.handler, args=(self.sock,), daemon=True)
handle_thread.start()
def handler(self,sock):
"""receive the message from the server and print it."""
while True:
lx=""
while True:
data = sock.recv(1024)
dl=len(data)
try:
rd=data.decode('utf-8')
except:
rd='?'*dl
for i in range(dl):
c=rd[i]
lx=lx+c
if c=="." or c=="\n":
print("[receive] "+lx)
self.parseLines(lx)
lx=""
if c=="." or c=="\n":
break
print("[receive]-"+lx)
if self.space!=None:
print("parse-"+lx)
self.parseLines(lx)
def parseLines(self,ls):
lsx=ls.splitlines()
for i in range(len(lsx)):
self.space.parse(lsx[i])
if __name__ == "__main__":
client=Chat_Client()
space=Space()
client.set_space(space)
client.client_start()
client.start_input_thread()
space.start_3d()
|