49 Commits

Author SHA1 Message Date
Robin Voetter
f879074293 Merge pull request #203 from Snektron/vkbool32-enum
replace vk.Bool32 with enum
2025-08-26 23:07:48 +02:00
Robin Voetter
571c59180d replace vk.Bool32 with enum 2025-08-26 23:06:23 +02:00
Robin Voetter
8322c9593f Merge pull request #201 from i-pj/fix-issue-200
Format function signature
2025-08-24 21:05:12 +02:00
Parth Jain
33407b8e4e update format function 2025-08-24 14:04:13 +05:30
Robin Voetter
93bc6f1ac3 Merge pull request #198 from flut2/update-zig-1
update to 0.15.0-dev.1518+749f10af4
2025-08-15 10:37:02 +02:00
flut2
bed9e2d224 update to 0.15.0-dev.1518+749f10af4 2025-08-15 06:48:14 +01:00
Robin Voetter
ed429842b8 Merge pull request #196 from mozbeel/android-fix
isARM -> isArm (Android)
2025-08-01 00:12:29 +02:00
mozbeel
cb618dea81 Fixed isARM -> isArm 2025-08-01 00:03:25 +02:00
Robin Voetter
e492b17810 Merge pull request #195 from Snektron/fix-windowresize
fix window extent after creating
2025-07-20 11:47:10 +02:00
Robin Voetter
39565ca4c3 fix window extent after creating
The requested dimensions of a newly created window may be different
from the actual dimensions as the window system may enforce additional
restrictions. This happens, for example, when using Wayland with a
scaling factor of 3 (the default width of 800 is not divisible by 3).

To fix it, just re-query the actual framebuffer size after creating the window.
The GLFW documentation also suggests to do this:

> The created window, framebuffer and context may differ from what you requested,
> as not all parameters and hints are hard constraints. This includes the size of
> the window, especially for full screen windows. To query the actual attributes
> of the created window, framebuffer and context, see glfwGetWindowAttrib,
> glfwGetWindowSize and glfwGetFramebufferSize.

-- https://www.glfw.org/docs/3.3/group__window.html#ga3555a418df92ad53f917597fe2f64aeb

