diff --git a/bun.lock b/bun.lock index 01ee175..a512305 100644 --- a/bun.lock +++ b/bun.lock @@ -5,6 +5,7 @@ "name": "libmojangles", "dependencies": { "jszip": "^3.10.1", + "libmojangles": "^1.4.2", }, "devDependencies": { "@playwright/test": "^1.59.1", @@ -90,6 +91,8 @@ "jszip": ["jszip@3.10.1", "", { "dependencies": { "lie": "~3.3.0", "pako": "~1.0.2", "readable-stream": "~2.3.6", "setimmediate": "^1.0.5" } }, "sha512-xXDvecyTpGLrqFrvkrUSoxxfJI5AH7U8zxxtVclpsUtMCq4JQ290LY8AW5c7Ggnr/Y/oK+bQMbqK2qmtk3pN4g=="], + "libmojangles": ["libmojangles@1.4.2", "", { "dependencies": { "jszip": "^3.10.1" }, "peerDependencies": { "typescript": "^5" } }, "sha512-LL7CH+/POFAlgWWJDa+VEKQlgj8BbgojAy/oBF2g+O0PJesdC4cRun7mRYcHi7rfMekETagPpsLk2zR3muwYKA=="], + "lie": ["lie@3.3.0", "", { "dependencies": { "immediate": "~3.0.5" } }, "sha512-UaiMJzeWRlEujzAuw5LokY1L5ecNQYZKfmyZ9L7wDHb/p5etKaxXhohBcrw0EYby+G/NA52vRSN4N39dxHAIwQ=="], "lightningcss": ["lightningcss@1.32.0", "", { "dependencies": { "detect-libc": "^2.0.3" }, "optionalDependencies": { "lightningcss-android-arm64": "1.32.0", "lightningcss-darwin-arm64": "1.32.0", "lightningcss-darwin-x64": "1.32.0", "lightningcss-freebsd-x64": "1.32.0", "lightningcss-linux-arm-gnueabihf": "1.32.0", "lightningcss-linux-arm64-gnu": "1.32.0", "lightningcss-linux-arm64-musl": "1.32.0", "lightningcss-linux-x64-gnu": "1.32.0", "lightningcss-linux-x64-musl": "1.32.0", "lightningcss-win32-arm64-msvc": "1.32.0", "lightningcss-win32-x64-msvc": "1.32.0" } }, "sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ=="], diff --git a/devserver/src/test-runner.ts b/devserver/src/test-runner.ts index abca38e..2328e13 100644 --- a/devserver/src/test-runner.ts +++ b/devserver/src/test-runner.ts @@ -25,6 +25,8 @@ declare global { __TEST_ERROR__?: string; __LAST_DRAW_RESULT__?: { components: Array<{ id?: string; bbox: { min: [number, number]; max: [number, number] } }> }; __runTest__: (config: TestConfig) => Promise; + __TEST_LIB__?: Libmojangles; + __TEST_MEMORY_PACK__?: typeof MemoryResourcePack; } } @@ -49,6 +51,8 @@ async function init() { }; window.__runTest__ = runTest; + window.__TEST_LIB__ = lib; + window.__TEST_MEMORY_PACK__ = MemoryResourcePack; window.__TEST_READY__ = true; } diff --git a/package.json b/package.json index 1b1c98b..792c249 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "libmojangles", "type": "module", - "version": "1.4.1", + "version": "1.4.2", "module": "dist/index.js", "types": "dist/index.d.ts", "exports": { @@ -33,6 +33,7 @@ "typescript": "^5" }, "dependencies": { - "jszip": "^3.10.1" + "jszip": "^3.10.1", + "libmojangles": "^1.4.2" } } diff --git a/src/renderer/webgl-shader.ts b/src/renderer/webgl-shader.ts index bcc4610..94e29b7 100644 --- a/src/renderer/webgl-shader.ts +++ b/src/renderer/webgl-shader.ts @@ -70,15 +70,12 @@ void main() { const MINECRAFT_PICKING_FRAGMENT_SHADER = `#version 300 es precision highp float; -in float sphericalVertexDistance; -in float cylindricalVertexDistance; -in vec4 vertexColor; -in vec2 texCoord0; +in vec4 vertexPickColor; out vec4 fragColor; void main() { - fragColor = vertexColor; + fragColor = vertexPickColor; } `; @@ -88,12 +85,35 @@ const MINECRAFT_ATTR_BINDINGS: Record = { Color: 1, UV0: 2, UV2: 3, + PickColor: 4, a_position: 0, a_color: 1, a_uv0: 2, a_uv2: 3, }; +export function injectPickingPassThrough(vertexSource: string): string { + const hasPickColorIn = /\bin\s+vec4\s+PickColor\s*;/m.test(vertexSource); + const hasPickColorOut = /\bout\s+vec4\s+vertexPickColor\s*;/m.test(vertexSource); + const mainMatch = /\bvoid\s+main\s*\(\s*\)\s*\{/m.exec(vertexSource); + if (!mainMatch || mainMatch.index === undefined) { + throw new Error("Failed to create picking shader variant: could not find main() in vertex shader"); + } + + let patched = vertexSource; + const declarationBlock = `${hasPickColorIn ? "" : "in vec4 PickColor;\n"}${hasPickColorOut ? "" : "out vec4 vertexPickColor;\n"}`; + if (declarationBlock) { + const headerMatch = /^(\s*#version\s+[^\n]*\n(?:\s*precision\s+[^\n]*\n)*)/m.exec(patched); + const insertDeclarationsAt = headerMatch ? headerMatch[0].length : 0; + patched = `${patched.slice(0, insertDeclarationsAt)}${declarationBlock}${patched.slice(insertDeclarationsAt)}`; + } + + const insertAt = mainMatch.index + (patched.length - vertexSource.length) + mainMatch[0].length; + patched = `${patched.slice(0, insertAt)}\n vertexPickColor = PickColor;${patched.slice(insertAt)}`; + + return patched; +} + interface CompiledProgram { program: WebGLProgram; uniforms: Map; @@ -489,7 +509,8 @@ export class WebGLShaderManager implements ShaderManager { // Create picking variant with same vertex shader + Minecraft-compatible picking fragment shader const pickingId = getPickingProgramId(programId); if (!this.compiledPrograms.has(pickingId)) { - const pickingCompiled = this.compileProgramWithBindings(vertexSource, MINECRAFT_PICKING_FRAGMENT_SHADER); + const pickingVertexSource = injectPickingPassThrough(vertexSource); + const pickingCompiled = this.compileProgramWithBindings(pickingVertexSource, MINECRAFT_PICKING_FRAGMENT_SHADER); this.compiledPrograms.set(pickingId, pickingCompiled); } diff --git a/src/renderer/webgl.ts b/src/renderer/webgl.ts index 0192229..2be753d 100644 --- a/src/renderer/webgl.ts +++ b/src/renderer/webgl.ts @@ -12,6 +12,7 @@ import { WebGLShaderManager, getPickingProgramId } from "./webgl-shader"; import { WebGLTextureManager } from "./webgl-texture"; const FLOATS_PER_VERTEX = 12; +const PICKING_FLOATS_PER_VERTEX = 16; function createOrthographicMatrix( left: number, @@ -184,6 +185,7 @@ export class WebGLRenderer implements Renderer { textures: WebGLTextureManager | null = null; private vao: WebGLVertexArrayObject | null = null; + private pickingVao: WebGLVertexArrayObject | null = null; private vbo: WebGLBuffer | null = null; private ebo: WebGLBuffer | null = null; @@ -243,6 +245,7 @@ export class WebGLRenderer implements Renderer { const gl = this.gl; this.vao = gl.createVertexArray(); + this.pickingVao = gl.createVertexArray(); this.vbo = gl.createBuffer(); this.ebo = gl.createBuffer(); @@ -264,6 +267,27 @@ export class WebGLRenderer implements Renderer { gl.enableVertexAttribArray(3); gl.vertexAttribPointer(3, 2, gl.FLOAT, false, stride, 36); + gl.bindVertexArray(this.pickingVao); + gl.bindBuffer(gl.ARRAY_BUFFER, this.vbo); + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.ebo); + + const pickingStride = PICKING_FLOATS_PER_VERTEX * 4; + + gl.enableVertexAttribArray(0); + gl.vertexAttribPointer(0, 3, gl.FLOAT, false, pickingStride, 0); + + gl.enableVertexAttribArray(1); + gl.vertexAttribPointer(1, 4, gl.FLOAT, false, pickingStride, 12); + + gl.enableVertexAttribArray(2); + gl.vertexAttribPointer(2, 2, gl.FLOAT, false, pickingStride, 28); + + gl.enableVertexAttribArray(3); + gl.vertexAttribPointer(3, 2, gl.FLOAT, false, pickingStride, 36); + + gl.enableVertexAttribArray(4); + gl.vertexAttribPointer(4, 4, gl.FLOAT, false, pickingStride, 48); + gl.bindVertexArray(null); } @@ -391,7 +415,7 @@ export class WebGLRenderer implements Renderer { if (projLoc) gl.uniformMatrix4fv(projLoc, false, projection); if (mvLoc) gl.uniformMatrix4fv(mvLoc, false, modelView); - gl.bindVertexArray(this.vao); + gl.bindVertexArray(this.pickingVao); this.drawPickingMesh(mesh.pickingMesh, compiled); gl.bindVertexArray(null); @@ -412,6 +436,7 @@ export class WebGLRenderer implements Renderer { private drawPickingMesh(mesh: TextMesh, compiled: { program: WebGLProgram; uniforms: Map }): void { const gl = this.gl; + const isCustomPickingMesh = (mesh.floatsPerVertex ?? FLOATS_PER_VERTEX) === PICKING_FLOATS_PER_VERTEX; // Bind white texture to Sampler2 for lightmap — required by Minecraft vertex shader const sampler2Loc = compiled.uniforms.get("Sampler2"); @@ -430,7 +455,16 @@ export class WebGLRenderer implements Renderer { gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.ebo); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, mesh.indices, gl.DYNAMIC_DRAW); + if (!isCustomPickingMesh) { + gl.disableVertexAttribArray(4); + gl.vertexAttrib4f(4, 0, 0, 0, 0); + } + gl.drawElements(gl.TRIANGLES, mesh.indexCount, gl.UNSIGNED_SHORT, 0); + + if (!isCustomPickingMesh) { + gl.enableVertexAttribArray(4); + } } readPickingBuffer(x: number, y: number): Uint8Array { @@ -486,6 +520,7 @@ export class WebGLRenderer implements Renderer { const gl = this.gl; if (this.vao) gl.deleteVertexArray(this.vao); + if (this.pickingVao) gl.deleteVertexArray(this.pickingVao); if (this.vbo) gl.deleteBuffer(this.vbo); if (this.ebo) gl.deleteBuffer(this.ebo); if (this.pickingFramebuffer) gl.deleteFramebuffer(this.pickingFramebuffer); diff --git a/src/types/vertex.ts b/src/types/vertex.ts index 7881277..df437de 100644 --- a/src/types/vertex.ts +++ b/src/types/vertex.ts @@ -14,6 +14,7 @@ export type TextMesh = { readonly textureId: string; readonly vertexCount: number; readonly indexCount: number; + readonly floatsPerVertex?: number; }; export type TextMeshGroup = { diff --git a/src/vertex/generator.ts b/src/vertex/generator.ts index ad9c32b..cda3889 100644 --- a/src/vertex/generator.ts +++ b/src/vertex/generator.ts @@ -18,6 +18,7 @@ const EXTRA_BOLD_THICKNESS = 0.1; const DEFAULT_LIGHTMAP: [number, number] = [240 / 256, 240 / 256]; const FLOATS_PER_VERTEX = 12; +const PICKING_FLOATS_PER_VERTEX = 16; function colorToArray(color: Color): [number, number, number, number] { return [color.r, color.g, color.b, color.a]; @@ -118,8 +119,9 @@ export class VertexGeneratorImpl implements VertexGenerator { vertices: new Float32Array(pickingData.vertices), indices: new Uint16Array(pickingData.indices), textureId: "picking", - vertexCount: pickingData.vertices.length / FLOATS_PER_VERTEX, + vertexCount: pickingData.vertices.length / PICKING_FLOATS_PER_VERTEX, indexCount: pickingData.indices.length, + floatsPerVertex: PICKING_FLOATS_PER_VERTEX, }; } @@ -339,7 +341,40 @@ export class VertexGeneratorImpl implements VertexGenerator { const y0 = glyph.y + glyph.glyph.up * scale; const y1 = glyph.y + glyph.glyph.down * scale; - this.addRectQuad(pickingData, x0, y0, x1, y1, z, pickColor, lightmapUV); + const color = glyph.style.color ?? { r: 1, g: 1, b: 1, a: 1 }; + this.addPickingRectQuad(pickingData, x0, y0, x1, y1, z, color, lightmapUV, pickColor); + } + + private addPickingRectQuad( + meshData: { vertices: number[]; indices: number[] }, + x0: number, + y0: number, + x1: number, + y1: number, + z: number, + color: Color, + lightmapUV: [number, number], + pickColor: Color + ): void { + const baseVertex = meshData.vertices.length / PICKING_FLOATS_PER_VERTEX; + const rgba = colorToArray(color); + const pickRgba = colorToArray(pickColor); + + meshData.vertices.push( + x0, y0, z, rgba[0], rgba[1], rgba[2], rgba[3], 0, 0, lightmapUV[0], lightmapUV[1], 0, pickRgba[0], pickRgba[1], pickRgba[2], pickRgba[3], + x0, y1, z, rgba[0], rgba[1], rgba[2], rgba[3], 0, 1, lightmapUV[0], lightmapUV[1], 0, pickRgba[0], pickRgba[1], pickRgba[2], pickRgba[3], + x1, y1, z, rgba[0], rgba[1], rgba[2], rgba[3], 1, 1, lightmapUV[0], lightmapUV[1], 0, pickRgba[0], pickRgba[1], pickRgba[2], pickRgba[3], + x1, y0, z, rgba[0], rgba[1], rgba[2], rgba[3], 1, 0, lightmapUV[0], lightmapUV[1], 0, pickRgba[0], pickRgba[1], pickRgba[2], pickRgba[3] + ); + + meshData.indices.push( + baseVertex, + baseVertex + 1, + baseVertex + 2, + baseVertex, + baseVertex + 2, + baseVertex + 3 + ); } private addQuad( diff --git a/tests/renderer/webgl-shader-compile.test.ts b/tests/renderer/webgl-shader-compile.test.ts new file mode 100644 index 0000000..2064954 --- /dev/null +++ b/tests/renderer/webgl-shader-compile.test.ts @@ -0,0 +1,349 @@ +import { describe, it, expect, beforeAll, afterAll } from "bun:test"; +import { createServer, type ViteDevServer } from "vite"; +import { chromium, type Browser, type Page } from "playwright"; +import * as path from "path"; + +const ROOT_DIR = path.resolve(__dirname, "../.."); +const DEVSERVER_DIR = path.join(ROOT_DIR, "devserver"); + +describe("WebGL shader picking variant compilation", () => { + let server: ViteDevServer | null = null; + let browser: Browser | null = null; + let page: Page | null = null; + let port = 0; + + beforeAll(async () => { + server = await createServer({ + root: DEVSERVER_DIR, + server: { port: 0 }, + logLevel: "silent", + }); + + await server.listen(); + const address = server.httpServer?.address(); + if (address && typeof address === "object") { + port = address.port; + } + + browser = await chromium.launch({ + args: ["--use-gl=swiftshader", "--use-angle=swiftshader"], + headless: true, + }); + + page = await browser.newPage({ + viewport: { width: 800, height: 600 }, + deviceScaleFactor: 1, + }); + + await page.goto(`http://localhost:${port}/test-harness.html`); + await page.waitForFunction(() => window.__TEST_READY__ === true, { timeout: 30000 }); + }); + + afterAll(async () => { + if (page) { + await page.close(); + page = null; + } + if (browser) { + await browser.close(); + browser = null; + } + if (server) { + await server.close(); + server = null; + } + }); + + async function compileTest(name: string, vertexSource: string): Promise { + if (!page) throw new Error("No browser page"); + + const result = await page.evaluate( + async (vertex) => { + const lib = window.__TEST_LIB__; + const MemoryResourcePack = window.__TEST_MEMORY_PACK__; + if (!lib || !MemoryResourcePack) { + return { ok: false, error: "Test lib not initialized" }; + } + + try { + const customPack = new MemoryResourcePack("__compile_edge_case__"); + customPack.setTextFile( + { namespace: "test", path: "shaders/edge.vsh" }, + vertex + ); + customPack.setTextFile( + { namespace: "test", path: "shaders/edge.fsh" }, + `#version 300 es +precision highp float; + +in vec4 vertexColor; +out vec4 fragColor; + +void main() { + fragColor = vertexColor; +} +` + ); + lib.addResourcePack(customPack); + + const program = await lib.shaders.loadProgram( + { namespace: "test", path: "shaders/edge.vsh" }, + { namespace: "test", path: "shaders/edge.fsh" } + ); + + const shaderManager = lib.renderer.getShaderManager(); + const pickingProgram = shaderManager?.getCompiledProgram(`${program.id}:picking`); + + return { + ok: !!pickingProgram, + error: pickingProgram ? undefined : "Picking program was not created", + }; + } catch (error) { + return { + ok: false, + error: error instanceof Error ? error.message : String(error), + }; + } + }, + vertexSource + ); + + if (!result.ok) { + throw new Error(`${name}: ${result.error}`); + } + expect(result.ok).toBe(true); + } + + it("compiles a patched picking variant for the sample custom vertex shader", async () => { + if (!page) throw new Error("No browser page"); + + const result = await page.evaluate(async () => { + const lib = window.__TEST_LIB__; + const MemoryResourcePack = window.__TEST_MEMORY_PACK__; + if (!lib) { + return { ok: false, error: "Test lib not initialized" }; + } + if (!MemoryResourcePack) { + return { ok: false, error: "MemoryResourcePack not initialized" }; + } + + try { + const response = await fetch(`${window.location.origin}/test-assets/simple-shader.vsh`); + if (!response.ok) { + return { ok: false, error: "Failed to fetch sample shader" }; + } + + const vertexSource = await response.text(); + const customPack = new MemoryResourcePack("__compile_test_shader__"); + customPack.setTextFile( + { namespace: "test", path: "shaders/custom.vsh" }, + vertexSource + ); + customPack.setTextFile( + { namespace: "test", path: "shaders/custom.fsh" }, + `#version 300 es +precision highp float; + +in vec4 vertexColor; +out vec4 fragColor; + +void main() { + fragColor = vertexColor; +} +` + ); + lib.addResourcePack(customPack); + + const program = await lib.shaders.loadProgram( + { namespace: "test", path: "shaders/custom.vsh" }, + { namespace: "test", path: "shaders/custom.fsh" } + ); + + const shaderManager = lib.renderer.getShaderManager(); + const pickingProgram = shaderManager?.getCompiledProgram(`${program.id}:picking`); + if (!pickingProgram) { + return { ok: false, error: "Picking program was not created" }; + } + + const pickColorAttribute = pickingProgram.attributes.get("PickColor"); + const vertexPickColorVarying = pickingProgram.attributes.has("Position") && pickingProgram.attributes.has("PickColor"); + + return { + ok: pickColorAttribute === 4 && vertexPickColorVarying === true, + pickColorAttribute, + vertexPickColorVarying, + error: pickColorAttribute === 4 && vertexPickColorVarying === true ? undefined : "Patched picking shader missing expected wiring", + }; + } catch (error) { + return { + ok: false, + error: error instanceof Error ? error.message : String(error), + }; + } + }); + + if (!result.ok) { + throw new Error(result.error); + } + expect(result.ok).toBe(true); + }); + + it("compiles patched shader with PickColor already declared as in", async () => { + await compileTest("PickColor already declared as in", `#version 300 es +precision highp float; + +in vec4 PickColor; +in vec3 Position; +out vec4 vertexColor; + +void main() { + gl_Position = vec4(Position, 1.0); +} +`); + }); + + it("compiles patched shader with vertexPickColor already declared as out", async () => { + await compileTest("vertexPickColor already declared as out", `#version 300 es +precision highp float; + +in vec3 Position; +out vec4 vertexPickColor; +out vec4 vertexColor; + +void main() { + gl_Position = vec4(Position, 1.0); +} +`); + }); + + it("compiles patched shader with both PickColor and vertexPickColor already declared", async () => { + await compileTest("both PickColor and vertexPickColor already declared", `#version 300 es +precision highp float; + +in vec4 PickColor; +in vec3 Position; +out vec4 vertexPickColor; +out vec4 vertexColor; + +void main() { + gl_Position = vec4(Position, 1.0); +} +`); + }); + + it("compiles patched shader with no #version directive", async () => { + await compileTest("no #version directive", `precision highp float; + +in vec3 Position; +out vec4 vertexColor; + +void main() { + gl_Position = vec4(Position, 1.0); +} +`); + }); + + it("compiles patched shader with comments before main", async () => { + await compileTest("comments before main", `#version 300 es +precision highp float; + +// This is a comment +/* Multi-line + comment */ +in vec3 Position; +out vec4 vertexColor; + +// Another comment +void main() { + gl_Position = vec4(Position, 1.0); +} +`); + }); + + it("compiles patched shader with main signature split across lines", async () => { + await compileTest("main signature split across lines", `#version 300 es +precision highp float; + +in vec3 Position; +out vec4 vertexColor; + +void +main +( +) +{ + gl_Position = vec4(Position, 1.0); +} +`); + }); + + it("compiles patched shader with multiple predeclared uniforms", async () => { + await compileTest("multiple predeclared uniforms", `#version 300 es +precision highp float; + +uniform mat4 u_projection; +uniform mat4 u_modelView; +uniform vec3 u_cameraPos; + +in vec3 Position; +out vec4 vertexColor; + +void main() { + gl_Position = u_projection * u_modelView * vec4(Position, 1.0); +} +`); + }); + + it("compiles patched shader with struct definitions before main", async () => { + await compileTest("struct definitions before main", `#version 300 es +precision highp float; + +struct VertexData { + vec3 position; + vec4 color; +}; + +in vec3 Position; +out vec4 vertexColor; + +void main() { + gl_Position = vec4(Position, 1.0); +} +`); + }); + + it("compiles patched shader with ifdef preprocessor directives", async () => { + await compileTest("ifdef preprocessor directives", `#version 300 es +precision highp float; + +#ifdef GL_ES +precision highp int; +#endif + +in vec3 Position; +out vec4 vertexColor; + +void main() { + gl_Position = vec4(Position, 1.0); +} +`); + }); + + it("compiles patched shader with multiple out varyings", async () => { + await compileTest("multiple out varyings", `#version 300 es +precision highp float; + +in vec3 Position; +out vec4 vertexColor; +out vec2 texCoord; +out float fogDist; + +void main() { + gl_Position = vec4(Position, 1.0); + vertexColor = vec4(1.0); + texCoord = vec2(0.0); + fogDist = 100.0; +} +`); + }); +}); \ No newline at end of file diff --git a/tests/renderer/webgl-shader.test.ts b/tests/renderer/webgl-shader.test.ts new file mode 100644 index 0000000..28c5cc8 --- /dev/null +++ b/tests/renderer/webgl-shader.test.ts @@ -0,0 +1,357 @@ +import { describe, it, expect } from "bun:test"; +import { injectPickingPassThrough } from "../../src/renderer/webgl-shader"; + +describe("injectPickingPassThrough", () => { + it("injects declarations after version and precision lines", () => { + const source = `#version 300 es +precision highp float; +precision highp int; + +in vec3 Position; +out vec4 vertexColor; + +void main() { + gl_Position = vec4(Position, 1.0); +} +`; + + const patched = injectPickingPassThrough(source); + + expect(patched).toContain(`#version 300 es +precision highp float; +precision highp int; +in vec4 PickColor; +out vec4 vertexPickColor;`); + expect(patched).toContain(`void main() { + vertexPickColor = PickColor;`); + }); + + it("does not duplicate declarations when they already exist", () => { + const source = `#version 300 es +precision highp float; + +in vec4 PickColor; +out vec4 vertexPickColor; +in vec3 Position; + +void main() { + gl_Position = vec4(Position, 1.0); +} +`; + + const patched = injectPickingPassThrough(source); + + expect(patched.match(/\bin\s+vec4\s+PickColor\s*;/g)).toHaveLength(1); + expect(patched.match(/\bout\s+vec4\s+vertexPickColor\s*;/g)).toHaveLength(1); + expect(patched.match(/vertexPickColor\s*=\s*PickColor;/g)).toHaveLength(1); + }); + + it("supports shaders with unusual whitespace around main", () => { + const source = `#version 300 es +precision highp float; + +in vec3 Position; + +void +main () +{ + gl_Position = vec4(Position, 1.0); +} +`; + + const patched = injectPickingPassThrough(source); + + expect(patched).toContain(`main () +{ + vertexPickColor = PickColor;`); + }); + + it("throws when no main function exists", () => { + expect(() => injectPickingPassThrough("#version 300 es\nprecision highp float;\n")).toThrow( + "Failed to create picking shader variant: could not find main() in vertex shader" + ); + }); + + it("handles shader with PickColor already declared as in", () => { + const source = `#version 300 es +precision highp float; + +in vec4 PickColor; +in vec3 Position; +out vec4 vertexColor; + +void main() { + gl_Position = vec4(Position, 1.0); +} +`; + const patched = injectPickingPassThrough(source); + expect(patched.match(/\bin\s+vec4\s+PickColor\s*;/g)).toHaveLength(1); + expect(patched).toContain("out vec4 vertexPickColor;"); + expect(patched).toContain("vertexPickColor = PickColor;"); + }); + + it("handles shader with vertexPickColor already declared as out", () => { + const source = `#version 300 es +precision highp float; + +in vec3 Position; +out vec4 vertexPickColor; +out vec4 vertexColor; + +void main() { + gl_Position = vec4(Position, 1.0); +} +`; + const patched = injectPickingPassThrough(source); + expect(patched).toContain("in vec4 PickColor;"); + expect(patched.match(/\bout\s+vec4\s+vertexPickColor\s*;/g)).toHaveLength(1); + expect(patched).toContain("vertexPickColor = PickColor;"); + }); + + it("handles shader with both PickColor and vertexPickColor already declared", () => { + const source = `#version 300 es +precision highp float; + +in vec4 PickColor; +in vec3 Position; +out vec4 vertexPickColor; +out vec4 vertexColor; + +void main() { + gl_Position = vec4(Position, 1.0); +} +`; + const patched = injectPickingPassThrough(source); + expect(patched.match(/\bin\s+vec4\s+PickColor\s*;/g)).toHaveLength(1); + expect(patched.match(/\bout\s+vec4\s+vertexPickColor\s*;/g)).toHaveLength(1); + expect(patched).toContain("vertexPickColor = PickColor;"); + }); + + it("handles shader with no #version directive", () => { + const source = `precision highp float; + +in vec3 Position; +out vec4 vertexColor; + +void main() { + gl_Position = vec4(Position, 1.0); +} +`; + const patched = injectPickingPassThrough(source); + expect(patched).toContain("in vec4 PickColor;"); + expect(patched).toContain("out vec4 vertexPickColor;"); + expect(patched).toContain("vertexPickColor = PickColor;"); + }); + + it("handles shader with comments before main", () => { + const source = `#version 300 es +precision highp float; + +// This is a comment +/* Multi-line + comment */ +in vec3 Position; +out vec4 vertexColor; + +// Another comment +void main() { + gl_Position = vec4(Position, 1.0); +} +`; + const patched = injectPickingPassThrough(source); + expect(patched).toContain("in vec4 PickColor;"); + expect(patched).toContain("vertexPickColor = PickColor;"); + }); + + it("handles shader with tabs for indentation", () => { + const source = `#version 300 es +precision highp float; + +in vec3 Position; +out vec4 vertexColor; + +void main() { +\tgl_Position = vec4(Position, 1.0); +} +`; + const patched = injectPickingPassThrough(source); + expect(patched).toContain("in vec4 PickColor;"); + expect(patched).toContain("out vec4 vertexPickColor;"); + }); + + it("handles shader with main signature split across lines", () => { + const source = `#version 300 es +precision highp float; + +in vec3 Position; +out vec4 vertexColor; + +void +main +( +) +{ + gl_Position = vec4(Position, 1.0); +} +`; + const patched = injectPickingPassThrough(source); + expect(patched).toContain("vertexPickColor = PickColor;"); + }); + + it("handles shader with multiple predeclared uniforms", () => { + const source = `#version 300 es +precision highp float; + +uniform mat4 u_projection; +uniform mat4 u_modelView; +uniform vec3 u_cameraPos; + +in vec3 Position; +out vec4 vertexColor; + +void main() { + gl_Position = u_projection * u_modelView * vec4(Position, 1.0); +} +`; + const patched = injectPickingPassThrough(source); + expect(patched).toContain("in vec4 PickColor;"); + expect(patched).toContain("out vec4 vertexPickColor;"); + expect(patched.indexOf("in vec4 PickColor;")).toBeLessThan(patched.indexOf("uniform mat4 u_projection;")); + }); + + it("handles shader with declarations on same line", () => { + const source = `#version 300 es +precision highp float; precision highp int; + +in vec3 Position; out vec4 vertexColor; + +void main() { + gl_Position = vec4(Position, 1.0); +} +`; + const patched = injectPickingPassThrough(source); + expect(patched).toContain("in vec4 PickColor;"); + expect(patched).toContain("out vec4 vertexPickColor;"); + }); + + it("handles shader with struct definitions before main", () => { + const source = `#version 300 es +precision highp float; + +struct VertexData { + vec3 position; + vec4 color; +}; + +in vec3 Position; +out vec4 vertexColor; + +void main() { + gl_Position = vec4(Position, 1.0); +} +`; + const patched = injectPickingPassThrough(source); + expect(patched).toContain("in vec4 PickColor;"); + expect(patched).toContain("out vec4 vertexPickColor;"); + expect(patched.indexOf("in vec4 PickColor;")).toBeLessThan(patched.indexOf("struct VertexData")); + }); + + it("handles shader with ifdef preprocessor directives", () => { + const source = `#version 300 es +precision highp float; + +#ifdef GL_ES +precision highp int; +#endif + +in vec3 Position; +out vec4 vertexColor; + +void main() { + gl_Position = vec4(Position, 1.0); +} +`; + const patched = injectPickingPassThrough(source); + expect(patched).toContain("in vec4 PickColor;"); + expect(patched).toContain("vertexPickColor = PickColor;"); + }); + + it("handles shader with empty lines and mixed whitespace", () => { + const source = `#version 300 es + + + +precision highp float; + + +in vec3 Position; +out vec4 vertexColor; + + +void main() { + gl_Position = vec4(Position, 1.0); +} +`; + const patched = injectPickingPassThrough(source); + expect(patched).toContain("in vec4 PickColor;"); + expect(patched).toContain("out vec4 vertexPickColor;"); + }); + + it("handles shader with K&R-style brace placement", () => { + const source = `#version 300 es +precision highp float; + +in vec3 Position; +out vec4 vertexColor; + +void main() +{ + gl_Position = vec4(Position, 1.0); +} +`; + const patched = injectPickingPassThrough(source); + expect(patched).toContain("vertexPickColor = PickColor;"); + }); + + it("handles shader with multiple out varyings", () => { + const source = `#version 300 es +precision highp float; + +in vec3 Position; +out vec4 vertexColor; +out vec2 texCoord; +out float fogDist; + +void main() { + gl_Position = vec4(Position, 1.0); + vertexColor = vec4(1.0); + texCoord = vec2(0.0); + fogDist = 100.0; +} +`; + const patched = injectPickingPassThrough(source); + expect(patched).toContain("in vec4 PickColor;"); + expect(patched).toContain("out vec4 vertexPickColor;"); + expect(patched).toContain("vertexPickColor = PickColor;"); + expect(patched.indexOf("out vec4 vertexPickColor;")).toBeLessThan(patched.indexOf("out float fogDist;")); + }); + + it("handles shader with only comments as header", () => { + const source = `// Just a comment +/* Another comment */ +/* +Multi-line +*/ + +in vec3 Position; +out vec4 vertexColor; + +void main() { + gl_Position = vec4(Position, 1.0); +} +`; + const patched = injectPickingPassThrough(source); + expect(patched).toContain("in vec4 PickColor;"); + expect(patched).toContain("out vec4 vertexPickColor;"); + }); +});