* Creates a new FilterRenderer2D instance. * @param {p5} parentRenderer - The p5.js instance.
(parentRenderer)
| 27 | * @param {p5} parentRenderer - The p5.js instance. |
| 28 | */ |
| 29 | constructor(parentRenderer) { |
| 30 | this.parentRenderer = parentRenderer; |
| 31 | // Create a canvas for applying WebGL-based filters |
| 32 | this.canvas = document.createElement('canvas'); |
| 33 | this.canvas.width = parentRenderer.width; |
| 34 | this.canvas.height = parentRenderer.height; |
| 35 | |
| 36 | // Initialize the WebGL context |
| 37 | let webglVersion = constants.WEBGL2; |
| 38 | this.gl = this.canvas.getContext('webgl2'); |
| 39 | if (!this.gl) { |
| 40 | webglVersion = constants.WEBGL; |
| 41 | this.gl = this.canvas.getContext('webgl'); |
| 42 | } |
| 43 | if (!this.gl) { |
| 44 | console.error('WebGL not supported, cannot apply filter.'); |
| 45 | return; |
| 46 | } |
| 47 | this.gl.pixelStorei(this.gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true); |
| 48 | |
| 49 | this.textures = new Map(); |
| 50 | |
| 51 | // Minimal renderer object required by p5.Shader and p5.Texture |
| 52 | this._renderer = { |
| 53 | GL: this.gl, |
| 54 | registerEnabled: new Set(), |
| 55 | _curShader: null, |
| 56 | _emptyTexture: null, |
| 57 | webglVersion, |
| 58 | states: { |
| 59 | textureWrapX: constants.CLAMP, |
| 60 | textureWrapY: constants.CLAMP, |
| 61 | }, |
| 62 | _arraysEqual: (a, b) => JSON.stringify(a) === JSON.stringify(b), |
| 63 | _getEmptyTexture: () => { |
| 64 | if (!this._emptyTexture) { |
| 65 | const im = new Image(1, 1); |
| 66 | im.set(0, 0, 255); |
| 67 | this._emptyTexture = new Texture(this._renderer, im); |
| 68 | } |
| 69 | return this._emptyTexture; |
| 70 | }, |
| 71 | _initShader: (shader) => { |
| 72 | const gl = this.gl; |
| 73 | |
| 74 | const vertShader = gl.createShader(gl.VERTEX_SHADER); |
| 75 | gl.shaderSource(vertShader, shader.vertSrc()); |
| 76 | gl.compileShader(vertShader); |
| 77 | if (!gl.getShaderParameter(vertShader, gl.COMPILE_STATUS)) { |
| 78 | throw new Error(`Yikes! An error occurred compiling the vertex shader: ${ |
| 79 | gl.getShaderInfoLog(vertShader) |
| 80 | }`); |
| 81 | } |
| 82 | |
| 83 | const fragShader = gl.createShader(gl.FRAGMENT_SHADER); |
| 84 | gl.shaderSource(fragShader, shader.fragSrc()); |
| 85 | gl.compileShader(fragShader); |
| 86 | if (!gl.getShaderParameter(fragShader, gl.COMPILE_STATUS)) { |
nothing calls this directly
no test coverage detected