@drawcall/webgpu 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +21 -2
- package/package.json +50 -4
- package/skills/webgpu/SKILL.md +51 -0
- package/src/browser.js +26 -0
- package/src/canvas.js +133 -0
- package/src/globals.js +15 -0
- package/src/gpu.js +37 -0
- package/src/host.js +62 -0
- package/src/image.js +59 -0
- package/src/index.js +30 -0
- package/src/native.js +51 -0
- package/src/platform.js +11 -0
- package/src/worker.js +99 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 drawcall
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,22 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @drawcall/webgpu
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Use standard Three.js rendering and WebGPU compute in browsers and GPU-less Node.js. Browsers use their own WebGPU implementation; Node uses bundled native CPU rendering. Three.js and original assets stay unchanged.
|
|
4
|
+
|
|
5
|
+
```js
|
|
6
|
+
import { createCanvas } from '@drawcall/webgpu';
|
|
7
|
+
import { WebGPURenderer } from 'three/webgpu';
|
|
8
|
+
|
|
9
|
+
const canvas = await createCanvas(1280, 720);
|
|
10
|
+
const renderer = new WebGPURenderer({ canvas });
|
|
11
|
+
await renderer.init();
|
|
12
|
+
// Build or load your scene with three/webgpu and standard Three.js loaders.
|
|
13
|
+
renderer.render(scene, camera);
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
In a browser, append the returned canvas to your container. It is a real canvas with normal CSS, events, and resizing. Use `{ offscreen: true }` as the third argument for an `OffscreenCanvas`. Browser support requires WebGPU in a secure context. Node canvases are always headless: CSS assignments are inert; explicit dimensions control output resolution.
|
|
17
|
+
|
|
18
|
+
For Node image export, canvas-free compute, loading assets, and cleanup, see the shipped [usage skill](skills/webgpu/SKILL.md). Compute uses `requestAdapter()` followed by standard WebGPU device and command APIs. Node does not provide DOM layout, video, or canvas-2D texture sources.
|
|
19
|
+
|
|
20
|
+
Node requires version 22+. Native packages bundle the software renderer and Vulkan loader for Linux x64/ARM64 (glibc 2.28+ or musl 1.2.5+/Alpine 3.22+), macOS 13.5+ (Intel/Apple Silicon), and Windows x64/ARM64. x64 requires SSE4.2. No GPU, browser, compiler, SDK, or system graphics packages are needed. Keep npm optional dependencies enabled. Other platform/CPU combinations are unsupported.
|
|
21
|
+
|
|
22
|
+
Run the upstream Three.js [compute-texture example](examples/compute-texture) with `npm install --prefix examples/compute-texture` and `npm run dev --prefix examples/compute-texture`. Browser and Node entry points share the same scene, compute, and camera logic, extracted from the upstream example. Render a PNG without a browser using `npm run render --prefix examples/compute-texture -- frame.png`.
|
package/package.json
CHANGED
|
@@ -1,6 +1,52 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@drawcall/webgpu",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "WebGPU rendering and compute in browsers and GPU-less Node.js",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": {
|
|
9
|
+
"node": "./src/index.js",
|
|
10
|
+
"default": "./src/browser.js"
|
|
11
|
+
}
|
|
12
|
+
},
|
|
13
|
+
"files": [
|
|
14
|
+
"src",
|
|
15
|
+
"skills"
|
|
16
|
+
],
|
|
17
|
+
"engines": {
|
|
18
|
+
"node": ">=22"
|
|
19
|
+
},
|
|
20
|
+
"repository": {
|
|
21
|
+
"type": "git",
|
|
22
|
+
"url": "git+https://github.com/drawcall-ai/webgpu.git"
|
|
23
|
+
},
|
|
24
|
+
"scripts": {
|
|
25
|
+
"build:native": "modal run native/cloud.py",
|
|
26
|
+
"test": "node --test --test-concurrency=1 test/*.test.js",
|
|
27
|
+
"test:cloud": "modal run test/cloud.py",
|
|
28
|
+
"bench": "modal run test/cloud.py",
|
|
29
|
+
"test:package": "node deps/consumer.js",
|
|
30
|
+
"release:prepare": "node deps/release.js prepare",
|
|
31
|
+
"release:publish": "node deps/release.js publish",
|
|
32
|
+
"test:release": "node --test test/tools/release.test.js",
|
|
33
|
+
"release:trust": "node deps/release.js trust"
|
|
34
|
+
},
|
|
35
|
+
"dependencies": {
|
|
36
|
+
"detect-libc": "2.1.2",
|
|
37
|
+
"sharp": "0.35.5"
|
|
38
|
+
},
|
|
39
|
+
"optionalDependencies": {
|
|
40
|
+
"@drawcall/webgpu-linux-x64": "0.1.1",
|
|
41
|
+
"@drawcall/webgpu-linux-arm64": "0.1.1",
|
|
42
|
+
"@drawcall/webgpu-darwin-x64": "0.1.1",
|
|
43
|
+
"@drawcall/webgpu-darwin-arm64": "0.1.1",
|
|
44
|
+
"@drawcall/webgpu-win32-x64": "0.1.1",
|
|
45
|
+
"@drawcall/webgpu-linuxmusl-x64": "0.1.1",
|
|
46
|
+
"@drawcall/webgpu-linuxmusl-arm64": "0.1.1",
|
|
47
|
+
"@drawcall/webgpu-win32-arm64": "0.1.1"
|
|
48
|
+
},
|
|
49
|
+
"devDependencies": {
|
|
50
|
+
"three": "0.186.1"
|
|
51
|
+
}
|
|
52
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: webgpu
|
|
3
|
+
description: Use @drawcall/webgpu for portable Three.js rendering and WebGPU compute in browsers and GPU-less Node.js, including headless scene export with standard loaders.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Render a scene
|
|
7
|
+
|
|
8
|
+
Use the same Three.js scene and renderer code in both environments. Browser canvases are real DOM elements; append them to the application container and use normal CSS and resize handling. In workers, request an offscreen canvas and send dimensions from the main thread. Node has no layout engine: supply output dimensions, and do not infer them from CSS.
|
|
9
|
+
|
|
10
|
+
In Node, create the canvas before loading assets and keep it alive until loaders and rendering finish. Import scene classes from `three/webgpu` and loaders from `three/addons`. Keep original assets intact; compressed glTF can use the standard `DRACOLoader` with its decoder directory served over HTTP.
|
|
11
|
+
|
|
12
|
+
Install `three` and `sharp` as application dependencies for this Node export pattern:
|
|
13
|
+
|
|
14
|
+
```js
|
|
15
|
+
import { createCanvas } from '@drawcall/webgpu';
|
|
16
|
+
import { WebGPURenderer } from 'three/webgpu';
|
|
17
|
+
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
|
|
18
|
+
import { DRACOLoader } from 'three/addons/loaders/DRACOLoader.js';
|
|
19
|
+
import sharp from 'sharp';
|
|
20
|
+
|
|
21
|
+
const canvas = await createCanvas(1280, 720);
|
|
22
|
+
const renderer = new WebGPURenderer({ canvas });
|
|
23
|
+
const draco = new DRACOLoader().setWorkerLimit(1).setDecoderPath(decoderURL);
|
|
24
|
+
try {
|
|
25
|
+
await renderer.init();
|
|
26
|
+
const gltf = await new GLTFLoader().setDRACOLoader(draco).loadAsync(modelURL);
|
|
27
|
+
renderer.render(gltf.scene, camera);
|
|
28
|
+
const pixels = await canvas.readPixels();
|
|
29
|
+
await sharp(pixels, {
|
|
30
|
+
raw: { width: canvas.width, height: canvas.height, channels: 4 },
|
|
31
|
+
}).png().toFile('frame.png');
|
|
32
|
+
} finally {
|
|
33
|
+
try { draco.dispose(); } finally {
|
|
34
|
+
try { await renderer.dispose(); } finally { await canvas.dispose(); }
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Use HTTP(S) URLs for standard loaders, including assets on a local file server; Node's fetch does not load `file:` URLs. Supply a camera and framing suitable for the scene. Three.js resources created by your application remain yours to dispose; see [Three.js cleanup guidance](https://threejs.org/manual/en/cleanup.html).
|
|
40
|
+
|
|
41
|
+
The example above exports a frame in Node. In browsers, use the canvas normally; do not call its Node-only export and cleanup methods. For portable Three readback, use a render target and Three’s readback API.
|
|
42
|
+
|
|
43
|
+
Render the final frame to the canvas. If custom passes use render targets, call `renderer.setRenderTarget(null)` before the final canvas render and readback. Dispose the renderer and loaders before the canvas. A canvas does not own an application-supplied device: destroy that device after all rendering and compute users finish.
|
|
44
|
+
|
|
45
|
+
For cold server-side rendering, launch a fresh process per task, render, encode, and await disposal. Node does not supply a browser DOM, video decoding, 2D canvas, or the complete browser Worker API. Blob image decoding and classic workers support the tested glTF and Draco paths; other loaders may need browser APIs outside this scope. Treat unsupported API errors as compatibility gaps rather than replacing assets or patching Three.js.
|
|
46
|
+
|
|
47
|
+
# Compute without a canvas
|
|
48
|
+
|
|
49
|
+
Import `requestAdapter` from the package, check its result, then call the adapter’s standard `requestDevice` with the features and limits the workload requires. Use ordinary WGSL, buffers, compute passes, and queue submission. No canvas or loader host is needed. Destroy application-owned devices when finished; do not rely on garbage collection to release GPU resources. Browser and software adapters can expose different capabilities.
|
|
50
|
+
|
|
51
|
+
For combined raw compute and Three rendering, pass the same application-created device to `WebGPURenderer`. For Three TSL compute nodes, use the renderer’s compute API directly. Neither path requires changing Three.js.
|
package/src/browser.js
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/** Return a real browser canvas; CSS, events and layout remain browser-owned. */
|
|
2
|
+
export async function createCanvas(width, height, { offscreen = false } = {}) {
|
|
3
|
+
if (!Number.isInteger(width) || width < 1 || !Number.isInteger(height) || height < 1) {
|
|
4
|
+
throw new RangeError('Canvas dimensions must be positive integers');
|
|
5
|
+
}
|
|
6
|
+
if (typeof offscreen !== 'boolean') throw new TypeError('offscreen must be a boolean');
|
|
7
|
+
if (offscreen) return new OffscreenCanvas(width, height);
|
|
8
|
+
const canvas = document.createElement('canvas');
|
|
9
|
+
canvas.width = width;
|
|
10
|
+
canvas.height = height;
|
|
11
|
+
return canvas;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function gpu() {
|
|
15
|
+
if (!globalThis.navigator?.gpu) throw new Error('WebGPU is unavailable; use a supported browser in a secure context');
|
|
16
|
+
return navigator.gpu;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** Forward standard adapter selection to the browser, including its null result. */
|
|
20
|
+
export async function requestAdapter(options) {
|
|
21
|
+
return gpu().requestAdapter(options);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function getPreferredCanvasFormat() {
|
|
25
|
+
return gpu().getPreferredCanvasFormat();
|
|
26
|
+
}
|
package/src/canvas.js
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
function dimension(value) {
|
|
2
|
+
if (!Number.isInteger(value) || value < 1) throw new RangeError('Canvas dimensions must be positive integers');
|
|
3
|
+
return value;
|
|
4
|
+
}
|
|
5
|
+
|
|
6
|
+
// A native canvas keeps its last frame available until resize or reconfiguration.
|
|
7
|
+
export function canvas(width, height, check) {
|
|
8
|
+
width = dimension(width);
|
|
9
|
+
height = dimension(height);
|
|
10
|
+
let configuration, texture, device, lost;
|
|
11
|
+
let closed = false;
|
|
12
|
+
const errors = [];
|
|
13
|
+
const events = new EventTarget();
|
|
14
|
+
const onError = event => errors.push(event.error);
|
|
15
|
+
|
|
16
|
+
function ready() {
|
|
17
|
+
check();
|
|
18
|
+
if (closed) throw new Error('Canvas is disposed');
|
|
19
|
+
if (lost) throw new Error(`Device lost: ${lost.reason}: ${lost.message}`);
|
|
20
|
+
if (errors.length) throw new AggregateError(errors, 'WebGPU rendering failed');
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function reset() {
|
|
24
|
+
texture?.destroy();
|
|
25
|
+
texture = undefined;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const output = {
|
|
29
|
+
get width() { return width; },
|
|
30
|
+
set width(value) { ready(); width = dimension(value); reset(); },
|
|
31
|
+
get height() { return height; },
|
|
32
|
+
set height(value) { ready(); height = dimension(value); reset(); },
|
|
33
|
+
style: {},
|
|
34
|
+
addEventListener: events.addEventListener.bind(events),
|
|
35
|
+
removeEventListener: events.removeEventListener.bind(events),
|
|
36
|
+
dispatchEvent: events.dispatchEvent.bind(events),
|
|
37
|
+
getContext(type) { ready(); return type === 'webgpu' ? context : null; },
|
|
38
|
+
/** Returns the current frame as packed, top-row-first straight-alpha RGBA8 bytes. */
|
|
39
|
+
async readPixels() {
|
|
40
|
+
ready();
|
|
41
|
+
if (!texture) throw new Error('Render a frame before reading canvas pixels');
|
|
42
|
+
const source = texture;
|
|
43
|
+
const premultiplied = configuration.alphaMode === 'premultiplied';
|
|
44
|
+
const rowBytes = source.width * 4;
|
|
45
|
+
const stride = Math.ceil(rowBytes / 256) * 256;
|
|
46
|
+
const buffer = device.createBuffer({ size: stride * source.height, usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ });
|
|
47
|
+
try {
|
|
48
|
+
const encoder = device.createCommandEncoder();
|
|
49
|
+
encoder.copyTextureToBuffer({ texture: source }, { buffer, bytesPerRow: stride }, [source.width, source.height]);
|
|
50
|
+
device.queue.submit([encoder.finish()]);
|
|
51
|
+
await buffer.mapAsync(GPUMapMode.READ);
|
|
52
|
+
ready();
|
|
53
|
+
const mapped = new Uint8Array(buffer.getMappedRange());
|
|
54
|
+
const pixels = new Uint8Array(rowBytes * source.height);
|
|
55
|
+
for (let row = 0; row < source.height; row++) {
|
|
56
|
+
pixels.set(mapped.subarray(row * stride, row * stride + rowBytes), row * rowBytes);
|
|
57
|
+
}
|
|
58
|
+
const bgra = source.format === 'bgra8unorm';
|
|
59
|
+
if (premultiplied) {
|
|
60
|
+
for (let index = 0; index < pixels.length; index += 4) {
|
|
61
|
+
const alpha = pixels[index + 3];
|
|
62
|
+
const scale = alpha === 0 ? 0 : 255 / alpha;
|
|
63
|
+
const red = pixels[index + (bgra ? 2 : 0)];
|
|
64
|
+
const blue = pixels[index + (bgra ? 0 : 2)];
|
|
65
|
+
pixels[index] = Math.min(255, Math.round(red * scale));
|
|
66
|
+
pixels[index + 1] = Math.min(255, Math.round(pixels[index + 1] * scale));
|
|
67
|
+
pixels[index + 2] = Math.min(255, Math.round(blue * scale));
|
|
68
|
+
}
|
|
69
|
+
} else if (bgra) {
|
|
70
|
+
for (let index = 0; index < pixels.length; index += 4) {
|
|
71
|
+
const red = pixels[index + 2];
|
|
72
|
+
pixels[index + 2] = pixels[index];
|
|
73
|
+
pixels[index] = red;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return pixels;
|
|
77
|
+
} finally {
|
|
78
|
+
buffer.destroy();
|
|
79
|
+
}
|
|
80
|
+
},
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
const context = {
|
|
84
|
+
canvas: output,
|
|
85
|
+
configure(value) {
|
|
86
|
+
ready();
|
|
87
|
+
if (device && value.device !== device) throw new TypeError('A canvas cannot switch WebGPU devices');
|
|
88
|
+
if (!value.device || typeof value.device.createTexture !== 'function') throw new TypeError('A WebGPU device is required');
|
|
89
|
+
if ((value.colorSpace ?? 'srgb') !== 'srgb') throw new TypeError('Only sRGB canvas color space is supported');
|
|
90
|
+
if (!['opaque', 'premultiplied'].includes(value.alphaMode ?? 'opaque')) throw new TypeError('Unsupported canvas alpha mode');
|
|
91
|
+
if ((value.toneMapping?.mode ?? 'standard') !== 'standard') throw new TypeError('Extended canvas tone mapping is not supported');
|
|
92
|
+
if (!['rgba8unorm', 'bgra8unorm'].includes(value.format)) throw new TypeError('Unsupported canvas format');
|
|
93
|
+
if (!device) {
|
|
94
|
+
device = value.device;
|
|
95
|
+
device.addEventListener('uncapturederror', onError);
|
|
96
|
+
device.lost.then(info => { if (!closed) lost = info; });
|
|
97
|
+
}
|
|
98
|
+
reset();
|
|
99
|
+
configuration = { ...value, viewFormats: [...(value.viewFormats ?? [])] };
|
|
100
|
+
},
|
|
101
|
+
getConfiguration() {
|
|
102
|
+
ready();
|
|
103
|
+
return configuration ? { ...configuration, viewFormats: [...configuration.viewFormats] } : null;
|
|
104
|
+
},
|
|
105
|
+
getCurrentTexture() {
|
|
106
|
+
ready();
|
|
107
|
+
if (!configuration) throw new Error('Canvas is not configured');
|
|
108
|
+
if (width > device.limits.maxTextureDimension2D || height > device.limits.maxTextureDimension2D) throw new RangeError('Canvas dimensions exceed the device texture limit');
|
|
109
|
+
texture ??= device.createTexture({
|
|
110
|
+
size: [width, height],
|
|
111
|
+
format: configuration.format,
|
|
112
|
+
usage: (configuration.usage ?? GPUTextureUsage.RENDER_ATTACHMENT) | GPUTextureUsage.COPY_SRC,
|
|
113
|
+
viewFormats: configuration.viewFormats,
|
|
114
|
+
});
|
|
115
|
+
return texture;
|
|
116
|
+
},
|
|
117
|
+
unconfigure() { ready(); reset(); configuration = undefined; },
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
return {
|
|
121
|
+
output,
|
|
122
|
+
close() {
|
|
123
|
+
closed = true;
|
|
124
|
+
reset();
|
|
125
|
+
configuration = undefined;
|
|
126
|
+
if (device) {
|
|
127
|
+
device.removeEventListener('uncapturederror', onError);
|
|
128
|
+
}
|
|
129
|
+
if (lost && lost.reason !== 'destroyed') errors.push(new Error(`Device lost: ${lost.reason}: ${lost.message}`));
|
|
130
|
+
if (errors.length) throw new AggregateError(errors, 'WebGPU rendering failed');
|
|
131
|
+
},
|
|
132
|
+
};
|
|
133
|
+
}
|
package/src/globals.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export function globals() {
|
|
2
|
+
const previous = new Map();
|
|
3
|
+
return {
|
|
4
|
+
set(name, value) {
|
|
5
|
+
if (!previous.has(name)) previous.set(name, Object.getOwnPropertyDescriptor(globalThis, name));
|
|
6
|
+
Object.defineProperty(globalThis, name, { value, configurable: true, writable: true });
|
|
7
|
+
},
|
|
8
|
+
restore() {
|
|
9
|
+
for (const [name, descriptor] of previous) {
|
|
10
|
+
if (descriptor) Object.defineProperty(globalThis, name, descriptor);
|
|
11
|
+
else delete globalThis[name];
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
};
|
|
15
|
+
}
|
package/src/gpu.js
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { globals } from './globals.js';
|
|
2
|
+
import { loadNative } from './native.js';
|
|
3
|
+
|
|
4
|
+
let runtime;
|
|
5
|
+
|
|
6
|
+
// Keep Dawn's instance alive independently of canvases and devices. It does not
|
|
7
|
+
// keep Node's event loop alive when no GPU operations are pending.
|
|
8
|
+
export function getRuntime() {
|
|
9
|
+
if (runtime) return runtime;
|
|
10
|
+
const installed = globals();
|
|
11
|
+
const loaded = loadNative();
|
|
12
|
+
try {
|
|
13
|
+
const gpu = loaded.native.create(['backend=vulkan']);
|
|
14
|
+
for (const [name, value] of Object.entries(loaded.native.globals)) {
|
|
15
|
+
if (name !== 'ImageBitmap') installed.set(name, value);
|
|
16
|
+
}
|
|
17
|
+
const navigator = globalThis.navigator ?? {};
|
|
18
|
+
Object.defineProperty(navigator, 'gpu', { value: gpu, configurable: true });
|
|
19
|
+
if (!globalThis.navigator) installed.set('navigator', navigator);
|
|
20
|
+
runtime = { gpu, native: loaded.native };
|
|
21
|
+
return runtime;
|
|
22
|
+
} catch (error) {
|
|
23
|
+
installed.restore();
|
|
24
|
+
loaded.restore();
|
|
25
|
+
throw error;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Select a native software adapter using standard GPURequestAdapterOptions. */
|
|
30
|
+
export async function requestAdapter(options) {
|
|
31
|
+
return getRuntime().gpu.requestAdapter(options);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Preferred canvas format of the active WebGPU implementation. */
|
|
35
|
+
export function getPreferredCanvasFormat() {
|
|
36
|
+
return getRuntime().gpu.getPreferredCanvasFormat();
|
|
37
|
+
}
|
package/src/host.js
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { globals } from './globals.js';
|
|
2
|
+
import { installImages } from './image.js';
|
|
3
|
+
import { installWorkers } from './worker.js';
|
|
4
|
+
|
|
5
|
+
let host;
|
|
6
|
+
let closing;
|
|
7
|
+
|
|
8
|
+
// Only canvases need loader and animation support; compute leaves it untouched.
|
|
9
|
+
export async function acquireHost(native) {
|
|
10
|
+
while (closing) await closing;
|
|
11
|
+
host ??= install(native);
|
|
12
|
+
const current = host;
|
|
13
|
+
current.users++;
|
|
14
|
+
let released = false;
|
|
15
|
+
return async () => {
|
|
16
|
+
if (released) return;
|
|
17
|
+
released = true;
|
|
18
|
+
if (--current.users) return;
|
|
19
|
+
host = undefined;
|
|
20
|
+
closing = current.close().finally(() => { closing = undefined; });
|
|
21
|
+
await closing;
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function install(native) {
|
|
26
|
+
const installed = globals();
|
|
27
|
+
const frames = new Set();
|
|
28
|
+
let restoreImages, restoreWorkers;
|
|
29
|
+
async function close() {
|
|
30
|
+
const failures = [];
|
|
31
|
+
for (const action of [
|
|
32
|
+
() => { for (const frame of frames) clearTimeout(frame); frames.clear(); },
|
|
33
|
+
() => restoreWorkers?.(),
|
|
34
|
+
() => restoreImages?.(),
|
|
35
|
+
() => installed.restore(),
|
|
36
|
+
]) {
|
|
37
|
+
try { await action(); } catch (error) { failures.push(error); }
|
|
38
|
+
}
|
|
39
|
+
if (failures.length) throw new AggregateError(failures, 'Canvas platform cleanup failed');
|
|
40
|
+
}
|
|
41
|
+
try {
|
|
42
|
+
installed.set('self', globalThis);
|
|
43
|
+
installed.set('ProgressEvent', class extends Event {
|
|
44
|
+
constructor(type, values = {}) { super(type); Object.assign(this, values); }
|
|
45
|
+
});
|
|
46
|
+
installed.set('requestAnimationFrame', callback => {
|
|
47
|
+
const frame = setTimeout(() => { frames.delete(frame); callback(performance.now()); });
|
|
48
|
+
frames.add(frame);
|
|
49
|
+
return frame;
|
|
50
|
+
});
|
|
51
|
+
installed.set('cancelAnimationFrame', frame => { clearTimeout(frame); frames.delete(frame); });
|
|
52
|
+
restoreImages = installImages(native);
|
|
53
|
+
restoreWorkers = installWorkers();
|
|
54
|
+
return { users: 0, close };
|
|
55
|
+
} catch (error) {
|
|
56
|
+
// Installation is synchronous; these restorations do not need worker teardown
|
|
57
|
+
// unless installWorkers completed, after which installation cannot fail.
|
|
58
|
+
restoreImages?.();
|
|
59
|
+
installed.restore();
|
|
60
|
+
throw error;
|
|
61
|
+
}
|
|
62
|
+
}
|
package/src/image.js
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
// Node image decoding for the platform boundary. Three's loaders remain untouched.
|
|
2
|
+
import { globals } from './globals.js';
|
|
3
|
+
|
|
4
|
+
let sharpPromise;
|
|
5
|
+
export function installImages(native) {
|
|
6
|
+
if (typeof native.createImageBitmapFromRGBA !== 'function') throw new Error('Native ImageBitmap bridge is unavailable');
|
|
7
|
+
const installed = globals();
|
|
8
|
+
let decoder, previousCache, closed = false;
|
|
9
|
+
const ImageBitmap = native.ImageBitmap ?? native.globals?.ImageBitmap;
|
|
10
|
+
if (!ImageBitmap) throw new Error('Native ImageBitmap constructor is unavailable');
|
|
11
|
+
async function createImageBitmap(source, options = {}) {
|
|
12
|
+
if (closed) throw new Error('Image decoder is disposed');
|
|
13
|
+
if (!(source instanceof Blob)) throw new TypeError('This Node image platform currently supports Blob input only');
|
|
14
|
+
if (arguments.length > 2) throw new TypeError('ImageBitmap cropping is not implemented');
|
|
15
|
+
const supported = new Set(['imageOrientation', 'premultiplyAlpha', 'colorSpaceConversion']);
|
|
16
|
+
for (const key of Object.keys(options)) if (!supported.has(key)) throw new TypeError(`Unsupported ImageBitmap option: ${key}`);
|
|
17
|
+
const orientation = options.imageOrientation ?? 'from-image';
|
|
18
|
+
const premultiply = options.premultiplyAlpha ?? 'default';
|
|
19
|
+
const conversion = options.colorSpaceConversion ?? 'default';
|
|
20
|
+
if (!['from-image', 'flipY', 'none'].includes(orientation)) throw new TypeError('Invalid imageOrientation');
|
|
21
|
+
if (!['none', 'premultiply', 'default'].includes(premultiply)) throw new TypeError('Invalid premultiplyAlpha');
|
|
22
|
+
if (!['none', 'default'].includes(conversion)) throw new TypeError('Invalid colorSpaceConversion');
|
|
23
|
+
sharpPromise ??= import('sharp').then(module => module.default);
|
|
24
|
+
const sharp = await sharpPromise;
|
|
25
|
+
if (closed) throw new Error('Image decoder is disposed');
|
|
26
|
+
if (!decoder) {
|
|
27
|
+
decoder = sharp;
|
|
28
|
+
const cache = sharp.cache();
|
|
29
|
+
previousCache = { memory: cache.memory.max, files: cache.files.max, items: cache.items.max };
|
|
30
|
+
sharp.cache(false);
|
|
31
|
+
}
|
|
32
|
+
let image = sharp(Buffer.from(await source.arrayBuffer()), { ignoreIcc: conversion === 'none' });
|
|
33
|
+
if (orientation !== 'none') image = image.autoOrient();
|
|
34
|
+
if (orientation === 'flipY') image = image.flip();
|
|
35
|
+
if (conversion === 'default') image = image.toColourspace('srgb');
|
|
36
|
+
const { data, info } = await image.ensureAlpha().raw().toBuffer({ resolveWithObject: true });
|
|
37
|
+
if (closed) throw new Error('Image decoder is disposed');
|
|
38
|
+
const premultipliedAlpha = premultiply === 'premultiply';
|
|
39
|
+
if (premultipliedAlpha) for (let i = 0; i < data.length; i += 4) {
|
|
40
|
+
data[i] = Math.round(data[i] * data[i + 3] / 255);
|
|
41
|
+
data[i + 1] = Math.round(data[i + 1] * data[i + 3] / 255);
|
|
42
|
+
data[i + 2] = Math.round(data[i + 2] * data[i + 3] / 255);
|
|
43
|
+
}
|
|
44
|
+
// The native object owns a copy; its lifetime is independent of Sharp/JS buffers.
|
|
45
|
+
return native.createImageBitmapFromRGBA(info.width, info.height, data, { premultipliedAlpha, colorSpace: 'srgb' });
|
|
46
|
+
}
|
|
47
|
+
try {
|
|
48
|
+
installed.set('createImageBitmap', createImageBitmap);
|
|
49
|
+
installed.set('ImageBitmap', ImageBitmap);
|
|
50
|
+
} catch (error) {
|
|
51
|
+
installed.restore();
|
|
52
|
+
throw error;
|
|
53
|
+
}
|
|
54
|
+
return () => {
|
|
55
|
+
closed = true;
|
|
56
|
+
installed.restore();
|
|
57
|
+
if (decoder) decoder.cache(previousCache);
|
|
58
|
+
};
|
|
59
|
+
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { canvas } from './canvas.js';
|
|
2
|
+
import { getRuntime } from './gpu.js';
|
|
3
|
+
|
|
4
|
+
export { requestAdapter, getPreferredCanvasFormat } from './gpu.js';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Create a headless WebGPU canvas. CSS style assignments are inert in Node;
|
|
8
|
+
* width/height control output resolution. The offscreen option is browser-only
|
|
9
|
+
* selection: every Node canvas is already headless.
|
|
10
|
+
* readPixels() returns straight-alpha RGBA8. Dispose renderer/loaders before the
|
|
11
|
+
* canvas. Canvas disposal never destroys an application-owned GPUDevice.
|
|
12
|
+
*/
|
|
13
|
+
export async function createCanvas(width, height, { offscreen = false } = {}) {
|
|
14
|
+
if (typeof offscreen !== 'boolean') throw new TypeError('offscreen must be a boolean');
|
|
15
|
+
let disposal;
|
|
16
|
+
const target = canvas(width, height, () => {
|
|
17
|
+
if (disposal) throw new Error('Canvas is disposed');
|
|
18
|
+
});
|
|
19
|
+
const { native } = getRuntime();
|
|
20
|
+
const { acquireHost } = await import('./host.js');
|
|
21
|
+
const release = await acquireHost(native);
|
|
22
|
+
target.output.dispose = () => disposal ??= (async () => {
|
|
23
|
+
const failures = [];
|
|
24
|
+
for (const action of [() => target.close(), release]) {
|
|
25
|
+
try { await action(); } catch (error) { failures.push(error); }
|
|
26
|
+
}
|
|
27
|
+
if (failures.length) throw new AggregateError(failures, 'Canvas cleanup failed');
|
|
28
|
+
})();
|
|
29
|
+
return target.output;
|
|
30
|
+
}
|
package/src/native.js
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { createRequire } from 'node:module';
|
|
2
|
+
import { existsSync } from 'node:fs';
|
|
3
|
+
import { dirname, join, resolve } from 'node:path';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
import { nativeTarget } from './platform.js';
|
|
6
|
+
|
|
7
|
+
const require = createRequire(import.meta.url);
|
|
8
|
+
|
|
9
|
+
function directory() {
|
|
10
|
+
if (process.env.DRAWCALL_WEBGPU_NATIVE) return resolve(process.env.DRAWCALL_WEBGPU_NATIVE);
|
|
11
|
+
const target = nativeTarget();
|
|
12
|
+
const local = fileURLToPath(new URL(`../dist/${target}/`, import.meta.url));
|
|
13
|
+
if (existsSync(join(local, 'dawn.node'))) return local;
|
|
14
|
+
try {
|
|
15
|
+
return dirname(require.resolve(`@drawcall/webgpu-${target}/package.json`));
|
|
16
|
+
} catch (cause) {
|
|
17
|
+
if (cause.code !== 'MODULE_NOT_FOUND') throw cause;
|
|
18
|
+
throw new Error(`Install @drawcall/webgpu-${target}; npm optional dependencies must be enabled`, { cause });
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function loadNative() {
|
|
23
|
+
const dir = directory();
|
|
24
|
+
const settings = {
|
|
25
|
+
LP_NUM_THREADS: '2',
|
|
26
|
+
// Cold processes cannot benefit from cross-render shader reuse. Disabling the
|
|
27
|
+
// disk cache also avoids the cached vertex-object corruption seen in Mesa 26.
|
|
28
|
+
MESA_SHADER_CACHE_DISABLE: 'true',
|
|
29
|
+
};
|
|
30
|
+
const previous = new Map(Object.keys(settings).map(key => [key, process.env[key]]));
|
|
31
|
+
const restore = () => {
|
|
32
|
+
for (const [key, value] of previous) {
|
|
33
|
+
if (value === undefined) delete process.env[key];
|
|
34
|
+
else process.env[key] = value;
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
Object.assign(process.env, settings);
|
|
38
|
+
try {
|
|
39
|
+
const native = require(join(dir, 'dawn.node'));
|
|
40
|
+
if (typeof native.createImageBitmapFromRGBA !== 'function') {
|
|
41
|
+
throw new Error('The native binding lacks ImageBitmap support; use the @drawcall/webgpu native build');
|
|
42
|
+
}
|
|
43
|
+
return { native, restore };
|
|
44
|
+
} catch (error) {
|
|
45
|
+
restore();
|
|
46
|
+
if (error.code === 'ERR_DLOPEN_FAILED') {
|
|
47
|
+
throw Object.assign(new Error(`Cannot load @drawcall/webgpu for ${process.platform}-${process.arch} on Node.js ${process.version}: ${error.message}`, { cause: error }), { code: error.code });
|
|
48
|
+
}
|
|
49
|
+
throw error;
|
|
50
|
+
}
|
|
51
|
+
}
|
package/src/platform.js
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { familySync } from 'detect-libc';
|
|
2
|
+
|
|
3
|
+
export function nativeTarget(platform = process.platform, arch = process.arch, libc = platform === 'linux' ? familySync() : null) {
|
|
4
|
+
if (!['linux', 'darwin', 'win32'].includes(platform) || !['x64', 'arm64'].includes(arch)) {
|
|
5
|
+
throw new Error(`@drawcall/webgpu has no native package for ${platform}-${arch}`);
|
|
6
|
+
}
|
|
7
|
+
if (platform !== 'linux') return `${platform}-${arch}`;
|
|
8
|
+
if (libc === 'glibc') return `linux-${arch}`;
|
|
9
|
+
if (libc === 'musl') return `linuxmusl-${arch}`;
|
|
10
|
+
throw new Error(`@drawcall/webgpu cannot select a Linux native package: unrecognized libc ${libc}`);
|
|
11
|
+
}
|
package/src/worker.js
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { Worker as Thread, isMainThread, parentPort, workerData } from 'node:worker_threads';
|
|
2
|
+
import { resolveObjectURL } from 'node:buffer';
|
|
3
|
+
import { readFile } from 'node:fs/promises';
|
|
4
|
+
import { runInNewContext } from 'node:vm';
|
|
5
|
+
|
|
6
|
+
const workers = new Set();
|
|
7
|
+
const stopping = new Set();
|
|
8
|
+
|
|
9
|
+
function errorEvent(error) {
|
|
10
|
+
const event = new Event('error', { cancelable: true });
|
|
11
|
+
Object.assign(event, { error, message: error.message, filename: '', lineno: 0, colno: 0 });
|
|
12
|
+
return event;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
// Classic workers only. Blob URLs are captured in the creating thread before revocation.
|
|
16
|
+
export class Worker extends EventTarget {
|
|
17
|
+
onmessage = null;
|
|
18
|
+
onmessageerror = null;
|
|
19
|
+
onerror = null;
|
|
20
|
+
#thread;
|
|
21
|
+
#stopped = false;
|
|
22
|
+
constructor(url, { type = 'classic', name = '', credentials = 'same-origin' } = {}) {
|
|
23
|
+
super();
|
|
24
|
+
if (type !== 'classic') throw new TypeError('This Worker host supports classic workers only');
|
|
25
|
+
if (credentials !== 'same-origin') throw new TypeError('Worker credentials are not implemented');
|
|
26
|
+
const location = new URL(String(url));
|
|
27
|
+
const blob = location.protocol === 'blob:' ? resolveObjectURL(location.href) : undefined;
|
|
28
|
+
if (location.protocol === 'blob:' && !blob) throw new DOMException('Unknown Blob URL', 'NetworkError');
|
|
29
|
+
if (!['blob:', 'data:', 'file:', 'http:', 'https:'].includes(location.protocol)) throw new TypeError('Unsupported Worker URL protocol');
|
|
30
|
+
// Classic workers do not inherit Node CLI flags such as --input-type.
|
|
31
|
+
this.#thread = new Thread(new URL(import.meta.url), { execArgv: [], workerData: { workerHost: true, blob, url: location.href, name } });
|
|
32
|
+
workers.add(this);
|
|
33
|
+
for (const type of ['message', 'messageerror', 'error']) {
|
|
34
|
+
this.addEventListener(type, event => {
|
|
35
|
+
if (this['on' + type]?.call(this, event) === true && type === 'error') event.preventDefault();
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
this.#thread.on('message', data => this.dispatchEvent(new MessageEvent('message', { data })));
|
|
39
|
+
this.#thread.on('messageerror', error => this.dispatchEvent(new MessageEvent('messageerror', { data: error })));
|
|
40
|
+
this.#thread.on('error', error => {
|
|
41
|
+
// An unhandled decoder failure must stop a pending loader, not hang it.
|
|
42
|
+
if (this.dispatchEvent(errorEvent(error))) throw error;
|
|
43
|
+
});
|
|
44
|
+
this.#thread.on('exit', () => workers.delete(this));
|
|
45
|
+
}
|
|
46
|
+
postMessage(message, options = []) {
|
|
47
|
+
if (this.#stopped) return;
|
|
48
|
+
this.#thread.postMessage(message, Array.isArray(options) ? options : options.transfer);
|
|
49
|
+
}
|
|
50
|
+
terminate() {
|
|
51
|
+
if (this.#stopped) return;
|
|
52
|
+
this.#stopped = true;
|
|
53
|
+
const pending = this.#thread.terminate();
|
|
54
|
+
stopping.add(pending);
|
|
55
|
+
pending.then(() => stopping.delete(pending), error => { stopping.delete(pending); throw error; });
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function installWorkers() {
|
|
60
|
+
const previous = Object.getOwnPropertyDescriptor(globalThis, 'Worker');
|
|
61
|
+
Object.defineProperty(globalThis, 'Worker', { value: Worker, configurable: true, writable: true });
|
|
62
|
+
return async () => {
|
|
63
|
+
try {
|
|
64
|
+
for (const worker of workers) worker.terminate();
|
|
65
|
+
await Promise.all(stopping);
|
|
66
|
+
} finally {
|
|
67
|
+
if (previous) Object.defineProperty(globalThis, 'Worker', previous);
|
|
68
|
+
else delete globalThis.Worker;
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
if (!isMainThread && workerData?.workerHost) {
|
|
74
|
+
const { blob, url, name } = workerData;
|
|
75
|
+
const events = new EventTarget();
|
|
76
|
+
const scope = {
|
|
77
|
+
name, location: new URL(url), onmessage: null, onmessageerror: null, onerror: null,
|
|
78
|
+
console, performance, crypto, fetch, URL, URLSearchParams, Blob, TextEncoder, TextDecoder,
|
|
79
|
+
Event, EventTarget, MessageEvent, DOMException, WebAssembly, atob, btoa,
|
|
80
|
+
setTimeout, clearTimeout, setInterval, clearInterval, queueMicrotask,
|
|
81
|
+
postMessage: (data, options = []) => parentPort.postMessage(data, Array.isArray(options) ? options : options.transfer),
|
|
82
|
+
close: () => parentPort.close(),
|
|
83
|
+
addEventListener: events.addEventListener.bind(events),
|
|
84
|
+
removeEventListener: events.removeEventListener.bind(events),
|
|
85
|
+
dispatchEvent: events.dispatchEvent.bind(events),
|
|
86
|
+
importScripts: () => { throw new Error('Synchronous importScripts is not implemented'); },
|
|
87
|
+
};
|
|
88
|
+
scope.self = scope;
|
|
89
|
+
const source = blob ? await blob.text() : url.startsWith('file:') ? await readFile(new URL(url), 'utf8') : await fetch(url).then(response => {
|
|
90
|
+
if (!response.ok) throw new Error('Worker script HTTP ' + response.status);
|
|
91
|
+
return response.text();
|
|
92
|
+
});
|
|
93
|
+
runInNewContext(source, scope, { filename: url });
|
|
94
|
+
parentPort.on('message', data => {
|
|
95
|
+
const event = new MessageEvent('message', { data });
|
|
96
|
+
scope.onmessage?.call(scope, event);
|
|
97
|
+
events.dispatchEvent(event);
|
|
98
|
+
});
|
|
99
|
+
}
|