-
Notifications
You must be signed in to change notification settings - Fork 10
/
rasterize_shader.js
421 lines (397 loc) · 15.1 KB
/
rasterize_shader.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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
/*
* Copyright Olli Etuaho 2013.
*/
'use strict';
/**
* A shader program generator. Inherited objects must generate 1 shader program
* and implement uniforms(width, height), vertexSource(), and fragmentSource().
* uniforms() must return an array of uniforms with name, type, shortType
* (postfix to gl.uniform*), inVertex (whether it's used in vertex shader),
* inFragment (whether it's used in fragment shader), defaultValue, arraySize
* (how many items in the uniform array). fragmentSource() and vertexSource()
* must return complete shader source strings.
*/
var ShaderGenerator = function() {
};
/**
* Initialize the shader generator.
*/
ShaderGenerator.prototype.initShaderGenerator = function() {
this.cachedGl = null;
this.cachedProgram = null;
};
/**
* Computes the types of uniforms used in the shader program.
* @return {Object.<string, string>} Map from uniform name to uniform short type
* to be used as postfix to gl.uniform* function call.
*/
ShaderGenerator.prototype.uniformTypes = function() {
var us = this.uniforms();
var result = {};
for (var i = 0; i < us.length; ++i) {
result[us[i].name] = us[i].shortType;
}
return result;
};
/**
* @param {WebGLRenderingContext} gl The context to place the shader program in.
* Note that this function only acts as an efficient cache for one gl context at
* a time.
* @return {ShaderProgram} Shader program for rasterizing circles.
*/
ShaderGenerator.prototype.programInstance = function(gl) {
// TODO: Limitation: can only work with one context at a time
if (this.cachedGl !== gl) {
this.cachedProgram =
new ShaderProgram(gl, this.fragmentSource(),
this.vertexSource(), this.uniformTypes());
this.cachedGl = gl;
}
return this.cachedProgram;
};
/**
* @param {number} width Width of the canvas in pixels. Used to determine the
* initial values of uniforms.
* @param {number} height Height of the canvas in pixels. Used to determine the
* initial values of uniforms.
* @return {Object.<string, *>} Map from uniform names to uniform values that
* should be filled in and passed to the shader program to draw.
*/
ShaderGenerator.prototype.uniformParameters = function(width, height) {
var us = this.uniforms(width, height);
var parameters = {};
for (var i = 0; i < us.length; ++i) {
var u = us[i];
if (u.shortType === '2fv' || u.shortType === '3fv' ||
u.shortType === '4fv') {
parameters[u.name] = new Float32Array(u.defaultValue);
} else {
parameters[u.name] = u.defaultValue;
}
}
return parameters;
};
/**
* Computes the uniform definition code for the fragment shader.
* @return {Array<string>} Shader source code lines.
*/
ShaderGenerator.prototype.fragmentUniformSource = function() {
var us = this.uniforms();
var src = [];
for (var i = 0; i < us.length; ++i) {
if (us[i].inFragment) {
var line = 'uniform ' + us[i].type + ' ' + us[i].name;
if (us[i].arraySize !== undefined) {
line += '[' + us[i].arraySize + ']';
}
line += ';';
if (us[i].comment !== undefined) {
line += ' // ' + us[i].comment;
}
src.push(line);
}
}
return src;
};
/**
* Computes the uniform definition code for the vertex shader.
* @return {Array<string>} Shader source code lines.
*/
ShaderGenerator.prototype.vertexUniformSource = function() {
var us = this.uniforms();
var src = [];
for (var i = 0; i < us.length; ++i) {
if (us[i].inVertex) {
var line = 'uniform ' + us[i].type + ' ' + us[i].name;
if (us[i].arraySize !== undefined) {
line += '[' + us[i].arraySize + ']';
}
line += ';';
if (us[i].comment !== undefined) {
line += ' // ' + us[i].comment;
}
src.push(line);
}
}
return src;
};
ShaderGenerator.commonGLSLHelpers = `
// Packs a normalized float in the 0.0 to 1.0 range to the red and green channels.
vec4 packNormFloatToRG(float value) {
int bytes = int(value * 255.0 * 256.0);
int highByte = bytes / 256;
int lowByte = bytes - highByte * 256;
return vec4(float(highByte) / 255.0, float(lowByte) / 255.0, 0.0, 1.0);
}`;
/**
* A shader program for blending together a bunch of monochrome circles.
* @constructor
* @param {GLRasterizerFormat} format Format of the rasterizer's backing.
* Affects whether to blend with a UINT8 source texture or a floating point
* framebuffer.
* @param {boolean} soft Use soft brush.
* @param {boolean} texturized True if circles are texturized. Overrides the soft parameter.
* @param {number} circles Amount of circles to draw in a single pass.
* @param {boolean} dynamicCircles The amount of circles drawn in a single pass
* can be set at run-time using an uniform.
* @param {boolean=} unroll Unroll the loop. True by default.
*/
var RasterizeShader = function(format, soft, texturized, circles, dynamicCircles,
unroll) {
if (unroll === undefined) {
unroll = true;
}
if (circles + 4 > glUtils.maxUniformVectors) {
console.log('Invalid RasterizeShader requested! Too many circles.');
return;
}
this.doubleBuffered = (format === GLRasterizerFormat.redGreen);
this.soft = soft;
this.circles = circles;
this.dynamicCircles = dynamicCircles;
this.texturized = texturized;
this.unroll = unroll;
this.initShaderGenerator();
};
RasterizeShader.prototype = new ShaderGenerator();
/**
* Computes the uniforms used in the shader program.
* @param {number=} width Width of the canvas in pixels. Defaults to 1.
* @param {number=} height Height of the canvas in pixels. Defaults to 1.
* @return {Array.<Object>} An array of uniforms with name, type, shortType
* (postfix to gl.uniform*), inVertex (whether it's used in vertex shader),
* inFragment (whether it's used in fragment shader), defaultValue, arraySize
* (how many items in the uniform array).
*/
RasterizeShader.prototype.uniforms = function(width, height) {
var i;
if (width === undefined || height === undefined) {
width = 1.0;
height = 1.0;
}
var us = [];
if (this.doubleBuffered) {
us.push({name: 'uSrcTex', type: 'sampler2D', shortType: 'tex2d',
inFragment: true, inVertex: false, defaultValue: null});
}
if (this.dynamicCircles) {
us.push({name: 'uCircleCount', type: 'int', shortType: '1i',
inFragment: true, inVertex: true, defaultValue: 1});
}
if (this.unroll) {
for (i = 0; i < this.circles; ++i) {
us.push({name: 'uCircle' + i, type: 'vec4', shortType: '4fv',
inFragment: true, inVertex: false,
defaultValue: [0.0, 0.0, 1.0, 1.0],
comment: 'x, y coords in pixel space, radius in pixels, flowAlpha from 0 to 1'});
if (this.texturized) {
us.push({name: 'uCircleB' + i, type: 'vec4', shortType: '4fv',
inFragment: true, inVertex: false,
defaultValue: [0.0, 0.0, 0.0, 0.0],
comment: 'rotation in radians'});
}
}
} else {
var def = [];
for (i = 0; i < this.circles; ++i) {
def.push(0.0, 0.0, 1.0, 1.0);
}
us.push({name: 'uCircle', type: 'vec4', arraySize: this.circles,
shortType: '4fv', inFragment: true, inVertex: false,
defaultValue: def,
comment: 'x, y coords in pixel space, radius in pixels, flowAlpha from 0 to 1'});
if (this.texturized) {
us.push({name: 'uCircleB', type: 'vec4', arraySize: this.circles,
shortType: '4fv', inFragment: true, inVertex: false,
defaultValue: def,
comment: 'rotation in radians'});
}
}
us.push({name: 'uPixelPitch', type: 'vec2', shortType: '2fv',
inFragment: false, inVertex: true,
defaultValue: [2.0 / width, 2.0 / height],
comment: 'in gl viewport space'});
if (this.texturized) {
us.push({name: 'uBrushTex', type: 'sampler2D', shortType: 'tex2d',
inFragment: true, inVertex: false, defaultValue: null});
}
return us;
};
/**
* Computes the varying definition code for both vertex and fragment shader.
* @return {Array<string>} Shader source code lines.
*/
RasterizeShader.prototype.varyingSource = function() {
var src = 'varying vec2 vPixelCoords; // in pixels\n';
if (this.doubleBuffered) {
src += 'varying vec2 vSrcTexCoord;\n';
}
return src;
};
/**
* Computes the minimum circle radius for rasterization purposes.
* @return {number} Minimum circle radius.
*/
RasterizeShader.prototype.minRadius = function() {
return (!this.texturized && this.soft) ? 1.0 : 0.5;
};
/**
* Generates fragment shader source that calculates alpha for a single circle.
* @param {string} assignTo The variable name where the result is assigned.
* @param {string} indent Prefix for each line, intended for indentation.
* @return {Array<string>} Shader source code lines.
*/
RasterizeShader.prototype.fragmentAlphaSource = function(assignTo, indent) {
// Generated shader assumes that:
// 1. circleRadius contains the intended perceived radius of the circle.
// 1. circleFlowAlpha contains the intended perceived alpha of the circle.
// 2. centerDist contains the fragment's distance from the circle center.
var src = `
float radius = max(circleRadius, ${ this.minRadius().toFixed(1) });
float flowAlpha = (circleRadius < ${ this.minRadius().toFixed(1) }) ?
circleFlowAlpha * circleRadius * circleRadius * ${ Math.pow(1.0 / this.minRadius(), 2).toFixed(1) } :
circleFlowAlpha;
float antialiasMult = clamp((radius + 1.0 - centerDist) * 0.5, 0.0, 1.0);`;
if (this.texturized) {
src += `
mat2 texRotation = mat2(cos(circleRotation), -sin(circleRotation),
sin(circleRotation), cos(circleRotation));
vec2 texCoords = texRotation * centerDiff / radius * 0.5 + 0.5;
// Note: remember to keep the texture2D call outside non-uniform flow control.
// TODO: We could also use explicit texture LOD in here in case it is supported.
float texValue = texture2D(uBrushTex, texCoords).r;
// Usage of antialiasMult even when we have a texturized brush increases accuracy at small brush sizes and ensures
// that the brush stays inside the bounding box even when rotated.
${ assignTo } = flowAlpha * antialiasMult * texValue;`;
} else {
if (this.soft) {
src += `
${ assignTo } = max((1.0 - centerDist / radius) * flowAlpha * antialiasMult, 0.0);`;
} else {
src += `
${ assignTo } = flowAlpha * antialiasMult;`;
}
}
// TODO: Restore indentation
return src;
};
/**
* Generates source for the inner loop of the fragment shader that blends a
* circle with the "destAlpha" value from previous rounds.
* @param {number} index Index of the circle.
* @param {string=} arrayIndex Postfix for uCircle, so that it can be either an
* array or just a bunch of separate uniforms to work around bugs. Defaults to
* array. Does not matter if circle parameters are taken from a texture.
* @return {Array<string>} Shader source code lines.
*/
RasterizeShader.prototype.fragmentInnerLoopSource = function(index,
arrayIndex) {
if (arrayIndex === undefined) {
arrayIndex = `[${ index }]`;
}
var texturizedCircleParams = '';
if (this.texturized) {
texturizedCircleParams = `
float circleRotation = uCircleB${ arrayIndex }.x;
vec2 centerDiff = vPixelCoords - center;`;
}
// The conditional controlling blending the circle is non-uniform flow control.
// See GLSL ES 1.0.17 spec Appendix A.6.
// For the texturized brush, the if must be deferred since the texture is mipmapped.
var evaluateCircleInsideIf = !this.texturized;
var ifCircleActive = this.dynamicCircles ? `if (${ index } < uCircleCount)` : '';
return `
${ evaluateCircleInsideIf ? ifCircleActive : '' } {
vec2 center = uCircle${ arrayIndex }.xy;
float circleRadius = uCircle${ arrayIndex }.z;
float circleFlowAlpha = uCircle${ arrayIndex }.w;
float centerDist = length(vPixelCoords - center);
${ texturizedCircleParams }
${ this.fragmentAlphaSource('float circleAlpha', ' ') }
${ !evaluateCircleInsideIf ? ifCircleActive : '' } {
destAlpha = clamp(circleAlpha + (1.0 - circleAlpha) * destAlpha, 0.0, 1.0);
}
}`;
};
/**
* @return {string} Fragment shader source.
*/
RasterizeShader.prototype.fragmentSource = function() {
var initSrcAlphaIfAny = '';
if (this.doubleBuffered) {
initSrcAlphaIfAny = `
vec4 src = texture2D(uSrcTex, vSrcTexCoord);
float srcAlpha = src.x + src.y / 256.0;`;
}
var fragmentInnerLoop = '';
if (this.unroll) {
for (var i = 0; i < this.circles; ++i) {
fragmentInnerLoop += this.fragmentInnerLoopSource(i, i);
}
} else {
fragmentInnerLoop = `
for (int i = 0; i < ${ this.circles }; ++i) {
${ this.fragmentInnerLoopSource('i') }
}`;
}
var writeFragColor = 'gl_FragColor = vec4(0.0, 0.0, 0.0, destAlpha);';
if (this.doubleBuffered) {
writeFragColor = `
float alpha = destAlpha + (1.0 - destAlpha) * srcAlpha;
gl_FragColor = packNormFloatToRG(alpha);`;
}
return `
precision highp float;
precision highp sampler2D;
precision highp int;
${ ShaderGenerator.commonGLSLHelpers }
${ this.varyingSource() }
${ this.fragmentUniformSource().join('\n') }
void main(void) {
float destAlpha = 0.0;
${ initSrcAlphaIfAny }
${ fragmentInnerLoop }
${ writeFragColor }
}`;
};
/**
* @param {number} index Index of the circle.
* @param {string} arrayIndex Postfix for uCircle, so that it can be either an
* array or just a bunch of separate uniforms to work around bugs. Defaults to
* arrays. Does not matter if circle parameters are taken from a texture.
* @return {Array<string>} Vertex shader inner loop lines.
*/
RasterizeShader.prototype.vertexInnerLoopSource = function(index, arrayIndex) {
return '';
};
/**
* @return {string} Vertex shader source.
*/
RasterizeShader.prototype.vertexSource = function() {
var src = `precision highp float;
// expecting a vertex array with corners at -1 and 1 x and y coordinates
attribute vec2 aVertexPosition;
${ this.varyingSource() }
${ this.vertexUniformSource().join('\n') }
void main(void) {
vPixelCoords = vec2(aVertexPosition.x + 1.0, 1.0 - aVertexPosition.y) / uPixelPitch;
`;
if (this.doubleBuffered) {
src += ' vSrcTexCoord = (aVertexPosition + 1.0) * 0.5;\n';
}
if (this.vertexInnerLoopSource('').length > 0) {
if (this.unroll) {
for (var i = 0; i < this.circles; ++i) {
src += this.vertexInnerLoopSource(i, i);
}
} else {
src += `
for (int i = 0; i < ${ this.circles }; ++i) {
${ this.vertexInnerLoopSource('i') }
}`;
}
}
src += ` gl_Position = vec4(aVertexPosition, 0.0, 1.0);
}`;
return src;
};