Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
microsoft
GitHub Repository: microsoft/vscode
Path: blob/main/src/vs/editor/browser/gpu/gpuDisposable.ts
3294 views
1
/*---------------------------------------------------------------------------------------------
2
* Copyright (c) Microsoft Corporation. All rights reserved.
3
* Licensed under the MIT License. See License.txt in the project root for license information.
4
*--------------------------------------------------------------------------------------------*/
5
6
import type { IReference } from '../../../base/common/lifecycle.js';
7
import { isFunction } from '../../../base/common/types.js';
8
9
export namespace GPULifecycle {
10
export async function requestDevice(fallback?: (message: string) => void): Promise<IReference<GPUDevice>> {
11
try {
12
if (!navigator.gpu) {
13
throw new Error('This browser does not support WebGPU');
14
}
15
const adapter = (await navigator.gpu.requestAdapter())!;
16
if (!adapter) {
17
throw new Error('This browser supports WebGPU but it appears to be disabled');
18
}
19
return wrapDestroyableInDisposable(await adapter.requestDevice());
20
} catch (e) {
21
if (fallback) {
22
fallback(e.message);
23
}
24
throw e;
25
}
26
}
27
28
export function createBuffer(device: GPUDevice, descriptor: GPUBufferDescriptor, initialValues?: Float32Array | (() => Float32Array)): IReference<GPUBuffer> {
29
const buffer = device.createBuffer(descriptor);
30
if (initialValues) {
31
device.queue.writeBuffer(buffer, 0, (isFunction(initialValues) ? initialValues() : initialValues) as Float32Array<ArrayBuffer>);
32
}
33
return wrapDestroyableInDisposable(buffer);
34
}
35
36
export function createTexture(device: GPUDevice, descriptor: GPUTextureDescriptor): IReference<GPUTexture> {
37
return wrapDestroyableInDisposable(device.createTexture(descriptor));
38
}
39
}
40
41
function wrapDestroyableInDisposable<T extends { destroy(): void }>(value: T): IReference<T> {
42
return {
43
object: value,
44
dispose: () => value.destroy()
45
};
46
}
47
48