This should be a better fix for #192
2025-07-20 09:19:47 +02:00
Robin Voetter
f99c5994dc Merge pull request #193 from alichraghi/master
update to latest zig
2025-07-19 13:30:49 +02:00
Robin Voetter
2a1dba26ff Add workaround for incorrect StdVideoH265HrdParameters encoding
See https://github.com/KhronosGroup/Vulkan-Docs/issues/2557
2025-07-19 13:26:20 +02:00
Robin Voetter
9e6c4640bf fix std.process.fatal usage in src/main.zig + fix tree rendering 2025-07-19 12:59:39 +02:00
Ali Cheraghi
0fd576a7e5 update to latest zig 2025-07-16 17:20:05 +03:30
Robin Voetter
c66bddee00 StdVideoVP9 workaround 2025-06-08 19:10:10 +02:00
Robin Voetter
0e164cd730 Merge pull request #191 from alichraghi/master
ci: add build with zig shaders step
2025-06-05 22:19:28 +02:00
Ali Cheraghi
e191c3ccbb ci: add build with zig shaders step 2025-06-05 23:46:27 +03:30
Robin Voetter
970d7f2e3a Merge pull request #190 from alichraghi/master
update zig shaders
2025-06-05 22:00:02 +02:00
Ali Cheraghi
c1c56e9ec5 update zig shaders 2025-06-05 02:37:24 +03:30
Robin Voetter
c9f2c528cc remove copyright year (its forever) 2025-06-04 20:30:31 +02:00
Robin Voetter
114654790e Merge pull request #181 from alichraghi/master
Add option to use zig shaders
2025-06-04 20:29:01 +02:00
Robin Voetter
2582717df1 ci: update to setup-zig v2 2025-06-04 20:26:35 +02:00
Robin Voetter
9b4090c852 Merge pull request #187 from Sebastian-Dawid/master
Fix crash of the example related to swapchain recreation during resizing.
2025-05-13 21:26:52 +02:00
Sebastian Emanuel Dawid
783b70a12e Make sure the example does not segfault if it crashes during swapchain
recreation.
2025-05-13 11:56:03 +02:00
Sebastian Emanuel Dawid
dfc5a3db4e Fix crash related to failure to acquire next swapchain image during resizing 2025-05-13 11:27:22 +02:00
Robin Voetter
fdbe6d60d1 examples: clean up extension_names 2025-05-05 21:16:31 +02:00
Robin Voetter
fa2948199c formatting 2025-05-05 21:13:26 +02:00
Robin Voetter
a5394e1b05 Merge pull request #185 from nicoabie/fix-issue-137
changes to support 1.3.216 Vulkan SDK and above
2025-05-05 21:10:37 +02:00
Nico Gallinal
c8c59544fc changes to support 1.3.216 Vulkan SDK and above 2025-05-04 16:01:08 -03:00
Ali Cheraghi
7b7adcd206 Add option to use zig shaders 2025-04-24 18:05:50 +03:30
Robin Voetter
42e7a8409b Merge pull request #180 from rpkak/remove-additional-null-termination
Remove additional null termination
2025-04-02 10:08:26 +02:00
rpkak
208f0612de Remove additional null termination
[`std.builtin.Type.StructField.name`](https://ziglang.org/documentation/master/std/#std.builtin.Type.StructField) has type `[:0]const u8`
2025-04-02 09:09:34 +02:00
Robin Voetter
355e4828dd Merge pull request #179 from rpkak/allow-custom-dispatch-types
Allow custom Dispatch structs
2025-03-31 21:27:53 +02:00
rpkak
d9fd4eb51a Allow custom dispatch structs 2025-03-31 13:44:23 +02:00
Robin Voetter
40ad90a912 Merge pull request #177 from Snektron/remove-commandflags
remove wrapper/proxy configurability, just load everything unconditionally
2025-03-24 22:50:51 +01:00
Robin Voetter
dd978e3023 remove wrapper/proxy configurability, just load everything unconditionally 2025-03-15 15:43:11 +01:00
Robin Voetter
57d587c8a4 Merge pull request #176 from Snektron/vulkan-video-flags
default initialize packed flag structs to false
2025-03-15 14:03:28 +01:00
Robin Voetter
d046ace4d8 default initialize packed flag structs to 0 2025-03-15 13:24:36 +01:00
Robin Voetter
f6e9565ab6 Merge pull request #175 from Snektron/vulkan-video
Add vulkan video support
2025-03-15 02:54:44 +01:00
Robin Voetter
dcb1d96c59 Add vulkan video support
Implements #174.
2025-03-15 02:51:56 +01:00
Robin Voetter
dcd538828c Merge pull request #172 from alichraghi/master
build: add fingerprint
2025-03-03 19:11:12 +01:00
Ali Cheraghi
19cb72207d build: add fingerprint 2025-03-03 21:26:03 +03:30
Robin Voetter
604416bf44 add renderSpecialContainer support for VK_NV_cluster_acceleration_structure
Solves #169
2025-02-09 16:14:27 +01:00
Robin Voetter
1fd5a6e217 Merge pull request #168 from flut2/master
Update to 0.14.0-dev.2837+f38d7a92c
2025-01-20 00:14:56 +01:00
flut2
55f3bb3c24 update to 0.14.0-dev.2837+f38d7a92c 2025-01-19 16:50:51 +00:00
Robin Voetter
bb470f16da accept registry option as LazyPath
This allows passing LazyPaths obtained from dependencies to
the vulkan-zig dependency, which streamlines using vulkan-zig
with Vulkan-Headers provided by the package manager.
2024-12-29 21:29:52 +01:00
Robin Voetter
dd6e61d689 add missing vulkan video type in ref_all_decls.zig 2024-11-24 21:00:24 +01:00
Robin Voetter
e43d635893 Merge pull request #166 from V-Fries/master
docs: Fixed compilation error in README.md example
2024-10-16 09:46:36 +02:00
V-Fries
6268a6fec4 docs: Fixed compilation error in README.md example 2024-10-16 07:21:42 +02:00
21 changed files with 2374 additions and 2089 deletions

View File

@@ -16,7 +16,7 @@ jobs:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- name: Setup Zig - name: Setup Zig
uses: mlugg/setup-zig@v1 uses: mlugg/setup-zig@v2
with: with:
version: master version: master
@@ -31,20 +31,30 @@ jobs:
sudo apt install shaderc libglfw3 libglfw3-dev sudo apt install shaderc libglfw3 libglfw3-dev
- name: Fetch latest vk.xml - name: Fetch latest vk.xml
run: wget https://raw.githubusercontent.com/KhronosGroup/Vulkan-Docs/main/xml/vk.xml run: |
wget https://raw.githubusercontent.com/KhronosGroup/Vulkan-Docs/main/xml/vk.xml
wget https://raw.githubusercontent.com/KhronosGroup/Vulkan-Docs/main/xml/video.xml
- name: Test and install with latest zig & latest vk.xml - name: Test and install with latest zig & latest vk.xml
run: zig build test install -Dregistry=$(pwd)/vk.xml run: zig build test install -Dregistry=$(pwd)/vk.xml
- name: Test and install with latest zig & latest vk.xml & latest video.xml
run: zig build test install -p zig-out-video -Dregistry=$(pwd)/vk.xml -Dvideo=$(pwd)/video.xml
- name: Build example with latest zig & vk.xml from dependency - name: Build example with latest zig & vk.xml from dependency
run: zig build --build-file $(pwd)/examples/build.zig run: zig build --build-file $(pwd)/examples/build.zig
- name: Build example with latest zig & latest vk.xml - name: Build example with latest zig & latest vk.xml
run: zig build --build-file $(pwd)/examples/build.zig -Doverride-registry=$(pwd)/vk.xml run: zig build --build-file $(pwd)/examples/build.zig -Doverride-registry=$(pwd)/vk.xml
- name: Build example with latest zig & vk.xml from dependency & use zig shaders
run: zig build --build-file $(pwd)/examples/build.zig -Dzig-shader
- name: Archive vk.zig - name: Archive vk.zig
uses: actions/upload-artifact@v4 uses: actions/upload-artifact@v4
with: with:
name: vk.zig name: vk.zig
path: zig-out/src/vk.zig path: |
zig-out/src/vk.zig
zig-out-video/src/vk.zig
if-no-files-found: error if-no-files-found: error

View File

@@ -1,4 +1,4 @@
Copyright © 2020-2022 Robin Voetter Copyright © Robin Voetter
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

186
README.md
View File

@@ -50,14 +50,35 @@ There is also support for adding this project as a dependency through zig packag
``` ```
And then in your build.zig file, you'll need to add a line like this to your build function: And then in your build.zig file, you'll need to add a line like this to your build function:
```zig ```zig
const vkzig_dep = b.dependency("vulkan_zig", .{ const vulkan = b.dependency("vulkan_zig", .{
.registry = @as([]const u8, b.pathFromRoot("path/to/vk.xml")), .registry = b.path("path/to/vk.xml"),
}); }).module("vulkan-zig");
const vkzig_bindings = vkzig_dep.module("vulkan-zig"); exe.root_module.addImport("vulkan", vulkan);
exe.root_module.addImport("vulkan", vkzig_bindings);
``` ```
That will allow you to `@import("vulkan")` in your executable's source. That will allow you to `@import("vulkan")` in your executable's source.
#### Generating bindings directly from Vulkan-Headers
Bindings can be generated directly from the Vulkan-Headers repository by adding Vulkan-Headers as a dependency, and then passing the path to `vk.xml` from that dependency:
```zig
.{
// -- snip --
.dependencies = .{
// -- snip --
.vulkan_headers = .{
.url = "https://github.com/KhronosGroup/Vulkan-Headers/archive/v1.3.283.tar.gz",
.hash = "<dependency hash>",
},
},
}
```
```zig
const vulkan = b.dependency("vulkan_zig", .{
.registry = b.dependency("vulkan_headers", .{}).path("registry/vk.xml"),
}).module("vulkan-zig");
exe.root_module.addImport("vulkan", vulkan);
```
### Manual generation with the package manager from build.zig ### Manual generation with the package manager from build.zig
Bindings can also be generated by invoking the generator directly. This may be useful is some special cases, for example, it integrates particularly well with fetching the registry via the package manager. This can be done by adding the Vulkan-Headers repository to your dependencies, and then passing the `vk.xml` inside it to vulkan-zig-generator: Bindings can also be generated by invoking the generator directly. This may be useful is some special cases, for example, it integrates particularly well with fetching the registry via the package manager. This can be done by adding the Vulkan-Headers repository to your dependencies, and then passing the `vk.xml` inside it to vulkan-zig-generator:
@@ -83,7 +104,7 @@ const vk_gen = b.dependency("vulkan_zig", .{}).artifact("vulkan-zig-generator");
// Set up a run step to generate the bindings // Set up a run step to generate the bindings
const vk_generate_cmd = b.addRunArtifact(vk_gen); const vk_generate_cmd = b.addRunArtifact(vk_gen);
// Pass the registry to the generator // Pass the registry to the generator
generate_cmd.addArg(registry); vk_generate_cmd.addFileArg(registry);
// Create a module from the generator's output... // Create a module from the generator's output...
const vulkan_zig = b.addModule("vulkan-zig", .{ const vulkan_zig = b.addModule("vulkan-zig", .{
.root_source_file = vk_generate_cmd.addOutputFileArg("vk.zig"), .root_source_file = vk_generate_cmd.addOutputFileArg("vk.zig"),
@@ -106,9 +127,9 @@ Functions and fields are renamed to be more or less in line with [Zig's standard
* Container fields and function parameter names are generated in (lower) snake case in a similar manner: `ppEnabledLayerNames` becomes `pp_enabled_layer_names`. * Container fields and function parameter names are generated in (lower) snake case in a similar manner: `ppEnabledLayerNames` becomes `pp_enabled_layer_names`.
* Any name which is either an illegal Zig name or a reserved identifier is rendered using `@"name"` syntax. For example, `VK_IMAGE_TYPE_2D` is translated to `@"2d"`. * Any name which is either an illegal Zig name or a reserved identifier is rendered using `@"name"` syntax. For example, `VK_IMAGE_TYPE_2D` is translated to `@"2d"`.
### Function pointers & Wrappers ### Dispatch Tables
vulkan-zig provides no integration for statically linking libvulkan, and these symbols are not generated at all. Instead, vulkan functions are to be loaded dynamically. For each Vulkan function, a function pointer type is generated using the exact parameters and return types as defined by the Vulkan specification: Vulkan-zig provides no integration for statically linking libvulkan, and these symbols are not generated at all. Instead, vulkan functions are to be loaded dynamically. For each Vulkan function, a function pointer type is generated using the exact parameters and return types as defined by the Vulkan specification:
```zig ```zig
pub const PfnCreateInstance = fn ( pub const PfnCreateInstance = fn (
p_create_info: *const InstanceCreateInfo, p_create_info: *const InstanceCreateInfo,
@@ -117,77 +138,58 @@ pub const PfnCreateInstance = fn (
) callconv(vulkan_call_conv) Result; ) callconv(vulkan_call_conv) Result;
``` ```
For each function, a wrapper is generated into one of three structs: A set of _dispatch table_ structures is generated. A dispatch table simply contains a set of (optional) function pointers to Vulkan API functions, and not much else. Function pointers grouped by the nature of the function as follows:
* BaseWrapper. This contains wrappers for functions which are loaded by `vkGetInstanceProcAddr` without an instance, such as `vkCreateInstance`, `vkEnumerateInstanceVersion`, etc. * Vulkan functions which are loaded by `vkGetInstanceProcAddr` without the need for passing an instance are placed in `BaseDispatch`.
* InstanceWrapper. This contains wrappers for functions which are otherwise loaded by `vkGetInstanceProcAddr`. * Vulkan functions which are loaded by `vkGetInstanceProcAddr` but do need an instance are placed in `InstanceDispatch`.
* DeviceWrapper. This contains wrappers for functions which are loaded by `vkGetDeviceProcAddr`. * Vulkan functions which are loaded by `vkGetDeviceProcAddr` are placed in `DeviceDispatch`.
To create a wrapper type, an "api specification" should be passed to it. This is a list of `ApiInfo` structs, which allows one to specify the functions that should be made available. An `ApiInfo` structure is initialized 3 optional fields, `base_commands`, `instance_commands`, and `device_commands`. Each of these takes a set of the vulkan functions that should be made available for that category, for example, setting `.createInstance = true` in `base_commands` makes the `createInstance` function available (loaded from `vkCreateInstance`). An entire feature level or extension can be pulled in at once too, for example, `vk.features.version_1_0` contains all functions for Vulkan 1.0. `vk.extensions.khr_surface` contains all functions for the `VK_KHR_surface` extension. ### Wrappers
To provide more interesting functionality, a set of _wrapper_ types is also generated, one for each dispatch table type. These contain the Zig-versions of each Vulkan API function, along with corresponding error set definitions, return type definitions, etc, where appropriate.
```zig
const vk = @import("vulkan");
/// To construct base, instance and device wrappers for vulkan-zig, you need to pass a list of 'apis' to it.
const apis: []const vk.ApiInfo = &.{
// You can either add invidiual functions by manually creating an 'api'
.{
.base_commands = .{
.createInstance = true,
},
.instance_commands = .{
.createDevice = true,
},
},
// Or you can add entire feature sets or extensions
vk.features.version_1_0,
vk.extensions.khr_surface,
vk.extensions.khr_swapchain,
};
const BaseDispatch = vk.BaseWrapper(apis);
```
The wrapper struct then provides wrapper functions for each function pointer in the dispatch struct: The wrapper struct then provides wrapper functions for each function pointer in the dispatch struct:
```zig ```zig
pub const BaseWrapper(comptime cmds: anytype) type { pub const BaseWrapper = struct {
... const Self = @This();
const Dispatch = CreateDispatchStruct(cmds); const Dispatch = CreateDispatchStruct(cmds);
return struct {
dispatch: Dispatch,
pub const CreateInstanceError = error{ dispatch: Dispatch,
OutOfHostMemory,
OutOfDeviceMemory, pub const CreateInstanceError = error{
InitializationFailed, OutOfHostMemory,
LayerNotPresent, OutOfDeviceMemory,
ExtensionNotPresent, InitializationFailed,
IncompatibleDriver, LayerNotPresent,
Unknown, ExtensionNotPresent,
}; IncompatibleDriver,
pub fn createInstance( Unknown,
self: Self, };
create_info: InstanceCreateInfo, pub fn createInstance(
p_allocator: ?*const AllocationCallbacks, self: Self,
) CreateInstanceError!Instance { create_info: InstanceCreateInfo,
var instance: Instance = undefined; p_allocator: ?*const AllocationCallbacks,
const result = self.dispatch.vkCreateInstance( ) CreateInstanceError!Instance {
&create_info, var instance: Instance = undefined;
p_allocator, const result = self.dispatch.vkCreateInstance.?(
&instance, &create_info,
); p_allocator,
switch (result) { &instance,
.success => {}, );
.error_out_of_host_memory => return error.OutOfHostMemory, switch (result) {
.error_out_of_device_memory => return error.OutOfDeviceMemory, .success => {},
.error_initialization_failed => return error.InitializationFailed, .error_out_of_host_memory => return error.OutOfHostMemory,
.error_layer_not_present => return error.LayerNotPresent, .error_out_of_device_memory => return error.OutOfDeviceMemory,
.error_extension_not_present => return error.ExtensionNotPresent, .error_initialization_failed => return error.InitializationFailed,
.error_incompatible_driver => return error.IncompatibleDriver, .error_layer_not_present => return error.LayerNotPresent,
else => return error.Unknown, .error_extension_not_present => return error.ExtensionNotPresent,
} .error_incompatible_driver => return error.IncompatibleDriver,
return instance; else => return error.Unknown,
} }
return instance;
...
} }
}
...
};
``` ```
Wrappers are generated according to the following rules: Wrappers are generated according to the following rules:
* The return type is determined from the original return type and the parameters. * The return type is determined from the original return type and the parameters.
@@ -198,10 +200,12 @@ Wrappers are generated according to the following rules:
* Error codes are translated into Zig errors. * Error codes are translated into Zig errors.
* As of yet, there is no specific handling of enumeration style commands or other commands which accept slices. * As of yet, there is no specific handling of enumeration style commands or other commands which accept slices.
Furthermore, each wrapper contains a function to load each function pointer member when passed either `PfnGetInstanceProcAddr` or `PfnGetDeviceProcAddr`, which attempts to load each member as function pointer and casts it to the appropriate type. These functions are loaded literally, and any wrongly named member or member with a wrong function pointer type will result in problems. #### Initializing Wrappers
* For `BaseWrapper`, this function has signature `fn load(loader: anytype) error{CommandFailure}!Self`, where the type of `loader` must resemble `PfnGetInstanceProcAddr` (with optionally having a different calling convention).
* For `InstanceWrapper`, this function has signature `fn load(instance: Instance, loader: anytype) error{CommandFailure}!Self`, where the type of `loader` must resemble `PfnGetInstanceProcAddr`. Wrapper types are initialized by the `load` function, which must be passed a _loader_: A function which loads a function pointer by name.
* For `DeviceWrapper`, this function has signature `fn load(device: Device, loader: anytype) error{CommandFailure}!Self`, where the type of `loader` must resemble `PfnGetDeviceProcAddr`. * For `BaseWrapper`, this function has signature `fn load(loader: anytype) Self`, where the type of `loader` must resemble `PfnGetInstanceProcAddr` (with optionally having a different calling convention).
* For `InstanceWrapper`, this function has signature `fn load(instance: Instance, loader: anytype) Self`, where the type of `loader` must resemble `PfnGetInstanceProcAddr`.
* For `DeviceWrapper`, this function has signature `fn load(device: Device, loader: anytype) Self`, where the type of `loader` must resemble `PfnGetDeviceProcAddr`.
Note that these functions accepts a loader with the signature of `anytype` instead of `PfnGetInstanceProcAddr`. This is because it is valid for `vkGetInstanceProcAddr` to load itself, in which case the returned function is to be called with the vulkan calling convention. This calling convention is not required for loading vulkan-zig itself, though, and a loader to be called with any calling convention with the target architecture may be passed in. This is particularly useful when interacting with C libraries that provide `vkGetInstanceProcAddr`. Note that these functions accepts a loader with the signature of `anytype` instead of `PfnGetInstanceProcAddr`. This is because it is valid for `vkGetInstanceProcAddr` to load itself, in which case the returned function is to be called with the vulkan calling convention. This calling convention is not required for loading vulkan-zig itself, though, and a loader to be called with any calling convention with the target architecture may be passed in. This is particularly useful when interacting with C libraries that provide `vkGetInstanceProcAddr`.
@@ -217,32 +221,33 @@ fn customGetInstanceProcAddress(instance: vk.Instance, procname: [*:0]const u8)
... ...
} }
// Both calls are valid, even // Both calls are valid.
const vkb = try BaseDispatch.load(glfwGetInstanceProcAddress); const vkb = BaseWrapper.load(glfwGetInstanceProcAddress);
const vkb = try BaseDispatch.load(customGetInstanceProcAddress); const vkb = BaseWrapper.load(customGetInstanceProcAddress);
``` ```
By default, wrapper `load` functions return `error.CommandLoadFailure` if a call to the loader resulted in `null`. If this behaviour is not desired, one can use `loadNoFail`. This function accepts the same parameters as `load`, but does not return an error any function pointer fails to load and sets its value to `undefined` instead. It is at the programmer's discretion not to invoke invalid functions, which can be tested for by checking whether the required core and extension versions the function requires are supported. The `load` function tries to load all function pointers unconditionally, regardless of enabled extensions or platform. If a function pointer could not be loaded, its entry in the dispatch table is set to `null`. When invoking a function on a wrapper table, the function pointer is checked for null, and there will be a crash or undefined behavior if it was not loaded properly. That means that **it is up to the programmer to ensure that a function pointer is valid for the platform before calling it**, either by checking whether the associated extension or Vulkan version is supported or simply by checking whether the function pointer is non-null.
One can access the underlying unwrapped C functions by doing `wrapper.dispatch.vkFuncYouWant(..)`. One can access the underlying unwrapped C functions by doing `wrapper.dispatch.vkFuncYouWant.?(..)`.
#### Proxying Wrappers #### Proxying Wrappers
Proxying wrappers wrap a wrapper and a pointer to the associated handle in a single struct, and automatically passes this handle to commands as appropriate. Besides the proxying wrappers for instances and devices, there are also proxying wrappers for queues and command buffers. Proxying wrapper type are constructed in the same way as a regular wrapper, by passing an api specification to them. To initialize a proxying wrapper, it must be passed a handle and a pointer to an appropriate wrapper. For queue and command buffer proxying wrappers, a pointer to a device wrapper must be passed. Proxying wrappers wrap a wrapper and a pointer to the associated handle in a single struct, and automatically passes this handle to commands as appropriate. Besides the proxying wrappers for instances and devices, there are also proxying wrappers for queues and command buffers. Proxying wrapper type are constructed in the same way as a regular wrapper, by passing an api specification to them. To initialize a proxying wrapper, it must be passed a handle and a pointer to an appropriate wrapper. For queue and command buffer proxying wrappers, a pointer to a device wrapper must be passed.
```zig ```zig
// Create the dispatch tables const InstanceWrapper = vk.InstanceWrapper;
const InstanceDispatch = vk.InstanceWrapper(apis); const Instance = vk.InstanceProxy;
const Instance = vk.InstanceProxy(apis);
const instance_handle = try vkb.createInstance(...); const instance_handle = try vkb.createInstance(...);
const vki = try InstanceDispatch.load(instance_handle, vkb.vkGetInstanceProcAddr); const vki = try InstanceWrapper.load(instance_handle, vkb.dispatch.vkGetInstanceProcAddr.?);
const instance = Instance.load(instance_handle, &vki); const instance = Instance.load(instance_handle, &vki);
defer instance.destroyInstance(null); defer instance.destroyInstance(null);
``` ```
For queue and command buffer proxying wrappers, the `queue` and `cmd` prefix is removed for functions where appropriate. Note that the device proxying wrappers also have the queue and command buffer functions made available for convenience, but there the prefix is not stripped. For queue and command buffer proxying wrappers, the `queue` and `cmd` prefix is removed for functions where appropriate. Note that the device proxying wrappers also have the queue and command buffer functions made available for convenience, but there the prefix is not stripped.
Note that the proxy must be passed a _pointer_ to a wrapper. This is because there was a limitation with LLVM in the past, where a struct with an object pointer and its associated function pointers wouldn't be optimized properly. By using a separate function pointer, LLVM knows that the "vtable" dispatch struct can never be modified and so it can subject each call to vtable optimizations.
### Bitflags ### Bitflags
Packed structs of bools are used for bit flags in vulkan-zig, instead of both a `FlagBits` and `Flags` variant. Places where either of these variants are used are both replaced by this packed struct instead. This means that even in places where just one flag would normally be accepted, the packed struct is accepted. The programmer is responsible for only enabling a single bit. Packed structs of bools are used for bit flags in vulkan-zig, instead of both a `FlagBits` and `Flags` variant. Places where either of these variants are used are both replaced by this packed struct instead. This means that even in places where just one flag would normally be accepted, the packed struct is accepted. The programmer is responsible for only enabling a single bit.
@@ -361,6 +366,19 @@ See [examples/build.zig](examples/build.zig) for a working example.
For more advanced shader compiler usage, one may consider a library such as [shader_compiler](https://github.com/Games-by-Mason/shader_compiler). For more advanced shader compiler usage, one may consider a library such as [shader_compiler](https://github.com/Games-by-Mason/shader_compiler).
### Vulkan Video
Vulkan-zig also supports generating Vulkan Video bindings. To do this, one additionally pass `--video <video.xml>` to the generator, or pass `-Dvideo=<video.xml>` to build.zig. If using vulkan-zig via the Zig package manager, the following also works:
```zig
const vulkan_headers = b.dependency("vulkan_headers");
const vulkan = b.dependency("vulkan_zig", .{
.registry = vulkan_headers.path("registry/vk.xml"),
.video = vulkan_headers.path("registery/video.xml"),
}).module("vulkan-zig");
```
The Vulkan Video bindings are not generated by default. In this case, the relevant definitions must be supplied by the user. See [platform types](#platform-types) for how this is done.
## Limitations ## Limitations
* vulkan-zig has as of yet no functionality for selecting feature levels and extensions when generating bindings. This is because when an extension is promoted to Vulkan core, its fields and commands are renamed to lose the extensions author tag (for example, VkSemaphoreWaitFlagsKHR was renamed to VkSemaphoreWaitFlags when it was promoted from an extension to Vulkan 1.2 core). This leads to inconsistencies when only items from up to a certain feature level is included, as these promoted items then need to re-gain a tag. * vulkan-zig has as of yet no functionality for selecting feature levels and extensions when generating bindings. This is because when an extension is promoted to Vulkan core, its fields and commands are renamed to lose the extensions author tag (for example, VkSemaphoreWaitFlagsKHR was renamed to VkSemaphoreWaitFlags when it was promoted from an extension to Vulkan 1.2 core). This leads to inconsistencies when only items from up to a certain feature level is included, as these promoted items then need to re-gain a tag.

View File

@@ -3,18 +3,23 @@ const std = @import("std");
pub fn build(b: *std.Build) void { pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{}); const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{}); const optimize = b.standardOptimizeOption(.{});
const maybe_registry: ?[]const u8 = b.option([]const u8, "registry", "Set the path to the Vulkan registry (vk.xml)"); const maybe_registry = b.option(std.Build.LazyPath, "registry", "Set the path to the Vulkan registry (vk.xml)");
const maybe_video = b.option(std.Build.LazyPath, "video", "Set the path to the Vulkan Video registry (video.xml)");
const test_step = b.step("test", "Run all the tests"); const test_step = b.step("test", "Run all the tests");
const root_module = b.createModule(.{
.root_source_file = b.path("src/main.zig"),
.target = target,
.optimize = optimize,
});
// Using the package manager, this artifact can be obtained by the user // Using the package manager, this artifact can be obtained by the user
// through `b.dependency(<name in build.zig.zon>, .{}).artifact("vulkan-zig-generator")`. // through `b.dependency(<name in build.zig.zon>, .{}).artifact("vulkan-zig-generator")`.
// with that, the user need only `.addArg("path/to/vk.xml")`, and then obtain // with that, the user need only `.addArg("path/to/vk.xml")`, and then obtain
// a file source to the generated code with `.addOutputArg("vk.zig")` // a file source to the generated code with `.addOutputArg("vk.zig")`
const generator_exe = b.addExecutable(.{ const generator_exe = b.addExecutable(.{
.name = "vulkan-zig-generator", .name = "vulkan-zig-generator",
.root_source_file = b.path("src/main.zig"), .root_module = root_module,
.target = target,
.optimize = optimize,
}); });
b.installArtifact(generator_exe); b.installArtifact(generator_exe);
@@ -23,7 +28,12 @@ pub fn build(b: *std.Build) void {
if (maybe_registry) |registry| { if (maybe_registry) |registry| {
const vk_generate_cmd = b.addRunArtifact(generator_exe); const vk_generate_cmd = b.addRunArtifact(generator_exe);
vk_generate_cmd.addArg(registry); if (maybe_video) |video| {
vk_generate_cmd.addArg("--video");
vk_generate_cmd.addFileArg(video);
}
vk_generate_cmd.addFileArg(registry);
const vk_zig = vk_generate_cmd.addOutputFileArg("vk.zig"); const vk_zig = vk_generate_cmd.addOutputFileArg("vk.zig");
const vk_zig_module = b.addModule("vulkan-zig", .{ const vk_zig_module = b.addModule("vulkan-zig", .{
@@ -41,16 +51,16 @@ pub fn build(b: *std.Build) void {
// It does not need to run anyway. // It does not need to run anyway.
const ref_all_decls_test = b.addObject(.{ const ref_all_decls_test = b.addObject(.{
.name = "ref-all-decls-test", .name = "ref-all-decls-test",
.root_source_file = b.path("test/ref_all_decls.zig"), .root_module = b.createModule(.{
.target = target, .root_source_file = b.path("test/ref_all_decls.zig"),
.optimize = optimize, .target = target,
.optimize = optimize,
}),
}); });
ref_all_decls_test.root_module.addImport("vulkan", vk_zig_module); ref_all_decls_test.root_module.addImport("vulkan", vk_zig_module);
test_step.dependOn(&ref_all_decls_test.step); test_step.dependOn(&ref_all_decls_test.step);
} }
const test_target = b.addTest(.{ const test_target = b.addTest(.{ .root_module = root_module });
.root_source_file = b.path("src/main.zig"),
});
test_step.dependOn(&b.addRunArtifact(test_target).step); test_step.dependOn(&b.addRunArtifact(test_target).step);
} }

View File

@@ -1,7 +1,8 @@
.{ .{
.name = "vulkan", .name = .vulkan,
.fingerprint = 0xbe155a03c72db6af,
.version = "0.0.0", .version = "0.0.0",
.minimum_zig_version = "0.14.0-dev.1359+e9a00ba7f", .minimum_zig_version = "0.15.0-dev.1518+749f10af4",
.paths = .{ .paths = .{
"build.zig", "build.zig",
"LICENSE", "LICENSE",

View File

@@ -6,54 +6,92 @@ pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{}); const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{}); const optimize = b.standardOptimizeOption(.{});
const maybe_override_registry = b.option([]const u8, "override-registry", "Override the path to the Vulkan registry used for the examples"); const maybe_override_registry = b.option([]const u8, "override-registry", "Override the path to the Vulkan registry used for the examples");
const use_zig_shaders = b.option(bool, "zig-shader", "Use Zig shaders instead of GLSL") orelse false;
const registry = b.dependency("vulkan_headers", .{}).path("registry/vk.xml"); const registry = b.dependency("vulkan_headers", .{}).path("registry/vk.xml");
const triangle_exe = b.addExecutable(.{ const triangle_exe = b.addExecutable(.{
.name = "triangle", .name = "triangle",
.root_source_file = b.path("triangle.zig"), .root_module = b.createModule(.{
.target = target, .root_source_file = b.path("triangle.zig"),
.link_libc = true, .target = target,
.optimize = optimize, .link_libc = true,
.optimize = optimize,
}),
// TODO: Remove this once x86_64 is stable
.use_llvm = true,
}); });
b.installArtifact(triangle_exe); b.installArtifact(triangle_exe);
triangle_exe.linkSystemLibrary("glfw"); triangle_exe.linkSystemLibrary("glfw");
const vk_gen = b.dependency("vulkan_zig", .{}).artifact("vulkan-zig-generator"); const registry_path: std.Build.LazyPath = if (maybe_override_registry) |override_registry|
const vk_generate_cmd = b.addRunArtifact(vk_gen); .{ .cwd_relative = override_registry }
else
registry;
if (maybe_override_registry) |override_registry| { const vulkan = b.dependency("vulkan_zig", .{
vk_generate_cmd.addFileArg(.{ .cwd_relative = override_registry }); .registry = registry_path,
}).module("vulkan-zig");
triangle_exe.root_module.addImport("vulkan", vulkan);
if (use_zig_shaders) {
const spirv_target = b.resolveTargetQuery(.{
.cpu_arch = .spirv32,
.os_tag = .vulkan,
.cpu_model = .{ .explicit = &std.Target.spirv.cpu.vulkan_v1_2 },
.ofmt = .spirv,
});
const vert_spv = b.addObject(.{
.name = "vertex_shader",
.root_module = b.createModule(.{
.root_source_file = b.path("shaders/vertex.zig"),
.target = spirv_target,
}),
.use_llvm = false,
});
triangle_exe.root_module.addAnonymousImport(
"vertex_shader",
.{ .root_source_file = vert_spv.getEmittedBin() },
);
const frag_spv = b.addObject(.{
.name = "fragment_shader",
.root_module = b.createModule(.{
.root_source_file = b.path("shaders/fragment.zig"),
.target = spirv_target,
}),
.use_llvm = false,
});
triangle_exe.root_module.addAnonymousImport(
"fragment_shader",
.{ .root_source_file = frag_spv.getEmittedBin() },
);
} else { } else {
vk_generate_cmd.addFileArg(registry); const vert_cmd = b.addSystemCommand(&.{
"glslc",
"--target-env=vulkan1.2",
"-o",
});
const vert_spv = vert_cmd.addOutputFileArg("vert.spv");
vert_cmd.addFileArg(b.path("shaders/triangle.vert"));
triangle_exe.root_module.addAnonymousImport("vertex_shader", .{
.root_source_file = vert_spv,
});
const frag_cmd = b.addSystemCommand(&.{
"glslc",
"--target-env=vulkan1.2",
"-o",
});
const frag_spv = frag_cmd.addOutputFileArg("frag.spv");
frag_cmd.addFileArg(b.path("shaders/triangle.frag"));
triangle_exe.root_module.addAnonymousImport("fragment_shader", .{
.root_source_file = frag_spv,
});
} }
triangle_exe.root_module.addAnonymousImport("vulkan", .{
.root_source_file = vk_generate_cmd.addOutputFileArg("vk.zig"),
});
const vert_cmd = b.addSystemCommand(&.{
"glslc",
"--target-env=vulkan1.2",
"-o",
});
const vert_spv = vert_cmd.addOutputFileArg("vert.spv");
vert_cmd.addFileArg(b.path("shaders/triangle.vert"));
triangle_exe.root_module.addAnonymousImport("vertex_shader", .{
.root_source_file = vert_spv,
});
const frag_cmd = b.addSystemCommand(&.{
"glslc",
"--target-env=vulkan1.2",
"-o",
});
const frag_spv = frag_cmd.addOutputFileArg("frag.spv");
frag_cmd.addFileArg(b.path("shaders/triangle.frag"));
triangle_exe.root_module.addAnonymousImport("fragment_shader", .{
.root_source_file = frag_spv,
});
const triangle_run_cmd = b.addRunArtifact(triangle_exe); const triangle_run_cmd = b.addRunArtifact(triangle_exe);
triangle_run_cmd.step.dependOn(b.getInstallStep()); triangle_run_cmd.step.dependOn(b.getInstallStep());

View File

@@ -1,5 +1,6 @@
.{ .{
.name = "vulkan-zig-examples", .name = .vulkan_zig_examples,
.fingerprint = 0x60508bcca14cfc6d,
.version = "0.1.0", .version = "0.1.0",
.dependencies = .{ .dependencies = .{
.vulkan_zig = .{ .vulkan_zig = .{
@@ -7,7 +8,7 @@
}, },
.vulkan_headers = .{ .vulkan_headers = .{
.url = "https://github.com/KhronosGroup/Vulkan-Headers/archive/v1.3.283.tar.gz", .url = "https://github.com/KhronosGroup/Vulkan-Headers/archive/v1.3.283.tar.gz",
.hash = "1220a7e73d72a0d56bc2a65f9d8999a7c019e42260a0744c408d1cded111bc205e10", .hash = "N-V-__8AAAkkoQGn5z1yoNVrwqZfnYmZp8AZ5CJgoHRMQI0c",
}, },
}, },
.paths = .{""}, .paths = .{""},

View File

@@ -5,38 +5,34 @@ const Allocator = std.mem.Allocator;
const required_device_extensions = [_][*:0]const u8{vk.extensions.khr_swapchain.name}; const required_device_extensions = [_][*:0]const u8{vk.extensions.khr_swapchain.name};
/// To construct base, instance and device wrappers for vulkan-zig, you need to pass a list of 'apis' to it. /// There are 3 levels of bindings in vulkan-zig:
const apis: []const vk.ApiInfo = &.{ /// - The Dispatch types (vk.BaseDispatch, vk.InstanceDispatch, vk.DeviceDispatch)
// You can either add invidiual functions by manually creating an 'api' /// are "plain" structs which just contain the function pointers for a particular
.{ /// object.
.base_commands = .{ /// - The Wrapper types (vk.Basewrapper, vk.InstanceWrapper, vk.DeviceWrapper) contains
.createInstance = true, /// the Dispatch type, as well as Ziggified Vulkan functions - these return Zig errors,
}, /// etc.
.instance_commands = .{ /// - The Proxy types (vk.InstanceProxy, vk.DeviceProxy, vk.CommandBufferProxy,
.createDevice = true, /// vk.QueueProxy) contain a pointer to a Wrapper and also contain the object's handle.
}, /// Calling Ziggified functions on these types automatically passes the handle as
}, /// the first parameter of each function. Note that this type accepts a pointer to
// Or you can add entire feature sets or extensions /// a wrapper struct as there is a problem with LLVM where embedding function pointers
vk.features.version_1_0, /// and object pointer in the same struct leads to missed optimizations. If the wrapper
vk.extensions.khr_surface, /// member is a pointer, LLVM will try to optimize it as any other vtable.
vk.extensions.khr_swapchain, /// The wrappers contain
}; const BaseWrapper = vk.BaseWrapper;
const InstanceWrapper = vk.InstanceWrapper;
const DeviceWrapper = vk.DeviceWrapper;
/// Next, pass the `apis` to the wrappers to create dispatch tables. const Instance = vk.InstanceProxy;
const BaseDispatch = vk.BaseWrapper(apis); const Device = vk.DeviceProxy;
const InstanceDispatch = vk.InstanceWrapper(apis);
const DeviceDispatch = vk.DeviceWrapper(apis);
// Also create some proxying wrappers, which also have the respective handles
const Instance = vk.InstanceProxy(apis);
const Device = vk.DeviceProxy(apis);
pub const GraphicsContext = struct { pub const GraphicsContext = struct {
pub const CommandBuffer = vk.CommandBufferProxy(apis); pub const CommandBuffer = vk.CommandBufferProxy;
allocator: Allocator, allocator: Allocator,
vkb: BaseDispatch, vkb: BaseWrapper,
instance: Instance, instance: Instance,
surface: vk.SurfaceKHR, surface: vk.SurfaceKHR,
@@ -51,28 +47,37 @@ pub const GraphicsContext = struct {
pub fn init(allocator: Allocator, app_name: [*:0]const u8, window: *c.GLFWwindow) !GraphicsContext { pub fn init(allocator: Allocator, app_name: [*:0]const u8, window: *c.GLFWwindow) !GraphicsContext {
var self: GraphicsContext = undefined; var self: GraphicsContext = undefined;
self.allocator = allocator; self.allocator = allocator;
self.vkb = try BaseDispatch.load(c.glfwGetInstanceProcAddress); self.vkb = BaseWrapper.load(c.glfwGetInstanceProcAddress);
var extension_names: std.ArrayList([*:0]const u8) = .empty;
defer extension_names.deinit(allocator);
// these extensions are to support vulkan in mac os
// see https://github.com/glfw/glfw/issues/2335
try extension_names.append(allocator, "VK_KHR_portability_enumeration");
try extension_names.append(allocator, "VK_KHR_get_physical_device_properties2");
var glfw_exts_count: u32 = 0; var glfw_exts_count: u32 = 0;
const glfw_exts = c.glfwGetRequiredInstanceExtensions(&glfw_exts_count); const glfw_exts = c.glfwGetRequiredInstanceExtensions(&glfw_exts_count);
try extension_names.appendSlice(allocator, @ptrCast(glfw_exts[0..glfw_exts_count]));
const app_info = vk.ApplicationInfo{
.p_application_name = app_name,
.application_version = vk.makeApiVersion(0, 0, 0, 0),
.p_engine_name = app_name,
.engine_version = vk.makeApiVersion(0, 0, 0, 0),
.api_version = vk.API_VERSION_1_2,
};
const instance = try self.vkb.createInstance(&.{ const instance = try self.vkb.createInstance(&.{
.p_application_info = &app_info, .p_application_info = &.{
.enabled_extension_count = glfw_exts_count, .p_application_name = app_name,
.pp_enabled_extension_names = @ptrCast(glfw_exts), .application_version = @bitCast(vk.makeApiVersion(0, 0, 0, 0)),
.p_engine_name = app_name,
.engine_version = @bitCast(vk.makeApiVersion(0, 0, 0, 0)),
.api_version = @bitCast(vk.API_VERSION_1_2),
},
.enabled_extension_count = @intCast(extension_names.items.len),
.pp_enabled_extension_names = extension_names.items.ptr,
// enumerate_portability_bit_khr to support vulkan in mac os
// see https://github.com/glfw/glfw/issues/2335
.flags = .{ .enumerate_portability_bit_khr = true },
}, null); }, null);
const vki = try allocator.create(InstanceDispatch); const vki = try allocator.create(InstanceWrapper);
errdefer allocator.destroy(vki); errdefer allocator.destroy(vki);
vki.* = try InstanceDispatch.load(instance, self.vkb.dispatch.vkGetInstanceProcAddr); vki.* = InstanceWrapper.load(instance, self.vkb.dispatch.vkGetInstanceProcAddr.?);
self.instance = Instance.init(instance, vki); self.instance = Instance.init(instance, vki);
errdefer self.instance.destroyInstance(null); errdefer self.instance.destroyInstance(null);
@@ -85,9 +90,9 @@ pub const GraphicsContext = struct {
const dev = try initializeCandidate(self.instance, candidate); const dev = try initializeCandidate(self.instance, candidate);
const vkd = try allocator.create(DeviceDispatch); const vkd = try allocator.create(DeviceWrapper);
errdefer allocator.destroy(vkd); errdefer allocator.destroy(vkd);
vkd.* = try DeviceDispatch.load(dev, self.instance.wrapper.dispatch.vkGetDeviceProcAddr); vkd.* = DeviceWrapper.load(dev, self.instance.wrapper.dispatch.vkGetDeviceProcAddr.?);
self.dev = Device.init(dev, vkd); self.dev = Device.init(dev, vkd);
errdefer self.dev.destroyDevice(null); errdefer self.dev.destroyDevice(null);
@@ -248,7 +253,7 @@ fn allocateQueues(instance: Instance, pdev: vk.PhysicalDevice, allocator: Alloca
graphics_family = family; graphics_family = family;
} }
if (present_family == null and (try instance.getPhysicalDeviceSurfaceSupportKHR(pdev, family, surface)) == vk.TRUE) { if (present_family == null and (try instance.getPhysicalDeviceSurfaceSupportKHR(pdev, family, surface)) == .true) {
present_family = family; present_family = family;
} }
} }

View File

@@ -0,0 +1,12 @@
const std = @import("std");
const gpu = std.gpu;
extern const v_color: @Vector(3, f32) addrspace(.input);
extern var f_color: @Vector(4, f32) addrspace(.output);
export fn main() callconv(.spirv_fragment) void {
gpu.location(&v_color, 0);
gpu.location(&f_color, 0);
f_color = .{ v_color[0], v_color[1], v_color[2], 1.0 };
}

View File

@@ -0,0 +1,16 @@
const std = @import("std");
const gpu = std.gpu;
extern const a_pos: @Vector(2, f32) addrspace(.input);
extern const a_color: @Vector(3, f32) addrspace(.input);
extern var v_color: @Vector(3, f32) addrspace(.output);
export fn main() callconv(.spirv_vertex) void {
gpu.location(&a_pos, 0);
gpu.location(&a_color, 1);
gpu.location(&v_color, 0);
gpu.position_out.* = .{ a_pos[0], a_pos[1], 0.0, 1.0 };
v_color = a_color;
}

View File

@@ -46,7 +46,7 @@ pub const Swapchain = struct {
else else
.exclusive; .exclusive;
const handle = try gc.dev.createSwapchainKHR(&.{ const handle = gc.dev.createSwapchainKHR(&.{
.surface = gc.surface, .surface = gc.surface,
.min_image_count = image_count, .min_image_count = image_count,
.image_format = surface_format.format, .image_format = surface_format.format,
@@ -60,9 +60,11 @@ pub const Swapchain = struct {
.pre_transform = caps.current_transform, .pre_transform = caps.current_transform,
.composite_alpha = .{ .opaque_bit_khr = true }, .composite_alpha = .{ .opaque_bit_khr = true },
.present_mode = present_mode, .present_mode = present_mode,
.clipped = vk.TRUE, .clipped = .true,
.old_swapchain = old_handle, .old_swapchain = old_handle,
}, null); }, null) catch {
return error.SwapchainCreationFailed;
};
errdefer gc.dev.destroySwapchainKHR(handle, null); errdefer gc.dev.destroySwapchainKHR(handle, null);
if (old_handle != .null_handle) { if (old_handle != .null_handle) {
@@ -80,7 +82,11 @@ pub const Swapchain = struct {
errdefer gc.dev.destroySemaphore(next_image_acquired, null); errdefer gc.dev.destroySemaphore(next_image_acquired, null);
const result = try gc.dev.acquireNextImageKHR(handle, std.math.maxInt(u64), next_image_acquired, .null_handle); const result = try gc.dev.acquireNextImageKHR(handle, std.math.maxInt(u64), next_image_acquired, .null_handle);
if (result.result != .success) { // event with a .suboptimal_khr we can still go on to present
// if we error even for .suboptimal_khr the example will crash and segfault
// on resize, since even the recreated swapchain can be suboptimal during a
// resize.
if (result.result == .not_ready or result.result == .timeout) {
return error.ImageAcquireFailed; return error.ImageAcquireFailed;
} }
@@ -109,6 +115,8 @@ pub const Swapchain = struct {
} }
pub fn deinit(self: Swapchain) void { pub fn deinit(self: Swapchain) void {
// if we have no swapchain none of these should exist and we can just return
if (self.handle == .null_handle) return;
self.deinitExceptSwapchain(); self.deinitExceptSwapchain();
self.gc.dev.destroySwapchainKHR(self.handle, null); self.gc.dev.destroySwapchainKHR(self.handle, null);
} }
@@ -118,7 +126,18 @@ pub const Swapchain = struct {
const allocator = self.allocator; const allocator = self.allocator;
const old_handle = self.handle; const old_handle = self.handle;
self.deinitExceptSwapchain(); self.deinitExceptSwapchain();
self.* = try initRecycle(gc, allocator, new_extent, old_handle); // set current handle to NULL_HANDLE to signal that the current swapchain does no longer need to be
// de-initialized if we fail to recreate it.
self.handle = .null_handle;
self.* = initRecycle(gc, allocator, new_extent, old_handle) catch |err| switch (err) {
error.SwapchainCreationFailed => {
// we failed while recreating so our current handle still exists,
// but we won't destroy it in the deferred deinit of this object.
gc.dev.destroySwapchainKHR(old_handle, null);
return err;
},
else => return err,
};
} }
pub fn currentImage(self: Swapchain) vk.Image { pub fn currentImage(self: Swapchain) vk.Image {
@@ -242,7 +261,7 @@ const SwapImage = struct {
} }
fn waitForFence(self: SwapImage, gc: *const GraphicsContext) !void { fn waitForFence(self: SwapImage, gc: *const GraphicsContext) !void {
_ = try gc.dev.waitForFences(1, @ptrCast(&self.frame_fence), vk.TRUE, std.math.maxInt(u64)); _ = try gc.dev.waitForFences(1, @ptrCast(&self.frame_fence), .true, std.math.maxInt(u64));
} }
}; };

View File

@@ -63,6 +63,23 @@ pub fn main() !void {
) orelse return error.WindowInitFailed; ) orelse return error.WindowInitFailed;
defer c.glfwDestroyWindow(window); defer c.glfwDestroyWindow(window);
// According to the GLFW docs:
//
// > Window systems put limits on window sizes. Very large or very small window dimensions
// > may be overridden by the window system on creation. Check the actual size after creation.
// -- https://www.glfw.org/docs/3.3/group__window.html#ga3555a418df92ad53f917597fe2f64aeb
//
// This happens in practice, for example, when using Wayland with a scaling factor that is not a
// divisor of the initial window size (see https://github.com/Snektron/vulkan-zig/pull/192).
// To fix it, just fetch the actual size here, after the windowing system has had the time to
// update the window.
extent.width, extent.height = blk: {
var w: c_int = undefined;
var h: c_int = undefined;
c.glfwGetFramebufferSize(window, &w, &h);
break :blk .{ @intCast(w), @intCast(h) };
};
var gpa = std.heap.GeneralPurposeAllocator(.{}){}; var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit(); defer _ = gpa.deinit();
const allocator = gpa.allocator(); const allocator = gpa.allocator();
@@ -123,6 +140,7 @@ pub fn main() !void {
); );
defer destroyCommandBuffers(&gc, pool, allocator, cmdbufs); defer destroyCommandBuffers(&gc, pool, allocator, cmdbufs);
var state: Swapchain.PresentState = .optimal;
while (c.glfwWindowShouldClose(window) == c.GLFW_FALSE) { while (c.glfwWindowShouldClose(window) == c.GLFW_FALSE) {
var w: c_int = undefined; var w: c_int = undefined;
var h: c_int = undefined; var h: c_int = undefined;
@@ -136,11 +154,6 @@ pub fn main() !void {
const cmdbuf = cmdbufs[swapchain.image_index]; const cmdbuf = cmdbufs[swapchain.image_index];
const state = swapchain.present(cmdbuf) catch |err| switch (err) {
error.OutOfDateKHR => Swapchain.PresentState.suboptimal,
else => |narrow| return narrow,
};
if (state == .suboptimal or extent.width != @as(u32, @intCast(w)) or extent.height != @as(u32, @intCast(h))) { if (state == .suboptimal or extent.width != @as(u32, @intCast(w)) or extent.height != @as(u32, @intCast(h))) {
extent.width = @intCast(w); extent.width = @intCast(w);
extent.height = @intCast(h); extent.height = @intCast(h);
@@ -161,6 +174,10 @@ pub fn main() !void {
framebuffers, framebuffers,
); );
} }
state = swapchain.present(cmdbuf) catch |err| switch (err) {
error.OutOfDateKHR => Swapchain.PresentState.suboptimal,
else => |narrow| return narrow,
};
c.glfwPollEvents(); c.glfwPollEvents();
} }
@@ -397,7 +414,7 @@ fn createPipeline(
const piasci = vk.PipelineInputAssemblyStateCreateInfo{ const piasci = vk.PipelineInputAssemblyStateCreateInfo{
.topology = .triangle_list, .topology = .triangle_list,
.primitive_restart_enable = vk.FALSE, .primitive_restart_enable = .false,
}; };
const pvsci = vk.PipelineViewportStateCreateInfo{ const pvsci = vk.PipelineViewportStateCreateInfo{
@@ -408,12 +425,12 @@ fn createPipeline(
}; };
const prsci = vk.PipelineRasterizationStateCreateInfo{ const prsci = vk.PipelineRasterizationStateCreateInfo{
.depth_clamp_enable = vk.FALSE, .depth_clamp_enable = .false,
.rasterizer_discard_enable = vk.FALSE, .rasterizer_discard_enable = .false,
.polygon_mode = .fill, .polygon_mode = .fill,
.cull_mode = .{ .back_bit = true }, .cull_mode = .{ .back_bit = true },
.front_face = .clockwise, .front_face = .clockwise,
.depth_bias_enable = vk.FALSE, .depth_bias_enable = .false,
.depth_bias_constant_factor = 0, .depth_bias_constant_factor = 0,
.depth_bias_clamp = 0, .depth_bias_clamp = 0,
.depth_bias_slope_factor = 0, .depth_bias_slope_factor = 0,
@@ -422,14 +439,14 @@ fn createPipeline(
const pmsci = vk.PipelineMultisampleStateCreateInfo{ const pmsci = vk.PipelineMultisampleStateCreateInfo{
.rasterization_samples = .{ .@"1_bit" = true }, .rasterization_samples = .{ .@"1_bit" = true },
.sample_shading_enable = vk.FALSE, .sample_shading_enable = .false,
.min_sample_shading = 1, .min_sample_shading = 1,
.alpha_to_coverage_enable = vk.FALSE, .alpha_to_coverage_enable = .false,
.alpha_to_one_enable = vk.FALSE, .alpha_to_one_enable = .false,
}; };
const pcbas = vk.PipelineColorBlendAttachmentState{ const pcbas = vk.PipelineColorBlendAttachmentState{
.blend_enable = vk.FALSE, .blend_enable = .false,
.src_color_blend_factor = .one, .src_color_blend_factor = .one,
.dst_color_blend_factor = .zero, .dst_color_blend_factor = .zero,
.color_blend_op = .add, .color_blend_op = .add,
@@ -440,7 +457,7 @@ fn createPipeline(
}; };
const pcbsci = vk.PipelineColorBlendStateCreateInfo{ const pcbsci = vk.PipelineColorBlendStateCreateInfo{
.logic_op_enable = vk.FALSE, .logic_op_enable = .false,
.logic_op = .copy, .logic_op = .copy,
.attachment_count = 1, .attachment_count = 1,
.p_attachments = @ptrCast(&pcbas), .p_attachments = @ptrCast(&pcbas),

View File

@@ -52,13 +52,8 @@ pub fn isZigPrimitiveType(name: []const u8) bool {
return false; return false;
} }
pub fn writeIdentifier(writer: anytype, id: []const u8) !void { pub fn writeIdentifier(w: *std.io.Writer, id: []const u8) !void {
// https://github.com/ziglang/zig/issues/2897 try w.print("{f}", .{std.zig.fmtId(id)});
if (isZigPrimitiveType(id)) {
try writer.print("@\"{}\"", .{std.zig.fmtEscapes(id)});
} else {
try writer.print("{}", .{std.zig.fmtId(id)});
}
} }
pub const CaseStyle = enum { pub const CaseStyle = enum {
@@ -126,12 +121,12 @@ pub const SegmentIterator = struct {
pub const IdRenderer = struct { pub const IdRenderer = struct {
tags: []const []const u8, tags: []const []const u8,
text_cache: std.ArrayList(u8), text_cache: std.io.Writer.Allocating,
pub fn init(allocator: Allocator, tags: []const []const u8) IdRenderer { pub fn init(allocator: Allocator, tags: []const []const u8) IdRenderer {
return .{ return .{
.tags = tags, .tags = tags,
.text_cache = std.ArrayList(u8).init(allocator), .text_cache = .init(allocator),
}; };
} }
@@ -147,19 +142,19 @@ pub const IdRenderer = struct {
if (first) { if (first) {
first = false; first = false;
} else { } else {
try self.text_cache.append('_'); try self.text_cache.writer.writeByte('_');
} }
for (segment) |c| { for (segment) |c| {
try self.text_cache.append(if (screaming) std.ascii.toUpper(c) else std.ascii.toLower(c)); try self.text_cache.writer.writeByte(if (screaming) std.ascii.toUpper(c) else std.ascii.toLower(c));
} }
} }
if (tag) |name| { if (tag) |name| {
try self.text_cache.append('_'); try self.text_cache.writer.writeByte('_');
for (name) |c| { for (name) |c| {
try self.text_cache.append(if (screaming) std.ascii.toUpper(c) else std.ascii.toLower(c)); try self.text_cache.writer.writeByte(if (screaming) std.ascii.toUpper(c) else std.ascii.toLower(c));
} }
} }
} }
@@ -171,7 +166,7 @@ pub const IdRenderer = struct {
while (it.next()) |segment| { while (it.next()) |segment| {
var i: usize = 0; var i: usize = 0;
while (i < segment.len and std.ascii.isDigit(segment[i])) { while (i < segment.len and std.ascii.isDigit(segment[i])) {
try self.text_cache.append(segment[i]); try self.text_cache.writer.writeByte(segment[i]);
i += 1; i += 1;
} }
@@ -180,34 +175,34 @@ pub const IdRenderer = struct {
} }
if (i == 0 and lower_first) { if (i == 0 and lower_first) {
try self.text_cache.append(std.ascii.toLower(segment[i])); try self.text_cache.writer.writeByte(std.ascii.toLower(segment[i]));
} else { } else {
try self.text_cache.append(std.ascii.toUpper(segment[i])); try self.text_cache.writer.writeByte(std.ascii.toUpper(segment[i]));
} }
lower_first = false; lower_first = false;
for (segment[i + 1 ..]) |c| { for (segment[i + 1 ..]) |c| {
try self.text_cache.append(std.ascii.toLower(c)); try self.text_cache.writer.writeByte(std.ascii.toLower(c));
} }
} }
if (tag) |name| { if (tag) |name| {
try self.text_cache.appendSlice(name); try self.text_cache.writer.writeAll(name);
} }
} }
pub fn renderFmt(self: *IdRenderer, out: anytype, comptime fmt: []const u8, args: anytype) !void { pub fn renderFmt(self: *IdRenderer, out: *std.Io.Writer, comptime fmt: []const u8, args: anytype) !void {
self.text_cache.items.len = 0; _ = self.text_cache.writer.consumeAll();
try std.fmt.format(self.text_cache.writer(), fmt, args); try self.text_cache.writer.print(fmt, args);
try writeIdentifier(out, self.text_cache.items); try writeIdentifier(out, self.text_cache.writer.buffered());
} }
pub fn renderWithCase(self: *IdRenderer, out: anytype, case_style: CaseStyle, id: []const u8) !void { pub fn renderWithCase(self: *IdRenderer, out: *std.Io.Writer, case_style: CaseStyle, id: []const u8) !void {
const tag = self.getAuthorTag(id); const tag = self.getAuthorTag(id);
// The trailing underscore doesn't need to be removed here as its removed by the SegmentIterator. // The trailing underscore doesn't need to be removed here as its removed by the SegmentIterator.
const adjusted_id = if (tag) |name| id[0 .. id.len - name.len] else id; const adjusted_id = if (tag) |name| id[0 .. id.len - name.len] else id;
self.text_cache.items.len = 0; _ = self.text_cache.writer.consumeAll();
switch (case_style) { switch (case_style) {
.snake => try self.renderSnake(false, adjusted_id, tag), .snake => try self.renderSnake(false, adjusted_id, tag),
@@ -216,7 +211,7 @@ pub const IdRenderer = struct {
.camel => try self.renderCamel(false, adjusted_id, tag), .camel => try self.renderCamel(false, adjusted_id, tag),
} }
try writeIdentifier(out, self.text_cache.items); try writeIdentifier(out, self.text_cache.writer.buffered());
} }
pub fn getAuthorTag(self: IdRenderer, id: []const u8) ?[]const u8 { pub fn getAuthorTag(self: IdRenderer, id: []const u8) ?[]const u8 {

View File

@@ -1,4 +1,5 @@
const std = @import("std"); const std = @import("std");
const generator = @import("vulkan/generator.zig"); const generator = @import("vulkan/generator.zig");
fn invalidUsage(prog_name: []const u8, comptime fmt: []const u8, args: anytype) noreturn { fn invalidUsage(prog_name: []const u8, comptime fmt: []const u8, args: anytype) noreturn {
@@ -8,39 +9,47 @@ fn invalidUsage(prog_name: []const u8, comptime fmt: []const u8, args: anytype)
} }
fn reportParseErrors(tree: std.zig.Ast) !void { fn reportParseErrors(tree: std.zig.Ast) !void {
const stderr = std.io.getStdErr().writer(); var buf: [1024]u8 = undefined;
var stderr = std.fs.File.stderr().writer(&buf);
const w = &stderr.interface;
for (tree.errors) |err| { for (tree.errors) |err| {
const loc = tree.tokenLocation(0, err.token); const loc = tree.tokenLocation(0, err.token);
try stderr.print("(vulkan-zig error):{}:{}: error: ", .{ loc.line + 1, loc.column + 1 }); try w.print("(vulkan-zig error):{}:{}: error: ", .{ loc.line + 1, loc.column + 1 });
try tree.renderError(err, stderr); try tree.renderError(err, w);
try stderr.print("\n{s}\n", .{tree.source[loc.line_start..loc.line_end]}); try w.print("\n{s}\n", .{tree.source[loc.line_start..loc.line_end]});
for (0..loc.column) |_| { for (0..loc.column) |_| {
try stderr.writeAll(" "); try w.writeAll(" ");
} }
try stderr.writeAll("^\n"); try w.writeAll("^\n");
} }
} }
pub fn main() void { fn oomPanic() noreturn {
@panic("Out of memory");
}
pub fn main() !void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit(); defer arena.deinit();
const allocator = arena.allocator(); const allocator = arena.allocator();
var args = std.process.argsWithAllocator(allocator) catch |err| switch (err) { var args = std.process.argsWithAllocator(allocator) catch |err| switch (err) {
error.OutOfMemory => @panic("OOM"), error.OutOfMemory => oomPanic(),
}; };
const prog_name = args.next() orelse "vulkan-zig-generator"; const prog_name = args.next() orelse "vulkan-zig-generator";
var maybe_xml_path: ?[]const u8 = null; var maybe_xml_path: ?[]const u8 = null;
var maybe_out_path: ?[]const u8 = null; var maybe_out_path: ?[]const u8 = null;
var maybe_video_xml_path: ?[]const u8 = null;
var debug: bool = false; var debug: bool = false;
var api = generator.Api.vulkan; var api = generator.Api.vulkan;
while (args.next()) |arg| { while (args.next()) |arg| {
if (std.mem.eql(u8, arg, "--help") or std.mem.eql(u8, arg, "-h")) { if (std.mem.eql(u8, arg, "--help") or std.mem.eql(u8, arg, "-h")) {
@setEvalBranchQuota(2000); @setEvalBranchQuota(2000);
std.io.getStdOut().writer().print( var buf: [1024]u8 = undefined;
var w = std.fs.File.stdout().writer(&buf);
w.interface.print(
\\Utility to generate a Zig binding from the Vulkan XML API registry. \\Utility to generate a Zig binding from the Vulkan XML API registry.
\\ \\
\\The most recent Vulkan XML API registry can be obtained from \\The most recent Vulkan XML API registry can be obtained from
@@ -52,13 +61,14 @@ pub fn main() void {
\\Options: \\Options:
\\-h --help show this message and exit. \\-h --help show this message and exit.
\\-a --api <api> Generate API for 'vulkan' or 'vulkansc'. Defaults to 'vulkan'. \\-a --api <api> Generate API for 'vulkan' or 'vulkansc'. Defaults to 'vulkan'.
\\--debug Write out unformatted source if does not parse correctly. \\--debug Write out unformatted source if does not parse correctly.
\\--video <path> Also gnerate Vulkan Video API bindings from video.xml
\\ registry at <path>.
\\ \\
, ,
.{prog_name}, .{prog_name},
) catch |err| { ) catch |err| {
std.log.err("failed to write to stdout: {s}", .{@errorName(err)}); std.process.fatal("failed to write to stdout: {s}", .{@errorName(err)});
std.process.exit(1);
}; };
return; return;
} else if (std.mem.eql(u8, arg, "-a") or std.mem.eql(u8, arg, "--api")) { } else if (std.mem.eql(u8, arg, "-a") or std.mem.eql(u8, arg, "--api")) {
@@ -68,12 +78,16 @@ pub fn main() void {
api = std.meta.stringToEnum(generator.Api, api_str) orelse { api = std.meta.stringToEnum(generator.Api, api_str) orelse {
invalidUsage(prog_name, "invalid api '{s}'", .{api_str}); invalidUsage(prog_name, "invalid api '{s}'", .{api_str});
}; };
} else if (std.mem.eql(u8, arg, "--debug")) {
debug = true;
} else if (std.mem.eql(u8, arg, "--video")) {
maybe_video_xml_path = args.next() orelse {
invalidUsage(prog_name, "{s} expects argument <path>", .{arg});
};
} else if (maybe_xml_path == null) { } else if (maybe_xml_path == null) {
maybe_xml_path = arg; maybe_xml_path = arg;
} else if (maybe_out_path == null) { } else if (maybe_out_path == null) {
maybe_out_path = arg; maybe_out_path = arg;
} else if (std.mem.eql(u8, arg, "--debug")) {
debug = true;
} else { } else {
invalidUsage(prog_name, "superficial argument '{s}'", .{arg}); invalidUsage(prog_name, "superficial argument '{s}'", .{arg});
} }
@@ -89,36 +103,49 @@ pub fn main() void {
const cwd = std.fs.cwd(); const cwd = std.fs.cwd();
const xml_src = cwd.readFileAlloc(allocator, xml_path, std.math.maxInt(usize)) catch |err| { const xml_src = cwd.readFileAlloc(allocator, xml_path, std.math.maxInt(usize)) catch |err| {
std.log.err("failed to open input file '{s}' ({s})", .{ xml_path, @errorName(err) }); std.process.fatal("failed to open input file '{s}' ({s})", .{ xml_path, @errorName(err) });
std.process.exit(1);
}; };
var out_buffer = std.ArrayList(u8).init(allocator); const maybe_video_xml_src = if (maybe_video_xml_path) |video_xml_path|
generator.generate(allocator, api, xml_src, out_buffer.writer()) catch |err| switch (err) { cwd.readFileAlloc(allocator, video_xml_path, std.math.maxInt(usize)) catch |err| {
error.InvalidXml => { std.process.fatal("failed to open input file '{s}' ({s})", .{ video_xml_path, @errorName(err) });
std.log.err("invalid vulkan registry - invalid xml", .{}); }
std.log.err("please check that the correct vk.xml file is passed", .{}); else
std.process.exit(1); null;
},
error.InvalidRegistry => { var aw: std.io.Writer.Allocating = .init(allocator);
std.log.err("invalid vulkan registry - registry is valid xml but contents are invalid", .{}); generator.generate(allocator, api, xml_src, maybe_video_xml_src, &aw.writer) catch |err| {
std.log.err("please check that the correct vk.xml file is passed", .{}); if (debug) {
std.process.exit(1); return err;
}, }
error.UnhandledBitfieldStruct => {
std.log.err("unhandled struct with bit fields detected in vk.xml", .{}); switch (err) {
std.log.err("this is a bug in vulkan-zig", .{}); error.InvalidXml => {
std.log.err("please make a bug report at https://github.com/Snektron/vulkan-zig/issues/", .{}); std.log.err("invalid vulkan registry - invalid xml", .{});
std.process.exit(1); std.log.err("please check that the correct vk.xml file is passed", .{});
}, std.process.exit(1);
error.OutOfMemory => @panic("oom"), },
error.InvalidRegistry => {
std.log.err("invalid vulkan registry - registry is valid xml but contents are invalid", .{});
std.log.err("please check that the correct vk.xml file is passed", .{});
std.process.exit(1);
},
error.UnhandledBitfieldStruct => {
std.log.err("unhandled struct with bit fields detected in vk.xml", .{});
std.log.err("this is a bug in vulkan-zig", .{});
std.log.err("please make a bug report at https://github.com/Snektron/vulkan-zig/issues/", .{});
std.process.exit(1);
},
error.OutOfMemory, error.WriteFailed => oomPanic(),
}
}; };
out_buffer.append(0) catch @panic("oom"); aw.writer.writeByte(0) catch oomPanic();
const src = out_buffer.items[0 .. out_buffer.items.len - 1 :0]; const buffered = aw.writer.buffered();
const src = buffered[0 .. buffered.len - 1 :0];
const tree = std.zig.Ast.parse(allocator, src, .zig) catch |err| switch (err) { const tree = std.zig.Ast.parse(allocator, src, .zig) catch |err| switch (err) {
error.OutOfMemory => @panic("oom"), error.OutOfMemory => oomPanic(),
}; };
const formatted = if (tree.errors.len > 0) blk: { const formatted = if (tree.errors.len > 0) blk: {
@@ -128,22 +155,20 @@ pub fn main() void {
std.log.err("or run with --debug to write out unformatted source", .{}); std.log.err("or run with --debug to write out unformatted source", .{});
reportParseErrors(tree) catch |err| { reportParseErrors(tree) catch |err| {
std.log.err("failed to dump ast errors: {s}", .{@errorName(err)}); std.process.fatal("failed to dump ast errors: {s}", .{@errorName(err)});
std.process.exit(1);
}; };
if (debug) { if (debug) {
break :blk src; break :blk src;
} }
std.process.exit(1); std.process.exit(1);
} else tree.render(allocator) catch |err| switch (err) { } else tree.renderAlloc(allocator) catch |err| switch (err) {
error.OutOfMemory => @panic("oom"), error.OutOfMemory => oomPanic(),
}; };
if (std.fs.path.dirname(out_path)) |dir| { if (std.fs.path.dirname(out_path)) |dir| {
cwd.makePath(dir) catch |err| { cwd.makePath(dir) catch |err| {
std.log.err("failed to create output directory '{s}' ({s})", .{ dir, @errorName(err) }); std.process.fatal("failed to create output directory '{s}' ({s})", .{ dir, @errorName(err) });
std.process.exit(1);
}; };
} }
@@ -151,8 +176,7 @@ pub fn main() void {
.sub_path = out_path, .sub_path = out_path,
.data = formatted, .data = formatted,
}) catch |err| { }) catch |err| {
std.log.err("failed to write to output file '{s}' ({s})", .{ out_path, @errorName(err) }); std.process.fatal("failed to write to output file '{s}' ({s})", .{ out_path, @errorName(err) });
std.process.exit(1);
}; };
} }

View File

@@ -90,10 +90,18 @@ pub const CTokenizer = struct {
const start = self.offset; const start = self.offset;
_ = self.consumeNoEof(); _ = self.consumeNoEof();
const hex = self.peek() == 'x';
if (hex) {
_ = self.consumeNoEof();
}
while (true) { while (true) {
const c = self.peek() orelse break; switch (self.peek() orelse break) {
switch (c) {
'0'...'9' => _ = self.consumeNoEof(), '0'...'9' => _ = self.consumeNoEof(),
'A'...'F', 'a'...'f' => {
if (!hex) break;
_ = self.consumeNoEof();
},
else => break, else => break,
} }
} }
@@ -164,7 +172,12 @@ pub const XmlCTokenizer = struct {
} }
fn elemToToken(elem: *xml.Element) !?Token { fn elemToToken(elem: *xml.Element) !?Token {
if (elem.children.len != 1 or elem.children[0] != .char_data) { // Sometimes we encounter empty comment tags. Filter those out
// by early returning here, otherwise the next check will
// determine that the input is not valid XML.
if (mem.eql(u8, elem.tag, "comment")) {
return null;
} else if (elem.children.len != 1 or elem.children[0] != .char_data) {
return error.InvalidXml; return error.InvalidXml;
} }
@@ -175,8 +188,6 @@ pub const XmlCTokenizer = struct {
return Token{ .kind = .enum_name, .text = text }; return Token{ .kind = .enum_name, .text = text };
} else if (mem.eql(u8, elem.tag, "name")) { } else if (mem.eql(u8, elem.tag, "name")) {
return Token{ .kind = .name, .text = text }; return Token{ .kind = .name, .text = text };
} else if (mem.eql(u8, elem.tag, "comment")) {
return null;
} else { } else {
return error.InvalidTag; return error.InvalidTag;
} }
@@ -446,8 +457,8 @@ fn parseFnPtrSuffix(allocator: Allocator, xctok: *XmlCTokenizer, return_type: Ty
// There is no good way to estimate the number of parameters beforehand. // There is no good way to estimate the number of parameters beforehand.
// Fortunately, there are usually a relatively low number of parameters to a function pointer, // Fortunately, there are usually a relatively low number of parameters to a function pointer,
// so an ArrayList backed by an arena allocator is good enough. // so an ArrayList backed by an arena allocator is good enough.
var params = std.ArrayList(registry.Command.Param).init(allocator); var params: std.ArrayList(registry.Command.Param) = .empty;
try params.append(.{ try params.append(allocator, .{
.name = first_param.name.?, .name = first_param.name.?,
.param_type = first_param.decl_type, .param_type = first_param.decl_type,
.is_buffer_len = false, .is_buffer_len = false,
@@ -462,7 +473,7 @@ fn parseFnPtrSuffix(allocator: Allocator, xctok: *XmlCTokenizer, return_type: Ty
} }
const decl = try parseDeclaration(allocator, xctok, ptrs_optional); const decl = try parseDeclaration(allocator, xctok, ptrs_optional);
try params.append(.{ try params.append(allocator, .{
.name = decl.name orelse return error.MissingTypeIdentifier, .name = decl.name orelse return error.MissingTypeIdentifier,
.param_type = decl.decl_type, .param_type = decl.decl_type,
.is_buffer_len = false, .is_buffer_len = false,
@@ -471,7 +482,7 @@ fn parseFnPtrSuffix(allocator: Allocator, xctok: *XmlCTokenizer, return_type: Ty
} }
_ = try xctok.nextNoEof(); _ = try xctok.nextNoEof();
command_ptr.decl_type.command_ptr.params = try params.toOwnedSlice(); command_ptr.decl_type.command_ptr.params = try params.toOwnedSlice(allocator);
return command_ptr; return command_ptr;
} }
@@ -530,7 +541,10 @@ fn parseArrayDeclarator(xctok: *XmlCTokenizer) !?ArraySize {
error.InvalidCharacter => unreachable, error.InvalidCharacter => unreachable,
}, },
}, },
.enum_name => .{ .alias = size_tok.text }, // Sometimes, arrays are declared as `<type>T</type> <name>aa</name>[<enum>SIZE</enum>]`,
// and sometimes just as `<type>T</type> <name>aa</name>[SIZE]`, so we have to account
// for both `.enum_name` and `.id` here.
.enum_name, .id => .{ .alias = size_tok.text },
else => return error.InvalidSyntax, else => return error.InvalidSyntax,
}; };
@@ -538,7 +552,7 @@ fn parseArrayDeclarator(xctok: *XmlCTokenizer) !?ArraySize {
return size; return size;
} }
pub fn parseVersion(xctok: *XmlCTokenizer) ![4][]const u8 { pub fn parseVersion(xctok: *XmlCTokenizer) !registry.ApiConstant.Value {
_ = try xctok.expect(.hash); _ = try xctok.expect(.hash);
const define = try xctok.expect(.id); const define = try xctok.expect(.id);
if (!mem.eql(u8, define.text, "define")) { if (!mem.eql(u8, define.text, "define")) {
@@ -547,12 +561,22 @@ pub fn parseVersion(xctok: *XmlCTokenizer) ![4][]const u8 {
_ = try xctok.expect(.name); _ = try xctok.expect(.name);
const vk_make_version = try xctok.expect(.type_name); const vk_make_version = try xctok.expect(.type_name);
if (!mem.eql(u8, vk_make_version.text, "VK_MAKE_API_VERSION")) { if (mem.eql(u8, vk_make_version.text, "VK_MAKE_API_VERSION")) {
return .{
.version = try parseVersionValues(xctok, 4),
};
} else if (mem.eql(u8, vk_make_version.text, "VK_MAKE_VIDEO_STD_VERSION")) {
return .{
.video_std_version = try parseVersionValues(xctok, 3),
};
} else {
return error.NotVersion; return error.NotVersion;
} }
}
fn parseVersionValues(xctok: *XmlCTokenizer, comptime count: usize) ![count][]const u8 {
_ = try xctok.expect(.lparen); _ = try xctok.expect(.lparen);
var version: [4][]const u8 = undefined; var version: [count][]const u8 = undefined;
for (&version, 0..) |*part, i| { for (&version, 0..) |*part, i| {
if (i != 0) { if (i != 0) {
_ = try xctok.expect(.comma); _ = try xctok.expect(.comma);

View File

@@ -10,11 +10,13 @@ const FeatureLevel = reg.FeatureLevel;
const EnumFieldMerger = struct { const EnumFieldMerger = struct {
const EnumExtensionMap = std.StringArrayHashMapUnmanaged(std.ArrayListUnmanaged(reg.Enum.Field)); const EnumExtensionMap = std.StringArrayHashMapUnmanaged(std.ArrayListUnmanaged(reg.Enum.Field));
const ApiConstantMap = std.StringArrayHashMapUnmanaged(reg.ApiConstant);
const FieldSet = std.StringArrayHashMapUnmanaged(void); const FieldSet = std.StringArrayHashMapUnmanaged(void);
arena: Allocator, arena: Allocator,
registry: *reg.Registry, registry: *reg.Registry,
enum_extensions: EnumExtensionMap, enum_extensions: EnumExtensionMap,
api_constants: ApiConstantMap,
field_set: FieldSet, field_set: FieldSet,
fn init(arena: Allocator, registry: *reg.Registry) EnumFieldMerger { fn init(arena: Allocator, registry: *reg.Registry) EnumFieldMerger {
@@ -22,6 +24,7 @@ const EnumFieldMerger = struct {
.arena = arena, .arena = arena,
.registry = registry, .registry = registry,
.enum_extensions = .{}, .enum_extensions = .{},
.api_constants = .{},
.field_set = .{}, .field_set = .{},
}; };
} }
@@ -29,7 +32,7 @@ const EnumFieldMerger = struct {
fn putEnumExtension(self: *EnumFieldMerger, enum_name: []const u8, field: reg.Enum.Field) !void { fn putEnumExtension(self: *EnumFieldMerger, enum_name: []const u8, field: reg.Enum.Field) !void {
const res = try self.enum_extensions.getOrPut(self.arena, enum_name); const res = try self.enum_extensions.getOrPut(self.arena, enum_name);
if (!res.found_existing) { if (!res.found_existing) {
res.value_ptr.* = std.ArrayListUnmanaged(reg.Enum.Field){}; res.value_ptr.* = .empty;
} }
try res.value_ptr.append(self.arena, field); try res.value_ptr.append(self.arena, field);
@@ -38,7 +41,17 @@ const EnumFieldMerger = struct {
fn addRequires(self: *EnumFieldMerger, reqs: []const reg.Require) !void { fn addRequires(self: *EnumFieldMerger, reqs: []const reg.Require) !void {
for (reqs) |req| { for (reqs) |req| {
for (req.extends) |enum_ext| { for (req.extends) |enum_ext| {
try self.putEnumExtension(enum_ext.extends, enum_ext.field); switch (enum_ext.value) {
.field => try self.putEnumExtension(enum_ext.extends, enum_ext.value.field),
.new_api_constant_expr => |expr| try self.api_constants.put(
self.arena,
enum_ext.extends,
.{
.name = enum_ext.extends,
.value = .{ .expr = expr },
},
),
}
} }
} }
} }
@@ -76,6 +89,10 @@ const EnumFieldMerger = struct {
} }
fn merge(self: *EnumFieldMerger) !void { fn merge(self: *EnumFieldMerger) !void {
for (self.registry.api_constants) |api_constant| {
try self.api_constants.put(self.arena, api_constant.name, api_constant);
}
for (self.registry.features) |feature| { for (self.registry.features) |feature| {
try self.addRequires(feature.requires); try self.addRequires(feature.requires);
} }
@@ -91,6 +108,8 @@ const EnumFieldMerger = struct {
try self.mergeEnumFields(decl.name, &decl.decl_type.enumeration); try self.mergeEnumFields(decl.name, &decl.decl_type.enumeration);
} }
} }
self.registry.api_constants = self.api_constants.values();
} }
}; };
@@ -98,9 +117,10 @@ pub const Generator = struct {
arena: std.heap.ArenaAllocator, arena: std.heap.ArenaAllocator,
registry: reg.Registry, registry: reg.Registry,
id_renderer: IdRenderer, id_renderer: IdRenderer,
have_video: bool,
fn init(allocator: Allocator, spec: *xml.Element, api: reg.Api) !Generator { fn init(allocator: Allocator, spec: *xml.Element, maybe_video_spec: ?*xml.Element, api: reg.Api) !Generator {
const result = try parseXml(allocator, spec, api); const result = try parseXml(allocator, spec, maybe_video_spec, api);
const tags = try allocator.alloc([]const u8, result.registry.tags.len); const tags = try allocator.alloc([]const u8, result.registry.tags.len);
for (tags, result.registry.tags) |*tag, registry_tag| tag.* = registry_tag.name; for (tags, result.registry.tags) |*tag, registry_tag| tag.* = registry_tag.name;
@@ -109,6 +129,7 @@ pub const Generator = struct {
.arena = result.arena, .arena = result.arena,
.registry = result.registry, .registry = result.registry,
.id_renderer = IdRenderer.init(allocator, tags), .id_renderer = IdRenderer.init(allocator, tags),
.have_video = maybe_video_spec != null,
}; };
} }
@@ -165,8 +186,8 @@ pub const Generator = struct {
self.registry.decls.len = i; self.registry.decls.len = i;
} }
fn render(self: *Generator, writer: anytype) !void { fn render(self: *Generator, writer: *std.Io.Writer) !void {
try renderRegistry(writer, self.arena.allocator(), &self.registry, &self.id_renderer); try renderRegistry(writer, self.arena.allocator(), &self.registry, &self.id_renderer, self.have_video);
} }
}; };
@@ -178,7 +199,13 @@ pub const Api = reg.Api;
/// and the resulting binding is written to `writer`. `allocator` will be used to allocate temporary /// and the resulting binding is written to `writer`. `allocator` will be used to allocate temporary
/// internal datastructures - mostly via an ArenaAllocator, but sometimes a hashmap uses this allocator /// internal datastructures - mostly via an ArenaAllocator, but sometimes a hashmap uses this allocator
/// directly. `api` is the API to generate the bindings for, usually `.vulkan`. /// directly. `api` is the API to generate the bindings for, usually `.vulkan`.
pub fn generate(allocator: Allocator, api: Api, spec_xml: []const u8, writer: anytype) !void { pub fn generate(
allocator: Allocator,
api: Api,
spec_xml: []const u8,
maybe_video_spec_xml: ?[]const u8,
writer: *std.Io.Writer,
) !void {
const spec = xml.parse(allocator, spec_xml) catch |err| switch (err) { const spec = xml.parse(allocator, spec_xml) catch |err| switch (err) {
error.InvalidDocument, error.InvalidDocument,
error.UnexpectedEof, error.UnexpectedEof,
@@ -195,7 +222,26 @@ pub fn generate(allocator: Allocator, api: Api, spec_xml: []const u8, writer: an
}; };
defer spec.deinit(); defer spec.deinit();
var gen = Generator.init(allocator, spec.root, api) catch |err| switch (err) { const maybe_video_spec_root = if (maybe_video_spec_xml) |video_spec_xml| blk: {
const video_spec = xml.parse(allocator, video_spec_xml) catch |err| switch (err) {
error.InvalidDocument,
error.UnexpectedEof,
error.UnexpectedCharacter,
error.IllegalCharacter,
error.InvalidEntity,
error.InvalidName,
error.InvalidStandaloneValue,
error.NonMatchingClosingTag,
error.UnclosedComment,
error.UnclosedValue,
=> return error.InvalidXml,
error.OutOfMemory => return error.OutOfMemory,
};
break :blk video_spec.root;
} else null;
var gen = Generator.init(allocator, spec.root, maybe_video_spec_root, api) catch |err| switch (err) {
error.InvalidXml, error.InvalidXml,
error.InvalidCharacter, error.InvalidCharacter,
error.Overflow, error.Overflow,

View File

@@ -17,18 +17,43 @@ pub const ParseResult = struct {
} }
}; };
pub fn parseXml(backing_allocator: Allocator, root: *xml.Element, api: registry.Api) !ParseResult { pub fn parseXml(
backing_allocator: Allocator,
root: *xml.Element,
maybe_video_root: ?*xml.Element,
api: registry.Api,
) !ParseResult {
var arena = ArenaAllocator.init(backing_allocator); var arena = ArenaAllocator.init(backing_allocator);
errdefer arena.deinit(); errdefer arena.deinit();
const allocator = arena.allocator(); const allocator = arena.allocator();
var decls: std.ArrayList(registry.Declaration) = .empty;
var api_constants: std.ArrayList(registry.ApiConstant) = .empty;
var tags: std.ArrayList(registry.Tag) = .empty;
var features: std.ArrayList(registry.Feature) = .empty;
var extensions: std.ArrayList(registry.Extension) = .empty;
try parseDeclarations(allocator, root, api, &decls);
try parseApiConstants(allocator, root, api, &api_constants);
try parseTags(allocator, root, &tags);
try parseFeatures(allocator, root, api, &features);
try parseExtensions(allocator, root, api, &extensions);
if (maybe_video_root) |video_root| {
try parseDeclarations(allocator, video_root, api, &decls);
try parseApiConstants(allocator, video_root, api, &api_constants);
try parseTags(allocator, video_root, &tags);
try parseFeatures(allocator, video_root, api, &features);
try parseExtensions(allocator, video_root, api, &extensions);
}
const reg = registry.Registry{ const reg = registry.Registry{
.decls = try parseDeclarations(allocator, root, api), .decls = decls.items,
.api_constants = try parseApiConstants(allocator, root, api), .api_constants = api_constants.items,
.tags = try parseTags(allocator, root), .tags = tags.items,
.features = try parseFeatures(allocator, root, api), .features = features.items,
.extensions = try parseExtensions(allocator, root, api), .extensions = extensions.items,
}; };
return ParseResult{ return ParseResult{
@@ -37,25 +62,33 @@ pub fn parseXml(backing_allocator: Allocator, root: *xml.Element, api: registry.
}; };
} }
fn parseDeclarations(allocator: Allocator, root: *xml.Element, api: registry.Api) ![]registry.Declaration { fn parseDeclarations(
allocator: Allocator,
root: *xml.Element,
api: registry.Api,
decls: *std.ArrayList(registry.Declaration),
) !void {
const types_elem = root.findChildByTag("types") orelse return error.InvalidRegistry; const types_elem = root.findChildByTag("types") orelse return error.InvalidRegistry;
const commands_elem = root.findChildByTag("commands") orelse return error.InvalidRegistry; try decls.ensureUnusedCapacity(allocator, types_elem.children.len);
const decl_upper_bound = types_elem.children.len + commands_elem.children.len; try parseTypes(allocator, types_elem, api, decls);
const decls = try allocator.alloc(registry.Declaration, decl_upper_bound); try parseEnums(allocator, root, api, decls);
var count: usize = 0; if (root.findChildByTag("commands")) |commands_elem| {
count += try parseTypes(allocator, decls, types_elem, api); try decls.ensureUnusedCapacity(allocator, commands_elem.children.len);
count += try parseEnums(allocator, decls[count..], root, api); try parseCommands(allocator, commands_elem, api, decls);
count += try parseCommands(allocator, decls[count..], commands_elem, api); }
return decls[0..count];
} }
fn parseTypes(allocator: Allocator, out: []registry.Declaration, types_elem: *xml.Element, api: registry.Api) !usize { fn parseTypes(
var i: usize = 0; allocator: Allocator,
types_elem: *xml.Element,
api: registry.Api,
decls: *std.ArrayList(registry.Declaration),
) !void {
var it = types_elem.findChildrenByTag("type"); var it = types_elem.findChildrenByTag("type");
while (it.next()) |ty| { while (it.next()) |ty| {
out[i] = blk: { try decls.append(allocator, blk: {
if (!requiredByApi(ty, api)) if (!requiredByApi(ty, api))
continue; continue;
@@ -80,12 +113,8 @@ fn parseTypes(allocator: Allocator, out: []registry.Declaration, types_elem: *xm
} }
continue; continue;
}; });
i += 1;
} }
return i;
} }
fn parseForeigntype(ty: *xml.Element) !registry.Declaration { fn parseForeigntype(ty: *xml.Element) !registry.Declaration {
@@ -336,10 +365,18 @@ fn parsePointerMeta(fields: Fields, type_info: *registry.TypeInfo, elem: *xml.El
else => break, else => break,
}; };
if (it.next()) |_| { if (it.next()) |_| ignore: {
// There are more elements in the `len` attribute than there are pointers // There are more elements in the `len` attribute than there are pointers
// Something probably went wrong // Something probably went wrong
std.log.err("len: {s}", .{lens}); switch (current_type_info.*) {
.name => |name| if (std.mem.eql(u8, name, "StdVideoH265SubLayerHrdParameters")) {
// Known issue: https://github.com/KhronosGroup/Vulkan-Docs/issues/2557
break :ignore;
},
else => {},
}
std.log.err("excessive pointer lengths: {s}", .{lens});
return error.InvalidRegistry; return error.InvalidRegistry;
} }
} }
@@ -388,8 +425,12 @@ fn parseEnumAlias(elem: *xml.Element) !?registry.Declaration {
return null; return null;
} }
fn parseEnums(allocator: Allocator, out: []registry.Declaration, root: *xml.Element, api: registry.Api) !usize { fn parseEnums(
var i: usize = 0; allocator: Allocator,
root: *xml.Element,
api: registry.Api,
decls: *std.ArrayList(registry.Declaration),
) !void {
var it = root.findChildrenByTag("enums"); var it = root.findChildrenByTag("enums");
while (it.next()) |enums| { while (it.next()) |enums| {
const name = enums.getAttribute("name") orelse return error.InvalidRegistry; const name = enums.getAttribute("name") orelse return error.InvalidRegistry;
@@ -397,14 +438,11 @@ fn parseEnums(allocator: Allocator, out: []registry.Declaration, root: *xml.Elem
continue; continue;
} }
out[i] = .{ try decls.append(allocator, .{
.name = name, .name = name,
.decl_type = .{ .enumeration = try parseEnumFields(allocator, enums, api) }, .decl_type = .{ .enumeration = try parseEnumFields(allocator, enums, api) },
}; });
i += 1;
} }
return i;
} }
fn parseEnumFields(allocator: Allocator, elem: *xml.Element, api: registry.Api) !registry.Enum { fn parseEnumFields(allocator: Allocator, elem: *xml.Element, api: registry.Api) !registry.Enum {
@@ -477,18 +515,19 @@ fn parseEnumField(field: *xml.Element) !registry.Enum.Field {
}; };
} }
fn parseCommands(allocator: Allocator, out: []registry.Declaration, commands_elem: *xml.Element, api: registry.Api) !usize { fn parseCommands(
var i: usize = 0; allocator: Allocator,
commands_elem: *xml.Element,
api: registry.Api,
decls: *std.ArrayList(registry.Declaration),
) !void {
var it = commands_elem.findChildrenByTag("command"); var it = commands_elem.findChildrenByTag("command");
while (it.next()) |elem| { while (it.next()) |elem| {
if (!requiredByApi(elem, api)) if (!requiredByApi(elem, api))
continue; continue;
out[i] = try parseCommand(allocator, elem, api); try decls.append(allocator, try parseCommand(allocator, elem, api));
i += 1;
} }
return i;
} }
fn splitCommaAlloc(allocator: Allocator, text: []const u8) ![][]const u8 { fn splitCommaAlloc(allocator: Allocator, text: []const u8) ![][]const u8 {
@@ -587,8 +626,13 @@ fn parseCommand(allocator: Allocator, elem: *xml.Element, api: registry.Api) !re
}; };
} }
fn parseApiConstants(allocator: Allocator, root: *xml.Element, api: registry.Api) ![]registry.ApiConstant { fn parseApiConstants(
var enums = blk: { allocator: Allocator,
root: *xml.Element,
api: registry.Api,
api_constants: *std.ArrayList(registry.ApiConstant),
) !void {
const maybe_enums = blk: {
var it = root.findChildrenByTag("enums"); var it = root.findChildrenByTag("enums");
while (it.next()) |child| { while (it.next()) |child| {
const name = child.getAttribute("name") orelse continue; const name = child.getAttribute("name") orelse continue;
@@ -597,52 +641,39 @@ fn parseApiConstants(allocator: Allocator, root: *xml.Element, api: registry.Api
} }
} }
return error.InvalidRegistry; break :blk null;
}; };
var types = root.findChildByTag("types") orelse return error.InvalidRegistry; if (maybe_enums) |enums| {
const n_defines = blk: { var it = enums.findChildrenByTag("enum");
var n_defines: usize = 0; while (it.next()) |constant| {
var it = types.findChildrenByTag("type"); if (!requiredByApi(constant, api))
while (it.next()) |ty| { continue;
if (ty.getAttribute("category")) |category| {
if (mem.eql(u8, category, "define")) { const expr = if (constant.getAttribute("value")) |expr|
n_defines += 1; expr
} else if (constant.getAttribute("alias")) |alias|
} alias
else
return error.InvalidRegistry;
try api_constants.append(allocator, .{
.name = constant.getAttribute("name") orelse return error.InvalidRegistry,
.value = .{ .expr = expr },
});
} }
break :blk n_defines;
};
const constants = try allocator.alloc(registry.ApiConstant, enums.children.len + n_defines);
var i: usize = 0;
var it = enums.findChildrenByTag("enum");
while (it.next()) |constant| {
if (!requiredByApi(constant, api))
continue;
const expr = if (constant.getAttribute("value")) |expr|
expr
else if (constant.getAttribute("alias")) |alias|
alias
else
return error.InvalidRegistry;
constants[i] = .{
.name = constant.getAttribute("name") orelse return error.InvalidRegistry,
.value = .{ .expr = expr },
};
i += 1;
} }
i += try parseDefines(types, constants[i..], api); const types = root.findChildByTag("types") orelse return error.InvalidRegistry;
return constants[0..i]; try parseDefines(allocator, types, api, api_constants);
} }
fn parseDefines(types: *xml.Element, out: []registry.ApiConstant, api: registry.Api) !usize { fn parseDefines(
var i: usize = 0; allocator: Allocator,
types: *xml.Element,
api: registry.Api,
api_constants: *std.ArrayList(registry.ApiConstant),
) !void {
var it = types.findChildrenByTag("type"); var it = types.findChildrenByTag("type");
while (it.next()) |ty| { while (it.next()) |ty| {
if (!requiredByApi(ty, api)) if (!requiredByApi(ty, api))
@@ -655,58 +686,45 @@ fn parseDefines(types: *xml.Element, out: []registry.ApiConstant, api: registry.
const name = ty.getCharData("name") orelse continue; const name = ty.getCharData("name") orelse continue;
if (mem.eql(u8, name, "VK_HEADER_VERSION") or mem.eql(u8, name, "VKSC_API_VARIANT")) { if (mem.eql(u8, name, "VK_HEADER_VERSION") or mem.eql(u8, name, "VKSC_API_VARIANT")) {
out[i] = .{ try api_constants.append(allocator, .{
.name = name, .name = name,
.value = .{ .expr = mem.trim(u8, ty.children[2].char_data, " ") }, .value = .{ .expr = mem.trim(u8, ty.children[2].char_data, " ") },
}; });
} else { } else {
var xctok = cparse.XmlCTokenizer.init(ty); var xctok = cparse.XmlCTokenizer.init(ty);
out[i] = .{ try api_constants.append(allocator, .{
.name = name, .name = name,
.value = .{ .version = cparse.parseVersion(&xctok) catch continue }, .value = cparse.parseVersion(&xctok) catch continue,
}; });
} }
i += 1;
} }
return i;
} }
fn parseTags(allocator: Allocator, root: *xml.Element) ![]registry.Tag { fn parseTags(
var tags_elem = root.findChildByTag("tags") orelse return error.InvalidRegistry; allocator: Allocator,
const tags = try allocator.alloc(registry.Tag, tags_elem.children.len); root: *xml.Element,
tags: *std.ArrayList(registry.Tag),
) !void {
var tags_elem = root.findChildByTag("tags") orelse return;
try tags.ensureUnusedCapacity(allocator, tags_elem.children.len);
var i: usize = 0;
var it = tags_elem.findChildrenByTag("tag"); var it = tags_elem.findChildrenByTag("tag");
while (it.next()) |tag| { while (it.next()) |tag| {
tags[i] = .{ tags.appendAssumeCapacity(.{
.name = tag.getAttribute("name") orelse return error.InvalidRegistry, .name = tag.getAttribute("name") orelse return error.InvalidRegistry,
.author = tag.getAttribute("author") orelse return error.InvalidRegistry, .author = tag.getAttribute("author") orelse return error.InvalidRegistry,
}; });
i += 1;
} }
return tags[0..i];
} }
fn parseFeatures(allocator: Allocator, root: *xml.Element, api: registry.Api) ![]registry.Feature { fn parseFeatures(allocator: Allocator, root: *xml.Element, api: registry.Api, features: *std.ArrayList(registry.Feature)) !void {
var it = root.findChildrenByTag("feature"); var it = root.findChildrenByTag("feature");
var count: usize = 0;
while (it.next()) |_| count += 1;
const features = try allocator.alloc(registry.Feature, count);
var i: usize = 0;
it = root.findChildrenByTag("feature");
while (it.next()) |feature| { while (it.next()) |feature| {
if (!requiredByApi(feature, api)) if (!requiredByApi(feature, api))
continue; continue;
features[i] = try parseFeature(allocator, feature, api); try features.append(allocator, try parseFeature(allocator, feature, api));
i += 1;
} }
return features[0..i];
} }
fn parseFeature(allocator: Allocator, feature: *xml.Element, api: registry.Api) !registry.Feature { fn parseFeature(allocator: Allocator, feature: *xml.Element, api: registry.Api) !registry.Feature {
@@ -736,11 +754,24 @@ fn parseFeature(allocator: Allocator, feature: *xml.Element, api: registry.Api)
fn parseEnumExtension(elem: *xml.Element, parent_extnumber: ?u31) !?registry.Require.EnumExtension { fn parseEnumExtension(elem: *xml.Element, parent_extnumber: ?u31) !?registry.Require.EnumExtension {
// check for either _SPEC_VERSION or _EXTENSION_NAME // check for either _SPEC_VERSION or _EXTENSION_NAME
const extends = elem.getAttribute("extends") orelse return null; const name = elem.getAttribute("name") orelse return error.InvalidRegistry;
if (std.mem.endsWith(u8, name, "_SPEC_VERSION") or std.mem.endsWith(u8, name, "_EXTENSION_NAME")) {
return null;
}
const extends = elem.getAttribute("extends") orelse {
const expr = elem.getAttribute("value") orelse return null;
// This adds a value to the 'API constants' set
return registry.Require.EnumExtension{
.extends = name,
.extnumber = null,
.value = .{ .new_api_constant_expr = expr },
};
};
if (elem.getAttribute("offset")) |offset_str| { if (elem.getAttribute("offset")) |offset_str| {
const offset = try std.fmt.parseInt(u31, offset_str, 10); const offset = try std.fmt.parseInt(u31, offset_str, 10);
const name = elem.getAttribute("name") orelse return error.InvalidRegistry;
const extnumber = if (elem.getAttribute("extnumber")) |num| const extnumber = if (elem.getAttribute("extnumber")) |num|
try std.fmt.parseInt(u31, num, 10) try std.fmt.parseInt(u31, num, 10)
else else
@@ -763,9 +794,11 @@ fn parseEnumExtension(elem: *xml.Element, parent_extnumber: ?u31) !?registry.Req
return registry.Require.EnumExtension{ return registry.Require.EnumExtension{
.extends = extends, .extends = extends,
.extnumber = actual_extnumber, .extnumber = actual_extnumber,
.field = .{ .value = .{
.name = name, .field = .{
.value = .{ .int = value }, .name = name,
.value = .{ .int = value },
},
}, },
}; };
} }
@@ -773,7 +806,7 @@ fn parseEnumExtension(elem: *xml.Element, parent_extnumber: ?u31) !?registry.Req
return registry.Require.EnumExtension{ return registry.Require.EnumExtension{
.extends = extends, .extends = extends,
.extnumber = parent_extnumber, .extnumber = parent_extnumber,
.field = try parseEnumField(elem), .value = .{ .field = try parseEnumField(elem) },
}; };
} }
@@ -844,11 +877,15 @@ fn parseRequire(allocator: Allocator, require: *xml.Element, extnumber: ?u31, ap
}; };
} }
fn parseExtensions(allocator: Allocator, root: *xml.Element, api: registry.Api) ![]registry.Extension { fn parseExtensions(
allocator: Allocator,
root: *xml.Element,
api: registry.Api,
extensions: *std.ArrayList(registry.Extension),
) !void {
const extensions_elem = root.findChildByTag("extensions") orelse return error.InvalidRegistry; const extensions_elem = root.findChildByTag("extensions") orelse return error.InvalidRegistry;
try extensions.ensureUnusedCapacity(allocator, extensions_elem.children.len);
const extensions = try allocator.alloc(registry.Extension, extensions_elem.children.len);
var i: usize = 0;
var it = extensions_elem.findChildrenByTag("extension"); var it = extensions_elem.findChildrenByTag("extension");
while (it.next()) |extension| { while (it.next()) |extension| {
if (!requiredByApi(extension, api)) if (!requiredByApi(extension, api))
@@ -860,14 +897,11 @@ fn parseExtensions(allocator: Allocator, root: *xml.Element, api: registry.Api)
} }
} }
extensions[i] = try parseExtension(allocator, extension, api); extensions.appendAssumeCapacity(try parseExtension(allocator, extension, api));
i += 1;
} }
return extensions[0..i];
} }
fn findExtVersion(extension: *xml.Element) !u32 { fn findExtVersion(extension: *xml.Element) !registry.Extension.Version {
var req_it = extension.findChildrenByTag("require"); var req_it = extension.findChildrenByTag("require");
while (req_it.next()) |req| { while (req_it.next()) |req| {
var enum_it = req.findChildrenByTag("enum"); var enum_it = req.findChildrenByTag("enum");
@@ -875,17 +909,23 @@ fn findExtVersion(extension: *xml.Element) !u32 {
const name = e.getAttribute("name") orelse continue; const name = e.getAttribute("name") orelse continue;
const value = e.getAttribute("value") orelse continue; const value = e.getAttribute("value") orelse continue;
if (mem.endsWith(u8, name, "_SPEC_VERSION")) { if (mem.endsWith(u8, name, "_SPEC_VERSION")) {
return try std.fmt.parseInt(u32, value, 10); // Vulkan Video extensions are sometimes aliases.
// If we fail to parse it as integer, just assume that its an alias and return that.
const version = std.fmt.parseInt(u32, value, 10) catch return .{ .alias = value };
return .{ .int = version };
} }
} }
} }
return error.InvalidRegistry; return .unknown;
} }
fn parseExtension(allocator: Allocator, extension: *xml.Element, api: registry.Api) !registry.Extension { fn parseExtension(allocator: Allocator, extension: *xml.Element, api: registry.Api) !registry.Extension {
const name = extension.getAttribute("name") orelse return error.InvalidRegistry; const name = extension.getAttribute("name") orelse return error.InvalidRegistry;
const platform = extension.getAttribute("platform"); const platform = extension.getAttribute("platform");
const is_video = std.mem.startsWith(u8, name, "vulkan_video_");
const version = try findExtVersion(extension); const version = try findExtVersion(extension);
// For some reason there are two ways for an extension to state its required // For some reason there are two ways for an extension to state its required
@@ -907,11 +947,14 @@ fn parseExtension(allocator: Allocator, extension: *xml.Element, api: registry.A
}; };
const number = blk: { const number = blk: {
// Vulkan Video extensions do not have numbers.
if (is_video) break :blk 0;
const number_str = extension.getAttribute("number") orelse return error.InvalidRegistry; const number_str = extension.getAttribute("number") orelse return error.InvalidRegistry;
break :blk try std.fmt.parseInt(u31, number_str, 10); break :blk try std.fmt.parseInt(u31, number_str, 10);
}; };
const ext_type: ?registry.Extension.ExtensionType = blk: { const ext_type: ?registry.Extension.ExtensionType = blk: {
if (is_video) break :blk .video;
const ext_type_str = extension.getAttribute("type") orelse break :blk null; const ext_type_str = extension.getAttribute("type") orelse break :blk null;
if (mem.eql(u8, ext_type_str, "instance")) { if (mem.eql(u8, ext_type_str, "instance")) {
break :blk .instance; break :blk .instance;

View File

@@ -42,6 +42,7 @@ pub const ApiConstant = struct {
pub const Value = union(enum) { pub const Value = union(enum) {
expr: []const u8, expr: []const u8,
version: [4][]const u8, version: [4][]const u8,
video_std_version: [3][]const u8,
}; };
name: []const u8, name: []const u8,
@@ -179,6 +180,7 @@ pub const Extension = struct {
pub const ExtensionType = enum { pub const ExtensionType = enum {
instance, instance,
device, device,
video,
}; };
pub const Promotion = union(enum) { pub const Promotion = union(enum) {
@@ -187,9 +189,15 @@ pub const Extension = struct {
extension: []const u8, extension: []const u8,
}; };
pub const Version = union(enum) {
int: u32,
alias: []const u8,
unknown,
};
name: []const u8, name: []const u8,
number: u31, number: u31,
version: u32, version: Version,
extension_type: ?ExtensionType, extension_type: ?ExtensionType,
depends: []const []const u8, // Other extensions depends: []const []const u8, // Other extensions
promoted_to: Promotion, promoted_to: Promotion,
@@ -200,9 +208,13 @@ pub const Extension = struct {
pub const Require = struct { pub const Require = struct {
pub const EnumExtension = struct { pub const EnumExtension = struct {
pub const Value = union(enum) {
field: Enum.Field,
new_api_constant_expr: []const u8,
};
extends: []const u8, extends: []const u8,
extnumber: ?u31, extnumber: ?u31,
field: Enum.Field, value: Value,
}; };
extends: []EnumExtension, extends: []EnumExtension,

File diff suppressed because it is too large Load Diff

View File

@@ -439,15 +439,15 @@ fn parseElement(parser: *Parser, alloc: Allocator, comptime kind: ElementKind) !
}, },
}; };
var attributes = std.ArrayList(Attribute).init(alloc); var attributes: std.ArrayList(Attribute) = .empty;
defer attributes.deinit(); defer attributes.deinit(alloc);
var children = std.ArrayList(Content).init(alloc); var children: std.ArrayList(Content) = .empty;
defer children.deinit(); defer children.deinit(alloc);
while (parser.eatWs()) { while (parser.eatWs()) {
const attr = (try parseAttr(parser, alloc)) orelse break; const attr = (try parseAttr(parser, alloc)) orelse break;
try attributes.append(attr); try attributes.append(alloc, attr);
} }
switch (kind) { switch (kind) {
@@ -464,7 +464,7 @@ fn parseElement(parser: *Parser, alloc: Allocator, comptime kind: ElementKind) !
} }
const content = try parseContent(parser, alloc); const content = try parseContent(parser, alloc);
try children.append(content); try children.append(alloc, content);
} }
const closing_tag = try parseNameNoDupe(parser); const closing_tag = try parseNameNoDupe(parser);
@@ -481,8 +481,8 @@ fn parseElement(parser: *Parser, alloc: Allocator, comptime kind: ElementKind) !
const element = try alloc.create(Element); const element = try alloc.create(Element);
element.* = .{ element.* = .{
.tag = try alloc.dupe(u8, tag), .tag = try alloc.dupe(u8, tag),
.attributes = try attributes.toOwnedSlice(), .attributes = try attributes.toOwnedSlice(alloc),
.children = try children.toOwnedSlice(), .children = try children.toOwnedSlice(alloc),
}; };
return element; return element;
} }

View File

@@ -21,7 +21,6 @@ pub const MTLTexture_id = u32;
pub const MTLSharedEvent_id = u32; pub const MTLSharedEvent_id = u32;
pub const IOSurfaceRef = u32; pub const IOSurfaceRef = u32;
// For some reason these types are exported in a different header, and not described in vk.xml.
pub const StdVideoH264ProfileIdc = u32; pub const StdVideoH264ProfileIdc = u32;
pub const StdVideoH264LevelIdc = u32; pub const StdVideoH264LevelIdc = u32;
pub const StdVideoH264ChromaFormatIdc = u32; pub const StdVideoH264ChromaFormatIdc = u32;
@@ -100,13 +99,13 @@ comptime {
fn reallyRefAllDecls(comptime T: type) void { fn reallyRefAllDecls(comptime T: type) void {
switch (@typeInfo(T)) { switch (@typeInfo(T)) {
.Struct, .Union => { .@"struct", .@"union" => {
reallyRefAllContainerDecls(T); reallyRefAllContainerDecls(T);
inline for (std.meta.fields(T)) |field| { inline for (std.meta.fields(T)) |field| {
reallyRefAllDecls(field.type); reallyRefAllDecls(field.type);
} }
}, },
.Enum, .Opaque => { .@"enum", .@"opaque" => {
reallyRefAllContainerDecls(T); reallyRefAllContainerDecls(T);
}, },
else => {}, else => {},