-
-
Notifications
You must be signed in to change notification settings - Fork 3.5k
/
base_filter.class.ts
393 lines (361 loc) · 13.9 KB
/
base_filter.class.ts
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
//@ts-nocheck
import { TWebGLPrecision, webGLProbe } from './WebGLProbe';
(function (global) {
var fabric = global.fabric;
/**
* @namespace fabric.Image.filters
* @memberOf fabric.Image
* @tutorial {@link http://fabricjs.com/fabric-intro-part-2#image_filters}
* @see {@link http://fabricjs.com/image-filters|ImageFilters demo}
*/
fabric.Image.filters = fabric.Image.filters || {};
/**
* Root filter class from which all filter classes inherit from
* @class fabric.Image.filters.BaseFilter
* @memberOf fabric.Image.filters
*/
fabric.Image.filters.BaseFilter = fabric.util.createClass(
/** @lends fabric.Image.filters.BaseFilter.prototype */ {
/**
* Filter type
* @param {String} type
* @default
*/
type: 'BaseFilter',
/**
* Array of attributes to send with buffers. do not modify
* @private
*/
vertexSource:
'attribute vec2 aPosition;\n' +
'varying vec2 vTexCoord;\n' +
'void main() {\n' +
'vTexCoord = aPosition;\n' +
'gl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);\n' +
'}',
fragmentSource:
'precision highp float;\n' +
'varying vec2 vTexCoord;\n' +
'uniform sampler2D uTexture;\n' +
'void main() {\n' +
'gl_FragColor = texture2D(uTexture, vTexCoord);\n' +
'}',
/**
* Constructor
* @param {Object} [options] Options object
*/
initialize: function (options) {
if (options) {
this.setOptions(options);
}
},
/**
* Sets filter's properties from options
* @param {Object} [options] Options object
*/
setOptions: function (options) {
for (var prop in options) {
this[prop] = options[prop];
}
},
/**
* Compile this filter's shader program.
*
* @param {WebGLRenderingContext} gl The GL canvas context to use for shader compilation.
* @param {String} fragmentSource fragmentShader source for compilation
* @param {String} vertexSource vertexShader source for compilation
*/
createProgram: function (gl, fragmentSource, vertexSource) {
fragmentSource = fragmentSource || this.fragmentSource;
vertexSource = vertexSource || this.vertexSource;
if (webGLProbe.webGLPrecision !== TWebGLPrecision.high) {
fragmentSource = fragmentSource.replace(
new RegExp(`precision ${TWebGLPrecision.high} float`, 'g'),
`precision ${webGLProbe.webGLPrecision} float`
);
}
var vertexShader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vertexShader, vertexSource);
gl.compileShader(vertexShader);
if (!gl.getShaderParameter(vertexShader, gl.COMPILE_STATUS)) {
throw new Error(
// eslint-disable-next-line prefer-template
'Vertex shader compile error for ' +
this.type +
': ' +
gl.getShaderInfoLog(vertexShader)
);
}
var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fragmentShader, fragmentSource);
gl.compileShader(fragmentShader);
if (!gl.getShaderParameter(fragmentShader, gl.COMPILE_STATUS)) {
throw new Error(
// eslint-disable-next-line prefer-template
'Fragment shader compile error for ' +
this.type +
': ' +
gl.getShaderInfoLog(fragmentShader)
);
}
var program = gl.createProgram();
gl.attachShader(program, vertexShader);
gl.attachShader(program, fragmentShader);
gl.linkProgram(program);
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
throw new Error(
// eslint-disable-next-line prefer-template
'Shader link error for "${this.type}" ' +
gl.getProgramInfoLog(program)
);
}
var attributeLocations = this.getAttributeLocations(gl, program);
var uniformLocations = this.getUniformLocations(gl, program) || {};
uniformLocations.uStepW = gl.getUniformLocation(program, 'uStepW');
uniformLocations.uStepH = gl.getUniformLocation(program, 'uStepH');
return {
program: program,
attributeLocations: attributeLocations,
uniformLocations: uniformLocations,
};
},
/**
* Return a map of attribute names to WebGLAttributeLocation objects.
*
* @param {WebGLRenderingContext} gl The canvas context used to compile the shader program.
* @param {WebGLShaderProgram} program The shader program from which to take attribute locations.
* @returns {Object} A map of attribute names to attribute locations.
*/
getAttributeLocations: function (gl, program) {
return {
aPosition: gl.getAttribLocation(program, 'aPosition'),
};
},
/**
* Return a map of uniform names to WebGLUniformLocation objects.
*
* Intended to be overridden by subclasses.
*
* @param {WebGLRenderingContext} gl The canvas context used to compile the shader program.
* @param {WebGLShaderProgram} program The shader program from which to take uniform locations.
* @returns {Object} A map of uniform names to uniform locations.
*/
getUniformLocations: function (/* gl, program */) {
// in case i do not need any special uniform i need to return an empty object
return {};
},
/**
* Send attribute data from this filter to its shader program on the GPU.
*
* @param {WebGLRenderingContext} gl The canvas context used to compile the shader program.
* @param {Object} attributeLocations A map of shader attribute names to their locations.
*/
sendAttributeData: function (gl, attributeLocations, aPositionData) {
var attributeLocation = attributeLocations.aPosition;
var buffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
gl.enableVertexAttribArray(attributeLocation);
gl.vertexAttribPointer(attributeLocation, 2, gl.FLOAT, false, 0, 0);
gl.bufferData(gl.ARRAY_BUFFER, aPositionData, gl.STATIC_DRAW);
},
_setupFrameBuffer: function (options) {
var gl = options.context,
width,
height;
if (options.passes > 1) {
width = options.destinationWidth;
height = options.destinationHeight;
if (
options.sourceWidth !== width ||
options.sourceHeight !== height
) {
gl.deleteTexture(options.targetTexture);
options.targetTexture = options.filterBackend.createTexture(
gl,
width,
height
);
}
gl.framebufferTexture2D(
gl.FRAMEBUFFER,
gl.COLOR_ATTACHMENT0,
gl.TEXTURE_2D,
options.targetTexture,
0
);
} else {
// draw last filter on canvas and not to framebuffer.
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
gl.finish();
}
},
_swapTextures: function (options) {
options.passes--;
options.pass++;
var temp = options.targetTexture;
options.targetTexture = options.sourceTexture;
options.sourceTexture = temp;
},
/**
* Generic isNeutral implementation for one parameter based filters.
* Used only in image applyFilters to discard filters that will not have an effect
* on the image
* Other filters may need their own version ( ColorMatrix, HueRotation, gamma, ComposedFilter )
* @param {Object} options
**/
isNeutralState: function (/* options */) {
var main = this.mainParameter,
_class = fabric.Image.filters[this.type].prototype;
if (main) {
if (Array.isArray(_class[main])) {
for (var i = _class[main].length; i--; ) {
if (this[main][i] !== _class[main][i]) {
return false;
}
}
return true;
} else {
return _class[main] === this[main];
}
} else {
return false;
}
},
/**
* Apply this filter to the input image data provided.
*
* Determines whether to use WebGL or Canvas2D based on the options.webgl flag.
*
* @param {Object} options
* @param {Number} options.passes The number of filters remaining to be executed
* @param {Boolean} options.webgl Whether to use webgl to render the filter.
* @param {WebGLTexture} options.sourceTexture The texture setup as the source to be filtered.
* @param {WebGLTexture} options.targetTexture The texture where filtered output should be drawn.
* @param {WebGLRenderingContext} options.context The GL context used for rendering.
* @param {Object} options.programCache A map of compiled shader programs, keyed by filter type.
*/
applyTo: function (options) {
if (options.webgl) {
this._setupFrameBuffer(options);
this.applyToWebGL(options);
this._swapTextures(options);
} else {
this.applyTo2d(options);
}
},
/**
* Retrieves the cached shader.
* @param {Object} options
* @param {WebGLRenderingContext} options.context The GL context used for rendering.
* @param {Object} options.programCache A map of compiled shader programs, keyed by filter type.
*/
retrieveShader: function (options) {
if (!options.programCache.hasOwnProperty(this.type)) {
options.programCache[this.type] = this.createProgram(options.context);
}
return options.programCache[this.type];
},
/**
* Apply this filter using webgl.
*
* @param {Object} options
* @param {Number} options.passes The number of filters remaining to be executed
* @param {Boolean} options.webgl Whether to use webgl to render the filter.
* @param {WebGLTexture} options.originalTexture The texture of the original input image.
* @param {WebGLTexture} options.sourceTexture The texture setup as the source to be filtered.
* @param {WebGLTexture} options.targetTexture The texture where filtered output should be drawn.
* @param {WebGLRenderingContext} options.context The GL context used for rendering.
* @param {Object} options.programCache A map of compiled shader programs, keyed by filter type.
*/
applyToWebGL: function (options) {
var gl = options.context;
var shader = this.retrieveShader(options);
if (options.pass === 0 && options.originalTexture) {
gl.bindTexture(gl.TEXTURE_2D, options.originalTexture);
} else {
gl.bindTexture(gl.TEXTURE_2D, options.sourceTexture);
}
gl.useProgram(shader.program);
this.sendAttributeData(
gl,
shader.attributeLocations,
options.aPosition
);
gl.uniform1f(shader.uniformLocations.uStepW, 1 / options.sourceWidth);
gl.uniform1f(shader.uniformLocations.uStepH, 1 / options.sourceHeight);
this.sendUniformData(gl, shader.uniformLocations);
gl.viewport(0, 0, options.destinationWidth, options.destinationHeight);
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
},
bindAdditionalTexture: function (gl, texture, textureUnit) {
gl.activeTexture(textureUnit);
gl.bindTexture(gl.TEXTURE_2D, texture);
// reset active texture to 0 as usual
gl.activeTexture(gl.TEXTURE0);
},
unbindAdditionalTexture: function (gl, textureUnit) {
gl.activeTexture(textureUnit);
gl.bindTexture(gl.TEXTURE_2D, null);
gl.activeTexture(gl.TEXTURE0);
},
getMainParameter: function () {
return this[this.mainParameter];
},
setMainParameter: function (value) {
this[this.mainParameter] = value;
},
/**
* Send uniform data from this filter to its shader program on the GPU.
*
* Intended to be overridden by subclasses.
*
* @param {WebGLRenderingContext} gl The canvas context used to compile the shader program.
* @param {Object} uniformLocations A map of shader uniform names to their locations.
*/
sendUniformData: function (/* gl, uniformLocations */) {
// Intentionally left blank. Override me in subclasses.
},
/**
* If needed by a 2d filter, this functions can create an helper canvas to be used
* remember that options.targetCanvas is available for use till end of chain.
*/
createHelpLayer: function (options) {
if (!options.helpLayer) {
var helpLayer = document.createElement('canvas');
helpLayer.width = options.sourceWidth;
helpLayer.height = options.sourceHeight;
options.helpLayer = helpLayer;
}
},
/**
* Returns object representation of an instance
* @return {Object} Object representation of an instance
*/
toObject: function () {
var object = { type: this.type },
mainP = this.mainParameter;
if (mainP) {
object[mainP] = this[mainP];
}
return object;
},
/**
* Returns a JSON representation of an instance
* @return {Object} JSON
*/
toJSON: function () {
// delegate, not alias
return this.toObject();
},
}
);
/**
* Create filter instance from an object representation
* @static
* @param {Object} object Object to create an instance from
* @returns {Promise<fabric.Image.filters.BaseFilter>}
*/
fabric.Image.filters.BaseFilter.fromObject = function (object) {
return Promise.resolve(new fabric.Image.filters[object.type](object));
};
})(typeof exports !== 'undefined' ? exports : window);