Lua logo

Preface

This is the reference manual of MoonVulkan, which is a Lua binding library for the Khronos Vulkan API. [1]

It is assumed that the reader is familiar with both Vulkan and the Lua programming language.

For convenience of reference, this document contains external (deep) links to the Lua Reference Manual, the Vulkan API Reference Pages, and the Vulkan Specification.

Getting and installing

For installation intructions, refer to the README file in the MoonVulkan official repository on GitHub.

Module organization

The MoonVulkan module is loaded using Lua’s require() and returns a table containing the functions it provides (as usual with Lua modules). This manual assumes that such table is named vk, i.e. that it is loaded with:

 vk = require("moonvulkan")

but nothing forbids the use of a different name.

Examples

Complete examples can be found in the examples/ directory of the release package.

License

MoonVulkan is released under the MIT/X11 license (same as Lua, and with the same only requirement to give proper credits to the original author). The copyright notice is in the LICENSE file in the base directory of the official repository on GitHub.

See also

MoonVulkan is part of MoonLibs, a collection of Lua libraries for graphics and audio programming.

Introduction

MoonVulkan is an (almost) one-to-one Lua binding library to the Vulkan API. It provides means to implement scripted Vulkan applications using Lua instead of C or C++, with all its pros and cons. You can think of it as a 'working pseudocode', less efficient but easier to write and read and to work with.

This section gives a brief overview, while the details of the bindings are given in the sections that follow.

As a general rule, Vulkan API functions are bound to by MoonVulkan functions whose names are snake_case versions of the original ones (for example, vkCreateInstance( ) is bound to by vk.create_instance( )).

If not stated otherwise, on error all MoonVulkan functions raise a Lua error. If needed, this behaviour can be overridden by wrapping function calls in the standard Lua pcall( ).

MoonVulkan avoids performing validations that can be delegated to Vulkan validation layers, and limits its error checks to the minimum needed to protect itself from script errors.

MoonVulkan binds Vulkan objects (instance, device, etc.) to Lua userdata, which are returned by the creating or allocating functions (vk.create_instance( ), vk.create_device( ), etc) and are then used to refer to objects in Lua in the same way as one would use Vulkan handles in C.

In the rest of this manual we will refer to userdata bound to Vulkan objects as to just 'objects', or as 'MoonVulkan objects' (vs. 'Vulkan objects') when there is need for disambiguation.

Occasionally, the actual Vulkan handles may be needed by the Lua code, mainly to interoperate in very dangerous ways with other libraries that access the Vulkan API directly. Handles can be retrieved with the raw( ) method that every object has.

Objects are garbage collected at exit (which includes on error) with automatic destruction/free at the Vulkan level, so there is no need to explicitly invoke the bindings to vkDestroy/FreeXxx( ) at exit for cleanup.

Apart from at exit, however, objects are not automatically garbage collected [2] and one should destroy/free them explicitly when needed, e.g. to release resources when the application is not exiting and some objects are no longer needed.

Destroying/freeing an object causes the automatic (pre) destruction of all its children objects, and the invalidation of any reference to the object and to its children. [3]

Vulkan structs (and lists, and arrays) that are used to pass parameters and results across the Vulkan API are mapped in MoonVulkan to tables, having more or less the same contents as their C counterparts but, again, with snake_case named fields. Enumerations are mapped to/from sets of string literals, while flags bitmasks are represented as plain integers encoded in the same way as in C. More details are given in the respective sections of this document (structs, enums, flags).

In addition to the bindings to the Vulkan API, which are described in the sections that follow, MoonVulkan also provides a few other utilities and object 'methods' that do not correspond to Vulkan functions. These are described mainly in the 'Miscellanea' subsections.

MoonVulkan does not support multithreading, at least for now. Support for multi-threaded applications is under study and may be added in the future (although one could argue that if performance is paramount for the application, maybe using a binding library to a dynamic, garbage-collected language is not the way to go).

Objects

The following tree shows the MoonVulkan (Vulkan) objects and their parent-child relationships.

instance (VkInstance)
├─ physical_device (VkPhysicalDevice)
│   └─ display (VkDisplayKHR)
│       └─ display_mode (VkDisplayModeKHR)
├─ device (VkDevice)
│   ├─ queue (VkQueue)
│   ├─ command_pool (VkCommandPool)
│   │   └─ command_buffer (VkCommandBuffer)
│   ├─ fence (VkFence)
│   ├─ semaphore (VkSemaphore)
│   ├─ event (VkEvent)
│   ├─ render_pass (VkRenderPass)
│   ├─ framebuffer (VkFramebuffer)
│   ├─ shader_module (VkShaderModule )
│   ├─ pipeline (VkPipeline)
│   ├─ pipeline_cache (VkPipelineCache)
│   ├─ device_memory (VkDeviceMemory)
│   ├─ buffer (VkBuffer)
│   │   └─ buffer_view (VkBufferView)
│   ├─ image (VkImage)
│   │   └─ image_view (VkImageView)
│   ├─ sampler (VkSampler)
│   ├─ descriptor_set_layout (VkDescriptorSetLayout)
│   ├─ pipeline_layout (VkPipelineLayout)
│   ├─ descriptor_pool (VkDescriptorPool)
│   │   └─ descriptor_set (VkDescriptorSet)
│   ├─ descriptor_update_template (VkDescriptorUpdateTemplateKHR)
│   ├─ validation_cache (VkValidationCacheEXT)
│   ├─ sampler_ycbcr_conversion (VkSamplerYcbcrConversionKHR)
│   ├─ query_pool (VkQueryPool)
│   └─ swapchain (VkSwapchainKHR)
│       └─ image (VkImage, present)
├─ surface (VkSurfaceKHR)
├─ debug_report_callback (VkDebugReportCallbackEXT)
└─ debug_utils_messenger (VkDebugUtilsMessengerEXT)

(Notice that the image object is listed two times because it may be either created by the application or acquired from a swapchain).

Core functions

This section lists the MoonVulkan bindings to the core Vulkan API functions.

Only the synopses are given. The functionalities, usages, and meanings of parameters and return values are basically the same as for the underlying Vulkan API.

The structure of this section purposedly reflects the structure of the Vulkan Specification, from chapter 3 onward.

Initialization

instance

Devices and Queues

physical_device

In this document, physdev is an abbreviation for physical_device when referring to a variable or a return value.

device

queue

Command Buffers

command_pool

command_buffer

In this document, cb is an abbreviation for command_buffer when referring to a variable or a return value.

Synchronization

fence

  • boolean = get_fence_status(fence)
    Returns true if the given fence is ready, false otherwise.
    Rfr: vkGetFenceStatus.

  • boolean = wait_for_fences({fence}, waitall, [timeout])
    waitall: boolean
    Returns true on success, false on timeout.
    Rfr: vkWaitForFences.

semaphore

event

  • boolean = get_event_status(event)
    Returns true if the given event is set, false otherwise.
    Rfr: vkGetEventStatus.

Render Pass

Rfr: Render Pass.

render_pass

framebuffer

Shaders

Rfr: Shaders.

shader_module

Pipelines

Rfr: Pipelines.

pipeline

pipeline_cache

  • data = get_pipeline_cache_data(pipeline_cache)
    Returns data as a binary string.
    Rfr: vkGetPipelineCacheData.

  • merge_pipeline_caches(destination, {source})
    destination, source: pipeline_cache
    Rfr: vkMergePipelineCaches.

Memory Allocation

device_memory

In this document, devmem is an abbreviation for device_memory when referring to a variable or a return value.

  • ptr = map_memory(devmem, offset, size, [memorymapflags])
    offset: integer
    size: integer or 'whole size'
    The returned ptr value is a lightuserdata containing the raw pointer to the mapped memory.
    Rfr: vkMapMemory.

  • write_memory(devmem, offset, data)
    offset: integer
    data: binary string.

  • data = read_memory(devmem, offset, size)
    offset: integer
    size: integer or 'whole size'
    Returns data as a binary string.





Resource Creation

buffer

buffer_view

image

image_view

Samplers

Rfr: Samplers.

sampler

Resource Descriptors

descriptor_set_layout

pipeline_layout

descriptor_pool

descriptor_set

Queries

Rfr: Queries.

query_pool

  • data = destroy_query_pool(query_pool, first_query, …​)
    arg2 - first_query: integer
    arg3 - query_count: integer
    arg4 - data_size: integer
    arg5 - size: integer
    arg6 - flags: queryresultflags
    Returns data as a binary string.
    Rfr: vkDestroyQueryPool.

Commands

The first argument (cb) of all the following functions is a command_buffer.

  • cmd_dispatch_base(cb, basegroup_x, basegroup_y, basegroup_z, groupcount_x, groupcount_y, groupcount_z)
    Rfr: vkCmdDispatchBase.

  • cmd_fill_buffer(cb, dst_buffer, dst_offset, size, data)
    dst_buffer: buffer
    dst_offset: integer
    size: integer (multiple of 4) or 'whole size'
    data: integer
    Rfr: vkCmdFillBuffer.

  • cmd_update_buffer(cb, dst_buffer, dst_offset, data)
    dst_buffer: buffer
    dst_offset: integer
    data: binary string (n x 4 bytes)
    Rfr: vkCmdUpdateBuffer.

