forked from DiligentGraphics/DiligentCore
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEngineFactoryWebGPU.cpp
More file actions
748 lines (633 loc) · 31 KB
/
EngineFactoryWebGPU.cpp
File metadata and controls
748 lines (633 loc) · 31 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
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
/*
* Copyright 2023-2026 Diligent Graphics LLC
*
* You may not use this file except in compliance with the License (see License.txt).
*
* In no event and under no legal theory, whether in tort (including negligence),
* contract, or otherwise, unless required by applicable law (such as deliberate
* and grossly negligent acts) or agreed to in writing, shall any Contributor be
* liable for any damages, including any direct, indirect, special, incidental,
* or consequential damages of any character arising as a result of this License or
* out of the use or inability to use the software (including but not limited to damages
* for loss of goodwill, work stoppage, computer failure or malfunction, or any and
* all other commercial damages or losses), even if such Contributor has been advised
* of the possibility of such damages.
*/
/// \file
/// Routines that initialize WebGPU-based engine implementation
#include "pch.h"
#include "WebGPUObjectWrappers.hpp"
#include "EngineFactoryBase.hpp"
#include "EngineFactoryWebGPU.h"
#include "DeviceContextWebGPUImpl.hpp"
#include "RenderDeviceWebGPUImpl.hpp"
#include "SwapChainWebGPUImpl.hpp"
#include "RenderPassWebGPUImpl.hpp"
#include "TextureWebGPUImpl.hpp"
#include "PipelineStateWebGPUImpl.hpp"
#include "PipelineResourceSignatureWebGPUImpl.hpp"
#include "PipelineResourceAttribsWebGPU.hpp"
#include "ShaderResourceCacheWebGPU.hpp"
#include "FenceWebGPUImpl.hpp"
#include "DearchiverWebGPUImpl.hpp"
#include "WebGPUStubs.hpp"
#include "StringTools.hpp"
#include "GraphicsAccessories.hpp"
#if !PLATFORM_WEB
# include "dawn/native/DawnNative.h"
# include "dawn/dawn_proc.h"
#endif
#if PLATFORM_WEB
# include <emscripten.h>
#endif
namespace Diligent
{
/// Engine factory for WebGPU implementation
class EngineFactoryWebGPUImpl final : public EngineFactoryBase<IEngineFactoryWebGPU>
{
public:
static EngineFactoryWebGPUImpl* GetInstance()
{
static EngineFactoryWebGPUImpl TheFactory;
return &TheFactory;
}
using TBase = EngineFactoryBase;
EngineFactoryWebGPUImpl() :
TBase{IID_EngineFactoryWebGPU}
{}
void DILIGENT_CALL_TYPE EnumerateAdapters(Version MinVersion,
Uint32& NumAdapters,
GraphicsAdapterInfo* Adapters) const override final;
void DILIGENT_CALL_TYPE CreateDearchiver(const DearchiverCreateInfo& CreateInfo,
IDearchiver** ppDearchiver) const override final;
void DILIGENT_CALL_TYPE CreateDeviceAndContextsWebGPU(const EngineWebGPUCreateInfo& EngineCI,
IRenderDevice** ppDevice,
IDeviceContext** ppContexts) override final;
void DILIGENT_CALL_TYPE CreateSwapChainWebGPU(IRenderDevice* pDevice,
IDeviceContext* pImmediateContext,
const SwapChainDesc& SCDesc,
const NativeWindow& Window,
ISwapChain** ppSwapChain) override final;
void DILIGENT_CALL_TYPE AttachToWebGPUDevice(void* wgpuInstance,
void* wgpuAdapter,
void* wgpuDevice,
const EngineWebGPUCreateInfo& EngineCI,
IRenderDevice** ppDevice,
IDeviceContext** ppContexts) override final;
const void* DILIGENT_CALL_TYPE GetProcessTable() const override final;
};
namespace
{
void InstancePoolEvents(WGPUInstance wgpuInstance)
{
#if !PLATFORM_WEB
wgpuInstanceProcessEvents(wgpuInstance);
#endif
}
WebGPUInstanceWrapper InitializeWebGPUInstance(bool EnableUnsafe)
{
// Not implemented in Emscripten https://github.com/emscripten-core/emscripten/blob/217010a223375e6e9251669187d406ef2ddf266e/system/lib/webgpu/webgpu.cpp#L24
#if PLATFORM_WEB
WebGPUInstanceWrapper wgpuInstance{wgpuCreateInstance(nullptr)};
#else
struct SetDawnProcsHelper
{
SetDawnProcsHelper()
{
dawnProcSetProcs(&dawn::native::GetProcs());
}
};
static SetDawnProcsHelper SetDawnProcs;
const char* ToggleNames[] = {
"allow_unsafe_apis"};
WGPUDawnTogglesDescriptor wgpuDawnTogglesDesc = {};
wgpuDawnTogglesDesc.chain.sType = WGPUSType_DawnTogglesDescriptor;
wgpuDawnTogglesDesc.enabledToggleCount = _countof(ToggleNames);
wgpuDawnTogglesDesc.enabledToggles = ToggleNames;
WGPUInstanceDescriptor wgpuInstanceDesc = {};
if (EnableUnsafe)
{
wgpuInstanceDesc.nextInChain = reinterpret_cast<WGPUChainedStruct*>(&wgpuDawnTogglesDesc);
}
WebGPUInstanceWrapper wgpuInstance{wgpuCreateInstance(&wgpuInstanceDesc)};
#endif
if (!wgpuInstance)
LOG_ERROR_AND_THROW("Failed to create WebGPU instance");
return wgpuInstance;
}
std::vector<WebGPUAdapterWrapper> FindCompatibleAdapters(WGPUInstance wgpuInstance, Version MinVersion)
{
std::vector<WebGPUAdapterWrapper> wgpuAdapters;
struct CallbackUserData
{
WGPUAdapter Adapter = nullptr;
WGPURequestAdapterStatus RequestStatus = {};
String Message = {};
bool IsReady = {};
};
auto OnAdapterRequestEnded = [](WGPURequestAdapterStatus Status, WGPUAdapter Adapter, WGPUStringView Message, void* pCallbackUserData) {
if (pCallbackUserData != nullptr)
{
CallbackUserData* pUserData = static_cast<CallbackUserData*>(pCallbackUserData);
pUserData->Adapter = Adapter;
pUserData->RequestStatus = Status;
pUserData->IsReady = true;
if (WGPUStringViewValid(Message))
pUserData->Message = WGPUStringViewToString(Message);
}
};
WGPUPowerPreference PowerPreferences[] = {
WGPUPowerPreference_HighPerformance,
WGPUPowerPreference_LowPower};
for (const WGPUPowerPreference& powerPreference : PowerPreferences)
{
CallbackUserData UserData{};
WGPURequestAdapterOptions Options{};
Options.powerPreference = powerPreference;
Options.backendType = WGPUBackendType_Undefined;
Options.forceFallbackAdapter = false;
Options.compatibilityMode = false;
wgpuInstanceRequestAdapter(wgpuInstance, &Options, OnAdapterRequestEnded, &UserData);
while (!UserData.IsReady)
InstancePoolEvents(wgpuInstance);
if (UserData.RequestStatus == WGPURequestAdapterStatus_Success)
{
auto adapter_it = std::find_if(wgpuAdapters.begin(), wgpuAdapters.end(),
[&](const auto& wgpuAdapter) { return wgpuAdapter.Get() == UserData.Adapter; });
if (adapter_it == wgpuAdapters.end())
wgpuAdapters.emplace_back(UserData.Adapter);
}
else
{
LOG_WARNING_MESSAGE(UserData.Message);
}
}
return wgpuAdapters;
}
static void DeviceLostCallback(WGPUDeviceLostReason Reason,
WGPUStringView Message,
void* userdata)
{
bool Expression = Reason != WGPUDeviceLostReason_Destroyed;
#if !PLATFORM_WEB
Expression &= (Reason != WGPUDeviceLostReason_InstanceDropped);
#endif
if (Expression && WGPUStringViewValid(Message))
{
LOG_DEBUG_MESSAGE(DEBUG_MESSAGE_SEVERITY_ERROR, "WebGPU: ", WGPUStringViewToString(Message));
}
}
#if !PLATFORM_WEB
static void DeviceLostCallback2(WGPUDevice const* device,
WGPUDeviceLostReason Reason,
WGPUStringView Message,
void* userdata1,
void* userdata2)
{
DeviceLostCallback(Reason, Message, userdata1);
}
static void UncapturedErrorCallback2(WGPUDevice const* device,
WGPUErrorType MessageType,
WGPUStringView Message,
void* userdata1,
void* userdata2)
{
if (WGPUStringViewValid(Message))
{
LOG_DEBUG_MESSAGE(DEBUG_MESSAGE_SEVERITY_ERROR, "WebGPU: ", WGPUStringViewToString(Message));
}
}
#endif
WebGPUDeviceWrapper CreateDeviceForAdapter(const DeviceFeatures& Features, WGPUInstance wgpuInstance, WGPUAdapter wgpuAdapter)
{
WGPUSupportedLimits SupportedLimits{};
wgpuAdapterGetLimits(wgpuAdapter, &SupportedLimits);
std::vector<WGPUFeatureName> wgpuFeatures{};
{
auto AddWGPUFeature = [wgpuAdapter, &wgpuFeatures](bool Required, WGPUFeatureName wgpuFeature) {
if (Required && wgpuAdapterHasFeature(wgpuAdapter, wgpuFeature))
wgpuFeatures.push_back(wgpuFeature);
};
AddWGPUFeature(Features.DepthBiasClamp, WGPUFeatureName_DepthClipControl);
AddWGPUFeature(Features.TimestampQueries || Features.DurationQueries, WGPUFeatureName_TimestampQuery);
AddWGPUFeature(Features.DurationQueries, WGPUFeatureName_ChromiumExperimentalTimestampQueryInsidePasses);
AddWGPUFeature(Features.TextureCompressionBC, WGPUFeatureName_TextureCompressionBC);
AddWGPUFeature(Features.TextureCompressionETC2, WGPUFeatureName_TextureCompressionETC2);
AddWGPUFeature(Features.ShaderFloat16, WGPUFeatureName_ShaderF16);
if (wgpuAdapterHasFeature(wgpuAdapter, WGPUFeatureName_Depth32FloatStencil8))
wgpuFeatures.push_back(WGPUFeatureName_Depth32FloatStencil8);
if (wgpuAdapterHasFeature(wgpuAdapter, WGPUFeatureName_Float32Filterable))
wgpuFeatures.push_back(WGPUFeatureName_Float32Filterable);
if (wgpuAdapterHasFeature(wgpuAdapter, WGPUFeatureName_IndirectFirstInstance))
wgpuFeatures.push_back(WGPUFeatureName_IndirectFirstInstance);
if (wgpuAdapterHasFeature(wgpuAdapter, WGPUFeatureName_RG11B10UfloatRenderable))
wgpuFeatures.push_back(WGPUFeatureName_RG11B10UfloatRenderable);
if (wgpuAdapterHasFeature(wgpuAdapter, WGPUFeatureName_BGRA8UnormStorage))
wgpuFeatures.push_back(WGPUFeatureName_BGRA8UnormStorage);
if (wgpuAdapterHasFeature(wgpuAdapter, WGPUFeatureName_Unorm16TextureFormats))
wgpuFeatures.push_back(WGPUFeatureName_Unorm16TextureFormats);
if (wgpuAdapterHasFeature(wgpuAdapter, WGPUFeatureName_Snorm16TextureFormats))
wgpuFeatures.push_back(WGPUFeatureName_Snorm16TextureFormats);
}
struct CallbackUserData
{
WGPUDevice Device = nullptr;
WGPURequestDeviceStatus RequestStatus = {};
String Message = {};
bool IsReady = {};
} UserData;
auto OnDeviceRequestEnded = [](WGPURequestDeviceStatus Status, WGPUDevice Device, WGPUStringView Message, void* pCallbackUserData) {
if (pCallbackUserData != nullptr)
{
CallbackUserData* pUserData = static_cast<CallbackUserData*>(pCallbackUserData);
pUserData->Device = Device;
pUserData->RequestStatus = Status;
pUserData->IsReady = true;
if (WGPUStringViewValid(Message))
pUserData->Message = WGPUStringViewToString(Message);
}
};
#if !PLATFORM_WEB
const char* ToggleNames[] = {
"disable_timestamp_query_conversion",
"use_dxc",
};
WGPUDawnTogglesDescriptor wgpuDawnTogglesDesc = {};
wgpuDawnTogglesDesc.chain.sType = WGPUSType_DawnTogglesDescriptor;
wgpuDawnTogglesDesc.enabledToggleCount = _countof(ToggleNames);
wgpuDawnTogglesDesc.enabledToggles = ToggleNames;
#endif
WGPURequiredLimits RequiredLimits{nullptr, SupportedLimits.limits};
WGPUDeviceDescriptor DeviceDesc{};
DeviceDesc.requiredLimits = &RequiredLimits;
DeviceDesc.requiredFeatureCount = wgpuFeatures.size();
DeviceDesc.requiredFeatures = wgpuFeatures.data();
#if PLATFORM_WEB
DeviceDesc.deviceLostCallback = DeviceLostCallback;
#else
DeviceDesc.deviceLostCallbackInfo2 = {nullptr, WGPUCallbackMode_AllowSpontaneous, DeviceLostCallback2};
DeviceDesc.uncapturedErrorCallbackInfo2 = {nullptr, UncapturedErrorCallback2};
DeviceDesc.nextInChain = reinterpret_cast<WGPUChainedStruct*>(&wgpuDawnTogglesDesc);
#endif
wgpuAdapterRequestDevice(wgpuAdapter, &DeviceDesc, OnDeviceRequestEnded, &UserData);
while (!UserData.IsReady)
InstancePoolEvents(wgpuInstance);
if (UserData.RequestStatus != WGPURequestDeviceStatus_Success)
LOG_ERROR_AND_THROW(UserData.Message);
return WebGPUDeviceWrapper{UserData.Device};
}
bool FeatureSupported(WGPUAdapter wgpuAdapter, WGPUDevice wgpuDevice, WGPUFeatureName Feature)
{
if (wgpuAdapter != nullptr)
{
return wgpuAdapterHasFeature(wgpuAdapter, Feature);
}
else if (wgpuDevice != nullptr)
{
return wgpuDeviceHasFeature(wgpuDevice, Feature);
}
else
{
UNEXPECTED("Either adapter or device must not be null");
return DEVICE_FEATURE_STATE_DISABLED;
}
}
DeviceFeatures GetSupportedFeatures(WGPUAdapter wgpuAdapter, WGPUDevice wgpuDevice = nullptr)
{
auto CheckFeature = [wgpuAdapter, wgpuDevice](WGPUFeatureName Feature) {
return FeatureSupported(wgpuAdapter, wgpuDevice, Feature) ? DEVICE_FEATURE_STATE_ENABLED : DEVICE_FEATURE_STATE_DISABLED;
};
DeviceFeatures Features;
Features.SeparablePrograms = DEVICE_FEATURE_STATE_ENABLED;
Features.ShaderResourceQueries = DEVICE_FEATURE_STATE_ENABLED;
Features.WireframeFill = DEVICE_FEATURE_STATE_DISABLED;
Features.MultithreadedResourceCreation = DEVICE_FEATURE_STATE_DISABLED;
Features.ComputeShaders = DEVICE_FEATURE_STATE_ENABLED;
Features.GeometryShaders = DEVICE_FEATURE_STATE_DISABLED;
Features.Tessellation = DEVICE_FEATURE_STATE_DISABLED;
Features.MeshShaders = DEVICE_FEATURE_STATE_DISABLED;
Features.RayTracing = DEVICE_FEATURE_STATE_DISABLED;
Features.BindlessResources = DEVICE_FEATURE_STATE_DISABLED;
Features.OcclusionQueries = DEVICE_FEATURE_STATE_ENABLED;
Features.BinaryOcclusionQueries = DEVICE_FEATURE_STATE_DISABLED;
Features.PipelineStatisticsQueries = DEVICE_FEATURE_STATE_DISABLED;
Features.DepthBiasClamp = DEVICE_FEATURE_STATE_ENABLED;
Features.DepthClamp = CheckFeature(WGPUFeatureName_DepthClipControl);
Features.IndependentBlend = DEVICE_FEATURE_STATE_ENABLED;
Features.DualSourceBlend = CheckFeature(WGPUFeatureName_DualSourceBlending);
Features.MultiViewport = DEVICE_FEATURE_STATE_DISABLED;
Features.TextureCompressionBC = CheckFeature(WGPUFeatureName_TextureCompressionBC);
Features.TextureCompressionETC2 = CheckFeature(WGPUFeatureName_TextureCompressionETC2);
Features.VertexPipelineUAVWritesAndAtomics = DEVICE_FEATURE_STATE_ENABLED;
Features.PixelUAVWritesAndAtomics = DEVICE_FEATURE_STATE_ENABLED;
Features.TextureUAVExtendedFormats = DEVICE_FEATURE_STATE_ENABLED;
Features.ShaderFloat16 = CheckFeature(WGPUFeatureName_ShaderF16);
Features.ResourceBuffer16BitAccess = DEVICE_FEATURE_STATE_DISABLED;
Features.UniformBuffer16BitAccess = DEVICE_FEATURE_STATE_DISABLED;
Features.ShaderInputOutput16 = DEVICE_FEATURE_STATE_DISABLED;
Features.ShaderInt8 = DEVICE_FEATURE_STATE_DISABLED;
Features.ResourceBuffer8BitAccess = DEVICE_FEATURE_STATE_DISABLED;
Features.UniformBuffer8BitAccess = DEVICE_FEATURE_STATE_DISABLED;
Features.ShaderResourceStaticArrays = DEVICE_FEATURE_STATE_DISABLED;
Features.ShaderResourceRuntimeArrays = DEVICE_FEATURE_STATE_DISABLED;
Features.WaveOp = DEVICE_FEATURE_STATE_DISABLED;
Features.InstanceDataStepRate = DEVICE_FEATURE_STATE_DISABLED;
Features.NativeFence = DEVICE_FEATURE_STATE_DISABLED;
Features.TileShaders = DEVICE_FEATURE_STATE_DISABLED;
Features.TransferQueueTimestampQueries = DEVICE_FEATURE_STATE_DISABLED;
Features.VariableRateShading = DEVICE_FEATURE_STATE_DISABLED;
Features.SparseResources = DEVICE_FEATURE_STATE_DISABLED;
Features.SubpassFramebufferFetch = DEVICE_FEATURE_STATE_DISABLED;
Features.TextureComponentSwizzle = DEVICE_FEATURE_STATE_DISABLED;
Features.TextureSubresourceViews = DEVICE_FEATURE_STATE_ENABLED;
Features.NativeMultiDraw = DEVICE_FEATURE_STATE_DISABLED;
Features.AsyncShaderCompilation = DEVICE_FEATURE_STATE_ENABLED;
Features.FormattedBuffers = DEVICE_FEATURE_STATE_DISABLED;
Features.SpecializationConstants = DEVICE_FEATURE_STATE_ENABLED;
Features.TimestampQueries = CheckFeature(WGPUFeatureName_TimestampQuery);
Features.DurationQueries = Features.TimestampQueries ?
CheckFeature(WGPUFeatureName_ChromiumExperimentalTimestampQueryInsidePasses) :
DEVICE_FEATURE_STATE_DISABLED;
ASSERT_SIZEOF(DeviceFeatures, 48, "Did you add a new feature to DeviceFeatures? Please handle its status here.");
return Features;
}
GraphicsAdapterInfo GetGraphicsAdapterInfo(WGPUAdapter wgpuAdapter, WGPUDevice wgpuDevice = nullptr)
{
WGPUAdapterInfo wgpuAdapterInfo{};
if (wgpuAdapter)
wgpuAdapterGetInfo(wgpuAdapter, &wgpuAdapterInfo);
GraphicsAdapterInfo AdapterInfo{};
// Set graphics adapter properties
{
auto ConvertWPUAdapterType = [](WGPUAdapterType Type) -> ADAPTER_TYPE {
switch (Type)
{
case WGPUAdapterType_CPU:
return ADAPTER_TYPE_SOFTWARE;
case WGPUAdapterType_DiscreteGPU:
return ADAPTER_TYPE_DISCRETE;
case WGPUAdapterType_IntegratedGPU:
return ADAPTER_TYPE_INTEGRATED;
default:
return ADAPTER_TYPE_UNKNOWN;
}
};
if (WGPUStringViewValid(wgpuAdapterInfo.vendor))
{
const std::string Description = WGPUStringViewToString(wgpuAdapterInfo.vendor);
const size_t DescriptionSize = std::min(_countof(AdapterInfo.Description) - 1, Description.length());
memcpy(AdapterInfo.Description, Description.c_str(), DescriptionSize);
}
AdapterInfo.Type = ConvertWPUAdapterType(wgpuAdapterInfo.adapterType);
AdapterInfo.Vendor = VendorIdToAdapterVendor(wgpuAdapterInfo.vendorID);
AdapterInfo.VendorId = wgpuAdapterInfo.vendorID;
AdapterInfo.DeviceId = wgpuAdapterInfo.deviceID;
AdapterInfo.NumOutputs = 0;
}
AdapterInfo.Features = GetSupportedFeatures(wgpuAdapter, wgpuDevice);
WGPUSupportedLimits wgpuSupportedLimits{};
if (wgpuAdapter)
wgpuAdapterGetLimits(wgpuAdapter, &wgpuSupportedLimits);
else
wgpuDeviceGetLimits(wgpuDevice, &wgpuSupportedLimits);
// Set adapter memory info
{
AdapterMemoryInfo& DrawCommandInfo{AdapterInfo.Memory};
DrawCommandInfo.UnifiedMemoryCPUAccess = CPU_ACCESS_NONE;
DrawCommandInfo.UnifiedMemory = 0;
}
// Draw command properties
{
DrawCommandProperties& DrawCommandInfo{AdapterInfo.DrawCommand};
DrawCommandInfo.MaxDrawIndirectCount = ~0u;
DrawCommandInfo.CapFlags = DRAW_COMMAND_CAP_FLAG_DRAW_INDIRECT;
if (FeatureSupported(wgpuAdapter, wgpuDevice, WGPUFeatureName_IndirectFirstInstance))
DrawCommandInfo.CapFlags |= DRAW_COMMAND_CAP_FLAG_DRAW_INDIRECT_FIRST_INSTANCE;
}
// Set queue info
{
AdapterInfo.NumQueues = 1;
AdapterInfo.Queues[0].QueueType = COMMAND_QUEUE_TYPE_GRAPHICS;
AdapterInfo.Queues[0].MaxDeviceContexts = 1;
AdapterInfo.Queues[0].TextureCopyGranularity[0] = 1;
AdapterInfo.Queues[0].TextureCopyGranularity[1] = 1;
AdapterInfo.Queues[0].TextureCopyGranularity[2] = 1;
}
// Set compute shader info
{
ComputeShaderProperties& ComputeShaderInfo{AdapterInfo.ComputeShader};
ComputeShaderInfo.MaxThreadGroupSizeX = wgpuSupportedLimits.limits.maxComputeWorkgroupSizeX;
ComputeShaderInfo.MaxThreadGroupSizeY = wgpuSupportedLimits.limits.maxComputeWorkgroupSizeY;
ComputeShaderInfo.MaxThreadGroupSizeZ = wgpuSupportedLimits.limits.maxComputeWorkgroupSizeZ;
ComputeShaderInfo.MaxThreadGroupCountX = wgpuSupportedLimits.limits.maxComputeWorkgroupsPerDimension;
ComputeShaderInfo.MaxThreadGroupCountY = wgpuSupportedLimits.limits.maxComputeWorkgroupsPerDimension;
ComputeShaderInfo.MaxThreadGroupCountZ = wgpuSupportedLimits.limits.maxComputeWorkgroupsPerDimension;
ComputeShaderInfo.SharedMemorySize = wgpuSupportedLimits.limits.maxComputeWorkgroupStorageSize;
ComputeShaderInfo.MaxThreadGroupInvocations = wgpuSupportedLimits.limits.maxComputeInvocationsPerWorkgroup;
}
// Set texture info
{
TextureProperties& TextureInfo{AdapterInfo.Texture};
TextureInfo.MaxTexture1DArraySlices = 0; // Not supported in WebGPU
TextureInfo.MaxTexture2DArraySlices = wgpuSupportedLimits.limits.maxTextureArrayLayers;
TextureInfo.MaxTexture1DDimension = wgpuSupportedLimits.limits.maxTextureDimension1D;
TextureInfo.MaxTexture2DDimension = wgpuSupportedLimits.limits.maxTextureDimension2D;
TextureInfo.MaxTexture3DDimension = wgpuSupportedLimits.limits.maxTextureDimension3D;
TextureInfo.Texture2DMSSupported = True;
TextureInfo.Texture2DMSArraySupported = False;
TextureInfo.TextureViewSupported = True;
TextureInfo.CubemapArraysSupported = True;
TextureInfo.TextureView2DOn3DSupported = True;
}
// Set buffer info
{
BufferProperties& BufferInfo{AdapterInfo.Buffer};
BufferInfo.ConstantBufferOffsetAlignment = wgpuSupportedLimits.limits.minUniformBufferOffsetAlignment;
BufferInfo.StructuredBufferOffsetAlignment = wgpuSupportedLimits.limits.minStorageBufferOffsetAlignment;
}
// Set sampler info
{
SamplerProperties& BufferInfo{AdapterInfo.Sampler};
BufferInfo.MaxAnisotropy = 16;
}
wgpuAdapterInfoFreeMembers(wgpuAdapterInfo);
return AdapterInfo;
}
} // namespace
void EngineFactoryWebGPUImpl::EnumerateAdapters(Version MinVersion,
Uint32& NumAdapters,
GraphicsAdapterInfo* Adapters) const
{
WebGPUInstanceWrapper wgpuInstance = InitializeWebGPUInstance(true);
std::vector<WebGPUAdapterWrapper> wgpuAdapters = FindCompatibleAdapters(wgpuInstance.Get(), MinVersion);
if (Adapters == nullptr)
NumAdapters = static_cast<Uint32>(wgpuAdapters.size());
else
{
NumAdapters = (std::min)(NumAdapters, static_cast<Uint32>(wgpuAdapters.size()));
for (Uint32 AdapterId = 0; AdapterId < NumAdapters; ++AdapterId)
{
WebGPUAdapterWrapper& wgpuAdapter{wgpuAdapters[AdapterId]};
Adapters[AdapterId] = GetGraphicsAdapterInfo(wgpuAdapter.Get());
}
}
}
void EngineFactoryWebGPUImpl::CreateDearchiver(const DearchiverCreateInfo& CreateInfo,
IDearchiver** ppDearchiver) const
{
TBase::CreateDearchiver<DearchiverWebGPUImpl>(CreateInfo, ppDearchiver);
}
void EngineFactoryWebGPUImpl::CreateDeviceAndContextsWebGPU(const EngineWebGPUCreateInfo& EngineCI,
IRenderDevice** ppDevice,
IDeviceContext** ppImmediateContext)
{
DEV_CHECK_ERR(ppDevice && ppImmediateContext, "Null pointer provided");
if (!ppDevice || !ppImmediateContext)
return;
*ppDevice = nullptr;
*ppImmediateContext = nullptr;
try
{
WebGPUInstanceWrapper wgpuInstance = InitializeWebGPUInstance(true);
std::vector<WebGPUAdapterWrapper> wgpuAdapters = FindCompatibleAdapters(wgpuInstance.Get(), EngineCI.GraphicsAPIVersion);
WebGPUAdapterWrapper SpecificAdapter{};
if (EngineCI.AdapterId != DEFAULT_ADAPTER_ID)
{
if (EngineCI.AdapterId < wgpuAdapters.size())
SpecificAdapter = std::move(wgpuAdapters[EngineCI.AdapterId]);
else
LOG_ERROR_AND_THROW(EngineCI.AdapterId, " is not a valid hardware adapter id. Total number of compatible adapters available on this system: ", wgpuAdapters.size());
}
else
{
SpecificAdapter = std::move(wgpuAdapters[0]);
}
WebGPUDeviceWrapper Device = CreateDeviceForAdapter(EngineCI.Features, wgpuInstance, SpecificAdapter);
AttachToWebGPUDevice(wgpuInstance.Detach(), SpecificAdapter.Detach(), Device.Detach(), EngineCI, ppDevice, ppImmediateContext);
}
catch (const std::runtime_error&)
{
}
}
void EngineFactoryWebGPUImpl::CreateSwapChainWebGPU(IRenderDevice* pDevice,
IDeviceContext* pImmediateContext,
const SwapChainDesc& SCDesc,
const NativeWindow& Window,
ISwapChain** ppSwapChain)
{
DEV_CHECK_ERR(ppSwapChain, "Null pointer provided");
if (!ppSwapChain)
return;
*ppSwapChain = nullptr;
try
{
RenderDeviceWebGPUImpl* pDeviceWebGPU = ClassPtrCast<RenderDeviceWebGPUImpl>(pDevice);
DeviceContextWebGPUImpl* pDeviceContextWebGPU = ClassPtrCast<DeviceContextWebGPUImpl>(pImmediateContext);
IMemoryAllocator& RawMemAllocator = GetRawAllocator();
SwapChainWebGPUImpl* pSwapChainWebGPU = NEW_RC_OBJ(RawMemAllocator, "SwapChainWebGPUImpl instance", SwapChainWebGPUImpl)(SCDesc, pDeviceWebGPU, pDeviceContextWebGPU, Window);
pSwapChainWebGPU->QueryInterface(IID_SwapChain, ppSwapChain);
}
catch (const std::runtime_error&)
{
if (*ppSwapChain)
{
(*ppSwapChain)->Release();
*ppSwapChain = nullptr;
}
LOG_ERROR("Failed to create WebGPU-based swapchain");
}
}
void EngineFactoryWebGPUImpl::AttachToWebGPUDevice(void* wgpuInstance,
void* wgpuAdapter,
void* wgpuDevice,
const EngineWebGPUCreateInfo& EngineCI,
IRenderDevice** ppDevice,
IDeviceContext** ppImmediateContext)
{
if (EngineCI.EngineAPIVersion != DILIGENT_API_VERSION)
{
LOG_ERROR_MESSAGE("Diligent Engine runtime (", DILIGENT_API_VERSION, ") is not compatible with the client API version (", EngineCI.EngineAPIVersion, ")");
return;
}
VERIFY(ppDevice && ppImmediateContext, "Null pointer provided");
if (!ppDevice || !ppImmediateContext)
return;
if (EngineCI.NumImmediateContexts > 1)
{
LOG_ERROR_MESSAGE("WebGPU backend doesn't support multiple immediate contexts");
return;
}
if (EngineCI.NumDeferredContexts > 0)
{
LOG_ERROR_MESSAGE("WebGPU backend doesn't support multiple deferred contexts");
return;
}
*ppDevice = nullptr;
*ppImmediateContext = nullptr;
try
{
const GraphicsAdapterInfo AdapterInfo = GetGraphicsAdapterInfo(static_cast<WGPUAdapter>(wgpuAdapter), static_cast<WGPUDevice>(wgpuDevice));
VerifyEngineCreateInfo(EngineCI, AdapterInfo);
const DeviceFeatures EnabledFeatures = GetSupportedFeatures(nullptr, static_cast<WGPUDevice>(wgpuDevice));
IMemoryAllocator& RawMemAllocator = GetRawAllocator();
RenderDeviceWebGPUImpl* pRenderDeviceWebGPU{
NEW_RC_OBJ(RawMemAllocator, "RenderDeviceWebGPUImpl instance", RenderDeviceWebGPUImpl)(
RenderDeviceWebGPUImpl::CreateInfo{
RawMemAllocator,
this,
EngineCI,
AdapterInfo,
EnabledFeatures,
static_cast<WGPUInstance>(wgpuInstance),
static_cast<WGPUAdapter>(wgpuAdapter),
static_cast<WGPUDevice>(wgpuDevice),
})};
pRenderDeviceWebGPU->QueryInterface(IID_RenderDevice, ppDevice);
DeviceContextWebGPUImpl* pDeviceContextWebGPU{
NEW_RC_OBJ(RawMemAllocator, "DeviceContextWebGPUImpl instance", DeviceContextWebGPUImpl)(
pRenderDeviceWebGPU,
DeviceContextDesc{
EngineCI.pImmediateContextInfo ? EngineCI.pImmediateContextInfo[0].Name : nullptr,
pRenderDeviceWebGPU->GetAdapterInfo().Queues[0].QueueType,
False, // IsDeferred
0, // Context id
0 // Queue id
})};
pDeviceContextWebGPU->QueryInterface(IID_DeviceContext, ppImmediateContext);
pRenderDeviceWebGPU->SetImmediateContext(0, pDeviceContextWebGPU);
}
catch (const std::runtime_error&)
{
if (*ppDevice)
{
(*ppDevice)->Release();
*ppDevice = nullptr;
}
if (*ppImmediateContext != nullptr)
{
(*ppImmediateContext)->Release();
*ppImmediateContext = nullptr;
}
LOG_ERROR("Failed to create WebGPU-based render device and context");
}
}
const void* EngineFactoryWebGPUImpl::GetProcessTable() const
{
#if !PLATFORM_WEB
return &dawn::native::GetProcs();
#else
return nullptr;
#endif
}
API_QUALIFIER IEngineFactoryWebGPU* GetEngineFactoryWebGPU()
{
return EngineFactoryWebGPUImpl::GetInstance();
}
} // namespace Diligent
extern "C"
{
API_QUALIFIER Diligent::IEngineFactoryWebGPU* Diligent_GetEngineFactoryWebGPU()
{
return Diligent::GetEngineFactoryWebGPU();
}
}