1 // Copyright 2021 The Dawn Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 #include "dawn/dawn_proc.h"
16 #include "src/dawn_node/binding/Flags.h"
17 #include "src/dawn_node/binding/GPU.h"
18
19 namespace {
CreateGPU(const Napi::CallbackInfo& info)20 Napi::Value CreateGPU(const Napi::CallbackInfo& info) {
21 const auto& env = info.Env();
22
23 std::tuple<std::vector<std::string>> args;
24 auto res = wgpu::interop::FromJS(info, args);
25 if (res != wgpu::interop::Success) {
26 Napi::Error::New(env, res.error).ThrowAsJavaScriptException();
27 return env.Undefined();
28 }
29
30 wgpu::binding::Flags flags;
31
32 // Parse out the key=value flags out of the input args array
33 for (const auto& arg : std::get<0>(args)) {
34 const size_t sep_index = arg.find("=");
35 if (sep_index == std::string::npos) {
36 Napi::Error::New(env, "Flags expected argument format is <key>=<value>")
37 .ThrowAsJavaScriptException();
38 return env.Undefined();
39 }
40 flags.Set(arg.substr(0, sep_index), arg.substr(sep_index + 1));
41 }
42
43 // Construct a wgpu::interop::GPU interface, implemented by wgpu::bindings::GPU.
44 return wgpu::interop::GPU::Create<wgpu::binding::GPU>(env, std::move(flags));
45 }
46
47 } // namespace
48
49 // Initialize() initializes the Dawn node module, registering all the WebGPU
50 // types into the global object, and adding the 'create' function on the exported
51 // object.
Initialize(Napi::Env env, Napi::Object exports)52 Napi::Object Initialize(Napi::Env env, Napi::Object exports) {
53 // Begin by setting the Dawn procedure function pointers.
54 dawnProcSetProcs(&dawn_native::GetProcs());
55
56 // Register all the interop types
57 wgpu::interop::Initialize(env);
58
59 // Export function that creates and returns the wgpu::interop::GPU interface
60 exports.Set(Napi::String::New(env, "create"), Napi::Function::New<CreateGPU>(env));
61
62 return exports;
63 }
64
65 NODE_API_MODULE(addon, Initialize)
66