290 {
291 IMG2NUM_LOG_DEBUG("Requesting Device...");
292
293 wgpu::DeviceDescriptor deviceDesc = {};
294 deviceDesc.SetUncapturedErrorCallback([](const wgpu::Device&, wgpu::ErrorType type,
295 wgpu::StringView msg) {
296
297 std::string err_str = (msg.data && msg.length > 0) ? std::string(msg.data, msg.length)
298 : "Unknown Error (Null message)";
299
300
301 IMG2NUM_LOG_ERROR(
302 "\n[WEBGPU FATAL ERROR] Type: {} | Msg: {}\n", static_cast<uint32_t>(type), err_str
303 );
304 });
305 deviceDesc.SetDeviceLostCallback(
306#if defined(__EMSCRIPTEN__)
307 wgpu::CallbackMode::AllowProcessEvents,
308#else
309
310 wgpu::CallbackMode::AllowSpontaneous,
311#endif
312 [](const wgpu::Device&, wgpu::DeviceLostReason reason, wgpu::StringView msg) {
313 std::string err_msg = (msg.data && msg.length > 0)
314 ? std::string(msg.data, msg.length)
315 : "Unknown device lost reason";
316
317 if (reason == wgpu::DeviceLostReason::CallbackCancelled ||
318 reason == wgpu::DeviceLostReason::Destroyed) {
319 return;
320 }
321 IMG2NUM_LOG_ERROR(
322 "[DEVICE LOST] Reason: {} Msg: {}", static_cast<int>(reason), err_msg
323 );
324 }
325 );
326
327#if !defined(__EMSCRIPTEN__)
328
329
330 static constexpr wgpu::FeatureName kImplicitSync =
331 wgpu::FeatureName::ImplicitDeviceSynchronization;
332 if (adapter.HasFeature(kImplicitSync)) {
333 deviceDesc.requiredFeatureCount = 1;
334 deviceDesc.requiredFeatures = &kImplicitSync;
335 }
336#endif
337
338
339 wgpu::Limits supportedLimits;
340 wgpu::Limits requiredLimits;
341 if (adapter.GetLimits(&supportedLimits)) {
342
343
344
345 requiredLimits = supportedLimits;
346
347 IMG2NUM_LOG_DEBUG("maxBufferSize: {}", requiredLimits.maxBufferSize);
348 IMG2NUM_LOG_DEBUG(
349 "maxStorageBufferBindingSize: {}", requiredLimits.maxStorageBufferBindingSize
350 );
351
352 deviceDesc.requiredLimits = &requiredLimits;
353 }
354
355 wgpu::Device device;
356 bool device_ready = false;
357 wgpu::Future future = adapter.RequestDevice(
358 &deviceDesc, kWaitMode,
359 [&](wgpu::RequestDeviceStatus status, wgpu::Device d, wgpu::StringView msg) {
360 if (status == wgpu::RequestDeviceStatus::Success) {
361 device = std::move(d);
362 IMG2NUM_LOG_INFO("Device Acquired");
363 } else {
364 IMG2NUM_LOG_WARN(
365 "Device Failed: {}", msg.data && msg.length > 0
366 ? std::string(msg.data, msg.length)
367 : "Unknown error"
368 );
369 }
370 device_ready = true;
371 }
372 );
373 wait(future, device_ready);
374 return device;
375 }