diff --git a/sdk/web/src/index.tsx b/sdk/web/src/index.tsx index b18ab62b..8201193e 100644 --- a/sdk/web/src/index.tsx +++ b/sdk/web/src/index.tsx @@ -8,6 +8,7 @@ import { createRoot } from "react-dom/client"; import { Clock, getCompositions, type InputTimeline, type RegisteredComposition } from "raea"; import { Input } from "@raea/playable/host/input"; import { Collector, UNDER3D_CSS, clearUnder3d } from "./collect"; +import { patchShaderModules } from "./wgsl"; /** raea-web's engine, as wasm-bindgen exports it (engine/web: `import init, { Raea } from "./raea_web.js"`). */ export interface RaeaEngine { @@ -31,6 +32,8 @@ const loaded = new WeakMap<() => Promise, Promise> export function loadRaea(load: () => Promise): Promise { let p = loaded.get(load); if (!p) { + // Safari reads WGSL to the letter: Bevy's shaders are made to its rules first (wgsl.ts) + patchShaderModules(); p = load().then(async (m) => (await m.default(), m)); loaded.set(load, p); } diff --git a/sdk/web/src/wgsl.ts b/sdk/web/src/wgsl.ts new file mode 100644 index 00000000..d7c3d0ac --- /dev/null +++ b/sdk/web/src/wgsl.ts @@ -0,0 +1,61 @@ +// Safari's WGSL (WebKit) holds to the spec: a `let` can't hold a texture or a sampler (they aren't constructible +// types), while Chrome's Tint lets it through. Bevy's PBR shaders do it (bevy_pbr pbr_fragment.wesl, +// `let texture = pbr_bindings::base_color_texture;`), in every mesh with UVs, so raea-web drew nothing in Safari +// ("Fragment module is invalid", 12-02). Each such `let` is inlined here before the module is made: its name is replaced +// by what it held (a global binding, or an index into a binding array) through the rest of its block. + +/** the global bindings of handle types (textures, samplers, arrays of either) a shader declares */ +function handles(code: string): Set { + const out = new Set(); + for (const m of code.matchAll(/\bvar\s+(\w+)\s*:\s*(?:texture_|sampler|binding_array\s*<\s*(?:texture_|sampler))/g)) out.add(m[1]); + return out; +} + +/** where the block holding `at` closes (the index of its `}`), or the end */ +function blockEnd(code: string, at: number): number { + let depth = 0; + for (let i = at; i < code.length; i++) { + const c = code[i]; + if (c === "{") depth++; + else if (c === "}") { + if (depth === 0) return i; + depth--; + } + } + return code.length; +} + +/** The shader with every `let` that holds a texture or sampler inlined; the same text when there's none. */ +export function inlineHandleLets(code: string): string { + const globals = handles(code); + if (!globals.size) return code; + const decl = /\blet\s+(\w+)\s*(?::\s*[^=]+)?=\s*([^;]+);/g; + for (let guard = 0; guard < 10_000; guard++) { + decl.lastIndex = 0; + let m: RegExpExecArray | null, found: RegExpExecArray | null = null; + while ((m = decl.exec(code))) { + const root = /^\s*(?:\w+::)*(\w+)/.exec(m[2])?.[1]; + if (root && globals.has(root)) { found = m; break; } + } + if (!found) return code; + const [whole, name, held] = found; + const from = found.index + whole.length; + const end = blockEnd(code, from); + const value = held.trim().replace(/\s+/g, " "); + const rest = code.slice(from, end).replace(new RegExp(`\\b${name}\\b`, "g"), () => value); + code = code.slice(0, found.index) + rest + code.slice(end); + } + return code; +} + +let patched = false; +/** Makes every WebGPU shader module from its inlined text (once per page; nothing where there's no WebGPU). */ +export function patchShaderModules() { + const G = (globalThis as { GPUDevice?: { prototype: { createShaderModule(d: { code: string }): unknown } } }).GPUDevice; + if (patched || !G) return; + patched = true; + const make = G.prototype.createShaderModule; + G.prototype.createShaderModule = function (d: { code: string }) { + return make.call(this, typeof d?.code === "string" ? { ...d, code: inlineHandleLets(d.code) } : d); + }; +} diff --git a/sdk/web/test/unit/wgsl.test.ts b/sdk/web/test/unit/wgsl.test.ts new file mode 100644 index 00000000..6539eb0d --- /dev/null +++ b/sdk/web/test/unit/wgsl.test.ts @@ -0,0 +1,56 @@ +// wgsl.ts: a `let` holding a texture or sampler is inlined for Safari; everything else is left as it was +import { expect, test } from "bun:test"; +import { inlineHandleLets } from "../../src/wgsl"; + +const head = `@group(2) @binding(1) var base_color_texture: texture_2d; +@group(2) @binding(2) var base_color_sampler: sampler; +@group(2) @binding(3) var bindless_textures_2d: binding_array, 16>; +`; + +test("a texture and a sampler held by lets are used directly, in their block only", () => { + const code = `${head}fn f(uv: vec2) -> vec4 { + var c = vec4(1.0); + if (true) { + let texture = base_color_texture; + let sampler_ = base_color_sampler; + let coords = uv; + c *= textureSampleBias(texture, sampler_, coords, 0.0); + } + let texture_scale = 2.0; + return c * texture_scale; +}`; + const out = inlineHandleLets(code); + expect(out).not.toContain("let texture ="); + expect(out).not.toContain("let sampler_ ="); + expect(out).toContain("textureSampleBias(base_color_texture, base_color_sampler, coords, 0.0)"); + expect(out).toContain("let coords = uv;"); + expect(out).toContain("let texture_scale = 2.0;"); + expect(out).toContain("return c * texture_scale;"); +}); + +test("a binding array's element, over lines, and the same name again in the next block", () => { + const code = `${head}fn g(i: u32, uv: vec2) -> f32 { + var a = 0.0; + { + let texture = bindless_textures_2d[ + i + ]; + a += textureSample(texture, base_color_sampler, uv).r; + } + { + let texture = base_color_texture; + a += textureSample(texture, base_color_sampler, uv).g; + } + return a; +}`; + const out = inlineHandleLets(code); + expect(out).toContain("textureSample(bindless_textures_2d[ i ], base_color_sampler, uv).r"); + expect(out).toContain("textureSample(base_color_texture, base_color_sampler, uv).g"); + expect(out).not.toMatch(/let texture\b/); +}); + +test("a module path (naga_oil's pbr_bindings::) is a binding all the same; a shader with no handles is untouched", () => { + expect(inlineHandleLets(`${head}fn h() { let t = pbr_bindings::base_color_texture; textureDimensions(t); }`)).toContain("textureDimensions(pbr_bindings::base_color_texture)"); + const plain = "fn k() -> f32 { let x = 1.0; return x; }"; + expect(inlineHandleLets(plain)).toBe(plain); +});