-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathkivyglops.py
3977 lines (3728 loc) · 179 KB
/
kivyglops.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 module is the Kivy implementation of PyGlops.
It provides features that are specific to display method
(Kivy's OpenGL-like API in this case).
"""
__author__ = 'Jake Gustafson'
import hashlib
from pyglops import *
import uuid
import ast
from kivy.resources import resource_find
from kivy.graphics import *
from kivy.uix.widget import Widget
from kivy.core.image import Image
from pyrealtime import *
from kivy.clock import Clock
# stuff required for KivyGlopsWindow
from kivy.app import App
from kivy.core.window import Window
from kivy.core.window import Keyboard
from kivy.graphics.transformation import Matrix
from kivy.graphics.opengl import *
from kivy.graphics import *
# from kivy.input.providers.mouse import MouseMotionEvent
from kivy.factory import Factory
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.graphics import Color, Rectangle
from kivy.logger import Logger
from kivy.vector import Vector
from kivy.core.audio import SoundLoader
from common import *
import time
import random
nearest_not_found_warning_enable = True
_multicontext_enable = False # only should be set while not running
print("[ kivyglops.py ] default _multicontext_enable: " +
str(_multicontext_enable))
# region changed automatically after showing error only once
tltf = " (this is the last time this message will be shown for "
tlt = "this is the last time this message will be shown"
bounds_warning_enable = True
look_at_none_warning_enable = True
look_at_pos_none_warning_enable = True
missing_bumpable_warning_enable = True
missing_bumper_warning_enable = True
missing_radius_warning_enable = True
no_bounds_warning_enable = True
# out_of_hitbox_note_enable = True
show_zero_degrees_pf_warning_enable = True # pf is per frame
show_zero_walk_upf_warning_enable = True # upf is units per frame
# endregion changed automatically after showing error only once
def get_distance_kivyglops(a_glop, b_glop):
return math.sqrt((b_glop._t_ins.x - a_glop._t_ins.x)**2 +
(b_glop._t_ins.y - a_glop._t_ins.y)**2 +
(b_glop._t_ins.z - a_glop._t_ins.z)**2)
# def get_distance_vec3(a_vec3, b_vec3):
# return math.sqrt((b_vec3[0] - a_vec3[0])**2 +
# (b_vec3[1] - a_vec3[1])**2 +
# (b_vec3[2] - a_vec3[2])**2)
# NOTE: use str(_t_ins.xyz) instead
# def translate_to_string(_t_ins):
# result = "None"
# if _t_ins is not None:
# result = str([_t_ins.x, _t_ins.y, _t_ins.z])
# return result
# If inherits from Widget, has the following error only on
# Kivy 1.9.0 (on Windows 10; does not occur on 1.10.0 on linux):
# [ KivyGlop ] ERROR--__init__ could not finish super!
# <class 'TypeError'> 'dict' object is not callable:
# File "T:\pcerruti2020\Programming\Open GL\kivyglops.py", \
# line 111, in __init__
# super(KivyGlop, self).__init__() # only does class inherited \
# FIRST (see class line above) therefore _init_glop is called below
# File "C:\kivy\kivy34\kivy\uix\widget.py", line 261, in __init__
# super(Widget, self).__init__(**kwargs)
# File "kivy\_event.pyx", line 252, in kivy._event.EventDispatcher.\
# __init__ (kivy\_event.c:4571)
# File "kivy\_event.pyx", line 777, in kivy._event.EventDispatcher.\
# properties (kivy\_event.c:8189)
class KivyGlop(PyGlop): # formerly KivyGlop(Widget, PyGlop)
# freeAngle = None
# degreesPerSecond = None
# freePos = None
_mesh = None # the (Kivy) Mesh object
_calculated_size = None
_t_ins = None
_r_ins_x = None
_r_ins_y = None
_r_ins_z = None
_s_ins = None
_color_instruction = None
_context_instruction = None
_axes_mesh = None # InstructionGroup for axes
_pivot_scaled_point = None
_pushmatrix = None
_updatenormalmatrix = None
_popmatrix = None
_own_shader_enable = None
no_mesh_warning_enable = None
def __init__(self, default_templates=None):
try:
super(KivyGlop, self).__init__(
default_templates=default_templates)
# only does class inherited FIRST (see class line above)
# therefore _init_glop is called below
except:
print("[ KivyGlop ] ERROR--__init__ could not finish"
" super!")
view_traceback()
try:
self._init_glop(default_templates=default_templates)
except:
print("[ KivyGlop ] ERROR--uh oh, "
"self._init_glop didn't work either:")
view_traceback()
self.material = new_material()
self.material['diffuse_color'] = (1.0, 1.0, 1.0, 1.0)
# overlay vertex color onto this using vertex alpha
self.material['ambient_color'] = (0.0, 0.0, 0.0, 1.0)
self.material['specular_color'] = (1.0, 1.0, 1.0, 1.0)
self.material['specular_coefficent'] = 16.0
self._own_shader_enable = False
# if False during add_glop, gets shader of parent if
# _multicontext_enable, else does nothing either way
self.no_mesh_warning_enable = True
# self.freeAngle = 0.0
# self.degreesPerSecond = 0.0
# self.freePos = (10.0,100.0)
# TODO: use a RenderContext instead?
# self.canvas = RenderContext()
if _multicontext_enable:
self.canvas = RenderContext(
use_parent_projection=True,
use_parent_modelview=True,
use_parent_frag_modelview=True)
# compute_normal_mat=False,
else:
self.canvas = InstructionGroup()
self.canvas.clear()
self._context_instruction = ContextInstruction()
self._calculated_size = (1.0,1.0)
# finish this--or skip since only needed for getting
# pivot point
# Rotate(
# angle=self.freeAngle,
# origin=(self._calculated_size[0]/2.0,
# self._calculated_size[1]/2.0))
self._pivot_point = 0.0, 0.0, 0.0
# self.get_center_average_of_vertices()
self._pivot_scaled_point = 0.0, 0.0, 0.0
self._r_ins_x = Rotate(0, 1, 0, 0) #angle, x, y z
self._r_ins_x.origin = self._pivot_scaled_point
self._r_ins_y = Rotate(0, 0, 1, 0) #angle, x, y z
self._r_ins_y.origin = self._pivot_scaled_point
self._r_ins_z = Rotate(0, 0, 0, 1) #angle, x, y z
self._r_ins_z.origin = self._pivot_scaled_point
self._s_ins = Scale(1.0,1.0,1.0)
# self._s_ins.origin = self._pivot_point
self._t_ins = Translate(0, 0, 0)
self._color_instruction = Color(1.0, 0.0, 1.0, 1.0)
# TODO: eliminate this in favor of
# self.set_uniform("mat_diffuse_color",
# (1.0, 0.0, 1.0, 1.0))
self.generate_axes()
def __str__(self):
result = str(type(self))
if self._t_ins is not None:
result = (str(type(self)) + " named " + str(self.name) +
" at " + str(self._t_ins.xyz))
return result
def debug_to(self, dest):
dest['pos'] = fixed_width(self._t_ins.xyz, 4, " ")
def get_angles(self):
return (self._r_ins_x.angle,
self._r_ins_y.angle,
self._r_ins_z.angle)
def set_angles(self, angles):
self._r_ins_x.angle = angles[0]
self._r_ins_y.angle = angles[1]
self._r_ins_z.angle = angles[2]
def get_pos(self):
return (self._t_ins.xyz)
def set_pos(self, pos):
self._t_ins.x = pos[0]
self._t_ins.y = pos[1]
self._t_ins.z = pos[2]
def get_angle(self, axis_index):
if axis_index == 0:
return self._r_ins_x.angle
elif axis_index == 1:
return self._r_ins_y.angle
elif axis_index == 2:
return self._r_ins_z.angle
return None
def set_angle(self, axis_index, angle):
if axis_index == 0:
self._r_ins_x.angle = angle
elif axis_index == 1:
self._r_ins_y.angle = angle
elif axis_index == 2:
self._r_ins_z.angle = angle
else:
print("[ KivyGlop ] ERROR in set_angle: " +
str(axis_index) + " is out of range (dimension" +
" should be 0, 1, or 2)")
def append_wobject(self, this_wobject,
pivot_to_g_enable=True):
super(KivyGlop, self).append_wobject(
this_wobject,
pivot_to_g_enable=pivot_to_g_enable)
if self.material is not None:
self._color_instruction = Color(
self.material['diffuse_color'][0],
self.material['diffuse_color'][1],
self.material['diffuse_color'][2],
self.material['diffuse_color'][3])
else:
print("[ KivyGlop ] WARNING in append_wobject:" +
" self.material is None for " + str(self.name))
def save(self, path):
lines = []
self.emit_yaml(lines, "")
try:
outs = open(path, 'w')
for line in lines:
outs.write(line + "\n")
outs.close()
except:
print("[ KivyGlop ] ERROR--could not finish save to '" +
path + "':")
view_traceback()
#load yaml-formatted glop file
def load(self, source_path, original_path=None):
specified_path = source_path
if self.vertices is not None:
print("[ KivyGlop ] WARNING: vertices are already "
"present during load, overwriting")
if specified_path is not None:
if original_path is None:
original_path = source_path
if not os.path.isfile(source_path):
source_path = resource_find(source_path)
if os.path.isfile(source_path):
ins = open(source_path)
line = True
line_number = 1
scopes = [ScopeInfo()]
scopes[0].indent = ""
scopes[0].name = ""
scopes[0].line_number = -1
nyi_names = {}
while line:
line = ins.readline()
if line:
line_strip = line.strip()
indent = find_any_not(line, " \t")
depth = int(len(indent)/2) # assumes " "
# yaml indent
while len(scopes)<=depth:
scopes.append(ScopeInfo())
if line_strip[:1] != "#":
op_i = line_strip.find(":")
if line_strip[-1:]==":":
scopes[depth].name = \
line_strip[:-1].strip()
scopes[depth].indent = indent
scopes[depth].line_number = line_number
array_i = line_strip.find("-")
if line_strip[0:1]=="-":
if depth>0:
val = \
get_literal_value_from_yaml(line_strip[2:].strip())
if scopes[depth-1].name == \
"vertices":
self.vertices.append(float(val))
elif scopes[depth-1].name == \
"indices":
self.indices.append(int(val))
else:
if scopes[depth-1].name not in \
nyi_names:
print(
specified_path + "(" +
str(line_number) +
",0): (INPUT ERROR)" +
" item for unknown " +
"array " +
scopes[depth-1].name +
" not implemented" +
ttl +
scopes[depth-1].name +
")"
)
nyi_names[scopes[depth-1].name] = False
else:
print(
specified_path + "(" +
str(line_number) + ",0): " +
"(INPUT ERROR) array in " +
"deepest scope (should be" +
" indented under an object" +
" name)"
)
else:
if op_i > -1:
name = line_strip[:op_i]
val = get_literal_value_from_yaml(
line_strip[op_i+1:])
if name == \
"get_texture_diffuse_path()":
self.set_texture_diffuse(val)
else:
print(
specified_path + "(" +
str(line_number) + ",0): " +
"(INPUT ERROR) input with " +
"neither colon nor starting" +
" with hyphen is not " +
"implemented"
)
prev_indent = indent
line_number += 1
ins.close()
else:
print("[ KivyGlop ] ERROR in load: missing '" +
specified_path + "")
# TODO: if cached, change source_path for each object to
# that in stats.yml in cache folder
else:
print("[ KivyGlop ] ERROR in load: source_path was None")
def emit_yaml(self, lines, min_tab_string):
super(KivyGlop, self).emit_yaml(lines, min_tab_string)
lines.append(min_tab_string +
"translate_x: " +
get_yaml_from_literal_value(self._t_ins.x))
lines.append(min_tab_string +
"translate_y: " +
get_yaml_from_literal_value(self._t_ins.y))
lines.append(min_tab_string +
"translate_z: " +
get_yaml_from_literal_value(self._t_ins.z))
def set_coord(self, index, value):
if index == 0:
self._t_ins.x = value
elif index == 1:
self._t_ins.y = value
elif index == 2:
self._t_ins.z = value
else:
print("[ KivyGlop ] ERROR in set_coord: bad index " +
str(index))
def get_coord(self, index):
if index == 0:
return self._t_ins.x
elif index == 1:
return self._t_ins.y
elif index == 2:
return self._t_ins.z
else:
print("[ KivyGlop ] ERROR in get_coord: bad index " +
str(index))
return None
def new_vertex(self, set_coords, set_color):
# NOTE: assumes vertex format is ok (should be checked by
# generate_axes)
# assumes normal should be point relative to 0,0,0
vertex_components = [0.0]*self.vertex_depth
for i in range(0, 3):
vertex_components[self._POSITION_OFFSET+i] = set_coords[i]
# Without the 4th index, matrix math cannot work and geometry
# cannot be translated (!):
if self.vertex_format[self.POSITION_INDEX][VFORMAT_VECTOR_LEN_INDEX] > 3:
vertex_components[self._POSITION_OFFSET+3] = 1.0
if set_color is not None:
for i in range(0, len(set_color)):
vertex_components[self.COLOR_OFFSET+i] = set_color[i]
if (len(set_color)) < 4 and (self.vertex_depth > 3):
vertex_components[self.COLOR_OFFSET+3] = 1.0
normals = [0.0]*3;
for i in range(0, 3):
normals[i] = set_coords[i]
normalize_3d_by_ref(normals)
for i in range(0, 3):
vertex_components[self._NORMAL_OFFSET+i] = normals[i]
# print(" #* made new vertex " + str(vertex_components) +
# " (color at " + str(self.COLOR_OFFSET) + ")")
return vertex_components
def append_vertex(self, target_vertices, set_coords, set_color):
offset = len(target_vertices)
index = int(offset/self.vertex_depth)
target_vertices.extend(self.new_vertex(set_coords, set_color))
return index
def generate_plane(self):
f_name = "generate_plane"
_axes_vertices = []
_axes_indices = []
IS_SELF_VFORMAT_OK = True
try:
fail_prefix = ("[ KivyGlop ] ERROR in " + f_name + ":" +
" could not find name containing ")
fail_suffix = (" in any vertex format element" +
" (see PyGlop __init__)")
if self._POSITION_OFFSET<0:
IS_SELF_VFORMAT_OK = False
print(fail_prefix + "'pos' or 'position'" + fail_suffix)
if self._NORMAL_OFFSET<0:
IS_SELF_VFORMAT_OK = False
print(fail_prefix + "'normal'" + fail_suffix)
if self._TEXCOORD0_OFFSET<0:
IS_SELF_VFORMAT_OK = False
print(fail_prefix + " 'texcoord'" + fail_suffix)
if self.COLOR_OFFSET<0:
IS_SELF_VFORMAT_OK = False
print(fail_prefix + " 'color'" + fail_suffix)
except:
IS_SELF_VFORMAT_OK = False
print("[ KivyGlop ] ERROR in " + f_name + ":" +
" couldn't find offsets")
offset = 0
white = (1.0, 1.0, 1.0, 1.0)
nv = -.5 # near vector
fv = .5 # far vector
self.append_vertex(_axes_vertices, (nv, 0.0, nv), white)
self.append_vertex(_axes_vertices, (nv, 0.0, fv), white)
self.append_vertex(_axes_vertices, (fv, 0.0, fv), white)
self.append_vertex(_axes_vertices, (fv, 0.0, nv), white)
_axes_indices.extend([0,3,2, 2,1,0]) # counterclockwise winding
#clockwise winding (not usual unless want to flip normal):
#_axes_indices.extend([0,1,2, 2,3,0])
self._mesh = Mesh(
vertices=_axes_vertices,
indices=_axes_indices,
fmt=self.vertex_format,
mode='triangles',
texture=None,
)
# NOTE: result is a full solid (3 boxes) where all axes can always
# be seen except when another is in the way (some vertices are
# doubled so that vertex color can be used).
# See etc/axes-widget-diagram.png
def generate_axes(self):
f_name = "generate_axes"
_axes_vertices = []
_axes_indices = []
if self.vertex_depth is None:
print("[ KivyGlop ] WARNING in generate_axes: "
"vertex_depth was None--trying "
"on_vertex_format_change...")
self.on_vertex_format_change()
IS_SELF_VFORMAT_OK = True
try:
fail_prefix = ("[ KivyGlop ] ERROR in " + f_name + ":" +
" could not find name containing ")
fail_suffix = (" in any vertex format element" +
" (see PyGlop __init__)")
if self._POSITION_OFFSET<0:
IS_SELF_VFORMAT_OK = False
print(fail_prefix + "'pos' or 'position'" + fail_suffix)
if self._NORMAL_OFFSET<0:
IS_SELF_VFORMAT_OK = False
print(fail_prefix + "'normal'" + fail_suffix)
if self._TEXCOORD0_OFFSET<0:
IS_SELF_VFORMAT_OK = False
print(fail_prefix + "'texcoord'" + fail_suffix)
if self.COLOR_OFFSET<0:
IS_SELF_VFORMAT_OK = False
print(fail_prefix + "'color'" + fail_suffix)
except:
IS_SELF_VFORMAT_OK = False
print("[ KivyGlop ] ERROR in " + f_name + ":" +
" couldn't find offsets")
offset = 0
red = (1.0, 0.0, 0.0)
green = (0.0, 1.0, 0.0)
blue = (0.0, 0.0, 1.0)
# NOTE: default opengl winding order is counter-clockwise
# (where makes normal face you)
cv = 0.0 # center vector
nv = 0.1 # near vector
fv = 1.0 # far vector
self.append_vertex(_axes_vertices, (cv, cv, cv), green) # 0
self.append_vertex(_axes_vertices, (nv, cv, cv), green) # 1
self.append_vertex(_axes_vertices, (cv, cv, nv), green) # 2
self.append_vertex(_axes_vertices, (nv, cv, nv), green) # 3
self.append_vertex(_axes_vertices, (cv, fv, cv), green) # 4
self.append_vertex(_axes_vertices, (nv, fv, cv), green) # 5
self.append_vertex(_axes_vertices, (cv, fv, nv), green) # 6
self.append_vertex(_axes_vertices, (nv, fv, nv), green) # 7
# bottom & right
# back & top
# left & front
_axes_indices.extend([0,1,3, 0,3,2, 0,2,6, 0,6,4,
0,4,5, 0,5,1, 4,5,7, 4,7,6,
1,5,7, 1,7,3, 2,3,7, 2,7,6
])
self.append_vertex(_axes_vertices, (nv, cv, cv), red) # 8
self.append_vertex(_axes_vertices, (nv, cv, nv), red) # 9
self.append_vertex(_axes_vertices, (nv, nv, cv), red) # 10
self.append_vertex(_axes_vertices, (fv, nv, nv), red) # 11
self.append_vertex(_axes_vertices, (fv, cv, cv), red) # 12
self.append_vertex(_axes_vertices, (fv, nv, cv), red) # 13
self.append_vertex(_axes_vertices, (fv, cv, nv), red) # 14
self.append_vertex(_axes_vertices, (fv, nv, nv), red) # 15
# back & outside
# bottom & inside
# top & front
_axes_indices.extend([8,9,11, 8,11,10, 8,10,13, 8,13,12,
8,12,14, 8,14,9, 9,14,15, 9,15,11,
10,11,15, 11,15,13, 12,13,15, 12,15,14
])
self.append_vertex(_axes_vertices, (cv, cv, nv), blue) # 16
self.append_vertex(_axes_vertices, (nv, cv, nv), blue) # 17
self.append_vertex(_axes_vertices, (cv, nv, nv), blue) # 18
self.append_vertex(_axes_vertices, (nv, nv, nv), blue) # 19
self.append_vertex(_axes_vertices, (cv, cv, fv), blue) # 20
self.append_vertex(_axes_vertices, (nv, cv, fv), blue) # 21
self.append_vertex(_axes_vertices, (cv, nv, fv), blue) # 22
self.append_vertex(_axes_vertices, (nv, nv, fv), blue) # 23
# back & outside
# bottom & inside
# top & front
_axes_indices.extend([16,18,19, 16,19,17, 16,22,18, 16,20,22,
16,17,21, 16,21,20, 17,19,20, 17,20,21,
19,18,22, 19,22,23, 20,21,23, 20,23,22
])
# new_texcoord = new_tuple(
# self.vertex_format[
# self.TEXCOORD0_INDEX][VFORMAT_VECTOR_LEN_INDEX])
if IS_SELF_VFORMAT_OK:
self._axes_mesh = Mesh(
vertices=_axes_vertices,
indices=_axes_indices,
fmt=self.vertex_format,
mode='triangles',
texture=None,
)
else:
#error already shown
#print("[ KivyGlop ] ERROR in generate_axes:"
# " bad vertex_format")
pass
#return _axes_vertices, _axes_indices
#"Called by the repr() built-in function to compute the "official"
# string representation of an object. If at all possible, this
# should look like a valid Python expression that could be used to
# recreate an object..."
# <https://docs.python.org/3/reference/datamodel.html#customization>
def __repr__(self):
return ("KivyGlop(name=" + str(self.name) + ", location=" +
str(self._t_ins.xyz) + ")")
def copy(self, depth=0):
target = None
try:
if get_verbose_enable():
print("[ KivyGlop ] " + " " * depth + "copy is" +
" calling copy_as_subclass")
target = self.copy_as_subclass(self.new_glop_method,
depth=depth+1)
target.canvas = InstructionGroup()
target._pivot_point = self._pivot_point
target._pivot_scaled_point = self._pivot_scaled_point
target._r_ins_x = Rotate(self._r_ins_x.angle, 1, 0, 0)
# angle, x, y z
target._r_ins_x.origin = self._pivot_scaled_point
target._r_ins_y = Rotate(self._r_ins_y.angle, 0, 1, 0)
# angle, x, y z
target._r_ins_y.origin = self._pivot_scaled_point
target._r_ins_z = Rotate(self._r_ins_z.angle, 0, 0, 1)
# angle, x, y z
target._r_ins_z.origin = self._pivot_scaled_point
target._t_ins = Translate(self._t_ins.x,
self._t_ins.y, self._t_ins.z)
target._color_instruction = Color(self._color_instruction.r,
self._color_instruction.g,
self._color_instruction.b,
self._color_instruction.a)
except:
print("[ KivyGlop ] ERROR--could not finish copy:")
view_traceback()
return target
def rotate_camera_relative(self, angle, axis_index):
# TODO: delete this method and see solutions from
# http://stackoverflow.com/questions/10048018/opengl-camera-rotation
# such as set_view method of
# https://github.com/sgolodetz/hesperus2/blob/master/Shipwreck/MapEditor/GUI/Camera.java
self.rotate_relative_around_point(self.camera_glop, angle,
axis_index,
self.camera_glop._t_ins.x,
self.camera_glop._t_ins.y,
self.camera_glop._t_ins.z)
def rotate_player_relative(self, angle, axis_index):
# TODO: delete this method and see solutions from
# http://stackoverflow.com/questions/10048018/opengl-camera-rotation
# such as set_view method of
# https://github.com/sgolodetz/hesperus2/blob/master/Shipwreck/MapEditor/GUI/Camera.java
self.rotate_relative_around_point(self.player_glop, angle,
axis_index,
self.player_glop._t_ins.x,
self.player_glop._t_ins.y,
self.player_glop._t_ins.z)
def rotate_relative_around_point(self, this_glop, angle, axis_index,
around_x, around_y, around_z):
if axis_index == 0: #x
# += around_y * math.tan(angle)
this_glop._r_ins_x.angle += angle
# origin_distance = math.sqrt(around_z*around_z +
# around_y*around_y)
# this_glop._t_ins.z += origin_distance * math.cos(-1*angle)
# this_glop._t_ins.y += origin_distance * math.sin(-1*angle)
elif axis_index == 1: #y
this_glop._r_ins_y.angle += angle
# origin_distance = math.sqrt(around_x*around_x +
# around_z*around_z)
# this_glop._t_ins.x += origin_distance * math.cos(-1*angle)
# this_glop._t_ins.z += origin_distance * math.sin(-1*angle)
else: #z
# this_glop._t_ins.z += around_y * math.tan(angle)
this_glop._r_ins_z.angle += angle
# origin_distance = math.sqrt(around_x*around_x +
# around_y*around_y)
# this_glop._t_ins.x += origin_distance * math.cos(-1*angle)
# this_glop._t_ins.y += origin_distance * math.sin(-1*angle)
def new_glop_method(self, default_templates=None):
#return PyGlops.new_glop_method(self)
return KivyGlop(default_templates=default_templates)
def get_class_name(self):
return "KivyGlop"
def look_at(self, target_glop):
if target_glop is not None:
self.look_at_pos(target_glop._t_ins.xyz)
# pitch = 0.0
# pitch = get_angle_between_points(self._t_ins.y,
# self._t_ins.z,
# target_glop._t_ins.y,
# target_glop._t_ins.z)
# self._r_ins_x.angle = pitch
# yaw = get_angle_between_points(self._t_ins.x,
# self._t_ins.z,
# target_glop._t_ins.x,
# target_glop._t_ins.z)
# self._r_ins_y.angle = yaw
# print("look at pitch,yaw: " +
# str(int(math.degrees(pitch))) + "," +
# str(int(math.degrees(yaw))))
else:
global look_at_none_warning_enable
if look_at_none_warning_enable:
print("[ KivyGlop ] look_at got None for target_glop")
look_at_none_warning_enable = False
def look_at_pos(self, pos):
if pos is not None:
pitch = self._r_ins_x.angle
yaw = self._r_ins_y.angle
if len(pos) > 2:
pitch = get_angle_between_points(self._t_ins.y,
self._t_ins.z,
pos[1], pos[2])
yaw = get_angle_between_points(self._t_ins.x,
self._t_ins.z,
pos[0], pos[2])
else:
yaw = get_angle_between_points(self._t_ins.x,
self._t_ins.z,
pos[0], pos[1])
if get_verbose_enable():
print("[ KivyGlop ]"
" WARNING: look_at_pos got 2D coords")
self._r_ins_x.angle = pitch
self._r_ins_y.angle = yaw
# print("look at pitch,yaw: " +
# str(int(math.degrees(pitch))) + "," +
# str(int(math.degrees(yaw))))
else:
global look_at_none_warning_enable
if look_at_pos_none_warning_enable:
print(
"[ KivyGlop ] ERROR: look_at_pos got None for pos")
look_at_pos_none_warning_enable = False
def copy_as_mesh_instance(self, depth=0, ref_vertices_enable=True):
result = KivyGlop()
result.name = self.name
if ref_vertices_enable:
result.vertex_format = self.vertex_format
result.on_vertex_format_change()
result.vertices = self.vertices
result.indices = self.indices
else:
result.vertex_format = copy.deepcopy(self.vertex_format)
result.on_vertex_format_change()
result.properties['hit_radius'] = self.properties['hit_radius']
result.properties['hitbox'] = self.properties['hitbox']
context = result.get_context()
result._t_ins.x = self._t_ins.x
result._t_ins.y = self._t_ins.y
result._t_ins.z = self._t_ins.z
result._r_ins_x.angle = self._r_ins_x.angle
result._r_ins_y.angle = self._r_ins_y.angle
result._r_ins_z.angle = self._r_ins_z.angle
#result._s_ins.x = self._s_ins.x
#result._s_ins.y = self._s_ins.y
#result._s_ins.z = self._s_ins.z
#result._color_instruction.r = self._color_instruction.r
#result._color_instruction.g = self._color_instruction.g
#result._color_instruction.b = self._color_instruction.b
result._pushmatrix = PushMatrix()
result._updatenormalmatrix = UpdateNormalMatrix()
result._popmatrix = PopMatrix()
context.add(result._pushmatrix)
context.add(result._t_ins)
context.add(result._r_ins_x)
context.add(result._r_ins_y)
context.add(result._r_ins_z)
context.add(result._s_ins)
context.add(result._updatenormalmatrix)
#context.add(this_glop._color_instruction) # TODO: asdf uniform
# instead
if self._mesh is not None:
context.add(self._mesh)
else:
print("[ KivyGlop ] " + " " * depth + "WARNING in " +
"copy_as_mesh_instance: meshless glop '" +
str(self.name) + "'")
context.add(result._popmatrix)
return result
def calculate_hit_range(self):
# TODO: re-implement super method, changing hitbox taking
# rotation & scale into account
# NOTE: index is set by add_glop so None if done earlier:
glop_msg = "new glop"
if self.glop_index is not None:
glop_msg = str(self.glop_index)
if self.name is not None:
glop_msg += " '" + self.name + "'"
if get_verbose_enable():
print("[ KivyGlop ] calculate_hit_range (hitbox) for " +
glop_msg + "...")
if self.vertices is None:
self.properties['hitbox'] = None # avoid 0-size hitbox
# which would prevent bumps
if self.properties['hit_radius'] is None:
self.properties['hit_radius'] = new_flag_f()
print("[ KivyGlop ] hitbox skipped since vertices None.")
return None
vertex_count = int(len(self.vertices)/self.vertex_depth)
if vertex_count>0:
v_offset = 0
self.properties['hit_radius'] = 0.0
hb = self.properties.get('hitbox')
hr = self.properties.get('hit_radius')
PO = self._POSITION_OFFSET
if hb is None:
hb = new_hitbox()
self.properties['hitbox'] = hb
for i in range(0,3):
# intentionally set to rediculously far in opposite
# direction:
hb['minimums'][i] = sys.maxsize
hb['maximums'][i] = -sys.maxsize
for v_number in range(0, vertex_count):
for i in range(0,3):
if self.vertices[v_offset + PO + i] < \
hb['minimums'][i]:
hb['minimums'][i] = \
self.vertices[v_offset+PO+i]
if (self.vertices[v_offset +
PO+i]) > \
hb['maximums'][i]:
hb['maximums'][i] = \
self.vertices[v_offset+PO+i]
this_vertex_relative_distance = get_distance_vec3(
self.vertices[v_offset+PO:v_offset+PO+3],
self._pivot_point)
if this_vertex_relative_distance > hr:
hr = this_vertex_relative_distance
v_offset += self.vertex_depth
self.properties['hit_radius'] = hr
phi_eye_height = 86.5 * hb['maximums'][1]
if 'eye_height' not in self.properties:
self.properties['eye_height'] = phi_eye_height
if self.properties['eye_height'] > phi_eye_height:
print("[ KivyGlop ]" +
" WARNING in calculate_hit_range:" +
" eye_height " +
str(self.properties['eye_height']) +
" is beyond phi_eye_height" +
str(phi_eye_height) +
" so is being set to that value")
self.properties['eye_height'] = hb['maximums'][1]
print(" done calculate_hit_range")
else:
self.properties['hitbox'] = None # avoid 0-size hitbox
# which would prevent bumps
if self.properties.get('hit_radius') is None:
self.properties['hit_radius'] = new_flag_f()
print(" skipped (0 vertices).")
def rotate_x_relative(self, angle):
self._r_ins_x.angle += angle
def rotate_y_relative(self, angle):
self._r_ins_y.angle += angle
def rotate_z_relative(self, angle):
self._r_ins_z.angle += angle
def move_x_relative(self, distance):
self._t_ins.x += distance
def move_y_relative(self, distance):
self._t_ins.y += distance
def move_z_relative(self, distance):
self._t_ins.z += distance
def transform_pivot_to_geometry(self):
previous_point = self._pivot_point
super(KivyGlop, self).transform_pivot_to_geometry()
# self._change_instructions()
# self._on_change_pivot(previous_point)
# commenting this assumes this subclass' version
# of _on_change_pivot is already run by super
def _on_change_pivot(self, previous_point=(0.0,0.0,0.0)):
super(KivyGlop, self)._on_change_pivot(
previous_point=previous_point, class_name="KivyGlop")
print("[ KivyGlop ] (verbose message in _on_change_pivot)" +
" from " + str(previous_point))
self._on_change_s_ins() # does calculate_hit_range
def get_scale(self):
return (self._s_ins.x + self._s_ins.y + self._s_ins.z) / 3.0
def set_scale(self, overall_scale):
self._s_ins.x = overall_scale
self._s_ins.y = overall_scale
self._s_ins.z = overall_scale
self._on_change_s_ins() # does calculate_hit_range
def _on_change_s_ins(self):
if self._pivot_point is not None:
self._pivot_scaled_point = (
self._pivot_point[0] * self._s_ins.x + self._t_ins.x,
self._pivot_point[1] * self._s_ins.y + self._t_ins.y,
self._pivot_point[2] * self._s_ins.z + self._t_ins.z
)
# else:
# self._pivot_point = 0,0,0
# self._pivot_scaled_point = 0,0,0
# super(KivyGlop, self)._on_change_scale()
# if self._pivot_point is not None:
self._r_ins_x.origin = self._pivot_scaled_point
self._r_ins_y.origin = self._pivot_scaled_point
self._r_ins_z.origin = self._pivot_scaled_point
# self._t_ins.x = self.freePos[0] - \
# self._rectangle_instruction.size[0]*self._s_ins.x/2
# self._t_ins.y = self.freePos[1] - \
# self._rectangle_instruction.size[1]*self._s_ins.y/2
# self._rotate_instruction.origin = \
# (self._rectangle_instruction.size[0]*self._s_ins.x/2.0,
# self._rectangle_instruction.size[1]*self._s_ins.x/2.0)
# self._rotate_instruction.angle = self.freeAngle
this_name = ""
if self.name is not None:
this_name = self.name
#print()
#print("_on_change_s_ins for object named '"+this_name+"'")
#print ("_pivot_point:"+str(self._pivot_point))
#print ("_pivot_scaled_point:"+str(self._pivot_scaled_point))
#if self.properties['hitbox'] is not None:
#only should be recalculated if already
# (already bumper or bumpable list)
if self.get_has_hit_range():
self.calculate_hit_range()
def apply_translate(self):
vertex_count = int(len(self.vertices)/self.vertex_depth)
v_offset = 0
for v_number in range(0, vertex_count):
self.vertices[v_offset+self._POSITION_OFFSET+0] -= \
self._t_ins.x
self.vertices[v_offset+self._POSITION_OFFSET+1] -= \
self._t_ins.y
self.vertices[v_offset+self._POSITION_OFFSET+2] -= \
self._t_ins.z
self._pivot_point = (self._pivot_point[0] - self._t_ins.x,
self._pivot_point[1] - self._t_ins.y,
self._pivot_point[2] - self._t_ins.z)
self._t_ins.x = 0.0
self._t_ins.y = 0.0
self._t_ins.z = 0.0
v_offset += self.vertex_depth
self.apply_pivot()
if self.get_has_hit_range():
self.calculate_hit_range()
def set_texture_diffuse(self, path):
self.last_loaded_path = path
this_texture_image = None
if self.last_loaded_path is not None:
participle = "getting image filename"
try:
participle = "loading "+self.last_loaded_path
if os.path.isfile(self.last_loaded_path):
this_texture_image = Image(self.last_loaded_path)
else:
this_texture_image = Image(
resource_find(self.last_loaded_path))
print("[ KivyGlop ] Loaded texture '" +
str(self.last_loaded_path) + "'")
except:
print(
"[ KivyGlop ] ERROR--" +
"could not finish loading texture: " +
str(self.last_loaded_path)
)
view_traceback()
else:
if get_verbose_enable():
Logger.debug("[ KivyGlop ] Warning: no texture " +
"specified for glop named '" + str(self.name) + "'")
this_material_name = ""
if self.material is not None:
try_name = self.material.get('name')
if try_name is not None:
this_material_name = try_name
Logger.debug("[ KivyGlop ] (material named '" +
this_material_name + "')")
else:
Logger.debug(
"[ KivyGlop ] (material with no name)")
else:
Logger.debug("[ KivyGlop ] (no material)")
if self._mesh is not None and this_texture_image is not None:
self._mesh.texture = this_texture_image.texture
context = self.get_context()
self.set_uniform("texture0_enable", True)
return this_texture_image