-
Notifications
You must be signed in to change notification settings - Fork 11
/
pmfx.py
3130 lines (2755 loc) · 117 KB
/
pmfx.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import sys
import json
import jsn
import re
import math
import subprocess
import platform
import copy
import threading
import cgu
import hashlib
import pmfx_pipeline
# print error with colour
def print_error(msg):
ERROR = '\033[91m'
ENDC = '\033[0m'
print(ERROR + msg + ENDC, flush=True)
# print warning with colour
def print_warning(msg):
WARNING = '\033[93m'
ENDC = '\033[0m'
print(WARNING + msg + ENDC, flush=True)
# print ok with colour
def print_ok(msg):
OK = '\033[92m'
ENDC = '\033[0m'
print(OK + msg + ENDC, flush=True)
# paths and info for current build environment
class BuildInfo:
shader_platform = "" # hlsl, glsl, metal, spir-v, pssl
shader_sub_platform = "" # gles
shader_version = "0" # 4_0, 5_0 (hlsl), 330, 420 (glsl), 1.1, 2.0 (metal)
metal_sdk = "" # macosx, iphoneos, appletvos
metal_min_os = "" # iOS (9.0 - 13.0), macOS (10.11 - 10.15)
metal_version = "2.0" # MSL version
debug = False # generate shader with debug info
inputs = [] # array of input files or directories
extensions = [] # array of shader extension currently for glsl/gles
nvn_extensions = [] # array of shader extensions for nvn/glsl
root_dir = "" # cwd dir to run from
build_config = "" # json contents of build_config.json
pmfx_dir = "" # location of pmfx
tools_dir = "" # location of pmtech/tools
output_dir = "" # dir to build shader binaries
struct_dir = "" # dir to output the shader structs
crate_dir = "" # dir to output the shader structs (rust crate)
temp_dir = "" # dir to put temp shaders
this_file = "" # the file u are reading
macros_file = "" # pmfx.h
platform_macros_file = "" # glsl.h, hlsl.h, metal.h
macros_source = "" # source code inside _shader_macros.h
error_code = 0 # non-zero if any shaders failed to build
nvn_exe = "" # optional executable path for nvn
cmdline_string = "" # stores the full cmdline passed
num_threads = 4 # number of threadsto distribute work over
v_flip = False # glsl only (flip-y coord in vertex shader for consistency with other platforms)
args = "" # anything passed after -args is concatonated into a string and forwarded to other executables (fxc, glsl validator etc)
force = False # force compilation even if dependecies are up-to-date
# info and contents of a .pmfx file
class PmfxInfo:
includes = "" # list of included files
json = "" # json object containing techniques
json_text = "" # json as text to reload mutable dictionary
source = "" # source code of the entire shader +includes
# info of pmfx technique permutation which is a combination of vs, ps or cs
class TechniquePermutationInfo:
pmfx_name = "" # name of the .pmfx shader containing technique
technique_name = "" # name of technique
technique = "" # technique / permutation json
permutation = "" # permutation options
shader_version = "0" # shader version to compile with
source = "" # conditioned source code for permute
id = "" # permutation id
cbuffers = [] # list of cbuffers source code
functions = [] # list of functions source code
textures = [] # technique / permutation textures
shader = [] # list of shaders, vs, ps or cs
resource_decl = [] # list of shader resources (textures / buffers)
threads = [] # number of compute threads, x, y, z
error_code = 0 # return value from compilation
error_list = [] # list of errors / warnings from compilation
output_list = [] # list of output from compilation
# info about a single vs, ps, or cs
class SingleShaderInfo:
shader_type = "" # ie. vs (vertex), ps (pixel), cs (compute)
main_func_name = "" # entry point ie. vs_main
functions_source = "" # source code of all used functions
main_func_source = "" # source code of main function
input_struct_name = "" # name of input to shader ie. vs_input
instance_input_struct_name = "" # name of instance input to vertex shader
output_struct_name = "" # name of output from shader ie. vs_output
input_decl = "" # struct decl of input struct
instance_input_decl = "" # struct decl of instance input struct
output_decl = "" # struct decl of shader output
struct_decls = "" # decls of all generic structs
resource_decl = [] # decl of only used resources by shader
cbuffers = [] # array of cbuffer decls used by shader
sv_semantics = [] # array of tuple [(semantic, variable name), ..]
duplicate = False
# used for eval to allow undefined variables
class Reflector(object):
def __getitem__(self, name):
return 0
# parse command line args passed in
def parse_args():
global _info
# set defaults
_info.compiled = True
_info.cbuffer_offset = 4
_info.texture_offset = 32
_info.stage_in = 1
_info.v_flip = False
_info.debug = False
_info.args = ""
if len(sys.argv) == 1:
display_help()
for arg in sys.argv:
_info.cmdline_string += arg + " "
for i in range(1, len(sys.argv)):
if "-help" in sys.argv[i]:
display_help()
if "-root_dir" in sys.argv[i]:
os.chdir(sys.argv[i + 1])
if "-shader_platform" in sys.argv[i]:
_info.shader_platform = sys.argv[i + 1]
if "-shader_version" in sys.argv[i]:
_info.shader_version = sys.argv[i + 1]
if sys.argv[i] == "-i":
j = i + 1
while j < len(sys.argv) and sys.argv[j][0] != '-':
_info.inputs.append(sys.argv[j])
j = j + 1
i = j
elif sys.argv[i] == "-o":
_info.output_dir = sys.argv[i + 1]
elif sys.argv[i] == "-h":
_info.struct_dir = sys.argv[i + 1]
elif sys.argv[i] == "-rs":
_info.crate_dir = sys.argv[i + 1]
elif sys.argv[i] == "-t":
_info.temp_dir = sys.argv[i + 1]
elif sys.argv[i] == "-f":
_info.force = True
elif sys.argv[i] == "-source":
_info.compiled = False
elif sys.argv[i] == "-cbuffer_offset":
_info.cbuffer_offset = sys.argv[i + 1]
elif sys.argv[i] == "-texture_offset":
_info.cbuffer_offset = sys.argv[i + 1]
elif sys.argv[i] == "-stage_in":
_info.stage_in = sys.argv[i + 1]
elif sys.argv[i] == "-v_flip":
_info.v_flip = True
elif sys.argv[i] == "-d":
_info.debug = False
elif sys.argv[i] == "-metal_min_os":
_info.metal_min_os = sys.argv[i+1]
elif sys.argv[i] == "-metal_version":
_info.metal_version = sys.argv[i+1]
elif sys.argv[i] == "-metal_sdk":
_info.metal_sdk = sys.argv[i+1]
elif sys.argv[i] == "-nvn_exe":
_info.nvn_exe = sys.argv[i+1]
elif sys.argv[i] == "-num_threads":
_info.num_threads = int(sys.argv[i+1])
elif sys.argv[i] == "-extensions":
j = i + 1
while j < len(sys.argv) and sys.argv[j][0] != '-':
_info.extensions.append(sys.argv[j])
j = j + 1
i = j
elif sys.argv[i] == "-nvn_extensions":
j = i + 1
while j < len(sys.argv) and sys.argv[j][0] != '-':
_info.nvn_extensions.append(sys.argv[j])
j = j + 1
i = j
elif sys.argv[i] == "-args":
j = i + 1
_info.args = ""
while j < len(sys.argv):
_info.args += sys.argv[j] + " "
j = j + 1
i = j
required = [
"-shader_platform",
"-i",
"-o",
"-t"
]
if _info.shader_platform == "nvn":
required.append("-nvn_exe")
missing = False
for r in required:
if r not in sys.argv:
print_error("error: missing rquired argument {}".format(r))
missing = True
if missing:
print("exit")
sys.exit(1)
# display help for args
def display_help():
print("commandline arguments:")
print(" -v1 compile using pmfx version 1 (legacy) will use v2 otherwise")
print(" -num_threads 4 (default) <supply threadpool size>")
print(" -shader_platform <hlsl, glsl, gles, spirv, metal, pssl, nvn>")
print(" -shader_version (optional) <shader version unless overridden in technique>")
print(" hlsl: 3_0, 4_0 (default), 5_0, 6_0 [-v2]")
print(" glsl: 200, 330 (default), 420, 450")
print(" gles: 100, 300, 310, 350")
print(" spirv: 420 (default), 450")
print(" metal: 2.0 (default)")
print(" nvn: (glsl)")
print(" -metal_sdk [metal only] <iphoneos, macosx, appletvos>")
print(" -metal_min_os (optional) [metal only] <9.0 - 13.0 (ios), 10.11 - 10.15 (macos)>")
print(" -nvn_exe [nvn only] <path to execulatble that can compile glsl to nvn glslc>")
print(" -extensions (optional) [glsl/gles only] <list of glsl extension strings separated by spaces>")
print(" -nvn_extensions (optional) [nvn only] <list of nvn glsl extension strings separated by spaces>")
print(" -i <list of input files or directories separated by spaces>")
print(" -o <output dir for shaders>")
print(" -t <output dir for temp files>")
print(" -h (optional) <output dir header file with shader structs>")
print(" -d (optional) generate debuggable shader")
print(" -f (optional) force build / compile even if dependencies are up-to-date")
print(" -rs (optional) <output dir for rust crate with shader structs> [-v2]")
print(" -root_dir (optional) <directory> sets working directory here")
print(" -source (optional) (generates platform source into -o no compilation)")
print(" -stage_in <0, 1> (optional) [metal only] (default 1) ")
print(" uses stage_in for metal vertex buffers, 0 uses raw buffers")
print(" -cbuffer_offset (optional) [metal only] (default 4) ")
print(" specifies an offset applied to cbuffer locations to avoid collisions with vertex buffers")
print(" -texture_offset (optional) [vulkan only] (default 32) ")
print(" specifies an offset applied to texture locations to avoid collisions with buffers")
print(" -v_flip (optional) [glsl only] (inserts glsl uniform to conditionally flip verts in the y axis)")
print(" -args (optional) anything passed after this will be forward to the platform specific compiler")
print(" for example for fxc.exe /Zpr or dxc.exe -Zpr etc.. check the compiler help for options")
sys.stdout.flush()
sys.exit(0)
# duplicated from pmtech/tools/scripts/util
def get_platform_name():
plat = "win64"
if os.name == "posix":
plat = "osx"
if platform.system() == "Linux":
plat = "linux"
return plat
# gets shader sub platform name, gles (glsl) spirv (glsl)
def shader_sub_platform():
sub_platforms = ["gles", "spirv"]
if _info.shader_sub_platform in sub_platforms:
return _info.shader_sub_platform
return _info.shader_platform
# get extension for windows
def get_platform_exe():
if get_platform_name() == "win64":
return ".exe"
return ""
def sanitize_file_path(path):
path = path.replace("/", os.sep)
path = path.replace("\\", os.sep)
path = path.replace("@", ":")
return path
# duplicated from pmtech/tools/scripts/dependencies
def unstrict_json_safe_filename(file):
file = file.replace("\\", '/')
file = file.replace(":", "@")
return file
def create_dependency(file):
file = sanitize_file_path(file)
modified_time = os.path.getmtime(file)
return {"name": file, "timestamp": float(modified_time)}
# wrap a string in quotes
def in_quotes(string):
return "\"" + string + "\""
# convert signed to unsigned integer in a c like manner for comparisons
def us(v):
if v == -1:
return sys.maxsize
return v
# calls subprocess, waits and gets output errors
def call_wait_subprocess(cmdline):
exclude_output = [
"Microsoft (R)",
"Copyright (C)",
"compilation object save succeeded;"
]
p = subprocess.Popen(cmdline, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
error_code = p.wait()
output, err = p.communicate()
err_str = err.decode('utf-8')
err_str = err_str.strip(" ")
err_list = err_str.split("\n")
out_str = output.decode('utf-8')
out_str = out_str.strip(" ")
out_list = out_str.split("\n")
clean_err = []
for e in err_list:
if len(e) > 0:
clean_err.append(e.strip())
clean_out = []
for o in out_list:
o = o.strip()
exclude = False
for ex in exclude_output:
if o.startswith(ex):
exclude = True
break
if len(o) > 0 and not exclude:
clean_out.append(o)
return error_code, clean_err, clean_out
# recursively merge members of 2 json objects
def member_wise_merge(j1, j2):
for key in j2.keys():
if key not in j1.keys():
j1[key] = j2[key]
elif type(j1[key]) is dict:
j1[key] = member_wise_merge(j1[key], j2[key])
return j1
# remove comments, taken from stub_format.py ()
def remove_comments(file_data):
lines = file_data.split("\n")
inside_block = False
conditioned = ""
for line in lines:
if inside_block:
ecpos = line.find("*/")
if ecpos != -1:
inside_block = False
line = line[ecpos+2:]
else:
continue
cpos = line.find("//")
mcpos = line.find("/*")
if cpos != -1:
conditioned += line[:cpos] + "\n"
elif mcpos != -1:
conditioned += line[:mcpos] + "\n"
inside_block = True
else:
conditioned += line + "\n"
return conditioned
# tidy shader source with consistent spaces, remove tabs and comments to make subsequent operations easier
def sanitize_shader_source(shader_source):
# replace tabs with spaces
shader_source = shader_source.replace("\t", " ")
# replace all spaces with single space
shader_source = re.sub(' +', ' ', shader_source)
# remove comments
shader_source = remove_comments(shader_source)
return shader_source
# parse and split into an array, from a list of textures or cbuffers etc
def parse_and_split_block(code_block):
start = code_block.find("{") + 1
end = code_block.find("};")
block_conditioned = code_block[start:end].replace(";", " ")
block_conditioned = block_conditioned.replace(":", " ")
block_conditioned = block_conditioned.replace("(", " ")
block_conditioned = block_conditioned.replace(")", " ")
block_conditioned = block_conditioned.replace(",", " ")
block_conditioned = re.sub(' +', ' ', block_conditioned)
return block_conditioned.split()
# find the end of a body text enclosed in brackets
def enclose_brackets(text):
body_pos = text.find("{")
bracket_stack = ["{"]
text_len = len(text)
while len(bracket_stack) > 0 and body_pos < text_len:
body_pos += 1
character = text[body_pos:body_pos+1]
if character == "{":
bracket_stack.insert(0, "{")
if character == "}" and bracket_stack[0] == "{":
bracket_stack.pop(0)
body_pos += 1
return body_pos
# replace all "input" and "output" tokens to "_input" and "_ouput" to avoid glsl keywords
# todo: this should be replaced with "replace_token"
def replace_io_tokens(text):
token_io = ["input", "output"]
token_io_replace = ["_input", "_output"]
token_post_delimiters = ['.', ';', ' ', '(', ')', ',', '-', '+', '*', '/']
token_pre_delimiters = [' ', '\t', '\n', '(', ')', ',', '-', '+', '*', '/']
split = text.split(' ')
split_replace = []
for token in split:
for i in range(0, len(token_io)):
if token_io[i] in token:
last_char = len(token_io[i])
first_char = token.find(token_io[i])
t = token[first_char:first_char+last_char+1]
l = len(t)
if first_char > 0 and token[first_char-1] not in token_pre_delimiters:
continue
if l > last_char:
c = t[last_char]
if c in token_post_delimiters:
token = token.replace(token_io[i], token_io_replace[i])
continue
elif l == last_char:
token = token.replace(token_io[i], token_io_replace[i])
continue
split_replace.append(token)
replaced_text = ""
for token in split_replace:
replaced_text += token + " "
return replaced_text
# get info filename for dependency checking
def get_resource_info_filename(filename, build_dir):
global _info
base_filename = os.path.basename(filename)
dir_path = os.path.dirname(filename)
info_filename = os.path.join(_info.output_dir, os.path.splitext(base_filename)[0], "info.json")
return info_filename, base_filename, dir_path
# check file time stamps and build times to determine if rebuild needs to happen
# returns true if the file does not need re-building, false if a file/dependency is out of date or input has changed
def check_dependencies(filename, included_files):
global _info
# look for .json file
file_list = list()
file_list.append(sanitize_file_path(os.path.join(_info.root_dir, filename)))
file_list.append(sanitize_file_path(_info.this_file))
file_list.append(sanitize_file_path(_info.macros_file))
file_list.append(sanitize_file_path(_info.platform_macros_file))
info_filename, base_filename, dir_path = get_resource_info_filename(filename, _info.output_dir)
for f in included_files:
file_list.append(sanitize_file_path(os.path.join(_info.root_dir, f)))
if os.path.exists(info_filename) and os.path.getsize(info_filename) > 0:
info_file = open(info_filename, "r")
info = json.loads(info_file.read())
if "cmdline" not in info or _info.cmdline_string != info["cmdline"]:
return False
for prev_built_with_file in info["files"]:
sanitized_name = sanitize_file_path(prev_built_with_file["name"])
if sanitized_name in file_list:
if not os.path.exists(sanitized_name):
return False
if prev_built_with_file["timestamp"] < os.path.getmtime(sanitized_name):
info_file.close()
print(os.path.basename(sanitized_name) + ": out-of-date", flush=True)
return False
else:
print(sanitized_name + ": out-of-date", flush=True)
return False
if "failures" in info.keys():
if len(info["failures"]) > 0:
return False
info_file.close()
else:
return False
return True
# find generic structs
def find_structs(shader_text, special_structs):
struct_list = []
start = 0
while start != -1:
op = start
start = find_token("struct", shader_text[start:])
if start == -1:
break
start = op + start
end = shader_text.find("};", start)
if end != -1:
end += 2
found_struct = shader_text[start:end]
valid = True
for ss in special_structs:
if ss in found_struct:
valid = False
if valid:
struct_list.append(shader_text[start:end] + "\n")
start = end
return struct_list
def find_c_structs(shader_text):
special_structs = ["vs_output", "ps_input", "ps_output"]
return find_structs(shader_text, special_structs)
def find_struct_declarations(shader_text):
special_structs = ["vs_input", "vs_output", "ps_input", "ps_output", "vs_instance_input"]
return find_structs(shader_text, special_structs)
# find shader resources
def find_shader_resources(shader_text):
start = shader_text.find("declare_texture_samplers")
if start == -1:
start = shader_text.find("shader_resources")
if start == -1:
return "\n"
start = shader_text.find("{", start) + 1
end = shader_text.find("};", start)
texture_sampler_text = shader_text[start:end] + "\n"
texture_sampler_text = texture_sampler_text.replace("\t", "")
texture_sampler_text += "\n"
return texture_sampler_text
# find struct in shader source
def find_struct(shader_text, decl):
delimiters = [" ", "\n", "{"]
start = 0
while True:
start = shader_text.find(decl, start)
if start == -1:
return ""
for d in delimiters:
if shader_text[start+len(decl)] == d:
end = shader_text.find("};", start)
end += 2
if start != -1 and end != -1:
return shader_text[start:end] + "\n\n"
else:
return ""
start += len(decl)
# find cbuffers in source
def find_constant_buffers(shader_text):
cbuffer_list = []
start = 0
while start != -1:
pos = find_token("cbuffer", shader_text[start:])
if pos == -1:
break
start += pos
end = shader_text.find("};", start)
if end != -1:
end += 2
cbuffer_list.append(shader_text[start:end] + "\n")
start = end
return cbuffer_list
# find function source
def find_function(shader_text, decl):
start = shader_text.find(decl)
if start == -1:
return ""
body_pos = shader_text.find("{", start)
bracket_stack = ["{"]
text_len = len(shader_text)
while len(bracket_stack) > 0 and body_pos < text_len:
body_pos += 1
character = shader_text[body_pos:body_pos+1]
if character == "{":
bracket_stack.insert(0, "{")
if character == "}" and bracket_stack[0] == "{":
bracket_stack.pop(0)
body_pos += 1
return shader_text[start:body_pos] + "\n\n"
# find functions in source
def find_functions(shader_text):
deliminator_list = [";", "\n"]
function_list = []
start = 0
while 1:
start = shader_text.find("(", start)
if start == -1:
break
# make sure the { opens before any other deliminator
deliminator_pos = shader_text.find(";", start)
body_pos = shader_text.find("{", start)
if deliminator_pos < body_pos:
start = deliminator_pos
continue
# find the function name and return type
function_name = shader_text.rfind(" ", 0, start)
name_str = shader_text[function_name:start]
if name_str.find("if:") != -1:
start = deliminator_pos
continue
function_return_type = 0
for delim in deliminator_list:
decl_start = shader_text.rfind(delim, 0, function_name)
if decl_start != -1:
function_return_type = decl_start
bracket_stack = ["{"]
text_len = len(shader_text)
while len(bracket_stack) > 0 and body_pos < text_len:
body_pos += 1
character = shader_text[body_pos:body_pos+1]
if character == "{":
bracket_stack.insert(0, "{")
if character == "}" and bracket_stack[0] == "{":
bracket_stack.pop(0)
body_pos += 1
function_list.append(shader_text[function_return_type:body_pos] + "\n\n")
start = body_pos
return function_list
# find #include statements
def find_includes(file_text, root):
global added_includes
include_list = []
start = 0
while 1:
start = file_text.find("#include", start)
if start == -1:
break
start = file_text.find("\"", start) + 1
end = file_text.find("\"", start)
if start == -1 or end == -1:
break
include_name = file_text[start:end]
include_path = os.path.join(root, include_name)
include_path = sanitize_file_path(include_path)
if include_path not in added_includes:
include_list.append(include_path)
added_includes.append(include_path)
return include_list
# recursively search for #includes
def add_files_recursive(filename, root):
file_path = filename
if not os.path.exists(filename):
file_path = os.path.join(root, filename)
included_file = open(file_path, "r")
shader_source = included_file.read()
included_file.close()
shader_source = sanitize_shader_source(shader_source)
sub_root = os.path.dirname(file_path)
include_list = find_includes(shader_source, sub_root)
for include_file in reversed(include_list):
included_source, sub_includes = add_files_recursive(include_file, sub_root)
shader_source = included_source + "\n" + shader_source
include_list = include_list + sub_includes
return shader_source, include_list
# gather include files and
def create_shader_set(filename, root):
global _info
global added_includes
added_includes = []
shader_file_text, included_files = add_files_recursive(filename, root)
shader_base_name = os.path.basename(filename)
shader_set_dir = os.path.splitext(shader_base_name)[0]
shader_set_build_dir = os.path.join(_info.output_dir, shader_set_dir)
if not os.path.exists(shader_set_build_dir):
os.makedirs(shader_set_build_dir)
return shader_file_text, included_files
# gets constants only for this current permutation
def get_permutation_conditionals(pmfx_json, permutation):
block = pmfx_json.copy()
if "constants" in block:
# find conditionals
conditionals = []
cblock = block["constants"]
for key in cblock.keys():
if key.find("permutation(") != -1:
conditionals.append((key, cblock[key]))
# check conditionals valid
for c in conditionals:
# remove conditional permutation
del block["constants"][c[0]]
full_condition = c[0].replace("permutation", "")
full_condition = full_condition.replace("&&", "and")
full_condition = full_condition.replace("||", "or")
gv = dict()
for v in permutation:
gv[str(v[0])] = v[1]
try:
if eval(full_condition, gv):
block["constants"] = member_wise_merge(block["constants"], c[1])
except NameError:
pass
return block
# get list of technique / permutation specific
def generate_technique_texture_variables(_tp):
technique_textures = []
if "texture_samplers" not in _tp.technique.keys():
return
textures = _tp.technique["texture_samplers"]
for t in textures.keys():
technique_textures.append((textures[t]["type"], t, textures[t]["unit"]))
return technique_textures
# generate cbuffer meta data, c structs for access in code
def generate_technique_constant_buffers(pmfx_json, _tp):
offset = 0
constant_info = [["", 0], ["float", 1], ["float2", 2], ["float3", 3], ["float4", 4], ["float4x4", 16]]
technique_constants = [_tp.technique]
technique_json = _tp.technique
# find inherited constants
if "inherit_constants" in _tp.technique.keys():
for inherit in _tp.technique["inherit_constants"]:
inherit_conditionals = get_permutation_conditionals(pmfx_json[inherit], _tp.permutation)
technique_constants.append(inherit_conditionals)
# find all constants
shader_constant = []
shader_struct = []
pmfx_constants = dict()
for tc in technique_constants:
if "constants" in tc.keys():
# sort constants
sorted_constants = []
for const in tc["constants"]:
for ci in constant_info:
if ci[0] == tc["constants"][const]["type"]:
cc = [const, ci[1]]
pos = 0
for sc in sorted_constants:
if cc[1] > sc[1]:
sorted_constants.insert(pos, cc)
break
pos += 1
if pos >= len(sorted_constants):
sorted_constants.append(cc)
for const in sorted_constants:
const_name = const[0]
const_elems = const[1]
pmfx_constants[const_name] = tc["constants"][const_name]
pmfx_constants[const_name]["offset"] = offset
pmfx_constants[const_name]["num_elements"] = const_elems
shader_constant.append(" " + tc["constants"][const_name]["type"] + " " + "m_" + const_name + ";\n")
shader_struct.append(" " + tc["constants"][const_name]["type"] + " " + "m_" + const_name + ";\n")
offset += const_elems
if offset == 0:
return _tp.technique, "", ""
# we must pad to 16 bytes alignment
pre_pad_offset = offset
diff = offset / 4
next = math.ceil(diff)
pad = (next - diff) * 4
if pad != 0:
shader_constant.append(" " + constant_info[int(pad)][0] + " " + "m_padding" + ";\n")
shader_struct.append(" " + constant_info[int(pad)][0] + " " + "m_padding" + ";\n")
offset += pad
cb_str = "cbuffer material_data : register(b7)\n"
cb_str += "{\n"
for sc in shader_constant:
cb_str += sc
cb_str += "};\n"
# append permutation string to shader c struct
skips = [
_info.shader_platform.upper(),
_info.shader_sub_platform.upper()
]
permutation_name = ""
if int(_tp.id) != 0:
for p in _tp.permutation:
if p[0] in skips or p[0] in caps_list():
continue
if p[1] == 1:
permutation_name += "_" + p[0].lower()
if p[1] > 1:
permutation_name += "_" + p[0].lower() + p[1]
c_struct = "struct " + _tp.technique_name + permutation_name + "\n"
c_struct += "{\n"
for ss in shader_struct:
c_struct += ss
c_struct += "};\n\n"
technique_json["constants"] = pmfx_constants
technique_json["constants_used_bytes"] = int(pre_pad_offset * 4)
technique_json["constants_size_bytes"] = int(offset * 4)
assert int(offset * 4) % 16 == 0
return technique_json, c_struct, cb_str
# removes un-used input structures which may be empty if they have been defined out by permutation.
def strip_empty_inputs(input, main):
conditioned = input.replace("\n", "").replace(";", "").replace(";", "").replace("}", "").replace("{", "")
tokens = conditioned.split(" ")
for t in tokens:
if t == "":
tokens.remove(t)
if len(tokens) == 2:
# input is empty so remove from vs_main args
input = ""
name = tokens[1]
pos = main.find(name)
prev_delim = max(us(main[:pos].rfind(",")), us(main[:pos].rfind("(")))
next_delim = pos + min(us(main[pos:].find(",")), us(main[pos:].find(")")))
main = main.replace(main[prev_delim:next_delim], " ")
return input, main
# gets system value semantics (SV_InstanceID) and stores them in a tuple, for platform specific code gen later.
def get_sv_sematics(main):
supported_sv = ["SV_InstanceID", "SV_VertexID"]
sig = main[main.find("(")+1:main.find(")")]
args = sig.split(',')
sv_semantics = []
for sv in supported_sv:
for arg in args:
if arg.find(sv) != -1:
arg_split = arg.replace(":", " ").strip().split(" ")
var_type = arg_split[0].strip()
var_name = arg_split[1].strip()
sv_semantics.append((sv, var_type, var_name))
return sv_semantics
# evaluate permutation / technique defines in if: blocks and remove unused branches
def evaluate_conditional_blocks(source, permutation):
if not permutation:
return source
pos = 0
case_accepted = False
while True:
else_pos = source.find("else:", pos)
else_if_pos = source.find("else if:", pos)
pos = source.find("if:", pos)
else_case = False
first_case = True
if us(else_if_pos) < us(pos):
pos = else_if_pos
first_case = False
if us(else_pos) < us(pos):
pos = else_pos
else_case = True
first_case = False
if first_case:
case_accepted = False
if pos == -1:
break
if not else_case:
conditions_start = source.find("(", pos)
body_start = source.find("{", conditions_start) + 1
conditions = source[conditions_start:body_start - 1]
conditions = conditions.replace('\n', '')
conditions = conditions.replace("&&", " and ")
conditions = conditions.replace("||", " or ")
conditions = conditions.replace("!", " not ")
else:
body_start = source.find("{", pos) + 1
conditions = "True"
gv = dict()
for v in permutation:
gv[str(v[0])] = v[1]
lv = dict()
conditional_block = ""
i = body_start
stack_size = 1
while True:
if source[i] == "{":
stack_size += 1
if source[i] == "}":
stack_size -= 1
if stack_size == 0:
break
i += 1
if not case_accepted:
while True:
try:
if eval(conditions, gv, lv):
conditional_block = source[body_start:i]
case_accepted = True
break
else:
break
except NameError as e:
defname = re.search("name '([^\']*)' is not defined", str(e)).group(1)
lv[defname] = 0
conditional_block = ""
else:
conditional_block = ""
source = source.replace(source[pos:i+1], conditional_block)
pos += len(conditional_block)
return source
# recursively generate all possible permutations from inputs
def permute(define_list, permute_list, output_permutations):
if len(define_list) == 0:
output_permutations.append(list(permute_list))
else:
d = define_list.pop()
for s in d[1]:
ds = (d[0], s)
permute_list.append(ds)
output_permutations = permute(define_list, permute_list, output_permutations)
if len(permute_list) > 0:
permute_list.pop()
define_list.append(d)
return output_permutations
# generate numerical id for permutation
def generate_permutation_id(define_list, permutation):
pid = 0
for p in permutation:
for d in define_list:
if p[0] == d[0]:
if p[1] > 0:
exponent = d[2]
if exponent < 0:
continue
if p[1] > 1:
exponent = p[1]+exponent-1
pid += pow(2, exponent)
return pid
# return shader version as float for consistent comparisons, version will be a string
def shader_version_float(platform, version):
if platform == "metal":
# metal version is already a float
return float(version)
elif platform == "glsl" or platform == "spirv" or platform == "gles":
# glsl version is integer 330, 400, 450..
return float(version)
elif platform == "hlsl":
# hlsl version is 3_0, 5_0
return float(version.replace("_", "."))
assert 0