@null3d/vite-plugin 0.0.0-stage → 0.0.0

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.
Files changed (50) hide show
  1. package/LICENSE-APACHE +176 -0
  2. package/LICENSE-MIT +21 -0
  3. package/THIRD-PARTY-NOTICES.txt +398 -0
  4. package/dist/shader-compiler.stamp.json +4 -0
  5. package/dist/shader-compiler.wasm +0 -0
  6. package/lib/assets.d.ts +94 -0
  7. package/lib/assets.js +189 -0
  8. package/lib/client.d.ts +21 -0
  9. package/lib/compile-pool.d.ts +25 -0
  10. package/lib/compile-pool.js +90 -0
  11. package/lib/compile-worker.js +11 -0
  12. package/lib/compiler-calls.d.ts +26 -0
  13. package/lib/compiler-calls.js +97 -0
  14. package/lib/compiler-stamp.d.ts +8 -0
  15. package/lib/compiler-stamp.js +34 -0
  16. package/lib/declarations.d.ts +10 -0
  17. package/lib/declarations.js +80 -0
  18. package/lib/engine-shaders-local.d.ts +6 -0
  19. package/lib/engine-shaders-local.js +75 -0
  20. package/lib/engine-shaders.d.ts +61 -0
  21. package/lib/engine-shaders.js +170 -0
  22. package/lib/hash-pool.d.ts +24 -0
  23. package/lib/hash-pool.js +84 -0
  24. package/lib/hash-worker.js +53 -0
  25. package/lib/hot.d.ts +53 -0
  26. package/lib/hot.js +101 -0
  27. package/lib/index.d.ts +95 -0
  28. package/lib/index.js +895 -0
  29. package/lib/material-builds.d.ts +91 -0
  30. package/lib/material-builds.js +236 -0
  31. package/lib/offline.d.ts +92 -0
  32. package/lib/offline.js +304 -0
  33. package/lib/pack.d.ts +30 -0
  34. package/lib/pack.js +112 -0
  35. package/lib/package-files.d.ts +12 -0
  36. package/lib/package-files.js +39 -0
  37. package/lib/paragraphs.d.ts +19 -0
  38. package/lib/paragraphs.js +131 -0
  39. package/lib/shader-cache.d.ts +59 -0
  40. package/lib/shader-cache.js +213 -0
  41. package/lib/shader-compiler.d.ts +258 -0
  42. package/lib/shader-compiler.js +169 -0
  43. package/lib/shader-types.d.ts +261 -0
  44. package/lib/shader-types.js +4 -0
  45. package/lib/wgsl.d.ts +118 -0
  46. package/lib/wgsl.js +446 -0
  47. package/lib/worker-preload.d.ts +17 -0
  48. package/lib/worker-preload.js +65 -0
  49. package/package.json +69 -5
  50. package/README.md +0 -3