Layers and extensions

Enumerate extensions

Each of the following functions returns an integer-indexed array unless it is called with byname=true, in which case the returned table is indexed by name. For example, vk.enumerate_instance_layer_properties(true) returns a table indexed by layer_name (which is usually more convenient).

Note
Device layers are deprecated (rfr: 'Device Layer Deprecation'). As a consequence, with up to date Vulkan implementations, the enumerate_device_layer_properties( ) function will always return an empty list, and the layer parameter in the enumerate_device_extension_properties( ) is irrelevant.

Supported extensions

MoonVulkan supports the core Vulkan API, plus most of the Khronos (KHR) and multivendor (EXT) extensions.

It also supports any extension that does not require API calls other than that for enabling it.

It does not support Khronos experimental extensions (KHX) and single vendor extensions (AMD, GOOGLE, NV, …​).

Surfaces (KHR)

surface

  • surface = created_surface(instance, surfaceRAW, [allocator])
    surfaceRAW: a valid VkSurfaceKHR handle (integer) for the given instance.
    Creates and returns a surface userdata (MoonVulkan object) bound to the given handle.
    (See 'Creating surfaces by other means' for details on how to use this function.)


Platform-specific surface API

Platform-specific surface API are available only if MoonVulkan was compiled with support enabled for the desired platforms. This is not needed if surfaces are created using MoonGLFW or equivalent libraries that handle platform-specific details.

(Hint: Use MoonGLFW, avoid compiling for specific platforms, and ignore this section).


  • surface = create_xlib_surface(instance, flags, dpy, window, [allocator])
    dpy: lightuserdata (Display*)
    window: lightuserdata (Window)
    Rfr: vkCreateXlibSurfaceKHR.


  • surface = create_xcb_surface(instance, flags, connection, window, [allocator])
    connection: lightuserdata (xcb_connection_t*)
    Rfr: vkCreateXcbSurfaceKHR.


  • surface = create_wayland_surface(instance, flags, wldisplay, wlsurface, [allocator])
    wldisplay: lightuserdata (wl_display*)
    wlsurface: lightuserdata (wl_surface*)
    Rfr: vkCreateWaylandSurfaceKHR.


  • surface = create_win32_surface(instance, flags, hinstance, hwnd, [allocator])
    hinstance: lightuserdata (HINSTANCE)
    hwnd: lightuserdata (HWND)
    Rfr: vkCreateWin32SurfaceKHR.


Displays (KHR)

display


display_mode

Swapchains (KHR)

swapchain

  • result, {result} = queue_present(queue, presentinfo, [per_swapchain_results])
    [per_swapchain_results]: boolean
    Returns the global result for the operation, optionally followed by a table with the individual results for each of the given swapchains.
    The individual results table is returned only if per_swapchain_results is true.
    Rfr: vkQueuePresentKHR.

Other (KHR)

descriptor_update_template

sampler_ycbcr_conversion

Other (EXT)

debug_report

debug_marker

debug_utils

validation_cache

calibrated_timestamps

Structs

This section describes the tables used in MoonVulkan to pass Vulkan API structures from Lua to C and viceversa.

