pydx12 0.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pydx12-0.2.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2021 Roberto De Ioris
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
pydx12-0.2.0/PKG-INFO ADDED
@@ -0,0 +1,191 @@
1
+ Metadata-Version: 2.4
2
+ Name: pydx12
3
+ Version: 0.2.0
4
+ Summary: Pure ctypes bindings for DirectX 12 (D3D12 + DX12 Ultimate, DXGI, DXC, DirectML, XAudio2, XInput)
5
+ Author-email: Roberto De Ioris <roberto.deioris@gmail.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/rdeioris/pydx12
8
+ Classifier: Operating System :: Microsoft :: Windows
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Topic :: Multimedia :: Graphics :: 3D Rendering
11
+ Requires-Python: >=3.9
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Provides-Extra: test
15
+ Requires-Dist: pytest; extra == "test"
16
+ Requires-Dist: numpy; extra == "test"
17
+ Dynamic: license-file
18
+
19
+ # pydx12
20
+
21
+ DirectX 12 for Python, in pure `ctypes`.
22
+
23
+ pydx12 exposes the whole DirectX 12 family as plain Python: every enum, constant, struct, COM interface and
24
+ exported function, generated from Microsoft's own headers. Nothing is compiled — the package is Python
25
+ source plus the DirectX Shader Compiler DLLs.
26
+
27
+ DirectX is Windows only, so this is the only supported platform. Python 3.9+ on x64.
28
+
29
+ | Area | APIs |
30
+ |---|---|
31
+ | Direct3D 12 | Core API and DirectX 12 Ultimate (DXR raytracing, mesh/amplification shaders, variable rate shading, sampler feedback), enhanced barriers, work graphs, D3D12 video, debug layer / DRED, shader reflection, Agility SDK device factory |
32
+ | DXGI / DXCore | DXGI 1.0–1.6 (adapters, outputs, swapchains, debug), DXCore adapter enumeration |
33
+ | Shader compilers | DXC (`dxcompiler.dll`, bundled, SM 6.0–6.9), FXC (`d3dcompiler_47.dll`) |
34
+ | Compute / ML | DirectML |
35
+ | I/O and input | DirectStorage, GameInput, XInput |
36
+ | Audio | XAudio2, X3DAudio, XAPO |
37
+
38
+ ## Install
39
+
40
+ From a checkout:
41
+
42
+ ```
43
+ pip install .
44
+ ```
45
+
46
+ DirectStorage and GameInput ship their runtimes as NuGet packages, and so does the newest D3D12 runtime (the Agility SDK);
47
+ see [Runtimes that are not in Windows](#runtimes-that-are-not-in-windows).
48
+
49
+ ## Quickstart
50
+
51
+ ```py
52
+ import pydx12 as dx
53
+
54
+ factory = dx.CreateDXGIFactory2()
55
+ i = 0
56
+ while True:
57
+ try:
58
+ adapter = factory.EnumAdapters1(i)
59
+ except dx.DXError as e:
60
+ if e.hresult == dx.DXGI_ERROR_NOT_FOUND:
61
+ break
62
+ raise
63
+ desc = adapter.GetDesc1()
64
+ print('%s (%d MB)' % (desc.Description, desc.DedicatedVideoMemory // 2**20))
65
+ i += 1
66
+
67
+ device = dx.D3D12CreateDevice(factory.EnumAdapterByGpuPreference(0, dx.DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE))
68
+ queue = device.CreateCommandQueue(dx.D3D12_COMMAND_QUEUE_DESC(Type=dx.D3D12_COMMAND_LIST_TYPE_DIRECT))
69
+ ```
70
+
71
+ Complete programs: [examples/triangle.py](https://github.com/rdeioris/pydx12/blob/main/examples/triangle.py) (a swapchain on a tkinter window),
72
+ [examples/directml_life.py](https://github.com/rdeioris/pydx12/blob/main/examples/directml_life.py) (Conway's Game of Life
73
+ as a DirectML operator graph: wrap padding, a 3×3 convolution and two element-wise operators) and the
74
+ tutorials in [docs/](https://github.com/rdeioris/pydx12/tree/main/docs), from enumerating adapters to DXR raytracing.
75
+
76
+ ## How the C API maps to Python
77
+
78
+ Names and parameter order are the ones in Microsoft's documentation, so the C++ docs apply directly. The
79
+ generator reads the headers' SAL annotations and applies these rules:
80
+
81
+ - **Errors raise.** A failing `HRESULT` raises `pydx12.DXError` (`.hresult`, `.name`); compiler error blobs
82
+ are included in the message. Successful calls return their out-parameters, or `None`.
83
+ - **Out-parameters are returned.** `adapter.GetDesc1()` returns a `DXGI_ADAPTER_DESC1`;
84
+ several out-parameters come back as a tuple.
85
+ - **`riid` / `ppv` pairs take an interface class** and return that interface. Common factory methods have
86
+ a default: `device.CreateCommandList(0, type, allocator)` returns an `ID3D12GraphicsCommandList`, and
87
+ `factory.CreateDeviceFactory(...)`, `D3D12CreateDevice(...)` and the like pick the obvious interface.
88
+ Pass another class to get a newer version: `D3D12CreateDevice(adapter, D3D_FEATURE_LEVEL_12_2, dx.ID3D12Device10)`.
89
+ - **Arrays take sequences** and their count parameter is filled in for you:
90
+ `cl.ResourceBarrier([barrier])`, `queue.ExecuteCommandLists([cl])`. The count is still available as a
91
+ keyword-only argument for partial arrays.
92
+ - **Buffers take bytes-like objects**: `bytes`, `bytearray`, `memoryview`, numpy arrays, ctypes arrays, or a
93
+ blob (`ID3DBlob`, `IDxcBlob`). Strings take `str`.
94
+ - **Methods that return a struct** (`GetDesc()`, `GetCPUDescriptorHandleForHeapStart()`, …) return it.
95
+ - **Pointers you get back are integers.** `resource.Map(0)` returns the address; use `ctypes.memmove`,
96
+ `ctypes.string_at` or `(ctypes.c_float * n).from_address(addr)` to read and write it.
97
+ - **C++ default arguments are kept** (`xaudio2.CreateMasteringVoice()` needs none), and trailing optional
98
+ pointers default to `None`.
99
+
100
+ Every method's docstring holds its C signature.
101
+
102
+ ### Structs
103
+
104
+ Structs are `ctypes.Structure` subclasses with keyword constructors, and struct fields accept Python values:
105
+
106
+ ```py
107
+ desc = dx.D3D12_GRAPHICS_PIPELINE_STATE_DESC(
108
+ pRootSignature=root_signature, # COM object: kept alive by the struct
109
+ VS=dx.D3D12_SHADER_BYTECODE(pShaderBytecode=blob), # BytecodeLength is filled in
110
+ RTVFormats=(dx.DXGI_FORMAT_R8G8B8A8_UNORM,), # fixed arrays take short sequences
111
+ NumRenderTargets=1)
112
+ desc.InputLayout.pInputElementDescs = [ # NumElements is filled in
113
+ dx.D3D12_INPUT_ELEMENT_DESC(SemanticName='POSITION', Format=dx.DXGI_FORMAT_R32G32B32_FLOAT)]
114
+ ```
115
+
116
+ Pointer and count fields, string fields, buffer fields and interface fields keep what you assign to them alive
117
+ for as long as the struct (or any struct it is copied into) lives. Anonymous unions are flattened as in C
118
+ (`barrier.Transition`, `clear_value.Color`).
119
+
120
+ ### COM objects
121
+
122
+ Interface wrappers release their reference when garbage collected. `Interface(obj)` and
123
+ `obj.QueryInterface(Interface)` both call `QueryInterface`, for example `dx.ID3D12InfoQueue(device)`.
124
+ `obj.value` is the raw pointer.
125
+
126
+ To implement an interface in Python (XAudio2 callbacks, include handlers, and so on), subclass `ComImplementation`:
127
+
128
+ ```py
129
+ class EngineCallback(dx.ComImplementation):
130
+ _interfaces_ = (dx.IXAudio2EngineCallback,)
131
+
132
+ def OnCriticalError(self, error):
133
+ print('XAudio2 error', hex(error))
134
+
135
+ xaudio2.RegisterForCallbacks(EngineCallback())
136
+ ```
137
+
138
+ Keep a reference to the object for as long as the API may call it.
139
+
140
+ ## Runtimes that are not in Windows
141
+
142
+ The bindings are generated from these SDK versions (`dx.PACKAGE_VERSIONS`):
143
+
144
+ | Package (NuGet) | Version | DLLs |
145
+ |---|---|---|
146
+ | `Microsoft.Direct3D.D3D12` (Agility SDK) | 1.620.2 | `D3D12Core.dll`, `d3d12SDKLayers.dll` |
147
+ | `Microsoft.Direct3D.DXC` | 1.9.2609.5 | `dxcompiler.dll`, `dxil.dll` (bundled in pydx12) |
148
+ | `Microsoft.Direct3D.DirectStorage` | 1.4.0 | `dstorage.dll`, `dstoragecore.dll` |
149
+ | `Microsoft.GameInput` | 4.1.315 | `GameInputRedist.dll` |
150
+
151
+ **Agility SDK.** The in-box D3D12 runtime works for the core API. For the newest features, load the Agility
152
+ SDK runtime through the device factory. This works from `python.exe` and does not need developer mode:
153
+
154
+ ```py
155
+ config = dx.D3D12GetInterface(dx.CLSID_D3D12SDKConfiguration, dx.ID3D12SDKConfiguration1)
156
+ factory = config.CreateDeviceFactory(dx.AGILITY_SDK_VERSION, 'C:\\path\\to\\agility\\bin\\x64\\')
157
+ device = factory.CreateDevice(adapter, dx.D3D_FEATURE_LEVEL_12_0, dx.ID3D12Device)
158
+ ```
159
+
160
+ **DirectStorage, GameInput.** Put the DLLs next to your program, or add their folder:
161
+
162
+ ```py
163
+ os.add_dll_directory(r'C:\path\to\directstorage\bin\x64')
164
+ storage = dx.DStorageGetFactory()
165
+ ```
166
+
167
+ XAudio2 needs COM initialized on the calling thread (`ctypes.windll.ole32.CoInitializeEx(None, 0)`).
168
+
169
+ ## Regenerating the bindings
170
+
171
+ `pydx12/_api.py` is generated by [tools/generate.py](https://github.com/rdeioris/pydx12/blob/main/tools/generate.py) from the Windows SDK headers plus any
172
+ NuGet packages extracted under `.deps/<name>-<version>/pkg` (agility, dxc, directstorage, gameinput):
173
+
174
+ ```
175
+ pip install clang==<your libclang version> # LLVM must be installed (libclang.dll)
176
+ python tools/generate.py
177
+ ```
178
+
179
+ It needs the Windows SDK, the MSVC headers and LLVM. `tests/layout_data.py` is generated along with it,
180
+ and `tests/test_layout.py` checks every struct's size, alignment and field offsets against clang's
181
+ MSVC x64 layout.
182
+
183
+ ## Tests
184
+
185
+ ```
186
+ pip install pytest numpy
187
+ python -m pytest tests
188
+ ```
189
+
190
+ The tests need a D3D12-capable GPU. The Agility SDK, DirectStorage and GameInput tests are skipped
191
+ unless those packages are under `.deps/`.
pydx12-0.2.0/README.md ADDED
@@ -0,0 +1,173 @@
1
+ # pydx12
2
+
3
+ DirectX 12 for Python, in pure `ctypes`.
4
+
5
+ pydx12 exposes the whole DirectX 12 family as plain Python: every enum, constant, struct, COM interface and
6
+ exported function, generated from Microsoft's own headers. Nothing is compiled — the package is Python
7
+ source plus the DirectX Shader Compiler DLLs.
8
+
9
+ DirectX is Windows only, so this is the only supported platform. Python 3.9+ on x64.
10
+
11
+ | Area | APIs |
12
+ |---|---|
13
+ | Direct3D 12 | Core API and DirectX 12 Ultimate (DXR raytracing, mesh/amplification shaders, variable rate shading, sampler feedback), enhanced barriers, work graphs, D3D12 video, debug layer / DRED, shader reflection, Agility SDK device factory |
14
+ | DXGI / DXCore | DXGI 1.0–1.6 (adapters, outputs, swapchains, debug), DXCore adapter enumeration |
15
+ | Shader compilers | DXC (`dxcompiler.dll`, bundled, SM 6.0–6.9), FXC (`d3dcompiler_47.dll`) |
16
+ | Compute / ML | DirectML |
17
+ | I/O and input | DirectStorage, GameInput, XInput |
18
+ | Audio | XAudio2, X3DAudio, XAPO |
19
+
20
+ ## Install
21
+
22
+ From a checkout:
23
+
24
+ ```
25
+ pip install .
26
+ ```
27
+
28
+ DirectStorage and GameInput ship their runtimes as NuGet packages, and so does the newest D3D12 runtime (the Agility SDK);
29
+ see [Runtimes that are not in Windows](#runtimes-that-are-not-in-windows).
30
+
31
+ ## Quickstart
32
+
33
+ ```py
34
+ import pydx12 as dx
35
+
36
+ factory = dx.CreateDXGIFactory2()
37
+ i = 0
38
+ while True:
39
+ try:
40
+ adapter = factory.EnumAdapters1(i)
41
+ except dx.DXError as e:
42
+ if e.hresult == dx.DXGI_ERROR_NOT_FOUND:
43
+ break
44
+ raise
45
+ desc = adapter.GetDesc1()
46
+ print('%s (%d MB)' % (desc.Description, desc.DedicatedVideoMemory // 2**20))
47
+ i += 1
48
+
49
+ device = dx.D3D12CreateDevice(factory.EnumAdapterByGpuPreference(0, dx.DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE))
50
+ queue = device.CreateCommandQueue(dx.D3D12_COMMAND_QUEUE_DESC(Type=dx.D3D12_COMMAND_LIST_TYPE_DIRECT))
51
+ ```
52
+
53
+ Complete programs: [examples/triangle.py](https://github.com/rdeioris/pydx12/blob/main/examples/triangle.py) (a swapchain on a tkinter window),
54
+ [examples/directml_life.py](https://github.com/rdeioris/pydx12/blob/main/examples/directml_life.py) (Conway's Game of Life
55
+ as a DirectML operator graph: wrap padding, a 3×3 convolution and two element-wise operators) and the
56
+ tutorials in [docs/](https://github.com/rdeioris/pydx12/tree/main/docs), from enumerating adapters to DXR raytracing.
57
+
58
+ ## How the C API maps to Python
59
+
60
+ Names and parameter order are the ones in Microsoft's documentation, so the C++ docs apply directly. The
61
+ generator reads the headers' SAL annotations and applies these rules:
62
+
63
+ - **Errors raise.** A failing `HRESULT` raises `pydx12.DXError` (`.hresult`, `.name`); compiler error blobs
64
+ are included in the message. Successful calls return their out-parameters, or `None`.
65
+ - **Out-parameters are returned.** `adapter.GetDesc1()` returns a `DXGI_ADAPTER_DESC1`;
66
+ several out-parameters come back as a tuple.
67
+ - **`riid` / `ppv` pairs take an interface class** and return that interface. Common factory methods have
68
+ a default: `device.CreateCommandList(0, type, allocator)` returns an `ID3D12GraphicsCommandList`, and
69
+ `factory.CreateDeviceFactory(...)`, `D3D12CreateDevice(...)` and the like pick the obvious interface.
70
+ Pass another class to get a newer version: `D3D12CreateDevice(adapter, D3D_FEATURE_LEVEL_12_2, dx.ID3D12Device10)`.
71
+ - **Arrays take sequences** and their count parameter is filled in for you:
72
+ `cl.ResourceBarrier([barrier])`, `queue.ExecuteCommandLists([cl])`. The count is still available as a
73
+ keyword-only argument for partial arrays.
74
+ - **Buffers take bytes-like objects**: `bytes`, `bytearray`, `memoryview`, numpy arrays, ctypes arrays, or a
75
+ blob (`ID3DBlob`, `IDxcBlob`). Strings take `str`.
76
+ - **Methods that return a struct** (`GetDesc()`, `GetCPUDescriptorHandleForHeapStart()`, …) return it.
77
+ - **Pointers you get back are integers.** `resource.Map(0)` returns the address; use `ctypes.memmove`,
78
+ `ctypes.string_at` or `(ctypes.c_float * n).from_address(addr)` to read and write it.
79
+ - **C++ default arguments are kept** (`xaudio2.CreateMasteringVoice()` needs none), and trailing optional
80
+ pointers default to `None`.
81
+
82
+ Every method's docstring holds its C signature.
83
+
84
+ ### Structs
85
+
86
+ Structs are `ctypes.Structure` subclasses with keyword constructors, and struct fields accept Python values:
87
+
88
+ ```py
89
+ desc = dx.D3D12_GRAPHICS_PIPELINE_STATE_DESC(
90
+ pRootSignature=root_signature, # COM object: kept alive by the struct
91
+ VS=dx.D3D12_SHADER_BYTECODE(pShaderBytecode=blob), # BytecodeLength is filled in
92
+ RTVFormats=(dx.DXGI_FORMAT_R8G8B8A8_UNORM,), # fixed arrays take short sequences
93
+ NumRenderTargets=1)
94
+ desc.InputLayout.pInputElementDescs = [ # NumElements is filled in
95
+ dx.D3D12_INPUT_ELEMENT_DESC(SemanticName='POSITION', Format=dx.DXGI_FORMAT_R32G32B32_FLOAT)]
96
+ ```
97
+
98
+ Pointer and count fields, string fields, buffer fields and interface fields keep what you assign to them alive
99
+ for as long as the struct (or any struct it is copied into) lives. Anonymous unions are flattened as in C
100
+ (`barrier.Transition`, `clear_value.Color`).
101
+
102
+ ### COM objects
103
+
104
+ Interface wrappers release their reference when garbage collected. `Interface(obj)` and
105
+ `obj.QueryInterface(Interface)` both call `QueryInterface`, for example `dx.ID3D12InfoQueue(device)`.
106
+ `obj.value` is the raw pointer.
107
+
108
+ To implement an interface in Python (XAudio2 callbacks, include handlers, and so on), subclass `ComImplementation`:
109
+
110
+ ```py
111
+ class EngineCallback(dx.ComImplementation):
112
+ _interfaces_ = (dx.IXAudio2EngineCallback,)
113
+
114
+ def OnCriticalError(self, error):
115
+ print('XAudio2 error', hex(error))
116
+
117
+ xaudio2.RegisterForCallbacks(EngineCallback())
118
+ ```
119
+
120
+ Keep a reference to the object for as long as the API may call it.
121
+
122
+ ## Runtimes that are not in Windows
123
+
124
+ The bindings are generated from these SDK versions (`dx.PACKAGE_VERSIONS`):
125
+
126
+ | Package (NuGet) | Version | DLLs |
127
+ |---|---|---|
128
+ | `Microsoft.Direct3D.D3D12` (Agility SDK) | 1.620.2 | `D3D12Core.dll`, `d3d12SDKLayers.dll` |
129
+ | `Microsoft.Direct3D.DXC` | 1.9.2609.5 | `dxcompiler.dll`, `dxil.dll` (bundled in pydx12) |
130
+ | `Microsoft.Direct3D.DirectStorage` | 1.4.0 | `dstorage.dll`, `dstoragecore.dll` |
131
+ | `Microsoft.GameInput` | 4.1.315 | `GameInputRedist.dll` |
132
+
133
+ **Agility SDK.** The in-box D3D12 runtime works for the core API. For the newest features, load the Agility
134
+ SDK runtime through the device factory. This works from `python.exe` and does not need developer mode:
135
+
136
+ ```py
137
+ config = dx.D3D12GetInterface(dx.CLSID_D3D12SDKConfiguration, dx.ID3D12SDKConfiguration1)
138
+ factory = config.CreateDeviceFactory(dx.AGILITY_SDK_VERSION, 'C:\\path\\to\\agility\\bin\\x64\\')
139
+ device = factory.CreateDevice(adapter, dx.D3D_FEATURE_LEVEL_12_0, dx.ID3D12Device)
140
+ ```
141
+
142
+ **DirectStorage, GameInput.** Put the DLLs next to your program, or add their folder:
143
+
144
+ ```py
145
+ os.add_dll_directory(r'C:\path\to\directstorage\bin\x64')
146
+ storage = dx.DStorageGetFactory()
147
+ ```
148
+
149
+ XAudio2 needs COM initialized on the calling thread (`ctypes.windll.ole32.CoInitializeEx(None, 0)`).
150
+
151
+ ## Regenerating the bindings
152
+
153
+ `pydx12/_api.py` is generated by [tools/generate.py](https://github.com/rdeioris/pydx12/blob/main/tools/generate.py) from the Windows SDK headers plus any
154
+ NuGet packages extracted under `.deps/<name>-<version>/pkg` (agility, dxc, directstorage, gameinput):
155
+
156
+ ```
157
+ pip install clang==<your libclang version> # LLVM must be installed (libclang.dll)
158
+ python tools/generate.py
159
+ ```
160
+
161
+ It needs the Windows SDK, the MSVC headers and LLVM. `tests/layout_data.py` is generated along with it,
162
+ and `tests/test_layout.py` checks every struct's size, alignment and field offsets against clang's
163
+ MSVC x64 layout.
164
+
165
+ ## Tests
166
+
167
+ ```
168
+ pip install pytest numpy
169
+ python -m pytest tests
170
+ ```
171
+
172
+ The tests need a D3D12-capable GPU. The Agility SDK, DirectStorage and GameInput tests are skipped
173
+ unless those packages are under `.deps/`.
@@ -0,0 +1,3 @@
1
+ """pydx12: pure-ctypes bindings for DirectX 12 (D3D12, DXGI, DXC, DirectML, XAudio2, XInput, ...)."""
2
+ from ._core import * # noqa: F401,F403
3
+ from ._api import * # noqa: F401,F403