-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgen_c.py
More file actions
1459 lines (1228 loc) · 43.1 KB
/
gen_c.py
File metadata and controls
1459 lines (1228 loc) · 43.1 KB
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 enum
import json
import math
import sys
from dataclasses import dataclass
from itertools import filterfalse, tee
from pathlib import Path
from types import SimpleNamespace
from typing import Optional
def partition(predicate, iterable):
"""Partition entries into false entries and true entries.
If *predicate* is slow, consider wrapping it with functools.lru_cache().
"""
# partition(is_odd, range(10)) → 0 2 4 6 8 and 1 3 5 7 9
t1, t2 = tee(iterable)
return filterfalse(predicate, t1), filter(predicate, t2)
@dataclass
class Constant:
name: str
value: str
doc: str
@dataclass
class Typedef:
name: str
doc: str
type: str
@dataclass
class EnumEntry:
name: str
doc: str
value: Optional[str]
@dataclass
class Enum:
name: str
doc: str
entries: list[EnumEntry]
extended: bool
@dataclass
class BitflagEntry:
name: str
doc: str
value: str
value_combination: list[str]
@dataclass
class Bitflag:
name: str
doc: str
entries: list[BitflagEntry]
extended: bool
class PointerType(enum.StrEnum):
MUTABLE = "mutable"
IMMUTABLE = "immutable"
@dataclass
class ParameterType:
name: str
doc: str
type: str
pointer: Optional[PointerType]
optional: bool
@dataclass
class Callback:
name: str
doc: str
style: str
args: list[ParameterType]
@dataclass
class Function:
name: str
doc: str
returns: ParameterType
args: list[ParameterType]
returns_async: list[ParameterType]
@dataclass
class Struct:
name: str
type: str
doc: str
free_members: bool
members: list[ParameterType]
@dataclass
class Object:
name: str
doc: str
methods: list[Function]
extended: bool
namespace: str
@dataclass
class Spec:
copyright: str
name: str
enum_prefix: str
constants: list[Constant]
# currently empty
typedefs: list[Typedef]
enums: list[Enum]
bitflags: list[Bitflag]
structs: list[Struct]
callbacks: list[Callback]
functions: list[Function]
objects: list[Object]
function_types: list[Function]
def load_spec(path: Path) -> Spec:
with open(path, "r") as f:
return json.load(f, object_hook=lambda d: SimpleNamespace(**d))
def gen_enum(entry: Enum) -> str:
doc = (
""
if entry.doc.strip() == "TODO"
else f"""\"\"\"\n {entry.doc.strip()}\"\"\"\n"""
)
output = f"""
@fieldwise_init
@register_passable("trivial")
struct {entry.name.title().replace("_", "")}(Copyable, EqualityComparable, ImplicitlyCopyable, Movable, Writable):
{doc}
var value: UInt32
fn __eq__(self, rhs: Self) -> Bool:
return self.value == rhs.value
"""
for i, e in enumerate(entry.entries):
ename = e.name.lower()
if entry.name == "texture_view_dimension" or entry.name == "texture_dimension":
ename = ename[::-1]
output += (
f" comptime {ename} = Self({e.value if hasattr(e, 'value') else i})\n"
)
if e.doc.strip() != "TODO":
output += f' """{e.doc.strip()}"""\n'
output += """\n fn write_to(self, mut w: Some[Writer]):\n"""
for i, e in enumerate(entry.entries):
ename = e.name.lower()
if entry.name == "texture_view_dimension" or entry.name == "texture_dimension":
ename = ename[::-1]
output += f"""
{"" if i == 0 else "el"}if self == Self.{ename}:
w.write("{ename}")
"""
return output
def gen_bitflag(entry: Bitflag) -> str:
doc = (
""
if entry.doc.strip() == "TODO"
else f"""\"\"\"\n {entry.doc.strip()}\"\"\"\n"""
)
output = f"""
@fieldwise_init
@register_passable("trivial")
struct {entry.name.title().replace("_", "")}(Copyable, EqualityComparable, ImplicitlyCopyable, Movable):
{doc}
var value: UInt32
fn __eq__(self, rhs: Self) -> Bool:
return self.value == rhs.value
fn __ne__(self, rhs: Self) -> Bool:
return self.value != rhs.value
fn __xor__(self, rhs: Self) -> Self:
return Self(self.value ^ rhs.value)
fn __and__(self, rhs: Self) -> Self:
return Self(self.value & rhs.value)
fn __or__(self, rhs: Self) -> Self:
return Self(self.value | rhs.value)
fn __invert__(self) -> Self:
return Self(~self.value)
"""
for i, e in enumerate(entry.entries):
if hasattr(e, "value_combination"):
combination = " | ".join(f"Self.{val}" for val in e.value_combination)
output += f" comptime {e.name.lower()} = {combination}\n"
else:
output += f" comptime {e.name.lower()} = Self({int(math.pow(2, int(e.value) if hasattr(e, 'value') else i - 1))})\n"
if e.doc.strip() != "TODO":
output += f' """{e.doc.strip()}"""\n'
return output
def gen_constant(entry: Constant) -> str:
match entry.value:
case "uint32_max":
val = "UInt32.MAX"
case "uint64_max":
val = "UInt64.MAX"
case "usize_max":
val = "Int.MAX"
case _:
val = entry.value
doc = (
""
if entry.doc.strip() == "TODO"
else f"""\"\"\"\n{entry.doc.strip()}\"\"\"\n"""
)
return f"""
comptime {entry.name.upper()} = {val}
{doc}
"""
def sanitize_name(
name: str,
object_pointer: bool = True,
struct_pointer: bool = False,
with_origin: bool = False,
) -> str:
if name.startswith("enum."):
return name.removeprefix("enum.").title().replace("_", "")
elif name.startswith("bitflag."):
return name.removeprefix("bitflag.").title().replace("_", "")
elif name.startswith("struct."):
if struct_pointer:
n = name.removeprefix("struct.").title().replace("_", "")
if with_origin:
return f"FFIPointer[WGPU{n}, mut=True]"
else:
return f"FFIPointer[WGPU{n}]"
else:
return "WGPU" + name.removeprefix("struct.").title().replace("_", "")
elif name.startswith("function_type."):
return name.removeprefix("function_type.").title().replace("_", "")
elif name.startswith("object."):
if object_pointer:
n = name.removeprefix("object.").title().replace("_", "")
return f"WGPU{n}"
else:
return name.removeprefix("object.").title().replace("_", "")
elif name == "string":
return "FFIPointer[Int8, mut=False]"
elif name == "uint32":
return "UInt32"
elif name == "uint16":
return "UInt16"
elif name == "int16":
return "Int16"
elif name == "uint64":
return "UInt64"
elif name == "int32":
return "Int32"
elif name == "int64":
return "Int64"
elif name == "bool":
return "Bool"
elif name == "float32":
return "Float32"
elif name == "float64":
return "Float64"
elif name == "usize":
return "Int"
elif name == "c_void":
return "FFIPointer[NoneType, mut=True]"
else:
return name
def gen_parameter_type(
entry: ParameterType,
*,
default_assign: bool = False,
type_only: bool = False,
object_pointer: bool = True,
struct_pointer: bool = False,
in_function: bool = False,
with_origin: bool = False,
) -> str:
ty = sanitize_name(
entry.type,
object_pointer=object_pointer,
struct_pointer=struct_pointer,
with_origin=with_origin,
)
if hasattr(entry, "pointer"):
if "array<" in entry.type:
ty = sanitize_name(
entry.type.removeprefix("array<").removesuffix(">"),
object_pointer=object_pointer,
struct_pointer=struct_pointer,
with_origin=with_origin,
)
if with_origin:
mutability = "True" if entry.pointer == "mutable" else "False"
ty = f"FFIPointer[{ty}, mut={mutability}]"
else:
ty = f"FFIPointer[{ty}]"
else:
ty = f"{ty}"
if type_only:
if in_function and entry.type.startswith("array<"):
return f"Int32, {ty}"
return ty
res = f"""{entry.name}: {ty}"""
if in_function and entry.type.startswith("array<"):
res = f"{entry.name[:-1]}_count: Int{' = Int()' if hasattr(entry, 'optional') else ''}, {res}"
if hasattr(entry, "optional") and default_assign:
res = f"{res} = {{}}"
return res
def gen_function(
entry: Function,
contains_self: bool = False,
type: Optional[str] = None,
prefix: Optional[str] = None,
) -> str:
args = entry.args if hasattr(entry, "args") else []
args_ordered = partition(lambda x: hasattr(x, "optional"), args)
params_pre_opt = ", ".join(
gen_parameter_type(
e,
default_assign=True,
in_function=True,
struct_pointer=True,
with_origin=True,
)
for e in args_ordered[0]
)
params_post_opt = ", ".join(
gen_parameter_type(
e,
default_assign=True,
in_function=True,
struct_pointer=True,
with_origin=True,
)
for e in args_ordered[1]
)
if hasattr(entry, "returns_async"):
ret_async = entry.returns_async
cb_params = ", ".join(
gen_parameter_type(
e,
default_assign=True,
type_only=True,
struct_pointer=True,
in_function=True,
with_origin=True,
)
for e in ret_async
)
cb_params += ", FFIPointer[NoneType, mut=True]"
cb_params_arg = ", ".join(
gen_parameter_type(
e,
default_assign=True,
object_pointer=True,
type_only=True,
struct_pointer=True,
in_function=True,
with_origin=True,
)
for e in ret_async
)
cb_params_arg += ", FFIPointer[NoneType, mut=True]"
params = ", ".join(
a
for a in [
params_pre_opt,
f"callback: fn({cb_params_arg}) -> None, user_data: FFIPointer[NoneType, mut=True]",
params_post_opt,
]
if a
)
else:
params = ", ".join(a for a in [params_pre_opt, params_post_opt] if a)
ret_async = None
if contains_self:
params = f"handle: WGPU{type}, {params}"
try:
ret = gen_parameter_type(
entry.returns, type_only=True, object_pointer=True, with_origin=True
)
except:
ret = "None"
arg_names = [
[f"{e.name[:-1]}_count", e.name] if e.type.startswith("array<") else [e.name]
for e in args
]
arg_names = [arg for arg_item in arg_names for arg in arg_item]
if contains_self:
arg_names.insert(0, "handle")
if ret_async:
arg_names.append("callback")
arg_names.append("user_data")
call_args = ", ".join(arg_names)
types = ", ".join(f"type_of({arg})" for arg in arg_names)
return f"""
fn {prefix + "_" if prefix else ""}{entry.name}({params}) -> {ret}:
\"\"\"
{entry.doc.strip()}
\"\"\"
{"return" if ret != "None" else "_ = "} external_call["wgpu{type or ""}{entry.name.title().replace("_", "")}", {ret if ret != "None" else "NoneType"}, {types}]({call_args})
"""
def gen_callback(entry: Callback):
args = entry.args if hasattr(entry, "args") else []
params_no_default = ", ".join(
gen_parameter_type(e, type_only=True, in_function=True) for e in args
)
return f"\ncomptime {entry.name}_callback = fn({params_no_default}) -> None\n"
def gen_object(entry: Object) -> str:
name = entry.name.title().replace("_", "")
output = f"""
struct _{name}Impl:
pass
comptime WGPU{name} = FFIPointer[_{name}Impl, mut=True]
fn {entry.name}_release(handle: WGPU{name}):
_ = external_call["wgpu{name}Release", NoneType, type_of(handle)](handle)
"""
for method in entry.methods:
output += gen_function(method, type=name, contains_self=True, prefix=entry.name)
return output
def gen_struct(entry: Struct) -> str:
output = f"""
struct WGPU{entry.name.title().replace("_", "")}(Copyable, ImplicitlyCopyable, Movable):
\"\"\"
{entry.doc.strip()}
\"\"\"
"""
if entry.type == "base_in":
output += " var next_in_chain: FFIPointer[ChainedStruct, mut=True]\n"
elif entry.type == "base_out":
output += " var next_in_chain: FFIPointer[ChainedStructOut, mut=True]\n"
elif entry.type == "extension_in":
output += " var chain: ChainedStruct\n"
elif entry.type == "extension_out":
output += " var chain: ChainedStructOut\n"
members = entry.members if hasattr(entry, "members") else []
for member in members:
if member.type.startswith("function_type."):
output += f" var {member.name}: FFIPointer[NoneType, mut=True]\n"
elif member.type.startswith("array<"):
output += f" var {member.name[:-1]}_count: Int\n"
output += f" var {gen_parameter_type(member, struct_pointer=False, with_origin=True)}\n"
else:
output += f" var {gen_parameter_type(member, struct_pointer=hasattr(member, 'pointer'), with_origin=True)}\n"
output += "\n fn __init__(out self,\n"
if entry.type == "base_in":
output += " next_in_chain: FFIPointer[ChainedStruct, mut=True] = {},\n"
elif entry.type == "base_out":
output += (
" next_in_chain: FFIPointer[ChainedStructOut, mut=True] = {},\n"
)
elif entry.type == "extension_in":
output += " chain: ChainedStruct = {},\n"
elif entry.type == "extension_out":
output += " chain: ChainedStructOut = {}\n"
for member in members:
if member.type.startswith("enum.") or member.type.startswith("bitflag."):
ty = gen_parameter_type(member, type_only=True, with_origin=True)
output += f"\n {member.name}: {ty} = {ty}(0),\n"
elif member.type == "bool":
output += f"\n {member.name}: Bool = False,"
elif member.type.startswith("function_type."):
output += (
f"\n {member.name}: FFIPointer[NoneType, mut=True] = {{}},\n"
)
elif member.type.startswith("array<"):
ty = gen_parameter_type(
member, type_only=True, struct_pointer=False, with_origin=True
)
output += f"\n {member.name[:-1]}_count: Int = Int(),\n"
output += f"\n {member.name}: {ty} = {{}},\n"
else:
ty = gen_parameter_type(
member,
type_only=True,
struct_pointer=hasattr(member, "pointer"),
with_origin=True,
)
owned = (
"var "
if member.type.startswith("struct.") and not hasattr(member, "pointer")
else ""
)
output += f"\n {owned}{member.name}: {ty} = {{}},\n"
output += " ):\n"
if entry.type == "base_in":
output += " self.next_in_chain = next_in_chain\n"
elif entry.type == "base_out":
output += " self.next_in_chain = next_in_chain\n"
elif entry.type == "extension_in":
output += " self.chain = chain\n"
elif entry.type == "extension_out":
output += " self.chain = chain\n"
for member in members:
take = (
"^"
if member.type.startswith("struct") and not hasattr(member, "pointer")
else ""
)
if member.type.startswith("array<"):
output += (
f" self.{member.name[:-1]}_count = {member.name[:-1]}_count\n"
)
output += f" self.{member.name} = {member.name}{take}\n"
return output
def gen_function_type(entry: Function) -> str:
cb_params_arg = ", ".join(
gen_parameter_type(
e,
default_assign=True,
object_pointer=True,
type_only=True,
struct_pointer=True,
)
for e in entry.args
)
cb_params_arg += ", FFIPointer[NoneType, mut=True]"
return f"comptime {entry.name.title().replace('_', '')} = fn({cb_params_arg}) -> None\n"
if __name__ == "__main__":
spec_path = Path.cwd() / (sys.argv[1])
spec = load_spec(spec_path)
enums = "\n".join(gen_enum(e) for e in spec.enums)
enums += """
# WGPU SPECIFIC ENUMS
@fieldwise_init
@register_passable("trivial")
struct NativeSType(Copyable, ImplicitlyCopyable, Movable, EqualityComparable):
var value: UInt32
fn __eq__(self, rhs: Self) -> Bool:
return self.value == rhs.value
# Start at 0003 since that's allocated range for wgpu-native
comptime device_extras = Self(0x00030001)
comptime required_limits_extras = Self(0x00030002)
comptime pipeline_layout_extras = Self(0x00030003)
comptime shader_module_glsl_descriptor = Self(0x00030004)
comptime supported_limits_extras = Self(0x00030005)
comptime instance_extras = Self(0x00030006)
comptime bind_group_entry_extras = Self(0x00030007)
comptime bind_group_layout_entry_extras = Self(0x00030008)
comptime query_set_descriptor_extras = Self(0x00030009)
comptime surface_configuration_extras = Self(0x0003000A)
@fieldwise_init
@register_passable("trivial")
struct NativeFeature(Copyable, ImplicitlyCopyable, Movable, EqualityComparable):
var value: Int
fn __eq__(self, rhs: Self) -> Bool:
return self.value == rhs.value
comptime push_constants = Self(0x00030001)
comptime texture_adapter_specific_format_features = Self(0x00030002)
comptime multi_draw_indirect = Self(0x00030003)
comptime multi_draw_indirect_count = Self(0x00030004)
comptime vertex_writable_storage = Self(0x00030005)
comptime texture_binding_array = Self(0x00030006)
comptime sampled_texture_and_storage_buffer_array_non_uniform_indexing = Self(
0x00030007
)
comptime pipeline_statistics_query = Self(0x00030008)
comptime storage_resource_binding_array = Self(0x00030009)
comptime partially_bound_binding_array = Self(0x0003000A)
comptime texture_format_16_bit_norm = Self(0x0003000B)
comptime texture_compression_astc_hdr = Self(0x0003000C)
# TODO: requires wgpu.h api change
# comptime timestamp_query_inside_passes = Self(0x0003000D)
comptime mappable_primary_buffers = Self(0x0003000E)
comptime buffer_binding_array = Self(0x0003000F)
comptime uniform_buffer_and_storage_texture_array_non_uniform_indexing = Self(
0x00030010
)
# TODO: requires wgpu.h api change
# comptime address_mode_clamp_to_zero = Self(0x00030011)
# comptime address_mode_clamp_to_border = Self(0x00030012)
# comptime polygon_mode_line = Self(0x00030013)
# comptime polygon_mode_point = Self(0x00030014)
# comptime conservative_rasterization = Self(0x00030015)
# comptime clear_texture = Self(0x00030016)
# comptime spirv_shader_passthrough = Self(0x00030017)
# comptime multiview = Self(0x00030018)
comptime vertex_attribute_64_bit = Self(0x00030019)
comptime texture_format_nv_12 = Self(0x0003001A)
comptime ray_tracing_acceleration_structure = Self(0x0003001B)
comptime ray_query = Self(0x0003001C)
comptime shader_f64 = Self(0x0003001D)
comptime shader_i16 = Self(0x0003001E)
comptime shader_primitive_index = Self(0x0003001F)
comptime shader_early_depth_test = Self(0x00030020)
@fieldwise_init
@register_passable("trivial")
struct LogLevel(Copyable, ImplicitlyCopyable, Movable, EqualityComparable):
var value: Int
fn __eq__(self, rhs: Self) -> Bool:
return self.value == rhs.value
comptime off = Self(0x00000000)
comptime error = Self(0x00000001)
comptime warn = Self(0x00000002)
comptime info = Self(0x00000003)
comptime debug = Self(0x00000004)
comptime trace = Self(0x00000005)
@fieldwise_init
@register_passable("trivial")
struct NativeTextureFormat(Copyable, ImplicitlyCopyable, Movable, EqualityComparable):
var value: UInt32
fn __eq__(self, rhs: Self) -> Bool:
return self.value == rhs.value
# From Features::TEXTURE_FORMAT_16BIT_NORM
comptime r_16_unorm = Self(0x00030001)
comptime r_16_snorm = Self(0x00030002)
comptime rg_16_unorm = Self(0x00030003)
comptime rg_16_snorm = Self(0x00030004)
comptime rgba_16_unorm = Self(0x00030005)
comptime rgba_16_snorm = Self(0x00030006)
# From Features::TEXTURE_FORMAT_NV12
comptime nv_12 = Self(0x00030007)
"""
with open("wgpu/enums.mojo", "w+") as f:
f.write(enums)
structs = "\n".join(gen_struct(e) for e in spec.structs)
bitflags = "\n".join(gen_bitflag(e) for e in spec.bitflags)
bitflags += """
# WGPU SPECIFIC BITFLAGS
@fieldwise_init
struct InstanceBackend(Copyable, ImplicitlyCopyable, Movable, EqualityComparable):
var value: UInt32
fn __eq__(self, rhs: Self) -> Bool:
return self.value == rhs.value
fn __xor__(self, rhs: Self) -> Self:
return Self(self.value ^ rhs.value)
fn __and__(self, rhs: Self) -> Self:
return Self(self.value & rhs.value)
fn __or__(self, rhs: Self) -> Self:
return Self(self.value | rhs.value)
fn __invert__(self) -> Self:
return Self(~self.value)
comptime all = Self(0x00000000)
comptime vulkan = Self(1 << 0)
comptime gl = Self(1 << 1)
comptime metal = Self(1 << 2)
comptime dx12 = Self(1 << 3)
comptime dx11 = Self(1 << 4)
comptime browser_webgpu = Self(1 << 5)
comptime primary = Self.vulkan | Self.metal | Self.dx12 | Self.browser_webgpu
comptime secondary = Self.gl | Self.dx11
@fieldwise_init
struct InstanceFlag(Copyable, ImplicitlyCopyable, Movable, EqualityComparable):
var value: UInt32
fn __eq__(self, rhs: Self) -> Bool:
return self.value == rhs.value
fn __xor__(self, rhs: Self) -> Self:
return Self(self.value ^ rhs.value)
fn __and__(self, rhs: Self) -> Self:
return Self(self.value & rhs.value)
fn __or__(self, rhs: Self) -> Self:
return Self(self.value | rhs.value)
fn __invert__(self) -> Self:
return Self(~self.value)
comptime default = Self(0x00000000)
comptime debug = Self(1 << 0)
comptime validation = Self(1 << 1)
comptime discard_hal_labels = Self(1 << 2)
@fieldwise_init
struct Dx12Compiler(Copyable, ImplicitlyCopyable, Movable, EqualityComparable):
var value: UInt32
fn __eq__(self, rhs: Self) -> Bool:
return self.value == rhs.value
fn __xor__(self, rhs: Self) -> Self:
return Self(self.value ^ rhs.value)
fn __and__(self, rhs: Self) -> Self:
return Self(self.value & rhs.value)
fn __or__(self, rhs: Self) -> Self:
return Self(self.value | rhs.value)
fn __invert__(self) -> Self:
return Self(~self.value)
comptime undefined = Self(0x00000000)
comptime fxc = Self(0x00000001)
comptime dxc = Self(0x00000002)
@fieldwise_init
struct Gles3MinorVersion(Copyable, ImplicitlyCopyable, Movable, EqualityComparable):
var value: UInt32
fn __eq__(self, rhs: Self) -> Bool:
return self.value == rhs.value
fn __xor__(self, rhs: Self) -> Self:
return Self(self.value ^ rhs.value)
fn __and__(self, rhs: Self) -> Self:
return Self(self.value & rhs.value)
fn __or__(self, rhs: Self) -> Self:
return Self(self.value | rhs.value)
fn __invert__(self) -> Self:
return Self(~self.value)
comptime automatic = Self(0x00000000)
comptime version0 = Self(0x00000001)
comptime version1 = Self(0x00000002)
comptime version2 = Self(0x00000003)
@fieldwise_init
struct PipelineStatisticName(Copyable, ImplicitlyCopyable, Movable, EqualityComparable):
var value: UInt32
fn __eq__(self, rhs: Self) -> Bool:
return self.value == rhs.value
fn __xor__(self, rhs: Self) -> Self:
return Self(self.value ^ rhs.value)
fn __and__(self, rhs: Self) -> Self:
return Self(self.value & rhs.value)
fn __or__(self, rhs: Self) -> Self:
return Self(self.value | rhs.value)
fn __invert__(self) -> Self:
return Self(~self.value)
comptime vertex_shader_invocations = Self(0x00000000)
comptime clipper_invocations = Self(0x00000001)
comptime clipper_primitives_out = Self(0x00000002)
comptime fragment_shader_invocations = Self(0x00000003)
comptime compute_shader_invocations = Self(0x00000004)
@fieldwise_init
struct NativeQueryType(Copyable, ImplicitlyCopyable, Movable, EqualityComparable):
var value: UInt32
fn __eq__(self, rhs: Self) -> Bool:
return self.value == rhs.value
fn __xor__(self, rhs: Self) -> Self:
return Self(self.value ^ rhs.value)
fn __and__(self, rhs: Self) -> Self:
return Self(self.value & rhs.value)
fn __or__(self, rhs: Self) -> Self:
return Self(self.value | rhs.value)
fn __invert__(self) -> Self:
return Self(~self.value)
comptime pipeline_statistics = Self(0x00030000)
"""
with open("wgpu/bitflags.mojo", "w+") as f:
f.write(bitflags)
constants = "\n".join(gen_constant(e) for e in spec.constants)
with open("wgpu/constants.mojo", "w+") as f:
f.write(constants)
functions = "\n".join(gen_function(e) for e in spec.functions)
objects = "\n".join(gen_object(e) for e in spec.objects)
function_types = "\n".join(gen_function_type(e) for e in spec.function_types)
output = """
from glfw._cffi import FFIPointer
from sys.ffi import external_call
from .enums import *
from .bitflags import *
from .constants import *
struct ChainedStruct(Copyable, ImplicitlyCopyable, Movable):
var next: FFIPointer[Self, mut=True]
var s_type: SType
fn __init__(out self, next: FFIPointer[Self, mut=True] = {}, s_type: SType = SType.invalid):
self.next = next
self.s_type = s_type
struct ChainedStructOut(Copyable, ImplicitlyCopyable, Movable):
var next: FFIPointer[Self, mut=True]
var s_type: SType
fn __init__(out self, next: FFIPointer[Self, mut=True] = {}, s_type: SType = SType.invalid):
self.next = next
self.s_type = s_type
"""
output += "\n".join([objects, structs, functions, function_types])
output += """
# WGPU SPECIFIC DEFS
struct WGPUInstanceExtras(Copyable, ImplicitlyCopyable, Movable):
var chain: ChainedStruct
var backends: InstanceBackend
var flags: InstanceFlag
var dx12_shader_compiler: Dx12Compiler
var gl_es_3_minor_version: Gles3MinorVersion
var dxil_path: FFIPointer[Int8, mut=False]
var dxc_path: FFIPointer[Int8, mut=False]
fn __init__(
out self,
chain: ChainedStruct = ChainedStruct(),
backends: InstanceBackend = InstanceBackend.all,
flags: InstanceFlag = InstanceFlag.default,
dx12_shader_compiler: Dx12Compiler = Dx12Compiler.undefined,
gl_es_3_minor_version: Gles3MinorVersion = Gles3MinorVersion.automatic,
dxil_path: FFIPointer[Int8, mut=False] = {},
dxc_path: FFIPointer[Int8, mut=False] = {},
):
self.chain = chain
self.backends = backends
self.flags = flags
self.dx12_shader_compiler = dx12_shader_compiler
self.gl_es_3_minor_version = gl_es_3_minor_version
self.dxil_path = dxil_path
self.dxc_path = dxc_path
struct WGPUDeviceExtras(Copyable, ImplicitlyCopyable, Movable):
var chain: ChainedStruct
var trace_path: FFIPointer[Int8, mut=False]
fn __init__(
out self,
chain: ChainedStruct = ChainedStruct(),
trace_path: FFIPointer[Int8, mut=False] = {},
):
self.chain = chain
self.trace_path = trace_path
struct WGPUNativeLimits(Copyable, ImplicitlyCopyable, Movable):
var max_push_constant_size: UInt32
var max_non_sampler_bindings: UInt32
fn __init__(
out self,
max_push_constant_size: UInt32 = 0,
max_non_sampler_bindings: UInt32 = 0,
):
self.max_push_constant_size = max_push_constant_size
self.max_non_sampler_bindings = max_non_sampler_bindings
struct WGPURequiredLimitsExtras(Copyable, ImplicitlyCopyable, Movable):
var chain: ChainedStruct
var limits: WGPUNativeLimits
fn __init__(
out self,
chain: ChainedStruct = ChainedStruct(),
limits: WGPUNativeLimits = WGPUNativeLimits(),
):
self.chain = chain
self.limits = limits
struct WGPUSupportedLimitsExtras(Copyable, ImplicitlyCopyable, Movable):
var chain: ChainedStruct
var limits: WGPUNativeLimits
fn __init__(
out self,
chain: ChainedStruct = ChainedStruct(),
limits: WGPUNativeLimits = WGPUNativeLimits(),
):
self.chain = chain
self.limits = limits
struct WGPUPushConstantRange(Copyable, ImplicitlyCopyable, Movable):
var stages: ShaderStage
var start: UInt32
var end: UInt32
fn __init__(
out self,
stages: ShaderStage = ShaderStage.none,
start: UInt32 = 0,
end: UInt32 = 0,
):
self.stages = stages
self.start = start
self.end = end
struct WGPUPipelineLayoutExtras(Copyable, ImplicitlyCopyable, Movable):
var chain: ChainedStruct
var push_constant_range_count: Int
var push_constant_ranges: FFIPointer[WGPUPushConstantRange, mut=True]
fn __init__(
out self,
chain: ChainedStruct = ChainedStruct(),
push_constant_range_count: Int = 0,
push_constant_ranges: FFIPointer[
WGPUPushConstantRange, mut=True
] = {},
):
self.chain = chain
self.push_constant_range_count = push_constant_range_count
self.push_constant_ranges = push_constant_ranges
comptime WGPUSubmissionIndex = UInt64
struct WGPUWrappedSubmissionIndex(Copyable, ImplicitlyCopyable, Movable):
var queue: WGPUQueue
var submission_index: WGPUSubmissionIndex
fn __init__(
out self,
queue: WGPUQueue = WGPUQueue(),
submission_index: WGPUSubmissionIndex = WGPUSubmissionIndex(),
):
self.queue = queue
self.submission_index = submission_index