-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
539 lines (424 loc) · 17 KB
/
Copy pathmain.cpp
File metadata and controls
539 lines (424 loc) · 17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
#include <GLFW/glfw3.h>
#include <webgpu/webgpu.h>
#ifdef WEBGPU_BACKEND_WGPU
# include <webgpu/wgpu.h>
#endif // WEBGPU_BACKEND_WGPU
#include <glfw3webgpu.h>
#ifdef __EMSCRIPTEN__
# include <emscripten.h>
#endif // __EMSCRIPTEN__
#include <iostream>
#include <cassert>
#include <vector>
const int SCR_WIDTH = 1024;
const int SCR_HEIGHT = 768;
/**
* Utility function to get a WebGPU adapter, so that
* WGPUAdapter adapter = requestAdapterSync(options);
* is roughly equivalent to
* const adapter = await navigator.gpu.requestAdapter(options);
*/
WGPUAdapter requestAdapterSync(WGPUInstance instance, WGPURequestAdapterOptions const * options) {
// A simple structure holding the local information shared with the
// onAdapterRequestEnded callback.
struct UserData {
WGPUAdapter adapter = nullptr;
bool requestEnded = false;
};
UserData userData;
// Callback called by wgpuInstanceRequestAdapter when the request returns
// This is a C++ lambda function, but could be any function defined in the
// global scope. It must be non-capturing (the brackets [] are empty) so
// that it behaves like a regular C function pointer, which is what
// wgpuInstanceRequestAdapter expects (WebGPU being a C API). The workaround
// is to convey what we want to capture through the pUserData pointer,
// provided as the last argument of wgpuInstanceRequestAdapter and received
// by the callback as its last argument.
auto onAdapterRequestEnded = [](WGPURequestAdapterStatus status, WGPUAdapter adapter, char const * message, void * pUserData) {
UserData& userData = *reinterpret_cast<UserData*>(pUserData);
if (status == WGPURequestAdapterStatus_Success) {
userData.adapter = adapter;
} else {
std::cout << "Could not get WebGPU adapter: " << message << std::endl;
}
userData.requestEnded = true;
};
// Call to the WebGPU request adapter procedure
wgpuInstanceRequestAdapter(
instance /* equivalent of navigator.gpu */,
options,
onAdapterRequestEnded,
(void*)&userData
);
// We wait until userData.requestEnded gets true
// [...] Wait for request to end
assert(userData.requestEnded);
return userData.adapter;
}
/**
* Utility function to get a WebGPU device, so that
* WGPUDevice device = requestDeviceSync(adapter, options);
* is roughly equivalent to
* const device = await adapter.requestDevice(descriptor);
* It is very similar to requestAdapter
*/
WGPUDevice requestDeviceSync(WGPUAdapter adapter, WGPUDeviceDescriptor const * descriptor) {
struct UserData {
WGPUDevice device = nullptr;
bool requestEnded = false;
};
UserData userData;
auto onDeviceRequestEnded = [](WGPURequestDeviceStatus status, WGPUDevice device, char const * message, void * pUserData) {
UserData& userData = *reinterpret_cast<UserData*>(pUserData);
if (status == WGPURequestDeviceStatus_Success) {
userData.device = device;
} else {
std::cout << "Could not get WebGPU device: " << message << std::endl;
}
userData.requestEnded = true;
};
wgpuAdapterRequestDevice(
adapter,
descriptor,
onDeviceRequestEnded,
(void*)&userData
);
#ifdef __EMSCRIPTEN__
while (!userData.requestEnded) {
emscripten_sleep(100);
}
#endif // __EMSCRIPTEN__
assert(userData.requestEnded);
return userData.device;
}
// We also add an inspect device function:
void inspectDevice(WGPUDevice device) {
std::vector<WGPUFeatureName> features;
size_t featureCount = wgpuDeviceEnumerateFeatures(device, nullptr);
features.resize(featureCount);
wgpuDeviceEnumerateFeatures(device, features.data());
std::cout << "Device features:" << std::endl;
std::cout << std::hex;
for (auto f : features) {
std::cout << " - 0x" << f << std::endl;
}
std::cout << std::dec;
WGPUSupportedLimits limits = {};
limits.nextInChain = nullptr;
#ifdef WEBGPU_BACKEND_DAWN
bool success = wgpuDeviceGetLimits(device, &limits) == WGPUStatus_Success;
#else
bool success = wgpuDeviceGetLimits(device, &limits);
#endif
if (success) {
std::cout << "Device limits:" << std::endl;
std::cout << " - maxTextureDimension1D: " << limits.limits.maxTextureDimension1D << std::endl;
std::cout << " - maxTextureDimension2D: " << limits.limits.maxTextureDimension2D << std::endl;
std::cout << " - maxTextureDimension3D: " << limits.limits.maxTextureDimension3D << std::endl;
std::cout << " - maxTextureArrayLayers: " << limits.limits.maxTextureArrayLayers << std::endl;
// [...] Extra device limits
}
}
WGPUTextureView getNextSurfaceTextureView(WGPUSurface surface) {
// Get the surface texture
WGPUSurfaceTexture surfaceTexture;
wgpuSurfaceGetCurrentTexture(surface, &surfaceTexture);
if (surfaceTexture.status != WGPUSurfaceGetCurrentTextureStatus_Success) {
return nullptr;
}
// Create a view for this surface texture
WGPUTextureViewDescriptor viewDescriptor;
viewDescriptor.nextInChain = nullptr;
viewDescriptor.label = "Surface texture view";
viewDescriptor.format = wgpuTextureGetFormat(surfaceTexture.texture);
viewDescriptor.dimension = WGPUTextureViewDimension_2D;
viewDescriptor.baseMipLevel = 0;
viewDescriptor.mipLevelCount = 1;
viewDescriptor.baseArrayLayer = 0;
viewDescriptor.arrayLayerCount = 1;
viewDescriptor.aspect = WGPUTextureAspect_All;
WGPUTextureView targetView = wgpuTextureCreateView(surfaceTexture.texture, &viewDescriptor);
#ifndef WEBGPU_BACKEND_WGPU
// We no longer need the texture, only its view
// (NB: with wgpu-native, surface textures must not be manually released)
wgpuTextureRelease(surfaceTexture.texture);
#endif // WEBGPU_BACKEND_WGPU
return targetView;
}
int main() {
std::cout << "hello" << std::endl;
// We create a descriptor
WGPUInstanceDescriptor desc = {};
desc.nextInChain = nullptr;
// We create the instance using this descriptor
WGPUInstance instance = wgpuCreateInstance(&desc);
// We can check whether there is actually an instance created
if (!instance) {
std::cerr << "Could not initialize WebGPU!" << std::endl;
return 1;
}
// Display the object (WGPUInstance is a simple pointer, it may be
// copied around without worrying about its size).
std::cout << "WGPU instance: " << instance << std::endl;
// GLFW !
if (!glfwInit()) {
std::cerr << "Could not initialize GLFW!" << std::endl;
return 1;
}
glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE);
GLFWwindow *window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "webgpu test", nullptr, nullptr);
if (!window) {
std::cerr << "Could not create window!" << std::endl;
glfwTerminate();
return 1;
}
// Surface
// Should keep alive during the app lifetime !
WGPUSurface surface = glfwGetWGPUSurface(instance, window);
std::cout << "Requesting adapter..." << std::endl;
WGPURequestAdapterOptions adapterOpts = {};
adapterOpts.nextInChain = nullptr;
adapterOpts.compatibleSurface = surface;
WGPUAdapter adapter = requestAdapterSync(instance, &adapterOpts);
std::cout << "Got adapter: " << adapter << std::endl;
WGPUSupportedLimits supportedLimits = {};
supportedLimits.nextInChain = nullptr;
bool success = wgpuAdapterGetLimits(adapter, &supportedLimits);
if (success) {
std::cout << "Adapter limits:" << std::endl;
std::cout << " - maxTextureDimension1D: " << supportedLimits.limits.maxTextureDimension1D << std::endl;
std::cout << " - maxTextureDimension2D: " << supportedLimits.limits.maxTextureDimension2D << std::endl;
std::cout << " - maxTextureDimension3D: " << supportedLimits.limits.maxTextureDimension3D << std::endl;
std::cout << " - maxTextureArrayLayers: " << supportedLimits.limits.maxTextureArrayLayers << std::endl;
}
WGPUAdapterProperties properties = {};
properties.nextInChain = nullptr;
wgpuAdapterGetProperties(adapter, &properties);
std::cout << "Adapter properties:" << std::endl;
std::cout << " - vendorID: " << properties.vendorID << std::endl;
if (properties.vendorName) {
std::cout << " - vendorName: " << properties.vendorName << std::endl;
}
if (properties.architecture) {
std::cout << " - architecture: " << properties.architecture << std::endl;
}
std::cout << " - deviceID: " << properties.deviceID << std::endl;
if (properties.name) {
std::cout << " - name: " << properties.name << std::endl;
}
if (properties.driverDescription) {
std::cout << " - driverDescription: " << properties.driverDescription << std::endl;
}
std::cout << std::hex;
std::cout << " - adapterType: 0x" << properties.adapterType << std::endl;
std::cout << " - backendType: 0x" << properties.backendType << std::endl;
std::cout << std::dec; // Restore decimal numbers
std::vector<WGPUFeatureName> features;
// Call the function a first time with a null return address, just to get
// the entry count.
size_t featureCount = wgpuAdapterEnumerateFeatures(adapter, nullptr);
// Allocate memory (could be a new, or a malloc() if this were a C program)
features.resize(featureCount);
// Call the function a second time, with a non-null return address
wgpuAdapterEnumerateFeatures(adapter, features.data());
std::cout << "Adapter features:" << std::endl;
std::cout << std::hex; // Write integers as hexadecimal to ease comparison with webgpu.h literals
for (auto f : features) {
std::cout << " - 0x" << f << std::endl;
}
std::cout << std::dec; // Restore decimal numbers
std::cout << "Requesting device..." << std::endl;
WGPUDeviceDescriptor deviceDesc = {};
// [...] Build device descriptor
WGPUDevice device = requestDeviceSync(adapter, &deviceDesc);
std::cout << "Got device: " << device << std::endl;
deviceDesc.nextInChain = nullptr;
deviceDesc.label = "My Device"; // anything works here, that's your call
deviceDesc.requiredFeatureCount = 0; // we do not require any specific feature
deviceDesc.requiredLimits = nullptr; // we do not require any specific limit
deviceDesc.defaultQueue.nextInChain = nullptr;
deviceDesc.defaultQueue.label = "The default queue";
// [...] Set device lost callback
// A function that is invoked whenever the device stops being available.
deviceDesc.deviceLostCallback = [](WGPUDeviceLostReason reason, char const* message, void* /* pUserData */) {
std::cout << "Device lost: reason " << reason;
if (message) std::cout << " (" << message << ")";
std::cout << std::endl;
};
auto onDeviceError = [](WGPUErrorType type, char const* message, void* /* pUserData */) {
std::cout << "Uncaptured device error: type " << type;
if (message) std::cout << " (" << message << ")";
std::cout << std::endl;
};
wgpuDeviceSetUncapturedErrorCallback(device, onDeviceError, nullptr /* pUserData */);
inspectDevice(device);
// Surface config
WGPUTextureFormat surfaceFormat = wgpuSurfaceGetPreferredFormat(surface, adapter);
WGPUSurfaceConfiguration config = {};
config.nextInChain = nullptr;
config.width = SCR_WIDTH;
config.height = SCR_HEIGHT;
config.format = surfaceFormat;
config.viewFormatCount = 0;
config.viewFormats = nullptr;
config.usage = WGPUTextureUsage_RenderAttachment;
config.device = device;
config.presentMode = WGPUPresentMode_Fifo;
config.alphaMode = WGPUCompositeAlphaMode_Auto;
wgpuSurfaceConfigure(surface, &config);
// Command queue
WGPUQueue queue = wgpuDeviceGetQueue(device);
auto onQueueWorkDone = [](WGPUQueueWorkDoneStatus status, void* /* pUserData */) {
std::cout << "Queued work finished with status: " << status << std::endl;
};
wgpuQueueOnSubmittedWorkDone(queue, onQueueWorkDone, nullptr /* pUserData */);
const char* shaderSource = R"(
@vertex
fn vs_main(@builtin(vertex_index) in_vertex_index: u32) -> @builtin(position) vec4f {
var p = vec2f(0.0, 0.0);
if (in_vertex_index == 0u) {
p = vec2f(-0.5, -0.5);
} else if (in_vertex_index == 1u) {
p = vec2f(0.5, -0.5);
} else {
p = vec2f(0.0, 0.5);
}
return vec4f(p, 0.0, 1.0);
}
@fragment
fn fs_main() -> @location(0) vec4f {
return vec4f(0.0, 0.4, 1.0, 1.0);
}
)";
// Shader module
WGPUShaderModuleWGSLDescriptor shaderCodeDesc{};
shaderCodeDesc.chain.next = nullptr;
shaderCodeDesc.chain.sType = WGPUSType_ShaderModuleWGSLDescriptor;
shaderCodeDesc.code = shaderSource;
WGPUShaderModuleDescriptor shaderDesc{};
shaderDesc.nextInChain = &shaderCodeDesc.chain;
shaderDesc.label = "shader_module";
#ifdef WEBGPU_BACKEND_WGPU
shaderDesc.hintCount = 0;
shaderDesc.hints = nullptr;
#endif
WGPUShaderModule shaderModule = wgpuDeviceCreateShaderModule(device, &shaderDesc);
// Pipeline
WGPURenderPipelineDescriptor pipelineDesc = {};
pipelineDesc.nextInChain = nullptr;
pipelineDesc.label = "standard_pipeline";
pipelineDesc.vertex.bufferCount = 0;
pipelineDesc.vertex.buffers = nullptr;
pipelineDesc.vertex.module = shaderModule;
pipelineDesc.vertex.entryPoint = "vs_main";
pipelineDesc.vertex.constantCount = 0;
pipelineDesc.vertex.constants = nullptr;
pipelineDesc.primitive.topology = WGPUPrimitiveTopology_TriangleList;
pipelineDesc.primitive.stripIndexFormat = WGPUIndexFormat_Undefined;
pipelineDesc.primitive.frontFace = WGPUFrontFace_CCW;
pipelineDesc.primitive.cullMode = WGPUCullMode_None; // Replace to front
WGPUFragmentState fragmentState{};
fragmentState.nextInChain = nullptr;
fragmentState.module = shaderModule;
fragmentState.entryPoint = "fs_main";
fragmentState.constantCount = 0;
fragmentState.constants = nullptr;
pipelineDesc.fragment = &fragmentState;
pipelineDesc.depthStencil = nullptr;
// Samples per pixel
pipelineDesc.multisample.count = 1;
// Default value for the mask, meaning "all bits on"
pipelineDesc.multisample.mask = ~0u;
// Default value as well (irrelevant for count = 1 anyways)
pipelineDesc.multisample.alphaToCoverageEnabled = false;
pipelineDesc.layout = nullptr;
WGPUBlendState blendState{};
blendState.color.srcFactor = WGPUBlendFactor_SrcAlpha;
blendState.color.dstFactor = WGPUBlendFactor_OneMinusSrcAlpha;
blendState.color.operation = WGPUBlendOperation_Add;
blendState.alpha.srcFactor = WGPUBlendFactor_Zero;
blendState.alpha.dstFactor = WGPUBlendFactor_One;
blendState.alpha.operation = WGPUBlendOperation_Add;
WGPUColorTargetState colorTarget{};
colorTarget.format = surfaceFormat;
colorTarget.blend = &blendState;
colorTarget.writeMask = WGPUColorWriteMask_All;
fragmentState.targetCount = 1; // Maybe change this if many color attachments ?
fragmentState.targets = &colorTarget;
WGPURenderPipeline pipeline = wgpuDeviceCreateRenderPipeline(device, &pipelineDesc);
// No longer needed
wgpuShaderModuleRelease(shaderModule);
// Loop
while (!glfwWindowShouldClose(window)) {
glfwPollEvents();
if (glfwGetKey(window, GLFW_KEY_ESCAPE)) {
glfwSetWindowShouldClose(window, true);
}
// auto [surfaceTexture, targetView] = getNextSurfaceViewData(surface);
auto targetView = getNextSurfaceTextureView(surface);
if (!targetView)
return 0;
// Command encoder
WGPUCommandEncoderDescriptor encoderDesc = {};
encoderDesc.nextInChain = nullptr;
encoderDesc.label = "My command encoder";
WGPUCommandEncoder encoder = wgpuDeviceCreateCommandEncoder(device, &encoderDesc);
// Create render command
WGPURenderPassDescriptor renderPassDesc = {};
renderPassDesc.nextInChain = nullptr;
WGPURenderPassColorAttachment renderPassColorAttachment = {};
renderPassColorAttachment.nextInChain = nullptr;
renderPassColorAttachment.resolveTarget = nullptr;
renderPassColorAttachment.loadOp = WGPULoadOp_Clear;
renderPassColorAttachment.storeOp = WGPUStoreOp_Store;
renderPassColorAttachment.clearValue = {0.7, 0.2, 0.4};
#ifndef WEBGPU_BACKEND_WGPU
renderPassColorAttachment.depthSlice = WGPU_DEPTH_SLICE_UNDEFINED;
#endif // NOT WEBGPU_BACKEND_WGPU
renderPassColorAttachment.view = targetView;
// Setup render command
renderPassDesc.colorAttachmentCount = 1;
renderPassDesc.colorAttachments = &renderPassColorAttachment;
renderPassDesc.depthStencilAttachment = nullptr;
renderPassDesc.timestampWrites = nullptr;
// Call draw commands
WGPURenderPassEncoder renderPass = wgpuCommandEncoderBeginRenderPass(encoder, &renderPassDesc);
// Set pipeline to render pass
wgpuRenderPassEncoderSetPipeline(renderPass, pipeline);
wgpuRenderPassEncoderDraw(renderPass, 3, 1, 0, 0);
wgpuRenderPassEncoderEnd(renderPass);
wgpuRenderPassEncoderRelease(renderPass);
// Finally encode and submit the render pass
WGPUCommandBufferDescriptor cmdBufferDescriptor = {};
cmdBufferDescriptor.nextInChain = nullptr;
cmdBufferDescriptor.label = "Command buffer";
WGPUCommandBuffer command = wgpuCommandEncoderFinish(encoder, &cmdBufferDescriptor);
wgpuCommandEncoderRelease(encoder);
// std::cout << "Submitting command..." << std::endl;
wgpuQueueSubmit(queue, 1, &command);
wgpuCommandBufferRelease(command);
// std::cout << "Command submitted." << std::endl;
// At the end of the frame
wgpuTextureViewRelease(targetView);
#ifndef __EMSCRIPTEN__
wgpuSurfacePresent(surface);
#endif
#if defined(WEBGPU_BACKEND_DAWN)
wgpuDeviceTick(device);
#elif defined(WEBGPU_BACKEND_WGPU)
wgpuDevicePoll(device, false, nullptr);
#endif
}
// Clean up
glfwDestroyWindow(window);
glfwTerminate();
wgpuRenderPipelineRelease(pipeline);
wgpuSurfaceUnconfigure(surface);
wgpuSurfaceRelease(surface);
wgpuQueueRelease(queue);
wgpuDeviceRelease(device);
wgpuAdapterRelease(adapter);
wgpuInstanceRelease(instance);
return 0;
}