The correspondence between the tables and the underlying C structs is almost one-to-one [4]. Fields in tables are named with snake_case versions of their C equivalents (without the leading p's denoting pointers in C), and have the same semantics.

When a table is passed from C to Lua, all its fields are always present unless otherwise explicitly stated in the descriptions below.

When passing a table from Lua to C, if a field is annotated with [R] it is required and must be explicitly set, otherwise it is optional. If an optional field is not set, the following default value(s) will be used unless otherwise specified in the field’s description:

  • fields that admit a 'not present' encoding will be encoded as such,

  • flags default to 0,

  • enums default to the value indicated as default for their type in the Enums section,

  • booleans default to false,

  • integers, floats, and numbers in general default to 0,

  • strings default to NULL (not present).

(note that a default value may not necessarily be considered valid by the Vulkan API: if you need to check this, use the validation layers).

The tables are described as fieldname:valuetype lists of fields, where fieldname is the key of the field in the Lua table, and valuetype is the type its value must be of. The notation {valuetype} denotes an array of valuetype elements (by 'array' we mean a table with 1-based integer keys and no gaps, a.k.a. 'sequence' in Lua’s jargon).


Basic types used in the table description that follow:

  • boolean: a Lua boolean.

  • integer: a Lua integer.

  • float: a Lua number that fits in a float32.

  • string: a NUL terminated Lua string.

  • binary string: a Lua binary string.

  • timeout = integer (nanoseconds) or 'blocking' or nil (both for blocking).

  • index = 0-based integer index.

  • devicesize: a Lua integer or the string 'whole size'.

Note
0-based indices that are used as identifiers in the Vulkan C API, like queue indices or queue family indices, are 0-based also in MoonVulkan functions and structs. They are not remapped to Lua-style 1-based indices to avoid confusion when using the validation layers. Care must be taken, however, when deducing their values from positions in Lua tables (for example, the queue_family_index of the i-th element in the table returned by get_physical_device_queue_family_properties( ) is i-1).

  • layerproperties = {
    layer_name: string,
    spec_version: integer,
    implementation_version: integer,
    description: string,
    } (rfr: VkLayerProperties)

  • extensionproperties = {
    extension_name: string,
    spec_version: integer,
    } (rfr: VkExtensionProperties)


  • applicationinfo = {
    application_name: string,
    application_version: integer,
    engine_name: string,
    engine_version: integer,
    api_version: integer,
    } (rfr: VkApplicationInfo)






















  • memoryrequirements = {
    size: integer,
    alignment: integer,
    memory_type_bits: integer,
    -- EXTENSION VkMemoryDedicatedRequirements:
    prefers_dedicated_allocation: boolean,
    requires_dedicated_allocation: boolean,
    } (rfr: VkMemoryRequirements2)

  • sparseimagememoryrequirements = {
    format_properties: sparseimageformatproperties,
    image_mip_tail_first_lod: integer,
    image_mip_tail_size: integer,
    image_mip_tail_offset: integer,
    image_mip_tail_stride: integer,
    } (rfr: VkSparseImageMemoryRequirements2)

  • subresourcelayout = {
    offset: integer,
    size: integer,
    row_pitch: integer,
    array_pitch: integer,
    depth_pitch: integer,
    } (rfr: VkSubresourceLayout)

  • imagesubresource = {
    aspect_mask: imageaspectflags,
    mip_level: integer,
    array_layer: integer,
    } (rfr: VkImageSubresource)
    Constructor: imagesubresource(aspect_mask, mip_level, array_layer)

  • imagesubresourcerange = {
    aspect_mask: imageaspectflags,
    base_mip_level: integer,
    level_count: integer or 'remaining' (defaults to 1),
    base_array_layer: integer,
    layer_count: integer or 'remaining' (defaults to 1),
    } (rfr: VkImageSubresourceRange)
    Constructor: imagesubresourcerange(aspect_mask, base_mip_level, level_count, base_array_layer, layer_count)

















  • hdrmetadata = {
    display_primary_red: xycolor,
    display_primary_green: xycolor,
    display_primary_blue: xycolor,
    white_point: xycolor,
    max_luminance: float,
    min_luminance: float,
    max_content_light_level: float,
    max_frame_average_light_level: float,
    } (rfr: VkHdrMetadataEXT)

  • xycolor = { x, y: float, }
    (rfr: VkXYColorEXT)


  • multidrawinfo = {
    first_vertex: integer,
    vertex_count: integer,
    } (rfr: VkMultiDrawInfoEXT)

  • multidrawindexedinfo = {
    first_index: integer,
    index_count: integer,
    vertex_offset: integer,
    } (rfr: VkMultiDrawIndexedInfoEXT)







Enums

Vulkan enums are mapped in MoonVulkan to sets of string literals (as is customary in Lua). Admitted literals are available in the vk table (e.g. vk.BLEND_OP_XXX for VK_BLEND_OP_XXX), and can also be inferred from the corresponding C enum names. For example, given the vk.BLEND_OP_XXX hint for the blendop enum type, the literals it admits are obtained by lowercasing the XXX part of the name and replacing any underscore with a space. Any extension suffix such as _KHR or _EXT is removed.

The example contained in the code snippets section should hopefully be clear enough.

If needed, the following function can be used to obtain the list of literals admitted by a particular enum type.

  • {literal} = vk.enum(enumtype)
    Returns a table listing the literals admitted by enumtype (given as a string, e.g. 'blendop', 'format', etc).

Below is the list of the enum types, each with its hint, the list of string values it admits (if not too long), and a reference to the original Vulkan enum type where to look for semantic and usage information.

result: vk.XXX (results), vk.ERROR_XXX (errors)
Values: 'success', 'not ready', 'timeout', 'unknown', 'event set', 'event reset', 'incomplete', 'out of host memory', 'out of device memory', 'initialization failed', 'device lost', 'memory map failed', 'layer not present', 'extension not present', 'feature not present', 'incompatible driver', 'too many objects', 'format not supported', 'fragmented pool', 'surface lost', 'native window in use', 'suboptimal', 'out of date', 'incompatible display', 'validation failed', 'out of pool memory', 'invalid external handle', 'not permitted', 'fragmentation', 'invalid drm format modifier plane layout', 'invalid opaque capture address', 'full screen exclusive mode lost', 'thread idle', 'thread done', 'operation deferred', 'operation not deferred', 'pipeline compile required'.
Rfr: VkResult.

accelerationstructurebuildtype: vk.ACCELERATION_STRUCTURE_BUILD_TYPE_XXX
Values: 'host', 'device', 'host or device'.
Rfr: VkAccelerationStructureBuildTypeKHR.

accelerationstructurecompatibility: vk.ACCELERATION_STRUCTURE_COMPATIBILITY_XXX
Values: 'compatible', 'incompatible'.
Rfr: VkAccelerationStructureCompatibilityKHR.

accelerationstructuretype: vk.ACCELERATION_STRUCTURE_TYPE_XXX
Values: 'top level', 'bottom level', 'generic'.
Rfr: VkAccelerationStructureTypeKHR.

attachmentloadop: vk.ATTACHMENT_LOAD_OP_XXX
Values: 'load', 'clear', 'dont care' (default), 'none'.
Rfr: VkAttachmentLoadOp.

attachmentstoreop: vk.ATTACHMENT_STORE_OP_XXX
Values: 'store', 'dont care' (default), 'none'.
Rfr: VkAttachmentStoreOp.

blendfactor: vk.BLEND_FACTOR_XXX
Values: 'zero' (default), 'one', 'src color', 'one minus src color', 'dst color', 'one minus dst color', 'src alpha', 'one minus src alpha', 'dst alpha', 'one minus dst alpha', 'constant color', 'one minus constant color', 'constant alpha', 'one minus constant alpha', 'src alpha saturate', 'src1 color', 'one minus src1 color', 'src1 alpha', 'one minus src1 alpha'.
Rfr: VkBlendFactor.

blendop: vk.BLEND_OP_XXX, vk.BLEND_OP_XXX
Values: 'add' (default), 'subtract', 'reverse subtract', 'min', 'max', 'zero', 'src', 'dst', 'src over', 'dst over', 'src in', 'dst in', 'src out', 'dst out', 'src atop', 'dst atop', 'xor', 'multiply', 'screen', 'overlay', 'darken', 'lighten', 'colordodge', 'colorburn', 'hardlight', 'softlight', 'difference', 'exclusion', 'invert', 'invert rgb', 'lineardodge', 'linearburn', 'vividlight', 'linearlight', 'pinlight', 'hardmix', 'hsl hue', 'hsl saturation', 'hsl color', 'hsl luminosity', 'plus', 'plus clamped', 'plus clamped alpha', 'plus darker', 'minus', 'minus clamped', 'contrast', 'invert ovg', 'red', 'green', 'blue'.
Rfr: VkBlendOp.

blendoverlap: vk.BLEND_OVERLAP_XXX
Values: 'uncorrelated' (default), 'disjoint', 'conjoint'.
Rfr: VkBlendOverlapEXT.

bordercolor: vk.BORDER_COLOR_XXX
Values: 'float transparent black' (default), 'int transparent black', 'float opaque black', 'int opaque black', 'float opaque white', 'int opaque white', 'float custom', 'int custom'.
Rfr: VkBorderColor.

buildaccelerationstructuremode: vk.BUILD_ACCELERATION_STRUCTURE_MODE_XXX
Values: 'build', 'update'.
Rfr: VkBuildAccelerationStructureModeKHR.

chromalocation: vk.CHROMA_LOCATION_XXX
Values: 'cosited even' (default), 'midpoint'.
Rfr: VkChromaLocation.

colorspace: vk.COLOR_SPACE_XXX, vk.COLOR_SPACE_XXX
Values: 'srgb nonlinear' (default), 'display p3 nonlinear', 'extended srgb linear', 'extended srgb nonlinear', 'dci p3 linear', 'dci p3 nonlinear', 'bt709 linear', 'bt709 nonlinear', 'bt2020 linear', 'hdr10 st2084', 'dolbyvision', 'hdr10 hlg', 'adobergb linear', 'adobergb nonlinear', 'pass through'.
Rfr: VkColorSpaceKHR.

commandbufferlevel: vk.COMMAND_BUFFER_LEVEL_XXX
Values: 'primary', 'secondary'.
Rfr: VkCommandBufferLevel.

compareop: vk.COMPARE_OP_XXX
Values: 'never' (default), 'less', 'equal', 'less or equal', 'greater', 'not equal', 'greater or equal', 'always'.
Rfr: VkCompareOp.

componentswizzle: vk.COMPONENT_SWIZZLE_XXX
Values: 'identity' (default), 'zero', 'one', 'r', 'g', 'b', 'a'.
Rfr: VkComponentSwizzle.

conservativerasterizationmode: vk.CONSERVATIVE_RASTERIZATION_MODE_XXX
Values: 'disabled', 'overestimate', 'underestimate'.
Rfr: VkConservativeRasterizationModeEXT.

copyaccelerationstructuremode: vk.COPY_ACCELERATION_STRUCTURE_MODE_XXX
Values: 'clone', 'compact', 'serialize', 'deserialize'.
Rfr: VkCopyAccelerationStructureModeKHR.

debugreportobjecttype: vk.DEBUG_REPORT_OBJECT_TYPE_XXX
Values: 'unknown', 'instance', 'physical device', 'device', 'queue', 'semaphore', 'command buffer', 'fence', 'device memory', 'buffer', 'image', 'event', 'query pool', 'buffer view', 'image view', 'shader module', 'pipeline cache', 'pipeline layout', 'render pass', 'pipeline', 'descriptor set layout', 'sampler', 'descriptor pool', 'descriptor set', 'framebuffer', 'command pool', 'surface', 'swapchain', 'debug report', 'display', 'display mode', 'validation cache', 'sampler ycbcr conversion', 'descriptor update template', 'acceleration structure'.
Rfr: VkDebugReportObjectTypeEXT.

descriptortype: vk.DESCRIPTOR_TYPE_XXX
Values: 'sampler', 'combined image sampler', 'sampled image', 'storage image', 'uniform texel buffer', 'storage texel buffer', 'uniform buffer', 'storage buffer', 'uniform buffer dynamic', 'storage buffer dynamic', 'input attachment', 'inline uniform block', 'acceleration structure'.
Rfr: VkDescriptorType.

descriptorupdatetemplatetype: vk.DESCRIPTOR_UPDATE_TEMPLATE_TYPE_XXX
Values: 'descriptor set', 'push descriptors'.
Rfr: VkDescriptorUpdateTemplateType.

deviceeventtype: vk.DEVICE_EVENT_TYPE_XXX
Values: 'display hotplug'.
Rfr: VkDeviceEventTypeEXT.

devicememoryreporteventtype: vk.DEVICE_MEMORY_REPORT_EVENT_TYPE_XXX
Values: 'allocate', 'free', 'import', 'unimport', 'allocation failed'.
Rfr: VkDeviceMemoryReportEventTypeEXT.

discardrectanglemode: vk.DISCARD_RECTANGLE_MODE_XXX
Values: 'inclusive', 'exclusive'.
Rfr: VkDiscardRectangleModeEXT.

displayeventtype: vk.DISPLAY_EVENT_TYPE_XXX
Values: 'first pixel out'.
Rfr: VkDisplayEventTypeEXT.

displaypowerstate: vk.DISPLAY_POWER_STATE_XXX
Values: 'off', 'suspend', 'on'.
Rfr: VkDisplayPowerStateEXT.

driverid: vk.DRIVER_ID_XXX
Values: 'amd proprietary', 'amd open source', 'mesa radv', 'nvidia proprietary', 'intel proprietary windows', 'intel open source mesa', 'imagination proprietary', 'qualcomm proprietary', 'arm proprietary', 'google swiftshader', 'ggp proprietary', 'broadcom proprietary', 'mesa llvmpipe', 'moltenvk', 'coreavi proprietary', 'juice proprietary', 'verisilicon proprietary', 'mesa turnip', 'mesa v3dv', 'mesa panvk'.
Rfr: VkDriverId.

dynamicstate: vk.DYNAMIC_STATE_XXX
Values: 'viewport', 'scissor', 'line width', 'depth bias', 'blend constants', 'depth bounds', 'stencil compare mask', 'stencil write mask', 'stencil reference', 'discard rectangle', 'sample locations', 'ray tracing pipeline stack size', 'fragment shading rate', 'line stipple', 'cull mode', 'front face', 'primitive topology', 'viewport with count', 'scissor with count', 'vertex input binding stride', 'depth test enable', 'depth write enable', 'depth compare op', 'depth bounds test enable', 'stencil test enable', 'stencil op', 'vertex input', 'patch control points', 'rasterizer discard enable', 'depth bias enable', 'logic op', 'primitive restart enable', 'color write enable'.
Rfr: VkDynamicState.

filter: vk.FILTER_XXX
Values: 'nearest' (default), 'linear', 'cubic'.
Rfr: VkFilter.

format: vk.FORMAT_XXX
Values: 'undefined' (default), 'r4g4 unorm pack8', 'r4g4b4a4 unorm pack16', etc.
Rfr: VkFormat.

fragmentshadingratecombinerop: vk.FRAGMENT_SHADING_RATE_COMBINER_OP_XXX
Values: 'keep', 'replace', 'min', 'max', 'mul'.
Rfr: VkFragmentShadingRateCombinerOpKHR.

frontface: vk.FRONT_FACE_XXX
Values: 'counter clockwise' (default), 'clockwise'.
Rfr: VkFrontFace.

fullscreenexclusive: vk.FULL_SCREEN_EXCLUSIVE_XXX
Values: 'default', 'allowed', 'disallowed', 'application controlled'.
Rfr: VkFullScreenExclusiveEXT.

geometrytype: vk.GEOMETRY_TYPE_XXX
Values: 'triangles', 'aabbs', 'instances'.
Rfr: VkGeometryTypeKHR.

imagelayout: vk.IMAGE_LAYOUT_XXX
Values: 'undefined' (default), 'general', 'color attachment optimal', 'depth stencil attachment optimal', 'depth stencil read only optimal', 'shader read only optimal', 'transfer src optimal', 'transfer dst optimal', 'preinitialized', 'present src', 'shared present', 'depth read only stencil attachment optimal', 'depth attachment stencil read only optimal', 'fragment density map optimal', 'depth attachment optimal', 'depth read only optimal', 'stencil attachment optimal', 'stencil read only optimal', 'fragment shading rate attachment optimal', 'read only optimal', 'attachment optimal'.
Rfr: VkImageLayout.

imagetiling: vk.IMAGE_TILING_XXX
Values: 'optimal' (default), 'linear', 'drm format modifier'.
Rfr: VkImageTiling.

imagetype: vk.IMAGE_TYPE_XXX
Values: '1d', '2d', '3d'.
Rfr: VkImageType.

imageviewtype: vk.IMAGE_VIEW_TYPE_XXX
Values: '1d', '2d', '3d', 'cube', '1d array', '2d array', 'cube array'.
Rfr: VkImageViewType.

indextype: vk.INDEX_TYPE_XXX
Values: 'uint16', 'uint32', 'none', 'uint8'.
Rfr: VkIndexType.

linerasterizationmode: vk.LINE_RASTERIZATION_MODE_XXX
Values: 'default', 'rectangular', 'bresenham', 'rectangular smooth'.
Rfr: VkLineRasterizationModeEXT.

logicop: vk.LOGIC_OP_XXX
Values: 'clear' (default), 'and', 'and reverse', 'copy', 'and inverted', 'no op', 'xor', 'or', 'nor', 'equivalent', 'invert', 'or reverse', 'copy inverted', 'or inverted', 'nand', 'set'.
Rfr: VkLogicOp.

objecttype: vk.OBJECT_TYPE_XXX
Values: 'unknown', 'instance', 'physical device', 'device', 'queue', 'semaphore', 'command buffer', 'fence', 'device memory', 'buffer', 'image', 'event', 'query pool', 'buffer view', 'image view', 'shader module', 'pipeline cache', 'pipeline layout', 'render pass', 'pipeline', 'descriptor set layout', 'sampler', 'descriptor pool', 'descriptor set', 'framebuffer', 'command pool', 'surface', 'swapchain', 'display', 'display mode', 'debug report callback', 'descriptor update template', 'sampler ycbcr conversion', 'validation cache', 'debug utils messenger', 'acceleration structure', 'deferred operation', 'private data slot'.
Rfr: VkObjectType.

performancecounterscope: vk.PERFORMANCE_COUNTER_SCOPE_XXX
Values: 'command buffer', 'render pass', 'command'.
Rfr: VkPerformanceCounterScopeKHR.

performancecounterstorage: vk.PERFORMANCE_COUNTER_STORAGE_XXX
Values: 'int32', 'int64', 'uint32', 'uint64', 'float32', 'float64'.
Rfr: VkPerformanceCounterStorageKHR.

performancecounterunit: vk.PERFORMANCE_COUNTER_UNIT_XXX
Values: 'generic', 'percentage', 'nanoseconds', 'bytes', 'bytes per second', 'kelvin', 'watts', 'volts', 'amps', 'hertz', 'cycles'.
Rfr: VkPerformanceCounterUnitKHR.

physicaldevicetype: vk.PHYSICAL_DEVICE_TYPE_XXX
Values: 'other', 'integrated gpu', 'discrete gpu', 'virtual gpu', 'cpu'.
Rfr: VkPhysicalDeviceType.

pipelinebindpoint: vk.PIPELINE_BIND_POINT_XXX
Values: 'graphics' (default), 'compute', 'ray tracing'.
Rfr: VkPipelineBindPoint.

pipelineexecutablestatisticformat: vk.PIPELINE_EXECUTABLE_STATISTIC_FORMAT_XXX
Values: 'bool32', 'int64', 'uint64', 'float64'.
Rfr: VkPipelineExecutableStatisticFormatKHR.

pointclippingbehavior: vk.POINT_CLIPPING_BEHAVIOR_XXX
Values: 'all clip planes', 'user clip planes only'.
Rfr: VkPointClippingBehavior.

polygonmode: vk.POLYGON_MODE_XXX
Values: 'fill' (default), 'line', 'point'.
Rfr: VkPolygonMode.

presentmode: vk.PRESENT_MODE_XXX
Values: 'immediate', 'mailbox', 'fifo' (default), 'fifo relaxed', 'shared demand refresh', 'shared continuous refresh'.
Rfr: VkPresentModeKHR.

primitivetopology: vk.PRIMITIVE_TOPOLOGY_XXX
Values: 'point list' (default), 'line list', 'line strip', 'triangle list', 'triangle strip', 'triangle fan', 'line list with adjacency', 'line strip with adjacency', 'triangle list with adjacency', 'triangle strip with adjacency', 'patch list'.
Rfr: VkPrimitiveTopology.

provokingvertexmode: vk.PROVOKING_VERTEX_MODE_XXX
Values: 'first vertex', 'last vertex'.
Rfr: VkProvokingVertexModeEXT.

querytype: vk.QUERY_TYPE_XXX
Values: 'occlusion', 'pipeline statistics', 'timestamp', 'transform feedback stream', 'performance query', 'acceleration structure compacted size', 'acceleration structure serialization size'.
Rfr: VkQueryType.

queueglobalpriority: vk.QUEUE_GLOBAL_PRIORITY_XXX
Values: 'low', 'medium', 'high', 'realtime'.
Rfr: VkQueueGlobalPriorityEXT.

raytracingshadergrouptype: vk.RAY_TRACING_SHADER_GROUP_TYPE_XXX
Values: 'general', 'triangles hit group', 'procedural hit group'.
Rfr: VkRayTracingShaderGroupTypeKHR.

sampleraddressmode: vk.SAMPLER_ADDRESS_MODE_XXX
Values: 'repeat' (default), 'mirrored repeat', 'clamp to edge', 'clamp to border', 'mirror clamp to edge'.
Rfr: VkSamplerAddressMode.

samplermipmapmode: vk.SAMPLER_MIPMAP_MODE_XXX
Values: 'nearest' (default), 'linear'.
Rfr: VkSamplerMipmapMode.

samplerreductionmode: vk.SAMPLER_REDUCTION_MODE_XXX
Values: 'weighted average' (default), 'min', 'max'.
Rfr: VkSamplerReductionMode.

samplerycbcrmodelconversion: vk.SAMPLER_YCBCR_MODEL_CONVERSION_XXX
Values: 'rgb identity' (default), 'ycbcr identity', 'ycbcr 709', 'ycbcr 601', 'ycbcr 2020'.
Rfr: VkSamplerYcbcrModelConversion.

samplerycbcrrange: vk.SAMPLER_YCBCR_RANGE_XXX
Values: 'itu full' (default), 'itu narrow'.
Rfr: VkSamplerYcbcrRange.

semaphoretype: vk.SEMAPHORE_TYPE_XXX
Values: 'binary', 'timeline'.
Rfr: VkSemaphoreType.

shaderfloatcontrolsindependence: vk.SHADER_FLOAT_CONTROLS_INDEPENDENCE_XXX
Values: '32 bit only', 'all', 'none'.
Rfr: VkShaderFloatControlsIndependence.

shadergroupshader: vk.SHADER_GROUP_SHADER_XXX
Values: 'general', 'closest hit', 'any hit', 'intersection'.
Rfr: VkShaderGroupShaderKHR.

sharingmode: vk.SHARING_MODE_XXX
Values: 'exclusive' (default), 'concurrent'.
Rfr: VkSharingMode.

stencilop: vk.STENCIL_OP_XXX
Values: 'keep' (default), 'zero', 'replace', 'increment and clamp', 'decrement and clamp', 'invert', 'increment and wrap', 'decrement and wrap'.
Rfr: VkStencilOp.

subpasscontents: vk.SUBPASS_CONTENTS_XXX
Values: 'inline', 'secondary command buffers'.
Rfr: VkSubpassContents.

tessellationdomainorigin: vk.TESSELLATION_DOMAIN_ORIGIN_XXX
Values: 'upper left', 'lower left'.
Rfr: VkTessellationDomainOrigin.

timedomain: vk.TIME_DOMAIN_XXX
Values: 'device', 'clock monotonic', 'clock monotonic raw', 'query performance counter'.
Rfr: VkTimeDomainEXT.

validationcacheheaderversion: vk.VALIDATION_CACHE_HEADER_VERSION_XXX
Values: 'one'.
Rfr: VkValidationCacheHeaderVersionEXT.

validationcheck: vk.VALIDATION_CHECK_XXX
Values: 'all', shaders'.
Rfr: VkValidationCheckEXT.

validationfeaturedisable: vk.VALIDATION_FEATURE_DISABLE_XXX
Values: 'all' ,'shaders' ,'thread safety' ,'api parameters' ,'object lifetimes' ,'core checks' ,'unique handles', 'shader validation cache'.
Rfr: VkValidationFeatureDisableEXT.

validationfeatureenable: vk.VALIDATION_FEATURE_ENABLE_XXX
Values: 'gpu assisted', 'gpu assisted reserve binding slot', 'best practices', 'debug printf', 'synchronization validation'.
Rfr: VkValidationFeatureEnableEXT.

vendorid: vk.VENDOR_ID_XXX
Values: 'viv', 'vsi', 'kazan', 'codeplay', 'mesa', 'pocl'.
Rfr: VkVendorId.

vertexinputrate: vk.VERTEX_INPUT_RATE_XXX
Values: 'vertex' (default), 'instance'.
Rfr: VkVertexInputRate.

Flags

Flags in MoonVulkan functions and structs are always represented as plain integers, and encoded in the same way as the corresponding flags in the C Vulkan API.

The vk table contains the VK_XXX_BIT values, renamed as vk.XXX_BIT (e.g. vk.STENCIL_FACE_FRONT_BIT, vk.STENCIL_FACE_BACK_BIT, etc.), without any extension suffix such as _KHR or _EXT.

For each flags type (see the list below), a utility function is also available to map an integer code to a list of string literals, each corresponding to an individual bit set in the code, and viceversa to encode an integer value from the individual bits given as a list of string literals. The generic definition of such functions is the following, where xxxflags stands for stencilfaceflags, commandbufferresetflags, etc:

  • code = xxxflags(s1, s2, …​)
    s1, s2, …​ = xxxflags(code)
    Maps the integer code to/from the list of string values s1, s2, …​.

See also the example contained in the code snippets section.

accessflags: vk.ACCESS_XXX_BIT
Values: 'none', 'indirect command read', 'index read', 'vertex attribute read', 'uniform read', 'input attachment read', 'shader read', 'shader write', 'color attachment read', 'color attachment write', 'depth stencil attachment read', 'depth stencil attachment write', 'transfer read', 'transfer write', 'host read', 'host write', 'memory read', 'memory write', 'color attachment read noncoherent', 'conditional rendering read', 'transform feedback write, 'transform feedback counter read, 'transform feedback counter write', 'fragment density map read', 'acceleration structure read', 'acceleration structure write', 'fragment shading rate attachment read', 'shader sampled read', 'shader storage read', 'shader storage write'.
Rfr. VkAccessFlagBits.

accelerationstructurecreateflags: vk.ACCELERATION_STRUCTURE_CREATE_XXX_BIT
Values: 'device address capture replay'.
Rfr: VkAccelerationStructureCreateFlagBitsKHR.

attachmentdescriptionflags: vk.ATTACHMENT_DESCRIPTION_XXX_BIT
Values: 'may alias'.
Rfr. VkAttachmentDescriptionFlagBits.

buffercreateflags: vk.BUFFER_CREATE_XXX_BIT
Values: 'sparse binding', 'sparse residency', 'sparse aliased', 'protected', 'device address capture replay'.
Rfr. VkBufferCreateFlagBits.

bufferusageflags: vk.BUFFER_USAGE_XXX_BIT
Values: 'transfer src', 'transfer dst', 'uniform texel buffer', 'storage texel buffer', 'uniform buffer', 'storage buffer', 'index buffer', 'vertex buffer', 'indirect buffer', 'conditional rendering', 'transform feedback buffer', 'transform feedback counter buffer', 'shader device address', 'acceleration structure build input read only', 'acceleration structure storage', 'shader binding table'.
Rfr. VkBufferUsageFlagBits.

buildaccelerationstructureflags: vk.BUILD_ACCELERATION_STRUCTURE_XXX_BIT
Values: 'allow update', 'allow compaction', 'prefer fast trace', 'prefer fast build', 'low memory'.
Rfr: VkBuildAccelerationStructureFlagBitsKHR.

colorcomponentflags: vk.COLOR_COMPONENT_XXX_BIT
Values: 'r', 'g', 'b', 'a'.
Rfr. VkColorComponentFlagBits.

commandbufferresetflags: vk.COMMAND_BUFFER_RESET_XXX_BIT
Values: 'release resources'.
Rfr. VkCommandBufferResetFlagBits.

commandbufferusageflags: vk.COMMAND_BUFFER_USAGE_XXX_BIT
Values: 'one time submit', 'render pass continue', 'simultaneous use'.
Rfr. VkCommandBufferUsageFlagBits.

commandpoolcreateflags: vk.COMMAND_POOL_CREATE_XXX_BIT
Values: 'transient', 'reset command buffer', 'protected'.
Rfr. VkCommandPoolCreateFlagBits.

commandpoolresetflags: vk.COMMAND_POOL_RESET_XXX_BIT
Values: 'release resources'.
Rfr. VkCommandPoolResetFlagBits.

compositealphaflags: vk.COMPOSITE_ALPHA_XXX_BIT
Values: 'opaque', 'pre multiplied', 'post multiplied', 'inherit'.
Rfr: VkCompositeAlphaFlagBitsKHR.

conditionalrenderingflags: vk.CONDITIONAL_RENDERING_XXX_BIT
Values: 'inverted'.
Rfr: VkConditionalRenderingFlagBitsEXT.

cullmodeflags: vk.CULL_MODE_XXX
Values: 'none' (=0), 'front', 'back', 'front and back'.
Rfr. VkCullModeFlagBits.

debugreportflags: vk.DEBUG_REPORT_XXX_BIT
Values: 'information', 'warning', 'performance warning', 'report', 'debug'.
Rfr: VkDebugReportFlagBitsEXT.

debugutilsmessageseverityflags: vk.DEBUG_UTILS_MESSAGE_SEVERITY_XXX_BIT
Values: 'verbose', 'info', 'warning', 'error'.
Rfr: VkDebugUtilsMessageSeverityFlagBitsEXT.

debugutilsmessagetypeflags: vk.DEBUG_UTILS_MESSAGE_TYPE_XXX_BIT
Values: 'general', 'validation', 'performance'.
Rfr: VkDebugUtilsMessageTypeFlagBitsEXT.

dependencyflags: vk.DEPENDENCY_XXX_BIT
Values: 'by region', 'device group', 'view local'.
Rfr. VkDependencyFlagBits.

descriptorbindingflags: vk.DESCRIPTOR_BINDING_XXX_BIT
Values: 'update after bind', 'update unused while pending', 'partially bound', 'variable descriptor count'.
Rfr: VkDescriptorBindingFlagBits.

descriptorpoolcreateflags: vk.DESCRIPTOR_POOL_CREATE_XXX_BIT
Values: 'free descriptor set', 'update after bind'.
Rfr. VkDescriptorPoolCreateFlagBits.

descriptorsetlayoutcreateflags: vk.DESCRIPTOR_SET_LAYOUT_CREATE_XXX_BIT
Values: 'push descriptor', 'update after bind pool'.
Rfr. VkDescriptorSetLayoutCreateFlagBits.

devicegrouppresentmodeflags: vk.DEVICE_GROUP_PRESENT_MODE_XXX_BIT
Values: 'local', 'remote', 'sum', 'local multi device'.
Rfr: VkDeviceGroupPresentModeFlagBitsKHR.

devicequeuecreateflags: vk.DEVICE_QUEUE_CREATE_XXX_BIT
Values: 'protected'.
Rfr: VkDeviceQueueCreateFlagBits.

displayplanealphaflags: vk.DISPLAY_PLANE_ALPHA_XXX_BIT
Values: 'opaque', 'global', 'per pixel', 'per pixel premultiplied'.
Rfr: VkDisplayPlaneAlphaFlagBitsKHR.

eventcreateflags: vk.EVENT_CREATE_XXX_BIT
Values: 'device only'.
Rfr: VkEventCreateFlagBits.

externalfencefeatureflags: vk.EXTERNAL_FENCE_FEATURE_XXX_BIT
Values: 'exportable', 'importable'.
Rfr: VkExternalFenceFeatureFlagBits.

externalfencehandletypeflags: vk.EXTERNAL_FENCE_HANDLE_TYPE_XXX_BIT
Values: 'opaque fd', 'opaque win32', 'opaque win32 kmt', 'sync fd'.
Rfr: VkExternalFenceHandleTypeFlagBits.

externalmemoryfeatureflags: vk.EXTERNAL_MEMORY_FEATURE_XXX_BIT
Values: 'dedicated only', 'exportable', 'importable'.
Rfr: VkExternalMemoryFeatureFlagBits.

externalmemoryhandletypeflags: vk.EXTERNAL_MEMORY_HANDLE_TYPE_XXX_BIT
Values: 'opaque fd', 'opaque win32', 'opaque win32 kmt', 'd3d11 texture', 'd3d11 texture kmt', 'd3d12 heap', 'd3d12 resource'.
Rfr: VkExternalMemoryHandleTypeFlagBits.

externalsemaphorefeatureflags: vk.EXTERNAL_SEMAPHORE_FEATURE_XXX_BIT
Values: 'exportable', 'importable'.
Rfr: VkExternalSemaphoreFeatureFlagBits.

externalsemaphorehandletypeflags: vk.EXTERNAL_SEMAPHORE_HANDLE_TYPE_XXX_BIT
Values: 'opaque fd', 'opaque win32', 'opaque win32 kmt', 'd3d12 fence', 'sync fd'.
Rfr: VkExternalSemaphoreHandleTypeFlagBits.

fencecreateflags: vk.FENCE_CREATE_XXX_BIT
Values: 'signaled'.
Rfr. VkFenceCreateFlagBits.

fenceimportflags: vk.FENCE_IMPORT_XXX_BIT
Values: 'temporary'.
Rfr: VkFenceImportFlagBits.

formatfeatureflags: vk.FORMAT_FEATURE_XXX_BIT
Values: 'sampled image', 'storage image', 'storage image atomic', 'uniform texel buffer', 'storage texel buffer', 'storage texel buffer atomic', 'vertex buffer', 'color attachment', 'color attachment blend', 'depth stencil attachment', 'blit src', 'blit dst', 'transfer src', 'transfer dst', 'sampled image filter linear', 'sampled image filter minmax', 'midpoint chroma samples', 'sampled image ycbcr conversion linear filter', 'sampled image ycbcr conversion separate reconstruction filter', 'sampled image ycbcr conversion chroma reconstruction explicit', 'sampled image ycbcr conversion chroma reconstruction explicit forceable', 'disjoint', 'cosited chroma samples', 'fragment density map', 'sampled image filter cubic', 'acceleration structure vertex buffer', 'fragment shading rate attachment', 'storage read without format', 'storage write without format', 'sampled image depth comparison'.
Rfr. VkFormatFeatureFlagBits2KHR.

framebuffercreateflags: vk.FRAMEBUFFER_CREATE_XXX_BIT
Values: 'imageless'.
Rfr: VkFramebufferCreateFlagBits.

geometryflags: vk.GEOMETRY_XXX_BIT
Values: 'opaque', 'no duplicate any hit invocation'.
Rfr: VkGeometryFlagBitsKHR.

geometryinstanceflags: vk.GEOMETRY_INSTANCE_XXX_BIT
Values: 'triangle facing cull disable', 'triangle flip facing', 'force opaque', 'force no opaque'.
Rfr: VkGeometryInstanceFlagBitsKHR.

imageaspectflags: vk.IMAGE_ASPECT_XXX_BIT
Values: 'color', 'depth', 'stencil', 'metadata', 'plane 0', 'plane 1', 'plane 2', 'memory plane 0', 'memory plane 1', 'memory plane 2', 'memory plane 3'.
Rfr. VkImageAspectFlagBits.

imagecreateflags: vk.IMAGE_CREATE_XXX_BIT
Values: 'sparse binding', 'sparse residency', 'sparse aliased', 'mutable format', 'cube compatible', 'block texel view compatible', 'extended usage', 'sample locations compatible depth', 'disjoint', 'alias','split instance bind regions', '2d array compatible', 'protected', 'subsampled'.
Rfr. VkImageCreateFlagBits.

imageusageflags: vk.IMAGE_USAGE_XXX_BIT
Values: 'transfer src', 'transfer dst', 'sampled', 'storage', 'color attachment', 'depth stencil attachment', 'transient attachment', 'input attachment', 'fragment density map'.
Rfr. VkImageUsageFlagBits.

imageviewcreateflags: vk.IMAGE_VIEW_CREATE_XXX_BIT
Values: 'fragment density map dynamic', 'fragment density map deferred'.
Rfr: VkImageViewCreateFlagBits.

memoryallocateflags: vk.MEMORY_ALLOCATE_XXX_BIT
Values: 'device mask', 'device address', 'device address capture replay'.
Rfr: VkMemoryAllocateFlagBits.

memoryheapflags: vk.MEMORY_HEAP_XXX_BIT
Values: 'device local', 'multi instance'.
Rfr. VkMemoryHeapFlagBits.

memorypropertyflags: vk.MEMORY_PROPERTY_XXX_BIT
Values: 'device local', 'host visible', 'host coherent', 'host cached', 'lazily allocated', 'protected'.
Rfr. VkMemoryPropertyFlagBits.

peermemoryfeatureflags: vk.PEER_MEMORY_FEATURE_XXX_BIT
Values: 'copy src', 'copy dst', 'generic src', 'generic dst'.
Rfr: VkPeerMemoryFeatureFlagBits.

performancecounterdescriptionflags: vk.PERFORMANCE_COUNTER_DESCRIPTION_XXX_BIT
Values: 'performance impacting', 'concurrently impacted'.
Rfr: VkPerformanceCounterDescriptionFlagBitsKHR.

pipelinecachecreateflags: vk.PIPELINE_CACHE_CREATE_XXX_BIT
Values: 'externally synchronized'.
Rfr: VkPipelineCacheCreateFlagBits.

pipelinecreateflags: vk.PIPELINE_CREATE_XXX_BIT
Values: 'disable optimization', 'allow derivatives', 'derivative', 'view index from device index', 'dispatch base', 'ray tracing no null any hit shaders', 'ray tracing no null closest hit shaders', 'ray tracing no null miss shaders', 'ray tracing no null intersection shaders', 'ray tracing skip triangles', 'ray tracing skip aabbs', 'ray tracing shader group handle capture replay', 'capture statistics', 'capture internal representations', 'library', 'fail on pipeline compile required', 'early return on failure'.
Rfr. VkPipelineCreateFlagBits.

pipelinecreationfeedbackflags: vk.PIPELINE_CREATION_FEEDBACK_XXX_BIT
Values:'valid', 'application pipeline cache hit', 'base pipeline acceleration'.
Rfr: VkPipelineCreationFeedbackFlagBitsEXT.

pipelineshaderstagecreateflags: vk.PIPELINE_SHADER_STAGE_CREATE_XXX_BIT
Values: 'allow varying subgroup size', 'require full subgroups'.
Rfr: VkPipelineShaderStageCreateFlagBits.

pipelinestageflags: vk.PIPELINE_STAGE_XXX_BIT
Values: 'none', 'top of pipe', 'draw indirect', 'vertex input', 'vertex shader', 'tessellation control shader', 'tessellation evaluation shader', 'geometry shader', 'fragment shader', 'early fragment tests', 'late fragment tests', 'color attachment output', 'compute shader', 'transfer', 'bottom of pipe', 'host', 'all graphics', 'all commands', 'conditional rendering', 'transform feedback', 'fragment density process', 'acceleration structure build', 'ray tracing shader', 'fragment shading rate attachment', 'copy', 'resolve', 'blit', 'clear', 'index input', 'vertex attribute input', 'pre rasterization shaders'.
Rfr. VkPipelineStageFlagBits.

querycontrolflags: vk.QUERY_CONTROL_XXX_BIT
Values: 'precise'.
Rfr. VkQueryControlFlagBits.

querypipelinestatisticflags: vk.QUERY_PIPELINE_STATISTIC_XXX_BIT
Values: 'input assembly vertices', 'input assembly primitives', 'vertex shader invocations', 'geometry shader invocations', 'geometry shader primitives', 'clipping invocations', 'clipping primitives', 'fragment shader invocations', 'tessellation control shader patches', 'tessellation evaluation shader invocations', 'compute shader invocations'.
Rfr. VkQueryPipelineStatisticFlagBits.

queryresultflags: vk.QUERY_RESULT_XXX_BIT
Values: '64', 'wait', 'with availability', 'partial'.
Rfr. VkQueryResultFlagBits.

queueflags: vk.QUEUE_XXX_BIT
Values: 'graphics', 'compute', 'transfer', 'sparse binding', 'protected'.
Rfr. VkQueueFlagBits.

renderingflags: vk.RENDERING_XXX_BIT
Values: 'contents secondary command buffers', 'suspending', 'resuming'.
Rfr: VkRenderingFlagBitsKHR.

resolvemodeflags: vk.RESOLVE_MODE_XXX_BIT
Values: 'none', 'sample zero', 'average', 'min', 'max'.
Rfr: VkResolveModeFlagBits.

samplecountflags: vk.SAMPLE_COUNT_XXX_BIT
Values: '1', '2', '4', '8', '16', '32', '64'.
Rfr. VkSampleCountFlagBits.

samplercreateflags: vk.SAMPLER_CREATE_XXX_BIT
Values: 'subsampled', 'subsampled coarse reconstruction'.
Rfr: VkSamplerCreateFlagBits.

semaphoreimportflags: vk.SEMAPHORE_IMPORT_XXX_BIT
Values: 'temporary'.
Rfr: VkSemaphoreImportFlagBits.

semaphorewaitflags: vk.SEMAPHORE_WAIT_XXX_BIT
Values: 'any'.
Rfr: VkSemaphoreWaitFlagBits.

shaderstageflags: vk.SHADER_STAGE_XXX_BIT
Values: 'vertex', 'tessellation control', 'tessellation evaluation', 'geometry', 'fragment', 'compute', 'all graphics', 'all', 'raygen', 'any hit', 'closest hit', 'miss', 'intersection', 'callable'.
Rfr. VkShaderStageFlagBits.

sparseimageformatflags: vk.SPARSE_IMAGE_FORMAT_XXX_BIT
Values: 'single miptail', 'aligned mip size', 'nonstandard block size'.
Rfr. VkSparseImageFormatFlagBits.

sparsememorybindflags: vk.SPARSE_MEMORY_BIND_XXX_BIT
Values: 'metadata'.
Rfr. VkSparseMemoryBindFlagBits.

stencilfaceflags: vk.STENCIL_FACE_XXX_BIT
Values: 'front', 'back', 'front and back'.
Rfr. VkStencilFaceFlagBits.

subgroupfeatureflags: vk.SUBGROUP_FEATURE_XXX_BIT
Values: 'basic', 'vote', 'arithmetic', 'ballot', 'shuffle', 'shuffle relative', 'clustered', 'quad'.
Rfr: VkSubgroupFeatureFlagBits.

submitflags: vk.SUBMIT_XXX_BIT
Values: 'protected'.
Rfr: VkSubmitFlagBitsKHR.

surfacecounterflags: vk.SURFACE_COUNTER_XXX_BIT
Values: 'vblank'.
Rfr: VkSurfaceCounterFlagBitsEXT.

surfacetransformflags: vk.SURFACE_TRANSFORM_XXX_BIT
Values: 'identity', 'rotate 90', 'rotate 180', 'rotate 270', 'horizontal mirror', 'horizontal mirror rotate 90', 'horizontal mirror rotate 180', 'horizontal mirror rotate 270', 'inherit'.
Rfr: VkSurfaceTransformFlagBitsKHR.

swapchaincreateflags: vk.SWAPCHAIN_CREATE_XXX_BIT
Values: 'split instance bind regions', 'protected', 'mutable format'.
Rfr: VkSwapchainCreateFlagBitsKHR.

toolpurposeflags: vk.TOOL_PURPOSE_XXX_BIT
Values: 'validation', 'profiling', 'tracing', 'additional features', 'modifying features', 'debug reporting', 'debug markers'.
Rfr: VkToolPurposeFlagBitsEXT.

Reserved for future use (must be set to 0):

acquireprofilinglockflags: 0

bufferviewcreateflags: 0

commandpooltrimflags: 0

debugutilsmessengercallbackdataflags: 0

debugutilsmessengercreateflags: 0

descriptorpoolresetflags: 0

descriptorupdatetemplatecreateflags: 0

devicecreateflags: 0

displaymodecreateflags: 0

displaysurfacecreateflags: 0

headlesssurfacecreateflags: 0

instancecreateflags: 0

memorymapflags: 0

pipelinecolorblendstatecreateflags: 0

pipelinerasterizationconservativestatecreateflags: 0

pipelinerasterizationstatestreamcreateflags: 0

pipelinerasterizationdepthclipstatecreateflags: 0

pipelinedepthstencilstatecreateflags: 0

pipelinediscardrectanglestatecreateflags: 0

pipelinedynamicstatecreateflags: 0

pipelineinputassemblystatecreateflags: 0

pipelinelayoutcreateflags: 0

pipelinemultisamplestatecreateflags: 0

pipelinerasterizationstatecreateflags: 0

pipelinetessellationstatecreateflags: 0

pipelinevertexinputstatecreateflags: 0

pipelineviewportstatecreateflags: 0

privatedataslotcreateflags: 0

querypoolcreateflags: 0

renderpasscreateflags: 0

semaphorecreateflags: 0

shadermodulecreateflags: 0

subpassdescriptionflags: 0

validationcachecreateflags: 0

Miscellanea

Version handling

  • version = make_version(major, minor, patch, [variant=0])
    Constructs version (an integer) from major, minor, patch, and variant numbers (also integers).
    Rfr: Version Numbers.

  • major, minor, patch = version_numbers(version)
    Extracts the major, minor, patch, and variant numbers (integers) from version (also an integer).

  • string = version_string(version)
    Returns the 'x.y.z' string for version (an integer), where x, y, and z are the major, minor and patch numbers, respectively.

The vk table contains also the following version related information:

  • vk._VERSION: MoonVulkan version (a string).

  • vk.API_VERSION_n_m: Vulkan versions supported by MoonVulkan (e.g. vk.API_VERSION_1_0, vk.API_VERSION_2_0, …​).

  • vk.API_VERSIONS: a table listing the supported versions as strings (e.g. { 'API_VERSION_1_0', 'API_VERSION_2_0', …​ }).

  • vk.HEADER_VERSION: Vulkan header version (VK_HEADER_VERSION). Note that this refers to the vulkan.h header that MoonVulkan is built against, which may not be aligned with the Vulkan implementation(s) installed on the system.

Common methods

The following methods are common to MoonVulkan objects.

  • handleRAW = object:raw( )
    Returns the raw Vulkan handle (an integer) for the given object (e.g. instance:raw( ) returns a VkInstance handle cast to integer).

  • typestring = object:type( )
    typestring = vk.type(object)
    Returns a string denoting the type of the given object (e.g. instance:type( ) returns 'instance').
    The vk.type( ) function returns nil if object is not a valid MoonVulkan object.

  • instance = object:instance( )
    Returns the instance the given object belongs to.

  • device = object:device( )
    Returns the device the given object belongs to.

  • parent = object:parent( )
    Returns the parent object of the given object.

Constructors

MoonVulkan structs are plain Lua tables, and thus an instance of a struct is usually created manually by simply creating a new table with the specified fields.

Alternatively, for a few struct types, a table constructor is provided and can be used to save typing and reduce code verbosity. The constructor for a struct type, if available, is a function of the vk table, having the same name of the struct type, and returning a table initialized with the passed values.

Available constructors are listed just below the definitions of their respective types, see for example the extent2d type (notice that, for the sake of brevity, the return value is not indicated).

Note that whenever a table constructor accepts a flags parameter, this can be passed either as integer code, or as a table of admitted literals for that flags type.

The following examples illustrate the use of constructors for the extent2d and imagesubresource struct types:

Examples
 -- Two alternative ways to create an instance of the 'offset2d' type:
 ext1 = { width=300, height=200 }   -- manually
 ext2 = vk.extent2d(300, 200)       -- using the table constructor

 -- Two alternative way of passing an 'imageaspectflags' parameter:
 subres1 = vk.imagesubresource(vk.IMAGE_ASPECT_COLOR_BIT, 0, 0)  -- as an integer
 subres2 = vk.imagesubresource({'color'}, 0, 0) -- as a table of admitted literals

Custom allocators

This section describes how to use custom memory allocators for Vulkan objects in MoonVulkan.

Almost all vk.create/allocate_xxx( ) functions accept the optional parameter allocator, that corresponds to the pAllocator parameter accepted by the underlying vkCreate/AllocateXxx( ) function of the Vulkan C API.

If the allocator parameter is not passed (or if it is nil), then the affected object(s) will be created/allocated with pAllocator=NULL, so that the Vulkan implementation will use its default. Otherwise, allocator must be a Lua lightuserdata encapsulating a valid pointer to the VkAllocationCallbacks to be used as pAllocator parameter.

How custom allocators are obtained/implemented is not a MoonVulkan concern. A working example is however provided in the examples/allocator directory.

Note that MoonVulkan has no means to check that the pointer encapsulated in a lightuserdata is actually what it is meant to be, so this functionality must be handled with care.

Notice also that there is no need (and no way) to pass the allocator at object destruction because MoonVulkan stores for this purpose the value it receives at object creation.

Creating surfaces

Surfaces in MoonVulkan can be created using the bindings to platform-specific API, or they can be created by means other than MoonVulkan itself - for example using MoonGLFW or similar libraries that access the Vulkan API directly to provide surface-creation services - and then passed to MoonVulkan using the created_surface( ) function.

The second method is more platform-agnostic, at least from the point of view of the Lua application, since most of the platform-specific details are handled by MoonGLFW (or by whatever is used in lieu of it).

The two methods are described in the following subsections.

Creating surfaces with the platform-specific API

The procedure to create a surface using the platform-specific API is the following:

  1. Create a MoonVulkan instance, enabling (at least) the extensions required for the specific platform.

  2. Use the platform-native API to create a window (or connection or whatever) and/or to obtain the window system specific handles and parameters.

  3. Pass the relevant handles and parameters to Lua (handles must be passed as lightuserdata).

  4. Create a MoonVulkan surface object using the platform-specific create_xxx_surface( ) function (where xxx may be xcb, xlib, etc.), passing it the handles and parameters obtained in the previous steps.

Note that MoonVulkan itself does not provide Lua bindings to platform native API (e.g. xcb_connect( ) etc.), so steps 2 and 3 involve writing some C/C++ code or relying on other Lua libraries.

Creating surfaces by other means

The procedure to create a surface by other means is summarized in the steps listed below, where MoonGLFW is used as example and prototype of 'other means': [5]

  1. Get from MoonGLFW the list of extensions it needs in order to create a surface.

  2. Create a MoonVulkan instance, enabling (at least) the extensions required by MoonGLFW.

  3. Use MoonGLFW to create (a window and) a surface for the instance. In order to do this, we need the raw VkInstance handle which we can retrieve using the instance:raw( ) method. MoonGLFW will return the raw VkSurfaceKHR handle.

  4. Finally, pass the VkSurfaceKHR handle to MoonVulkan using created_surface( ).

Once passed to created_surface( ), the surface handle is to be considered as owned by MoonVulkan. In particular, the surface MUST NOT be destroyed (vkDestroySurfaceKHR) by means other than those provided by MoonVulkan (that is, by automatic destruction at exit or by explictly calling destroy_surface( )).

A working example can be found in the code snippets section.

Data handling

This section describes additional utilities that can be used to encode data from Lua variables to binary strings and viceversa.

  • val1, …​, valN = flatten(table)
    Flattens out the given table and returns the terminal elements in the order they are found.
    Similar to Lua’s table.unpack( ), but it also unpacks any nested table. Only the array part of the table and of nested tables is considered.

  • {val1, …​, valN} = flatten_table(table)
    Same as flatten( ), but returns the values in a flat table. Unlike flatten( ), this function can be used also with very large tables.

  • size = sizeof(datatype)
    Returns the size in bytes of the given datatype.

  • data = pack(datatype, val1, …​, valN)
    data = pack(datatype, table)
    Packs the numbers val1, …​, valN, encoding them according to the given datatype, and returns the resulting binary string.
    The values may also be passed in a (possibly nested) table. Only the array part of the table (and of nested tables) is considered.

  • {val1, …​, valN} = unpack(datatype, data)
    Unpacks the binary string data, interpreting it as a sequence of values of the given datatype, and returns the extracted values in a flat table.
    The length of data must be a multiple of sizeof(datatype).

datatype: 'byte', 'ubyte', 'int8', 'uint8', 'short', 'ushort', 'int16', 'uint16', 'int', 'uint', 'int32', 'uint32', 'long', 'ulong', 'int64', 'uint64', 'float', 'double'.
(byte, short, int and long are aliases for int8, int16, int32 and int64, respectively).


The following functions can be used to pack (serialize) data when updating descriptor sets with template.

  • data = pack_descriptorbufferinfo(buffer, offset, range)
    offset: integer
    range: integer or 'whole size' (defaults to 'whole size')
    Constructs a VkDescriptorBufferInfo with the given parameters and returns it as a binary string.

  • data = pack_bufferview(buffer_view, application_data)
    Returns a binary string obtained by serializing buffer_view and concatenating it with application_data (a binary string).
    The application_data binary string encodes application specific data and may be constructed using Lua’s string.pack( ).

Tracing utilities

  • trace_objects(boolean)
    Enable/disable tracing of objects creation and destruction (which by default is disabled). If enabled, a printf is generated whenever an object is created/allocated or destructed/freed, indicating the object type and the value of its raw Vulkan handle.

  • t = now( )
    Returns the current time in seconds (a Lua number).
    This is implemented with monotonic clock_gettime(3), if available, or with gettimeofday(3) otherwise.

  • dt = since(t)
    Returns the time in seconds (a Lua number) elapsed since the time t, previously obtained with the now( ) function.

Platforms support

A few MoonVulkan functions are available only on specific platforms, in the same way the underlying Vulkan functions are. In order to use such functions, MoonVulkan must be compiled as described in this section.

To enable support for a specific platform, set the PLATFORM_XXX environment variable before compiling MoonVulkan (XXX here stands for XCB, XLIB, WAYLAND, etc.). For example:

[moonvulkan]$ export PLATFORM_XCB=1      # enable XCB support
[moonvulkan]$ export PLATFORM_XLIB=1     # enable XLIB support
[moonvulkan]$ make && sudo make install  # compile and install MoonVulkan

As a prerequisite, you’ll need to make sure that the platform libraries are installed on the system and that the relevant header files are where vulkan.h expects them to be.

(Functions that need platform-specific support are those that have a PLATFORM_XXX link to this section in their references. For example, the create_xlib_surface( ) function has a PLATFORM_XLIB link, meaning that it requires MoonVulkan to be compiled with the PLATFORM_XLIB environment variable set).

Code snippets

Examples for clearcolorvalue and clearvalue
 clearvalue = { color = { 0.2, 0.5, 0.1, 1.0 } }  -- t defaults to 'float32'
 clearvalue = { color = { 0.2, 0.5, 0.1, 1.0, t='float32' } }
 clearvalue = { color = { 20, 112, 200, 1, t='uint32' } }
 clearvalue = { depth = 1.0, stencil = 0 }
Dealing with enums
 -- Alternative and equivalent ways to assign values of the 'blendop' enum type
 -- (whose hint is vk.BLEND_OP_XXX):
 op1 = vk.BLEND_OP_ADD
 op2 = 'add' -- XXX=ADD
 op3 = vk.BLEND_OP_REVERSE_SUBTRACT
 op4 = 'reverse subtract' -- XXX=REVERSE_SUBTRACT

 print(op1) --> 'add'
 print(op2) --> 'add'
 print(op3) --> 'reverse subtract'
 print(op4) --> 'reverse subtract'
 print(op1 == 'add') --> true
 print(op3 == op4) --> true

 -- List the literals admitted by the 'blendop' enum type:
 ops = vk.enum('blendop')
 print(table.concat(ops, ', ')) --> 'add', 'subtract', 'reverse subtract', 'min', 'max'
Dealing with flags
 -- Two alternative equivalent ways to produce a 'stencilfaceflags' value:
 code1 = vk.STENCIL_FACE_FRONT_BIT | vk.STENCIL_FACE_BACK_BIT
 code2 = vk.stencilfaceflags('front', 'back')

 assert(code1 == code2) -- true
 print(code1) --> 3
 print(vk.stencilfaceflags(code1)) --> front back
 print(vk.stencilfaceflags(code2)) --> ditto

 if (code1 & vk.STENCIL_FACE_FRONT_BIT) ~= 0 then -- NB: 0 is not false in Lua
   print("'front' bit is set")
 else
   print("'front' bit is not set")
 end
Creating a surface with MoonGLFW
 glfw = require("moonglfw")
 vk = require("moonvulkan")

 -- 1) Get the list of extensions required by GLFW to create surfaces:
 extension_names = glfw.get_required_instance_extensions()
 print("Required extensions: " .. table.concat(extension_names, ', '))

 -- 2) Create a Vulkan instance, enabling the required extensions:
 instance = vk.create_instance({ enabled_extension_names = extension_names })

 -- 3.1) Create a window, not tied to any particular API:
 glfw.window_hint('client api', 'no api')
 window = glfw.create_window(640, 480, "My first GLFW/Vulkan window")

 -- 3.2) Create a surface for the window:
 surfaceRAW = glfw.create_window_surface(window, instance:raw())

 -- 4) Finally, pass the surface to MoonVulkan:
 surface = vk.created_surface(instance, surfaceRAW)

 -- Event loop:
 while not glfw.window_should_close(window) do
    glfw.poll_events()
 end
