-
-
Notifications
You must be signed in to change notification settings - Fork 38
/
rs.py
2752 lines (2392 loc) · 111 KB
/
rs.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
"""
WGPU backend implementation based on wgpu-native.
The wgpu-native project (https://github.com/gfx-rs/wgpu-native) is a Rust
library based on wgpu-core, which wraps Metal, Vulkan, DX12, and more.
It compiles to a dynamic library exposing a C-API, accompanied by a C
header file. We wrap this using cffi, which uses the header file to do
most type conversions for us.
This module is maintained using a combination of manual code and
automatically inserted code. In short, the codegen utility inserts
new methods and checks plus annotates all structs and C api calls.
Read the codegen/readme.md for more information.
"""
import os
import ctypes
import logging
import ctypes.util
from weakref import WeakKeyDictionary
from typing import List, Dict, Union
from .. import base, flags, enums, structs
from .. import _register_backend
from .._coreutils import ApiDiff, str_flag_to_int
from .rs_ffi import ffi, lib, check_expected_version
from .rs_mappings import cstructfield2enum, enummap, enum_str2int, enum_int2str
from .rs_helpers import (
get_wgpu_instance,
get_surface_id_from_canvas,
get_memoryview_from_address,
get_memoryview_and_address,
to_snake_case,
to_camel_case,
ErrorHandler,
SafeLibCalls,
)
logger = logging.getLogger("wgpu") # noqa
apidiff = ApiDiff()
# The wgpu-native version that we target/expect
__version__ = "0.17.2.1"
__commit_sha__ = "44d18911dc598104a9d611f8b6128e2620a5f145"
version_info = tuple(map(int, __version__.split(".")))
check_expected_version(version_info) # produces a warning on mismatch
# %% Helper functions and objects
# Features that wgpu-native supports that are not part of WebGPU
NATIVE_FEATURES = (
"PushConstants",
"TextureAdapterSpecificFormatFeatures",
"MultiDrawIndirect",
"MultiDrawIndirectCount",
"VertexWritableStorage",
)
# Object to be able to bind the lifetime of objects to other objects
_refs_per_struct = WeakKeyDictionary()
# Some enum keys need a shortcut
_cstructfield2enum_alt = {
"load_op": "LoadOp",
"store_op": "StoreOp",
"depth_store_op": "StoreOp",
"stencil_store_op": "StoreOp",
}
def new_struct_p(ctype, **kwargs):
"""Create a pointer to an ffi struct. Provides a flatter syntax
and converts our string enums to int enums needed in C. The passed
kwargs are also bound to the lifetime of the new struct.
"""
assert ctype.endswith(" *")
struct_p = _new_struct_p(ctype, **kwargs)
_refs_per_struct[struct_p] = kwargs
return struct_p
# Some kwargs may be other ffi objects, and some may represent
# pointers. These need special care because them "being in" the
# current struct does not prevent them from being cleaned up by
# Python's garbage collector. Keeping hold of these objects in the
# calling code is painful and prone to missing cases, so we solve
# the issue here. We cannot attach an attribute to the struct directly,
# so we use a global WeakKeyDictionary. Also see issue #52.
def new_struct(ctype, **kwargs):
"""Create an ffi value struct. The passed kwargs are also bound
to the lifetime of the new struct.
"""
assert not ctype.endswith("*")
struct_p = _new_struct_p(ctype + " *", **kwargs)
struct = struct_p[0]
_refs_per_struct[struct] = kwargs
return struct
def _new_struct_p(ctype, **kwargs):
struct_p = ffi.new(ctype)
for key, val in kwargs.items():
if isinstance(val, str) and isinstance(getattr(struct_p, key), int):
# An enum - these are ints in C, but str in our public API
if key in _cstructfield2enum_alt:
structname = _cstructfield2enum_alt[key]
else:
structname = cstructfield2enum[ctype.strip(" *")[4:] + "." + key]
ival = enummap[structname + "." + val]
setattr(struct_p, key, ival)
else:
setattr(struct_p, key, val)
return struct_p
def _tuple_from_tuple_or_dict(ob, fields):
"""Given a tuple/list/dict, return a tuple. Also checks tuple size.
>> # E.g.
>> _tuple_from_tuple_or_dict({"x": 1, "y": 2}, ("x", "y"))
(1, 2)
>> _tuple_from_tuple_or_dict([1, 2], ("x", "y"))
(1, 2)
"""
error_msg = "Expected tuple/key/dict with fields: {}"
if isinstance(ob, (list, tuple)):
if len(ob) != len(fields):
raise ValueError(error_msg.format(", ".join(fields)))
return tuple(ob)
elif isinstance(ob, dict):
try:
return tuple(ob[key] for key in fields)
except KeyError:
raise ValueError(error_msg.format(", ".join(fields)))
else:
raise TypeError(error_msg.format(", ".join(fields)))
_empty_label = ffi.new("char []", b"")
def to_c_label(label):
"""Get the C representation of a label."""
if not label:
return _empty_label
else:
return ffi.new("char []", label.encode())
def feature_flag_to_feature_names(flag):
"""Convert a feature flags into a tuple of names."""
feature_names = {} # import this from mappings?
features = []
for i in range(32):
val = int(2**i)
if flag & val:
features.append(feature_names.get(val, val))
return tuple(sorted(features))
def check_struct(struct_name, d):
"""Check that all keys in the given dict exist in the corresponding struct."""
valid_keys = set(getattr(structs, struct_name))
invalid_keys = set(d.keys()).difference(valid_keys)
if invalid_keys:
raise ValueError(f"Invalid keys in {struct_name}: {invalid_keys}")
error_handler = ErrorHandler(logger)
libf = SafeLibCalls(lib, error_handler)
# %% The API
@_register_backend
class GPU(base.GPU):
def request_adapter(
self, *, canvas, power_preference=None, force_fallback_adapter=False
):
"""Create a `GPUAdapter`, the object that represents an abstract wgpu
implementation, from which one can request a `GPUDevice`.
This is the implementation based on the Rust wgpu-native library.
Arguments:
canvas (WgpuCanvas): The canvas that the adapter should be able to
render to (to create a swap chain for, to be precise). Can be None
if you're not rendering to screen (or if you're confident that the
returned adapter will work just fine).
power_preference(PowerPreference): "high-performance" or "low-power".
force_fallback_adapter (bool): whether to use a (probably CPU-based)
fallback adapter.
"""
# ----- Surface ID
# Get surface id that the adapter must be compatible with. If we
# don't pass a valid surface id, there is no guarantee we'll be
# able to create a swapchain for it (from this adapter).
surface_id = ffi.NULL
if canvas is not None:
window_id = canvas.get_window_id()
if window_id is not None: # e.g. could be an off-screen canvas
surface_id = get_surface_id_from_canvas(canvas)
# ----- Select backend
# Try to read the WGPU_BACKEND_TYPE environment variable to see
# if a backend should be forced.
force_backend = os.getenv("WGPU_BACKEND_TYPE", None)
backend = enum_str2int["BackendType"]["Undefined"]
if force_backend:
try:
backend = enum_str2int["BackendType"][force_backend]
except KeyError:
logger.warning(
f"Invalid value for WGPU_BACKEND_TYPE: '{force_backend}'.\n"
f"Valid values are: {list(enum_str2int['BackendType'].keys())}"
)
else:
logger.warning(f"Forcing backend: {force_backend} ({backend})")
# ----- Request adapter
# H: nextInChain: WGPUChainedStruct *, compatibleSurface: WGPUSurface, powerPreference: WGPUPowerPreference, backendType: WGPUBackendType, forceFallbackAdapter: bool
struct = new_struct_p(
"WGPURequestAdapterOptions *",
compatibleSurface=surface_id,
powerPreference=power_preference or "high-performance",
forceFallbackAdapter=bool(force_fallback_adapter),
backendType=backend,
# not used: nextInChain
)
adapter_id = None
error_msg = None
@ffi.callback("void(WGPURequestAdapterStatus, WGPUAdapter, char *, void *)")
def callback(status, result, message, userdata):
if status != 0:
nonlocal error_msg
msg = "-" if message == ffi.NULL else ffi.string(message).decode()
error_msg = f"Request adapter failed ({status}): {msg}"
else:
nonlocal adapter_id
adapter_id = result
# H: void f(WGPUInstance instance, WGPURequestAdapterOptions const * options, WGPURequestAdapterCallback callback, void * userdata)
libf.wgpuInstanceRequestAdapter(get_wgpu_instance(), struct, callback, ffi.NULL)
# For now, Rust will call the callback immediately
# todo: when wgpu gets an event loop -> while run wgpu event loop or something
if adapter_id is None: # pragma: no cover
error_msg = error_msg or "Could not obtain new adapter id."
raise RuntimeError(error_msg)
# ----- Get adapter info
# H: nextInChain: WGPUChainedStructOut *, vendorID: int, vendorName: char *, architecture: char *, deviceID: int, name: char *, driverDescription: char *, adapterType: WGPUAdapterType, backendType: WGPUBackendType
c_properties = new_struct_p(
"WGPUAdapterProperties *",
# not used: nextInChain
# not used: deviceID
# not used: vendorID
# not used: name
# not used: driverDescription
# not used: adapterType
# not used: backendType
# not used: vendorName
# not used: architecture
)
# H: void f(WGPUAdapter adapter, WGPUAdapterProperties * properties)
libf.wgpuAdapterGetProperties(adapter_id, c_properties)
def to_py_str(key):
char_p = getattr(c_properties, key)
if char_p:
return ffi.string(char_p).decode(errors="ignore")
return ""
adapter_info = {
"vendor": to_py_str("vendorName"),
"architecture": to_py_str("architecture"),
"device": to_py_str("name"),
"description": to_py_str("driverDescription"),
"adapter_type": enum_int2str["AdapterType"].get(
c_properties.adapterType, "unknown"
),
"backend_type": enum_int2str["BackendType"].get(
c_properties.backendType, "unknown"
),
# "vendor_id": c_properties.vendorID,
# "device_id": c_properties.deviceID,
}
# ----- Get adapter limits
# H: nextInChain: WGPUChainedStructOut *, limits: WGPULimits
c_supported_limits = new_struct_p(
"WGPUSupportedLimits *",
# not used: nextInChain
# not used: limits
)
c_limits = c_supported_limits.limits
# H: bool f(WGPUAdapter adapter, WGPUSupportedLimits * limits)
libf.wgpuAdapterGetLimits(adapter_id, c_supported_limits)
limits = {to_snake_case(k): getattr(c_limits, k) for k in sorted(dir(c_limits))}
# ----- Get adapter features
# WebGPU features
features = set()
for f in sorted(enums.FeatureName):
key = f"FeatureName.{f}"
i = enummap[key]
# H: bool f(WGPUAdapter adapter, WGPUFeatureName feature)
if libf.wgpuAdapterHasFeature(adapter_id, i):
features.add(f)
# Native features
for f in NATIVE_FEATURES:
i = getattr(lib, f"WGPUNativeFeature_{f}")
# H: bool f(WGPUAdapter adapter, WGPUFeatureName feature)
if libf.wgpuAdapterHasFeature(adapter_id, i):
features.add(f)
# ----- Done
return GPUAdapter(adapter_id, features, limits, adapter_info)
async def request_adapter_async(
self, *, canvas, power_preference=None, force_fallback_adapter=False
):
"""Async version of ``request_adapter()``.
This function uses the Rust WGPU library.
"""
return self.request_adapter(
canvas=canvas,
power_preference=power_preference,
force_fallback_adapter=force_fallback_adapter,
) # no-cover
class GPUCanvasContext(base.GPUCanvasContext):
def __init__(self, canvas):
super().__init__(canvas)
self._device = None
self._surface_size = (-1, -1)
self._surface_id = None
self._internal = None
self._current_texture = None
def get_current_texture(self):
if self._device is None: # pragma: no cover
raise RuntimeError(
"Preset context must be configured before get_current_texture()."
)
if self._current_texture is None:
self._create_native_swap_chain_if_needed()
try:
# H: WGPUTextureView f(WGPUSwapChain swapChain)
view_id = libf.wgpuSwapChainGetCurrentTextureView(self._internal)
except Exception as err:
extra_msg = "\nThis may be caused by dragging the window to a monitor with different dpi. "
extra_msg += "Resize window to proceed.\n"
err.args = (err.args[0] + extra_msg,) + err.args[1:]
raise err from None
size = self._surface_size[0], self._surface_size[1], 1
self._current_texture = GPUTextureView(
"swap_chain", view_id, self._device, None, size
)
return self._current_texture
def present(self):
if (
self._internal is not None
and lib is not None
and self._current_texture is not None
):
# H: void f(WGPUSwapChain swapChain)
libf.wgpuSwapChainPresent(self._internal)
# Reset - always ask for a fresh texture (exactly once) on each draw
self._current_texture = None
def _create_native_swap_chain_if_needed(self):
canvas = self._get_canvas()
psize = canvas.get_physical_size()
if psize == self._surface_size:
return
self._surface_size = psize
if self._surface_id is None:
self._surface_id = get_surface_id_from_canvas(canvas)
# logger.info(str((psize, canvas.get_logical_size(), canvas.get_pixel_ratio())))
# Set the present mode to determine vsync behavior.
#
# 0 Immediate: no waiting, with risk of tearing.
# 1 Mailbox: submit without delay, but present on vsync. Not always available.
# 2 Fifo: Wait for vsync.
#
# In general 2 gives the best result, but sometimes people want to
# benchmark something and get the highest FPS possible. Note
# that we've observed rate limiting regardless of setting this
# to 0, depending on OS or being on battery power.
#
# Also see:
# * https://github.com/gfx-rs/wgpu/blob/e54a36ee/wgpu-types/src/lib.rs#L2663-L2678
# * https://github.com/pygfx/wgpu-py/issues/256
pm_fifo = lib.WGPUPresentMode_Fifo
pm_immediate = lib.WGPUPresentMode_Immediate
present_mode = pm_fifo if getattr(canvas, "_vsync", True) else pm_immediate
# H: nextInChain: WGPUChainedStruct *, label: char *, usage: WGPUTextureUsageFlags/int, format: WGPUTextureFormat, width: int, height: int, presentMode: WGPUPresentMode
struct = new_struct_p(
"WGPUSwapChainDescriptor *",
usage=self._usage,
format=self._format,
width=max(1, psize[0]),
height=max(1, psize[1]),
presentMode=present_mode,
# not used: nextInChain
# not used: label
)
# Destroy old one
if self._internal is not None:
# H: void f(WGPUSwapChain swapChain)
libf.wgpuSwapChainRelease(self._internal)
# H: WGPUSwapChain f(WGPUDevice device, WGPUSurface surface, WGPUSwapChainDescriptor const * descriptor)
self._internal = libf.wgpuDeviceCreateSwapChain(
self._device._internal, self._surface_id, struct
)
def get_preferred_format(self, adapter):
if self._surface_id is None:
canvas = self._get_canvas()
self._surface_id = get_surface_id_from_canvas(canvas)
# # The C-call
# c_count = ffi.new("size_t *")
# c_formats = libxx.wgpuSurfaceGetSupportedFormats(
# self._surface_id, adapter._internal, c_count
# )
#
# # Convert to string formats
# try:
# count = c_count[0]
# supported_format_ints = [c_formats[i] for i in range(count)]
# formats = []
# for key in list(enums.TextureFormat):
# i = enummap[f"TextureFormat.{key}"]
# if i in supported_format_ints:
# formats.append(key)
# finally:
# t = ffi.typeof(c_formats)
# libxx.wgpuFree(c_formats, count * ffi.sizeof(t), ffi.alignof(t))
# There appears to be a bug in wgpuSurfaceGetSupportedFormats, see #341 - disabled it for now.
formats = []
# Select one
default = "bgra8unorm-srgb" # seems to be a good default
preferred = [f for f in formats if "srgb" in f]
if default in formats:
return default
elif preferred:
return preferred[0]
elif formats:
return formats[0]
else:
return default
def _destroy(self):
if self._internal is not None and libf is not None:
self._internal, internal = None, self._internal
# H: void f(WGPUSwapChain swapChain)
libf.wgpuSwapChainRelease(internal)
if self._surface_id is not None and lib is not None:
self._surface_id, surface_id = None, self._surface_id
# H: void f(WGPUSurface surface)
libf.wgpuSurfaceRelease(surface_id)
class GPUObjectBase(base.GPUObjectBase):
pass
class GPUAdapterInfo(base.GPUAdapterInfo):
pass
class GPUAdapter(base.GPUAdapter):
def request_device(
self,
*,
label="",
required_features: "List[enums.FeatureName]" = [],
required_limits: "Dict[str, int]" = {},
default_queue: "structs.QueueDescriptor" = {},
):
if default_queue:
check_struct("QueueDescriptor", default_queue)
return self._request_device(
label, required_features, required_limits, default_queue, ""
)
@apidiff.add("a sweet bonus feature from wgpu-native")
def request_device_tracing(
self,
trace_path,
*,
label="",
required_features: "list(enums.FeatureName)" = [],
required_limits: "Dict[str, int]" = {},
default_queue: "structs.QueueDescriptor" = {},
):
"""Write a trace of all commands to a file so it can be reproduced
elsewhere. The trace is cross-platform!
"""
if default_queue:
check_struct("QueueDescriptor", default_queue)
if not os.path.isdir(trace_path):
os.makedirs(trace_path, exist_ok=True)
elif os.listdir(trace_path):
logger.warning(f"Trace directory not empty: {trace_path}")
return self._request_device(
label, required_features, required_limits, default_queue, trace_path
)
def _request_device(
self, label, required_features, required_limits, default_queue, trace_path
):
# ---- Handle features
assert isinstance(required_features, (tuple, list, set))
c_features = set()
for f in required_features:
if isinstance(f, str):
if "_" in f:
f = "".join(x.title() for x in f.split("_"))
i1 = enummap.get(f"FeatureName.{f}", None)
i2 = getattr(lib, f"WGPUNativeFeature_{f}", None)
i = i2 if i1 is None else i1
if i is None: # pragma: no cover
raise KeyError(f"Unknown feature: '{f}'")
c_features.add(i)
else:
raise TypeError("Features must be given as str.")
c_features = sorted(c_features) # makes it a list
# ----- Set limits
# H: nextInChain: WGPUChainedStruct *, limits: WGPULimits
c_required_limits = new_struct_p(
"WGPURequiredLimits *",
# not used: nextInChain
# not used: limits
)
c_limits = c_required_limits.limits
# Set all limits to the adapter default
# This is important, because zero does NOT mean default, and a limit of zero
# for a specific limit may break a lot of applications.
for key, val in self.limits.items():
setattr(c_limits, to_camel_case(key), val)
# Overload with any set limits
required_limits = required_limits or {}
for key, val in required_limits.items():
setattr(c_limits, to_camel_case(key), val)
# ---- Set queue descriptor
# Note that the default_queue arg is a descriptor (dict for QueueDescriptor), but is currently empty :)
# H: nextInChain: WGPUChainedStruct *, label: char *
queue_struct = new_struct(
"WGPUQueueDescriptor",
label=to_c_label("default_queue"),
# not used: nextInChain
)
# ----- Compose device descriptor extras
c_trace_path = ffi.NULL
if trace_path: # no-cover
c_trace_path = ffi.new("char []", trace_path.encode())
# H: chain: WGPUChainedStruct, tracePath: char *
extras = new_struct_p(
"WGPUDeviceExtras *",
tracePath=c_trace_path,
# not used: chain
)
extras.chain.sType = lib.WGPUSType_DeviceExtras
# ----- Device lost
@ffi.callback("void(WGPUDeviceLostReason, char *, void *)")
def device_lost_callback(c_reason, c_message, userdata):
reason = enum_int2str["DeviceLostReason"].get(c_reason, "Unknown")
message = ffi.string(c_message).decode(errors="ignore")
error_handler.log_error(f"The WGPU device was lost ({reason}):\n{message}")
# Keep the ref alive
self._device_lost_callback = device_lost_callback
# ----- Request device
# H: nextInChain: WGPUChainedStruct *, label: char *, requiredFeaturesCount: int, requiredFeatures: WGPUFeatureName *, requiredLimits: WGPURequiredLimits *, defaultQueue: WGPUQueueDescriptor, deviceLostCallback: WGPUDeviceLostCallback, deviceLostUserdata: void *
struct = new_struct_p(
"WGPUDeviceDescriptor *",
label=to_c_label(label),
nextInChain=ffi.cast("WGPUChainedStruct * ", extras),
requiredFeaturesCount=len(c_features),
requiredFeatures=ffi.new("WGPUFeatureName []", c_features),
requiredLimits=c_required_limits,
defaultQueue=queue_struct,
deviceLostCallback=device_lost_callback,
# not used: deviceLostUserdata
)
device_id = None
error_msg = None
@ffi.callback("void(WGPURequestDeviceStatus, WGPUDevice, char *, void *)")
def callback(status, result, message, userdata):
if status != 0:
nonlocal error_msg
msg = "-" if message == ffi.NULL else ffi.string(message).decode()
error_msg = f"Request device failed ({status}): {msg}"
else:
nonlocal device_id
device_id = result
# H: void f(WGPUAdapter adapter, WGPUDeviceDescriptor const * descriptor, WGPURequestDeviceCallback callback, void * userdata)
libf.wgpuAdapterRequestDevice(self._internal, struct, callback, ffi.NULL)
if device_id is None: # pragma: no cover
error_msg = error_msg or "Could not obtain new device id."
raise RuntimeError(error_msg)
# ----- Get device limits
# H: nextInChain: WGPUChainedStructOut *, limits: WGPULimits
c_supported_limits = new_struct_p(
"WGPUSupportedLimits *",
# not used: nextInChain
# not used: limits
)
c_limits = c_supported_limits.limits
# H: bool f(WGPUDevice device, WGPUSupportedLimits * limits)
libf.wgpuDeviceGetLimits(device_id, c_supported_limits)
limits = {to_snake_case(k): getattr(c_limits, k) for k in dir(c_limits)}
# ----- Get device features
# WebGPU features
features = set()
for f in sorted(enums.FeatureName):
key = f"FeatureName.{f}"
i = enummap[key]
# H: bool f(WGPUDevice device, WGPUFeatureName feature)
if libf.wgpuDeviceHasFeature(device_id, i):
features.add(f)
# Native features
for f in NATIVE_FEATURES:
i = getattr(lib, f"WGPUNativeFeature_{f}")
# H: bool f(WGPUDevice device, WGPUFeatureName feature)
if libf.wgpuDeviceHasFeature(device_id, i):
features.add(f)
# ---- Get queue
# H: WGPUQueue f(WGPUDevice device)
queue_id = libf.wgpuDeviceGetQueue(device_id)
queue = GPUQueue("", queue_id, None)
# ----- Done
return GPUDevice(label, device_id, self, features, limits, queue)
async def request_device_async(
self,
*,
label="",
required_features: "List[enums.FeatureName]" = [],
required_limits: "Dict[str, int]" = {},
default_queue: "structs.QueueDescriptor" = {},
):
if default_queue:
check_struct("QueueDescriptor", default_queue)
return self._request_device(
label, required_features, required_limits, default_queue, ""
) # no-cover
def _destroy(self):
if self._internal is not None and libf is not None:
self._internal, internal = None, self._internal
# H: void f(WGPUAdapter adapter)
libf.wgpuAdapterRelease(internal)
class GPUDevice(base.GPUDevice, GPUObjectBase):
def __init__(self, label, internal, adapter, features, limits, queue):
super().__init__(label, internal, adapter, features, limits, queue)
@ffi.callback("void(WGPUErrorType, char *, void *)")
def uncaptured_error_callback(c_type, c_message, userdata):
error_type = enum_int2str["ErrorType"].get(c_type, "Unknown")
message = ffi.string(c_message).decode(errors="ignore")
message = "\n".join(line.rstrip() for line in message.splitlines())
error_handler.handle_error(error_type, message)
# Keep the ref alive
self._uncaptured_error_callback = uncaptured_error_callback
# H: void f(WGPUDevice device, WGPUErrorCallback callback, void * userdata)
libf.wgpuDeviceSetUncapturedErrorCallback(
self._internal, uncaptured_error_callback, ffi.NULL
)
def _poll(self):
# Internal function
if self._internal:
# H: bool f(WGPUDevice device, bool wait, WGPUWrappedSubmissionIndex const * wrappedSubmissionIndex)
libf.wgpuDevicePoll(self._internal, True, ffi.NULL)
def create_buffer(
self,
*,
label="",
size: int,
usage: "flags.BufferUsage",
mapped_at_creation: bool = False,
):
return self._create_buffer(label, int(size), usage, bool(mapped_at_creation))
def _create_buffer(self, label, size, usage, mapped_at_creation):
# Create a buffer object
if isinstance(usage, str):
usage = str_flag_to_int(flags.BufferUsage, usage)
# H: nextInChain: WGPUChainedStruct *, label: char *, usage: WGPUBufferUsageFlags/int, size: int, mappedAtCreation: bool
struct = new_struct_p(
"WGPUBufferDescriptor *",
label=to_c_label(label),
size=size,
usage=int(usage),
mappedAtCreation=mapped_at_creation,
# not used: nextInChain
)
map_state = (
enums.BufferMapState.mapped
if mapped_at_creation
else enums.BufferMapState.unmapped
)
# H: WGPUBuffer f(WGPUDevice device, WGPUBufferDescriptor const * descriptor)
id = libf.wgpuDeviceCreateBuffer(self._internal, struct)
# Note that there is wgpuBufferGetSize and wgpuBufferGetUsage,
# but we already know these, so they are kindof useless?
# Return wrapped buffer
return GPUBuffer(label, id, self, size, usage, map_state)
def create_texture(
self,
*,
label="",
size: "Union[List[int], structs.Extent3D]",
mip_level_count: int = 1,
sample_count: int = 1,
dimension: "enums.TextureDimension" = "2d",
format: "enums.TextureFormat",
usage: "flags.TextureUsage",
view_formats: "List[enums.TextureFormat]" = [],
):
if isinstance(usage, str):
usage = str_flag_to_int(flags.TextureUsage, usage)
usage = int(usage)
size = _tuple_from_tuple_or_dict(
size, ("width", "height", "depth_or_array_layers")
)
# H: width: int, height: int, depthOrArrayLayers: int
c_size = new_struct(
"WGPUExtent3D",
width=size[0],
height=size[1],
depthOrArrayLayers=size[2],
)
if view_formats:
raise NotImplementedError(
"create_texture(.. view_formats is not yet supported."
)
if not mip_level_count:
mip_level_count = 1 # or lib.WGPU_MIP_LEVEL_COUNT_UNDEFINED ?
mip_level_count = int(mip_level_count)
if not sample_count:
sample_count = 1
sample_count = int(sample_count)
# H: nextInChain: WGPUChainedStruct *, label: char *, usage: WGPUTextureUsageFlags/int, dimension: WGPUTextureDimension, size: WGPUExtent3D, format: WGPUTextureFormat, mipLevelCount: int, sampleCount: int, viewFormatCount: int, viewFormats: WGPUTextureFormat *
struct = new_struct_p(
"WGPUTextureDescriptor *",
label=to_c_label(label),
size=c_size,
mipLevelCount=mip_level_count,
sampleCount=sample_count,
dimension=dimension,
format=format,
usage=usage,
# not used: nextInChain
# not used: viewFormatCount
# not used: viewFormats
)
# H: WGPUTexture f(WGPUDevice device, WGPUTextureDescriptor const * descriptor)
id = libf.wgpuDeviceCreateTexture(self._internal, struct)
# Note that there are methods (e.g. wgpuTextureGetHeight) to get
# the below props, but we know them now, so why bother?
tex_info = {
"size": size,
"mip_level_count": mip_level_count,
"sample_count": sample_count,
"dimension": dimension,
"format": format,
"usage": usage,
}
return GPUTexture(label, id, self, tex_info)
def create_sampler(
self,
*,
label="",
address_mode_u: "enums.AddressMode" = "clamp-to-edge",
address_mode_v: "enums.AddressMode" = "clamp-to-edge",
address_mode_w: "enums.AddressMode" = "clamp-to-edge",
mag_filter: "enums.FilterMode" = "nearest",
min_filter: "enums.FilterMode" = "nearest",
mipmap_filter: "enums.MipmapFilterMode" = "nearest",
lod_min_clamp: float = 0,
lod_max_clamp: float = 32,
compare: "enums.CompareFunction" = None,
max_anisotropy: int = 1,
):
# H: nextInChain: WGPUChainedStruct *, label: char *, addressModeU: WGPUAddressMode, addressModeV: WGPUAddressMode, addressModeW: WGPUAddressMode, magFilter: WGPUFilterMode, minFilter: WGPUFilterMode, mipmapFilter: WGPUMipmapFilterMode, lodMinClamp: float, lodMaxClamp: float, compare: WGPUCompareFunction, maxAnisotropy: int
struct = new_struct_p(
"WGPUSamplerDescriptor *",
label=to_c_label(label),
addressModeU=address_mode_u,
addressModeV=address_mode_v,
addressModeW=address_mode_w,
magFilter=mag_filter,
minFilter=min_filter,
mipmapFilter=mipmap_filter,
lodMinClamp=lod_min_clamp,
lodMaxClamp=lod_max_clamp,
compare=0 if compare is None else compare,
maxAnisotropy=max_anisotropy,
# not used: nextInChain
)
# H: WGPUSampler f(WGPUDevice device, WGPUSamplerDescriptor const * descriptor)
id = libf.wgpuDeviceCreateSampler(self._internal, struct)
return GPUSampler(label, id, self)
def create_bind_group_layout(
self, *, label="", entries: "List[structs.BindGroupLayoutEntry]"
):
c_entries_list = []
for entry in entries:
check_struct("BindGroupLayoutEntry", entry)
buffer = {}
sampler = {}
texture = {}
storage_texture = {}
if entry.get("buffer"):
info = entry["buffer"]
check_struct("BufferBindingLayout", info)
min_binding_size = info.get("min_binding_size", None)
if min_binding_size is None:
min_binding_size = 0 # lib.WGPU_LIMIT_U64_UNDEFINED
# H: nextInChain: WGPUChainedStruct *, type: WGPUBufferBindingType, hasDynamicOffset: bool, minBindingSize: int
buffer = new_struct(
"WGPUBufferBindingLayout",
type=info["type"],
hasDynamicOffset=info.get("has_dynamic_offset", False),
minBindingSize=min_binding_size,
# not used: nextInChain
)
elif entry.get("sampler"):
info = entry["sampler"]
check_struct("SamplerBindingLayout", info)
# H: nextInChain: WGPUChainedStruct *, type: WGPUSamplerBindingType
sampler = new_struct(
"WGPUSamplerBindingLayout",
type=info["type"],
# not used: nextInChain
)
elif entry.get("texture"):
info = entry["texture"]
check_struct("TextureBindingLayout", info)
# H: nextInChain: WGPUChainedStruct *, sampleType: WGPUTextureSampleType, viewDimension: WGPUTextureViewDimension, multisampled: bool
texture = new_struct(
"WGPUTextureBindingLayout",
sampleType=info.get("sample_type", "float"),
viewDimension=info.get("view_dimension", "2d"),
multisampled=info.get("multisampled", False),
# not used: nextInChain
)
elif entry.get("storage_texture"):
info = entry["storage_texture"]
check_struct("StorageTextureBindingLayout", info)
# H: nextInChain: WGPUChainedStruct *, access: WGPUStorageTextureAccess, format: WGPUTextureFormat, viewDimension: WGPUTextureViewDimension
storage_texture = new_struct(
"WGPUStorageTextureBindingLayout",
access=info["access"],
viewDimension=info.get("view_dimension", "2d"),
format=info["format"],
# not used: nextInChain
)
else:
raise ValueError(
"Bind group layout entry did not contain field 'buffer', 'sampler', 'texture', nor 'storage_texture'"
)
# Unreachable - fool the codegen
check_struct("ExternalTextureBindingLayout", info)
visibility = entry["visibility"]
if isinstance(visibility, str):
visibility = str_flag_to_int(flags.ShaderStage, visibility)
# H: nextInChain: WGPUChainedStruct *, binding: int, visibility: WGPUShaderStageFlags/int, buffer: WGPUBufferBindingLayout, sampler: WGPUSamplerBindingLayout, texture: WGPUTextureBindingLayout, storageTexture: WGPUStorageTextureBindingLayout
c_entry = new_struct(
"WGPUBindGroupLayoutEntry",
binding=int(entry["binding"]),
visibility=int(visibility),
buffer=buffer,
sampler=sampler,
texture=texture,
storageTexture=storage_texture,
# not used: nextInChain
)
c_entries_list.append(c_entry)
c_entries_array = ffi.NULL
if c_entries_list:
c_entries_array = ffi.new("WGPUBindGroupLayoutEntry []", c_entries_list)
# H: nextInChain: WGPUChainedStruct *, label: char *, entryCount: int, entries: WGPUBindGroupLayoutEntry *
struct = new_struct_p(
"WGPUBindGroupLayoutDescriptor *",
label=to_c_label(label),
entries=c_entries_array,
entryCount=len(c_entries_list),
# not used: nextInChain
)
# Note: wgpu-core re-uses BindGroupLayouts with the same (or similar
# enough) descriptor. You would think that this means that the id is
# the same when you call wgpuDeviceCreateBindGroupLayout with the same
# input, but it's not. So we cannot let wgpu-native/core decide when
# to re-use a BindGroupLayout. I don't feel confident checking here
# whether a BindGroupLayout can be re-used, so we simply don't. Higher
# level code can sometimes make this decision because it knows the app
# logic.
# H: WGPUBindGroupLayout f(WGPUDevice device, WGPUBindGroupLayoutDescriptor const * descriptor)
id = libf.wgpuDeviceCreateBindGroupLayout(self._internal, struct)
return GPUBindGroupLayout(label, id, self, entries)
def create_bind_group(
self,
*,
label="",
layout: "GPUBindGroupLayout",
entries: "List[structs.BindGroupEntry]",
):
c_entries_list = []
for entry in entries:
check_struct("BindGroupEntry", entry)
# The resource can be a sampler, texture view, or buffer descriptor
resource = entry["resource"]
if isinstance(resource, GPUSampler):
# H: nextInChain: WGPUChainedStruct *, binding: int, buffer: WGPUBuffer, offset: int, size: int, sampler: WGPUSampler, textureView: WGPUTextureView