@@ -0,0 +1,94 @@
1
+ /** Options of the asset tool, as `assets optimize` takes them. */
2
+ export interface AssetOptions {
3
+ /** Add levels of detail to meshes of 64 triangles or more. The default is false. */
4
+ lod?: boolean;
5
+ /**
6
+ * Write each mesh's levels of detail as separate files beside the model, so the engine draws the
7
+ * coarsest level at once and takes each finer one as it arrives. It needs `lod`. The default is
8
+ * false.
9
+ */
10
+ stages?: boolean;
11
+ /**
12
+ * Add a tree of cluster patches to each large static mesh of 20,000 triangles or more. The
13
+ * default is false.
14
+ */
15
+ clusters?: boolean;
16
+ /**
17
+ * Keep this share of each mesh's triangles, above 0 and up to 1, as far as `simplifyError`
18
+ * allows. The default, 1, keeps them all.
19
+ */
20
+ simplify?: number;
21
+ /**
22
+ * The most that `simplify` may move a mesh's surface, as a share of the mesh's size. The
23
+ * default is 0.01.
24
+ */
25
+ simplifyError?: number;
26
+ /** The largest side of a texture: a power of two up to 2048, the default. */
27
+ maxTextureSize?: number;
28
+ /** `size` encodes color and data maps in ETC1S, the default; `high` in UASTC. */
29
+ textureQuality?: 'size' | 'high';
30
+ /**
31
+ * Add the detail of each material's normal map to the roughness levels of its metal-rough map,
32
+ * which then takes UASTC, so distant bumpy surfaces do not flicker. The default is true.
33
+ */
34
+ roughnessBake?: boolean;
35
+ /** Compress the model's buffers with meshopt, which the engine decodes on load. Default: true. */
36
+ meshopt?: boolean;
37
+ /**
38
+ * Give each mesh that encloses space a blocker for software occlusion culling
39
+ * (`NULL3D_occluder`). The default is true.
40
+ */
41
+ blockers?: boolean;
42
+ /**
43
+ * Store the tree that raycasts walk for each mesh part of at least this many triangles
44
+ * (`NULL3D_mesh_bvh`), or for none with 0. The default is 20,000.
45
+ */
46
+ bvh?: number;
47
+ }
48
+ /** The query that asks for an optimized model. */
49
+ export declare const OPTIMIZED_QUERY = "optimized";
50
+ /** An import of an optimized model: a `.glb` or `.gltf` file with the query. */
51
+ export declare const OPTIMIZED_MODEL: RegExp;
52
+ /** The address prefix and folder name of the optimized files, in the dev server and in a build. */
53
+ export declare const ASSET_FOLDER = "null3d-assets";
54
+ /** An optimized model in the cache: its folder's key and its file's name. */
55
+ export interface CachedModel {
56
+ key: string;
57
+ name: string;
58
+ /** The model file, and the texture files it names, by their paths from the cache's folder. */
59
+ files: string[];
60
+ }
61
+ /** The cache's folder in a project. */
62
+ export declare const cacheFolder: (root: string) => string;
63
+ /**
64
+ * The cache key of a model: the hash of the tool's identity, the options, and each file of the
65
+ * model, its own and those it names.
66
+ */
67
+ export declare function modelKey(identity: string, options: object, files: readonly string[]): string;
68
+ /**
69
+ * What the asset tool is: the version it reports and a hash of its own code, which is the module the
70
+ * plugin loads and the files that share its name, the WebAssembly file among them. The version alone
71
+ * is not enough, because it stays `0.0.0` in the repository: a fix to the tool can change what a
72
+ * model encodes to without changing the key, and the cache would keep serving models that the tool
73
+ * wrote before the fix (code review H-17). A tool whose files cannot be read falls back to the
74
+ * version it reports.
75
+ */
76
+ export declare function toolIdentity(version: string): string;
77
+ /**
78
+ * A hash of the module at `path` and of the files that share its name, a WebAssembly file among
79
+ * them, or null when they cannot be read. A tool's own file names its siblings, so one name covers
80
+ * the JavaScript that drives it and the module it runs.
81
+ */
82
+ export declare function fileCodeHash(path: string): string | null;
83
+ /**
84
+ * Optimizes a model into the cache unless the cache has it, and returns where it is. The model's
85
+ * folder appears whole or not at all, so a stopped run leaves nothing half written.
86
+ */
87
+ export declare function optimizedModel(root: string, path: string, options?: AssetOptions): Promise<CachedModel>;
88
+ /** The media type of an optimized file. */
89
+ export declare function assetType(file: string): string;
90
+ /**
91
+ * A cached file of a project by its path from the cache, such as `textures/<name>.ktx2`, for the
92
+ * dev server. A path of any other shape, which could reach outside the cache, gives nothing.
93
+ */
94
+ export declare function cachedFile(root: string, path: string): Uint8Array | undefined;
package/lib/assets.js ADDED
@@ -0,0 +1,189 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
9
+ // glTF models that a project imports with `?optimized`: the plugin runs the asset tool of
10
+ // `@null3d/cli` on them, the steps of `bunx @null3d/cli assets optimize`, and the import gives the
11
+ // optimized model's address. Results stay in a cache, keyed by the model's files, the tool's
12
+ // version and the options, so each model encodes once until one of them changes. The dev server
13
+ // serves the cache, and a build writes the files into its assets folder.
14
+ import { createHash } from 'node:crypto';
15
+ import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync, } from 'node:fs';
16
+ import { createRequire } from 'node:module';
17
+ import { basename, dirname, extname, join } from 'node:path';
18
+ /** The query that asks for an optimized model. */
19
+ export const OPTIMIZED_QUERY = 'optimized';
20
+ /** An import of an optimized model: a `.glb` or `.gltf` file with the query. */
21
+ export const OPTIMIZED_MODEL = /\.(glb|gltf)\?optimized$/;
22
+ /** The address prefix and folder name of the optimized files, in the dev server and in a build. */
23
+ export const ASSET_FOLDER = 'null3d-assets';
24
+ /** The folder of the texture files, which every model shares. */
25
+ const TEXTURES = 'textures';
26
+ /** The asset tool, loaded on the first optimized import. */
27
+ let tool;
28
+ /** The CLI's asset module, which stays out of projects that import no optimized model. */
29
+ const TOOL_MODULE = '@null3d/cli/assets';
30
+ function loadTool() {
31
+ tool ??= import(__rewriteRelativeImportExtension(/* @vite-ignore */ TOOL_MODULE)).catch(() => {
32
+ tool = undefined;
33
+ throw new Error('null3D optimizes models with the asset tool of @null3d/cli, which the project does not install. Add it with bun add -d @null3d/cli.');
34
+ });
35
+ return tool;
36
+ }
37
+ /** The cache's folder in a project. */
38
+ export const cacheFolder = (root) => join(root, 'node_modules/.cache', ASSET_FOLDER);
39
+ /**
40
+ * The cache key of a model: the hash of the tool's identity, the options, and each file of the
41
+ * model, its own and those it names.
42
+ */
43
+ export function modelKey(identity, options, files) {
44
+ const hash = createHash('sha256').update(`${identity}\n${JSON.stringify(options)}\n`);
45
+ for (const file of files)
46
+ hash.update(readFileSync(file));
47
+ return hash.digest('hex').slice(0, 16);
48
+ }
49
+ /**
50
+ * What the asset tool is: the version it reports and a hash of its own code, which is the module the
51
+ * plugin loads and the files that share its name, the WebAssembly file among them. The version alone
52
+ * is not enough, because it stays `0.0.0` in the repository: a fix to the tool can change what a
53
+ * model encodes to without changing the key, and the cache would keep serving models that the tool
54
+ * wrote before the fix (code review H-17). A tool whose files cannot be read falls back to the
55
+ * version it reports.
56
+ */
57
+ export function toolIdentity(version) {
58
+ try {
59
+ const module = createRequire(import.meta.url).resolve(TOOL_MODULE);
60
+ const code = fileCodeHash(module);
61
+ return code === null ? version : `${version}+${code}`;
62
+ }
63
+ catch {
64
+ return version;
65
+ }
66
+ }
67
+ /**
68
+ * A hash of the module at `path` and of the files that share its name, a WebAssembly file among
69
+ * them, or null when they cannot be read. A tool's own file names its siblings, so one name covers
70
+ * the JavaScript that drives it and the module it runs.
71
+ */
72
+ export function fileCodeHash(path) {
73
+ try {
74
+ const folder = dirname(path);
75
+ const stem = basename(path, extname(path));
76
+ const names = readdirSync(folder)
77
+ .filter((name) => basename(name, extname(name)) === stem)
78
+ .sort();
79
+ // A module that is not there has no code to hash, so the caller falls back rather than keying
80
+ // every model by the same empty hash.
81
+ if (!names.includes(basename(path)))
82
+ return null;
83
+ const hash = createHash('sha256');
84
+ for (const name of names)
85
+ hash.update(readFileSync(join(folder, name)));
86
+ return hash.digest('hex').slice(0, 16);
87
+ }
88
+ catch {
89
+ return null;
90
+ }
91
+ }
92
+ /** A stage file's name: a plain file name beside the model, as the tool writes it. */
93
+ const STAGE_FILE = /^[\w.-]+\.bin$/;
94
+ /**
95
+ * The stage files that a model names, by their file names beside it: the files of the levels and
96
+ * the bands that download after it, from `NULL3D_stages` in each node's extras.
97
+ */
98
+ function stagesOf(glb) {
99
+ const view = new DataView(glb.buffer, glb.byteOffset, glb.byteLength);
100
+ const json = JSON.parse(new TextDecoder().decode(glb.subarray(20, 20 + view.getUint32(12, true))));
101
+ const out = [];
102
+ for (const node of json.nodes ?? []) {
103
+ const staged = node.extras?.NULL3D_stages;
104
+ for (const stage of [...(staged?.levels ?? []), ...(staged?.bands ?? [])])
105
+ if (typeof stage.url === 'string' && STAGE_FILE.test(stage.url))
106
+ out.push(stage.url);
107
+ }
108
+ return out;
109
+ }
110
+ /** The textures that a model file names, by their file names. */
111
+ function texturesOf(glb) {
112
+ const view = new DataView(glb.buffer, glb.byteOffset, glb.byteLength);
113
+ const json = JSON.parse(new TextDecoder().decode(glb.subarray(20, 20 + view.getUint32(12, true))));
114
+ return (json.images ?? [])
115
+ .map((image) => image.uri)
116
+ .filter((uri) => typeof uri === 'string' && uri.startsWith(`../${TEXTURES}/`))
117
+ .map((uri) => uri.slice(`../${TEXTURES}/`.length));
118
+ }
119
+ /** Models that are optimizing now, by key, so two imports of one model optimize it once. */
120
+ const running = new Map();
121
+ /**
122
+ * Optimizes a model into the cache unless the cache has it, and returns where it is. The model's
123
+ * folder appears whole or not at all, so a stopped run leaves nothing half written.
124
+ */
125
+ export async function optimizedModel(root, path, options = {}) {
126
+ const asset = await loadTool();
127
+ const settings = { ...asset.DEFAULT_OPTIONS, ...options };
128
+ const sources = [path, ...asset.namedFiles(path)];
129
+ const key = modelKey(toolIdentity(asset.VERSION), settings, sources);
130
+ const name = `${basename(path, extname(path))}.glb`;
131
+ const cache = cacheFolder(root);
132
+ const folder = join(cache, key);
133
+ const listed = (glb) => ({
134
+ key,
135
+ name,
136
+ files: [
137
+ `${key}/${name}`,
138
+ ...stagesOf(glb).map((file) => `${key}/${file}`),
139
+ ...texturesOf(glb).map((file) => `${TEXTURES}/${file}`),
140
+ ],
141
+ });
142
+ if (existsSync(join(folder, name)))
143
+ return listed(readFileSync(join(folder, name)));
144
+ const pending = running.get(key);
145
+ if (pending)
146
+ return pending;
147
+ const work = (async () => {
148
+ const pool = asset.encoderPool(asset.defaultJobs());
149
+ try {
150
+ const model = await asset.optimizeModel(path, { ...settings, textureFolder: `../${TEXTURES}` }, asset.encodeOnce((job) => pool.encode(job)));
151
+ mkdirSync(join(cache, TEXTURES), { recursive: true });
152
+ for (const [file, bytes] of model.files)
153
+ writeFileSync(join(cache, TEXTURES, file), bytes);
154
+ const staging = join(cache, `.${key}-${process.pid}`);
155
+ rmSync(staging, { recursive: true, force: true });
156
+ mkdirSync(staging, { recursive: true });
157
+ writeFileSync(join(staging, name), model.glb);
158
+ // A tool older than this plugin writes no stage, and its answer holds no such list.
159
+ for (const [file, bytes] of model.stages ?? [])
160
+ writeFileSync(join(staging, file), bytes);
161
+ rmSync(folder, { recursive: true, force: true });
162
+ renameSync(staging, folder);
163
+ return listed(model.glb);
164
+ }
165
+ finally {
166
+ await pool.close();
167
+ running.delete(key);
168
+ }
169
+ })();
170
+ running.set(key, work);
171
+ return work;
172
+ }
173
+ /** The media type of an optimized file. */
174
+ export function assetType(file) {
175
+ if (file.endsWith('.ktx2'))
176
+ return 'image/ktx2';
177
+ return file.endsWith('.bin') ? 'application/octet-stream' : 'model/gltf-binary';
178
+ }
179
+ /**
180
+ * A cached file of a project by its path from the cache, such as `textures/<name>.ktx2`, for the
181
+ * dev server. A path of any other shape, which could reach outside the cache, gives nothing.
182
+ */
183
+ export function cachedFile(root, path) {
184
+ const parts = path.split('/');
185
+ if (parts.length !== 2 || parts.some((part) => !/^[\w-][\w.-]*$/.test(part)))
186
+ return undefined;
187
+ const file = join(cacheFolder(root), ...parts);
188
+ return existsSync(file) ? readFileSync(file) : undefined;
189
+ }
@@ -0,0 +1,21 @@
1
+ // Types for the modules that the null3D Vite plugin makes. A project adds them with
2
+ // `/// <reference types="@null3d/vite-plugin/client" />`, or with `@null3d/vite-plugin/client` in
3
+ // the `types` of its tsconfig.json.
4
+
5
+ declare module '*.wgsl' {
6
+ /** The WGSL file, compiled for WebGPU and WebGL2: a whole shader, a custom material, a custom effect, a custom tone curve or a sky layer. */
7
+ const shader: import('./shader-types.js').CompiledWgsl;
8
+ export default shader;
9
+ }
10
+
11
+ declare module '*.glb?optimized' {
12
+ /** The address of the model after the asset tool optimized it, for `assets.loadGltf`. */
13
+ const url: string;
14
+ export default url;
15
+ }
16
+
17
+ declare module '*.gltf?optimized' {
18
+ /** The address of the model after the asset tool optimized it, as one `.glb` file. */
19
+ const url: string;
20
+ export default url;
21
+ }
@@ -0,0 +1,25 @@
1
+ import { type CompileResult, type EffectResult, type MaterialResult, type MaterialSource, type ShaderCompiler, type ShaderSource, type SkyLayerResult } from './shader-compiler.js';
2
+ /** The workers of a pool by default: one for each core but one, at most `MOST_WORKERS`. */
3
+ export declare function defaultWorkers(): number;
4
+ /**
5
+ * Compiles on worker threads, which start at the first compile. An idle worker does not keep the
6
+ * process alive, so a build ends without `close`.
7
+ */
8
+ export declare class CompilerPool implements ShaderCompiler {
9
+ /** The most workers that run at once, and the shares that a custom material splits into. */
10
+ readonly size: number;
11
+ private readonly workers;
12
+ private nextId;
13
+ constructor(size?: number);
14
+ shader(shader: ShaderSource): Promise<CompileResult>;
15
+ material(material: MaterialSource): Promise<MaterialResult>;
16
+ /** Compiles a custom effect or tone curve, whose few builds take one worker. */
17
+ effect(effect: MaterialSource): Promise<EffectResult>;
18
+ /** Compiles a sky layer, whose few builds take one worker. */
19
+ skyLayer(layer: MaterialSource): Promise<SkyLayerResult>;
20
+ /** Stops every worker. A later compile starts them again. */
21
+ close(): Promise<void>;
22
+ /** Runs a call on the worker with the fewest calls waiting, or on a new one while there is room. */
23
+ private run;
24
+ private start;
25
+ }
@@ -0,0 +1,90 @@
1
+ // The shader compiler on worker threads. A compile takes the CPU for most of a second, and Node
2
+ // answers no request while it runs on Node's own thread: on the dev server, a page then waits for
3
+ // every file, the engine's worker probe among them. The pool runs each compile on a worker thread
4
+ // instead. It splits a custom material's builds into one share for each worker, so the material
5
+ // compiles in a fraction of the time, and joins the shares' results.
6
+ import { availableParallelism } from 'node:os';
7
+ import { Worker } from 'node:worker_threads';
8
+ import { compilerModule, effectResult, joinShares, materialResult, shaderResult, skyLayerResult, } from "./shader-compiler.js";
9
+ /**
10
+ * The most workers a pool starts. Each holds about 20 MB, and a custom material's compile takes
11
+ * about 270 ms with 8 against 525 ms with 4 on a busy 18-core Mac; more gain less for their memory.
12
+ */
13
+ const MOST_WORKERS = 8;
14
+ /** The workers of a pool by default: one for each core but one, at most `MOST_WORKERS`. */
15
+ export function defaultWorkers() {
16
+ return Math.max(1, Math.min(MOST_WORKERS, availableParallelism() - 1));
17
+ }
18
+ /**
19
+ * Compiles on worker threads, which start at the first compile. An idle worker does not keep the
20
+ * process alive, so a build ends without `close`.
21
+ */
22
+ export class CompilerPool {
23
+ /** The most workers that run at once, and the shares that a custom material splits into. */
24
+ size;
25
+ workers = [];
26
+ nextId = 0;
27
+ constructor(size = defaultWorkers()) {
28
+ this.size = size;
29
+ }
30
+ async shader(shader) {
31
+ return shaderResult(await this.run('compile', shader));
32
+ }
33
+ async material(material) {
34
+ const count = this.size;
35
+ if (count === 1)
36
+ return materialResult(await this.run('compile_material', material));
37
+ const shares = Array.from({ length: count }, (_, index) => this.run('compile_material', { ...material, share: { index, count } }));
38
+ return joinShares((await Promise.all(shares)).map(materialResult));
39
+ }
40
+ /** Compiles a custom effect or tone curve, whose few builds take one worker. */
41
+ async effect(effect) {
42
+ return effectResult(await this.run('compile_effect', effect));
43
+ }
44
+ /** Compiles a sky layer, whose few builds take one worker. */
45
+ async skyLayer(layer) {
46
+ return skyLayerResult(await this.run('compile_sky_layer', layer));
47
+ }
48
+ /** Stops every worker. A later compile starts them again. */
49
+ async close() {
50
+ const workers = this.workers.splice(0);
51
+ await Promise.all(workers.map((worker) => worker.thread.terminate()));
52
+ }
53
+ /** Runs a call on the worker with the fewest calls waiting, or on a new one while there is room. */
54
+ run(name, request) {
55
+ let worker = this.workers.reduce((best, next) => (!best || next.waiting.size < best.waiting.size ? next : best), undefined);
56
+ if (!worker || (worker.waiting.size > 0 && this.workers.length < this.size))
57
+ worker = this.start();
58
+ const id = this.nextId++;
59
+ const { thread, waiting } = worker;
60
+ const answer = new Promise((resolve, reject) => waiting.set(id, { resolve, reject }));
61
+ thread.ref();
62
+ thread.postMessage({ id, name, request: JSON.stringify(request) });
63
+ return answer.then((response) => JSON.parse(response));
64
+ }
65
+ start() {
66
+ const thread = new Worker(new URL('./compile-worker.js', import.meta.url), {
67
+ workerData: { module: compilerModule() },
68
+ });
69
+ const worker = { thread, waiting: new Map() };
70
+ thread.on('message', ({ id, response }) => {
71
+ worker.waiting.get(id)?.resolve(response);
72
+ worker.waiting.delete(id);
73
+ if (worker.waiting.size === 0)
74
+ thread.unref();
75
+ });
76
+ const fail = (error) => {
77
+ const index = this.workers.indexOf(worker);
78
+ if (index >= 0)
79
+ this.workers.splice(index, 1);
80
+ for (const call of worker.waiting.values())
81
+ call.reject(error);
82
+ worker.waiting.clear();
83
+ };
84
+ thread.on('error', (error) => fail(new Error(`null3D: a shader compiler thread stopped: ${error.message}`)));
85
+ thread.on('exit', (code) => fail(new Error(`null3D: a shader compiler thread exited with code ${code}`)));
86
+ thread.unref();
87
+ this.workers.push(worker);
88
+ return worker;
89
+ }
90
+ }
@@ -0,0 +1,11 @@
1
+ // A worker thread of the shader compiler pool. It runs the shader compiler on the requests that
2
+ // the pool sends, so the dev server and the build go on while a shader compiles. The pool hands
3
+ // over the compiled module, so no worker reads or compiles the file again.
4
+ import { parentPort, workerData } from 'node:worker_threads';
5
+ import { CompilerCalls } from './compiler-calls.js';
6
+
7
+ const calls = new CompilerCalls(workerData.module);
8
+
9
+ parentPort?.on('message', ({ id, name, request }) => {
10
+ parentPort?.postMessage({ id, response: calls.call(name, request) });
11
+ });
@@ -0,0 +1,26 @@
1
+ // Types of `compiler-calls.js`, which stays plain JavaScript so that a worker thread loads it
2
+ // with no TypeScript step.
3
+
4
+ /** Runs the shader compiler's exports, on one instance of its module at a time. */
5
+ export declare class CompilerCalls {
6
+ constructor(module: WebAssembly.Module);
7
+ /** The compiled shader compiler. */
8
+ readonly module: WebAssembly.Module;
9
+ /**
10
+ * Runs one export on a request in JSON, and returns the response in JSON. The first call makes
11
+ * the instance, and later calls reuse it with the library modules that it composed. A manifest
12
+ * build's answer arrives in pieces from the module and this joins them, so the response is one
13
+ * JSON text whichever call ran.
14
+ */
15
+ call(
16
+ name:
17
+ | 'compile'
18
+ | 'compile_material'
19
+ | 'compile_effect'
20
+ | 'compile_sky_layer'
21
+ | 'build'
22
+ | 'prepare_modules'
23
+ | 'module',
24
+ request: string,
25
+ ): string;
26
+ }
@@ -0,0 +1,97 @@
1
+ // The shader compiler module's calling convention: a call writes its JSON request into the
2
+ // module's memory, runs an export, and reads the JSON response. The file is plain JavaScript, so
3
+ // a worker thread loads it under every Node version that Vite supports, with no TypeScript step.
4
+
5
+ const encoder = new TextEncoder();
6
+ const decoder = new TextDecoder();
7
+
8
+ /**
9
+ * A pointer the module returned, as the offset a typed array takes. A WebAssembly function that
10
+ * returns a 32-bit value gives JavaScript a signed number, so a pointer at or above 2 GB arrives
11
+ * negative and a typed array built from it throws `byteOffset cannot be negative`. The module's own
12
+ * memory passes 2 GB while it builds the engine's manifest, so every pointer it returns is brought
13
+ * back to unsigned here rather than trusted to stay small.
14
+ *
15
+ * @param {number} value
16
+ * @returns {number}
17
+ */
18
+ function pointer(value) {
19
+ return value >>> 0;
20
+ }
21
+
22
+ /** Runs the shader compiler's exports, on one instance of its module at a time. */
23
+ export class CompilerCalls {
24
+ /** @param {WebAssembly.Module} module The compiled shader compiler. */
25
+ constructor(module) {
26
+ /** @readonly */
27
+ this.module = module;
28
+ /** @type {any} */
29
+ this.instance = undefined;
30
+ }
31
+
32
+ /**
33
+ * Runs one export on a request in JSON, and returns the response in JSON. The first call makes
34
+ * the instance, and later calls reuse it with the library modules that it composed.
35
+ *
36
+ * A manifest build answers in pieces, because the module keeps no copy of an answer that grows
37
+ * with the engine: `build` writes the first piece and `build_next` each piece after it, until a
38
+ * piece comes back empty. This joins them, so a caller of `call` sees one response either way.
39
+ *
40
+ * @param {'compile' | 'compile_material' | 'compile_effect' | 'compile_sky_layer' | 'build'} name
41
+ * @param {string} request
42
+ * @returns {string}
43
+ */
44
+ call(name, request) {
45
+ this.instance ??= new WebAssembly.Instance(this.module).exports;
46
+ const wasm = this.instance;
47
+ const bytes = encoder.encode(request);
48
+ // Making room can grow the memory, which replaces its buffer, so the view comes after.
49
+ const at = pointer(wasm.request(bytes.length));
50
+ new Uint8Array(wasm.memory.buffer, at, bytes.length).set(bytes);
51
+ // The memory may grow between pieces, which replaces its buffer, so each view is made from
52
+ // the buffer as it is then.
53
+ const piece = () =>
54
+ decoder.decode(
55
+ new Uint8Array(wasm.memory.buffer, pointer(wasm.response()), wasm.response_length()),
56
+ );
57
+ let response = '';
58
+ let stopped;
59
+ try {
60
+ wasm[name]();
61
+ if (wasm.response_length() !== 0) response = piece();
62
+ // A manifest build's answer arrives in pieces, because the module keeps no copy of an
63
+ // answer that grows with the engine. An empty piece says the answer is complete.
64
+ while (name === 'build' && wasm.response_length() !== 0) {
65
+ wasm.build_next();
66
+ if (wasm.response_length() !== 0) response += piece();
67
+ }
68
+ } catch (error) {
69
+ // A call that stops part way can leave the instance in any state, so the next call makes
70
+ // a new instance. A panic has written its own response first, and a memory request the
71
+ // module could not be given has left its own account of the stop.
72
+ this.instance = undefined;
73
+ stopped = error;
74
+ response = '';
75
+ const notice = wasm.stopped_length();
76
+ if (notice !== 0) {
77
+ response = decoder.decode(
78
+ new Uint8Array(wasm.memory.buffer, pointer(wasm.stopped()), notice),
79
+ );
80
+ }
81
+ }
82
+ if (response !== '') return response;
83
+ return JSON.stringify({
84
+ ok: false,
85
+ problems: [
86
+ {
87
+ file: null,
88
+ line: null,
89
+ column: null,
90
+ feature: null,
91
+ message: `the shader compiler stopped on an internal error, which is a bug in null3D: ${String(stopped)}. Report it with the shader that caused it.`,
92
+ variants: [],
93
+ },
94
+ ],
95
+ });
96
+ }
97
+ }
@@ -0,0 +1,8 @@
1
+ /** The record's file name, in the compiler's folder. */
2
+ export declare const COMPILER_STAMP_FILE = "shader-compiler.stamp.json";
3
+ /** The record's format. A record of another format names no version. */
4
+ export declare const COMPILER_STAMP_FORMAT = 1;
5
+ /** The version that a record holds, or undefined when it is not one that this code writes. */
6
+ export declare function compilerStampVersion(record: unknown): string | undefined;
7
+ /** The version that the record at `file` holds, or undefined when it is missing or unreadable. */
8
+ export declare function readCompilerStamp(file: string | URL): string | undefined;
@@ -0,0 +1,34 @@
1
+ // The record beside the shader compiler that names the inputs of a project's compile. The build
2
+ // writes it, and the Vite plugin reads it as the compiler's version. The version covers the
3
+ // compiler's own sources, the library modules, the manifest's template tables and the template
4
+ // shaders: everything a project's compile can read. An engine entry shader that no project
5
+ // compiles is not one of them, so changing it keeps the cache's entries.
6
+ //
7
+ // A record that is missing or unreadable names no version. The caller then reads the compiler's own
8
+ // bytes as its version, which is safe: a change to any shader moves that version, and every entry
9
+ // compiles again.
10
+ import { readFileSync } from 'node:fs';
11
+ /** The record's file name, in the compiler's folder. */
12
+ export const COMPILER_STAMP_FILE = 'shader-compiler.stamp.json';
13
+ /** The record's format. A record of another format names no version. */
14
+ export const COMPILER_STAMP_FORMAT = 1;
15
+ /** The version that a record holds, or undefined when it is not one that this code writes. */
16
+ export function compilerStampVersion(record) {
17
+ if (typeof record !== 'object' || record === null)
18
+ return undefined;
19
+ const { format, version } = record;
20
+ if (format !== COMPILER_STAMP_FORMAT ||
21
+ typeof version !== 'string' ||
22
+ !/^[0-9a-f]{64}$/.test(version))
23
+ return undefined;
24
+ return version;
25
+ }
26
+ /** The version that the record at `file` holds, or undefined when it is missing or unreadable. */
27
+ export function readCompilerStamp(file) {
28
+ try {
29
+ return compilerStampVersion(JSON.parse(readFileSync(file, 'utf8')));
30
+ }
31
+ catch {
32
+ return undefined;
33
+ }
34
+ }
@@ -0,0 +1,10 @@
1
+ import type { CompiledWgsl } from './shader-types.js';
2
+ /** The path of the declaration of a `.wgsl` file. */
3
+ export declare function declarationPath(file: string): string;
4
+ /** The declaration of a compiled `.wgsl` file, which TypeScript reads for imports of the file. */
5
+ export declare function wgslDeclaration(file: string, shader: CompiledWgsl): string;
6
+ /**
7
+ * Writes the declaration of a compiled `.wgsl` file beside it, unless the file there already holds
8
+ * it. An unchanged declaration is left alone, so that editors and file watchers see no change.
9
+ */
10
+ export declare function writeWgslDeclaration(file: string, shader: CompiledWgsl): void;