I am trying to use WebGPU with C with the implementation from wgpu-native and GLFW to create window. I follow the tutorial from here. The tutorial is a bit old and there’s changes in the API. One of the change which getting in my way was creating the swapchain. The older API explicitly requires you to create the swapchain object, while the recent one the swapchain information is already in the surface object so you only need to configure the surface.
Now what make me stuck is that I could not get my renderpass working. The wgpu-native implementation always panic with error “invalid load op for render pass color attachment: 0”. I have tried things that might works but none of the is working, like I tried the example from the wgpu-native repository but still it’s not working. I am currently thinking that the problem is the native webgpu implementation from wgpu-rs is the problem, but the only alternatives right now is google’s dawn which is very large and I have to build it myself (If only there’s precompiled binaries). I am still hoping that my code is the troublemaker here not the wgpu-rs, so I would provide the source code
// main.c
#include "glfw3ext.h"
#include "webgpu.h"
#include <GLFW/glfw3.h>
#include <stdlib.h>
#include <stdio.h>
#include <webgpu/webgpu.h>
#define GLFW_EXPOSE_NATIVE_X11
#include <GLFW/glfw3native.h>
#include <assert.h>
char *load_file_data(const char *file_path, size_t *size)
{
FILE *f = fopen(file_path, "rb");
if(!f) return NULL;
fseek(f, 0, SEEK_END);
size_t filesz = ftell(f);
fseek(f, 0, SEEK_SET);
char *data = malloc(filesz + 1);
data[filesz] = '';
size_t readsz = fread(data, sizeof(char), filesz, f);
fclose(f);
if(readsz != filesz) {
free(data);
return NULL;
}
if(size) *size = filesz;
return data;
}
void wgpuDeviceDefaultUncapturedErrorCallback(WGPUErrorType type, char const* message, void *userData)
{
fprintf(stderr, "Uncaptured device error %d: %sn", type, message);
}
void wgpuQueueDefaultOnSubmittedWorkDone(WGPUQueueWorkDoneStatus status, void *userData)
{
printf("Queue work done with status: %dn", status);
}
void wgpuDefaultAdapterRequestDeviceCallback(WGPURequestDeviceStatus status, WGPUDevice device, char const * message, WGPU_NULLABLE void * userdata) WGPU_FUNCTION_ATTRIBUTE
{
WGPUDevice *result_device = (WGPUDevice *)userdata;
if(status == WGPURequestDeviceStatus_Success) {
*result_device = device;
}
}
void wgpuDefaultInstanceRequestAdapterCallback(WGPURequestAdapterStatus status, WGPUAdapter adapter, char const * message, WGPU_NULLABLE void * userdata) WGPU_FUNCTION_ATTRIBUTE
{
WGPUAdapter *result_adapter = (WGPUAdapter *)userdata;
if(status == WGPURequestAdapterStatus_Success) {
*result_adapter = adapter;
}
}
typedef struct WGPURenderPipelineSimpleDescriptor{
} WGPURenderPipelineSimpleDescriptor;
WGPURenderPipeline wgpuDeviceCreateSimpleRenderPipeline(WGPUDevice device, const WGPURenderPipelineSimpleDescriptor *desc)
{
return NULL;
}
int main(void)
{
assert(glfwInit() && "Failed to initialize GLFW");
WGPUInstanceDescriptor inst_desc = {0};
inst_desc.nextInChain = NULL;
WGPUInstance instance = wgpuCreateInstance(&inst_desc);
assert(instance && "Failed to create WGPU instance");
WGPURequestAdapterOptions adapter_options = {0};
WGPUAdapter adapter = NULL;
wgpuInstanceRequestAdapter(instance, &adapter_options, wgpuDefaultInstanceRequestAdapterCallback, &adapter);
assert(adapter && "Failed to find adapter");
WGPUDeviceDescriptor device_desc = {0};
device_desc.defaultQueue.nextInChain = NULL;
device_desc.defaultQueue.label = "The default queue";
WGPUDevice device;
WGPUAdapterRequestDeviceCallback callback;
wgpuAdapterRequestDevice(adapter, &device_desc, wgpuDefaultAdapterRequestDeviceCallback, &device);
assert(device && "Failed to find device");
wgpuDeviceSetUncapturedErrorCallback(device, wgpuDeviceDefaultUncapturedErrorCallback, NULL);
glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE);
GLFWwindow *window = glfwCreateWindow(800, 600, "WebGPU Window", NULL, NULL);
assert(window && "Failed to create GLFW window");
WGPUSurface surface = glfwCreateWGPUSurface(instance, window);
WGPUSurfaceCapabilities surface_capabilities = {0};
wgpuSurfaceGetCapabilities(surface, adapter, &surface_capabilities);
WGPUSurfaceConfiguration surface_config;
glfwGetFramebufferSize(window, (int *)&surface_config.width, (int *)&surface_config.height);
surface_config.usage = WGPUTextureUsage_RenderAttachment;
surface_config.presentMode = WGPUPresentMode_Fifo;
surface_config.device = device;
surface_config.format = surface_capabilities.formats[0];
surface_config.alphaMode = surface_capabilities.alphaModes[0];
wgpuSurfaceConfigure(surface, &surface_config);
WGPUQueue queue = wgpuDeviceGetQueue(device);
wgpuQueueOnSubmittedWorkDone(queue, wgpuQueueDefaultOnSubmittedWorkDone, NULL);
char *shader_code = load_file_data("./shader.wgsl", 0);
WGPUShaderModuleWGSLDescriptor wgsl_desc;
wgsl_desc.chain.sType = WGPUSType_ShaderModuleWGSLDescriptor;
wgsl_desc.code = shader_code;
WGPUShaderModuleDescriptor shader_module_desc = {0};
shader_module_desc.label = "Simple Shader Module";
shader_module_desc.nextInChain = (WGPUChainedStruct *)&wgsl_desc;
WGPUShaderModule shader_module = wgpuDeviceCreateShaderModule(device, &shader_module_desc);
free(shader_code);
WGPUVertexState vertex_state = {0};
vertex_state.entryPoint = "vert_main";
vertex_state.module = shader_module;
WGPUColorTargetState color_target_state;
color_target_state.format = surface_capabilities.formats[0];
color_target_state.writeMask = WGPUColorWriteMask_All;
WGPUFragmentState fragment_state = {0};
fragment_state.entryPoint = "frag_main";
fragment_state.targetCount = 1;
fragment_state.targets = &color_target_state;
fragment_state.module = shader_module;
WGPUPrimitiveState primitive_state = {0};
primitive_state.topology = WGPUPrimitiveTopology_TriangleList;
WGPUMultisampleState multisample_state = {0};
multisample_state.mask = 0xFFFFFFFF;
multisample_state.count = 1;
WGPUPipelineLayoutDescriptor pipeline_layout_desc;
pipeline_layout_desc.label = "Simple";
WGPUPipelineLayout pipeline_layout = wgpuDeviceCreatePipelineLayout(device, &pipeline_layout_desc);
WGPURenderPipelineDescriptor pipeline_desc = {0};
pipeline_desc.label = "Simple Pipeline";
pipeline_desc.vertex = vertex_state;
pipeline_desc.fragment = &fragment_state;
pipeline_desc.multisample = multisample_state;
pipeline_desc.primitive = primitive_state;
pipeline_desc.layout = pipeline_layout;
WGPURenderPipeline pipeline = wgpuDeviceCreateRenderPipeline(device, &pipeline_desc);
while(!glfwWindowShouldClose(window)) {
glfwPollEvents();
WGPUSurfaceTexture surface_texture;
wgpuSurfaceGetCurrentTexture(surface, &surface_texture);
switch (surface_texture.status) {
case WGPUSurfaceGetCurrentTextureStatus_Success:
assert(surface_texture.texture);
// All good, could check for `surface_texture.suboptimal` here.
break;
case WGPUSurfaceGetCurrentTextureStatus_Timeout:
case WGPUSurfaceGetCurrentTextureStatus_Outdated:
case WGPUSurfaceGetCurrentTextureStatus_Lost:
{
// Skip this frame, and re-configure surface.
if (surface_texture.texture != NULL) {
wgpuTextureRelease(surface_texture.texture);
}
int width, height;
glfwGetWindowSize(window, &width, &height);
if (width != 0 && height != 0) {
surface_config.width = width;
surface_config.height = height;
wgpuSurfaceConfigure(surface, &surface_config);
}
continue;
};
case WGPUSurfaceGetCurrentTextureStatus_OutOfMemory:
case WGPUSurfaceGetCurrentTextureStatus_DeviceLost:
case WGPUSurfaceGetCurrentTextureStatus_Force32:
// Fatal error
fprintf(stderr, "get_current_texture status=%#.8xn",surface_texture.status);
assert(0 && "Invalid surface texture");
}
WGPUTextureView texture_view = wgpuTextureCreateView(surface_texture.texture, NULL);
assert(texture_view);
WGPUCommandEncoderDescriptor command_encoder_desc = {0};
command_encoder_desc.label = "My Command Encoder";
WGPUCommandEncoder encoder = wgpuDeviceCreateCommandEncoder(device, &command_encoder_desc);
WGPURenderPassColorAttachment render_pass_color_attachment = {0};
render_pass_color_attachment.view = texture_view;
render_pass_color_attachment.loadOp = WGPULoadOp_Clear;
render_pass_color_attachment.storeOp = WGPUStoreOp_Store;
render_pass_color_attachment.clearValue = (WGPUColor){ .r = 0.0f, .g = 0.0f, .b = 0.0f, .a = 1.0f };
WGPURenderPassDescriptor render_pass_desc = {0};
render_pass_desc.label = "Render Pass Encoder";
render_pass_desc.colorAttachmentCount = 1;
render_pass_desc.colorAttachments = &render_pass_color_attachment;
WGPURenderPassEncoder render_pass = wgpuCommandEncoderBeginRenderPass(encoder, &render_pass_desc);
assert(render_pass);
wgpuRenderPassEncoderSetPipeline(render_pass, pipeline);
// Here we draw the things
wgpuRenderPassEncoderEnd(render_pass);
WGPUCommandBufferDescriptor command_buffer_desc = {0};
command_buffer_desc.label = "My Command Buffer";
WGPUCommandBuffer command = wgpuCommandEncoderFinish(encoder, &command_buffer_desc);
wgpuQueueSubmit(queue, 1, &command);
wgpuSurfacePresent(surface);
wgpuRenderPassEncoderRelease(render_pass);
wgpuCommandEncoderRelease(encoder);
wgpuCommandBufferRelease(command);
wgpuTextureViewRelease(texture_view);
wgpuTextureRelease(surface_texture.texture);
}
wgpuRenderPipelineRelease(pipeline);
wgpuQueueRelease(queue);
wgpuDeviceRelease(device);
wgpuSurfaceRelease(surface);
wgpuAdapterRelease(adapter);
wgpuInstanceRelease(instance);
glfwTerminate();
}
// shader.wgsl
@vertex
fn vert_main(@builtin(vertex_index) in_vertex_index: u32) -> @builtin(position) vec4<f32> {
let x = f32(i32(in_vertex_index) - 1);
let y = f32(i32(in_vertex_index & 1u) * 2 - 1);
return vec4<f32>(x, y, 0.0, 1.0);
}
@fragment
fn frag_main() -> @location(0) vec4<f32> {
return vec4<f32>(1.0, 0.0, 0.0, 1.0);
}
I am expecting the GLFW window clear with black color.