-
Notifications
You must be signed in to change notification settings - Fork 1
/
glslgen.py
1111 lines (861 loc) · 31.4 KB
/
glslgen.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
# GLSL Generator
import binascii, collections, inspect, os, re, sys
from pyosl.ast import Node
variables = {}
functions = {}
STDLIB_FUNCTIONS = {
'radians': ('type', 'type'),
'degrees': ('type', 'type'),
'cos': ('type', 'type'),
'sin': ('type', 'type'),
'tan': ('type', 'type'),
'sincos': ('type', '', 'type'),
'acos': ('type', 'type'),
'asin': ('type', 'type'),
'atan': ('type', 'type'),
'atan2': ('type', 'type', 'type'),
'cosh': ('type', 'type'),
'sinh': ('type', 'type'),
'tanh': ('type', 'type'),
'pow': ('type', 'type', 'type'),
'exp': ('type', 'type'),
'exp2': ('type', 'type'),
'expm1': ('type', 'type'),
'log': ('type', 'type'),
'log2': ('type', 'type'),
'log10': ('type', 'type'),
'log': ('type', 'type', 'float'),
'logb': ('type', 'type'),
'sqrt': ('type', 'type'),
'inversesqrt': ('type', 'type'),
'hypot': ('float', 'float', 'float', 'float'),
'abs': ('type', 'type'),
'fabs': ('type', 'type'),
'sign': ('type', 'type'),
'floor': ('type', 'type'),
'ceil': ('type', 'type'),
'round': ('type', 'type'),
'trunc': ('type', 'type'),
'fmod': ('type', 'type', 'type'),
'mod': ('type', 'type', 'type'),
'min': ('type', 'type', 'type'),
'max': ('type', 'type', 'type'),
'clamp': ('type', 'type', 'type', 'type'),
'mix': ('type', 'type', 'type', 'type'),
'select': ('type', 'type', 'type', ''),
'isnan': ('int', 'float'),
'isinf': ('int', 'float'),
'isfinite': ('int', 'float'),
'erf': ('float', 'float'),
'erfc': ('float', 'float'),
'dot': ('float', 'vector', 'vector'),
'cross': ('vector', 'vector', 'vector'),
'length': ('float', ''),
'distance': ('float', 'point', 'point', 'point'),
'normalize': ('', ''),
'faceforward': ('vector', 'vector', 'vector', 'vector'),
'reflect': ('vector', 'vector', 'vector'),
'refract': ('vector', 'vector', 'vector', 'float'),
'fresnel': ('void', 'vector', 'normal', 'float', 'float', 'float', 'vector', 'vector'),
'rotate': ('point', 'point', 'float', 'point', 'point'),
'transform': ('', '', '', ''),
'transformu': ('float', 'string', '', 'float'),
'color': ('color', '', '', '', ''),
'luminance': ('float', 'color'),
'blackbody': ('color', 'float'),
'wavelength_color': ('color', 'float'),
'transformc': ('color', 'string', '', 'color'),
'matrix': ('matrix', '', '', '', '',
'', '', '', '',
'', '', '', '',
'', '', '', '', ''),
'getmatrix': ('int', 'string', 'string', 'matrix'),
'determinant': ('float', 'matrix'),
'transpose': ('matrix', 'matrix'),
'step': ('type', 'type', 'type'),
'linearstep': ('type', 'type', 'type', 'type'),
'smoothstep': ('type', 'type', 'type', 'type'),
'smooth_linearstep': ('type', 'type', 'type', 'type', 'type'),
'noise': ('', 'string', 'type', 'float'), # not for gabor noise
'pnoise': ('', 'string', 'type', 'type', 'type', 'float'),
'snoise': None, # deprecated, converted to noise
'psnoise': None, # deprecated, converted to pnoise
'cellnoise': None, # deprecated, converted to noise
'hashnoise': ('', 'type', 'type'),
'spline': ('', 'string', 'float', '', '', '', '', ''), # ...
'splineinverse': ('', 'string', 'float', '', '', '', '', ''), # ...
'Dx': ('', ''),
'Dy': ('', ''),
'Dz': ('', ''),
'filterwidth': ('', ''),
'area': ('float', 'point'),
'calculatenormal': ('vector', 'point'),
'aastep': ('float', 'float', 'float', 'float'),
'displace': ('void', '', ''),
'bump': ('void', '', ''),
'printf': ('void', 'string', '', '', '', '', ''), # ...
'format': ('string', 'string', '', '', '', '', ''), # ...
'error': ('void', 'string', '', '', '', '', ''), # ...
'warning': ('void', 'string', '', '', '', '', ''), # ...
'fprintf': ('void', 'string', 'string', '', '', '', '', ''), # ...
'concat': ('string', 'string', 'string', 'string', 'string'), # ...
'strlen': ('int', 'string'),
'startswith': ('int', 'string', 'string'),
'endswith': ('int', 'string', 'string'),
'stoi': ('int', 'string'),
'stof': ('float', 'string'),
'split': ('int', 'string', 'string', 'string', 'int'),
'substr': ('string', 'string', 'int', 'int'),
'getchar': ('int', 'string', 'int'),
'hash': ('int', 'string'),
'regex_search': ('int', 'string', '', 'string'),
'regex_match': ('int', 'string', 'float', 'float', '', '', '', '', ''), # ...
'texture': ('color', 'string', 'float', 'float', '', '', '', '', ''), # + float
'texture3d': ('color', 'string', 'point', '', '', '', '', ''), # + float
'environment': ('color', 'string', 'vector', '', '', '', '', ''), # + float
'gettextureinfo': ('int', 'string', 'string', ''),
'pointcloud_search': ('int', 'string', 'point', 'float', 'int', '', '', '', '', ''), # ...
'pointcloud_get': ('int', 'string', 'int', 'int', 'string', ''),
'pointcloud_write': ('int', 'string', 'point', 'string', ''),
'diffuse': ('color', 'normal'),
'phong': ('color', 'normal', 'float'),
'oren_nayar': ('color', 'normal', 'float'),
'ward': ('color', 'normal', 'vector', 'float', 'float'),
'microfacet': ('color', 'string', 'normal', '', '', '', '', ''),
'reflection': ('color', 'normal', 'float'),
'refraction': ('color', 'normal', 'float'),
'transparent': ('color'),
'translucent': ('color'),
'isotropic': ('color'),
'henyey greenstein': ('color', 'float'),
'absorption': ('color'),
'emission': ('color'),
'background': ('color'),
'holdout': ('color'),
'debug': ('color', 'string'),
'getattribute': ('int', 'string', '', '', ''),
'setmessage': ('void', 'string', ''),
'getmessage': ('int', 'string', '', ''),
'surfacearea': ('float'),
'raytype': ('int', 'string'),
'backfacing': ('int'),
'isconnected': ('int', ''),
'isconstant': ('int', ''),
'dict_find': ('int', '', 'string'),
'dict_next': ('int', 'int'),
'dict_value': ('int', 'int', 'string', ''),
'trace': ('int', 'point', 'vector', '', '', '', '', ''), # ...
'arraylength': ('int', ''),
'exit': ('void')
}
STRING_CONSTANTS = {
'alpha': 'OSL_ALPHA',
'anisotropic': 'OSL_ANISOTROPIC',
'averagealpha': 'OSL_AVERAGEALPHA',
'averagecolor': 'OSL_AVERAGECOLOR',
'bandwidth': 'OSL_BANDWIDTH',
'black': 'OSL_BLACK',
'bezier': 'OSL_BEZIER',
'blur': 'OSL_BLACK',
'bspline': 'OSL_BSPLINE',
'camera': 'OSL_CAMERA',
'camera:resolution': 'OSL_CAMERA_RESOLUTION',
'camera:pixelaspect': 'OSL_CAMERA_PIXELASPECT',
'camera:projection': 'OSL_CAMERA_PROJECTION',
'camera:fov': 'OSL_CAMERA_FOV',
'camera:clip_near': 'OSL_CAMERA_CLIP_NEAR',
'camera:clip_far': 'OSL_CAMERA_CLIP_FAR',
'camera:clip': 'OSL_CAMERA_CLIP',
'camera:shutter_open': 'OSL_CAMERA_SHUTTER_OPEN',
'camera:shutter_close': 'OSL_CAMERA_SHUTTER_CLOSE',
'camera:shutter': 'OSL_CAMERA_SHUTTER',
'camera:screen_window': 'OSL_CAMERA_SCREEN_WINDOW',
'catmull-rom': 'OSL_CATMULL_ROM',
'cell': 'OSL_CELL',
'channels': 'OSL_CHANNELS',
'clamp': 'OSL_CLAMP',
'color': 'OSL_COLOR',
'constant': 'OSL_CONSTANT',
'common': 'OSL_COMMON',
'datawindow': 'OSL_DATAWINDOW',
'default': 'OSL_DEFAULT',
'displaywindow': 'OSL_DISPLAYWINDOW',
'distance': 'OSL_DISTANCE',
'diffuse': 'OSL_DIFFUSE',
'direction': 'OSL_DIRECTION',
'do_filter': 'OSL_DO_FILTER',
'errormessage': 'OSL_ERRORMESSAGE',
'exists': 'OSL_EXISTS',
'fill': 'OSL_FILL',
'firstchannel': 'OSL_FIRSTCHANNEL',
'gabor': 'OSL_GABOR',
'geom:name': 'OSL_GEOM_NAME',
'glossy': 'OSL_GLOSSY',
'hash': 'OSL_HASH',
'hermite': 'OSL_HERMITE',
'hit': 'OSL_HIT',
'hitdist': 'OSL_HITDIST',
'hsl': 'OSL_HSL',
'hsv': 'OSL_HSV',
'impulses': 'OSL_IMPULSES',
'index': 'OSL_INDEX',
'interp': 'OSL_INTERP',
'linear': 'OSL_LINEAR',
'mirror': 'OSL_MIRROR',
'missingalpha': 'OSL_MISSINGALPHA',
'missingcolor': 'OSL_MISSINGCOLOR',
'NDC': 'OSL_NDC',
'normal': 'OSL_NORMAL',
'object': 'OSL_OBJECT',
'osl:version': 'OSL_OSL_VERSION',
'periodic': 'OSL_PERIODIC',
'perlin': 'OSL_PERLIN',
'position': 'OSL_POSITION',
'raster': 'OSL_RASTER',
'reflection': 'OSL_REFLECTION',
'refraction': 'OSL_REFRACTION',
'resolution': 'OSL_RESOLUTION',
'rgb': 'OSL_RGB',
'rwrap': 'OSL_RWRAP',
'screen': 'OSL_SCREEN',
'shader': 'OSL_SHADER',
'shadow': 'OSL_SHADOW',
'shader:groupname': 'OSL_SHADER_GROUPNAME',
'shader:layername': 'OSL_SHADER_LAYERNAME',
'shader:shadername': 'OSL_SHADER_SHADERNAME',
'simple': 'OSL_SIMPLEX',
'subimage': 'OSL_SUBIMAGE',
'subimages': 'OSL_SUBIMAGES',
'swrap': 'OSL_SWRAP',
'textureformat': 'OSL_TEXTUREFORMAT',
'time': 'OSL_TIME',
'trace': 'OSL_TRACE',
'type': 'OSL_TYPE',
'twrap': 'OSL_TWRAP',
'uperlin': 'OSL_UPERLIN',
'usimplex': 'OSL_USIMPLEX',
'width': 'OSL_WIDTH',
'world': 'OSL_WORLD',
'worldtocamera': 'OSL_WORLDTOCAMERA',
'worldtoscreen': 'OSL_WORLDTOSCREEN',
'wrap': 'OSL_WRAP',
'YIQ': 'OSL_YIQ',
'XYZ': 'OSL_XYZ',
'xyY': 'OSL_XYY',
'': 'OSL_EMPTY',
' ': 'OSL_EMPTY'
}
MATH_CONSTANTS = {
'M_PI': 'float',
'M_PI_2': 'float',
'M_PI_4': 'float',
'M_2_PI': 'float',
'M_2PI': 'float',
'M_4PI': 'float',
'M_2_SQRTPI': 'float',
'M_E': 'float',
'M_LN2': 'float',
'M_LN10': 'float',
'M_LOG2E': 'float',
'M_LOG10E': 'float',
'M_SQRT2': 'float',
'M_SQRT1_2': 'float'
}
# to preserve shader parameters order
GLOBAL_VARIABLES = collections.OrderedDict([
('P', 'point'),
('I', 'vector'),
('N', 'normal'),
('Ng', 'normal'),
('u', 'float'),
('v', 'float'),
('dPdu', 'vector'),
('dPdv', 'vector'),
('Ps', 'point'),
('time', 'float'),
('dtime', 'float'),
('dPdtime', 'vector'),
('Ci', 'color')
])
def join_toks(array, sep=''):
array = list(filter(lambda i: i != '', array))
return sep.join(array)
def indent_lines(string, indent=4):
ind_lines = []
for l in string.splitlines():
ind_lines.append(' ' * indent + l)
return '\n'.join(ind_lines)
def g_shader_file(n):
return join_toks(n)
def g_global_declaration(n):
return n[0]
def g_shader_declaration(n):
return '''void {0}({1}) {{
{2}
}}
'''.format(n[1], n[3], indent_lines(n[4]))
def g_shadertype(n):
return ''
def g_shader_formal_params_opt(n):
return n[0] if n[0] is not None else ''
def g_shader_formal_params(n):
return join_toks(n, ', ')
def g_shader_formal_param(n):
# no initializers
if len(n) == 5:
return join_toks(n[0:3], ' ')
else:
return join_toks(n[0:4], ' ')
def g_metadata_block_opt(n):
return ''
def g_metadata_block(n):
return ''
def g_metadata_list(n):
return ''
def g_metadata(n):
return ''
def g_function_declaration(n):
return '''{0} {1}({2}) {{
{3}
}}
'''.format(n[0], n[1], n[2], indent_lines(n[3]))
def g_function_formal_params_opt(n):
return n if n else ''
def g_function_formal_params(n):
return join_toks(n, ', ')
def g_function_formal_param(n):
return join_toks(n, ' ')
def g_outputspec(n):
return n[0]
def g_struct_declaration(n):
return '''struct {0} {{
{1}
}};
'''.format(n[0], indent_lines(n[1]))
def g_field_declarations(n):
return join_toks(n, '\n')
def g_field_declaration(n):
return '{0} {1};'.format(n[0], n[1])
def g_typed_field_list(n):
return join_toks(n, ', ')
def g_typed_field(n):
if n[1] != '':
return '{0} {1}'.format(n[0], n[1])
else:
return n[0]
def g_local_declaration(n):
return ''
def g_arrayspec_opt(n):
return n[0] if n[0] is not None else ''
def g_arrayspec(n):
if len(n) == 1:
return '[{0}]'.format(n[0])
else:
return '[]'
def g_variable_declaration(n):
return '{0} {1};'.format(n[0], n[1])
def g_def_expressions(n):
return join_toks(n, ', ')
def g_def_expression(n):
if len(n) == 2:
if n[1] != '':
return '{0} {1}'.format(n[0], n[1])
else:
return '{0}'.format(n[0])
else:
return '{0}{1} {2}'.format(n[0], n[1], n[2])
def g_initializer_opt(n):
return '' if n[0] == None else n[0]
def g_initializer(n):
return '= ' + n[0]
def g_initializer_list_opt(n):
return n[0] if n[0] is not None else ''
def g_initializer_list(n):
return '= ' + n[0]
def g_compound_initializer(n):
#return 'int[]( {0} )'.format(n[0])
return '{{ {0} }}'.format(n[0])
def g_init_expression_list(n):
return join_toks(n, ', ')
def g_init_expression(n):
return n[0]
def g_typespec(n):
return n[0]
def g_simple_typename(n):
return n[0]
def g_statement_list_opt(n):
return n[0] if n[0] is not None else ''
def g_statement_list(n):
return join_toks(n, '\n')
def g_statement(n):
return n[0]
def g_statement_semi(n):
return n[0] + ';'
def g_scoped_statements(n):
return '''{{
{0}
}}'''.format(indent_lines(n[0]))
def g_conditional_statement(n):
# improve indentation
if '{' not in n[1]:
n[1] = '\n ' + n[1];
else:
n[1] = ' ' + n[1];
if len(n) == 2:
return 'if ({0}){1}'.format(n[0], n[1])
else:
# improve last 'else' indentation
if '{' not in n[1]:
n[1] = n[1] + '\n'
else:
n[1] = n[1] + ' '
if '{' not in n[2] and 'if' not in n[2]:
n[2] = '\n ' + n[2];
else:
n[2] = ' ' + n[2];
return 'if ({0}){1}else{2}'.format(n[0], n[1], n[2])
def g_loop_statement_while(n):
return '''while ({0}) {1}'''.format(n[0], n[1])
def g_loop_statement_do_while(n):
return '''do {0} while ({1});'''.format(n[0], n[1])
def g_loop_statement_for(n):
return '''for ({0} {1}; {2}) {3}'''.format(n[0], n[1], n[2], n[3])
def g_for_init_statement_opt(n):
return n[0] if n[0] is not None else ''
def g_for_init_statement(n):
return n[0]
def g_for_init_statement_semi(n):
return '{0};'.format(n[0])
def g_loopmod_statement(n):
return '{0};'.format(n[0])
def g_return_statement(n):
if n[0] != '':
return 'return {0};'.format(n[0])
else:
return 'return;'
def g_expression_list(n):
return join_toks(n, ', ')
def g_expression_opt(n):
return n[0] if n[0] is not None else ''
def g_expression(n):
# TODO
return join_toks(n)
def g_expression_paren(n):
return '({0})'.format(n[0])
def g_compound_expression_opt(n):
return n[0] if n[0] is not None else ''
def g_compound_expression(n):
return join_toks(n, ', ')
def g_variable_lvalue(n):
return join_toks(n)
def g_variable_lvalue_brackets(n):
return '{0}[{1}]'.format(n[0], n[1])
def g_variable_lvalue_period(n):
return '{0}.{1}'.format(n[0], n[1])
def g_variable_ref(n):
return join_toks(n)
def g_binary_op(n):
return '{0} {1} {2}'.format(n[0], n[1], n[2])
def g_unary_op(n):
return n[0]
def g_incdec_op(n):
return n[0]
def g_type_constructor(n):
return '{0}({1})'.format(n[0], n[1])
def g_function_call(n):
return '{0}({1})'.format(n[0], n[1])
def g_function_args_opt(n):
return n[0] if n[0] is not None else ''
def g_function_args(n):
return join_toks(n, ', ')
def g_assign_expression(n):
return join_toks(n, '')
def g_assign_op(n):
return ' {0} '.format(n[0])
def g_ternary_expression(n):
return '{0} ? {1} : {2}'.format(n[0], n[1], n[2])
def g_typecast_expression(n):
return '({0}){1}'.format(n[0], n[1])
def g_sign(n):
return ''
def g_integer(n):
return n[0]
def g_floating_point(n):
return n[0]
def g_number(n):
return n[0]
def g_stringliteral(n):
return n[0]
def g_identifier(n):
return n[0]
def g_empty(n):
return ''
def g_raw_code(n):
return n[0]
def g_default(n):
print('Unsupported AST item:', n)
return ''
def traverse_ast_visitors(ast, visitors):
if isinstance(ast, Node):
type = ast.type
n_resolved = [traverse_ast_visitors(i, visitors) for i in ast.children]
return visitors[type if type in visitors else 'default'](n_resolved)
else:
return ast if ast is not None else ''
def string_to_osl_const(s):
s = s.strip('"')
h = binascii.crc_hqx(s.encode(), 0)
if s in STRING_CONSTANTS:
return STRING_CONSTANTS[s]
else:
return str(h)
def get_all_string_constants():
dest = {}
for s in STRING_CONSTANTS:
dest[STRING_CONSTANTS[s]] = binascii.crc_hqx(s.encode(), 0)
return dest
def convert_types(ast):
global variables
variables = ast.get_variables()
variables.update(GLOBAL_VARIABLES)
variables.update(MATH_CONSTANTS)
global functions
functions = ast.get_functions()
functions.update(STDLIB_FUNCTIONS)
def cb_add_type_converters(node):
type = node.type
childs = node.children
if type == 'assign-expression':
lvalue_node = node.get_child(0)
rvalue_node = node.get_child(2)
lvalue_type = resolve_expr_type(lvalue_node)
rvalue_type = resolve_expr_type(rvalue_node)
if lvalue_type != rvalue_type:
node.set_child(2, typecast(lvalue_type, rvalue_node))
elif type == 'conditional-statement' or type == 'loop-statement-while':
expr_node = node.get_child(0)
if resolve_expr_type(expr_node) != 'bool':
node.set_child(0, typecast('bool', expr_node))
elif type == 'def-expression':
idt = node.get_child(0)
idt_type = variables[idt]
if len(node.children) == 2:
intz = node.get_child(1)
if intz and resolve_expr_type(intz) != idt_type:
node_init = node.get_child('initializer')
node_init.set_child(0, typecast(idt_type, node_init.get_child(0)))
elif type == 'function-call':
resolve_expr_type(node)
elif type == 'loop-statement-do-while':
expr_node = node.get_child(1)
if resolve_expr_type(expr_node) != 'bool':
node.set_child(1, typecast('bool', expr_node))
elif type == 'loop-statement-for':
expr_node = node.get_child(1)
if expr_node and resolve_expr_type(expr_node) != 'bool':
node.set_child(1, typecast('bool', expr_node))
elif type == 'ternary-expression':
cond_node = node.get_child(0)
if resolve_expr_type(cond_node) != 'bool':
node.set_child(0, typecast('bool', cond_node))
elif type == 'typecast-expression':
# no need to typecast, just process children
resolve_expr_type(node.get_child(1))
elif type == 'type-constructor':
# no need to typecast, just process children
resolve_expr_type(node.get_child(1))
ast.traverse_nodes(cb_add_type_converters)
def replace_types(ast):
def cb_replace_types(node):
type = node.type
childs = node.children
if type == 'simple-typename':
if childs[0] in ['point', 'vector', 'normal', 'color']:
childs[0] = 'vec3'
elif childs[0] == 'string':
childs[0] = 'int'
elif childs[0] == 'matrix':
childs[0] = 'mat4'
elif type == 'outputspec':
if childs[0] == 'output':
childs[0] = 'out'
elif type == 'stringliteral':
node.type = 'integer'
node.set_child(0, string_to_osl_const(node.get_child(0)))
elif type == 'typecast-expression':
node.type = 'type-constructor'
elif type == 'compound-initializer':
decl_node = node.find_ancestor_node(ast, 'variable-declaration')
if decl_node:
type = resolve_expr_type(decl_node.get_child('typespec'))
init_expr_list = node.get_child('init-expression-list')
node.type = 'type-constructor'
# NOTE: hack, identifier-like argument
node.set_child(0, Node('typespec', type + '[]'))
node.append(init_expr_list)
ast.traverse_nodes(cb_replace_types)
def add_shader_params(ast):
glob_vars = find_global_variables(ast)
for var_type, var_name in reversed(glob_vars):
add_shader_param(ast, var_type, var_name)
# also add texture param
call_nodes = ast.find_nodes('function-call')
for cn in call_nodes:
name = cn.get_child(0)
if name == 'texture':
add_shader_param(ast, 'sampler2D', 'Image')
def find_global_variables(ast):
dest = []
sts_node = ast.get_child('shader-declaration').get_child('statement-list')
for var_name in GLOBAL_VARIABLES:
if sts_node.uses_variable(var_name):
var_type = GLOBAL_VARIABLES[var_name]
dest.append((var_type, var_name))
return dest
def add_shader_param(ast, type, name):
outspec_node = Node('outputspec', None)
typespec_node = Node('typespec', Node('simple-typename', type))
param_node = Node('shader-formal-param', outspec_node, typespec_node, name, None, None)
params_node = ast.get_child('shader-declaration').get_child('shader-formal-params')
params_node.insert(0, param_node)
def replace_identifiers(ast):
def cb(node):
for i in range(node.num_childs()):
if node.get_child(i) == 'in':
node.set_child(i, 'inp')
ast.traverse_nodes(cb)
def replace_global_functions(ast):
call_nodes = ast.find_nodes('function-call')
for node in call_nodes:
name = node.get_child(0)
args = node.get_child('function-args')
if name in ['error', 'fprintf', 'printf', 'warning']:
name = name.replace('error', 'oslError')
name = name.replace('fprintf', 'oslFPrintf')
name = name.replace('printf', 'oslPrintf')
name = name.replace('warning', 'oslWarning')
# remove args
node.set_child(1, None)
elif name == 'log' and args.num_childs() == 2:
name = 'oslLog2'
elif name in ['noise', 'pnoise']:
noise_type = 'float'
par_node = node.get_ancestor(ast).get_ancestor(ast)
if par_node:
if par_node.type == 'typecast-expression':
noise_type = resolve_expr_type(par_node)
else:
par_node = par_node.get_ancestor(ast)
if par_node.type == 'type-constructor':
noise_type = resolve_expr_type(par_node)
if noise_type in ['point', 'vector', 'normal', 'color']:
if name == 'noise':
name = 'oslNoise3D'
else:
name = 'oslPNoise3D'
else:
if name == 'noise':
name = 'oslNoise'
else:
name = 'oslPNoise'
elif name == 'texture':
# e.g Filename -> Image
first_arg_var_ref = args.get_child(0).get_child('variable-ref')
if first_arg_var_ref:
first_arg_var_ref.find_node('variable-lvalue').set_child(0, 'Image')
name = 'oslTexture'
elif name == 'transform':
last_arg_type = resolve_expr_type(args.get_child(-1))
if last_arg_type in ['vector', 'normal']:
name = 'oslTransformDir'
else:
name = 'oslTransform'
else:
name = name.replace('atan2', 'atan')
name = name.replace('blackbody', 'oslBlackbody')
name = name.replace('distance', 'oslDistance')
name = name.replace('endswith', 'oslEndsWith')
name = name.replace('fabs', 'abs')
name = name.replace('fmod', 'mod')
name = name.replace('format', 'oslFormat')
name = name.replace('getattribute', 'oslGetAttribute')
name = name.replace('gettextureinfo', 'oslGetTextureInfo')
name = name.replace('hypot', 'oslHypot')
name = name.replace('luminance', 'oslLuminance')
name = name.replace('pow', 'oslPow')
name = name.replace('raytype', 'oslRayType')
name = name.replace('rotate', 'oslRotate')
name = name.replace('startswith', 'oslStartsWith')
name = name.replace('strlen', 'oslStrLen')
name = name.replace('substr', 'oslSubStr')
name = name.replace('transformc', 'oslTransformC')
name = name.replace('wavelength_color', 'oslWaveLengthColor')
node.set_child(0, name)
def resolve_expr_type(node):
type = node.type
if type == 'binary-op':
c0 = node.get_child(0)
c2 = node.get_child(2)
t0 = resolve_expr_type(c0)
t2 = resolve_expr_type(c2)
op = node.get_child(1)
is_bool_op = True if op in ['&&', '||'] else False
is_int_op = True if op in ['%', '<<', '>>', '&', '|', '^'] else False
if is_bool_op:
if t0 != 'bool':
node.set_child(0, typecast('bool', c0))
if t2 != 'bool':
node.set_child(2, typecast('bool', c2))
elif is_int_op:
if t0 != 'int':
node.set_child(0, typecast('int', c0))
if t2 != 'int':
node.set_child(2, typecast('int', c2))
elif t0 == 'int' and t2 in ['bool', 'float']:
node.set_child(0, typecast(t2, c0))
elif t0 in ['bool', 'float'] and t2 == 'int':
node.set_child(2, typecast(t0, c2))
elif t0 == 'float' and t2 in ['point', 'vector', 'normal', 'matrix', 'color']:
node.set_child(0, typecast(t2, c0))
elif t0 in ['point', 'vector', 'normal', 'matrix', 'color'] and t2 == 'float':
node.set_child(2, typecast(t0, c2))
if op in ['<', '<=', '>', '>=', '==', '!=', '&&', '||']:
return 'bool'
else:
return resolve_expr_type(node.get_child(0))
elif type == 'expression':
if len(node.children) == 2:
op = node.get_child(0)
child = node.get_child(1)
if (op.type == 'unary-op' and (op.get_child(0) == 'not' or op.get_child(0) == '!') and
resolve_expr_type(child) != 'bool'):
node.set_child(1, typecast('bool', child))
return resolve_expr_type(node.get_child(1))
else:
return resolve_expr_type(node.get_child(0))
elif type == 'floating-point':
return 'float'
elif type == 'function-call':
name = node.get_child(0)
spec = functions[name]
# resolve all arguments first
args = node.get_child('function-args')
if args:
new_name = refactor_function_arguments(name, args)
if new_name != name:
node.set_child(0, new_name)
name = new_name
spec = functions[new_name]
if spec[0] == 'type' or spec[0] == 'ptype':
for i in range(args.num_childs()):
# first argument of the same generic type
if spec[i+1] == 'type' or spec[i+1] == 'ptype':
arg_node = args.get_child(i)
arg_type = resolve_expr_type(arg_node)
return arg_type
return 'float'
elif spec[0] == '':
return 'float'
else:
return spec[0]
elif type == 'integer':
return 'int'
elif type == 'simple-typename':
return node.get_child(0)
elif type == 'stringliteral':
return 'string'
elif type == 'ternary-expression':
c1 = node.get_child(1)
c2 = node.get_child(2)
t1 = resolve_expr_type(c1)
t2 = resolve_expr_type(c2)
if t1 == 'int' and t2 in ['bool', 'float']:
node.set_child(1, typecast(t2, c1))
elif t1 in ['bool', 'float'] and t2 == 'int':
node.set_child(2, typecast(t1, c2))
elif t1 == 'float' and t2 in ['point', 'vector', 'normal', 'matrix', 'color']:
node.set_child(1, typecast(t2, c1))
elif t1 in ['point', 'vector', 'normal', 'matrix', 'color'] and t2 == 'float':
node.set_child(2, typecast(t1, c2))
return resolve_expr_type(node.get_child(1))
elif type == 'typecast-expression':
return node.get_child(0)