Handling versions
 print("MoonVulkan version:", vk._VERSION)
 print("Header version (vulkan.h):", vk.HEADER_VERSION)
 print("Supported versions:", table.concat(vk.API_VERSIONS, ","))

 for _, s in ipairs(vk.API_VERSIONS) do
     local ver = vk[s]
     local major, minor, patch = vk.version_numbers(ver)
     print(s .. ": " .. ver .. " (" ..  vk.version_string(ver) ..")" ..
         " major="..major.." minor="..minor.." patch="..patch)
 end

 if not vk.API_VERSION_1_0 then print("API_VERSION_1_0 is not supported") end
 if not vk.API_VERSION_2_0 then print("API_VERSION_2_0 is not supported") end

 assert(vk.make_version(1, 0, 0) == vk.API_VERSION_1_0) --> true

1. This manual is written in AsciiDoc, rendered with AsciiDoctor and a CSS from the AsciiDoctor Stylesheet Factory.
2. Objects are anchored to the Lua registry at their creation, so even if the script does not have references to an object, a reference always exists on the registry and this prevents the GC to collect it.
3. It is good practice to not leave invalid references to objects around, because they prevent the GC to collect the memory associated with the userdata.
4. With respect to C structs, Lua tables don’t include those fields whose values can be inferred from the values of other fields (for example counts, sizes and lengths), and in general all those fields that can be dealt with by MoonVulkan in C without passing them to/from Lua, like 'sType' and 'pNext' fields.
5. Note that MoonGLFW is used here only as example, but MoonVulkan is not tied to it in any way. MoonGLFW can be replaced by …​ whatever, as long as 'whatever' provides the needed functionalities and is able to exchange raw Vulkan handles in the form of Lua integers.