-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathpmfx_pipeline.py
1498 lines (1306 loc) · 55.1 KB
/
pmfx_pipeline.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 pmfx as build_pmfx
import cgu
import os
import json
import hashlib
import zlib
import sys
import jsn
from multiprocessing.pool import ThreadPool
# replace warning string with colour coded warning:
def replace_warning(msg):
WARNING = '\033[93m'
ENDC = '\033[0m'
return msg.replace("warning:", WARNING + "warning:" + ENDC)
# replace error string with colour coded error:
def replace_error(msg):
ERROR = '\033[91m'
ENDC = '\033[0m'
return msg.replace("error:", ERROR + "error:" + ENDC)
# colour code the squiggles as warnings
def squiggle_warning(msg):
WARNING = '\033[93m'
ENDC = '\033[0m'
return WARNING + msg + ENDC
# colour code the squiggles as errors
def squiggle_error(msg):
ERROR = '\033[91m'
ENDC = '\033[0m'
return ERROR + msg + ENDC
# return a 32 bit hash from objects which can cast to str
def pmfx_hash(src):
return zlib.adler32(bytes(str(src).encode("utf8")))
# combine 2, 32 bit hashes
def pmfx_hash_combine(h1: int, h2: int) -> int:
combined_data = h1.to_bytes(4, 'little') + h2.to_bytes(4, 'little')
return zlib.adler32(combined_data)
# return names of supported shader stages
def get_shader_stages():
return [
"vs",
"ps",
"cs",
"lib"
]
# return the key of state groups, specified in pmfx
def get_states():
return [
"depth_stencil_states",
"sampler_states",
"render_target_blend_states",
"blend_states",
"raster_states",
"textures",
"views",
"update_graphs",
"render_graphs"
]
# return a lits of bindabled resource keywords
def get_bindable_resource_keys():
return [
"cbuffer",
"ConstantBuffer",
"StructuredBuffer",
"ByteAddressBuffer",
"RWStructuredBuffer",
"RWByteAddressBuffer",
"AppendStructuredBuffer",
"ConsumeStructuredBuffer",
"Texture1D",
"Texture1DArray",
"Texture2D",
"Texture2DArray",
"Texture2DMS",
"Texture2DMSArray",
"TextureCube",
"TextureCubeArray",
"Texture3D",
"RWTexture1D",
"RWTexture1DArray",
"RWTexture2D",
"RWTexture2DArray",
"RWTexture3D",
"SamplerState",
"SamplerComparisonState",
"RaytracingAccelerationStructure"
]
# resource keyword to categroy mapping
def get_resource_mappings():
return [
{"category": "structs", "identifier": "struct"},
{"category": "cbuffers", "identifier": "cbuffer"},
{"category": "cbuffers", "identifier": "ConstantBuffer"},
{"category": "samplers", "identifier": "SamplerState"},
{"category": "samplers", "identifier": "SamplerComparisonState"},
{"category": "structured_buffers", "identifier": "StructuredBuffer"},
{"category": "structured_buffers", "identifier": "ByteAddressBuffer"},
{"category": "structured_buffers", "identifier": "AppendStructuredBuffer"},
{"category": "structured_buffers", "identifier": "ConsumeStructuredBuffer"},
{"category": "structured_buffers", "identifier": "RWStructuredBuffer"},
{"category": "structured_buffers", "identifier": "RWByteAddressBuffer"},
{"category": "textures", "identifier": "Texture1D"},
{"category": "textures", "identifier": "Texture1DArray"},
{"category": "textures", "identifier": "Texture2D"},
{"category": "textures", "identifier": "Texture2DArray"},
{"category": "textures", "identifier": "Texture2DMS"},
{"category": "textures", "identifier": "Texture2DMSArray"},
{"category": "textures", "identifier": "TextureCube"},
{"category": "textures", "identifier": "TextureCubeArray"},
{"category": "textures", "identifier": "Texture3D"},
{"category": "textures", "identifier": "RWTexture1D"},
{"category": "textures", "identifier": "RWTexture1DArray"},
{"category": "textures", "identifier": "RWTexture2D"},
{"category": "textures", "identifier": "RWTexture2DArray"},
{"category": "textures", "identifier": "RWTexture3D"},
{"category": "acceleration_structures", "identifier": "RaytracingAccelerationStructure"},
]
# return list of resource categories
def get_resource_categories():
return [
"structs",
"cbuffers",
"structured_buffers",
"textures",
"samplers",
"acceleration_structures"
]
# return global types we want to check for within source
def get_global_types():
return [
"groupshared"
]
# returns info for types, (num_elements, element_size, total_size)
def get_type_size_info(type):
lookup = {
"float": (1, 4, 4),
"float2": (2, 4, 8),
"float3": (3, 4, 12),
"float4": (4, 4, 16),
"float2x2": (8, 4, 32),
"float3x4": (12, 4, 48),
"float4x3": (12, 4, 48),
"float4x4": (16, 4, 64),
"int": (1, 4, 4),
"int2": (2, 4, 8),
"int3": (3, 4, 12),
"int4": (4, 4, 16),
"uint": (1, 4, 4),
"uint2": (2, 4, 8),
"uint3": (3, 4, 12),
"uint4": (4, 4, 16),
}
return lookup[type]
# return number of 32 bit values for a member of a push constants cbuffer
def get_num_32bit_values(type):
lookup = {
"float": 1,
"float2": 2,
"float3": 3,
"float4": 4,
"float2x2": 8,
"float3x4": 12,
"float4x3": 12,
"float4x4": 16,
"int": 1,
"int2": 2,
"int3": 3,
"int4": 4,
"uint": 1,
"uint2": 2,
"uint3": 3,
"uint4": 4,
}
if type in lookup:
return lookup[type]
return 0
# returns a vertex format type from the data type
def vertex_format_from_type(type):
lookup = {
"float": "R32f",
"float2": "RG32f",
"float3": "RGB32f",
"float4": "RGBA32f",
"half": "R16f",
"half2": "RG16f",
"half3": "RGB16f",
"half4": "RGBA16f",
"int": "R32i",
"int2": "RG32i",
"int3": "RGB32i",
"int4": "RGBA32i",
"uint": "R32u",
"uint2": "RG32u",
"uint3": "RGB32u",
"uint4": "RGBA32u",
}
if type in lookup:
return lookup[type]
assert(0)
return "Unknown"
# shader visibility can be on a single stage or all
def get_shader_visibility(vis):
if len(vis) == 1:
stages = {
"vs": "Vertex",
"ps": "Fragment",
"cs": "Compute",
}
if vis[0] in stages:
return stages[vis[0]]
return "All"
# return the binding type from hlsl register names
def get_binding_type(register_type):
type_lookup = {
"t": "ShaderResource",
"b": "ConstantBuffer",
"u": "UnorderedAccess",
"s": "Sampler"
}
return type_lookup[register_type]
# assign default values to all struct members
def get_state_with_defaults(state_type, state):
state_defaults = {
"depth_stencil_states": {
"depth_enabled": False,
"depth_write_mask": "Zero",
"depth_func": "Always",
"stencil_enabled": False,
"stencil_read_mask": 0,
"stencil_write_mask": 0,
"front_face": {
"fail": "Keep",
"depth_fail": "Keep",
"pass": "Keep",
"func": "Always"
},
"back_face": {
"fail": "Keep",
"depth_fail": "Keep",
"pass": "Keep",
"func": "Always"
}
},
"sampler_states": {
"filter": "Linear",
"address_u": "Wrap",
"address_v": "Wrap",
"address_w": "Wrap",
"comparison": None,
"border_colour": None,
"mip_lod_bias": 0.0,
"max_aniso": 0,
"min_lod": 0.0,
"max_lod": sys.float_info.max
},
"render_target_blend_states": {
"blend_enabled": False,
"logic_op_enabled": False,
"src_blend": "Zero",
"dst_blend": "Zero",
"blend_op": "Add",
"src_blend_alpha": "Zero",
"dst_blend_alpha": "Zero",
"blend_op_alpha": "Add",
"logic_op": "Clear",
"write_mask": {
"bits": (1<<0)|(1<<1)|(1<<2)
}
},
"blend_states": {
"alpha_to_coverage_enabled": False,
"independent_blend_enabled": False,
"render_targets": []
},
"raster_states": {
"fill_mode": "Solid",
"cull_mode": "None",
"front_ccw": False,
"depth_bias": 0,
"depth_bias_clamp": 0.0,
"slope_scaled_depth_bias": 0.0,
"depth_clip_enable": False,
"multisample_enable": False,
"antialiased_line_enable": False,
"forced_sample_count": 0,
"conservative_raster_mode": False,
},
"textures": {
"format": "RGBA8n",
"width": 1,
"height": 1,
"depth": 1,
"array_layers": 1,
"mip_levels": 1,
"samples": 1,
"cubemap": False,
"usage": ["ShaderResource"]
},
"views": {
"viewport": [0.0, 0.0, 1.0, 1.0, 0.0, 1.0],
"scissor": [0.0, 0.0, 1.0, 1.0],
"render_target": list(),
"depth_stencil": list(),
}
}
# converts write_mask: RGBA to bits
if state_type == "render_target_blend_states":
if "write_mask" in state:
bits = 0
if state["write_mask"] == "All":
bits = (1<<4)-1
elif state["write_mask"] != "None":
if "R" in state["write_mask"]:
bits |= (1<<0)
if "G" in state["write_mask"]:
bits |= (1<<1)
if "B" in state["write_mask"]:
bits |= (1<<2)
if "A" in state["write_mask"]:
bits |= (1<<3)
state["write_mask"] = {
"bits": bits
}
if state_type in state_defaults:
default = dict(state_defaults[state_type])
state = merge_dicts(default, state)
state["hash"] = pmfx_hash(state)
return state
# get pipeline with defaults
def get_pipeline_with_defaults(output_pipeline, pipeline):
# topology
if "topology" in pipeline:
output_pipeline["topology"] = pipeline["topology"]
else:
output_pipeline["topology"] = "TriangleList"
# sample mask
if "sample_mask" in pipeline:
output_pipeline["sample_mask"] = pipeline["sample_mask"]
else:
output_pipeline["sample_mask"] = int("0xffffffff", 16)
return output_pipeline
# return identifier names of valid vertex semantics
def get_vertex_semantics():
return [
"BINORMAL",
"BLENDINDICES",
"BLENDWEIGHT",
"COLOR",
"NORMAL",
"POSITION",
"POSITIONT",
"PSIZE",
"TANGENT",
"TEXCOORD"
]
# log formatted json
def log_json(j):
print(json.dumps(j, indent=4), flush=True)
# member wise merge 2 dicts, second will overwrite dest will append items in arrays
def merge_dicts(dest, second, extend = []):
for k, v in second.items():
if type(v) == dict:
if k not in dest or type(dest[k]) != dict:
dest[k] = dict()
merge_dicts(dest[k], v, extend)
elif k in dest and k in extend and type(v) == list and type(dest[k]) == list:
dest[k].extend(v)
else:
dest[k] = v
return dest
# retuns the array size of a descriptor binding -1 can indicate unbounded, which translates to None
def get_descriptor_array_size(resource):
if "array_size" in resource:
if resource["array_size"] == -1:
return None
else:
if resource["array_size"] != None:
return resource["array_size"]
return 1
# parses the register for the resource unit, ie. : register(t0)
def parse_register(type_dict):
rp = cgu.find_token("register", type_dict["declaration"])
type_dict["shader_register"] = None
type_dict["register_type"] = None
type_dict["register_space"] = 0
if rp != -1:
start, end = cgu.enclose_start_end("(", ")", type_dict["declaration"], rp)
decl = type_dict["declaration"][start:end]
multi = decl.split(",")
for r in multi:
r = r.strip()
if r.find("space") != -1:
type_dict["register_space"] = cgu.separate_alpha_numeric(r)[1]
else:
type_dict["register_type"], type_dict["shader_register"] = cgu.separate_alpha_numeric(r)
# local resource decl will not contain a register mapping, structs do not bind to registers but they declare members
def is_local_resource_decl(type_dict):
parse_register(type_dict)
if type_dict["register_type"] == None:
if len(type_dict["members"]) == 0:
return True
return False
# parses a type and generates a vertex layout, array of elements with sizes and offsets
def generate_vertex_layout_slot(members):
offset = 0
layout = list()
for member in members:
semantic_name, semantic_index = cgu.separate_alpha_numeric(member["semantic"])
_, _, size = get_type_size_info(member["data_type"])
# pers instance step rate default is 0 and per instance is 1
default_step = member["step_rate"]
if member["input_slot_class"] == "PerInstance" and default_step == 0:
default_step = 1
input = {
"name": member["name"],
"semantic": semantic_name,
"index": semantic_index,
"format": vertex_format_from_type(member["data_type"]),
"aligned_byte_offset": offset,
"input_slot": member["input_slot"],
"input_slot_class": member["input_slot_class"],
"step_rate": default_step
}
offset += size
layout.append(input)
return layout
# generate a vertex layout from the supplied vertex shader inputs, overriding where specified in the pmfx
def generate_vertex_layout(vertex_elements, pmfx_vertex_layout):
# gather up individual slots
slots = {
}
for element in vertex_elements:
if element["parent"] in pmfx_vertex_layout:
element = merge_dicts(element, pmfx_vertex_layout[element["parent"]])
if element["name"] in pmfx_vertex_layout:
element = merge_dicts(element, pmfx_vertex_layout[element["name"]])
slot_key = str(element["input_slot"])
if slot_key not in slots.keys():
slots[slot_key]= []
slots[slot_key].append(element)
# make 1 array with combined slots, and calculate offsets
vertex_layout = []
for slot in slots.values():
vertex_layout.extend(generate_vertex_layout_slot(slot))
return vertex_layout
# get a list of vertex elements deduced from the input arguments to a vertex shader, ready to be generated into a vertex layout with pipeline specified slot overrides
def get_vertex_elements(pmfx, entry_point):
slot = 0
elements = []
for input in pmfx["functions"][entry_point]["args"]:
t = input["type"]
# gather struct inputs
if t in pmfx["resources"]["structs"]:
is_vertex = True
for member in pmfx["resources"]["structs"][t]["members"]:
semantic, _ = cgu.separate_alpha_numeric(member["semantic"])
if semantic not in get_vertex_semantics():
is_vertex = False
if is_vertex:
for member in pmfx["resources"]["structs"][t]["members"]:
member_input = dict(member)
member_input["parent"] = t
member_input["input_slot"] = slot
member_input["input_slot_class"] = "PerVertex"
member_input["step_rate"] = 0
elements.append(member_input)
slot += 1
else:
# gather single elements
semantic, _ = cgu.separate_alpha_numeric(input["semantic"])
if semantic in get_vertex_semantics():
arg_input = dict(input)
arg_input["parent"] = "args"
arg_input["data_type"] = arg_input["type"]
arg_input["input_slot"] = slot
arg_input["input_slot_class"] = "PerVertex"
arg_input["step_rate"] = 0
elements.append(arg_input)
return elements
# recurses through nested structure to reach and sum the number of 32bit values from primitive types
def structure_get_num_32_bit_values(typename, structs):
if typename in structs:
total = 0
for member in structs[typename]["members"]:
total += structure_get_num_32_bit_values(member["data_type"], structs)
return total
else:
value = get_num_32bit_values(typename)
if value == 0:
print(json.dumps(structs, indent=4))
print("mssing member {}".format(typename))
assert(0)
return value
# builds a descriptor set from resources used in the pipeline
def generate_pipeline_layout(pmfx, pmfx_pipeline, resources):
bindable_resources = get_bindable_resource_keys()
pipeline_layout = {
"bindings": [],
"push_constants": [],
"static_samplers": []
}
for r in resources:
resource = resources[r]
resource_type = resource["type"]
# check if we have flagged resource as push constants
if "push_constants" in pmfx_pipeline:
if r in pmfx_pipeline["push_constants"]:
# work out how many 32 bit values
num_values = 0
for member in resource["members"]:
num_values += get_num_32bit_values(member["data_type"])
# we need to lookup a templated data type
if num_values == 0:
if "template_type" in resource:
t = resource["template_type"]
num_values = structure_get_num_32_bit_values(t, resources)
push_constants = {
"shader_register": resource["shader_register"],
"register_space": resource["register_space"],
"binding_type": get_binding_type(resource["register_type"]),
"visibility": get_shader_visibility(resource["visibility"]),
"num_values": num_values,
"name": resource["name"]
}
pipeline_layout["push_constants"].append(push_constants)
continue
if "static_samplers" in pmfx_pipeline:
if r in pmfx_pipeline["static_samplers"]:
lookup = pmfx_pipeline["static_samplers"][r]
static_sampler = {
"shader_register": resource["shader_register"],
"register_space": resource["register_space"],
"visibility": get_shader_visibility(resource["visibility"]),
"sampler_info": pmfx["sampler_states"][lookup],
"name": resource["name"]
}
pipeline_layout["static_samplers"].append(static_sampler)
continue
# fall trhough and add as a bindable resource
if resource_type in bindable_resources:
binding = {
"shader_register": resource["shader_register"],
"register_space": resource["register_space"],
"binding_type": get_binding_type(resource["register_type"]),
"visibility": get_shader_visibility(resource["visibility"]),
"num_descriptors": get_descriptor_array_size(resource),
"name": resource["name"]
}
pipeline_layout["bindings"].append(binding)
# combine bindings on the same slot (allow resource type aliasing)
combined_bindings = dict()
for binding in pipeline_layout["bindings"]:
bh = pmfx_hash({
"shader_register": binding["shader_register"],
"register_space": binding["register_space"],
"binding_type": binding["binding_type"]
})
if bh not in combined_bindings:
combined_bindings[bh] = dict(binding)
else:
cur = combined_bindings[bh]
# extend visibility
if binding["visibility"] != cur["visibility"]:
cur["visibility"] = "All"
# sort bindings in index order
sorted_bindings = list()
for binding in combined_bindings.values():
sorted_bindings.append(binding)
# bubble sort sort them
sorted = False
while not sorted:
sorted = True
for i in range(0, len(sorted_bindings) - 1):
j = i + 1
if sorted_bindings[j]["shader_register"] < sorted_bindings[i]["shader_register"]:
temp = sorted_bindings[j]
sorted_bindings[j] = dict(sorted_bindings[i])
sorted_bindings[i] = dict(temp)
sorted = False
pipeline_layout["bindings"] = list(sorted_bindings)
return pipeline_layout
# wrtie out c++ header from the json info
def write_header(path, pmfx_name, resources):
src_h = cgu.src_line("namespace pmfx_{} {{".format(pmfx_name))
if "structs" in resources:
for struct_name, struct in resources["structs"].items():
if "members" in struct:
src_h += cgu.src_line("struct {} {{".format(struct_name))
for member in struct["members"]:
src_h += cgu.src_line("{} {};".format(member["data_type"], member["name"]))
src_h += cgu.src_line("};")
src_h += cgu.src_line("}")
src_h = cgu.format_source(src_h, 4)
os.makedirs(path, exist_ok=True)
open(os.path.join(path, "{}.h".format(pmfx_name)), "w+").write(src_h)
# wrtie out rust crate from the json info
def write_rs_crate(path, pmfx_name, resources):
src_h = cgu.src_line("pub mod pmfx_{} {{".format(pmfx_name))
if "structs" in resources:
for struct_name, struct in resources["structs"].items():
if "members" in struct:
src_h += cgu.src_line("#[repr(C)]")
src_h += cgu.src_line("pub struct {} {{".format(struct_name))
for member in struct["members"]:
src_h += cgu.src_line("{}: {},".format(member["name"], member["data_type"]))
src_h += cgu.src_line("}")
src_h += cgu.src_line("}")
src_h = cgu.format_source(src_h, 4)
os.makedirs(path, exist_ok=True)
open(os.path.join(path, "{}.rs".format(pmfx_name)), "w+").write(src_h)
# parse metal specific options from command lines, returning (metal_sdk, metal_min_os, metal_version)
def metal_compile_options(info):
# default to metal 2.0, but allow cmdline override
metal_version = info.metal_version
# selection of sdk, macos, ios, tvos
metal_sdk = "macosx"
if info.metal_sdk != "":
metal_sdk = info.metal_sdk
# insert some defaults fo version min based on os
metal_min_os = ""
if metal_sdk == "macosx":
metal_min_os = "10.11"
if info.metal_min_os != "":
metal_min_os = info.metal_min_os
metal_min_os = "-mmacosx-version-min=" + metal_min_os
elif metal_sdk == "iphoneos":
metal_min_os = "9.0"
if info.metal_min_os != "":
metal_min_os = info.metal_min_os
metal_min_os = "-mios-version-min=" + metal_min_os
elif metal_sdk == "appletvos":
metal_min_os = "13.0"
if info.metal_min_os != "":
metal_min_os = info.metal_min_os
metal_min_os = "-mtvos-version-min=" + metal_min_os
# finally set metal -std.
if metal_sdk == "iphoneos" or metal_sdk == "appletvos":
metal_version = "-std=ios-metal" + metal_version
else:
metal_version = "-std=macos-metal" + metal_version
return metal_sdk, metal_min_os, metal_version
# convert msl version (ie. 2.1) to spriv msl version 201000 <MMmmpp>
def to_spirv_msl_version(metal_version):
# spirv msl versions
msl_version = metal_version.split(".")
if len(msl_version) < 3:
msl_version.append("00")
spirv_msl_version = ""
for v in msl_version:
if len(v) < 2:
v += "0"
spirv_msl_version += v
return spirv_msl_version
# cross compile hlsl -> spirv -> metal
def cross_compile_hlsl_metal(info, src, stage, entry_point, temp_filepath, output_filepath):
exe = os.path.join(info.tools_dir, "bin", "macos", "dxc")
metal_sdk, metal_min_os, metal_version = metal_compile_options(info)
error_code = 0
error_list = []
output_list = []
spirv_cross = os.path.join(info.tools_dir, "bin", "macos", "spirv-cross")
spirv_filepath = os.path.splitext(temp_filepath)[0] + ".spirv"
cmdline = "{} -T {}_{} -E {} -spirv -Fo {} {}".format(exe, stage, info.shader_version, entry_point, spirv_filepath, temp_filepath)
ec, el, ol = build_pmfx.call_wait_subprocess(cmdline)
error_list += el
output_list += ol
spirv_msl_version = to_spirv_msl_version(info.metal_version)
metal_filepath = os.path.splitext(temp_filepath)[0] + ".metal"
cmdline = "{} --msl --msl-version {} {} --output {}".format(spirv_cross, spirv_msl_version, spirv_filepath, metal_filepath)
ec, el, ol = build_pmfx.call_wait_subprocess(cmdline)
error_list += el
output_list += ol
air_filepath = os.path.splitext(temp_filepath)[0] + ".air"
cmdline = "xcrun -sdk {} metal {} {} -c -frecord-sources {} -o {}".format(metal_sdk, metal_min_os, metal_version, metal_filepath, air_filepath)
ec, el, ol = build_pmfx.call_wait_subprocess(cmdline)
error_list += el
output_list += ol
cmdline = "xcrun -sdk {} metal {} -o {}".format(metal_sdk, air_filepath, output_filepath)
ec, el, ol = build_pmfx.call_wait_subprocess(cmdline)
error_list += el
output_list += ol
return 0, error_list, output_list
# compile a hlsl version 2
def compile_shader_hlsl(info, src, stage, entry_point, temp_filepath, output_filepath):
exe = os.path.join(info.tools_dir, "bin", "dxc", "dxc")
open(temp_filepath, "w+").write(src)
# compile... or skip
error_code = 0
error_list = []
output_list = []
if info.compiled:
if info.shader_platform == "metal":
error_code, error_list, output_list = cross_compile_hlsl_metal(info, src, stage, entry_point, temp_filepath, output_filepath)
elif info.shader_platform == "hlsl":
cmdline = "{} -T {}_{} -E {} -Fo {} {}".format(exe, stage, info.shader_version, entry_point, output_filepath, temp_filepath)
cmdline += " " + build_pmfx.get_info().args
error_code, error_list, output_list = build_pmfx.call_wait_subprocess(cmdline)
output = ""
if len(error_list) > 0:
# build output string from error
output = "\n"
msg_type = ""
for err in error_list:
# highlight errors
err = replace_error(err)
err = replace_warning(err)
# switch between wanring and error colour coding
if err.find("warning:") != -1:
msg_type = "warning:"
elif err.find("error:") != -1:
msg_type = "error:"
# add squiggles
if err.find("^") != -1:
if msg_type == "error:":
err = squiggle_error(err)
if msg_type == "warning:":
err = squiggle_warning(err)
output += " " + err + "\n"
output = output.strip("\n").strip()
elif len(output_list) > 0:
# build output string from output message
output = "\n"
for out in output_list:
output += " " + out + "\n"
output = output.strip("\n").strip()
basename = os.path.basename(output_filepath)
if len(output) > 0:
print(" compiling: {}\n {}".format(basename, output), flush=True)
else:
print(" compiling: {}".format(basename), flush=True)
return error_code
# add shader resource for the shader stage
def add_used_shader_resource(resource, stage):
output = dict(resource)
if "visibility" not in output:
output["visibility"] = list()
output["visibility"].append(stage)
return output
# add somesbuilt in defines for convenience
def add_built_in_defines(src):
defines = [
"#define pmfx_touch(value) (void)(value)"
]
define_src = ""
for define in defines:
define_src += define + "\n"
src = define_src + "\n" + src
return src
# adds structs to respurces recursively
def add_struct_members_recursive(typename, stage, structs, resources, depth):
if typename in structs and typename not in resources:
resources[typename] = add_used_shader_resource(structs[typename], stage)
resources[typename]["depth"] = depth
for member in structs[typename]["members"]:
add_struct_members_recursive(member["data_type"], stage, structs, resources, depth + 1)
# given an entry point generate src code and resource meta data for the shader
def generate_shader_info(pmfx, entry_point, stage, permute=None):
# resource categories
resource_categories = get_resource_categories()
# validate entry point
if entry_point not in pmfx["functions"]:
build_pmfx.print_error(" error: missing shader entry point: {}".format(entry_point))
return None
# start globals then with entry point src code
src = pmfx["functions"][entry_point]["source"]
# grab any attributes
attribs = pmfx["functions"][entry_point]["attributes"]
resources = dict()
recursive_resources = dict()
vertex_elements = None
# recursively insert used functions
complete = False
added_functions = [entry_point]
forward_decls = []
while not complete:
if permute:
# evaluate permutations each iteration to remove all dead code
src = build_pmfx.evaluate_conditional_blocks(src, permute)
complete = True
for func in pmfx["functions"]:
if func not in added_functions:
if cgu.find_token(func, src) != -1:
fwd = pmfx["functions"][func]["source"].replace(pmfx["functions"][func]["body"], ";")
forward_decls.append(fwd)
added_functions.append(func)
# add attributes
src = pmfx["functions"][func]["source"] + "\n" + src
complete = False
break
# now add used resource src decls
for category in resource_categories:
for r in pmfx["resources"][category]:
tokens = [r]
resource = pmfx["resources"][category][r]
# cbuffers with inline decl need to check for usage per member
if category == "cbuffers":
for member in resource["members"]:
tokens.append(member["name"])
# types with templates need to include structs
if cgu.find_token(resource["name"], src) != -1:
if resource["template_type"] and resource["type"] != "struct":
template_typeame = resource["template_type"]
if template_typeame in pmfx["resources"]["structs"]:
struct_resource = pmfx["resources"]["structs"][template_typeame]
resources[template_typeame] = add_used_shader_resource(struct_resource, stage)
add_struct_members_recursive(template_typeame, stage, pmfx["resources"]["structs"], recursive_resources, 0)
# add resource and append resource src code
for token in tokens:
p = cgu.find_token(token, src)
if p != -1:
# ignore struct member refernces with names which collide with cbuffer members
if resource["type"] == "cbuffer":
if cgu.find_prev_non_whitespace(src, p) == ".":
continue
# add nested members
if resource["type"] == "cbuffer" or resource["type"] == "struct":
for member in resource["members"]:
add_struct_members_recursive(member["data_type"], stage, pmfx["resources"]["structs"], recursive_resources, 1)
# add the resource itself
resources[r] = add_used_shader_resource(resource, stage)
break
# add any globals..
globals = ""
for g in pmfx["globals"]:
globals += g + "\n"
# create resource src code
res = ""
# adds built in pmfx defines
res = add_built_in_defines(res)
# pragmas
if len(pmfx["pragmas"]) > 0:
res += "// pragmas\n"
for pragma in pmfx["pragmas"]:
res += "{}\n".format(pragma)
# resources input structs, textures, buffers etc
added_resources = []
if len(resources) > 0:
res += "// resource declarations\n"
for resource in recursive_resources:
if resource in added_resources:
continue
if recursive_resources[resource]["depth"] > 0:
res += recursive_resources[resource]["declaration"] + ";\n"
added_resources.append(resource)
for resource in resources:
if resource in added_resources:
continue
res += resources[resource]["declaration"] + ";\n"
added_resources.append(resource)
# extract vs_input (input layout)
if stage == "vs":
vertex_elements = get_vertex_elements(pmfx, entry_point)
# typedefs
typedef_decls = cgu.find_typedef_decls(pmfx["source"])
if len(typedef_decls) > 0:
res += "// typedefs\n"
for typedef_decl in typedef_decls:
res += typedef_decl + ";\n"
# add fwd function decls
if len(forward_decls) > 0:
res += "// function foward declarations\n"
for fwd in forward_decls:
res += fwd + "\n"
# join resource src and src
src = cgu.format_source(res, 4) + "\n // source\n" + globals + "\n" + cgu.format_source(src, 4)
if permute:
# evaluate permutations on the full source including resources
src = build_pmfx.evaluate_conditional_blocks(src, permute)
src = cgu.format_source(src, 4)
return {
"src": src,
"src_hash": hashlib.md5(src.encode("utf-8")).hexdigest(),
"resources": merge_dicts(dict(resources), dict(recursive_resources)),
"vertex_elements": vertex_elements,
"attributes": attribs