Skip to content

Instantly share code, notes, and snippets.

@ofZach
Last active June 6, 2023 12:23
Show Gist options
  • Save ofZach/7da40cbe446ef1c6d6009488aee76d53 to your computer and use it in GitHub Desktop.
Save ofZach/7da40cbe446ef1c6d6009488aee76d53 to your computer and use it in GitHub Desktop.
// this code takes a src string,
// tries to fine multiline strings that are
// of the form
// var fs = ` .... ` or let vs = `....`
// and tries to compress them via
// glslx
// I found renaming hard to manage so this is set to not rename. (my approach is to rename myself to something small)
function compressShaders(src) {
const regex = /(let|var)\s+(\w+)\s*=\s*(`|")([\s\S]*?)\3/gs;
let modifiedSrc = '';
let lastIndex = 0;
let match;
while ((match = regex.exec(src)) !== null) {
const variableDeclaration = match[1];
const variableName = match[2];
const openingDelimiter = match[3];
const content = match[4];
let modifiedContent = content;
// try to compress via glslx
let result = GLSLX.compile(content, {
disableRewriting: false,
format: "json",
keepSymbols: false,
prettyPrint: false,
renaming: "none",
});
if (result.output === null) {
} else {
var jsonData = JSON.parse(result.output);
modifiedContent = jsonData.shaders[0].contents;
}
modifiedSrc += src.slice(lastIndex, match.index); // Append the portion before the matched string
modifiedSrc += `${variableDeclaration} ${variableName} = ${openingDelimiter}${modifiedContent}${openingDelimiter}`; // Append the modified string
lastIndex = match.index + match[0].length;
}
modifiedSrc += src.slice(lastIndex); // Append the remaining portion of the source string
return modifiedSrc;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment