UNPKG

1.52 kBPlain TextView Raw
1import fs from 'fs';
2import glob from 'glob';
3
4console.log('Generating shaders');
5
6/**
7 * This script is intended to copy the glsl file to the compilation output folder,
8 * change their extension to .js and export the shaders as strings in javascript.
9 * It will also minify them a bit if needed and change the extension to .js
10 * After that it will create a combined typescript definition file and manipulate it a bit
11 * It will also create a simple package.json file to allow importing this package in webpack
12 */
13
14glob('./src/shaders/*.glsl', null, (_err, files) => {
15 for (const file of files) {
16 const code = fs.readFileSync(file, 'utf8');
17 const content = glslToTs(code);
18 const fileName = `./src/shaders/${file.split('/').splice(-1)}.g.ts`;
19 fs.writeFileSync(fileName, content);
20 }
21 console.log(`Finished converting ${files.length} glsl files`);
22});
23
24function glslToTs(code: string): string {
25 code = code
26 .trim() // strip whitespace at the start/end
27 .replace(/\s*\/\/[^\n]*\n/g, '\n') // strip double-slash comments
28 .replace(/\n+/g, '\n') // collapse multi line breaks
29 .replace(/\n\s+/g, '\n') // strip identation
30 .replace(/\s?([+-\/*=,])\s?/g, '$1') // strip whitespace around operators
31 .replace(/([;\(\),\{\}])\n(?=[^#])/g, '$1'); // strip more line breaks
32
33 return `// This file is generated. Edit build/generate-shaders.ts, then run \`npm run codegen\`.
34export default ${JSON.stringify(code).replaceAll('"', '\'')};\n`;
35}