/
vpython.py
4093 lines (3613 loc) · 136 KB
/
vpython.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
# Cythonize the encode machinery?
import colorsys
from .rate_control import rate
import platform
from math import sqrt, tan, pi
import time
try:
clock = time.perf_counter # time.clock is deprecated in Python 3.3, gone in 3.8
except:
clock = time.clock
import sys
from . import __version__, __gs_version__
from ._notebook_helpers import _isnotebook
from ._vector_import_helper import (vector, mag, norm, dot, adjust_up,
adjust_axis, object_rotate)
# List of names that will be imported from this file with import *
__all__ = ['Camera', 'GlowWidget', 'version', 'GSversion', 'Mouse', 'arrow', 'attach_arrow',
'attach_trail', 'baseObj', 'box', 'bumpmaps', 'button',
'canvas', 'checkbox', 'clock', 'color', 'combin', 'compound', 'cone', 'controls',
'curve', 'curveMethods', 'cylinder', 'distant_light', 'ellipsoid',
'event_return', 'extrusion', 'faces', 'frame', 'gcurve', 'gdots',
'ghbars', 'gobj', 'graph', 'gvbars', 'helix', 'label',
'local_light', 'menu', 'meta_canvas', 'points', 'pyramid',
'quad', 'radio', 'ring', 'simple_sphere', 'sleep', 'slider', 'sphere',
'standardAttributes', 'text', 'textures', 'triangle', 'vertex',
'wtext', 'winput']
__p = platform.python_version()
_ispython3 = (__p[0] == '3')
if _ispython3:
from inspect import signature # Python 3; needed to allow zero arguments in a bound function
else:
from inspect import getargspec # Python 2; needed to allow zero arguments in a bound function
# __version__ is the version number of the Jupyter VPython installer, generated in building the installer.
version = [__version__, 'jupyter']
GSversion = [__gs_version__, 'glowscript']
# To print immediately, do this:
# print(.....)
# sys.stdout.flush()
##def eprint(*args, **kwargs): # this may output when ordinary print won't
## print(*args, file=sys.stderr, **kwargs)
##
##def jprint(s): # prints to terminal, for debugging purposes
## os.write(1, json.dumps(s, separators=(',', ':')).encode('utf_8')+ b'\n')
# scalar attribute: { <'a' or 'b'>: string }
# string is str(idx)+attrs[<attributename>]+str(attributevalue)
# for example: {'a':'23K1.72'} thickness of object 23 is 1.72
# vector attrribute:
# string is str(idx)+ attrs[<attributename>]+str(val.x)+','+str(val.y)+','+str(val.z)
# for example: {'a':'37f23.54678,32.12345,-65.00123'} axis of object 37
# text attribute:
# string is str(value)
# boolean values are integers (0,1)
# method: {'m': str(idx)+methods[<methodname>]+<value(s) as above>}
# attrs are X in {'a': '23X....'}
__attrs = {'pos':'a', 'up':'b', 'color':'c', 'trail_color':'d', # don't use single and double quotes; available: comma, but maybe that would cause trouble
'ambient':'e', 'axis':'f', 'size':'g', 'origin':'h',
'direction':'j', 'linecolor':'k', 'bumpaxis':'l', 'dot_color':'m',
'foreground':'n', 'background':'o', 'ray':'p', 'center':'E', 'forward':'#', 'resizable':'+',
# scalar attributes
'graph':'q', 'canvas':'r', 'trail_radius':'s',
'visible':'t', 'opacity':'u','shininess':'v', 'emissive':'w',
'make_trail':'x', 'trail_type':'y', 'interval':'z', 'pps':'A', 'retain':'B',
'red':'C', 'green':'D', 'blue':'F','length':'G', 'width':'H', 'height':'I', 'radius':'J',
'thickness':'K', 'shaftwidth':'L', 'headwidth':'M', 'headlength':'N', 'pickable':'O',
'coils':'P', 'xoffset':'Q', 'yoffset':'R',
'border':'S', 'line':'T', 'box':'U', 'space':'V', 'linewidth':'W',
'xmin':'X', 'xmax':'Y', 'ymin':'Z', 'ymax':'`',
'ctrl':'~', 'shift':'!', 'alt':'@',
# text attributes:
'text':'$', 'align':'%', 'caption':'^',
'fast':'-', 'title':'&', 'xtitle':'*', 'ytitle':'(',
# Miscellany:
'lights':')', 'objects':'_', 'bind':'=',
'pixel_pos':'[', 'texpos':']',
'v0':'{', 'v1':'}', 'v2':';', 'v3':':', 'vs':'<', 'type':'>',
'font':'?', 'texture':'/'}
# attrsb are X in {'b': '23X....'}; ran out of easily typable one-character codes
__attrsb = {'userzoom':'a', 'userspin':'b', 'range':'c', 'autoscale':'d', 'fov':'e',
'normal':'f', 'data':'g', 'checked':'h', 'disabled':'i', 'selected':'j',
'vertical':'k', 'min':'l', 'max':'m', 'step':'n', 'value':'o', 'left':'p',
'right':'q', 'top':'r', 'bottom':'s', '_cloneid':'t',
'logx':'u', 'logy':'v', 'dot':'w', 'dot_radius':'x',
'markers':'y', 'legend':'z', 'label':'A', 'delta':'B', 'marker_color':'C',
'size_units':'D', 'userpan':'E'}
# methods are X in {'m': '23X....'}
# pos is normally updated as an attribute, but for interval-based trails, it is updated (multiply) as a method
__methods = {'select':'a', 'pos':'b', 'start':'c', 'stop':'d', 'clear':'f', # unused eghijklmnopvxyzCDFAB
'plot':'q', 'add_to_trail':'s',
'follow':'t', '_attach_arrow':'u', 'clear_trail':'w',
'bind':'G', 'unbind':'H', 'waitfor':'I', 'pause':'J', 'pick':'K', 'GSprint':'L',
'delete':'M', 'capture':'N'}
__vecattrs = ['pos', 'up', 'color', 'trail_color', 'axis', 'size', 'origin', '_attach_arrow',
'direction', 'linecolor', 'bumpaxis', 'dot_color', 'ambient', 'add_to_trail',
'foreground', 'background', 'ray', 'ambient', 'center', 'forward', 'normal',
'marker_color']
__textattrs = ['text', 'align', 'caption', 'title', 'xtitle', 'ytitle', 'selected', 'label', 'capture',
'append_to_caption', 'append_to_title', 'bind', 'unbind', 'pause', 'GSprint']
def _encode_attr2(sendval, val, ismethods):
s = ''
if sendval in __vecattrs: # it would be good to do some kind of compression of doubles
s += "{:.16G},{:.16G},{:.16G}".format(val[0], val[1], val[2])
elif sendval in __textattrs:
# '\n' doesn't survive JSON transmission, so we replace '\n' with '<br>' (and convert back in glowcomm)
if not isinstance(val, str): val = print_to_string(val)
val = val.replace('\n', '<br>')
s += val
elif sendval == 'rotate':
for p in val:
s += "{:.16G},".format(p)
s = s[:-1]
elif sendval == 'plot' or sendval == 'data':
for p in val:
s += "{:.16G},{:.16G},".format(p[0], p[1])
s = s[:-1]
elif sendval in ['v0', 'v1', 'v2', 'v3']: # val is the vertex object referenced by triangle or quad
s += str(val.idx)
elif sendval == 'vs':
if len(val) == 3:
s += "{d},{d},{d}".format(val[0].idx, val[1].idx, val[2].idx)
else:
s += "{d},{d},{d},{d}".format(val[0].idx, val[1].idx, val[2].idx, val[3].idx)
elif ismethods:
#if sendval in ['follow', 'waitfor', 'delete']: val = str(val) # scene.camera.follow(object idx)
s += str(val)
else:
s += "{:.16G}".format(val)
return s
def _encode_attr(D, ismethods): # ismethods is True if a list of method operations
# If ismethods is True, D is [ [idx, method, data], [idx, method, data], etc. ]
# If ismethods is False: D is {idx:{'pos':vec, etc.}, idx:{'pos':vec, etc.}, etc.}
# For 'attrs', convert {'opacity': 0.5, 'idx': 3} to 'a(idx)X(value)' or 'b(idx)X(value)'
# where (idx) is a number, X is the attribute code in attrs, (value) is a number or x,y,z or a string
# For a method, we have {idx, method, value} to be converted to 'm(idx)X(value)'
out = []
if ismethods: # methods; a list
for d in D:
s = 'm'+str(d[0])+__methods[d[1]]
s += _encode_attr2(d[1], d[2], True)
out.append(s)
else: # attributes, a dictionary
for idx,d in D.items():
for sendval,val in d.items():
if sendval in __attrs:
s = 'a'+str(idx)+__attrs[sendval]
else:
s = 'b'+str(idx)+__attrsb[sendval]
s += _encode_attr2(sendval, val, False)
out.append(s)
return out
if sys.version > '3':
long = int
def list_to_vec(L):
return vector(L[0], L[1], L[2])
class baseObj(object):
glow = None
objCnt = 0
sent = True # set to True by a render in the non-notebook case
_view_constructed = False
_canvas_constructing = False
# 'cmds': list of constructors,
# 'attrs': {idx:{'pos':vec, etc.}, idx:{'pos':vec, etc.}, etc.},
# 'methods': [ [idx, method, date], [idx, method, date], etc. ]
updates = {'cmds':[], 'methods':[], 'attrs':{}}
object_registry = {} ## idx -> instance
attach_arrows = []
attach_trails = [] ## needed only for functions
attrs = set() # each element is (idx, attr name)
@classmethod
def initialize(cls):
cls.updates = {'cmds':[], 'methods':[], 'attrs':{}}
cls.attrs = set()
@classmethod
def empty(cls):
b = cls.updates
return b['cmds'] == [] and b['methods'] == [] and len(cls.attrs) == 0
@classmethod
def handle_attach(cls): # called when about to send data to the browser
## update every attach_arrow if relevant vector has changed
for aa in cls.attach_arrows:
obj = baseObj.object_registry[aa._obj]
vval = getattr(obj, aa.attr) # could be 'velocity', for example
if not isinstance(vval, vector):
raise AttributeError("attach_arrow value must be a vector.")
if (isinstance(aa._last_val, vector) and aa._last_val.equals(vval)):
continue
aa.addmethod('_attach_arrow', vval.value)
aa._last_val = vector(vval) # keep copy of last vector
## update every attach_trail that depends on a function
for aa in cls.attach_trails:
if aa._obj == '_func':
fval = aa._func()
if not isinstance(fval, vector):
raise AttributeError('attach_trail value must be a vector')
aa.addmethod('add_to_trail', fval.value)
else:
fval = cls.object_registry[aa._obj].pos
if ( isinstance(aa._last_val, vector) and aa._last_val.equals(fval) ):
continue
aa._last_val = fval
def __init__(self, **kwargs):
if not (baseObj._view_constructed or
baseObj._canvas_constructing):
if _isnotebook:
from .with_notebook import _
else:
from .no_notebook import _
baseObj._view_constructed = True
self.idx = baseObj.objCnt ## an integer
self.object_registry[self.idx] = self
if kwargs is not None:
for key, value in kwargs.items():
object.__setattr__(self, key, value)
baseObj.incrObjCnt()
def delete(self):
# Currently delete decrements the object count but doesn't
# delete any objects in the browser....so, let's not decrement
# the count for now.
# baseObj.decrObjCnt()
# The body of this and __del__ are the same other than the
# decrement here, so let's just call __del__.
self.__del__()
def appendcmd(self,cmd):
# The following code makes sure that constructors are sent to the front end first.
cmd['idx'] = self.idx
while not baseObj.sent: # baseObj.sent is always True in the notebook case
time.sleep(0.001)
baseObj.updates['cmds'].append(cmd) # this is an "atomic" (uninterruptable) operation
def addmethod(self, method, data):
while not baseObj.sent: # baseObj.sent is always True in the notebook case
time.sleep(0.001)
baseObj.updates['methods'].append((self.idx, method, data)) # this is an "atomic" (uninterruptable) operation
def addattr(self, attr):
while not baseObj.sent: # baseObj.sent is always True in the notebook case
time.sleep(0.001)
baseObj.attrs.add((self.idx, attr)) # this is an "atomic" (uninterruptable) operation
@classmethod
def package(cls, objdata): # package up the data to send to the browser
ret = {}
m = None
if objdata['cmds'] != []: ret['cmds'] = objdata['cmds']
if objdata['methods'] != []:
m = _encode_attr(objdata['methods'], True)
if objdata['attrs'] != {}:
ret['attrs'] = _encode_attr(objdata['attrs'], False)
if m is not None: ret['attrs'] += m
elif m is not None:
ret['attrs'] = m
return ret
@classmethod
def trigger(cls): # isnotebook; called by a canvas update event from browser, coming from GlowWidget.handle_msg
if cls.empty():
objdata = 'trigger' # handshake with browser
else:
cls.handle_attach()
for a in baseObj.attrs:
idx, attr = a
val = getattr(baseObj.object_registry[idx], attr)
if type(val) is vector: val = [val.x, val.y, val.z]
if idx in baseObj.updates['attrs']:
baseObj.updates['attrs'][idx][attr] = val
else:
baseObj.updates['attrs'][idx] = {attr:val}
objdata = cls.package(baseObj.updates)
sender(objdata)
cls.initialize()
baseObj.sent = True
@classmethod
def incrObjCnt(cls):
cls.objCnt += 1
@classmethod
def decrObjCnt(cls):
cls.objCnt -= 1
def __del__(self):
cmd = {"cmd": "delete", "idx": self.idx}
if (baseObj.glow is not None and sender is not None):
sender([cmd])
else:
self.appendcmd(cmd)
# Jupyter does not immediately transmit data to the browser from a thread,
# which made for an awkward thread in early versions of Jupyter VPython, and
# even caused display mistakes due to losing portions of data sent to the browser
# from within a thread.
# Now there is no threading in Jupyter VPython. Data is sent to the
# browser from the trigger() function, which is called by a
# canvas_update event sent to Python from the browser (glowcomm.js), currently
# every 33 milliseconds. When trigger() is called, it immediately signals
# the browser to set a timeout of 33 ms to send another signal to Python.
# Note that a typical VPython program starts out by creating objects (constructors) and
# specifying their attributes. The 33 ms signal from the browser is adequate to ensure
# prompt data transmissions to the browser.
# The situation with non-notebook use is similar, but the http server is threaded,
# in order to serve glowcomm.html, jpg texture files, and font files, and the
# websocket is also threaded.
# In both the notebook and non-notebook cases output is buffered in baseObj.updates
# and sent as a block to the browser at render times.
class GlowWidget(object):
def __init__(self, wsport=None, wsuri=None):
global sender
baseObj.glow = self
if _isnotebook:
from ipykernel.comm import Comm
if (wsport):
self.comm = Comm(target_name='glow', data={'wsport':wsport, 'wsuri':wsuri})
else:
self.comm = Comm(target_name='glow')
self.comm.on_close(self.handle_close)
self.comm.on_msg(self.handle_msg)
sender = self.comm.send
self.show = True
else:
sender = None
## baseObj.object_registry = {}
## idx -> instance
def handle_msg(self, msg):
events = msg['content']['data'] # this is a list of time-ordered events
for evt in events:
if 'widget' in evt:
obj = baseObj.object_registry[evt['idx']]
if evt['widget'] == 'button':
pass
elif evt['widget'] == 'slider':
obj._value = evt['value']
elif evt['widget'] == 'menu':
obj._selected = obj._choices[evt['value']]
elif evt['widget'] == 'checkbox':
obj._checked = evt['value']
elif evt['widget'] == 'radio':
obj._checked = evt['value']
elif evt['widget'] == 'winput':
obj._text = evt['text']
obj._number = evt['value']
# inspect the bound function and see what it's expecting
if _ispython3: # Python 3
a = signature(obj._bind)
if str(a) != '()': obj._bind( obj )
else: obj._bind()
else: # Python 2
a = getargspec(obj._bind)
if len(a.args) > 0: obj._bind( obj )
else: obj._bind()
else: ## a canvas event
if 'trigger' not in evt:
cvs = baseObj.object_registry[evt['canvas']]
cvs.handle_event(evt)
if _isnotebook:
baseObj.trigger()
def handle_close(self, data):
print ("comm closed")
def _wait(cvs): # wait for an event
cvs._waitfor = None
if _isnotebook: baseObj.trigger() # in notebook environment must send methods immediately
while cvs._waitfor is None:
rate(30)
return cvs._waitfor
class color(object):
black = vector(0,0,0)
white = vector(1,1,1)
red = vector(1,0,0)
green = vector(0,1,0)
blue = vector(0,0,1)
yellow = vector(1,1,0)
cyan = vector(0,1,1)
magenta = vector(1,0,1)
orange = vector(1,0.6,0)
purple = vector(0.4,0.2,0.6)
@classmethod
def gray(cls,luminance):
return vector(luminance,luminance,luminance)
@classmethod
def rgb_to_hsv(cls,v):
T = [v.x, v.y, v.z]
c = colorsys.rgb_to_hsv(*T)
return list_to_vec(c)
@classmethod
def hsv_to_rgb(cls,v):
T = [v.x, v.y, v.z]
c = colorsys.hsv_to_rgb(*T)
return list_to_vec(c)
@classmethod
def rgb_to_grayscale(cls,v):
luminance = 0.21*v.x + 0.71*v.y + 0.07*v.z
return vector(luminance, luminance, luminance)
class textures(object):
flower = ":flower_texture.jpg"
granite=":granite_texture.jpg"
gravel=":gravel_texture.jpg"
earth=":earth_texture.jpg"
metal=":metal_texture.jpg"
rock=":rock_texture.jpg"
rough=":rough_texture.jpg"
rug=":rug_texture.jpg"
stones=":stones_texture.jpg"
stucco=":stucco_texture.jpg"
wood=":wood_texture.jpg"
wood_old=":wood_old_texture.jpg"
class bumpmaps(object):
gravel=":gravel_bumpmap.jpg"
rock=":rock_bumpmap.jpg"
stones=":stones_bumpmap.jpg"
stucco=":stucco_bumpmap.jpg"
wood_old=":wood_old_bumpmap.jpg"
class standardAttributes(baseObj):
# vector-no-interactions, vector-interactions, scalar-no-interactions, scalar-interactions
attrLists = {'box':[['pos', 'color', 'trail_color'],
['axis', 'size', 'up'],
['visible', 'opacity','shininess', 'emissive',
'make_trail', 'trail_type', 'interval',
'retain', 'trail_color', 'trail_radius', 'texture', 'pickable'],
['red', 'green', 'blue','length', 'width', 'height']],
'sphere':[['pos', 'color', 'trail_color'],
['axis', 'size', 'up'],
['visible', 'opacity','shininess', 'emissive',
'make_trail', 'trail_type', 'interval',
'retain', 'trail_color', 'trail_radius', 'texture', 'pickable'],
['red', 'green', 'blue','length', 'width', 'height', 'radius']],
'simple_sphere':[['pos', 'color', 'trail_color'],
['axis', 'size', 'up'],
['visible', 'opacity','shininess', 'emissive',
'make_trail', 'trail_type', 'interval',
'retain', 'trail_color', 'trail_radius', 'texture', 'pickable'],
['red', 'green', 'blue','length', 'width', 'height', 'radius']],
'arrow':[['pos', 'color', 'trail_color'],
['axis', 'size', 'up'],
['visible', 'opacity',
'shininess', 'emissive', 'texture', 'frame', 'material',
'make_trail', 'trail_type', 'interval',
'retain', 'trail_color', 'trail_radius', 'texture',
'shaftwidth', 'headwidth', 'headlength', 'pickable'],
['red', 'green', 'blue','length', 'width', 'height']],
'ring':[['pos', 'color', 'trail_color', 'size'],
['axis', 'up'],
['visible', 'opacity','shininess', 'emissive',
'make_trail', 'trail_type', 'interval',
'retain', 'trail_color', 'trail_radius', 'texture', 'pickable'],
['red', 'green', 'blue','length', 'width', 'height', 'thickness']],
'helix':[['pos', 'color', 'trail_color'],
['axis', 'size', 'up'],
['visible', 'opacity','shininess', 'emissive',
'make_trail', 'trail_type', 'interval',
'retain', 'trail_color', 'trail_radius', 'coils', 'thickness', 'pickable'],
['red', 'green', 'blue','length', 'width', 'height']],
'curve':[['origin', 'color'],
['axis', 'size', 'up'],
['visible', 'shininess', 'emissive', 'radius', 'retain', 'pickable'],
['red', 'green', 'blue','length', 'width', 'height']],
'points':[['color'],
[],
['visible', 'shininess', 'emissive', 'radius', 'retain', 'pickable', 'size_units'],
['red', 'green', 'blue']],
'label':[['pos', 'color', 'background', 'linecolor'],
[],
['visible', 'xoffset', 'yoffset', 'font', 'height', 'opacity',
'border', 'line', 'box', 'space', 'align', 'linewidth', 'pixel_pos'],
['text']],
'local_light':[['pos', 'color'],
[],
['visible'],
[]],
'distant_light':[['direction', 'color'],
[],
['visible'],
[]],
'compound':[['pos', 'color', 'trail_color'],
['axis', 'size', 'up'],
['visible', 'opacity','shininess', 'emissive',
'make_trail', 'trail_type', 'interval', 'texture',
'retain', 'trail_color', 'trail_radius', 'obj_idxs', 'pickable'],
['red', 'green', 'blue', 'length', 'width', 'height']],
'vertex':[['pos', 'color', 'normal', 'bumpaxis', 'texpos'],
[],
['visible', 'opacity','shininess', 'emissive'],
['red', 'green', 'blue']],
'triangle': [ [],
[],
['texture', 'bumpmap', 'visible', 'pickable'],
['v0', 'v1', 'v2'] ],
'quad': [ [],
[],
['texture', 'bumpmap', 'visible', 'pickable'],
['v0', 'v1', 'v2', 'v3'] ],
'attach_arrow': [ [ 'color', 'attrval'],
[],
['shaftwidth', 'scale', 'obj', 'attr'],
[] ],
'attach_trail': [ ['color'],
[],
['radius', 'pps', 'retain', 'type', '_obj'],
[] ],
'wtext': [[],
[],
['location', 'text'],
[]],
'extrusion':[ ['pos', 'color', 'start_face_color', 'end_face_color'],
[ 'axis', 'size', 'up' ],
['path', 'shape', 'visible', 'opacity','shininess', 'emissive',
'show_start_face', 'show_end_face',
'make_trail', 'trail_type', 'interval', 'show_start_face', 'show_end_face',
'retain', 'trail_color', 'trail_radius', 'texture', 'pickable' ],
['red', 'green', 'blue','length', 'width', 'height'] ],
'text': [ ['pos', 'up', 'color', 'start_face_color', 'end_face_color', 'axis'],
[],
['visible', 'opacity','shininess', 'emissive',
'make_trail', 'trail_type', 'interval',
'retain', 'trail_color', 'trail_radius', 'obj_idxs', 'pickable',
'align', 'text', 'font', 'billboard', 'show_start_face', 'show_end_face', 'descender',
'vertical_spacing', 'depth', 'length', 'width', 'height'],
['red', 'green', 'blue'] ]
}
attrLists['pyramid'] = attrLists['box']
attrLists['cylinder'] = attrLists['sphere']
attrLists['cone'] = attrLists['sphere']
attrLists['ellipsoid'] = attrLists['sphere']
def setup(self, args):
super(standardAttributes, self).__init__()
self._constructing = True ## calls to setters are from constructor
objName = self._objName = args['_objName'] ## identifies object type
if objName[:8] == 'compound': objName = 'compound'
del args['_objName']
# default values
self._pos = vector(0,0,0)
self._axis = vector(1,0,0)
self._up = vector(0,1,0)
self._color = vector(1,1,1)
defaultSize = args['_default_size']
if defaultSize is not None: # is not points or vertex or triangle or quad
self._size = defaultSize ## because VP differs from JS
del args['_default_size']
self._texture = None
self._opacity = 1.0
self._shininess = 0.6
self._emissive = False
self._make_trail = False
self._trail_type = 'curve'
self._trail_color = self._color
self._interval = 0 # means no interval set
self._retain = -1
self._trail_radius = None # set by default after size set
self._canvas = None
if 'canvas' in args: ## converted to idx below
self._canvas = args['canvas']
self._visible = True
self._frame = None
self._size_units = 'pixels'
self._texture = None
self._pickable = True
self._save_oldaxis = None # used in linking axis and up
self._save_oldup = None # used in linking axis and up
_special_clone = None
if '_cloneid' in args: # text, extrusion, or compound is being cloned
_special_clone = args['_cloneid']
del args['_cloneid']
argsToSend = [] ## send to GlowScript only attributes specified in constructor
## override defaults for vector attributes without side effects
attrs = standardAttributes.attrLists[objName][0]
for a in attrs:
if a in args:
argsToSend.append(a)
val = args[a]
if isinstance(val, vector): setattr(self, '_'+a, vector(val)) ## '_' bypasses setters; copy of val
else: raise AttributeError(a+' must be a vector')
del args[a]
vectorInteractions = [ ('size','axis'), ('axis','size'), ('axis','up'), ('up','axis')]
# override defaults for vector attributes with side effects
# For consistency with GlowScript, axis is listed before up in the attrLists,
# so that setting axis may affect up, but then setting up can affect axis afterwards.
attrs = standardAttributes.attrLists[objName][1]
for a in attrs:
if a in args:
val = args[a]
if isinstance(val, vector):
setattr(self, a, vector(val)) ## use setter to take care of side effects; copy of val
if a not in argsToSend:
argsToSend.append(a)
for vi in vectorInteractions:
if vi[0] == a:
if vi[1] not in argsToSend:
argsToSend.append(vi[1])
elif objName == 'points' and a == 'size': ## in this case size is a scalar
argsToSend.append(a)
else: raise AttributeError(a+' must be a vector')
del args[a]
if defaultSize is not None:
## If not 3D text, always send size because Python size differs from JS size
if 'size' not in argsToSend and objName != 'text':
argsToSend.append('size')
self._trail_radius = 0.1 * self._size.y ## default depends on size
elif objName == 'points':
self._trail_radius = self._radius # points object
# override defaults for scalar attributes without side effects
attrs = standardAttributes.attrLists[objName][2]
for a in attrs:
if a in args:
argsToSend.append(a)
setattr(self, '_'+a, args[a]) ## by-pass setters
del args[a]
scalarInteractions={'red':'color', 'green':'color', 'blue':'color', 'radius':'size', 'thickness':'size',
'length':'size', 'height':'size', 'width':'size', 'v0':'v0', 'v1':'v1',
'v2':'v2', 'v3':'v3', 'text':'text'}
# override defaults for scalar attributes with side effects
attrs = standardAttributes.attrLists[objName][3]
for a in attrs:
if a in args:
setattr(self, a, args[a]) ## use setter to take care of side effects
if scalarInteractions[a] not in argsToSend:
argsToSend.append(scalarInteractions[a]) # e.g. if a is radius, send size
del args[a]
# set values of user-defined attributes
for key, value in args.items(): # Assign all other properties
setattr(self, key, value)
cmd = {"cmd": objName, "idx": self.idx}
# now put all args to send into cmd
nosize = ['compound', 'extrusion', 'text'] # size will be computed by the constuctor
for a in argsToSend:
aval = getattr(self,a)
if isinstance(aval, vector):
aval = aval.value
elif isinstance(aval, vertex):
aval = aval.idx
if objName in nosize and a == 'size': continue # do not send superfluous size
#cmd["attrs"].append({"attr":a, "value": aval})
cmd[a] = aval
# set canvas
if self.canvas == None: ## not specified in constructor
self.canvas = canvas.get_selected()
#cmd["attrs"].append({"attr": 'canvas', "value": self.canvas.idx})
cmd['canvas'] = self.canvas.idx
# Lights are listed in canvas.lights, not canvas.objects
if not (objName == 'distant_light' or objName == 'local_light'):
self.canvas.objz(self,'add')
self._constructing = False ## from now on any setter call will not be from constructor
# _special_clone is True if text, extrusion, or compound objects
if _special_clone is not None: cmd["_cloneid"] = _special_clone
self.appendcmd(cmd)
# if ('frame' in args and args['frame'] != None):
# frame.objects.append(self)
# frame.update_obj_list()
# attribute vectors have these methods which call self.addattr()
# The vector class calls a change function when there's a change in x, y, or z.
noSize = ['points', 'label', 'vertex', 'triangle', 'quad', 'attach_arrow', 'attach_trail']
self._color.on_change = self._on_color_change
if objName not in noSize:
self._axis.on_change = self._on_axis_change
self._size.on_change = self._on_size_change
self._up.on_change = self._on_up_change
noPos = ['curve', 'points', 'triangle', 'quad', 'attach_arrow']
if objName not in noPos:
self._pos.on_change = self._on_pos_change
elif objName == 'curve':
self._origin.on_change = self._on_origin_change
if objName == 'vertex':
self._bumpaxis.on_change = self._on_bumpaxis_change
self._normal.on_change = self._on_normal_change
# Ensure that if axis or up is <0,0,0> in constructor, we'll recover eventually:
if self._axis.mag2 == 0: self._save_oldaxis = vector(1,0,0)
if self._up.mag2 == 0: self._save_oldup = vector(0,1,0)
@property
def pos(self):
return self._pos
@pos.setter
def pos(self,value):
self._pos.value = value
if not self._constructing:
if self._make_trail and self._interval > 0:
self.addmethod('pos', value.value)
else:
self.addattr('pos')
@property
def up(self):
return self._up
@up.setter
def up(self,value):
self._save_oldup = adjust_axis(self._up, value, self._axis, self._save_oldup) # this sets self._axis and self._up
if not self._constructing:
# must update both axis and up when either is changed
self.addattr('axis')
self.addattr('up')
@property
def axis(self):
return self._axis
@axis.setter
def axis(self,value):
self._save_oldaxis = adjust_up(self._axis, value, self._up, self._save_oldaxis) # this sets self._axis and self._up
if not self._constructing:
# must update both axis and up when either is changed
self.addattr('axis')
self.addattr('up')
m = value.mag
if abs(self._size._x - m) > 0.0001*self._size._x: # need not update size if very small change
self._size._x = m
if not self._constructing:
self.addattr('size')
@property
def size(self):
return self._size
@size.setter
def size(self,value):
self._size.value = value
if not self._constructing:
self.addattr('size')
a = self._axis.norm() * value.x
if mag(self._axis) == 0:
a = vector(value.x,0,0)
v = self._axis
if not v.equals(a):
self._axis.value = a
if not self._constructing:
self.addattr('axis')
@property
def length(self):
return self._size.x
@length.setter
def length(self,value):
self._axis = self._axis.norm() * value
self._size._x = value
if not self._constructing:
self.addattr('axis')
self.addattr('size')
@property
def height(self):
return self._size.y
@height.setter
def height(self,value):
self._size._y = value
if not self._constructing:
self.addattr('size')
@property
def width(self):
return self._size.z
@width.setter
def width(self,value):
self._size._z = value
if not self._constructing:
self.addattr('size')
@property
def color(self):
return self._color
@color.setter
def color(self,value):
self._color.value = value
if not self._constructing:
self.addattr('color')
@property
def red(self):
return self._color.x
@red.setter
def red(self,value):
self._color = (value,self.green,self.blue)
if not self._constructing:
self.addattr('color')
@property
def green(self):
return self._color.y
@green.setter
def green(self,value):
self._color = (self.red,value,self.blue)
if not self._constructing:
self.addattr('color')
@property
def blue(self):
return self._color.z
@blue.setter
def blue(self,value):
self._color = (self.red,self.green,value)
if not self._constructing:
self.addattr('color')
@property
def visible(self):
return self._visible
@visible.setter
def visible(self,value):
self._visible = value
if not self._constructing:
self.addattr('visible')
@property
def pickable(self):
return self._pickable
@pickable.setter
def pickable(self,value):
self._pickable = value
if not self._constructing:
self.addattr('pickable')
@property
def canvas(self):
return self._canvas
@canvas.setter
def canvas(self,value):
self._canvas = value
if not self._constructing:
raise AttributeError('canvas cannot be modified')
@property
def opacity(self):
return self._opacity
@opacity.setter
def opacity(self,value):
self._opacity = value
if not self._constructing:
self.addattr('opacity')
@property
def emissive(self):
return self._emissive
@emissive.setter
def emissive(self,value):
self._emissive = value
if not self._constructing:
self.addattr('emissive')
@property
def texture(self):
return self._texture
@texture.setter
def texture(self,value):
self._texture = value
if not self._constructing:
self.appendcmd({"texture":value})
@property
def shininess(self):
return self._shininess
@shininess.setter
def shininess(self,value):
self._shininess = value
if not self._constructing:
self.addattr('shininess')
@property
def make_trail(self):
return self._make_trail
@make_trail.setter
def make_trail(self,value):
self._make_trail = value
if not self._constructing:
self.addattr('make_trail')
@property
def trail_type(self):
return self._trail_type
@trail_type.setter
def trail_type(self,value):
if (value not in ['curve', 'points']):
raise Exception("ArgumentError: trail_type must be 'curve' or 'points'")
self._trail_type = value
if not self._constructing:
self.addattr('trail_type')
@property
def trail_color(self):
return self._trail_color
@trail_color.setter
def trail_color(self, value):
if isinstance(value, vector):
self._trail_color.value = value
else:
raise TypeError('trail_color must be a vector')
if not self._constructing:
self.addattr('trail_color')
@property
def interval(self):
return self._interval
@interval.setter
def interval(self,value):
self._interval = value
if not self._constructing:
self.addattr('interval')
@property
def retain(self):
return self._retain
@retain.setter
def retain(self,value):
self._retain = value
if not self._constructing:
self.addattr('retain')
@property
def trail_radius(self):
return self._trail_radius
@trail_radius.setter
def trail_radius(self,value):
self._trail_radius = value
if not self._constructing:
self.addattr('trail_radius')
@property
def pps(self):
return self._pps
@pps.setter
def pps(self, value):
self._pps = value
if not self._constructing:
self.addattr('pps')
@property
def frame(self):
return self._frame
@frame.setter
def frame(self,value):
self._frame = value
def rotate(self, angle=None, axis=None, origin=None):
saveorigin = origin
if angle == 0: