40 Commits

Author SHA1 Message Date
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
20 changed files with 2294 additions and 2034 deletions

View File

@@ -16,7 +16,7 @@ jobs:
- uses: actions/checkout@v4
- name: Setup Zig
uses: mlugg/setup-zig@v1
uses: mlugg/setup-zig@v2
with:
version: master
@@ -31,20 +31,30 @@ jobs:
sudo apt install shaderc libglfw3 libglfw3-dev
- 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
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
run: zig build --build-file $(pwd)/examples/build.zig
- name: Build example with latest zig & latest 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
uses: actions/upload-artifact@v4
with:
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

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:

122
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:
```zig
const vkzig_dep = b.dependency("vulkan_zig", .{
.registry = @as([]const u8, b.pathFromRoot("path/to/vk.xml")),
});
const vkzig_bindings = vkzig_dep.module("vulkan-zig");
exe.root_module.addImport("vulkan", vkzig_bindings);
const vulkan = b.dependency("vulkan_zig", .{
.registry = b.path("path/to/vk.xml"),
}).module("vulkan-zig");
exe.root_module.addImport("vulkan", vulkan);
```
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
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
const vk_generate_cmd = b.addRunArtifact(vk_gen);
// Pass the registry to the generator
generate_cmd.addArg(registry);
vk_generate_cmd.addFileArg(registry);
// Create a module from the generator's output...
const vulkan_zig = b.addModule("vulkan-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`.
* 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
pub const PfnCreateInstance = fn (
p_create_info: *const InstanceCreateInfo,
@@ -117,39 +138,21 @@ pub const PfnCreateInstance = fn (
) callconv(vulkan_call_conv) Result;
```
For each function, a wrapper is generated into one of three structs:
* BaseWrapper. This contains wrappers for functions which are loaded by `vkGetInstanceProcAddr` without an instance, such as `vkCreateInstance`, `vkEnumerateInstanceVersion`, etc.
* InstanceWrapper. This contains wrappers for functions which are otherwise loaded by `vkGetInstanceProcAddr`.
* DeviceWrapper. This contains wrappers for functions which are loaded by `vkGetDeviceProcAddr`.
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:
* Vulkan functions which are loaded by `vkGetInstanceProcAddr` without the need for passing an instance are placed in `BaseDispatch`.
* Vulkan functions which are loaded by `vkGetInstanceProcAddr` but do need an instance are placed in `InstanceDispatch`.
* 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:
```zig
pub const BaseWrapper(comptime cmds: anytype) type {
...
pub const BaseWrapper = struct {
const Self = @This();
const Dispatch = CreateDispatchStruct(cmds);
return struct {
dispatch: Dispatch,
pub const CreateInstanceError = error{
@@ -167,7 +170,7 @@ pub const BaseWrapper(comptime cmds: anytype) type {
p_allocator: ?*const AllocationCallbacks,
) CreateInstanceError!Instance {
var instance: Instance = undefined;
const result = self.dispatch.vkCreateInstance(
const result = self.dispatch.vkCreateInstance.?(
&create_info,
p_allocator,
&instance,
@@ -186,8 +189,7 @@ pub const BaseWrapper(comptime cmds: anytype) type {
}
...
}
}
};
```
Wrappers are generated according to the following rules:
* 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.
* 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.
* 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`.
* For `DeviceWrapper`, this function has signature `fn load(device: Device, loader: anytype) error{CommandFailure}!Self`, where the type of `loader` must resemble `PfnGetDeviceProcAddr`.
#### Initializing Wrappers
Wrapper types are initialized by the `load` function, which must be passed a _loader_: A function which loads a function pointer by name.
* 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`.
@@ -217,32 +221,33 @@ fn customGetInstanceProcAddress(instance: vk.Instance, procname: [*:0]const u8)
...
}
// Both calls are valid, even
const vkb = try BaseDispatch.load(glfwGetInstanceProcAddress);
const vkb = try BaseDispatch.load(customGetInstanceProcAddress);
// Both calls are valid.
const vkb = BaseWrapper.load(glfwGetInstanceProcAddress);
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 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
// Create the dispatch tables
const InstanceDispatch = vk.InstanceWrapper(apis);
const Instance = vk.InstanceProxy(apis);
const InstanceWrapper = vk.InstanceWrapper;
const Instance = vk.InstanceProxy;
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);
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.
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
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).
### 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
* 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 {
const target = b.standardTargetOptions(.{});
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 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
// 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
// a file source to the generated code with `.addOutputArg("vk.zig")`
const generator_exe = b.addExecutable(.{
.name = "vulkan-zig-generator",
.root_source_file = b.path("src/main.zig"),
.target = target,
.optimize = optimize,
.root_module = root_module,
});
b.installArtifact(generator_exe);
@@ -23,7 +28,12 @@ pub fn build(b: *std.Build) void {
if (maybe_registry) |registry| {
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_module = b.addModule("vulkan-zig", .{
@@ -41,16 +51,16 @@ pub fn build(b: *std.Build) void {
// It does not need to run anyway.
const ref_all_decls_test = b.addObject(.{
.name = "ref-all-decls-test",
.root_module = b.createModule(.{
.root_source_file = b.path("test/ref_all_decls.zig"),
.target = target,
.optimize = optimize,
}),
});
ref_all_decls_test.root_module.addImport("vulkan", vk_zig_module);
test_step.dependOn(&ref_all_decls_test.step);
}
const test_target = b.addTest(.{
.root_source_file = b.path("src/main.zig"),
});
const test_target = b.addTest(.{ .root_module = root_module });
test_step.dependOn(&b.addRunArtifact(test_target).step);
}

View File

@@ -1,5 +1,6 @@
.{
.name = "vulkan",
.name = .vulkan,
.fingerprint = 0xbe155a03c72db6af,
.version = "0.0.0",
.minimum_zig_version = "0.14.0-dev.1359+e9a00ba7f",
.paths = .{

View File

@@ -6,32 +6,69 @@ pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{});
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 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 triangle_exe = b.addExecutable(.{
.name = "triangle",
.root_module = b.createModule(.{
.root_source_file = b.path("triangle.zig"),
.target = target,
.link_libc = true,
.optimize = optimize,
}),
// TODO: Remove this once x86_64 is stable
.use_llvm = true,
});
b.installArtifact(triangle_exe);
triangle_exe.linkSystemLibrary("glfw");
const vk_gen = b.dependency("vulkan_zig", .{}).artifact("vulkan-zig-generator");
const vk_generate_cmd = b.addRunArtifact(vk_gen);
const registry_path: std.Build.LazyPath = if (maybe_override_registry) |override_registry|
.{ .cwd_relative = override_registry }
else
registry;
if (maybe_override_registry) |override_registry| {
vk_generate_cmd.addFileArg(.{ .cwd_relative = override_registry });
} else {
vk_generate_cmd.addFileArg(registry);
}
const vulkan = b.dependency("vulkan_zig", .{
.registry = registry_path,
}).module("vulkan-zig");
triangle_exe.root_module.addAnonymousImport("vulkan", .{
.root_source_file = vk_generate_cmd.addOutputFileArg("vk.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 {
const vert_cmd = b.addSystemCommand(&.{
"glslc",
"--target-env=vulkan1.2",
@@ -53,6 +90,7 @@ pub fn build(b: *std.Build) void {
triangle_exe.root_module.addAnonymousImport("fragment_shader", .{
.root_source_file = frag_spv,
});
}
const triangle_run_cmd = b.addRunArtifact(triangle_exe);
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",
.dependencies = .{
.vulkan_zig = .{
@@ -7,7 +8,7 @@
},
.vulkan_headers = .{
.url = "https://github.com/KhronosGroup/Vulkan-Headers/archive/v1.3.283.tar.gz",
.hash = "1220a7e73d72a0d56bc2a65f9d8999a7c019e42260a0744c408d1cded111bc205e10",
.hash = "N-V-__8AAAkkoQGn5z1yoNVrwqZfnYmZp8AZ5CJgoHRMQI0c",
},
},
.paths = .{""},

View File

@@ -5,38 +5,34 @@ const Allocator = std.mem.Allocator;
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.
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,
};
/// There are 3 levels of bindings in vulkan-zig:
/// - The Dispatch types (vk.BaseDispatch, vk.InstanceDispatch, vk.DeviceDispatch)
/// are "plain" structs which just contain the function pointers for a particular
/// object.
/// - The Wrapper types (vk.Basewrapper, vk.InstanceWrapper, vk.DeviceWrapper) contains
/// the Dispatch type, as well as Ziggified Vulkan functions - these return Zig errors,
/// etc.
/// - The Proxy types (vk.InstanceProxy, vk.DeviceProxy, vk.CommandBufferProxy,
/// 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
/// a wrapper struct as there is a problem with LLVM where embedding function pointers
/// and object pointer in the same struct leads to missed optimizations. If the wrapper
/// member is a pointer, LLVM will try to optimize it as any other vtable.
/// 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 BaseDispatch = vk.BaseWrapper(apis);
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);
const Instance = vk.InstanceProxy;
const Device = vk.DeviceProxy;
pub const GraphicsContext = struct {
pub const CommandBuffer = vk.CommandBufferProxy(apis);
pub const CommandBuffer = vk.CommandBufferProxy;
allocator: Allocator,
vkb: BaseDispatch,
vkb: BaseWrapper,
instance: Instance,
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 {
var self: GraphicsContext = undefined;
self.allocator = allocator;
self.vkb = try BaseDispatch.load(c.glfwGetInstanceProcAddress);
self.vkb = BaseWrapper.load(c.glfwGetInstanceProcAddress);
var extension_names = std.ArrayList([*:0]const u8).init(allocator);
defer extension_names.deinit();
// these extensions are to support vulkan in mac os
// see https://github.com/glfw/glfw/issues/2335
try extension_names.append("VK_KHR_portability_enumeration");
try extension_names.append("VK_KHR_get_physical_device_properties2");
var glfw_exts_count: u32 = 0;
const glfw_exts = c.glfwGetRequiredInstanceExtensions(&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,
};
try extension_names.appendSlice(@ptrCast(glfw_exts[0..glfw_exts_count]));
const instance = try self.vkb.createInstance(&.{
.p_application_info = &app_info,
.enabled_extension_count = glfw_exts_count,
.pp_enabled_extension_names = @ptrCast(glfw_exts),
.p_application_info = &.{
.p_application_name = app_name,
.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);
const vki = try allocator.create(InstanceDispatch);
const vki = try allocator.create(InstanceWrapper);
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);
errdefer self.instance.destroyInstance(null);
@@ -85,9 +90,9 @@ pub const GraphicsContext = struct {
const dev = try initializeCandidate(self.instance, candidate);
const vkd = try allocator.create(DeviceDispatch);
const vkd = try allocator.create(DeviceWrapper);
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);
errdefer self.dev.destroyDevice(null);

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
.exclusive;
const handle = try gc.dev.createSwapchainKHR(&.{
const handle = gc.dev.createSwapchainKHR(&.{
.surface = gc.surface,
.min_image_count = image_count,
.image_format = surface_format.format,
@@ -62,7 +62,9 @@ pub const Swapchain = struct {
.present_mode = present_mode,
.clipped = vk.TRUE,
.old_swapchain = old_handle,
}, null);
}, null) catch {
return error.SwapchainCreationFailed;
};
errdefer gc.dev.destroySwapchainKHR(handle, null);
if (old_handle != .null_handle) {
@@ -80,7 +82,11 @@ pub const Swapchain = struct {
errdefer gc.dev.destroySemaphore(next_image_acquired, null);
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;
}
@@ -109,6 +115,8 @@ pub const Swapchain = struct {
}
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.gc.dev.destroySwapchainKHR(self.handle, null);
}
@@ -118,7 +126,18 @@ pub const Swapchain = struct {
const allocator = self.allocator;
const old_handle = self.handle;
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 {

View File

@@ -63,6 +63,23 @@ pub fn main() !void {
) orelse return error.WindowInitFailed;
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(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
@@ -123,6 +140,7 @@ pub fn main() !void {
);
defer destroyCommandBuffers(&gc, pool, allocator, cmdbufs);
var state: Swapchain.PresentState = .optimal;
while (c.glfwWindowShouldClose(window) == c.GLFW_FALSE) {
var w: c_int = undefined;
var h: c_int = undefined;
@@ -136,11 +154,6 @@ pub fn main() !void {
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))) {
extent.width = @intCast(w);
extent.height = @intCast(h);
@@ -161,6 +174,10 @@ pub fn main() !void {
framebuffers,
);
}
state = swapchain.present(cmdbuf) catch |err| switch (err) {
error.OutOfDateKHR => Swapchain.PresentState.suboptimal,
else => |narrow| return narrow,
};
c.glfwPollEvents();
}

View File

@@ -52,13 +52,8 @@ pub fn isZigPrimitiveType(name: []const u8) bool {
return false;
}
pub fn writeIdentifier(writer: anytype, id: []const u8) !void {
// https://github.com/ziglang/zig/issues/2897
if (isZigPrimitiveType(id)) {
try writer.print("@\"{}\"", .{std.zig.fmtEscapes(id)});
} else {
try writer.print("{}", .{std.zig.fmtId(id)});
}
pub fn writeIdentifier(w: *std.io.Writer, id: []const u8) !void {
try w.print("{f}", .{std.zig.fmtId(id)});
}
pub const CaseStyle = enum {
@@ -196,13 +191,13 @@ pub const IdRenderer = struct {
}
}
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;
try std.fmt.format(self.text_cache.writer(), fmt, args);
try writeIdentifier(out, self.text_cache.items);
}
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);
// 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;

View File

@@ -8,21 +8,22 @@ fn invalidUsage(prog_name: []const u8, comptime fmt: []const u8, args: anytype)
}
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| {
const loc = tree.tokenLocation(0, err.token);
try stderr.print("(vulkan-zig error):{}:{}: error: ", .{ loc.line + 1, loc.column + 1 });
try tree.renderError(err, stderr);
try stderr.print("\n{s}\n", .{tree.source[loc.line_start..loc.line_end]});
try w.print("(vulkan-zig error):{}:{}: error: ", .{ loc.line + 1, loc.column + 1 });
try tree.renderError(err, w);
try w.print("\n{s}\n", .{tree.source[loc.line_start..loc.line_end]});
for (0..loc.column) |_| {
try stderr.writeAll(" ");
try w.writeAll(" ");
}
try stderr.writeAll("^\n");
try w.writeAll("^\n");
}
}
pub fn main() void {
pub fn main() !void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = arena.allocator();
@@ -34,13 +35,16 @@ pub fn main() void {
var maybe_xml_path: ?[]const u8 = null;
var maybe_out_path: ?[]const u8 = null;
var maybe_video_xml_path: ?[]const u8 = null;
var debug: bool = false;
var api = generator.Api.vulkan;
while (args.next()) |arg| {
if (std.mem.eql(u8, arg, "--help") or std.mem.eql(u8, arg, "-h")) {
@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.
\\
\\The most recent Vulkan XML API registry can be obtained from
@@ -53,12 +57,13 @@ pub fn main() void {
\\-h --help show this message and exit.
\\-a --api <api> Generate API for 'vulkan' or 'vulkansc'. Defaults to 'vulkan'.
\\--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},
) catch |err| {
std.log.err("failed to write to stdout: {s}", .{@errorName(err)});
std.process.exit(1);
std.process.fatal("failed to write to stdout: {s}", .{@errorName(err)});
};
return;
} else if (std.mem.eql(u8, arg, "-a") or std.mem.eql(u8, arg, "--api")) {
@@ -68,12 +73,16 @@ pub fn main() void {
api = std.meta.stringToEnum(generator.Api, api_str) orelse {
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) {
maybe_xml_path = arg;
} else if (maybe_out_path == null) {
maybe_out_path = arg;
} else if (std.mem.eql(u8, arg, "--debug")) {
debug = true;
} else {
invalidUsage(prog_name, "superficial argument '{s}'", .{arg});
}
@@ -89,12 +98,24 @@ pub fn main() void {
const cwd = std.fs.cwd();
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.exit(1);
std.process.fatal("failed to open input file '{s}' ({s})", .{ xml_path, @errorName(err) });
};
const maybe_video_xml_src = if (maybe_video_xml_path) |video_xml_path|
cwd.readFileAlloc(allocator, video_xml_path, std.math.maxInt(usize)) catch |err| {
std.process.fatal("failed to open input file '{s}' ({s})", .{ video_xml_path, @errorName(err) });
}
else
null;
var out_buffer = std.ArrayList(u8).init(allocator);
generator.generate(allocator, api, xml_src, out_buffer.writer()) catch |err| switch (err) {
var w = out_buffer.writer().adaptToNewApi();
generator.generate(allocator, api, xml_src, maybe_video_xml_src, &w.new_interface) catch |err| {
if (debug) {
return err;
}
switch (err) {
error.InvalidXml => {
std.log.err("invalid vulkan registry - invalid xml", .{});
std.log.err("please check that the correct vk.xml file is passed", .{});
@@ -111,7 +132,8 @@ pub fn main() void {
std.log.err("please make a bug report at https://github.com/Snektron/vulkan-zig/issues/", .{});
std.process.exit(1);
},
error.OutOfMemory => @panic("oom"),
error.OutOfMemory, error.WriteFailed => @panic("oom"),
}
};
out_buffer.append(0) catch @panic("oom");
@@ -128,22 +150,20 @@ pub fn main() void {
std.log.err("or run with --debug to write out unformatted source", .{});
reportParseErrors(tree) catch |err| {
std.log.err("failed to dump ast errors: {s}", .{@errorName(err)});
std.process.exit(1);
std.process.fatal("failed to dump ast errors: {s}", .{@errorName(err)});
};
if (debug) {
break :blk src;
}
std.process.exit(1);
} else tree.render(allocator) catch |err| switch (err) {
} else tree.renderAlloc(allocator) catch |err| switch (err) {
error.OutOfMemory => @panic("oom"),
};
if (std.fs.path.dirname(out_path)) |dir| {
cwd.makePath(dir) catch |err| {
std.log.err("failed to create output directory '{s}' ({s})", .{ dir, @errorName(err) });
std.process.exit(1);
std.process.fatal("failed to create output directory '{s}' ({s})", .{ dir, @errorName(err) });
};
}
@@ -151,8 +171,7 @@ pub fn main() void {
.sub_path = out_path,
.data = formatted,
}) catch |err| {
std.log.err("failed to write to output file '{s}' ({s})", .{ out_path, @errorName(err) });
std.process.exit(1);
std.process.fatal("failed to write to output file '{s}' ({s})", .{ out_path, @errorName(err) });
};
}

View File

@@ -90,10 +90,18 @@ pub const CTokenizer = struct {
const start = self.offset;
_ = self.consumeNoEof();
const hex = self.peek() == 'x';
if (hex) {
_ = self.consumeNoEof();
}
while (true) {
const c = self.peek() orelse break;
switch (c) {
switch (self.peek() orelse break) {
'0'...'9' => _ = self.consumeNoEof(),
'A'...'F', 'a'...'f' => {
if (!hex) break;
_ = self.consumeNoEof();
},
else => break,
}
}
@@ -164,7 +172,12 @@ pub const XmlCTokenizer = struct {
}
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;
}
@@ -175,8 +188,6 @@ pub const XmlCTokenizer = struct {
return Token{ .kind = .enum_name, .text = text };
} else if (mem.eql(u8, elem.tag, "name")) {
return Token{ .kind = .name, .text = text };
} else if (mem.eql(u8, elem.tag, "comment")) {
return null;
} else {
return error.InvalidTag;
}
@@ -530,7 +541,10 @@ fn parseArrayDeclarator(xctok: *XmlCTokenizer) !?ArraySize {
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,
};
@@ -538,7 +552,7 @@ fn parseArrayDeclarator(xctok: *XmlCTokenizer) !?ArraySize {
return size;
}
pub fn parseVersion(xctok: *XmlCTokenizer) ![4][]const u8 {
pub fn parseVersion(xctok: *XmlCTokenizer) !registry.ApiConstant.Value {
_ = try xctok.expect(.hash);
const define = try xctok.expect(.id);
if (!mem.eql(u8, define.text, "define")) {
@@ -547,12 +561,22 @@ pub fn parseVersion(xctok: *XmlCTokenizer) ![4][]const u8 {
_ = try xctok.expect(.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;
}
}
fn parseVersionValues(xctok: *XmlCTokenizer, comptime count: usize) ![count][]const u8 {
_ = try xctok.expect(.lparen);
var version: [4][]const u8 = undefined;
var version: [count][]const u8 = undefined;
for (&version, 0..) |*part, i| {
if (i != 0) {
_ = try xctok.expect(.comma);

View File

@@ -10,11 +10,13 @@ const FeatureLevel = reg.FeatureLevel;
const EnumFieldMerger = struct {
const EnumExtensionMap = std.StringArrayHashMapUnmanaged(std.ArrayListUnmanaged(reg.Enum.Field));
const ApiConstantMap = std.StringArrayHashMapUnmanaged(reg.ApiConstant);
const FieldSet = std.StringArrayHashMapUnmanaged(void);
arena: Allocator,
registry: *reg.Registry,
enum_extensions: EnumExtensionMap,
api_constants: ApiConstantMap,
field_set: FieldSet,
fn init(arena: Allocator, registry: *reg.Registry) EnumFieldMerger {
@@ -22,6 +24,7 @@ const EnumFieldMerger = struct {
.arena = arena,
.registry = registry,
.enum_extensions = .{},
.api_constants = .{},
.field_set = .{},
};
}
@@ -38,7 +41,17 @@ const EnumFieldMerger = struct {
fn addRequires(self: *EnumFieldMerger, reqs: []const reg.Require) !void {
for (reqs) |req| {
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 {
for (self.registry.api_constants) |api_constant| {
try self.api_constants.put(self.arena, api_constant.name, api_constant);
}
for (self.registry.features) |feature| {
try self.addRequires(feature.requires);
}
@@ -91,6 +108,8 @@ const EnumFieldMerger = struct {
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,
registry: reg.Registry,
id_renderer: IdRenderer,
have_video: bool,
fn init(allocator: Allocator, spec: *xml.Element, api: reg.Api) !Generator {
const result = try parseXml(allocator, spec, api);
fn init(allocator: Allocator, spec: *xml.Element, maybe_video_spec: ?*xml.Element, api: reg.Api) !Generator {
const result = try parseXml(allocator, spec, maybe_video_spec, api);
const tags = try allocator.alloc([]const u8, result.registry.tags.len);
for (tags, result.registry.tags) |*tag, registry_tag| tag.* = registry_tag.name;
@@ -109,6 +129,7 @@ pub const Generator = struct {
.arena = result.arena,
.registry = result.registry,
.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;
}
fn render(self: *Generator, writer: anytype) !void {
try renderRegistry(writer, self.arena.allocator(), &self.registry, &self.id_renderer);
fn render(self: *Generator, writer: *std.Io.Writer) !void {
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
/// 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`.
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) {
error.InvalidDocument,
error.UnexpectedEof,
@@ -195,7 +222,26 @@ pub fn generate(allocator: Allocator, api: Api, spec_xml: []const u8, writer: an
};
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.InvalidCharacter,
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);
errdefer arena.deinit();
const allocator = arena.allocator();
var decls: std.ArrayListUnmanaged(registry.Declaration) = .{};
var api_constants: std.ArrayListUnmanaged(registry.ApiConstant) = .{};
var tags: std.ArrayListUnmanaged(registry.Tag) = .{};
var features: std.ArrayListUnmanaged(registry.Feature) = .{};
var extensions: std.ArrayListUnmanaged(registry.Extension) = .{};
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{
.decls = try parseDeclarations(allocator, root, api),
.api_constants = try parseApiConstants(allocator, root, api),
.tags = try parseTags(allocator, root),
.features = try parseFeatures(allocator, root, api),
.extensions = try parseExtensions(allocator, root, api),
.decls = decls.items,
.api_constants = api_constants.items,
.tags = tags.items,
.features = features.items,
.extensions = extensions.items,
};
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.ArrayListUnmanaged(registry.Declaration),
) !void {
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;
const decls = try allocator.alloc(registry.Declaration, decl_upper_bound);
try parseTypes(allocator, types_elem, api, decls);
try parseEnums(allocator, root, api, decls);
var count: usize = 0;
count += try parseTypes(allocator, decls, types_elem, api);
count += try parseEnums(allocator, decls[count..], root, api);
count += try parseCommands(allocator, decls[count..], commands_elem, api);
return decls[0..count];
if (root.findChildByTag("commands")) |commands_elem| {
try decls.ensureUnusedCapacity(allocator, commands_elem.children.len);
try parseCommands(allocator, commands_elem, api, decls);
}
}
fn parseTypes(allocator: Allocator, out: []registry.Declaration, types_elem: *xml.Element, api: registry.Api) !usize {
var i: usize = 0;
fn parseTypes(
allocator: Allocator,
types_elem: *xml.Element,
api: registry.Api,
decls: *std.ArrayListUnmanaged(registry.Declaration),
) !void {
var it = types_elem.findChildrenByTag("type");
while (it.next()) |ty| {
out[i] = blk: {
try decls.append(allocator, blk: {
if (!requiredByApi(ty, api))
continue;
@@ -80,12 +113,8 @@ fn parseTypes(allocator: Allocator, out: []registry.Declaration, types_elem: *xm
}
continue;
};
i += 1;
});
}
return i;
}
fn parseForeigntype(ty: *xml.Element) !registry.Declaration {
@@ -336,10 +365,18 @@ fn parsePointerMeta(fields: Fields, type_info: *registry.TypeInfo, elem: *xml.El
else => break,
};
if (it.next()) |_| {
if (it.next()) |_| ignore: {
// There are more elements in the `len` attribute than there are pointers
// 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;
}
}
@@ -388,8 +425,12 @@ fn parseEnumAlias(elem: *xml.Element) !?registry.Declaration {
return null;
}
fn parseEnums(allocator: Allocator, out: []registry.Declaration, root: *xml.Element, api: registry.Api) !usize {
var i: usize = 0;
fn parseEnums(
allocator: Allocator,
root: *xml.Element,
api: registry.Api,
decls: *std.ArrayListUnmanaged(registry.Declaration),
) !void {
var it = root.findChildrenByTag("enums");
while (it.next()) |enums| {
const name = enums.getAttribute("name") orelse return error.InvalidRegistry;
@@ -397,14 +438,11 @@ fn parseEnums(allocator: Allocator, out: []registry.Declaration, root: *xml.Elem
continue;
}
out[i] = .{
try decls.append(allocator, .{
.name = name,
.decl_type = .{ .enumeration = try parseEnumFields(allocator, enums, api) },
};
i += 1;
});
}
return i;
}
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 {
var i: usize = 0;
fn parseCommands(
allocator: Allocator,
commands_elem: *xml.Element,
api: registry.Api,
decls: *std.ArrayListUnmanaged(registry.Declaration),
) !void {
var it = commands_elem.findChildrenByTag("command");
while (it.next()) |elem| {
if (!requiredByApi(elem, api))
continue;
out[i] = try parseCommand(allocator, elem, api);
i += 1;
try decls.append(allocator, try parseCommand(allocator, elem, api));
}
return i;
}
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 {
var enums = blk: {
fn parseApiConstants(
allocator: Allocator,
root: *xml.Element,
api: registry.Api,
api_constants: *std.ArrayListUnmanaged(registry.ApiConstant),
) !void {
const maybe_enums = blk: {
var it = root.findChildrenByTag("enums");
while (it.next()) |child| {
const name = child.getAttribute("name") orelse continue;
@@ -597,26 +641,10 @@ 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;
const n_defines = blk: {
var n_defines: usize = 0;
var it = types.findChildrenByTag("type");
while (it.next()) |ty| {
if (ty.getAttribute("category")) |category| {
if (mem.eql(u8, category, "define")) {
n_defines += 1;
}
}
}
break :blk n_defines;
};
const constants = try allocator.alloc(registry.ApiConstant, enums.children.len + n_defines);
var i: usize = 0;
if (maybe_enums) |enums| {
var it = enums.findChildrenByTag("enum");
while (it.next()) |constant| {
if (!requiredByApi(constant, api))
@@ -629,20 +657,23 @@ fn parseApiConstants(allocator: Allocator, root: *xml.Element, api: registry.Api
else
return error.InvalidRegistry;
constants[i] = .{
try api_constants.append(allocator, .{
.name = constant.getAttribute("name") orelse return error.InvalidRegistry,
.value = .{ .expr = expr },
};
i += 1;
});
}
}
i += try parseDefines(types, constants[i..], api);
return constants[0..i];
const types = root.findChildByTag("types") orelse return error.InvalidRegistry;
try parseDefines(allocator, types, api, api_constants);
}
fn parseDefines(types: *xml.Element, out: []registry.ApiConstant, api: registry.Api) !usize {
var i: usize = 0;
fn parseDefines(
allocator: Allocator,
types: *xml.Element,
api: registry.Api,
api_constants: *std.ArrayListUnmanaged(registry.ApiConstant),
) !void {
var it = types.findChildrenByTag("type");
while (it.next()) |ty| {
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;
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,
.value = .{ .expr = mem.trim(u8, ty.children[2].char_data, " ") },
};
});
} else {
var xctok = cparse.XmlCTokenizer.init(ty);
out[i] = .{
try api_constants.append(allocator, .{
.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,
tags: *std.ArrayListUnmanaged(registry.Tag),
) !void {
var tags_elem = root.findChildByTag("tags") orelse return;
try tags.ensureUnusedCapacity(allocator, tags_elem.children.len);
fn parseTags(allocator: Allocator, root: *xml.Element) ![]registry.Tag {
var tags_elem = root.findChildByTag("tags") orelse return error.InvalidRegistry;
const tags = try allocator.alloc(registry.Tag, tags_elem.children.len);
var i: usize = 0;
var it = tags_elem.findChildrenByTag("tag");
while (it.next()) |tag| {
tags[i] = .{
tags.appendAssumeCapacity(.{
.name = tag.getAttribute("name") 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.ArrayListUnmanaged(registry.Feature)) !void {
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| {
if (!requiredByApi(feature, api))
continue;
features[i] = try parseFeature(allocator, feature, api);
i += 1;
try features.append(allocator, try parseFeature(allocator, feature, api));
}
return features[0..i];
}
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 {
// 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| {
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|
try std.fmt.parseInt(u31, num, 10)
else
@@ -763,17 +794,19 @@ fn parseEnumExtension(elem: *xml.Element, parent_extnumber: ?u31) !?registry.Req
return registry.Require.EnumExtension{
.extends = extends,
.extnumber = actual_extnumber,
.value = .{
.field = .{
.name = name,
.value = .{ .int = value },
},
},
};
}
return registry.Require.EnumExtension{
.extends = extends,
.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.ArrayListUnmanaged(registry.Extension),
) !void {
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");
while (it.next()) |extension| {
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);
i += 1;
extensions.appendAssumeCapacity(try parseExtension(allocator, extension, api));
}
}
return extensions[0..i];
}
fn findExtVersion(extension: *xml.Element) !u32 {
fn findExtVersion(extension: *xml.Element) !registry.Extension.Version {
var req_it = extension.findChildrenByTag("require");
while (req_it.next()) |req| {
var enum_it = req.findChildrenByTag("enum");
@@ -875,17 +909,23 @@ fn findExtVersion(extension: *xml.Element) !u32 {
const name = e.getAttribute("name") orelse continue;
const value = e.getAttribute("value") orelse continue;
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 {
const name = extension.getAttribute("name") orelse return error.InvalidRegistry;
const platform = extension.getAttribute("platform");
const is_video = std.mem.startsWith(u8, name, "vulkan_video_");
const version = try findExtVersion(extension);
// 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: {
// Vulkan Video extensions do not have numbers.
if (is_video) break :blk 0;
const number_str = extension.getAttribute("number") orelse return error.InvalidRegistry;
break :blk try std.fmt.parseInt(u31, number_str, 10);
};
const ext_type: ?registry.Extension.ExtensionType = blk: {
if (is_video) break :blk .video;
const ext_type_str = extension.getAttribute("type") orelse break :blk null;
if (mem.eql(u8, ext_type_str, "instance")) {
break :blk .instance;

View File

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

View File

@@ -17,19 +17,19 @@ const preamble =
\\const Allocator = std.mem.Allocator;
\\
\\pub const vulkan_call_conv: std.builtin.CallingConvention = if (builtin.os.tag == .windows and builtin.cpu.arch == .x86)
\\ .Stdcall
\\ .winapi
\\ else if (builtin.abi == .android and (builtin.cpu.arch.isARM() or builtin.cpu.arch.isThumb()) and std.Target.arm.featureSetHas(builtin.cpu.features, .has_v7) and builtin.cpu.arch.ptrBitWidth() == 32)
\\ // On Android 32-bit ARM targets, Vulkan functions use the "hardfloat"
\\ // calling convention, i.e. float parameters are passed in registers. This
\\ // is true even if the rest of the application passes floats on the stack,
\\ // as it does by default when compiling for the armeabi-v7a NDK ABI.
\\ .AAPCSVFP
\\ .arm_aapcs_vfp
\\ else
\\ .C;
\\ .c;
// Note: Keep in sync with flag_functions
\\pub fn FlagsMixin(comptime FlagsType: type) type {
\\ return struct {
\\ pub const IntType = @typeInfo(FlagsType).Struct.backing_integer.?;
\\ pub const IntType = @typeInfo(FlagsType).@"struct".backing_integer.?;
\\ pub fn toInt(self: FlagsType) IntType {
\\ return @bitCast(self);
\\ }
@@ -81,27 +81,18 @@ const preamble =
\\ }
\\ };
\\}
\\pub fn makeApiVersion(variant: u3, major: u7, minor: u10, patch: u12) u32 {
\\ return (@as(u32, variant) << 29) | (@as(u32, major) << 22) | (@as(u32, minor) << 12) | patch;
\\}
\\pub fn apiVersionVariant(version: u32) u3 {
\\ return @truncate(version >> 29);
\\}
\\pub fn apiVersionMajor(version: u32) u7 {
\\ return @truncate(version >> 22);
\\}
\\pub fn apiVersionMinor(version: u32) u10 {
\\ return @truncate(version >> 12);
\\}
\\pub fn apiVersionPatch(version: u32) u12 {
\\ return @truncate(version);
\\pub const Version = packed struct(u32) {
\\ patch: u12,
\\ minor: u10,
\\ major: u7,
\\ variant: u3,
\\};
\\pub fn makeApiVersion(variant: u3, major: u7, minor: u10, patch: u12) Version {
\\ return .{ .variant = variant, .major = major, .minor = minor, .patch = patch };
\\}
\\pub const ApiInfo = struct {
\\ name: [:0]const u8 = "custom",
\\ version: u32 = makeApiVersion(0, 0, 0, 0),
\\ base_commands: BaseCommandFlags = .{},
\\ instance_commands: InstanceCommandFlags = .{},
\\ device_commands: DeviceCommandFlags = .{},
\\ version: Version = makeApiVersion(0, 0, 0, 0),
\\};
;
@@ -123,7 +114,7 @@ const command_flags_mixin =
\\ pub fn merge(lhs: CommandFlags, rhs: CommandFlags) CommandFlags {
\\ var result: CommandFlags = .{};
\\ @setEvalBranchQuota(10_000);
\\ inline for (@typeInfo(CommandFlags).Struct.fields) |field| {
\\ inline for (@typeInfo(CommandFlags).@"struct".fields) |field| {
\\ @field(result, field.name) = @field(lhs, field.name) or @field(rhs, field.name);
\\ }
\\ return result;
@@ -131,7 +122,7 @@ const command_flags_mixin =
\\ pub fn intersect(lhs: CommandFlags, rhs: CommandFlags) CommandFlags {
\\ var result: CommandFlags = .{};
\\ @setEvalBranchQuota(10_000);
\\ inline for (@typeInfo(CommandFlags).Struct.fields) |field| {
\\ inline for (@typeInfo(CommandFlags).@"struct".fields) |field| {
\\ @field(result, field.name) = @field(lhs, field.name) and @field(rhs, field.name);
\\ }
\\ return result;
@@ -139,7 +130,7 @@ const command_flags_mixin =
\\ pub fn complement(self: CommandFlags) CommandFlags {
\\ var result: CommandFlags = .{};
\\ @setEvalBranchQuota(10_000);
\\ inline for (@typeInfo(CommandFlags).Struct.fields) |field| {
\\ inline for (@typeInfo(CommandFlags).@"struct".fields) |field| {
\\ @field(result, field.name) = !@field(self, field.name);
\\ }
\\ return result;
@@ -147,14 +138,14 @@ const command_flags_mixin =
\\ pub fn subtract(lhs: CommandFlags, rhs: CommandFlags) CommandFlags {
\\ var result: CommandFlags = .{};
\\ @setEvalBranchQuota(10_000);
\\ inline for (@typeInfo(CommandFlags).Struct.fields) |field| {
\\ inline for (@typeInfo(CommandFlags).@"struct".fields) |field| {
\\ @field(result, field.name) = @field(lhs, field.name) and !@field(rhs, field.name);
\\ }
\\ return result;
\\ }
\\ pub fn contains(lhs: CommandFlags, rhs: CommandFlags) bool {
\\ @setEvalBranchQuota(10_000);
\\ inline for (@typeInfo(CommandFlags).Struct.fields) |field| {
\\ inline for (@typeInfo(CommandFlags).@"struct".fields) |field| {
\\ if (!@field(lhs, field.name) and @field(rhs, field.name)) {
\\ return false;
\\ }
@@ -214,6 +205,18 @@ const foreign_types = std.StaticStringMap([]const u8).initComptime(.{
.{ "_screen_window", "opaque {}" },
.{ "IDirectFB", "opaque {}" },
.{ "IDirectFBSurface", "opaque {}" },
.{ "NvSciSyncAttrList", "*opaque{}" },
.{ "NvSciSyncObj", "*opaque{}" },
.{ "NvSciSyncFence", "*opaque{}" },
.{ "NvSciBufAttrList", "*opaque{}" },
.{ "NvSciBufObj", "*opaque{}" },
// We don't know the true size of these but whatever Stadia is dead anyway.
.{ "GgpStreamDescriptor", "*opaque{}" },
.{ "GgpFrameToken", "*opaque{}" },
// The Vulkan Video tokens cannot be "opaque {}" and have to be handled
// separately.
.{ "StdVideoVP9Profile", "u32" },
.{ "StdVideoVP9Level", "u32" },
});
const CommandDispatchType = enum {
@@ -333,11 +336,9 @@ pub fn trimVkNamespace(id: []const u8) []const u8 {
return id;
}
fn Renderer(comptime WriterType: type) type {
return struct {
const Renderer = struct {
const Self = @This();
const WriteError = WriterType.Error;
const RenderTypeInfoError = WriteError || std.fmt.ParseIntError || error{ OutOfMemory, InvalidRegistry };
const RenderTypeInfoError = std.Io.Writer.Error || std.fmt.ParseIntError || error{ OutOfMemory, InvalidRegistry };
const BitflagName = struct {
/// Name without FlagBits, so VkSurfaceTransformFlagBitsKHR
@@ -371,29 +372,47 @@ fn Renderer(comptime WriterType: type) type {
},
};
writer: WriterType,
writer: *std.Io.Writer,
allocator: Allocator,
registry: *const reg.Registry,
id_renderer: *IdRenderer,
declarations_by_name: std.StringHashMap(*const reg.DeclarationType),
decls_by_name: std.StringArrayHashMap(reg.DeclarationType),
structure_types: std.StringHashMap(void),
have_video: bool,
fn init(writer: WriterType, allocator: Allocator, registry: *const reg.Registry, id_renderer: *IdRenderer) !Self {
var declarations_by_name = std.StringHashMap(*const reg.DeclarationType).init(allocator);
errdefer declarations_by_name.deinit();
fn init(
writer: *std.Io.Writer,
allocator: Allocator,
registry: *const reg.Registry,
id_renderer: *IdRenderer,
have_video: bool,
) !Self {
var decls_by_name = std.StringArrayHashMap(reg.DeclarationType).init(allocator);
errdefer decls_by_name.deinit();
for (registry.decls) |*decl| {
const result = try declarations_by_name.getOrPut(decl.name);
const result = try decls_by_name.getOrPut(decl.name);
if (result.found_existing) {
// Allow overriding 'foreign' types. These are for example the Vulkan Video types
// declared as foreign type in the vk.xml, then defined in video.xml. Sometimes
// this also includes types like uint32_t, for these we don't really care.
// Just make sure to keep the non-foreign variant.
if (result.value_ptr.* == .foreign) {
result.value_ptr.* = decl.decl_type;
} else if (decl.decl_type == .foreign) {
// Foreign type trying to override a non-foreign one. Just keep the current
// one, and don't generate an error.
} else {
std.log.err("duplicate registry entry '{s}'", .{decl.name});
return error.InvalidRegistry;
}
result.value_ptr.* = &decl.decl_type;
} else {
result.value_ptr.* = decl.decl_type;
}
}
const vk_structure_type_decl = declarations_by_name.get("VkStructureType") orelse return error.InvalidRegistry;
const vk_structure_type = switch (vk_structure_type_decl.*) {
const vk_structure_type_decl = decls_by_name.get("VkStructureType") orelse return error.InvalidRegistry;
const vk_structure_type = switch (vk_structure_type_decl) {
.enumeration => |e| e,
else => return error.InvalidRegistry,
};
@@ -409,13 +428,14 @@ fn Renderer(comptime WriterType: type) type {
.allocator = allocator,
.registry = registry,
.id_renderer = id_renderer,
.declarations_by_name = declarations_by_name,
.decls_by_name = decls_by_name,
.structure_types = structure_types,
.have_video = have_video,
};
}
fn deinit(self: *Self) void {
self.declarations_by_name.deinit();
self.decls_by_name.deinit();
}
fn writeIdentifier(self: Self, id: []const u8) !void {
@@ -501,8 +521,8 @@ fn Renderer(comptime WriterType: type) type {
}
fn resolveDeclaration(self: Self, name: []const u8) ?reg.DeclarationType {
const decl = self.declarations_by_name.get(name) orelse return null;
return self.resolveAlias(decl.*) catch return null;
const decl = self.decls_by_name.get(name) orelse return null;
return self.resolveAlias(decl) catch return null;
}
fn resolveAlias(self: Self, start_decl: reg.DeclarationType) !reg.DeclarationType {
@@ -513,8 +533,7 @@ fn Renderer(comptime WriterType: type) type {
else => return decl,
};
const decl_ptr = self.declarations_by_name.get(name) orelse return error.InvalidRegistry;
decl = decl_ptr.*;
decl = self.decls_by_name.get(name) orelse return error.InvalidRegistry;
}
}
@@ -614,17 +633,23 @@ fn Renderer(comptime WriterType: type) type {
fn render(self: *Self) !void {
try self.writer.writeAll(preamble);
try self.writer.print("pub const have_vulkan_video = {};\n", .{self.have_video});
for (self.registry.api_constants) |api_constant| {
try self.renderApiConstant(api_constant);
}
for (self.registry.decls) |decl| {
try self.renderDecl(decl);
for (self.decls_by_name.keys(), self.decls_by_name.values()) |name, decl_type| {
try self.renderDecl(.{
.name = name,
.decl_type = decl_type,
});
}
try self.renderCommandPtrs();
try self.renderFeatureInfo();
try self.renderExtensionInfo();
try self.renderDispatchTables();
try self.renderWrappers();
try self.renderProxies();
}
@@ -636,8 +661,12 @@ fn Renderer(comptime WriterType: type) type {
switch (api_constant.value) {
.expr => |expr| try self.renderApiConstantExpr(expr),
.version => |version| {
inline .version, .video_std_version => |version, kind| {
try self.writer.writeAll("makeApiVersion(");
// For Vulkan Video, just re-use the API version and set the variant to 0.
if (kind == .video_std_version) {
try self.writer.writeAll("0, ");
}
for (version, 0..) |part, i| {
if (i != 0) {
try self.writer.writeAll(", ");
@@ -688,6 +717,7 @@ fn Renderer(comptime WriterType: type) type {
} else if (mem.eql(u8, suffix.text, "U")) {
try self.writer.print("@as(u32, {s})", .{tok.text});
} else {
std.debug.print("aaa {s}\n", .{suffix.text});
return error.InvalidApiConstant;
}
},
@@ -894,16 +924,134 @@ fn Renderer(comptime WriterType: type) type {
.{maybe_author orelse ""},
);
return true;
} else if (std.mem.eql(u8, basename, "VkClusterAccelerationStructureBuildTriangleClusterInfo")) {
try self.writer.print(
\\extern struct {{
\\ cluster_id: u32,
\\ cluster_flags: ClusterAccelerationStructureClusterFlags{0s},
\\ cluster_data: packed struct(u32) {{
\\ triangle_count: u9,
\\ vertex_count: u9,
\\ position_truncate_bit_count: u6,
\\ index_type: u4,
\\ opacity_micromap_index_type: u4,
\\ }},
\\ base_geometry_index_and_geometry_flags: ClusterAccelerationStructureGeometryIndexAndGeometryFlags{0s},
\\ index_buffer_stride: u16,
\\ vertex_buffer_stride: u16,
\\ geometry_index_and_flags_buffer_stride: u16,
\\ opacity_micromap_index_buffer_stride: u16,
\\ index_buffer: DeviceAddress,
\\ vertex_buffer: DeviceAddress,
\\ geometry_index_and_flags_buffer: DeviceAddress,
\\ opacity_micromap_array: DeviceAddress,
\\ opacity_micromap_index_buffer: DeviceAddress,
\\}};
,
.{maybe_author orelse ""},
);
return true;
} else if (std.mem.eql(u8, basename, "VkClusterAccelerationStructureBuildTriangleClusterTemplateInfo")) {
try self.writer.print(
\\extern struct {{
\\ cluster_id: u32,
\\ cluster_flags: ClusterAccelerationStructureClusterFlags{0s},
\\ cluster_data: packed struct(u32) {{
\\ triangle_count: u9,
\\ vertex_count: u9,
\\ position_truncate_bit_count: u6,
\\ index_type: u4,
\\ opacity_micromap_index_type: u4,
\\ }},
\\ base_geometry_index_and_geometry_flags: ClusterAccelerationStructureGeometryIndexAndGeometryFlags{0s},
\\ index_buffer_stride: u16,
\\ vertex_buffer_stride: u16,
\\ geometry_index_and_flags_buffer_stride: u16,
\\ opacity_micromap_index_buffer_stride: u16,
\\ index_buffer: DeviceAddress,
\\ vertex_buffer: DeviceAddress,
\\ geometry_index_and_flags_buffer: DeviceAddress,
\\ opacity_micromap_array: DeviceAddress,
\\ opacity_micromap_index_buffer: DeviceAddress,
\\ instantiation_bounding_box_limit: DeviceAddress,
\\}};
,
.{maybe_author orelse ""},
);
return true;
} else if (std.mem.eql(u8, basename, "VkClusterAccelerationStructureInstantiateClusterInfo")) {
try self.writer.print(
\\extern struct {{
\\ cluster_id_offset: u32,
\\ geometry_index_offset: packed struct(u32) {{
\\ offset: u24,
\\ reserved: u8 = 0,
\\ }},
\\ cluster_template_address: DeviceAddress,
\\ vertex_buffer: StridedDeviceAddress{0s},
\\}};
,
.{maybe_author orelse ""},
);
return true;
}
return false;
}
fn renderSimpleBitContainer(self: *Self, container: reg.Container) !bool {
var total_bits: usize = 0;
var is_flags_container = true;
for (container.fields) |field| {
const bits = field.bits orelse {
// C abi type - not a packed struct.
return false;
};
total_bits += bits;
if (bits != 1) {
is_flags_container = false;
}
}
try self.writer.writeAll("packed struct(u32) {");
for (container.fields) |field| {
const bits = field.bits.?;
try self.writeIdentifierWithCase(.snake, field.name);
try self.writer.writeAll(": ");
// Default-zero fields that look like they are not used.
if (std.mem.eql(u8, field.name, "reserved")) {
try self.writer.print(" u{} = 0,\n", .{field.bits.?});
} else if (bits == 1) {
// Assume its a flag.
if (is_flags_container) {
try self.writer.writeAll(" bool = false,\n");
} else {
try self.writer.writeAll(" bool,\n");
}
} else {
try self.writer.print(" u{},\n", .{field.bits.?});
}
}
if (total_bits != 32) {
try self.writer.print("_reserved: u{} = 0,\n", .{32 - total_bits});
}
try self.writer.writeAll("};\n");
return true;
}
fn renderContainer(self: *Self, name: []const u8, container: reg.Container) !void {
try self.writer.writeAll("pub const ");
try self.renderName(name);
try self.writer.writeAll(" = ");
if (try self.renderSimpleBitContainer(container)) {
return;
}
if (try self.renderSpecialContainer(name)) {
return;
}
@@ -1150,7 +1298,9 @@ fn Renderer(comptime WriterType: type) type {
}
fn renderForeign(self: *Self, name: []const u8, foreign: reg.Foreign) !void {
if (mem.eql(u8, foreign.depends, "vk_platform")) {
if (mem.eql(u8, foreign.depends, "vk_platform") or
builtin_types.get(name) != null)
{
return; // Skip built-in types, they are handled differently
}
@@ -1181,18 +1331,18 @@ fn Renderer(comptime WriterType: type) type {
}
fn renderCommandPtrs(self: *Self) !void {
for (self.registry.decls) |decl| {
switch (decl.decl_type) {
for (self.decls_by_name.keys(), self.decls_by_name.values()) |name, decl_type| {
switch (decl_type) {
.command => {
try self.writer.writeAll("pub const ");
try self.renderCommandPtrName(decl.name);
try self.renderCommandPtrName(name);
try self.writer.writeAll(" = ");
try self.renderCommandPtr(decl.decl_type.command, false);
try self.renderCommandPtr(decl_type.command, false);
try self.writer.writeAll(";\n");
},
.alias => |alias| if (alias.target == .other_command) {
try self.writer.writeAll("pub const ");
try self.renderCommandPtrName(decl.name);
try self.renderCommandPtrName(name);
try self.writer.writeAll(" = ");
try self.renderCommandPtrName(alias.name);
try self.writer.writeAll(";\n");
@@ -1207,62 +1357,15 @@ fn Renderer(comptime WriterType: type) type {
\\pub const features = struct {
\\
);
// The commands in a feature level are not pre-sorted based on if they are instance or device functions.
var base_commands = std.BufSet.init(self.allocator);
defer base_commands.deinit();
var instance_commands = std.BufSet.init(self.allocator);
defer instance_commands.deinit();
var device_commands = std.BufSet.init(self.allocator);
defer device_commands.deinit();
for (self.registry.features) |feature| {
try self.writer.writeAll("pub const ");
try self.writeIdentifierWithCase(.snake, trimVkNamespace(feature.name));
try self.writer.writeAll("= ApiInfo {\n");
try self.writer.print(".name = \"{s}\", .version = makeApiVersion(0, {}, {}, 0),", .{
try self.writer.print(".name = \"{s}\", .version = makeApiVersion(0, {}, {}, 0),\n}};\n", .{
trimVkNamespace(feature.name),
feature.level.major,
feature.level.minor,
});
// collect feature information
for (feature.requires) |require| {
for (require.commands) |command_name| {
const decl = self.resolveDeclaration(command_name) orelse continue;
// If the target type does not exist, it was likely an empty enum -
// assume spec is correct and that this was not a function alias.
const decl_type = self.resolveAlias(decl) catch continue;
const command = switch (decl_type) {
.command => |cmd| cmd,
else => continue,
};
const class = classifyCommandDispatch(command_name, command);
switch (class) {
.base => {
try base_commands.insert(command_name);
},
.instance => {
try instance_commands.insert(command_name);
},
.device => {
try device_commands.insert(command_name);
},
}
}
}
// and write them out
// clear command lists for next iteration
try self.writer.writeAll(".base_commands = ");
try self.renderCommandFlags(&base_commands);
base_commands.hash_map.clearRetainingCapacity();
try self.writer.writeAll(".instance_commands = ");
try self.renderCommandFlags(&instance_commands);
instance_commands.hash_map.clearRetainingCapacity();
try self.writer.writeAll(".device_commands = ");
try self.renderCommandFlags(&device_commands);
device_commands.hash_map.clearRetainingCapacity();
try self.writer.writeAll("};\n");
}
try self.writer.writeAll("};\n");
@@ -1273,71 +1376,60 @@ fn Renderer(comptime WriterType: type) type {
\\pub const extensions = struct {
\\
);
// The commands in an extension are not pre-sorted based on if they are instance or device functions.
var base_commands = std.BufSet.init(self.allocator);
defer base_commands.deinit();
var instance_commands = std.BufSet.init(self.allocator);
defer instance_commands.deinit();
var device_commands = std.BufSet.init(self.allocator);
defer device_commands.deinit();
for (self.registry.extensions) |ext| {
try self.writer.writeAll("pub const ");
if (ext.extension_type == .video) {
// These are already in the right form, and the auto-casing style transformer
// is prone to messing up these names.
try self.writeIdentifier(trimVkNamespace(ext.name));
} else {
try self.writeIdentifierWithCase(.snake, trimVkNamespace(ext.name));
}
try self.writer.writeAll("= ApiInfo {\n");
try self.writer.print(".name = \"{s}\", .version = {},", .{ ext.name, ext.version });
// collect extension functions
for (ext.requires) |require| {
for (require.commands) |command_name| {
const decl = self.resolveDeclaration(command_name) orelse continue;
// If the target type does not exist, it was likely an empty enum -
// assume spec is correct and that this was not a function alias.
const decl_type = self.resolveAlias(decl) catch continue;
const command = switch (decl_type) {
try self.writer.print(".name = \"{s}\", .version = ", .{ext.name});
switch (ext.version) {
.int => |version| try self.writer.print("makeApiVersion(0, {}, 0, 0)", .{version}),
// This should be the same as in self.renderApiConstant.
// We assume that this is already a vk.Version type.
.alias => |alias| try self.renderName(alias),
.unknown => try self.writer.writeAll("makeApiVersion(0, 0, 0, 0)"),
}
try self.writer.writeAll(",};\n");
}
try self.writer.writeAll("};\n");
}
fn renderDispatchTables(self: *Self) !void {
try self.renderDispatchTable(.base);
try self.renderDispatchTable(.instance);
try self.renderDispatchTable(.device);
}
fn renderDispatchTable(self: *Self, dispatch_type: CommandDispatchType) !void {
try self.writer.print(
"pub const {s}Dispatch = struct {{\n",
.{dispatch_type.name()},
);
for (self.decls_by_name.keys(), self.decls_by_name.values()) |name, decl_type| {
const final_decl_type = self.resolveAlias(decl_type) catch continue;
const command = switch (final_decl_type) {
.command => |cmd| cmd,
else => continue,
};
const class = classifyCommandDispatch(command_name, command);
switch (class) {
.base => {
try base_commands.insert(command_name);
},
.instance => {
try instance_commands.insert(command_name);
},
.device => {
try device_commands.insert(command_name);
},
}
}
}
// and write them out
try self.writer.writeAll(".base_commands = ");
try self.renderCommandFlags(&base_commands);
base_commands.hash_map.clearRetainingCapacity();
try self.writer.writeAll(".instance_commands = ");
try self.renderCommandFlags(&instance_commands);
instance_commands.hash_map.clearRetainingCapacity();
if (classifyCommandDispatch(name, command) != dispatch_type) {
continue;
}
try self.writer.writeAll(".device_commands = ");
try self.renderCommandFlags(&device_commands);
device_commands.hash_map.clearRetainingCapacity();
try self.writeIdentifier(name);
try self.writer.writeAll(": ?");
try self.renderCommandPtrName(name);
try self.writer.writeAll(" = null,\n");
}
try self.writer.writeAll("};\n");
}
try self.writer.writeAll("};\n");
}
fn renderCommandFlags(self: *Self, commands: *const std.BufSet) !void {
try self.writer.writeAll(".{\n");
var iterator = commands.iterator();
while (iterator.next()) |command_name| {
try self.writer.writeAll(".");
try self.writeIdentifierWithCase(.camel, trimVkNamespace(command_name.*));
try self.writer.writeAll(" = true, \n");
}
try self.writer.writeAll("},\n");
}
fn renderWrappers(self: *Self) !void {
try self.writer.writeAll(command_flags_mixin);
@@ -1348,130 +1440,17 @@ fn Renderer(comptime WriterType: type) type {
fn renderWrappersOfDispatchType(self: *Self, dispatch_type: CommandDispatchType) !void {
const name = dispatch_type.name();
const name_lower = dispatch_type.nameLower();
try self.writer.print(
\\pub const {0s}CommandFlags = packed struct {{
\\
, .{name});
for (self.registry.decls) |decl| {
// If the target type does not exist, it was likely an empty enum -
// assume spec is correct and that this was not a function alias.
const decl_type = self.resolveAlias(decl.decl_type) catch continue;
const command = switch (decl_type) {
.command => |cmd| cmd,
else => continue,
};
if (classifyCommandDispatch(decl.name, command) == dispatch_type) {
try self.writer.writeAll(" ");
try self.writeIdentifierWithCase(.camel, trimVkNamespace(decl.name));
try self.writer.writeAll(": bool = false,\n");
}
}
try self.writer.print(
\\pub fn CmdType(comptime tag: std.meta.FieldEnum({0s}CommandFlags)) type {{
\\ return switch (tag) {{
\\
, .{name});
for (self.registry.decls) |decl| {
// If the target type does not exist, it was likely an empty enum -
// assume spec is correct and that this was not a function alias.
const decl_type = self.resolveAlias(decl.decl_type) catch continue;
const command = switch (decl_type) {
.command => |cmd| cmd,
else => continue,
};
if (classifyCommandDispatch(decl.name, command) == dispatch_type) {
try self.writer.writeByte('.');
try self.writeIdentifierWithCase(.camel, trimVkNamespace(decl.name));
try self.writer.writeAll(" => ");
try self.renderCommandPtrName(decl.name);
try self.writer.writeAll(",\n");
}
}
try self.writer.writeAll(" };\n}");
try self.writer.print(
\\pub fn cmdName(tag: std.meta.FieldEnum({0s}CommandFlags)) [:0]const u8 {{
\\ return switch(tag) {{
\\
, .{name});
for (self.registry.decls) |decl| {
// If the target type does not exist, it was likely an empty enum -
// assume spec is correct and that this was not a function alias.
const decl_type = self.resolveAlias(decl.decl_type) catch continue;
const command = switch (decl_type) {
.command => |cmd| cmd,
else => continue,
};
if (classifyCommandDispatch(decl.name, command) == dispatch_type) {
try self.writer.writeByte('.');
try self.writeIdentifierWithCase(.camel, trimVkNamespace(decl.name));
try self.writer.print(
\\ => "{s}",
\\
, .{decl.name});
}
}
try self.writer.writeAll(" };\n}");
try self.renderFlagFunctions(name, "CommandFlagsMixin", command_flag_functions, "CommandFlags");
try self.writer.print(
\\}};
\\pub fn {0s}Wrapper(comptime apis: []const ApiInfo) type {{
\\pub const {0s}Wrapper = {0s}WrapperWithCustomDispatch({0s}Dispatch);
\\pub fn {0s}WrapperWithCustomDispatch(DispatchType: type) type {{
\\ return struct {{
\\ const Self = @This();
\\ pub const Dispatch = DispatchType;
\\
\\ dispatch: Dispatch,
\\
\\ const Self = @This();
\\ pub const commands = blk: {{
\\ var cmds: {0s}CommandFlags = .{{}};
\\ for (apis) |api| {{
\\ cmds = cmds.merge(api.{1s}_commands);
\\ }}
\\ break :blk cmds;
\\ }};
\\ pub const Dispatch = blk: {{
\\ @setEvalBranchQuota(1_000_000);
\\ const Type = std.builtin.Type;
\\ const fields_len = fields_len: {{
\\ var fields_len: u32 = 0;
\\ for (@typeInfo({0s}CommandFlags).Struct.fields) |field| {{
\\ fields_len += @intCast(@intFromBool(@field(commands, field.name)));
\\ }}
\\ break :fields_len fields_len;
\\ }};
\\ var fields: [fields_len]Type.StructField = undefined;
\\ var i: usize = 0;
\\ for (@typeInfo({0s}CommandFlags).Struct.fields) |field| {{
\\ if (@field(commands, field.name)) {{
\\ const field_tag = std.enums.nameCast(std.meta.FieldEnum({0s}CommandFlags), field.name);
\\ const PfnType = {0s}CommandFlags.CmdType(field_tag);
\\ fields[i] = .{{
\\ .name = {0s}CommandFlags.cmdName(field_tag),
\\ .type = PfnType,
\\ .default_value = null,
\\ .is_comptime = false,
\\ .alignment = @alignOf(PfnType),
\\ }};
\\ i += 1;
\\ }}
\\ }}
\\ break :blk @Type(.{{
\\ .Struct = .{{
\\ .layout = .auto,
\\ .fields = &fields,
\\ .decls = &[_]std.builtin.Type.Declaration{{}},
\\ .is_tuple = false,
\\ }},
\\ }});
\\ }};
\\
, .{ name, name_lower });
, .{name});
try self.renderWrapperLoader(dispatch_type);
@@ -1516,24 +1495,10 @@ fn Renderer(comptime WriterType: type) type {
@setEvalBranchQuota(2000);
try self.writer.print(
\\pub fn load({[params]s}) error{{CommandLoadFailure}}!Self {{
\\ var self: Self = undefined;
\\pub fn load({[params]s}) Self {{
\\ var self: Self = .{{ .dispatch = .{{}} }};
\\ inline for (std.meta.fields(Dispatch)) |field| {{
\\ const name: [*:0]const u8 = @ptrCast(field.name ++ "\x00");
\\ if (loader({[first_arg]s}, name)) |cmd_ptr| {{
\\ @field(self.dispatch, field.name) = @ptrCast(cmd_ptr);
\\ }} else {{
\\ std.log.err("Command loading failed for \"{{s}}\".", .{{field.name}});
\\ return error.CommandLoadFailure;
\\ }}
\\ }}
\\ return self;
\\}}
\\pub fn loadNoFail({[params]s}) Self {{
\\ var self: Self = undefined;
\\ inline for (std.meta.fields(Dispatch)) |field| {{
\\ const name: [*:0]const u8 = @ptrCast(field.name ++ "\x00");
\\ const cmd_ptr = loader({[first_arg]s}, name) orelse undefined;
\\ const cmd_ptr = loader({[first_arg]s}, field.name.ptr) orelse undefined;
\\ @field(self.dispatch, field.name) = @ptrCast(cmd_ptr);
\\ }}
\\ return self;
@@ -1557,13 +1522,16 @@ fn Renderer(comptime WriterType: type) type {
const loader_name = dispatch_type.name();
try self.writer.print(
\\pub fn {0s}Proxy(comptime apis: []const ApiInfo) type {{
\\ @setEvalBranchQuota(100_000);
\\pub const {0s}Proxy = {0s}ProxyWithCustomDispatch({1s}Dispatch);
\\pub fn {0s}ProxyWithCustomDispatch(DispatchType: type) type {{
\\ return struct {{
\\ const Self = @This();
\\ pub const Wrapper = {1s}Wrapper(apis);
\\ pub const Wrapper = {1s}WrapperWithCustomDispatch(DispatchType);
\\
\\ handle: {0s},
// Note: This is a pointer because in the past there were some performance
// issues with putting an object and vtable in the same structure. This also
// affected std.mem.Allocator, which is why its like that too.
\\ wrapper: *const Wrapper,
\\
\\ pub fn init(handle: {0s}, wrapper: *const Wrapper) Self {{
@@ -1684,11 +1652,13 @@ fn Renderer(comptime WriterType: type) type {
const params = command.params[0 .. command.params.len - 2];
const data_type = try getEnumerateFunctionDataType(command);
if (returns_vk_result) {
try self.writer.writeAll("pub const ");
try self.renderErrorSetName(name);
try self.writer.writeAll(" = Wrapper.");
try self.renderErrorSetName(name);
try self.writer.writeAll(";\n");
}
try self.renderAllocWrapperPrototype(name, params, returns_vk_result, data_type, dispatch_handle, .proxy);
try self.writer.writeAll(
@@ -1817,7 +1787,7 @@ fn Renderer(comptime WriterType: type) type {
) !void {
try self.writer.writeAll("self.dispatch.");
try self.writeIdentifier(name);
try self.writer.writeAll("(");
try self.writer.writeAll(".?(");
for (command.params) |param| {
switch (try self.classifyParam(param)) {
@@ -2143,10 +2113,15 @@ fn Renderer(comptime WriterType: type) type {
}
}
};
}
pub fn render(writer: anytype, allocator: Allocator, registry: *const reg.Registry, id_renderer: *IdRenderer) !void {
var renderer = try Renderer(@TypeOf(writer)).init(writer, allocator, registry, id_renderer);
pub fn render(
writer: *std.Io.Writer,
allocator: Allocator,
registry: *const reg.Registry,
id_renderer: *IdRenderer,
have_video: bool,
) !void {
var renderer = try Renderer.init(writer, allocator, registry, id_renderer, have_video);
defer renderer.deinit();
try renderer.render();
}

View File

@@ -21,7 +21,6 @@ pub const MTLTexture_id = u32;
pub const MTLSharedEvent_id = 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 StdVideoH264LevelIdc = u32;
pub const StdVideoH264ChromaFormatIdc = u32;
@@ -100,13 +99,13 @@ comptime {
fn reallyRefAllDecls(comptime T: type) void {
switch (@typeInfo(T)) {
.Struct, .Union => {
.@"struct", .@"union" => {
reallyRefAllContainerDecls(T);
inline for (std.meta.fields(T)) |field| {
reallyRefAllDecls(field.type);
}
},
.Enum, .Opaque => {
.@"enum", .@"opaque" => {
reallyRefAllContainerDecls(T);
},
else => {},