forked from jaburns/js13k2020
-
Notifications
You must be signed in to change notification settings - Fork 0
/
build.js
274 lines (223 loc) · 7.89 KB
/
build.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
#!/usr/bin/env node
const sh = require('shelljs');
const fs = require('fs');
const path = require('path');
const _ = require('lodash');
const ShapeShifter = require('regpack/shapeShifter');
const advzipPath = require('advzip-bin');
const definitionsJson = require('./src/definitions.json');
const DEBUG = process.argv.indexOf('--debug') >= 0;
const MONO_RUN = process.platform === 'win32' ? '' : 'mono ';
const g_shaderExternalNameMap = {};
const run = cmd =>
{
const code = sh.exec( cmd ).code;
if( code !== 0 )
process.exit( code );
};
const replaceSimple = (x, y, z) =>
{
const idx = x.indexOf( y );
if( idx < 0 ) return x;
return x.substr( 0, idx ) + z + x.substr( idx + y.length );
};
const applyStateMap = code =>
{
for( let k in definitionsJson.constants )
code = code.replace( new RegExp( k, 'g' ), definitionsJson.constants[k] );
for( let i in definitionsJson.stateFields )
code = code.replace( new RegExp( definitionsJson.stateFields[i], 'g' ), i );
return code;
};
const hashWebglIdentifiers = ( js, and2dContext ) =>
{
let result = new ShapeShifter().preprocess(js, {
hashWebGLContext: true,
contextVariableName: 'g',
contextType: 1,
reassignVars: true,
varsNotReassigned: ['A','b','g','c'],
useES6: true,
})[2].contents;
result = result.replace('for(', 'for(let ');
if( and2dContext )
{
result = new ShapeShifter().preprocess(result, {
hash2DContext: true,
contextVariableName: 'c',
contextType: 0,
reassignVars: true,
varsNotReassigned: ['A','b','g','c'],
useES6: true,
})[2].contents;
result = result.replace('for(', 'for(let ');
}
return result;
};
const buildShaderExternalNameMap = shaderCode =>
{
let i = 0;
_.uniq( shaderCode.match(/[vau]_[a-zA-Z0-9]+/g) )
.forEach( x => g_shaderExternalNameMap[x] = `x${i++}` );
};
const minifyShaderExternalNames = code =>
{
for( let k in g_shaderExternalNameMap )
code = code.replace( new RegExp( k, 'g' ), g_shaderExternalNameMap[k] );
return code;
};
const convertStateAccessNotation = shaderCode =>
{
// i.e. ST.wheelPos[2] -> g_state[s_wheelPos2];
// ST.wheelLastPos[i] -> g_state[s_wheelLastPos0 + i * s_wheelStructSize ];
let match;
while( match = shaderCode.match( /ST\.[a-zA-Z0-9\[\]]+/ ))
{
const str = match[0];
let newStr = str;
if( str.endsWith(']'))
{
const idx = str.match(/\[(.+)\]/)[1];
const propName = str.replace('ST.', '').replace(/\[.*/, '');
const structName = propName.match(/^[a-z]+/)[0];
if( isNaN( parseInt( idx )))
newStr = `g_state[s_${propName}0 + ${idx} * s_${structName}StructSize]`;
else
newStr = `g_state[s_${propName}${idx}]`;
}
else
{
const propName = str.replace('ST.', '');
newStr = `g_state[s_${propName}]`;
}
shaderCode = shaderCode.substr( 0, match.index ) + newStr + shaderCode.substr( match.index + str.length );
}
return shaderCode;
};
const convertHLSLtoGLSL = hlsl =>
{
const glslOverride = '//GLSL//';
let lines = hlsl
.replace(/float3x3/g, 'mat3')
.replace(/float2x2/g, 'mat2')
.replace(/float2/g, 'vec2')
.replace(/float3/g, 'vec3')
.replace(/float4/g, 'vec4')
.replace(/lerp/g, 'mix')
.replace(/frac/g, 'fract')
.replace(/atan2/g, 'atan')
.replace(/transpose_hlsl_only/g, '')
.replace(/static /g, '')
.split('\n');
lines = lines.map( x =>
{
const idx = x.indexOf(glslOverride);
return idx >= 0
? x.substr( idx + glslOverride.length )
: x;
});
return lines.join('\n');
}
const insertWorldSDFCode = shaderCode =>
{
const sdfDefs = convertHLSLtoGLSL( fs.readFileSync( 'src/sdfDefs.hlsl', 'utf8' ));
const tracks = sh.ls( 'tracks' )
.map( x => '#ifdef T' + x.replace(/[^0-9]/g, '') + '\n' + fs.readFileSync( 'tracks/' + x, 'utf8' ) + '\n' + '#endif' )
.join('\n')
.split('\n')
.map( x => x.trim().startsWith('const') ? '' : x )
.join('\n');
return shaderCode.replace( '#pragma INCLUDE_WORLD_SDF', sdfDefs + '\n' + tracks + '\n' );
};
const preprocessShader = shaderCode =>
applyStateMap( convertStateAccessNotation( insertWorldSDFCode( shaderCode )));
const reinsertTrackConstants = shaderGenTS =>
{
const lines = shaderGenTS.split('\n');
sh.ls( 'tracks' ).forEach( x =>
{
const trackId = x.replace(/[^0-9]/g, '');
const consts = fs.readFileSync( 'tracks/' + x, 'utf8' )
.split('\n')
.filter( x => x.trim().startsWith('const') )
.map( x => '"' + x + '" +' )
.join('\n');
for( let i = 0; i < lines.length; ++i )
{
if( lines[i].indexOf('T'+trackId) >= 0 )
{
lines.splice( i+1, 0, consts );
break;
}
}
});
return lines.join('\n');
}
const generateShaderFile = () =>
{
sh.mkdir( '-p', 'shadersTmp' );
sh.ls( 'src' ).forEach( x =>
{
if( x.endsWith('.frag') || x.endsWith('.vert'))
{
const code = fs.readFileSync( path.resolve( 'src', x ), 'utf8' );
fs.writeFileSync( path.resolve( 'shadersTmp', x ), preprocessShader( code ));
}
});
let noRenames = ['main','Xm','Xt'];
// noRenames = noRenames.concat([0,1,2,3].flatMap(x => (['Xc'+x, 'Xf'+x])));
// noRenames = noRenames.concat([0].map(x => (['Xp'+x])));
run( MONO_RUN + 'tools/shader_minifier.exe --no-renaming-list '+noRenames.join(',')+' --format js -o build/shaders.js --preserve-externals '+(DEBUG ? '--preserve-all-globals' : '')+' shadersTmp/*' );
let shaderCode = fs.readFileSync('build/shaders.js', 'utf8');
buildShaderExternalNameMap( shaderCode );
shaderCode = minifyShaderExternalNames( shaderCode );
shaderCode = shaderCode
.split('\n')
.map( x => x.replace(/^var/, 'export let'))
.join('\n');
shaderCode = reinsertTrackConstants( shaderCode );
if( DEBUG )
shaderCode = shaderCode.replace(/" \+/g, '\\n" +');
fs.writeFileSync( 'src/shaders.gen.ts', shaderCode );
sh.rm( '-rf', 'shadersTmp' );
};
const wrapWithHTML = js =>
{
let htmlTemplate = fs.readFileSync( DEBUG ? 'src/index.debug.html' : 'src/index.release.html', 'utf8' );
if( !DEBUG ) htmlTemplate = htmlTemplate
.split('\n')
.map( line => line.trim() )
.join('')
.trim();
return replaceSimple(htmlTemplate, '__CODE__', js.trim());
};
const main = () =>
{
definitionsJson.constants.s_totalStateSize = definitionsJson.stateFields.length;
definitionsJson.constants.s_totalStateSizeX4 = 4 * definitionsJson.stateFields.length;
sh.cd( __dirname );
sh.mkdir( '-p', 'build' );
fs.writeFileSync( 'src/debug.gen.ts', `export const DEBUG = ${DEBUG ? 'true' : 'false'};\n` );
console.log('Minifying shaders...');
generateShaderFile();
console.log('Compiling typescript...');
run( 'tsc --outDir build' );
console.log('Rolling up bundle...');
run( 'rollup -c' + ( DEBUG ? ' --config-debug' : '' ));
let x = fs.readFileSync('build/bundle.js', 'utf8');
x = minifyShaderExternalNames( x );
if( !DEBUG ) x = hashWebglIdentifiers( x, true );
x = wrapWithHTML( x );
x = applyStateMap( x );
fs.writeFileSync( 'build/index.html', x );
if( !DEBUG )
{
run( advzipPath + ' --shrink-insane -i 10 -a out.zip build/index.html' );
const zipStat = fs.statSync('out.zip');
const percent = Math.floor((zipStat.size / 13312) * 100);
console.log('');
console.log(` Final bundle size: ${zipStat.size} / 13312 bytes (${percent} %)`);
console.log('');
}
};
main();